SLOPSHOPPER

fabric-data-app

A Fabric data app pane that follows the rayfin CLI: browse every Fabric App under your working directory with its data sources and files, and see what Claude…

paneguardcommandtoastpromptprocess
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · fabric-data-app
│ ┃ Fabric apps: app ✕ › fix the failing auth test and add an audit log call │ ┃ ▣ client module ./rows.tsx │ ┃ ⏺ Read(src/auth.ts) │ ┃ Filter, or Enter to jump ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ no rayfin app here yet; rayfin init adds one ⎿ Added 2 lines, removed 1 line │ ┃ ▣ client module ./rows.tsx ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ │ ┃ › /fabric-app-pane │ ┃ ⎿ fabric-data-app: 0 Fabric apps under /work/app. │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ │ ┃ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Fabric apps: app
▣ client module ./rows.tsx Filter, or Enter to jump no rayfin app here yet; rayfin init adds one ▣ client module ./rows.tsx
README

<h1 align="center">Power BI Agentic Dev</h1>

A personalized fork of Kurt Buhler's Power BI &amp; Microsoft Fabric skills marketplace <br></br> <i>Teach AI agents like Claude Code, GitHub Copilot, or OpenAI Codex to work with Power BI and Microsoft Fabric</i>

<img src="https://img.shields.io/badge/version-26.25-blue" alt="Version"> <img src="https://img.shields.io/badge/Power_BI-F2C811?logo=powerbi&logoColor=000" alt="Power BI"> <img src="https://img.shields.io/badge/Microsoft_Fabric-008272" alt="Microsoft Fabric"> <img src="https://img.shields.io/badge/Tabular_Editor-2E7D32" alt="Tabular Editor"> <img src="https://img.shields.io/badge/license-GPL--3.0-green" alt="License">

[!NOTE] This is Tim's personalized fork of data-goblin/power-bi-agentic-development, renamed to power-bi-agentic-dev so it can coexist with the original. It carries the upstream plugins plus additional personal skills, and tracks Kurt's releases selectively rather than following his weekly cadence. Full credit for the original work goes to Kurt Buhler — see Attribution.


What is agentic development?

  • Agentic development is when you use AI agents to help build, manage, and optimize artifacts and software — semantic models, reports, and everything around them (workspaces, deployment pipelines, and processes).
  • A marketplace hosts plugins you can install. A plugin is a bundle of resources that help coding agents perform better: skills, subagents, hooks, and MCP servers focused on a topic or task.
  • This marketplace is focused on making your agent work well with Power BI and Fabric — Power BI skills, Fabric skills, subagents, and hooks for coding agents.

Installation

Add the marketplace in Claude Code — run this in the terminal:

claude plugin marketplace add InsightfulAnalytics/PBI_Agentic_Dev

This registers the marketplace under the name power-bi-agentic-dev (from the repo's .claude-plugin/marketplace.json). Note that the GitHub repo slug (PBI_Agentic_Dev) differs from the marketplace name (power-bi-agentic-dev) — the slug is used only in the marketplace add command above; the install commands below reference the marketplace name.

Claude Code

After adding the marketplace, install plugins interactively via /plugin → Marketplaces → select power-bi-agentic-dev → install the plugins you want. You can also enable auto-update per marketplace there.

Or install from the command line:

claude plugin install semantic-models@power-bi-agentic-dev
claude plugin install reports@power-bi-agentic-dev
claude plugin install pbip@power-bi-agentic-dev
claude plugin install custom-visuals@power-bi-agentic-dev
claude plugin install tabular-editor@power-bi-agentic-dev
claude plugin install pbi-desktop@power-bi-agentic-dev
claude plugin install fabric-cli@power-bi-agentic-dev
claude plugin install fabric-admin@power-bi-agentic-dev
claude plugin install paginated-reports@power-bi-agentic-dev
claude plugin install etl@power-bi-agentic-dev
claude plugin install fabric-data-app@power-bi-agentic-dev

Verify what's installed with claude plugin list, and inspect a plugin's contents and token cost with claude plugin details <plugin>.

Updates. Every release is listed in CHANGELOG.md and published as a GitHub Release, so to hear about new ones, choose Watch → Custom → Releases on this repository. To update, run claude plugin marketplace update power-bi-agentic-dev, then claude plugin update <plugin>@power-bi-agentic-dev for each plugin you use, or turn on auto-update for the marketplace in /plugin.

Copilot CLI

The standalone Copilot CLI supports plugin installation from GitHub repos. Copilot CLI reads the same .claude-plugin/marketplace.json manifest this repo uses, so the marketplace and child-plugin layout works without modification.

TMDL files can produce repository-relative paths over 260 characters. Windows' legacy MAX_PATH blocks git clone from writing them unless long path support is enabled at both the OS and git level. Without this, copilot plugin install aborts with Filename too long.

See useful-stuff/agent-scripts/enable-windows-longpaths.ps1 for an example script you can run from an elevated PowerShell session to enable long paths (a reboot is recommended after the registry change). This is a Windows OS limitation, documented at Maximum Path Length Limitation.

Also set the git-level flag:

git config --system core.longpaths true

This repository is an Anthropic-format plugin marketplace (a set of plugins), not a single distributable plugin, so the root .claude-plugin/ contains only marketplace.json. Two documented install paths work:

1. Register the marketplace once, then install named child plugins:

copilot plugin marketplace add InsightfulAnalytics/PBI_Agentic_Dev
copilot plugin install tabular-editor@power-bi-agentic-dev

2. Or install a single plugin directly from its subdirectory, no marketplace registration needed:

copilot plugin install InsightfulAnalytics/PBI_Agentic_Dev:plugins/pbip

Both forms are documented in the Copilot CLI plugin reference and the plugins how-to. Inside an interactive Copilot session, /plugin install PLUGIN-NAME@power-bi-agentic-dev is the equivalent of (1). The bare copilot plugin install InsightfulAnalytics/PBI_Agentic_Dev (no qualifier) will not install anything useful, because the root is a marketplace catalog, not a plugin.

Inside Copilot CLI:

/env                    # Loaded instructions, MCP servers, skills, agents, plugins, LSPs, extensions
/plugin list            # Installed plugins
/skills list            # Available skills
/skills info pbip       # Details for a specific skill
/agent                  # Browse installed agents
  • Skills load identically; Copilot CLI reads skills/<name>/SKILL.md.
  • Agents use the *.agent.md extension required by Copilot CLI's documented convention. Claude Code matches any *.md file in agents/, so the dual extension works in both tools.
  • MCP servers load from .mcp.json (plugin root) or .github/mcp.json. Two plugins ship MCP declarations: fabric-cli (microsoft-learn, HTTP) and custom-visuals (pbiviz, stdio via npx).
  • Hooks ship twice. Claude Code reads hooks/hooks.json (with per-hook if path filters). Copilot CLI reads .github/plugin/plugin.json, which points it at hooks/copilot-hooks.json: the same scripts, wired with explicit bash and powershell commands so a Windows host without Git Bash on PATH gets a clean no-op instead of a failed launch. Copilot has no if filter and denies a tool call on any non-zero PreToolUse exit, so every script also re-applies its own path and command filters and exits 0 on anything unrelated. Requires Copilot CLI >= 1.0.26 (2026-04-14) for CLAUDE_PLUGIN_ROOT (changelog); older builds skip the hooks rather than fail. Native Windows bash users may also hit a separate path-format bug tracked upstream at claude-code#11984.
  • Scope is always user-wide in Copilot CLI: plugins install to ~/.copilot/installed-plugins/ and their hooks run in every session on the machine. There is no per-project install, so the "prefer project scope" advice below applies to Claude Code only; in Copilot, install a plugin only while you need it.

/plugin rm or copilot plugin uninstall can fail with Access is denied. (os error 5). This is an open Copilot CLI bug, not a plugin problem: the installer swaps the plugin folder by renaming it, and Windows refuses the rename while another process holds a handle on it. VS Code's Copilot extension keeps directory watchers on every installed plugin's hooks/, agents/ and skills/ folders, and a second Copilot CLI session does the same. Tracked at github/copilot-cli#4095 and #4151.

  1. Close every VS Code window and every other Copilot CLI session, then retry the uninstall.
  2. If it still fails, delete the plugin by hand: remove its folder under %USERPROFILE%\.copilot\installed-plugins\ (or %COPILOT_HOME%\installed-plugins\) and restart Copilot CLI.
  3. To stop the hooks without uninstalling, delete the plugin's hooks folder from that same location.

GitHub Codespaces and other Linux hosts

Most of what these skills know is about TMDL, the PBIR JSON schemas, and the Fabric and Power BI REST APIs, none of which care about the operating system. A Codespace on this repository picks the skills up with no setup: .devcontainer/devcontainer.json installs Claude Code and runs the bootstrap.

For a Codespace on a Power BI project repository, which is the usual case, copy the devcontainer.json block from .devcontainer/README.md. To set an existing Linux or macOS machine up by hand:

git clone --depth 1 https://github.com/InsightfulAnalytics/PBI_Agentic_Dev.git ~/.pbi-agentic-dev
bash ~/.pbi-agentic-dev/scripts/bootstrap-agent-env.sh

The bootstrap registers the marketplace, installs the toolchain that exists on the platform, and prints a capability report naming what does not, so an agent learns the limits before its first turn rather than by failing:

LinuxWindows with Desktop
fab, te, az, the REST APIsyesyes
TMDL validation (bundled tmdl-validate binary)yesyes
Server-side report render (ExportTo to PDF, then pymupdf to PNG)yesyes
ADOMD or TOM over XMLA against a published modelyesyes
pbir CLIno, and there is no wheel or sdist to installyes
Power BI Desktop, local msmdsrv, DAX Studio, Tabular Editor 2 and 3noyes

On Linux, author PBIR by hand from the pbip:pbir-format examples, publish with fab import, and verify by rendering server-side. .devcontainer/README.md has the detail.

OpenAI Codex

Codex supports the same open Agent Skills standard these plugins use, so the skills work there too — installed with a small script instead of a plugin marketplace:

git clone https://github.com/InsightfulAnalytics/PBI_Agentic_Dev.git
cd PBI_Agentic_Dev
python codex/install.py --check    # dry run: preview what will be installed
python codex/install.py            # skills -> ~/.agents/skills, adapter -> ~/.codex/AGENTS.md
python codex/install.py --mcp      # optional: also add the MCP servers to ~/.codex/config.toml

Keep the clone — it's the runtime store for bundled scripts and validators that the copies in ~/.agents/skills reference. After a git pull, re-run the installer (idempotent) to refresh. The full guide — project-scoped installs, junction mode, uninstall, and troubleshooting — is in codex/README.md.

Inside a Codex session:

/skills                 # list available skills (the Power BI skills should appear)
$tmdl                   # invoke a skill explicitly by name
/mcp                    # MCP servers (if installed with --mcp)
/status                 # loaded AGENTS.md, model, config
  • Skills load identically — Codex reads ~/.agents/skills/<name>/SKILL.md and auto-activates from the description, or on $name.
  • Hooks don't fire on file edits in Codex, so the installer converts the TMDL/PBIR/RDL validation hooks into rules in ~/.codex/AGENTS.md for the agent to run after edits.
  • Subagents aren't spawned; the eight reviewer/validator agents become inline checklists the agent reads from plugins/*/agents/*.agent.md.
  • Slash commands are ported as skills ($audit-context, $suggest-rule, $migrating-fabric-trial-capacities) since Codex deprecated custom prompts.
  • MCP servers are added to ~/.codex/config.toml with --mcp (microsoft-learn over HTTP, pbiviz over stdio).
  • Skills kept outside this repo (e.g. personal skills Claude loads from ~/.claude/skills) are not touched by the installer — copy any you want Codex to have into ~/.agents/skills yourself.
  • The codex/ layer only reads from plugins/; Claude Code behavior is unchanged.

Overview

The repo contains skills, agents, and hooks.

  • Skills teach agents domain knowledge and workflows. They activate automatically based on task context, or can be invoked manually with /skill-name. In Claude Code, skills and commands have coalesced; commands are simply more prescriptive skill workflows.
  • Agents are autonomous subprocesses that handle complex, multi-step tasks independently; typically used for review and validation.
  • Hooks run automatically after tool use to validate files and catch errors early. They are deterministic — they fire when a specific pattern is matched, not by LLM judgment.

Hook checks can be individually toggled via config files. Set any check to false to disable it:

  • plugins/pbip/hooks/config.yaml — PBIR, TMDL, and report-binding validation
  • plugins/pbi-desktop/hooks/config.yaml — DAX references, measure metadata, referential integrity, metadata cache
  • plugins/paginated-reports/hooks/config.yaml — RDL validation

Available plugins

[!WARNING] Don't install every plugin. Each skill competes for the agent's attention and context window, so install a plugin only when you need it and remove it when you don't. Prefer installing plugins scoped to a project rather than to your user, so each project carries only the skills it actually uses.

TypeNameDescription
Skillsemantic-modelDesign, build, refresh, and review semantic models through a te-first tool cascade
Skilldate-tableDrop a ready-made 58-column DimDate (calendar, ISO week, fiscal, to-date flags) plus the Dates Selected title measure into any PBIP model
Skilldax-standardThe house style for authoring measures: table-first DAX, formatting via dynamic format strings, worked recipes
Skilldax-optimisationDebug and optimize DAX performance (server timings, anti-patterns, tuning)
Skillpower-queryWrite M expressions, debug query folding, execute M locally or via Fabric API
Skillorganize-semantic-modelOrganize a model end to end: names, folders, hierarchies, descriptions, formats, UDFs, perspectives, translations, roles
Skillrefresh-semantic-modelTrigger or troubleshoot refreshes
Skilllineage-analysisTrace downstream reports from a semantic model across workspaces
Agentsemantic-model-auditorAudit semantic models for quality, memory, DAX, and design issues
TypeNameDescription
Skillpbir-cliProgrammatic report manipulation via the pbir CLI, including live Power BI Desktop refresh and page screenshots
Skillcreate-pbi-reportEnd-to-end workflow for building a report from scratch with the pbir CLI
Skillpbi-verify-loopRefresh → settle → screenshot loop to visually verify report edits (optional mockup diff)
Skillpower-bi-themeBrowse a preset-theme gallery and apply a chosen theme to a report
Skillmodifying-theme-jsonEdit, enforce, audit, and re-theme report theme JSON
Skillworkout-wednesdayTurn a Workout Wednesday challenge link into a built, verified, published report — see Try it end-to-end
Skillpbi-report-design (WIP)Power BI report best practices, design, and style
Skillreview-report (WIP)Review Power BI reports for usage metrics and best practices
Agentdeneb-reviewerReview Deneb specs for Vega/Vega-Lite syntax and conventions
Agentsvg-reviewerReview SVG DAX measures for syntax and design quality
Agentr-reviewerReview R visual scripts (ggplot2) for Power BI conventions
Agentpython-reviewerReview Python visual scripts (matplotlib/seaborn) for Power BI conventions
TypeNameDescription
Skilldeneb-visualsAuthor Deneb visuals with Vega and Vega-Lite specs
Skilldeneb-pbirRound-trip tooling: extract/embed a Deneb spec in visual.json and offline-render it
Skillperformant-matrixDiagnose a slow financial matrix, then choose between a bridge model fix, a native restructure, or a Deneb grid
Skillpython-visualsCustom Python visuals (matplotlib/seaborn) in Power BI reports
Skillr-visualsCustom R visuals (ggplot2) in Power BI reports
Skillsvg-visualsSVG visuals via DAX measures in Power BI reports
Skillpowerbi-custom-visualsDevelop, build, and package .pbiviz custom visuals with the pbiviz toolchain
TypeNameDescription
SkillpbipPower BI Project (PBIP) format, structure, and file types
SkilltmdlAuthor and edit TMDL files directly
Skillpbir-formatAuthor and edit PBIR metadata files directly (visual.json, report.json, themes, filters, report extensions, visual calculations)
Agentpbip-validatorValidate PBIP project structure, TMDL syntax, and PBIR schemas
HookPBIR validationValidates PBIR structure, required fields, naming conventions, and schema URLs
HookReport binding validationValidates semantic model binding (byPath directory exists; byConnection model exists via fab exists)
HookTMDL validationValidates TMDL structural syntax
TypeNameDescription
Skillbpa-rulesCreate and improve Best Practice Analyzer rules for models
Skillc-sharp-scriptingC# scripting and macros for TE
Skillte-cliCross-platform Tabular Editor CLI (te, preview) for semantic models from the terminal
Skillte2-cliTabular Editor 2 CLI usage and automation (not TE3)
Skillte-docsTabular Editor documentation search, TE3 config files. Uses pbi-search CLI
Command/suggest-ruleGenerate BPA rules from descriptions
Agentbpa-expression-helperDebug and improve BPA rule expressions
TypeNameDescription
Skillconnect-pbidExplore, query, and modify a model in Power BI Desktop, and reload/screenshot the report canvas via the Desktop Bridge
Agentquery-listenerCapture DAX queries from Power BI Desktop visuals in real time
HookDAX reference validationValidates table, column, and measure references against the connected model; suggests corrections
HookMeasure metadata enforcementBlocks adding measures without DisplayFolder, Description, and FormatString
HookReferential integrity checkReports unmatched many-side keys after relationship or column changes
HookMetadata cache refreshAuto-snapshots model metadata on TOM connect or model modification
HookCompatibility level checkReports features available by upgrading; optional auto-upgrade
TypeNameDescription
Skillfabric-cliFabric CLI (fab) for any remote operation in Power BI or Fabric (works fully on Pro/PPU; Fabric not required)
Command/audit-contextReview project context files (CLAUDE.md, agents.md, memory files)

| Command | [/migrating-fabric-trial-capacities](plugins/fabric-cli/commands/migrating

Source 13 files
hooks/register.tsx 1691 lines
1import { type EngineInterface, type Register, type Timer, update } from 'claude-code'
2import { openCommand } from './open'
3
4import type { AppInfo, FileNode, FileTree, Source, Theme } from '../types'
5import { itemUrl, merge, parseSources } from './apps'
6import { CLIS } from './clis'
7import { glyphFor, KIND_LABEL, type Tier } from './glyphs'
8import type { RowSpec, RowsProps, Seg } from './rows'
9import { FABRIC_SVG } from './svg-data'
10import type { ZoneProps } from './zone'
11import { CHEVRON_CLOSED, CHEVRON_OPEN, fileIcon, GIT_COLOR, plainIcon, stronger } from './icons'
12import { type CliCall, cliCalls, deploys, mutates, tokenize } from './parse'
13import {
14  ancestorsOf,
15  type Change,
16  DEFAULT_THEME,
17  dirname,
18  emptyTree,
19  inside,
20  join,
21  mapLimit,
22  parseGit,
23  parseNumstat,
24  rollCounts,
25  rollUp,
26  parseTheme,
27  posix,
28  replaceChildren,
29  resolvePath,
30  stamp,
31  toNodes,
32  underAny,
33  useDrives,
34  visibleRows,
35} from './tree'
36
37const PANE = 'fabric-app-pane'
38const TREE = { plugin: 'fabric-data-app', key: 'tree' } as const
39const APPS = { plugin: 'fabric-data-app', key: 'apps' } as const
40const THEME = { plugin: 'fabric-data-app', key: 'theme' } as const
41const ADD_COLOR = '#98c379'
42const DEL_COLOR = '#e06c75'
43const TITLE = 'Fabric apps'
44const WORKING = 'Claude is working in Fabric...'
45const FONT_HINT = 'Tell user once: Fabric app pane icons need github.com/data-goblin/fabric-nf plus a Nerd Font. Plugin option fontHint=off disables this.'
46const BUSY_MAX_MS = 600_000
47const FLASH_MS = 2700
48const DOUBLE_MS = 450
49const FIND_LIMIT = 200
50const READ_LIMIT = 8
51const SOURCE_INPUTS = ['fabric.yaml', 'rayfin/rayfin.yml', 'rayfin/data/schema.ts']
52const APP_INPUTS = [...new Set([...SOURCE_INPUTS, ...CLIS.flatMap(c => [c.marker, ...c.inputs])])]
53const LIST_LIMIT = 16
54const TONES: Record<string, { bright: string[]; dim: string[] }> = {
55  orange: { bright: ['#f97316', '#fb923c', '#fdba74', '#ffedd5'], dim: ['#8a4316', '#a3562a', '#bd7444', '#d29267'] },
56  teal: { bright: ['#14b8a6', '#2dd4bf', '#5eead4', '#ccfbf1'], dim: ['#0f5e57', '#16786f', '#2a9488', '#4fb3a8'] },
57  purple: { bright: ['#a855f7', '#c084fc', '#d8b4fe', '#f3e8ff'], dim: ['#581c87', '#6b21a8', '#8b47c4', '#a874d6'] },
58}
59const MUTED = '#6e6e7a'
60const PROPS = 'props:toggle'
61const DETAIL_ROWS = 12
62const ROW_PX = 24
63const SVG_NS = 'http://www.w3.org/2000/svg'
64const GUID_RE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi
65const FAB_WRITES = /\bfab\s+(set|rm|del|import|create|mkdir|cp|mv|assign|unassign|start|stop|run|job)\b|\s-X\s*(post|put|patch|delete)\b/i
66const OWN_KINDS = ['SQLDatabase', 'SQLEndpoint', 'UserDataFunction'] as const
67const OWN_NAME: Record<string, [string, string]> = {
68  SQLDatabase: ['SQL database', 'deployed'],
69  SQLEndpoint: ['SQL endpoint', 'SQL analytics endpoint'],
70  UserDataFunction: ['User data functions', 'deployed'],
71}
72const THEME_FILE = '.local/state/omarchy/current/theme/colors.toml'
73const APP_COLOR = '#5a91e2'
74const FONT_SCRIPT =
75  'f=; command -v fc-list >/dev/null 2>&1 && f=$(fc-list ":charset=$1" file 2>/dev/null | head -n1 | cut -d: -f1); ' +
76  '[ -n "$f" ] || f=$(ls "$HOME"/Library/Fonts/*"$2"* /Library/Fonts/*"$2"* "$HOME"/.local/share/fonts/*"$2"* 2>/dev/null | head -n1); ' +
77  '[ -n "$f" ] || { echo missing; exit 0; }; m=$(stat -c %Z "$f" 2>/dev/null || stat -f %c "$f"); p=$PPID; ' +
78  'while [ -n "$p" ] && [ "$p" -gt 1 ]; do c=$(ps -o comm= -p "$p" 2>/dev/null); c=$(basename "$c" 2>/dev/null | tr -d " "); case "$c" in ' +
79  'ghostty|kitty|alacritty|Alacritty|foot|footclient|wezterm-gui|konsole|gnome-terminal-|xterm|urxvt|st|Terminal|iTerm2) ' +
80  'e=$(ps -o etime= -p "$p" 2>/dev/null | awk -F\'[-:]\' \'{n=NF; s=$n+60*$(n-1); if (n>2) s+=3600*$(n-2); if (n>3) s+=86400*$(n-3); print s}\'); [ -n "$e" ] && [ $(( $(date +%s) - e )) -lt "$m" ] && echo stale || echo ok; exit 0;; esac; ' +
81  'p=$(ps -o ppid= -p "$p" 2>/dev/null | tr -d " "); done; echo ok'
82const PRUNE = ['node_modules', '.git', 'dist', 'target', '.venv', '__pycache__', '.playwright']
83const HOME_PRUNE = ['Library', 'AppData', '.Trash']
84
85let blink: Timer | null = null
86let generation = 0
87let workTimer: Timer | null = null
88let workGen = 0
89let epoch = 0
90let lastPress = { key: '', at: 0 }
91let view: { from: number; max: number; ids: string[] } = { from: 0, max: 0, ids: [] }
92let shownApps: AppInfo[] = []
93let gitTops = new Set<string>()
94let gitRun: Promise<void> | null = null
95let gitNext: Promise<void> | null = null
96let closed = false
97let noDock = false
98let detected: Tier = 'nerd'
99let glyphSetting = 'auto'
100let follow = true
101let fontHint = true
102let hinted = false
103let fellBack = false
104let remote = false
105let propsOpen = false
106let nativeScroll = false
107let pending = ''
108
109type Deployed = { type: string; name: string; id: string }
110const deployedOf = new Map<string, Deployed[]>()
111const deployAsked = new Set<string>()
112
113function jsonOf<T>(text: string): T | null {
114  try {
115    return JSON.parse(text.slice(Math.max(0, text.indexOf('{')))) as T
116  } catch {
117    return null
118  }
119}
120
121async function loadDeployed($: EngineInterface, workspace: string, force = false): Promise<Deployed[]> {
122  if (!/^[0-9a-f-]{36}$/i.test(workspace)) return []
123  const hit = deployedOf.get(workspace.toLowerCase())
124  if (hit && !force) return hit
125  const out: Deployed[] = []
126  let token = ''
127  for (let page = 0; page < 20; page++) {
128    const path = `workspaces/${workspace}/items${token ? `?continuationToken=${encodeURIComponent(token)}` : ''}`
129    const run = await $.process.run(['fab', 'api', path, '-q', 'text'], { timeoutMs: 60_000 }).catch(() => null)
130    const body = run && run.exitCode === 0 ? jsonOf<{ value?: { id?: string; displayName?: string; type?: string }[]; continuationToken?: string }>(run.stdout) : null
131    if (!body || !Array.isArray(body.value)) return out
132    for (const i of body.value) if (i.id && i.displayName && i.type) out.push({ type: i.type, name: i.displayName, id: i.id })
133    token = body.continuationToken ?? ''
134    if (!token) break
135  }
136  deployedOf.set(workspace.toLowerCase(), out)
137  $.ui.invalidate('ui.render')
138  return out
139}
140
141function viewApp(app: AppInfo): AppInfo {
142  const items = deployedOf.get(app.workspace.toLowerCase())
143  if (!items) return app
144  const names = [app.key, app.name].filter(Boolean).map(n => n.toLowerCase())
145  const own = (type: string) => items.find(i => i.type === type && names.includes(i.name.toLowerCase()))
146  const sources = app.sources.map(src => {
147    if (src.item) return src.workspace || !items.some(i => i.id.toLowerCase() === src.item?.toLowerCase()) ? src : { ...src, workspace: app.workspace }
148    const hit = (OWN_KINDS as readonly string[]).includes(src.kind) ? own(src.kind) : items.find(i => i.type === src.kind && i.name.toLowerCase() === src.name.toLowerCase())
149    return hit ? { ...src, item: hit.id, workspace: app.workspace } : src
150  })
151  const extra: Source[] = []
152  for (const kind of OWN_KINDS) {
153    const hit = sources.some(src => src.kind === kind) ? undefined : own(kind)
154    const [name, note] = OWN_NAME[kind] ?? [kind, '']
155    if (hit) extra.push({ kind, name, note, item: hit.id, workspace: app.workspace })
156  }
157  return extra.length || sources.some((src, i) => src !== app.sources[i]) ? { ...app, sources: [...sources, ...extra] } : app
158}
159
160function sourceUrl(app: AppInfo, src: Source): string {
161  return src.item && src.workspace ? itemUrl(src.workspace, src.kind, src.item, app.tenant) : ''
162}
163
164function sourceAt(apps: AppInfo[], id: string): { app: AppInfo; src: Source; child: string } | null {
165  const m = id.match(/^(.*)#s(\d+)(?::(.*))?$/)
166  const app = m ? apps.find(a => a.dir === m[1]) : undefined
167  const src = app?.sources[Number(m?.[2])]
168  return app && src ? { app, src, child: m?.[3] ?? '' } : null
169}
170
171function guidHits(command: string, apps: AppInfo[]): string[] {
172  const guids = new Set((command.match(GUID_RE) ?? []).map(g => g.toLowerCase()))
173  if (guids.size === 0) return []
174  const out: string[] = []
175  for (const app of apps) {
176    if (app.item && guids.has(app.item.toLowerCase())) out.push(app.dir)
177    app.sources.forEach((src, i) => {
178      if (src.item && guids.has(src.item.toLowerCase())) out.push(`${app.dir}#s${i}`)
179    })
180  }
181  return out
182}
183
184async function withBusy<T>($: EngineInterface, text: string, fn: () => Promise<T>): Promise<T> {
185  pending = text
186  $.ui.invalidate('ui.render')
187  try {
188    return await fn()
189  } finally {
190    pending = ''
191    $.ui.invalidate('ui.render')
192  }
193}
194
195const GIT_WORD: Record<string, string> = { M: 'modified', A: 'added', '?': 'untracked', D: 'deleted', R: 'renamed', C: 'copied', U: 'conflict', T: 'type changed' }
196
197function guides(depth: number): string {
198  const lines = Array.from({ length: depth }, (_, i) => `<rect x="${i * 16 + 7.5}" y="0" width="1" height="${ROW_PX}" fill="#34343c"/>`).join('')
199  return `<svg xmlns="${SVG_NS}" width="${depth * 16}" height="${ROW_PX}" viewBox="0 0 ${depth * 16} ${ROW_PX}">${lines}</svg>`
200}
201
202async function openSource($: EngineInterface, id: string): Promise<void> {
203  let hit = sourceAt((await getApps($)).map(viewApp), id)
204  if (!hit) return
205  let url = sourceUrl(hit.app, hit.src)
206  if (!url && hit.app.workspace && !deployedOf.has(hit.app.workspace.toLowerCase())) {
207    await withBusy($, 'Finding deployed items…', () => loadDeployed($, hit?.app.workspace ?? ''))
208    hit = sourceAt((await getApps($)).map(viewApp), id) ?? hit
209    url = sourceUrl(hit.app, hit.src)
210  }
211  if (url) await openTarget($, url)
212  else $.ui.toast(hit.app.workspace ? `No deployed ${KIND_LABEL[hit.src.kind] ?? hit.src.kind} found for ${hit.app.title}` : `${hit.app.title} is not deployed yet`)
213}
214
215async function pressSource($: EngineInterface, id: string): Promise<void> {
216  const now = Date.now()
217  const isDouble = lastPress.key === id && now - lastPress.at < DOUBLE_MS
218  lastPress = { key: isDouble ? '' : id, at: now }
219  if (isDouble) await openSource($, id)
220  else await patch($, () => ({ cursor: id, selected: id }))
221}
222
223function tierFor(surface: string): Tier {
224  if (glyphSetting === 'fabric' || glyphSetting === 'nerd' || glyphSetting === 'plain') return glyphSetting
225  return surface === 'desktop' ? 'plain' : detected
226}
227
228function fontNote(): string {
229  if (!fontHint || hinted || !fellBack) return ''
230  hinted = true
231  return FONT_HINT
232}
233
234function quiet(p: Promise<unknown>): void {
235  void p.catch(() => undefined)
236}
237let scanning: Promise<void> | null = null
238let scanJobs: Job[] = []
239const running = new Map<string, Job>()
240
241type Since = { ms: number; mark: string; os: 'linux' | 'darwin' | 'win32' }
242type Job = { since: Since; usedCli: boolean; deploy: boolean; deployDir: string; busy: boolean }
243
244let platform: Promise<'linux' | 'darwin' | 'win32'> | null = null
245let markId = 0
246let home = ''
247
248function osName($: EngineInterface): Promise<'linux' | 'darwin' | 'win32'> {
249  platform ??= (async () => {
250    if ((await $.env.get('OS')) === 'Windows_NT') return 'win32'
251    try {
252      return (await $.process.run(['uname', '-s'], { timeoutMs: 3_000 })).stdout.trim() === 'Darwin' ? 'darwin' : 'linux'
253    } catch {
254      return 'linux'
255    }
256  })()
257  return platform
258}
259
260async function openPane($: EngineInterface, args: { id: string; title: string; focus?: true }): Promise<void> {
261  if (noDock && !args.focus) return
262  await $.ui.open(args)
263}
264
265async function cwdOf($: EngineInterface): Promise<string> {
266  return posix(await $.session.cwd())
267}
268
269async function sinceNow($: EngineInterface, watch: boolean): Promise<Since> {
270  const ms = await $.clock.now()
271  if (!watch) return { ms, mark: '', os: 'linux' }
272  const os = await osName($)
273  if (os !== 'darwin') return { ms, mark: '', os }
274  const mark = `${((await $.env.get('TMPDIR')) || '/tmp').replace(/\/+$/, '')}/${PANE}-${await $.session.id()}-${++markId}.mark`
275  try {
276    await $.process.run(['touch', mark], { timeoutMs: 3_000 })
277    return { ms, mark, os }
278  } catch {
279    return { ms, mark: '', os }
280  }
281}
282
283async function dropMarks($: EngineInterface, marks: string[]): Promise<void> {
284  const live = marks.filter(Boolean)
285  if (live.length) await $.process.run(['rm', '-f', ...live], { timeoutMs: 3_000 }).catch(() => undefined)
286}
287
288async function copyOf($: EngineInterface, id: string, root: string, absolute: boolean, surface?: string): Promise<void> {
289  await copyText($, !absolute && id.startsWith(root + '/') ? id.slice(root.length + 1) : id, surface)
290}
291
292async function copyText($: EngineInterface, text: string, surface?: string): Promise<void> {
293  const done = await $.ui.copy({ text, ...(surface ? { surface: surface as 'terminal' } : {}) })
294  $.ui.toast(done.isCopied ? `Copied ${text}` : `Could not copy: ${done.reason}`)
295}
296
297function fit(text: string, cols: number): string {
298  return text.length > cols ? text.slice(0, cols - 1) + '…' : text
299}
300
301function clean(segs: Seg[]): Seg[] {
302  for (const seg of segs) for (const k of Object.keys(seg) as (keyof Seg)[]) if (seg[k] === undefined) delete seg[k]
303  return segs
304}
305
306async function listNames($: EngineInterface, dir: string): Promise<{ name: string; kind: string }[]> {
307  try {
308    return (await $.fs.list(dir)).map(e => ({ name: e.name, kind: e.kind }))
309  } catch {
310    return []
311  }
312}
313
314async function sourcesOf($: EngineInterface, dir: string): Promise<Source[]> {
315  const fp = join(dir, 'rayfin/functions-python')
316  const udfDefs = await Promise.all(
317    (await listNames($, fp)).filter(e => e.kind === 'dir').map(async e => ({ folder: e.name, text: await readText($, join(fp, `${e.name}/definition.json`)) })),
318  )
319  const tsFunctions = (await listNames($, join(dir, 'rayfin/functions')))
320    .filter(e => e.kind === 'file' && /\.(ts|js)$/.test(e.name) && !/\.d\.ts$/.test(e.name) && e.name !== 'index.ts')
321    .map(e => e.name.replace(/\.(ts|js)$/, ''))
322  return parseSources({
323    fabricYaml: await readText($, join(dir, 'fabric.yaml')),
324    rayfinYml: await readText($, join(dir, 'rayfin/rayfin.yml')),
325    schemaTs: await readText($, join(dir, 'rayfin/data/schema.ts')),
326    udfDefs,
327    tsFunctions,
328  })
329}
330
331async function get($: EngineInterface): Promise<FileTree> {
332  return { ...emptyTree(''), ...(await $.state.get(TREE)).value }
333}
334
335async function getApps($: EngineInterface): Promise<AppInfo[]> {
336  return (await $.state.get(APPS)).value ?? []
337}
338
339async function put($: EngineInterface, fn: (t: FileTree) => FileTree): Promise<void> {
340  await update($, TREE, value => {
341    const cur = { ...emptyTree(''), ...value }
342    return anchored(cur, fn(cur))
343  })
344}
345
346type Item = { node: FileNode; depth: number; open: boolean; source?: Source; child?: string }
347
348function topOf(t: FileTree): string {
349  return t.top && t.nodes.some(n => n.id === t.top) ? t.top : ''
350}
351
352function itemsOf(t: FileTree, apps: AppInfo[]): Item[] {
353  const byDir = new Map(apps.map(a => [a.dir, a]))
354  const rows: Item[] = []
355  const sources = (app: AppInfo, depth: number) => {
356    const synthetic = (key: string, name: string): FileNode => ({ id: `${app.dir}#${key}`, parent: app.dir, name, kind: 'file', hidden: false, mtime: 0, loaded: false })
357    if (app.error) rows.push({ node: synthetic('error', app.error), depth, open: false, source: { kind: 'error', name: app.error, note: '' } })
358    if (app.sources.length === 0) rows.push({ node: synthetic('none', 'no data sources configured'), depth, open: false, source: { kind: 'none', name: 'no data sources configured', note: '' } })
359    app.sources.forEach((src, i) => {
360      rows.push({ node: synthetic(`s${i}`, src.name), depth, open: false, source: src })
361      for (const child of src.children ?? []) rows.push({ node: synthetic(`s${i}:${child}`, child), depth: depth + 1, open: false, source: src, child })
362    })
363  }
364  const top = topOf(t)
365  const topApp = byDir.get(top)
366  if (topApp) sources(topApp, 0)
367  for (const r of visibleRows(t, top)) {
368    rows.push(r)
369    const app = byDir.get(r.node.id)
370    if (app && r.open) sources(app, r.depth + 1)
371  }
372  return rows
373}
374
375function anchored(cur: FileTree, next: FileTree): FileTree {
376  if (follow || cur.scroll === null || next.scroll !== cur.scroll || (next.nodes === cur.nodes && next.expanded === cur.expanded)) return next
377  const top = itemsOf(cur, shownApps)[cur.scroll]?.node.id
378  const at = top ? itemsOf(next, shownApps).findIndex(r => r.node.id === top) : -1
379  return at < 0 || at === cur.scroll ? next : { ...next, scroll: at }
380}
381
382function patch($: EngineInterface, fn: (t: FileTree) => Partial<FileTree>) {
383  return put($, t => ({ ...t, ...fn(t) }))
384}
385
386function appOf(apps: AppInfo[], path: string): AppInfo | undefined {
387  return apps
388    .filter(a => path === a.dir || path.startsWith(a.dir + '/') || path.startsWith(a.dir + '#'))
389    .sort((a, b) => b.dir.length - a.dir.length)[0]
390}
391
392function chainOf(apps: AppInfo[], id: string): string[] {
393  const app = appOf(apps, id)
394  if (!app || id === app.dir) return []
395  if (id.startsWith(app.dir + '#')) return [app.dir]
396  const out: string[] = []
397  let dir = dirname(id)
398  while (dir.length >= app.dir.length) {
399    out.push(dir)
400    if (dir === app.dir) break
401    dir = dirname(dir)
402  }
403  return out
404}
405
406async function list($: EngineInterface, dir: string): Promise<FileNode[]> {
407  const entries = await $.fs.list(dir)
408  const resolved = await Promise.all(
409    entries.map(async e => {
410      if (!e.isLink) return { name: e.name, kind: e.kind, mtimeMs: e.mtimeMs, isLink: false }
411      try {
412        const target = await $.fs.stat(join(dir, e.name))
413        return target.kind === 'dir'
414          ? { name: e.name, kind: 'dir' as const, mtimeMs: target.mtimeMs, isLink: false }
415          : { name: e.name, kind: 'file' as const, mtimeMs: target.mtimeMs, isLink: true }
416      } catch {
417        return { name: e.name, kind: 'other' as const, mtimeMs: 0, isLink: true }
418      }
419    }),
420  )
421  return toNodes(dir, resolved)
422}
423
424async function loadDirs($: EngineInterface, dirs: string[]): Promise<Map<string, FileNode[]>> {
425  const root = (await get($)).root
426  const listed = new Map<string, FileNode[]>()
427  const failed: string[] = []
428  await mapLimit(dirs, LIST_LIMIT, async dir => {
429    try {
430      listed.set(dir, await list($, dir))
431    } catch (err) {
432      failed.push(`${shortPath(dir)} (${err instanceof Error ? err.message : String(err)})`)
433    }
434  })
435  await patch($, t => (t.root === root ? { nodes: replaceChildren(t.nodes, listed), status: failed.length ? `could not list ${failed.join(', ')}` : '' } : {}))
436  return listed
437}
438
439async function readText($: EngineInterface, path: string): Promise<string> {
440  try {
441    return String(await $.fs.read(path))
442  } catch {
443    return ''
444  }
445}
446
447async function walkMarkers($: EngineInterface, root: string): Promise<string[]> {
448  const hits: string[] = []
449  let level = [root]
450  let seen = 0
451  for (let depth = 0; depth < 6 && level.length && seen < 20_000; depth++) {
452    const next: string[] = []
453    for (const dir of level) {
454      for (const n of await list($, dir).catch(() => [] as FileNode[])) {
455        seen++
456        if (n.kind === 'dir' && !PRUNE.includes(n.name) && !(root === home && HOME_PRUNE.includes(n.name))) next.push(n.id)
457        for (const cli of CLIS) {
458          const [first, ...rest] = cli.marker.split('/')
459          if (n.name !== first) continue
460          if (rest.length === 0 && n.kind !== 'dir') hits.push(n.id)
461          else if (rest.length && n.kind === 'dir' && (await $.fs.stat(join(n.id, rest.join('/'))).then(st => st.kind === 'file', () => false))) hits.push(join(n.id, rest.join('/')))
462        }
463      }
464    }
465    level = next
466  }
467  return hits
468}
469
470function markerOf(path: string): { dir: string; cli: string } | null {
471  for (const cli of CLIS) if (path.endsWith(`/${cli.marker}`)) return { dir: path.slice(0, -(cli.marker.length + 1)) || '/', cli: cli.name }
472  return null
473}
474
475async function discover($: EngineInterface, root: string): Promise<AppInfo[]> {
476  const names = root === home ? [...PRUNE, ...HOME_PRUNE] : PRUNE
477  const prune = names.flatMap((name, i) => (i === 0 ? ['-name', name] : ['-o', '-name', name]))
478  const markers = CLIS.flatMap((c, i) => [...(i ? ['-o'] : []), ...(c.marker.includes('/') ? ['-path', `*/${c.marker}`] : ['-name', c.marker])])
479  let hits: string[] = []
480  try {
481    if ((await osName($)) === 'win32') hits = await walkMarkers($, root)
482    else {
483      const run = await $.process.run(['find', '-H', root, '-maxdepth', '6', '(', ...prune, ')', '-prune', '-o', '(', ...markers, ')', '-print0'], { timeoutMs: 10_000 })
484      hits = run.stdout.split('\0').filter(Boolean)
485    }
486  } catch {
487    hits = []
488  }
489  const kinds = new Map<string, string[]>()
490  for (const hit of hits) {
491    const found = markerOf(hit)
492    if (!found) continue
493    const names = kinds.get(found.dir) ?? []
494    if (!names.includes(found.cli)) names.push(found.cli)
495    kinds.set(found.dir, names)
496  }
497  const dirs = [...kinds.keys()].sort((a, b) => a.localeCompare(b))
498  return mapLimit(dirs, READ_LIMIT, dir => appAt($, dir, kinds.get(dir) ?? []))
499}
500
501async function appAt($: EngineInterface, dir: string, names: string[]): Promise<AppInfo> {
502  const clis = CLIS.filter(c => names.includes(c.name))
503  const cli = clis.map(c => c.name).join('+')
504  try {
505    const parts = await Promise.all(clis.map(c => c.read(dir, rel => readText($, join(dir, rel)))))
506    const info = parts.reduce((a, b) => merge(a, b))
507    return { ...info, sources: await sourcesOf($, dir) }
508  } catch (err) {
509    const name = dir.split('/').pop() || dir
510    return { dir, name, key: '', title: name, cli, tenant: '', workspace: '', item: '', portal: '', hosting: '', sources: [], error: `could not read this app: ${err instanceof Error ? err.message : String(err)}` }
511  }
512}
513
514async function syncApps($: EngineInterface, found?: AppInfo[], at = epoch): Promise<{ added: string[]; changed: string[] }> {
515  const t = await get($)
516  if (!t.root || epoch !== at) return { added: [], changed: [] }
517  const before = await getApps($)
518  const apps = (found ?? (await discover($, t.root))).filter(a => a.dir !== t.root)
519  const now = await get($)
520  if (epoch !== at || now.root !== t.root) return { added: [], changed: [] }
521  await $.state.set(APPS, apps)
522  const old = new Map(before.map(a => [a.dir, JSON.stringify(a)]))
523  const added = apps.filter(a => !old.has(a.dir)).map(a => a.dir)
524  const changed = apps.filter(a => old.has(a.dir) && old.get(a.dir) !== JSON.stringify(a)).map(a => a.dir)
525  await patch($, cur => {
526    if (cur.root !== t.root) return {}
527    const keep = new Set(apps.map(a => a.dir))
528    const appNodes: FileNode[] = apps.map(a => {
529      const prev = cur.nodes.find(n => n.id === a.dir)
530      return { id: a.dir, parent: cur.root, name: a.title, kind: 'dir', hidden: false, mtime: 0, loaded: prev?.loaded ?? false }
531    })
532    const rest = cur.nodes.filter(n => n.parent !== cur.root && !keep.has(n.id) && underAny(n.parent, keep, cur.root))
533    return { nodes: [...appNodes, ...rest] }
534  })
535  return { added, changed }
536}
537
538type GitScan = { dir: string; git: Record<string, string>; ignored: string[]; untrackedDirs: string[]; diff: Record<string, [number, number]>; files: Record<string, Change> }
539
540async function gitAt($: EngineInterface, dir: string): Promise<{ top: string; prefix: string } | null> {
541  const run = await $.process.run(['git', '-C', dir, 'rev-parse', '--show-prefix', '--show-toplevel'], { timeoutMs: 10_000 })
542  if (run.exitCode !== 0) return null
543  const [prefix = '', toplevel = ''] = run.stdout.split('\n')
544  return { top: toplevel.trim(), prefix: prefix.trim() }
545}
546
547async function scanGit($: EngineInterface, dir: string, prefix: string): Promise<GitScan | null> {
548  const git = (args: string[]) => $.process.run(['git', '--no-optional-locks', '-C', dir, ...args], { timeoutMs: 20_000, env: { GIT_OPTIONAL_LOCKS: '0' } })
549  const run = await git(['status', '--porcelain=v1', '-z', '--ignored=traditional', '--untracked-files=normal', '--', '.'])
550  if (run.exitCode !== 0) return null
551  const parsed = parseGit(run.stdout, dir, prefix)
552  const diff: Record<string, [number, number]> = {}
553  const head = await git(['diff', 'HEAD', '--numstat', '-z', '--', '.'])
554  if (head.exitCode === 0) parseNumstat(head.stdout, dir, prefix, diff)
555  const files = { ...parsed.files }
556  if (parsed.untrackedDirs.length) {
557    const others = await git(['ls-files', '-o', '--exclude-standard', '-z', '--', ...parsed.untrackedDirs.map(d => d.slice(dir.length + 1) || '.')])
558    if (others.exitCode === 0) for (const rel of others.stdout.split('\0').filter(Boolean)) files[join(dir, rel)] = 'new'
559  }
560  for (const path of Object.keys(diff)) if (files[path] === 'new') delete diff[path]
561  return { dir, git: parsed.git, ignored: parsed.ignored, untrackedDirs: parsed.untrackedDirs, diff, files }
562}
563
564async function readGit($: EngineInterface): Promise<void> {
565  const t = await get($)
566  if (!t.root) return
567  const root = t.root
568  try {
569    const apps = await getApps($)
570    const base = await gitAt($, root)
571    const rootScan = base ? await scanGit($, root, base.prefix) : null
572    if (base && !rootScan) return
573    const loose = rootScan ? new Set([...rootScan.untrackedDirs, ...rootScan.ignored]) : null
574    const candidates = apps.filter(a => !loose || loose.has(a.dir)).sort((x, y) => x.dir.length - y.dir.length)
575    const found = await mapLimit(candidates, READ_LIMIT, a => gitAt($, a.dir).catch(() => null))
576    const own: { dir: string; top: string; prefix: string }[] = []
577    candidates.forEach((a, i) => {
578      const g = found[i]
579      if (!g || (base && g.top === base.top) || own.some(o => o.top === g.top && a.dir.startsWith(o.dir + '/'))) return
580      own.push({ dir: a.dir, top: g.top, prefix: g.prefix })
581    })
582    const extra = await mapLimit(own, READ_LIMIT, o => scanGit($, o.dir, o.prefix).catch(() => null))
583    const scans = [...(rootScan ? [rootScan] : []), ...extra.filter((x): x is GitScan => x !== null)]
584    const owned = scans.map(x => x.dir).filter(d => d !== root)
585    gitTops = new Set([...(base ? [base.top] : []), ...own.filter((_, i) => extra[i]).map(o => o.top)])
586    const git: Record<string, string> = {}
587    const ignored: string[] = []
588    const untrackedDirs: string[] = []
589    const diff: Record<string, [number, number]> = {}
590    const files: Record<string, Change> = {}
591    for (const scan of scans) {
592      const deeper = owned.filter(d => d !== scan.dir && d.startsWith(scan.dir === '/' ? '/' : scan.dir + '/'))
593      const keep = (p: string) => !deeper.some(d => p === d || p.startsWith(d + '/'))
594      for (const [p, l] of Object.entries(scan.git)) if (keep(p)) git[p] = stronger(git[p], l)
595      ignored.push(...scan.ignored.filter(keep))
596      untrackedDirs.push(...scan.untrackedDirs.filter(keep))
597      for (const [p, d] of Object.entries(scan.diff)) if (keep(p)) diff[p] = d
598      for (const [p, c] of Object.entries(scan.files)) if (keep(p)) files[p] = c
599    }
600    await patch($, cur => (cur.root === root ? { git, ignored, untrackedDirs, diff: rollUp(diff, root), counts: rollCounts(files, root) } : {}))
601  } catch {
602    gitTops = new Set()
603  }
604}
605
606function refreshGit($: EngineInterface): Promise<void> {
607  if (!gitRun) {
608    gitRun = readGit($).finally(() => {
609      gitRun = null
610    })
611    return gitRun
612  }
613  const rerun = () => {
614    gitNext = null
615    return refreshGit($)
616  }
617  gitNext ??= gitRun.then(rerun, rerun)
618  return gitNext
619}
620
621async function reset($: EngineInterface, start: string, focus = false, found?: AppInfo[]): Promise<void> {
622  const mine = ++epoch
623  const apps = found ?? (await discover($, start))
624  const root = apps.some(a => a.dir === start) ? dirname(start) : start
625  const keepHidden = (await get($)).showHidden
626  if (epoch !== mine) return
627  generation += 1
628  blink?.cancel()
629  blink = null
630  await put($, () => ({ ...emptyTree(root), showHidden: keepHidden }))
631  await $.state.set(APPS, [])
632  const title = titleOf(root)
633  closed = false
634  if (focus) await openPane($, { id: PANE, title, focus: true })
635  else await openPane($, { id: PANE, title })
636  await syncApps($, apps, mine)
637  await refreshGit($)
638}
639
640function titleOf(root: string): string {
641  return `${TITLE}: ${root.split('/').pop() || root}`
642}
643
644function isLoaded(t: FileTree, dir: string): boolean {
645  return Boolean(t.nodes.find(n => n.id === dir)?.loaded)
646}
647
648async function revealPaths($: EngineInterface, paths: string[]): Promise<void> {
649  const apps = await getApps($)
650  for (let pass = 0; pass < 32; pass++) {
651    const t = await get($)
652    const need = new Set<string>()
653    for (const p of paths) {
654      for (const dir of chainOf(apps, p).reverse()) {
655        if (!isLoaded(t, dir)) {
656          need.add(dir)
657          break
658        }
659      }
660    }
661    if (need.size === 0) return
662    await loadDirs($, [...need])
663  }
664}
665
666async function changedSince($: EngineInterface, dirs: string[], since: Since): Promise<string[]> {
667  if (dirs.length === 0 || since.os === 'win32') return []
668  const prune = PRUNE.flatMap((name, i) => (i === 0 ? ['-name', name] : ['-o', '-name', name]))
669  const test = since.mark ? ['-newer', since.mark] : ['-newermt', `@${(since.ms / 1000).toFixed(3)}`]
670  try {
671    const run = await $.process.run(['find', '-H', ...dirs, '-xdev', '(', ...prune, ')', '-prune', '-o', '-type', 'f', ...test, '-print0'], {
672      timeoutMs: 8_000,
673    })
674    return run.stdout.split('\0').filter(Boolean)
675  } catch {
676    return []
677  }
678}
679
680async function flash($: EngineInterface, ids: string[], tone = 'orange', ends = 0): Promise<void> {
681  const unique = [...new Set(ids)]
682  if (unique.length === 0 && ends === 0) return
683  const apps = await getApps($)
684  const root = (await get($)).root
685  const now = await $.clock.now()
686  const seen = new Set(view.ids)
687  const inView = unique.every(id => seen.has(id))
688  let mode = 'none' as 'none' | 'flash' | 'work'
689  await patch($, cur => {
690    mode = 'none'
691    if (cur.root !== root) return {}
692    const w = ends > 0 ? cur.work : null
693    if (!w && unique.length === 0) return {}
694    const open = new Set(cur.expanded)
695    const prior = w ? w.lit : cur.flashOn ? cur.flash : []
696    const bright = new Set([...prior.filter(id => !unique.includes(id)), ...unique])
697    const dim = new Set<string>(w ? w.dim : cur.flashOn ? cur.flashDim : [])
698    const tones: Record<string, string> = !w && cur.flashOn ? { ...cur.flashTones } : {}
699    for (const id of unique) {
700      tones[id] = tone
701      const chain = chainOf(apps, id)
702      if (!chain.some(a => !open.has(a))) continue
703      for (const a of chain) {
704        if (!open.has(a)) {
705          dim.add(a)
706          tones[a] ??= tone
707        }
708        if (follow) open.add(a)
709      }
710    }
711    for (const id of bright) dim.delete(id)
712    const top = topOf(cur)
713    const away = follow && top !== '' && unique.some(id => id !== top && !inside(top, id))
714    const reveal: Partial<FileTree> = unique.length
715      ? { expanded: [...open], ...(follow && !inView ? { scroll: null } : {}), ...(away ? { top: '' } : {}) }
716      : {}
717    if (w) {
718      const n = Math.max(0, w.n - ends)
719      if (n === 0 && unique.length === 0) return { work: null }
720      if (n === 0) mode = 'work'
721      return { ...reveal, work: { ...w, n, lit: [...bright], dim: [...dim], until: n === 0 ? now + FLASH_MS : 0 } }
722    }
723    mode = 'flash'
724    return { ...reveal, flash: [...bright], flashDim: [...dim], flashOn: true, flashTones: tones }
725  })
726  if (mode === 'flash') {
727    const mine = ++generation
728    blink?.cancel()
729    blink = $.clock.after(FLASH_MS, () => {
730      if (generation !== mine) return
731      blink = null
732      quiet(patch($, cur => (generation === mine ? { flash: [], flashDim: [], flashOn: false, flashTones: {} } : {})))
733    })
734  } else if (mode === 'work') {
735    const mine = ++workGen
736    workTimer?.cancel()
737    workTimer = $.clock.after(FLASH_MS, () => {
738      if (workGen !== mine) return
739      workTimer = null
740      quiet(patch($, cur => (workGen === mine && cur.work?.n === 0 ? { work: null } : {})))
741    })
742  }
743  if (unique.length === 0) return
744  const t = await get($)
745  if (!closed) await openPane($, { id: PANE, title: titleOf(t.root) })
746}
747
748function touchedBy(apps: AppInfo[], calls: CliCall[]): string[] {
749  return [...new Set(calls.map(c => (c.cwd ? appOf(apps, c.cwd)?.dir : undefined)).filter((d): d is string => Boolean(d)))]
750}
751
752async function startWork($: EngineInterface, tone: string, lit: string[]): Promise<void> {
753  const at = await $.clock.now()
754  workGen += 1
755  workTimer?.cancel()
756  workTimer = null
757  await patch($, cur => {
758    const live = cur.work && cur.work.n > 0 ? cur.work : null
759    return {
760      work: {
761        tone: live?.tone === 'teal' ? 'teal' : tone,
762        n: (live?.n ?? 0) + 1,
763        at,
764        until: 0,
765        lit: [...new Set([...(live?.lit ?? []), ...lit])],
766        dim: live?.dim ?? [],
767      },
768    }
769  })
770}
771
772function endWork($: EngineInterface): Promise<void> {
773  return flash($, [], 'orange', 1)
774}
775
776async function afterBash($: EngineInterface, jobs: Job[]): Promise<{ ids: string[]; tone: string }> {
777  const t = await get($)
778  if (!t.root) return { ids: [], tone: 'orange' }
779  const usedCli = jobs.some(j => j.usedCli)
780  const deploy = jobs.some(j => j.deploy)
781  const deployDir = jobs.map(j => j.deployDir).find(Boolean) ?? ''
782  const since = jobs.reduce((a, j) => (j.since.ms < a.ms ? j.since : a), jobs[0]?.since ?? { ms: 0, mark: '', os: 'linux' as const })
783  const { added, changed } = usedCli ? await syncApps($) : { added: [], changed: [] }
784  const apps = await getApps($)
785  await refreshGit($)
786  const ignored = new Set((await get($)).ignored)
787  const fresh = added.length ? [] : await changedSince($, apps.map(a => a.dir), since)
788  const hits = fresh.filter(p => !underAny(p, ignored, t.root)).slice(0, FIND_LIMIT)
789  const newMarker = hits.some(p => markerOf(p) !== null)
790  const sync = usedCli ? { added: [], changed: [] } : newMarker ? await syncApps($) : { added: [], changed: await refreshApps($, hits) }
791  await revealPaths($, hits)
792  const loaded = await get($)
793  const open = new Set(loaded.expanded)
794  await loadDirs($, [...new Set([...loaded.nodes.filter(n => n.kind === 'dir' && n.loaded && open.has(n.id)).map(n => n.id), ...hits.map(dirname)])])
795  const present = new Set((await get($)).nodes.map(n => n.id))
796  const ids = [...added, ...changed, ...sync.added, ...sync.changed, ...hits.filter(p => present.has(p))]
797  if (deploy) {
798    const target = deployDir ? appOf(apps, deployDir) : undefined
799    const deployed = [...changed, ...sync.changed].filter(d => apps.some(a => a.dir === d))
800    return { ids: deployed.length ? deployed : target ? [target.dir] : [], tone: 'teal' }
801  }
802  return { ids, tone: 'orange' }
803}
804
805function scheduleScan($: EngineInterface, job: Job): void {
806  scanJobs.push(job)
807  if (scanning) return
808  scanning = (async () => {
809    try {
810      while (scanJobs.length) {
811        const jobs = scanJobs
812        scanJobs = []
813        let lit = { ids: [] as string[], tone: 'orange' }
814        try {
815          lit = await afterBash($, jobs)
816        } catch (err) {
817          await report($, `refresh failed: ${err instanceof Error ? err.message : String(err)}`)
818        } finally {
819          await dropMarks($, jobs.map(j => j.since.mark))
820        }
821        try {
822          await flash($, lit.ids, lit.tone, jobs.filter(j => j.busy).length)
823        } catch (err) {
824          await report($, `refresh failed: ${err instanceof Error ? err.message : String(err)}`)
825        }
826      }
827    } finally {
828      scanning = null
829    }
830  })()
831  quiet(scanning)
832}
833
834async function report($: EngineInterface, text: string): Promise<void> {
835  await patch($, () => ({ status: text })).catch(() => $.ui.toast(text))
836}
837
838function feedsApp(app: AppInfo, path: string): boolean {
839  if (!path.startsWith(app.dir + '/')) return false
840  const rel = path.slice(app.dir.length + 1)
841  return (
842    APP_INPUTS.includes(rel) ||
843    /^rayfin\/functions\/[^/]+\.(ts|js)$/.test(rel) ||
844    /^rayfin\/functions-python\/[^/]+\/definition\.json$/.test(rel)
845  )
846}
847
848async function refreshApps($: EngineInterface, paths: string[]): Promise<string[]> {
849  const at = epoch
850  const root = (await get($)).root
851  for (let i = 0; i < 5; i++) {
852    const cur = await $.state.get(APPS)
853    const apps = cur.value ?? []
854    const dirs = new Set<string>()
855    for (const p of paths) {
856      const app = appOf(apps, p)
857      if (app && feedsApp(app, p)) dirs.add(app.dir)
858    }
859    if (dirs.size === 0) return []
860    const fresh = await Promise.all(apps.map(a => (dirs.has(a.dir) ? appAt($, a.dir, a.cli.split('+')) : a)))
861    const now = await get($)
862    if (epoch !== at || now.root !== root) return []
863    const changed = fresh.filter((a, j) => JSON.stringify(a) !== JSON.stringify(apps[j])).map(a => a.dir)
864    if (changed.length === 0) return []
865    if ((await $.state.set(APPS, fresh, { ifVersion: cur.version })).isSet) return changed
866  }
867  return []
868}
869
870async function touched($: EngineInterface, paths: string[]): Promise<void> {
871  const markers = paths.filter(p => markerOf(p) !== null)
872  const sync = markers.length ? await syncApps($) : { added: [], changed: await refreshApps($, paths) }
873  const apps = await getApps($)
874  const within = paths.filter(p => appOf(apps, p))
875  if (within.length === 0 && sync.added.length === 0) return
876  await revealPaths($, within)
877  await loadDirs($, [...new Set(within.map(dirname))].filter(d => appOf(apps, d)))
878  await refreshGit($)
879  await flash($, [...sync.added, ...within])
880}
881
882async function openTarget($: EngineInterface, target: string): Promise<void> {
883  const { argv, init } = openCommand(await osName($), target)
884  try {
885    const run = await $.process.run(argv, init)
886    if (run.exitCode !== 0) $.ui.toast(`could not open ${target} with ${argv[0]}: ${run.stderr.trim().split('\n')[0] || `exit ${run.exitCode}`}`)
887  } catch {
888    $.ui.toast(`could not open ${target} with ${argv[0]}`)
889  }
890}
891
892async function toggle($: EngineInterface, n: FileNode): Promise<void> {
893  if (n.kind === 'dir' && !n.loaded) await loadDirs($, [n.id])
894  await patch($, t => {
895    const open = new Set(t.expanded)
896    if (n.kind === 'dir') open.has(n.id) ? open.delete(n.id) : open.add(n.id)
897    return { expanded: [...open], cursor: n.id, selected: n.kind === 'dir' && n.parent !== t.root ? t.selected : n.id }
898  })
899}
900
901async function press($: EngineInterface, n: FileNode): Promise<void> {
902  const now = Date.now()
903  const isDouble = lastPress.key === n.id && now - lastPress.at < DOUBLE_MS
904  lastPress = { key: isDouble ? '' : n.id, at: now }
905  if (!isDouble) await toggle($, n)
906  else if (n.kind === 'dir') await navigate($, n)
907  else await openNode($, n, false)
908}
909
910async function navigate($: EngineInterface, n: FileNode): Promise<void> {
911  if (!n.loaded) await loadDirs($, [n.id])
912  await patch($, cur => ({ top: n.id, cursor: n.id, scroll: null, expanded: [...new Set([...cur.expanded, n.id])] }))
913}
914
915async function goUp($: EngineInterface): Promise<void> {
916  await patch($, cur => {
917    const n = cur.nodes.find(x => x.id === topOf(cur))
918    return { top: n && n.parent !== cur.root ? n.parent : '', cursor: n?.id ?? cur.cursor, scroll: null }
919  })
920}
921
922async function goHome($: EngineInterface): Promise<void> {
923  await patch($, () => ({ top: '', scroll: null }))
924}
925
926async function openNode($: EngineInterface, n: FileNode, web: boolean): Promise<void> {
927  const app = (await getApps($)).find(a => a.dir === n.id)
928  await openTarget($, app ? (web ? app.portal || app.dir : app.dir) : n.id)
929}
930
931function faint(hex: string): string {
932  const v = parseInt(hex.slice(1), 16)
933  const ch = (shift: number) => Math.round(0x26 + (((v >> shift) & 255) - 0x26) * 0.3)
934  return `#${[16, 8, 0].map(x => ch(x).toString(16).padStart(2, '0')).join('')}`
935}
936
937async function fontState($: EngineInterface, charset: string, name: string): Promise<'ok' | 'stale' | 'missing'> {
938  try {
939    const out = (await $.process.run(['sh', '-c', FONT_SCRIPT, 'sh', charset, name], { timeoutMs: 5_000 })).stdout.trim()
940    return out === 'stale' || out === 'missing' ? out : 'ok'
941  } catch {
942    return 'missing'
943  }
944}
945
946function shortPath(path: string): string {
947  return home && (path === home || path.startsWith(`${home}/`)) ? `~${path.slice(home.length)}` : path
948}
949
950function jumpTo(t: FileTree, query: string): Partial<FileTree> {
951  const q = query.trim().toLowerCase()
952  const hits = q ? t.nodes.filter(n => n.name.toLowerCase().includes(q)).slice(0, 10) : []
953  const open = new Set(t.expanded)
954  for (const n of hits) for (const a of ancestorsOf(n.id, t.root)) open.add(a)
955  const top = topOf(t)
956  const first = hits[0]?.id
957  return { query: '', expanded: [...open], cursor: first ?? t.cursor, scroll: null, top: first && top && !inside(top, first) ? '' : top }
958}
959
960let lastDetect = 0
961
962async function detectGlyphs($: EngineInterface): Promise<void> {
963  lastDetect = await $.clock.now()
964  if (remote) {
965    detected = 'nerd'
966    return
967  }
968  const nerd = (await fontState($, 'f04eb', 'Nerd')) === 'ok'
969  detected = nerd && (await fontState($, 'f2002', 'FabricSymbols')) === 'ok' ? 'fabric' : nerd ? 'nerd' : 'plain'
970}
971
972async function startup($: EngineInterface, detect: boolean): Promise<void> {
973  if (detect) {
974    remote = Boolean((await $.env.get('SSH_CONNECTION')) || (await $.env.get('SSH_TTY')))
975    await detectGlyphs($)
976  }
977  try {
978    await $.state.set(THEME, parseTheme(String(await $.fs.read(`${(await $.env.get('HOME')) ?? ''}/${THEME_FILE}`))))
979  } catch {
980    await $.state.set(THEME, DEFAULT_THEME)
981  }
982  const t = await get($)
983  if (t.flashOn || t.work) await patch($, () => ({ flash: [], flashDim: [], flashOn: false, flashTones: {}, work: null }))
984  const cwd = await cwdOf($)
985  if (!t.root) await put($, () => emptyTree(cwd))
986  const apps = await discover($, t.root || cwd)
987  if (apps.length) {
988    if (!t.root || t.nodes.length === 0) await reset($, t.root || cwd, false, apps)
989    else {
990      await syncApps($, apps)
991      await openPane($, { id: PANE, title: titleOf(t.root || cwd) })
992    }
993  }
994}
995
996export const register: Register = (on, options) => {
997  glyphSetting = typeof options?.glyphs === 'string' ? options.glyphs : 'auto'
998  follow = options?.follow !== 'off'
999  fontHint = options?.fontHint !== 'off'
1000  on('session.start', async ($, e, next) => {
1001    useDrives((await $.env.get('OS')) === 'Windows_NT')
1002    home = posix(((await $.env.get('HOME')) || (await $.env.get('USERPROFILE')) || '').replace(/[\\/]+$/, ''))
1003    hinted = false
1004    fellBack = false
1005    closed = false
1006    noDock = false
1007    await $.command.register({ name: PANE, description: 'Show the Fabric apps under a folder; args: [path]' })
1008    quiet(startup($, true))
1009    return next(e)
1010  })
1011
1012  on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
1013    quiet(startup($, false))
1014    return next(e)
1015  })
1016
1017  on('command.run', { command: PANE }, async ($, e) => {
1018    const terminal = (await $.session.surfaces()).includes('terminal')
1019    if (terminal && e.presentation && !e.presentation.isFullscreen) return { text: `The Fabric app pane shows in the sidebar, which needs the fullscreen layout. Run /tui fullscreen, then /${PANE}.` }
1020    if (terminal && e.presentation && e.presentation.columns < 110) return { text: `The Fabric app pane shows in the sidebar, which needs a terminal at least 110 columns wide. Widen it, then run /${PANE}.` }
1021    noDock = false
1022    fellBack = false
1023    quiet(detectGlyphs($).then(() => $.ui.invalidate('ui.render')))
1024    const raw = (e.args ?? '').trim()
1025    const arg = /^["']/.test(raw) ? (tokenize(raw)[0] ?? '') : raw
1026    const cwd = await cwdOf($)
1027    const root = arg ? resolvePath(cwd, arg) : cwd
1028    if (arg) {
1029      const kind = await $.fs.stat(root).then(
1030        st => st.kind,
1031        () => 'missing',
1032      )
1033      if (kind !== 'dir') return { text: kind === 'missing' ? `No folder at ${shortPath(root)}.` : `${shortPath(root)} is not a folder.` }
1034    }
1035    await reset($, root, true)
1036    const apps = await getApps($)
1037    return { text: `${apps.length} Fabric app${apps.length === 1 ? '' : 's'} under ${shortPath(root)}.` }
1038  })
1039
1040  on('tool.call', async ($, e, next) => {
1041    if (e.tool !== 'Edit' && e.tool !== 'Write' && e.tool !== 'NotebookEdit' && e.tool !== 'Bash') return next(e)
1042    const cwd = await cwdOf($)
1043    const calls = e.tool === 'Bash' ? cliCalls(e.command, cwd, home) : []
1044    const known = e.tool === 'Bash' ? await getApps($) : []
1045    const since = await sinceNow($, e.tool === 'Bash' && (calls.length > 0 || known.length > 0))
1046    const busy = calls.length && !closed && !noDock && (await get($)).root ? (calls.some(deploys) ? 'teal' : 'orange') : ''
1047    if (busy) await startWork($, busy, touchedBy(known, calls))
1048    const hits = e.tool === 'Bash' && !closed && !noDock && (await get($)).root ? guidHits(e.command, (known.length ? known : await getApps($)).map(viewApp)) : []
1049    const hitTone = e.tool === 'Bash' && FAB_WRITES.test(e.command) ? 'orange' : 'purple'
1050    if (hits.length) await startWork($, hitTone, hits)
1051    let result: Awaited<ReturnType<typeof next>>
1052    try {
1053      result = await next(e)
1054    } catch (err) {
1055      quiet(dropMarks($, [since.mark]))
1056      if (busy) await endWork($)
1057      if (hits.length) await endWork($)
1058      throw err
1059    }
1060    if (hits.length) quiet(flash($, result.deny || result.isError ? [] : hits, hitTone, 1))
1061    const record = e.tool === 'Bash' && !result.deny && !result.isError && result.result && typeof result.result === 'object' ? (result.result as { backgroundTaskId?: unknown }) : undefined
1062    const task = typeof record?.backgroundTaskId === 'string' ? record.backgroundTaskId : ''
1063    if (result.deny || (result.isError && e.tool !== 'Bash')) {
1064      quiet(dropMarks($, [since.mark]))
1065      if (busy) await endWork($)
1066      return result
1067    }
1068    const t = await get($)
1069    if (e.tool === 'Bash') {
1070      const used = calls.filter(mutates)
1071      const usedCli = used.length > 0
1072      if (usedCli && !t.root) await reset($, cwd)
1073      const deployed = used.find(deploys)
1074      const job: Job = { since, usedCli, deploy: Boolean(deployed), deployDir: deployed?.cwd ?? '', busy: Boolean(busy) }
1075      if (!usedCli && (await getApps($)).length === 0) {
1076        quiet(dropMarks($, [since.mark]))
1077        if (task && busy) running.set(task, { ...job, usedCli: false })
1078        else if (busy) await endWork($)
1079      } else if (task) running.set(task, job)
1080      else scheduleScan($, job)
1081    } else {
1082      const file =
1083        'file_path' in e && typeof e.file_path === 'string'
1084          ? e.file_path
1085          : 'notebook_path' in e && typeof e.notebook_path === 'string'
1086            ? e.notebook_path
1087            : ''
1088      if (file) quiet(touched($, [posix(file)]))
1089    }
1090    return result
1091  })
1092
1093  on('skill.prompt', async ($, e, next) => {
1094    const result = await next(e)
1095    if (CLIS.some(c => c.skills.some(s => e.skill === s || e.skill.endsWith(`:${s}`)))) {
1096      quiet(
1097        (async () => {
1098          const t = await get($)
1099          const cwd = await cwdOf($)
1100          if (!t.root || t.nodes.length === 0) await reset($, t.root || cwd)
1101          else await openPane($, { id: PANE, title: titleOf(t.root) })
1102        })(),
1103      )
1104    }
1105    return result
1106  })
1107
1108  on('ui.message', async ($, e, next) => {
1109    if (e.requestId === PANE && e.element.startsWith('z:') && e.data && typeof e.data === 'object') {
1110      const data = e.data as { zone?: unknown; ctrl?: unknown; shift?: unknown }
1111      const id = typeof data.zone === 'string' ? data.zone : ''
1112      if (id === PROPS) {
1113        propsOpen = !propsOpen
1114        $.ui.invalidate('ui.render')
1115        return {}
1116      }
1117      if (id.includes('#')) quiet(data.ctrl ? openSource($, id) : pressSource($, id))
1118      else {
1119        const n = (await get($)).nodes.find(x => x.id === id)
1120        if (n && (data.ctrl || data.shift)) quiet(openNode($, n, Boolean(data.ctrl)))
1121        else if (n) quiet(press($, n))
1122      }
1123      return {}
1124    }
1125    if (e.requestId !== PANE || e.element !== 'rows' || !e.data || typeof e.data !== 'object') return next(e)
1126    const data = e.data as { press?: unknown; key?: unknown; ctrl?: unknown; shift?: unknown; scrollTo?: unknown; copy?: unknown }
1127    const t = await get($)
1128    if (typeof data.scrollTo === 'number') {
1129      const to = Math.round(Math.max(0, Math.min(1, data.scrollTo)) * view.max)
1130      if (to !== t.scroll) await patch($, () => ({ scroll: to }))
1131      return {}
1132    }
1133    if (typeof data.copy === 'string') {
1134      const hit = data.copy.includes('#') ? sourceAt((await getApps($)).map(viewApp), data.copy) : null
1135      if (hit) await copyText($, hit.src.item || hit.child || hit.src.name, e.surface)
1136      else await copyOf($, data.copy, t.root, Boolean(data.shift), e.surface)
1137      return {}
1138    }
1139    if (typeof data.press === 'string') {
1140      if (t.scroll === null) await patch($, () => ({ scroll: view.from }))
1141      if (data.press.includes('#')) {
1142        await (data.ctrl ? openSource($, data.press) : pressSource($, data.press))
1143        return {}
1144      }
1145      const n = t.nodes.find(x => x.id === data.press)
1146      if (!n) return {}
1147      if (data.ctrl || data.shift) await openNode($, n, Boolean(data.ctrl))
1148      else await press($, n)
1149      return {}
1150    }
1151    if (typeof data.key !== 'string') return {}
1152    const top = topOf(t)
1153    const rows = itemsOf(t, (await getApps($)).map(viewApp)).filter(r => !r.source || (r.source.kind !== 'none' && r.source.kind !== 'error'))
1154    const at = rows.findIndex(r => r.node.id === t.cursor)
1155    const item = rows[at]
1156    const cur = item?.node
1157    const move = (d: number) => {
1158      const target = rows[Math.max(0, Math.min(rows.length - 1, (at < 0 ? 0 : at) + d))]
1159      return target ? patch($, () => ({ cursor: target.node.id, scroll: null })) : Promise.resolve()
1160    }
1161    if (data.key === 'up' || data.key === 'k') await move(-1)
1162    else if (data.key === 'down' || data.key === 'j') await move(1)
1163    else if (data.key === 'pageup') await move(-10)
1164    else if (data.key === 'pagedown') await move(10)
1165    else if (data.key === 'home') await move(-rows.length)
1166    else if (data.key === 'end') await move(rows.length)
1167    else if (item?.source && cur) {
1168      if (data.key === 'return') await openSource($, cur.id)
1169      else if (data.key === ' ') await patch($, () => ({ selected: cur.id }))
1170      else if (data.key === 'left' || data.key === 'h') await patch($, () => ({ cursor: cur.parent }))
1171    } else if (cur && (data.key === 'y' || data.key === 'Y')) await copyOf($, cur.id, t.root, data.key === 'Y' || Boolean(data.shift), e.surface)
1172    else if (cur && (data.key === 'right' || data.key === 'l') && cur.kind === 'dir' && !t.expanded.includes(cur.id)) await toggle($, cur)
1173    else if (cur && (data.key === 'left' || data.key === 'h')) {
1174      if (cur.kind === 'dir' && t.expanded.includes(cur.id)) await toggle($, cur)
1175      else if (cur.parent !== (top || t.root)) await patch($, () => ({ cursor: cur.parent }))
1176    } else if (cur && data.key === 'return') await (cur.kind === 'file' ? openNode($, cur, false) : toggle($, cur))
1177    else if (cur && data.key === ' ') await toggle($, cur)
1178    return {}
1179  })
1180
1181  on('ui.close', async ($, e, next) => {
1182    const result = await next(e)
1183    if (e.id === PANE && e.origin.kind === 'person') closed = true
1184    return result
1185  })
1186
1187  on('ui.scroll', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
1188    if (nativeScroll) return next(e)
1189    const t = await get($)
1190    const to = Math.max(0, Math.min(view.max, (t.scroll ?? view.from) + Math.sign(e.by) * Math.max(3, Math.abs(e.by))))
1191    if (to !== t.scroll) await patch($, () => ({ scroll: to }))
1192    return {}
1193  })
1194
1195  on('prompt.submit', async ($, e, next) => {
1196    if (e.origin.kind === 'task-notification') {
1197      for (const [task, job] of running) {
1198        if (!e.text.includes(task)) continue
1199        running.delete(task)
1200        if (job.usedCli || (await getApps($)).length > 0) scheduleScan($, job)
hooks/open.ts 41 lines
1export const LINUX_LAUNCH = 'setsid -f -w "$@" </dev/null >/dev/null 2>&1 & p=$!; sleep 1; kill -0 "$p" 2>/dev/null && exit 0; wait "$p"'
2
3export const LINUX_OPEN = [
4  'set -f',
5  'f=$1',
6  'if command -v gio >/dev/null; then',
7  '  if [ -f "$f" ] && command -v file >/dev/null && encoding=$(file -b --mime-encoding -- "$f") && [ -n "$encoding" ] && [ "$encoding" != binary ]; then',
8  '    case $(gio info -a standard::content-type -- "$f" | sed -n \'s/.*standard::content-type: //p\') in',
9  '      video/* | audio/*)',
10  '        app=$(xdg-mime query default text/plain)',
11  '        IFS=:',
12  '        for dir in "${XDG_DATA_HOME:-$HOME/.local/share}" ${XDG_DATA_DIRS:-/usr/local/share:/usr/share}; do',
13  '          [ -n "$app" ] && [ -f "$dir/applications/$app" ] && exec gio launch "$dir/applications/$app" "$f"',
14  '        done',
15  '        echo "No text/plain desktop application found for $f" >&2',
16  '        exit 1',
17  '        ;;',
18  '    esac',
19  '  fi',
20  '  if (exec gio open "$f"); then exit 0; fi',
21  'fi',
22  'exec xdg-open "$f"',
23].join('\n')
24
25const WIN_OPEN = "$ErrorActionPreference = 'Stop'; [Diagnostics.Process]::Start([Diagnostics.ProcessStartInfo]@{ FileName = $env:PANE_OPEN_TARGET; UseShellExecute = $true }) | Out-Null"
26
27export function openCommand(os: 'linux' | 'darwin' | 'win32', target: string) {
28  const argv = os === 'linux'
29    ? ['sh', '-c', LINUX_LAUNCH, 'sh', 'sh', '-c', LINUX_OPEN, 'sh', target]
30    : os === 'darwin'
31      ? ['open', '--', target]
32      : ['powershell', '-NoProfile', '-NonInteractive', '-Command', WIN_OPEN]
33  return {
34    argv,
35    init: {
36      timeoutMs: 10_000,
37      ...(os === 'win32' ? { env: { PANE_OPEN_TARGET: /^[a-z][a-z0-9+.-]*:\/\//i.test(target) ? target : target.replace(/\//g, '\\') } } : {}),
38    },
39  }
40}
41
hooks/apps.ts 217 lines
1import type { AppInfo, Source } from '../types'
2import { CONNECTOR_KIND, KIND_LABEL } from './glyphs'
3
4const PORTAL = 'https://app.fabric.microsoft.com'
5const GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
6
7export type Cli = {
8  name: string
9  commands: string[]
10  packages: string[]
11  mutating: string[]
12  deploy: string[]
13  marker: string
14  inputs: string[]
15  start: string
16  skills: string[]
17  read: (dir: string, text: (rel: string) => Promise<string>) => Promise<AppInfo>
18}
19
20export function yamlScalar(raw: string): string {
21  const v = raw.trim()
22  const quoted = v.match(/^"((?:[^"\\]|\\.)*)"|^'((?:[^']|'')*)'/)
23  if (quoted) return quoted[1] !== undefined ? quoted[1].replace(/\\(.)/g, '$1') : (quoted[2] ?? '').replace(/''/g, "'")
24  return v.replace(/(^|\s+)#.*$/, '').trim()
25}
26
27export function portalUrl(workspace: string, item: string): string {
28  return GUID.test(workspace) && GUID.test(item) ? `${PORTAL}/groups/${workspace}/appbackends/${item}` : ''
29}
30
31const ITEM_ROUTE: Record<string, string> = {
32  SemanticModel: 'datasets',
33  Lakehouse: 'lakehouses',
34  Warehouse: 'datawarehouses',
35  SQLEndpoint: 'lakewarehouses',
36  SQLDatabase: 'sqldatabases',
37  KQLDatabase: 'databases',
38  UserDataFunction: 'userdatafunctions',
39  AppBackend: 'appbackends',
40}
41
42export function itemUrl(workspace: string, type: string, item: string, tenant = ''): string {
43  const route = ITEM_ROUTE[type]
44  if (!route || !GUID.test(workspace) || !GUID.test(item)) return ''
45  const tail = type === 'SemanticModel' ? '/details' : ''
46  return `${PORTAL}/groups/${workspace}/${route}/${item}${tail}${GUID.test(tenant) ? `?ctid=${tenant}` : ''}`
47}
48
49export function merge(a: AppInfo, b: AppInfo): AppInfo {
50  return {
51    ...a,
52    key: a.key || b.key,
53    title: b.title !== b.name ? b.title : a.title,
54    cli: a.cli === b.cli ? a.cli : `${a.cli}+${b.cli}`,
55    tenant: a.tenant || b.tenant,
56    workspace: a.workspace || b.workspace,
57    item: a.item || b.item,
58    portal: a.portal || b.portal,
59    hosting: a.hosting || b.hosting,
60    error: [a.error, b.error].filter(Boolean).join('; '),
61  }
62}
63
64export type SourceInputs = {
65  fabricYaml: string
66  rayfinYml: string
67  schemaTs: string
68  udfDefs: { folder: string; text: string }[]
69  tsFunctions: string[]
70}
71
72function indentOf(line: string): number {
73  return line.length - line.trimStart().length
74}
75
76function yamlSection(yaml: string, key: string): string[] {
77  const lines = yaml.split('\n')
78  const start = lines.findIndex(l => new RegExp(`^\\s*${key}:\\s*$`).test(l))
79  if (start < 0) return []
80  const base = indentOf(lines[start] ?? '')
81  const out: string[] = []
82  for (const line of lines.slice(start + 1)) {
83    if (line.trim() === '' || line.trim().startsWith('#')) continue
84    if (indentOf(line) <= base && !line.trimStart().startsWith('- ')) break
85    if (indentOf(line) < base) break
86    out.push(line)
87  }
88  return out
89}
90
91function fabricYamlModels(yaml: string): Source[] {
92  const block = yamlSection(yaml, 'semanticModels')
93  if (block.length === 0) return []
94  const keyIndent = Math.min(...block.map(indentOf))
95  const out: Source[] = []
96  for (const l of block) {
97    if (indentOf(l) === keyIndent && /^\s*[^\s:]+:\s*$/.test(l)) {
98      out.push({ kind: 'SemanticModel', name: l.trim().replace(/:$/, ''), note: 'semantic model' })
99      continue
100    }
101    const item = l.match(/^\s*itemId:\s*["']?([0-9a-fA-F-]{36})/)?.[1]
102    const ws = l.match(/^\s*workspaceId:\s*["']?([0-9a-fA-F-]{36})/)?.[1]
103    const last = out[out.length - 1]
104    if (item && last && !last.item) last.item = item
105    if (ws && last && !last.workspace) last.workspace = ws
106  }
107  return out
108}
109
110function rayfinConnectors(yaml: string): Source[] {
111  const lines = yaml.split('\n')
112  const start = lines.findIndex(l => /^connectors:\s*(#.*)?$/.test(l))
113  if (start < 0) return []
114  const items: { keys: Record<string, string>; itemId: string; workspaceId: string }[] = []
115  let dash = -1
116  let keyIndent = -1
117  const take = (text: string, indent: number) => {
118    const item = items[items.length - 1]
119    const kv = text.match(/^([\w-]+):(.*)$/)
120    if (!item || !kv?.[1]) return
121    const value = yamlScalar(kv[2] ?? '')
122    if (indent === keyIndent && !(kv[1] in item.keys)) item.keys[kv[1]] = value
123    if (kv[1] === 'itemId' && !item.itemId && /^[0-9a-fA-F-]{36}$/.test(value)) item.itemId = value
124    if (kv[1] === 'workspaceId' && !item.workspaceId && /^[0-9a-fA-F-]{36}$/.test(value)) item.workspaceId = value
125  }
126  for (const line of lines.slice(start + 1)) {
127    if (line.trim() === '' || line.trim().startsWith('#')) continue
128    if (/^\S/.test(line) && !line.startsWith('-')) break
129    const entry = line.match(/^(\s*)-(\s+)(.*)$/)
130    if (entry && (dash < 0 || (entry[1] ?? '').length === dash)) {
131      dash = (entry[1] ?? '').length
132      keyIndent = dash + 1 + (entry[2] ?? '').length
133      items.push({ keys: {}, itemId: '', workspaceId: '' })
134      take(entry[3] ?? '', keyIndent)
135      continue
136    }
137    take(line.trimStart(), indentOf(line))
138  }
139  return items
140    .filter(i => i.keys.name)
141    .map(i => {
142      const type = i.keys.type ?? ''
143      const kind = CONNECTOR_KIND[type] ?? 'table'
144      return { kind, name: i.keys.name ?? '', note: KIND_LABEL[kind] ?? type, ...(i.itemId ? { item: i.itemId } : {}), ...(i.workspaceId ? { workspace: i.workspaceId } : {}) }
145    })
146}
147
148function service(yaml: string, name: string): { enabled: boolean; dialect: string } {
149  const block = yamlSection(yaml, name)
150  const enabled = block.some(l => /^\s*enabled:\s*true\b/.test(l) && indentOf(l) === Math.min(...block.map(indentOf)))
151  const dialect = block.map(l => l.match(/^\s*dialect:\s*["']?([\w-]+)/)?.[1]).find(Boolean) ?? ''
152  return { enabled, dialect }
153}
154
155function schemaEntities(ts: string): string[] {
156  const list = ts.match(/schema\s*=\s*\[([^\]]*)\]/)?.[1] ?? ''
157  return list
158    .split(',')
159    .map(s => s.trim())
160    .filter(Boolean)
161}
162
163export function parseSources(input: SourceInputs): Source[] {
164  const seen = new Set<string>()
165  const out: Source[] = []
166  const add = (s: Source) => {
167    const key = s.item ? `id:${s.item.toLowerCase()}` : `${s.kind}:${s.name.toLowerCase()}`
168    if (seen.has(key)) return
169    seen.add(key)
170    out.push(s)
171  }
172  for (const s of rayfinConnectors(input.rayfinYml)) add(s)
173  for (const s of fabricYamlModels(input.fabricYaml)) add(s)
174  for (const def of input.udfDefs) {
175    try {
176      const parsed = JSON.parse(def.text) as {
177        connectedDataSources?: { alias?: string; artifactType?: string }[]
178      }
179      for (const c of parsed.connectedDataSources ?? []) {
180        const kind = c.artifactType && KIND_LABEL[c.artifactType] ? c.artifactType : 'table'
181        add({ kind, name: c.alias ?? 'connection', note: `${KIND_LABEL[kind] ?? c.artifactType ?? 'source'} (UDF)` })
182      }
183    } catch {
184      continue
185    }
186  }
187  const data = service(input.rayfinYml, 'data')
188  if (data.enabled) {
189    const entities = schemaEntities(input.schemaTs)
190    add({
191      kind: 'SQLDatabase',
192      name: 'SQL database',
193      note: [data.dialect || 'sql', entities.length ? `${entities.length} table${entities.length === 1 ? '' : 's'}` : ''].filter(Boolean).join(' · '),
194      children: entities,
195    })
196  }
197  const functions: string[] = [...input.tsFunctions]
198  for (const def of input.udfDefs) {
199    try {
200      const parsed = JSON.parse(def.text) as { functions?: { name?: string }[] }
201      for (const f of parsed.functions ?? []) if (f.name) functions.push(f.name)
202    } catch {
203      continue
204    }
205  }
206  const fnService = service(input.rayfinYml, 'functions')
207  if (functions.length || fnService.enabled) {
208    add({
209      kind: 'UserDataFunction',
210      name: 'User data functions',
211      note: functions.length ? `${functions.length} function${functions.length === 1 ? '' : 's'}` : 'enabled, none yet',
212      children: [...new Set(functions)],
213    })
214  }
215  return out
216}
217
hooks/clis.ts 4 lines
1import { rayfin } from './rayfin'
2
3export const CLIS = [rayfin]
4
hooks/glyphs.ts 82 lines
1export type Tier = 'fabric' | 'nerd' | 'plain'
2type Rgb = [number, number, number]
3type Glyph = { fabric: number; nerd: string; plain: string; rgb: Rgb }
4
5const GLYPHS: Record<string, Glyph> = {
6  app: { fabric: 991302, nerd: '\u{f003b}', plain: '▣', rgb: [29, 83, 164] },
7  SemanticModel: { fabric: 991234, nerd: '\u{f01bc}', plain: '◆', rgb: [90, 64, 156] },
8  Lakehouse: { fabric: 991258, nerd: '\u{f0b9d}', plain: '◇', rgb: [29, 83, 164] },
9  Warehouse: { fabric: 991243, nerd: '\u{f0a0b}', plain: '▤', rgb: [29, 83, 164] },
10  SQLDatabase: { fabric: 991280, nerd: '\u{f1063}', plain: '▦', rgb: [0, 142, 230] },
11  SQLEndpoint: { fabric: 991243, nerd: '\u{f0a0b}', plain: '▥', rgb: [29, 83, 164] },
12  KQLDatabase: { fabric: 991255, nerd: '\u{f1063}', plain: '▦', rgb: [0, 142, 230] },
13  UserDataFunction: { fabric: 991284, nerd: '\u{f0295}', plain: 'ƒ', rgb: [63, 125, 53] },
14  function: { fabric: 0, nerd: '\u{f0295}', plain: 'ƒ', rgb: [63, 125, 53] },
15}
16
17const TABLE: Glyph = { fabric: 0, nerd: '\u{f04eb}', plain: '⊞', rgb: [0, 142, 230] }
18
19function hls(rgb: Rgb): [number, number, number] {
20  const [r, g, b] = rgb.map(v => v / 255) as Rgb
21  const max = Math.max(r, g, b)
22  const min = Math.min(r, g, b)
23  const l = (max + min) / 2
24  const range = max - min
25  if (range < 1e-6) return [0, l, 0]
26  const s = l <= 0.5 ? range / (max + min) : range / (2 - max - min)
27  const rc = (max - r) / range
28  const gc = (max - g) / range
29  const bc = (max - b) / range
30  const h = r === max ? bc - gc : g === max ? 2 + rc - bc : 4 + gc - rc
31  return [(((h / 6) % 1) + 1) % 1, l, s]
32}
33
34function component(m1: number, m2: number, hue: number): number {
35  const h = ((hue % 1) + 1) % 1
36  if (h < 1 / 6) return m1 + (m2 - m1) * h * 6
37  if (h < 0.5) return m2
38  if (h < 2 / 3) return m1 + (m2 - m1) * (2 / 3 - h) * 6
39  return m1
40}
41
42function lifted(rgb: Rgb): string {
43  const [h, l0, s] = hls(rgb)
44  const l = Math.max(l0, 0.62)
45  const out =
46    s < 1e-6
47      ? [l, l, l]
48      : (() => {
49          const m2 = l <= 0.5 ? l * (1 + s) : l + s - l * s
50          const m1 = 2 * l - m2
51          return [h + 1 / 3, h, h - 1 / 3].map(x => component(m1, m2, x))
52        })()
53  return '#' + out.map(v => Math.round(v * 255).toString(16).padStart(2, '0')).join('')
54}
55
56export function glyphFor(kind: string, tier: Tier): { char: string; color: string } {
57  const g = GLYPHS[kind] ?? TABLE
58  const char = tier === 'fabric' && g.fabric ? String.fromCodePoint(g.fabric) : tier === 'plain' ? g.plain : g.nerd
59  return { char, color: lifted(g.rgb) }
60}
61
62export const KIND_LABEL: Record<string, string> = {
63  SemanticModel: 'semantic model',
64  Lakehouse: 'lakehouse',
65  Warehouse: 'warehouse',
66  SQLDatabase: 'SQL database',
67  SQLEndpoint: 'SQL endpoint',
68  KQLDatabase: 'KQL database',
69  UserDataFunction: 'user data functions',
70}
71
72export const CONNECTOR_KIND: Record<string, string> = {
73  'fabric-semanticmodel': 'SemanticModel',
74  'fabric-lakehouse': 'Lakehouse',
75  'fabric-warehouse': 'Warehouse',
76  'fabric-sqldatabase': 'SQLDatabase',
77  'fabric-sql': 'SQLDatabase',
78  'fabric-kqldatabase': 'KQLDatabase',
79  'fabric-kusto': 'KQLDatabase',
80  kusto: 'KQLDatabase',
81}
82
hooks/rows.tsx 165 lines
1import type { ClientModule } from 'claude-code'
2
3export type Seg = { t: string; c?: string; b?: boolean; s?: boolean; i?: boolean; sh?: string; dim?: boolean; one?: boolean; spin?: boolean; claude?: boolean; bg?: string; tab?: string }
4export type RowSpec = { id: string; left: Seg[]; right: Seg[] }
5export type RowsProps = {
6  rows: RowSpec[]
7  active: string
8  activeBg: string
9  hoverBg: string
10  tones: Record<string, { bright: string[]; dim: string[] }>
11  pointer?: boolean
12  bar?: { pos: number; size: number; thumb: string; track: string }
13}
14type Local = { hover: number; phase: number; drag: boolean; ref: { stop?: () => void; unpoint?: () => void } }
15
16const TICK_MS = 90
17const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
18const GRADIENT = ['#5eead4', '#67e8f9', '#7dd3fc', '#93c5fd', '#a5b4fc', '#c4b5fd', '#d8b4fe', '#f0abfc', '#d8b4fe', '#c4b5fd', '#a5b4fc', '#93c5fd', '#7dd3fc', '#67e8f9']
19
20function shimmer(i: number, phase: number, len: number, palette: string[]): string {
21  const band = ((phase * 1.6) % (len + 8)) - 4
22  const d = Math.abs(i - band)
23  return palette[d < 0.8 ? 3 : d < 1.8 ? 2 : d < 2.8 ? 1 : 0] ?? palette[0] ?? '#f97316'
24}
25
26const Rows: ClientModule<RowsProps, Local> = (props, surface) => {
27  const { Box, Text } = surface.elements
28  let state = surface.state
29  if (state === undefined) {
30    state = { hover: -1, phase: 0, drag: false, ref: {} }
31    surface.setState(state)
32  }
33  const lit = props.rows.some(r => r.left.some(s => s.sh || s.spin || s.claude) || r.right.some(s => s.sh || s.spin || s.claude))
34  if (lit && !state.ref.stop) {
35    state.ref.stop = surface.every(TICK_MS, () => {
36      const cur = surface.state
37      if (cur) surface.setState({ ...cur, phase: cur.phase + 1 })
38    })
39  } else if (!lit && state.ref.stop) {
40    state.ref.stop()
41    state.ref.stop = undefined
42  }
43  if (props.pointer === false) {
44    state.ref.unpoint?.()
45    state.ref.unpoint = undefined
46  } else state.ref.unpoint = surface.onPointer(e => {
47    const cur = surface.state ?? state
48    const span = Math.max(1, props.rows.length - 1)
49    const onBar = Boolean(props.bar) && e.x >= surface.columns - 1
50    if (props.bar && (cur.drag || (onBar && e.type === 'down' && (e.button ?? 'left') === 'left'))) {
51      if (e.type === 'up' || e.type === 'leave') {
52        surface.setState({ ...cur, drag: false })
53        return
54      }
55      if (e.type === 'down' || e.type === 'move') {
56        if (!cur.drag) surface.setState({ ...cur, drag: true, hover: -1 })
57        surface.post({ scrollTo: Math.max(0, Math.min(1, e.y / span)) })
58        return
59      }
60    }
61    if (e.type === 'leave' || e.y < 0 || e.y >= props.rows.length) {
62      if (cur.hover !== -1) surface.setState({ ...cur, hover: -1 })
63      return
64    }
65    if (e.type === 'move' && !e.button && cur.hover !== e.y) surface.setState({ ...cur, hover: e.y })
66    const row = props.rows[e.y]
67    if (e.type === 'down' && e.button === 'right' && row?.id) {
68      surface.post({ copy: row.id, shift: Boolean(e.shift) })
69      return
70    }
71    if (e.type !== 'down' || (e.button ?? 'left') !== 'left' || !row) return
72    const wide = (seg: Seg) => [...seg.t].length + (seg.spin ? 1 : 0)
73    let x = 0
74    for (const seg of row.left) {
75      const w = wide(seg)
76      if (seg.tab && e.x >= x && e.x < x + w) {
77        surface.post({ tab: seg.tab })
78        return
79      }
80      x += w
81    }
82    x = surface.columns - (props.bar ? 1 : 0) - row.right.reduce((n, seg) => n + wide(seg), 0)
83    for (const seg of row.right) {
84      const w = wide(seg)
85      if (seg.tab && e.x >= x && e.x < x + w) {
86        surface.post({ tab: seg.tab })
87        return
88      }
89      x += w
90    }
91    if (row.id) surface.post({ press: row.id, ctrl: Boolean(e.ctrl), shift: Boolean(e.shift) })
92  })
93  surface.onKey(e => surface.post({ key: e.key, ctrl: Boolean(e.ctrl), shift: Boolean(e.shift) }))
94  const draw = (s: Seg, k: number) => {
95    if (s.claude) {
96      const shut = Math.floor(state.phase / 3) % 12 === 11
97      return (
98        <Text key={String(k)} color={shut ? '#7a4535' : '#d97757'} bold={!shut}>
99          {s.t}
100        </Text>
101      )
102    }
103    if (s.spin) {
104      const frame = FRAMES[state.phase % FRAMES.length] ?? ''
105      return (
106        <Text key={String(k)} bold={s.b}>
107          {s.t ? <Text color={s.c}>{s.t}</Text> : null}
108          <Text color={GRADIENT[state.phase % GRADIENT.length]} bold>
109            {frame}
110          </Text>
111        </Text>
112      )
113    }
114    const palette = s.sh ? (s.dim ? props.tones[s.sh]?.dim : props.tones[s.sh]?.bright) : undefined
115    if (!palette) {
116      return (
117        <Text key={String(k)} color={s.c} backgroundColor={s.bg} bold={s.b} strikethrough={s.s} italic={s.i}>
118          {s.t}
119        </Text>
120      )
121    }
122    if (s.one) {
123      return (
124        <Text key={String(k)} color={shimmer(-1, state.phase, s.t.length, palette)}>
125          {s.t}
126        </Text>
127      )
128    }
129    const chars = [...s.t]
130    return (
131      <Text key={String(k)} bold={s.b}>
132        {chars.map((ch, i) => (
133          <Text key={String(i)} color={shimmer(i, state.phase, chars.length, palette)}>{ch}</Text>
134        ))}
135      </Text>
136    )
137  }
138  return (
139    <Box flexDirection="column">
140      {props.rows.map((r, i) => (
141        <Box
142          key={r.id || `row-${i}`}
143          flexDirection="row"
144          height={1}
145          overflow="hidden"
146          backgroundColor={r.id && r.id === props.active ? props.activeBg : r.id && i === state.hover ? props.hoverBg : undefined}
147        >
148          <Box flexShrink={1} overflow="hidden">
149            {r.left.map(draw)}
150          </Box>
151          <Box flexGrow={1} />
152          {r.right.map(draw)}
153          {props.bar && (
154            <Text color={i >= props.bar.pos && i < props.bar.pos + props.bar.size ? props.bar.thumb : props.bar.track}>
155              {i >= props.bar.pos && i < props.bar.pos + props.bar.size ? '┃' : '│'}
156            </Text>
157          )}
158        </Box>
159      ))}
160    </Box>
161  )
162}
163
164export default Rows
165
hooks/svg-data.ts 2 lines
1export const FABRIC_SVG: Record<string, string> = {"AppBackend":"<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#hrpaint0_linear_67530_250)\"/><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#hrpaint1_radial_67530_250)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M19 3H5C3.89 3 3 3.89 3 5V19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.89 20.1 3 19 3ZM5 2C3.34 2 2 3.34 2 5V19C2 20.65 3.34 22 5 22H19C20.65 22 22 20.65 22 19V5C22 3.34 20.65 2 19 2H5Z\" fill=\"url(#hrpaint2_linear_67530_250)\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M16.5 11C17.32 11 18 11.67 18 12.5V16.5C18 17.32 17.32 18 16.5 18H12.5C11.67 18 11 17.32 11 16.5V15.5C11 14.67 11.67 14 12.5 14H14V12.5C14 11.67 14.67 11 15.5 11H16.5ZM12.5 15C12.22 15 12 15.22 12 15.5V16.5C12 16.77 12.22 17 12.5 17H14V15H12.5ZM15 17H16.5C16.77 17 17 16.77 17 16.5V15.5C17 15.22 16.77 15 16.5 15H15V17ZM15.5 12C15.22 12 15 12.22 15 12.5V14H16.5C16.67 14 16.84 14.03 17 14.08V12.5C17 12.22 16.77 12 16.5 12H15.5Z\" fill=\"url(#hrpaint3_linear_67530_250)\"/><path d=\"M14.5 7C15.88 7 17 8.11 17 9.5V10.04C16.83 10.01 16.67 10 16.5 10H8V14.5C8 15.32 8.67 16 9.5 16H10V16.5C10 16.67 10.01 16.83 10.04 17H9.5C8.11 17 7 15.88 7 14.5V9.5C7 8.11 8.11 7 9.5 7H14.5Z\" fill=\"url(#hrpaint4_linear_67530_250)\"/><defs><linearGradient id=\"hrpaint0_linear_67530_250\" x1=\"7.55\" y1=\"2\" x2=\"10.08\" y2=\"22.23\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"hrpaint1_radial_67530_250\" cx=\"0\" cy=\"0\" r=\"1\" gradientTransform=\"matrix(10.55 15.83 -15.83 5.93 8.38 7.2)\" gradientUnits=\"userSpaceOnUse\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"hrpaint2_linear_67530_250\" x1=\"8.45\" y1=\"2\" x2=\"11.15\" y2=\"22.19\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"hrpaint3_linear_67530_250\" x1=\"7\" y1=\"7\" x2=\"18\" y2=\"18\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#3477EA\"/><stop offset=\"1\" stop-color=\"#1D53A4\"/></linearGradient><linearGradient id=\"hrpaint4_linear_67530_250\" x1=\"7\" y1=\"7\" x2=\"18\" y2=\"18\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#3477EA\"/><stop offset=\"1\" stop-color=\"#1D53A4\"/></linearGradient></defs></svg>","SemanticModel":"<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#fhpaint0_linear_41743_62611)\"/><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#fhpaint1_radial_41743_62611)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M19 3H5C3.89 3 3 3.89 3 5V19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.89 20.1 3 19 3ZM5 2C3.34 2 2 3.34 2 5V19C2 20.65 3.34 22 5 22H19C20.65 22 22 20.65 22 19V5C22 3.34 20.65 2 19 2H5Z\" fill=\"url(#fhpaint2_linear_41743_62611)\"/><path d=\"M7.25 10.5C7.94 10.5 8.5 9.94 8.5 9.25C8.5 8.55 7.94 8 7.25 8C6.55 8 6 8.55 6 9.25C6 9.94 6.55 10.5 7.25 10.5Z\" fill=\"url(#fhpaint3_linear_41743_62611)\"/><path d=\"M12 10.5C12.69 10.5 13.25 9.94 13.25 9.25C13.25 8.55 12.69 8 12 8C11.3 8 10.75 8.55 10.75 9.25C10.75 9.94 11.3 10.5 12 10.5Z\" fill=\"url(#fhpaint4_linear_41743_62611)\"/><path d=\"M13.25 14.75C13.25 15.44 12.69 16 12 16C11.3 16 10.75 15.44 10.75 14.75C10.75 14.05 11.3 13.5 12 13.5C12.69 13.5 13.25 14.05 13.25 14.75Z\" fill=\"url(#fhpaint5_linear_41743_62611)\"/><path d=\"M7.25 16C7.94 16 8.5 15.44 8.5 14.75C8.5 14.05 7.94 13.5 7.25 13.5C6.55 13.5 6 14.05 6 14.75C6 15.44 6.55 16 7.25 16Z\" fill=\"url(#fhpaint6_linear_41743_62611)\"/><path d=\"M18 9.25C18 9.94 17.44 10.5 16.75 10.5C16.05 10.5 15.5 9.94 15.5 9.25C15.5 8.55 16.05 8 16.75 8C17.44 8 18 8.55 18 9.25Z\" fill=\"url(#fhpaint7_linear_41743_62611)\"/><defs><linearGradient id=\"fhpaint0_linear_41743_62611\" x1=\"7.55\" y1=\"2\" x2=\"10.08\" y2=\"22.23\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"fhpaint1_radial_41743_62611\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"translate(8.38 7.2) rotate(56.3) scale(19.02 16.46)\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"fhpaint2_linear_41743_62611\" x1=\"8.45\" y1=\"2\" x2=\"11.15\" y2=\"22.19\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"fhpaint3_linear_41743_62611\" x1=\"6\" y1=\"8\" x2=\"13.38\" y2=\"19.07\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7751B8\"/><stop offset=\"1\" stop-color=\"#5A409C\"/></linearGradient><linearGradient id=\"fhpaint4_linear_41743_62611\" x1=\"6\" y1=\"8\" x2=\"13.38\" y2=\"19.07\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7751B8\"/><stop offset=\"1\" stop-color=\"#5A409C\"/></linearGradient><linearGradient id=\"fhpaint5_linear_41743_62611\" x1=\"6\" y1=\"8\" x2=\"13.38\" y2=\"19.07\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7751B8\"/><stop offset=\"1\" stop-color=\"#5A409C\"/></linearGradient><linearGradient id=\"fhpaint6_linear_41743_62611\" x1=\"6\" y1=\"8\" x2=\"13.38\" y2=\"19.07\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7751B8\"/><stop offset=\"1\" stop-color=\"#5A409C\"/></linearGradient><linearGradient id=\"fhpaint7_linear_41743_62611\" x1=\"6\" y1=\"8\" x2=\"13.38\" y2=\"19.07\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#7751B8\"/><stop offset=\"1\" stop-color=\"#5A409C\"/></linearGradient></defs></svg>","Lakehouse":"<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M3 4C3 2.34 4.34 1 6 1H18C19.65 1 21 2.34 21 4V20C21 21.65 19.65 23 18 23H6C4.34 23 3 21.65 3 20V4Z\" fill=\"url(#lbpaint0_linear_41743_63346)\"/><path d=\"M3 4C3 2.34 4.34 1 6 1H18C19.65 1 21 2.34 21 4V20C21 21.65 19.65 23 18 23H6C4.34 23 3 21.65 3 20V4Z\" fill=\"url(#lbpaint1_radial_41743_63346)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M18 2H6C4.89 2 4 2.89 4 4V20C4 21.1 4.89 22 6 22H18C19.1 22 20 21.1 20 20V4C20 2.89 19.1 2 18 2ZM6 1C4.34 1 3 2.34 3 4V20C3 21.65 4.34 23 6 23H18C19.65 23 21 21.65 21 20V4C21 2.34 19.65 1 18 1H6Z\" fill=\"url(#lbpaint2_linear_41743_63346)\"/><path d=\"M10.99 17.69C10.92 17.78 10.87 17.89 10.83 18H8C6.89 18 6 17.1 6 16V11.79C6 11.22 6.24 10.68 6.66 10.3L10.66 6.7C11.42 6.01 12.57 6.01 13.33 6.7L17.33 10.3C17.75 10.68 18 11.22 18 11.79V14.04C17.97 14.03 17.96 14.03 17.96 14.03C17.95 14.02 17.95 14.01 17.94 14.01C17.93 13.98 17.91 13.95 17.89 13.89C17.82 13.7 17.71 13.53 17.56 13.37C17.42 13.23 17.25 13.12 17.07 13.04L16.98 13C16.83 12.95 16.67 12.92 16.5 12.92C16.34 12.92 16.19 12.94 16.04 12.99L15.92 13.04C15.55 13.19 15.26 13.48 15.11 13.85C15.1 13.87 15.06 13.92 15 13.98C14.94 13.93 14.89 13.87 14.89 13.85C14.66 13.28 14.11 12.92 13.5 12.92H13.36C12.79 12.97 12.31 13.34 12.1 13.87C12.06 13.95 12.04 14 12.04 14C12.03 14 12 14.01 11.95 14.03L11.92 14.04C11.12 14.22 10.61 15.02 10.79 15.83C10.92 16.45 11.43 16.9 12.05 16.98L12.05 16.99C12.04 16.99 12.01 17 11.96 17.02L11.93 17.03C11.54 17.12 11.2 17.35 10.99 17.69Z\" fill=\"url(#lbpaint3_linear_41743_63346)\"/><path d=\"M16.34 13.93C16.33 13.93 16.32 13.94 16.3 13.95C16.18 13.99 16.08 14.09 16.03 14.22C15.96 14.39 15.81 14.6 15.61 14.75C15.41 14.91 15.19 14.99 14.99 14.99C14.78 14.99 14.57 14.91 14.38 14.76C14.18 14.6 14.03 14.4 13.96 14.22C13.88 14.02 13.69 13.91 13.49 13.91C13.48 13.91 13.46 13.91 13.45 13.91C13.27 13.93 13.1 14.04 13.03 14.23C12.93 14.49 12.81 14.65 12.69 14.76C12.56 14.87 12.39 14.95 12.14 15.01C11.87 15.07 11.7 15.34 11.76 15.6C11.82 15.87 12.09 16.04 12.35 15.98C12.72 15.9 13.06 15.76 13.34 15.52C13.4 15.46 13.47 15.4 13.52 15.33C13.6 15.41 13.67 15.48 13.75 15.54C14.08 15.8 14.51 15.99 14.99 15.99C15.47 15.99 15.9 15.8 16.23 15.54C16.31 15.48 16.39 15.41 16.46 15.33C16.52 15.4 16.59 15.46 16.65 15.52C16.93 15.76 17.27 15.9 17.64 15.98C17.91 16.04 18.17 15.87 18.23 15.6C18.29 15.34 18.12 15.07 17.86 15.01C17.6 14.95 17.43 14.87 17.3 14.76C17.18 14.65 17.06 14.49 16.96 14.23C16.94 14.16 16.9 14.1 16.85 14.06C16.81 14.01 16.75 13.97 16.68 13.94L16.68 13.94C16.62 13.92 16.56 13.91 16.5 13.91C16.45 13.91 16.39 13.91 16.34 13.93Z\" fill=\"url(#lbpaint4_linear_41743_63346)\"/><path d=\"M13.34 18.52C13.4 18.46 13.47 18.4 13.52 18.33C13.6 18.41 13.67 18.48 13.75 18.54C14.08 18.8 14.51 18.99 14.99 18.99C15.47 18.99 15.9 18.8 16.23 18.54C16.31 18.48 16.39 18.41 16.46 18.33C16.52 18.4 16.59 18.46 16.65 18.52C16.93 18.76 17.27 18.9 17.64 18.98C17.91 19.04 18.17 18.87 18.23 18.6C18.29 18.34 18.12 18.07 17.86 18.01C17.6 17.95 17.43 17.87 17.3 17.76C17.18 17.65 17.06 17.49 16.96 17.23C16.94 17.16 16.9 17.1 16.85 17.06C16.81 17.01 16.75 16.97 16.68 16.94C16.62 16.92 16.56 16.91 16.5 16.91C16.45 16.91 16.39 16.91 16.34 16.93C16.27 16.95 16.2 16.99 16.15 17.05C16.1 17.09 16.06 17.15 16.03 17.22C15.96 17.39 15.81 17.6 15.61 17.75C15.41 17.91 15.19 17.99 14.99 17.99C14.78 17.99 14.57 17.91 14.38 17.76C14.18 17.6 14.03 17.4 13.96 17.22C13.88 17.03 13.7 16.91 13.5 16.91C13.48 16.91 13.46 16.91 13.44 16.91C13.26 16.93 13.1 17.05 13.03 17.23C12.93 17.49 12.81 17.65 12.69 17.76C12.56 17.87 12.39 17.95 12.14 18.01C11.87 18.07 11.7 18.34 11.76 18.6C11.82 18.87 12.09 19.04 12.35 18.98C12.72 18.9 13.06 18.76 13.34 18.52Z\" fill=\"url(#lbpaint5_linear_41743_63346)\"/><defs><linearGradient id=\"lbpaint0_linear_41743_63346\" x1=\"8\" y1=\"1\" x2=\"11.37\" y2=\"23.09\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"lbpaint1_radial_41743_63346\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"translate(8.75 6.72) rotate(61.38) scale(19.83 15.63)\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"lbpaint2_linear_41743_63346\" x1=\"8.81\" y1=\"1\" x2=\"12.4\" y2=\"23.02\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"lbpaint3_linear_41743_63346\" x1=\"6\" y1=\"6.19\" x2=\"18.79\" y2=\"18.42\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#3477EA\"/><stop offset=\"1\" stop-color=\"#1D53A4\"/></linearGradient><linearGradient id=\"lbpaint4_linear_41743_63346\" x1=\"6\" y1=\"6.19\" x2=\"18.79\" y2=\"18.42\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#3477EA\"/><stop offset=\"1\" stop-color=\"#1D53A4\"/></linearGradient><linearGradient id=\"lbpaint5_linear_41743_63346\" x1=\"6\" y1=\"6.19\" x2=\"18.79\" y2=\"18.42\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#3477EA\"/><stop offset=\"1\" stop-color=\"#1D53A4\"/></linearGradient></defs></svg>","Warehouse":"<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M3 4C3 2.34 4.34 1 6 1H18C19.65 1 21 2.34 21 4V20C21 21.65 19.65 23 18 23H6C4.34 23 3 21.65 3 20V4Z\" fill=\"url(#ebpaint0_linear_41743_62508)\"/><path d=\"M3 4C3 2.34 4.34 1 6 1H18C19.65 1 21 2.34 21 4V20C21 21.65 19.65 23 18 23H6C4.34 23 3 21.65 3 20V4Z\" fill=\"url(#ebpaint1_radial_41743_62508)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M18 2H6C4.89 2 4 2.89 4 4V20C4 21.1 4.89 22 6 22H18C19.1 22 20 21.1 20 20V4C20 2.89 19.1 2 18 2ZM6 1C4.34 1 3 2.34 3 4V20C3 21.65 4.34 23 6 23H18C19.65 23 21 21.65 21 20V4C21 2.34 19.65 1 18 1H6Z\" fill=\"url(#ebpaint2_linear_41743_62508)\"/><path d=\"M11.49 18H16C17.1 18 18 17.1 18 16V11.79C18 11.22 17.75 10.68 17.33 10.3L13.33 6.7C12.57 6.01 11.42 6.01 10.66 6.7L6.66 10.3C6.24 10.68 6 11.22 6 11.79V16C6 17.1 6.89 18 8 18H12.5\" fill=\"url(#ebpaint3_linear_41743_62508)\"/><path d=\"M9 12.75C9.41 12.75 9.75 12.41 9.75 12C9.75 11.58 9.41 11.25 9 11.25C8.58 11.25 8.25 11.58 8.25 12C8.25 12.41 8.58 12.75 9 12.75Z\" fill=\"#B4CDF8\"/><path d=\"M12.75 12C12.75 12.41 12.41 12.75 12 12.75C11.58 12.75 11.25 12.41 11.25 12C11.25 11.58 11.58 11.25 12 11.25C12.41 11.25 12.75 11.58 12.75 12Z\" fill=\"#B4CDF8\"/><path d=\"M15.75 12C15.75 12.41 15.41 12.75 15 12.75C14.58 12.75 14.25 12.41 14.25 12C14.25 11.58 14.58 11.25 15 11.25C15.41 11.25 15.75 11.58 15.75 12Z\" fill=\"#B4CDF8\"/><path d=\"M12.75 15C12.75 15.41 12.41 15.75 12 15.75C11.58 15.75 11.25 15.41 11.25 15C11.25 14.58 11.58 14.25 12 14.25C12.41 14.25 12.75 14.58 12.75 15Z\" fill=\"#B4CDF8\"/><path d=\"M15 15.75C15.41 15.75 15.75 15.41 15.75 15C15.75 14.58 15.41 14.25 15 14.25C14.58 14.25 14.25 14.58 14.25 15C14.25 15.41 14.58 15.75 15 15.75Z\" fill=\"#B4CDF8\"/><path d=\"M9.75 15C9.75 15.41 9.41 15.75 9 15.75C8.58 15.75 8.25 15.41 8.25 15C8.25 14.58 8.58 14.25 9 14.25C9.41 14.25 9.75 14.58 9.75 15Z\" fill=\"#B4CDF8\"/><defs><linearGradient id=\"ebpaint0_linear_41743_62508\" x1=\"8\" y1=\"1\" x2=\"11.37\" y2=\"23.09\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"ebpaint1_radial_41743_62508\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"translate(8.75 6.72) rotate(61.38) scale(19.83 15.63)\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"ebpaint2_linear_41743_62508\" x1=\"8.81\" y1=\"1\" x2=\"12.4\" y2=\"23.02\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"ebpaint3_linear_41743_62508\" x1=\"6\" y1=\"5.5\" x2=\"18.48\" y2=\"17.49\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#3477EA\"/><stop offset=\"1\" stop-color=\"#1D53A4\"/></linearGradient></defs></svg>","SQLEndpoint":"<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M3 4C3 2.34 4.34 1 6 1H18C19.65 1 21 2.34 21 4V20C21 21.65 19.65 23 18 23H6C4.34 23 3 21.65 3 20V4Z\" fill=\"url(#ebpaint0_linear_41743_62508)\"/><path d=\"M3 4C3 2.34 4.34 1 6 1H18C19.65 1 21 2.34 21 4V20C21 21.65 19.65 23 18 23H6C4.34 23 3 21.65 3 20V4Z\" fill=\"url(#ebpaint1_radial_41743_62508)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M18 2H6C4.89 2 4 2.89 4 4V20C4 21.1 4.89 22 6 22H18C19.1 22 20 21.1 20 20V4C20 2.89 19.1 2 18 2ZM6 1C4.34 1 3 2.34 3 4V20C3 21.65 4.34 23 6 23H18C19.65 23 21 21.65 21 20V4C21 2.34 19.65 1 18 1H6Z\" fill=\"url(#ebpaint2_linear_41743_62508)\"/><path d=\"M11.49 18H16C17.1 18 18 17.1 18 16V11.79C18 11.22 17.75 10.68 17.33 10.3L13.33 6.7C12.57 6.01 11.42 6.01 10.66 6.7L6.66 10.3C6.24 10.68 6 11.22 6 11.79V16C6 17.1 6.89 18 8 18H12.5\" fill=\"url(#ebpaint3_linear_41743_62508)\"/><path d=\"M9 12.75C9.41 12.75 9.75 12.41 9.75 12C9.75 11.58 9.41 11.25 9 11.25C8.58 11.25 8.25 11.58 8.25 12C8.25 12.41 8.58 12.75 9 12.75Z\" fill=\"#B4CDF8\"/><path d=\"M12.75 12C12.75 12.41 12.41 12.75 12 12.75C11.58 12.75 11.25 12.41 11.25 12C11.25 11.58 11.58 11.25 12 11.25C12.41 11.25 12.75 11.58 12.75 12Z\" fill=\"#B4CDF8\"/><path d=\"M15.75 12C15.75 12.41 15.41 12.75 15 12.75C14.58 12.75 14.25 12.41 14.25 12C14.25 11.58 14.58 11.25 15 11.25C15.41 11.25 15.75 11.58 15.75 12Z\" fill=\"#B4CDF8\"/><path d=\"M12.75 15C12.75 15.41 12.41 15.75 12 15.75C11.58 15.75 11.25 15.41 11.25 15C11.25 14.58 11.58 14.25 12 14.25C12.41 14.25 12.75 14.58 12.75 15Z\" fill=\"#B4CDF8\"/><path d=\"M15 15.75C15.41 15.75 15.75 15.41 15.75 15C15.75 14.58 15.41 14.25 15 14.25C14.58 14.25 14.25 14.58 14.25 15C14.25 15.41 14.58 15.75 15 15.75Z\" fill=\"#B4CDF8\"/><path d=\"M9.75 15C9.75 15.41 9.41 15.75 9 15.75C8.58 15.75 8.25 15.41 8.25 15C8.25 14.58 8.58 14.25 9 14.25C9.41 14.25 9.75 14.58 9.75 15Z\" fill=\"#B4CDF8\"/><defs><linearGradient id=\"ebpaint0_linear_41743_62508\" x1=\"8\" y1=\"1\" x2=\"11.37\" y2=\"23.09\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"ebpaint1_radial_41743_62508\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"translate(8.75 6.72) rotate(61.38) scale(19.83 15.63)\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"ebpaint2_linear_41743_62508\" x1=\"8.81\" y1=\"1\" x2=\"12.4\" y2=\"23.02\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"ebpaint3_linear_41743_62508\" x1=\"6\" y1=\"5.5\" x2=\"18.48\" y2=\"17.49\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#3477EA\"/><stop offset=\"1\" stop-color=\"#1D53A4\"/></linearGradient></defs></svg>","SQLDatabase":"<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><g clip-path=\"url(#thclip0_41743_62893)\"><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#thpaint0_linear_41743_62893)\"/><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#thpaint1_radial_41743_62893)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M19 3H5C3.89 3 3 3.89 3 5V19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.89 20.1 3 19 3ZM5 2C3.34 2 2 3.34 2 5V19C2 20.65 3.34 22 5 22H19C20.65 22 22 20.65 22 19V5C22 3.34 20.65 2 19 2H5Z\" fill=\"url(#thpaint2_linear_41743_62893)\"/><path d=\"M12 11C13.19 11 14.31 10.82 15.17 10.49C15.46 10.39 15.74 10.26 15.99 10.1L15.99 15.75C15.99 16.52 15.38 17.09 14.7 17.43C13.98 17.79 13.03 18 12 18C10.97 18 10.02 17.79 9.31 17.43C8.62 17.09 8.01 16.52 8.01 15.75L8 10.09C8.25 10.25 8.53 10.38 8.82 10.49C9.68 10.82 10.8 11 12 11Z\" fill=\"url(#thpaint3_linear_41743_62893)\"/><path d=\"M8 8.6C8.15 9.38 9.88 10 12 10C14.15 10 15.91 9.35 15.99 8.55C15.99 8.53 16 8.51 16 8.5C16 7.67 14.21 7 12 7C9.79 7 8.01 7.67 8.01 8.5C8.01 8.53 8.01 8.57 8.02 8.61L8 8.6Z\" fill=\"url(#thpaint4_linear_41743_62893)\"/><path d=\"M22.49 21H21.99V18.5C21.99 17.67 21.32 17 20.49 17C19.88 17 19.36 17.36 19.12 17.89C18.55 17.32 17.8 17.01 17 17.01C16.27 17.01 15.58 17.27 15.03 17.75C14.99 17.72 14.96 17.68 14.92 17.65C14.36 17.22 13.68 16.99 12.99 16.99C12.92 16.99 12.85 16.99 12.78 16.99C12.75 16.99 12.71 16.99 12.68 16.99C12.42 17 12.17 17.03 11.93 17.1C11.59 17.2 11.29 17.37 11.02 17.59C10.75 17.81 10.53 18.09 10.37 18.4C10.21 18.71 10.12 19.05 10.09 19.4V19.5C10.09 20.05 10.28 20.56 10.64 20.97C10.56 21.03 10.49 21.1 10.43 21.18C9.91 21.82 10 22.77 10.64 23.29C11.2 23.75 11.92 24 12.65 24C12.73 24 12.81 24 12.82 24C13.44 24 13.98 23.84 14.43 23.54C14.6 23.42 14.76 23.29 14.89 23.13C15.46 23.69 16.2 24 17 24C17.41 24 17.81 23.92 18.18 23.76C18.42 23.92 18.7 24 19 24C19.26 24 19.52 23.93 19.75 23.8C19.97 23.93 20.23 24 20.5 24H22.5C23.33 24 24 23.33 24 22.5C24 21.67 23.33 21 22.5 21H22.49Z\" fill=\"#F5F5F5\"/><path d=\"M14.3 18.43C13.87 18.1 13.33 17.94 12.79 17.99C12.6 17.98 12.4 18 12.22 18.05C12.01 18.12 11.82 18.22 11.66 18.35C11.5 18.49 11.36 18.66 11.27 18.85C11.17 19.04 11.11 19.25 11.1 19.46L11.09 19.48V19.5C11.09 20.07 11.46 20.43 11.79 20.63C12.09 20.82 12.44 20.92 12.64 20.97L12.66 20.98L12.72 20.99C12.92 21.05 13.11 21.1 13.26 21.2C13.4 21.28 13.45 21.36 13.45 21.5C13.45 21.75 13.37 21.84 13.3 21.88C13.2 21.95 13.03 22 12.79 22H12.77L12.75 22C12.45 22.02 12.15 21.93 11.91 21.74C11.7 21.56 11.38 21.59 11.21 21.81C11.03 22.02 11.06 22.34 11.28 22.51C11.71 22.86 12.26 23.04 12.82 23C13.14 22.99 13.53 22.93 13.86 22.71C14.24 22.45 14.45 22.04 14.45 21.5C14.45 20.91 14.12 20.55 13.78 20.34C13.5 20.17 13.18 20.08 12.99 20.03L12.93 20.01C12.72 19.96 12.49 19.89 12.31 19.78C12.14 19.68 12.1 19.59 12.1 19.51C12.1 19.44 12.12 19.37 12.16 19.31C12.19 19.24 12.24 19.17 12.3 19.12C12.36 19.07 12.43 19.04 12.51 19.01C12.58 18.99 12.66 18.98 12.74 18.99L12.8 19L12.85 18.99C13.15 18.96 13.45 19.04 13.69 19.22C13.91 19.39 14.22 19.35 14.39 19.13C14.56 18.91 14.52 18.6 14.3 18.43Z\" fill=\"url(#thpaint5_linear_41743_62893)\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M17 18C16.46 18 15.96 18.21 15.58 18.58C15.21 18.96 15 19.46 15 20V21C15 21.53 15.21 22.03 15.58 22.41C15.96 22.78 16.46 23 17 23C17.45 23 17.89 22.84 18.24 22.56L18.7 22.9C18.92 23.06 19.23 23.02 19.4 22.8C19.56 22.57 19.52 22.26 19.3 22.1L18.84 21.76C18.94 21.52 19 21.26 19 21V20C19 19.46 18.78 18.96 18.41 18.58C18.03 18.21 17.53 18 17 18ZM17.3 20.6L17.99 21.11C17.99 21.08 18 21.04 18 21V20C18 19.73 17.89 19.48 17.7 19.29C17.51 19.1 17.26 19 17 19C16.73 19 16.48 19.1 16.29 19.29C16.1 19.48 16 19.73 16 20V21C16 21.26 16.1 21.51 16.29 21.7C16.48 21.89 16.73 22 17 22C17.13 22 17.26 21.97 17.39 21.91L16.7 21.4C16.47 21.23 16.43 20.92 16.6 20.7C16.76 20.47 17.07 20.43 17.3 20.6Z\" fill=\"url(#thpaint6_linear_41743_62893)\"/><path d=\"M20.99 18.5C20.99 18.22 20.77 18 20.49 18C20.22 18 19.99 18.22 19.99 18.5V22.5C19.99 22.77 20.22 23 20.49 23H22.49C22.77 23 22.99 22.77 22.99 22.5C22.99 22.22 22.77 22 22.49 22H20.99V18.5Z\" fill=\"url(#thpaint7_linear_41743_62893)\"/></g><defs><linearGradient id=\"thpaint0_linear_41743_62893\" x1=\"7.55\" y1=\"2\" x2=\"10.08\" y2=\"22.23\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"thpaint1_radial_41743_62893\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"translate(8.38 7.2) rotate(56.3) scale(19.02 16.46)\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"thpaint2_linear_41743_62893\" x1=\"8.45\" y1=\"2\" x2=\"11.15\" y2=\"22.19\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"thpaint3_linear_41743_62893\" x1=\"8\" y1=\"7\" x2=\"18.46\" y2=\"14.6\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><linearGradient id=\"thpaint4_linear_41743_62893\" x1=\"8\" y1=\"7\" x2=\"18.46\" y2=\"14.6\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><linearGradient id=\"thpaint5_linear_41743_62893\" x1=\"11.09\" y1=\"17.98\" x2=\"14.69\" y2=\"26.5\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><linearGradient id=\"thpaint6_linear_41743_62893\" x1=\"11.09\" y1=\"17.98\" x2=\"14.69\" y2=\"26.5\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><linearGradient id=\"thpaint7_linear_41743_62893\" x1=\"11.09\" y1=\"17.98\" x2=\"14.69\" y2=\"26.5\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><clipPath id=\"thclip0_41743_62893\"><rect width=\"24\" height=\"24\" fill=\"white\"/></clipPath></defs></svg>","KQLDatabase":"<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><g clip-path=\"url(#krclip0_41743_62807)\"><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#krpaint0_linear_41743_62807)\"/><path d=\"M2 5C2 3.34 3.34 2 5 2H19C20.65 2 22 3.34 22 5V19C22 20.65 20.65 22 19 22H5C3.34 22 2 20.65 2 19V5Z\" fill=\"url(#krpaint1_radial_41743_62807)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M19 3H5C3.89 3 3 3.89 3 5V19C3 20.1 3.89 21 5 21H19C20.1 21 21 20.1 21 19V5C21 3.89 20.1 3 19 3ZM5 2C3.34 2 2 3.34 2 5V19C2 20.65 3.34 22 5 22H19C20.65 22 22 20.65 22 19V5C22 3.34 20.65 2 19 2H5Z\" fill=\"url(#krpaint2_linear_41743_62807)\"/><path d=\"M12 11C13.19 11 14.31 10.82 15.17 10.49C15.46 10.39 15.74 10.26 15.99 10.1L15.99 15.75C15.99 16.52 15.38 17.09 14.7 17.43C13.98 17.79 13.03 18 12 18C10.97 18 10.02 17.79 9.31 17.43C8.62 17.09 8.01 16.52 8.01 15.75L8 10.09C8.25 10.25 8.53 10.38 8.82 10.49C9.68 10.82 10.8 11 12 11Z\" fill=\"url(#krpaint3_linear_41743_62807)\"/><path d=\"M8 8.6C8.15 9.38 9.88 10 12 10C14.15 10 15.91 9.35 15.99 8.55C15.99 8.53 16 8.51 16 8.5C16 7.67 14.21 7 12 7C9.79 7 8.01 7.67 8.01 8.5C8.01 8.53 8.01 8.57 8.02 8.61L8 8.6Z\" fill=\"url(#krpaint4_linear_41743_62807)\"/><path d=\"M23.56 15.44C23.28 15.16 22.9 15 22.5 15H17.5C17.31 15 17.12 15.04 16.95 15.11L16.81 15.18L16.68 15.26C16.53 15.36 16.4 15.49 16.24 15.72L16.2 15.79L16.12 15.93C16.09 16 16.07 16.06 16.05 16.13L16.02 16.25V16.31C15.99 16.47 16 16.63 16.02 16.8C16.08 17.09 16.22 17.36 16.43 17.56L16.53 17.66C16.38 17.73 16.25 17.82 16.13 17.94L15.42 18.65C15.14 18.93 14.98 19.31 14.98 19.71C14.98 20.11 15.14 20.49 15.42 20.77C15.54 20.89 15.69 20.99 15.84 21.06L15.42 21.48C15.14 21.76 14.98 22.14 14.98 22.54C14.98 22.94 15.14 23.32 15.42 23.6C15.7 23.88 16.08 24.04 16.48 24.04C16.88 24.04 17.26 23.88 17.54 23.6L17.96 23.18C18.03 23.33 18.13 23.48 18.25 23.6C18.53 23.88 18.91 24.04 19.31 24.04C19.71 24.04 20.09 23.88 20.37 23.6L21.08 22.89C21.2 22.77 21.28 22.63 21.35 22.48L21.43 22.56C21.64 22.77 21.91 22.92 22.19 22.97L22.39 23H22.49C22.69 23 22.88 22.96 23.08 22.88C23.19 22.83 23.28 22.78 23.33 22.74L23.46 22.64L23.52 22.58L23.67 22.41L23.72 22.33C23.89 22.08 23.98 21.79 23.98 21.49V16.5C23.98 16.1 23.82 15.72 23.54 15.44H23.56Z\" fill=\"#F5F5F5\"/><path d=\"M17.5 16H22.5C22.63 16 22.76 16.05 22.85 16.14C22.95 16.24 23 16.36 23 16.5V21.5C23 21.59 22.97 21.69 22.92 21.77L22.9 21.8C22.89 21.81 22.87 21.83 22.86 21.84C22.85 21.85 22.84 21.86 22.84 21.86C22.82 21.88 22.8 21.89 22.79 21.9C22.76 21.93 22.72 21.94 22.69 21.96C22.6 21.99 22.5 22 22.4 21.99C22.31 21.97 22.22 21.92 22.15 21.85L17.15 16.85C17.08 16.78 17.03 16.69 17.01 16.59C17 16.54 17 16.48 17 16.43C17.01 16.41 17.01 16.39 17.02 16.37C17.02 16.35 17.03 16.33 17.04 16.3C17.04 16.29 17.05 16.28 17.05 16.27C17.06 16.26 17.06 16.25 17.07 16.24L17.08 16.23L17.09 16.2C17.13 16.15 17.17 16.11 17.22 16.08C17.23 16.07 17.24 16.07 17.25 16.06C17.26 16.05 17.27 16.05 17.28 16.04C17.29 16.04 17.3 16.04 17.31 16.03C17.37 16.01 17.44 16 17.5 16Z\" fill=\"url(#krpaint5_linear_41743_62807)\"/><path d=\"M17.56 18.65C17.75 18.84 17.75 19.16 17.56 19.36L16.85 20.06C16.65 20.26 16.34 20.26 16.14 20.06C15.95 19.87 15.95 19.55 16.14 19.36L16.85 18.65C17.04 18.45 17.36 18.45 17.56 18.65Z\" fill=\"url(#krpaint6_linear_41743_62807)\"/><path d=\"M20.38 21.48C20.58 21.67 20.58 21.99 20.38 22.18L19.68 22.89C19.48 23.09 19.17 23.09 18.97 22.89C18.77 22.7 18.77 22.38 18.97 22.18L19.68 21.48C19.87 21.28 20.19 21.28 20.38 21.48Z\" fill=\"url(#krpaint7_linear_41743_62807)\"/><path d=\"M18.97 20.06C19.17 20.26 19.17 20.57 18.97 20.77L16.85 22.89C16.65 23.09 16.34 23.09 16.14 22.89C15.95 22.7 15.95 22.38 16.14 22.18L18.26 20.06C18.46 19.87 18.77 19.87 18.97 20.06Z\" fill=\"url(#krpaint8_linear_41743_62807)\"/></g><defs><linearGradient id=\"krpaint0_linear_41743_62807\" x1=\"7.55\" y1=\"2\" x2=\"10.08\" y2=\"22.23\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"krpaint1_radial_41743_62807\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"translate(8.38 7.2) rotate(56.3) scale(19.02 16.46)\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"krpaint2_linear_41743_62807\" x1=\"8.45\" y1=\"2\" x2=\"11.15\" y2=\"22.19\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"krpaint3_linear_41743_62807\" x1=\"8\" y1=\"7\" x2=\"18.46\" y2=\"14.6\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><linearGradient id=\"krpaint4_linear_41743_62807\" x1=\"8\" y1=\"7\" x2=\"18.46\" y2=\"14.6\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><linearGradient id=\"krpaint5_linear_41743_62807\" x1=\"16\" y1=\"16\" x2=\"23.04\" y2=\"23\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><linearGradient id=\"krpaint6_linear_41743_62807\" x1=\"16\" y1=\"16\" x2=\"23.04\" y2=\"23\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><linearGradient id=\"krpaint7_linear_41743_62807\" x1=\"16\" y1=\"16\" x2=\"23.04\" y2=\"23\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><linearGradient id=\"krpaint8_linear_41743_62807\" x1=\"16\" y1=\"16\" x2=\"23.04\" y2=\"23\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#008EE6\"/><stop offset=\"1\" stop-color=\"#006094\"/></linearGradient><clipPath id=\"krclip0_41743_62807\"><rect width=\"24\" height=\"24\" fill=\"white\"/></clipPath></defs></svg>","UserDataFunction":"<svg width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M4 6C4 4.34 5.34 3 7 3H19C20.65 3 22 4.34 22 6V17.5C22 20.53 19.53 23 16.5 23H7C5.34 23 4 21.65 4 20V6Z\" fill=\"url(#ihpaint0_linear_42209_28444)\"/><path d=\"M4 6C4 4.34 5.34 3 7 3H19C20.65 3 22 4.34 22 6V17.5C22 20.53 19.53 23 16.5 23H7C5.34 23 4 21.65 4 20V6Z\" fill=\"url(#ihpaint1_radial_42209_28444)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M19 4H7C5.89 4 5 4.89 5 6V20C5 21.1 5.89 22 7 22H16.5C18.98 22 21 19.98 21 17.5V6C21 4.89 20.1 4 19 4ZM7 3C5.34 3 4 4.34 4 6V20C4 21.65 5.34 23 7 23H16.5C19.53 23 22 20.53 22 17.5V6C22 4.34 20.65 3 19 3H7Z\" fill=\"url(#ihpaint2_linear_42209_28444)\"/><path d=\"M2 4C2 2.34 3.34 1 5 1H17C18.65 1 20 2.34 20 4V18C20 19.65 18.65 21 17 21H5C3.34 21 2 19.65 2 18V4Z\" fill=\"url(#ihpaint3_linear_42209_28444)\"/><path d=\"M2 4C2 2.34 3.34 1 5 1H17C18.65 1 20 2.34 20 4V18C20 19.65 18.65 21 17 21H5C3.34 21 2 19.65 2 18V4Z\" fill=\"url(#ihpaint4_radial_42209_28444)\" fill-opacity=\"0.2\"/><path fill-rule=\"evenodd\" clip-rule=\"evenodd\" d=\"M17 2H5C3.89 2 3 2.89 3 4V18C3 19.1 3.89 20 5 20H17C18.1 20 19 19.1 19 18V4C19 2.89 18.1 2 17 2ZM5 1C3.34 1 2 2.34 2 4V18C2 19.65 3.34 21 5 21H17C18.65 21 20 19.65 20 18V4C20 2.34 18.65 1 17 1H5Z\" fill=\"url(#ihpaint5_linear_42209_28444)\"/><path d=\"M11.25 5.02C11.13 4.99 10.96 4.99 10.72 5.02C10.34 5.08 10.07 5.26 9.89 5.53C9.7 5.8 9.57 6.18 9.54 6.64C9.53 6.79 9.51 7.3 9.47 7.97H11.5C11.77 7.97 12 8.2 12 8.47C12 8.75 11.77 8.97 11.5 8.97H9.42C9.32 10.77 9.18 13.02 9.13 13.64L9.13 13.65L9.13 13.71C9.09 14.16 9.04 14.72 8.88 15.23C8.7 15.79 8.38 16.32 7.77 16.68C6.9 17.22 5.97 16.97 5.27 16.62C5.02 16.5 4.92 16.2 5.05 15.95C5.17 15.71 5.47 15.61 5.72 15.73C6.31 16.02 6.82 16.09 7.24 15.83L7.26 15.82C7.6 15.62 7.8 15.32 7.93 14.93C8.06 14.53 8.09 14.07 8.14 13.58L8.14 13.57L8.14 13.57C8.18 12.94 8.32 10.74 8.42 8.97H6.5C6.22 8.97 6 8.75 6 8.47C6 8.2 6.22 7.97 6.5 7.97H8.47C8.51 7.25 8.54 6.72 8.54 6.61C8.54 6.6 8.54 6.59 8.54 6.58C8.58 5.99 8.74 5.42 9.07 4.95C9.41 4.47 9.91 4.13 10.57 4.03L10.58 4.03C10.89 3.98 11.18 3.98 11.45 4.03C11.72 4.09 11.96 4.2 12.19 4.34C12.43 4.48 12.51 4.79 12.36 5.02C12.22 5.26 11.92 5.34 11.68 5.2C11.51 5.09 11.38 5.04 11.25 5.02Z\" fill=\"url(#ihpaint6_linear_42209_28444)\"/><path d=\"M16.85 10.14C17.04 10.34 17.04 10.65 16.85 10.85L14.62 13.08C14.98 13.72 15.31 14.29 15.4 14.43C15.46 14.52 15.51 14.61 15.55 14.68L15.58 14.73C15.62 14.81 15.65 14.86 15.68 14.89C15.71 14.93 15.73 14.96 15.79 14.99C15.84 15 15.87 15 15.88 14.99C15.89 14.99 15.89 14.99 15.9 14.99C15.9 14.99 15.92 14.97 15.96 14.93C15.98 14.9 16 14.87 16.03 14.83C16.05 14.81 16.07 14.78 16.1 14.74C16.27 14.52 16.58 14.48 16.8 14.65C17.02 14.82 17.06 15.13 16.89 15.35C16.88 15.36 16.87 15.38 16.86 15.4C16.78 15.51 16.64 15.7 16.46 15.82C16.19 16 15.88 16.03 15.52 15.96C15.48 15.95 15.44 15.94 15.41 15.92C15.17 15.8 15.01 15.67 14.87 15.48C14.81 15.4 14.76 15.31 14.71 15.23L14.68 15.18C14.64 15.11 14.6 15.04 14.55 14.96C14.46 14.82 14.19 14.35 13.88 13.81L11.85 15.85C11.65 16.04 11.34 16.04 11.14 15.85C10.95 15.65 10.95 15.34 11.14 15.14L13.37 12.91C13 12.28 12.68 11.71 12.59 11.57C12.58 11.56 12.58 11.55 12.57 11.54C12.51 11.41 12.43 11.28 12.35 11.17C12.28 11.08 12.22 11.02 12.17 11L12.16 11C12.16 11 12.15 11 12.14 11.01C12.07 11.05 11.99 11.13 11.89 11.26C11.72 11.48 11.41 11.52 11.19 11.35C10.97 11.18 10.93 10.87 11.1 10.65C11.22 10.5 11.39 10.3 11.62 10.16C11.86 10.01 12.19 9.93 12.55 10.07C12.56 10.07 12.57 10.08 12.58 10.08C12.83 10.2 13.01 10.39 13.14 10.56C13.27 10.73 13.37 10.91 13.45 11.06C13.55 11.22 13.8 11.67 14.1 12.18L16.14 10.14C16.34 9.95 16.65 9.95 16.85 10.14Z\" fill=\"url(#ihpaint7_linear_42209_28444)\"/><defs><linearGradient id=\"ihpaint0_linear_42209_28444\" x1=\"9\" y1=\"3\" x2=\"11.8\" y2=\"23.16\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"ihpaint1_radial_42209_28444\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"translate(9.75 8.2) rotate(59.03) scale(18.46 15.27)\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"ihpaint2_linear_42209_28444\" x1=\"9.81\" y1=\"3\" x2=\"12.79\" y2=\"23.11\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"ihpaint3_linear_42209_28444\" x1=\"7\" y1=\"1\" x2=\"9.8\" y2=\"21.16\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#EBEBEB\"/></linearGradient><radialGradient id=\"ihpaint4_radial_42209_28444\" cx=\"0\" cy=\"0\" r=\"1\" gradientUnits=\"userSpaceOnUse\" gradientTransform=\"translate(7.75 6.2) rotate(59.03) scale(18.46 15.27)\"><stop offset=\"0.17\" stop-color=\"white\"/><stop offset=\"1\" stop-color=\"#B8B8B8\"/></radialGradient><linearGradient id=\"ihpaint5_linear_42209_28444\" x1=\"7.81\" y1=\"1\" x2=\"10.79\" y2=\"21.11\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#BBBBBB\"/><stop offset=\"1\" stop-color=\"#888888\"/></linearGradient><linearGradient id=\"ihpaint6_linear_42209_28444\" x1=\"5\" y1=\"3.99\" x2=\"17.95\" y2=\"15.96\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#4BA446\"/><stop offset=\"1\" stop-color=\"#3F7D35\"/></linearGradient><linearGradient id=\"ihpaint7_linear_42209_28444\" x1=\"5\" y1=\"3.99\" x2=\"17.95\" y2=\"15.96\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#4BA446\"/><stop offset=\"1\" stop-color=\"#3F7D35\"/></linearGradient></defs></svg>","ui:open":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" width=\"20\" height=\"20\" fill=\"#c5c5d0\"><path d=\"M6 4a2 2 0 0 0-2 2v8c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2v-2.5a.5.5 0 0 1 1 0V14a3 3 0 0 1-3 3H6a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3h2.5a.5.5 0 0 1 0 1H6Zm5-.5c0-.28.22-.5.5-.5h5c.28 0 .5.22.5.5v5a.5.5 0 0 1-1 0V4.7l-4.15 4.15a.5.5 0 0 1-.7-.7L15.29 4H11.5a.5.5 0 0 1-.5-.5Z\"/></svg>","ui:copy":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" width=\"20\" height=\"20\" fill=\"#c5c5d0\"><path d=\"M8 2a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h6a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8ZM7 4a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1V4ZM4 6a2 2 0 0 1 1-1.73V14.5A2.5 2.5 0 0 0 7.5 17h6.23A2 2 0 0 1 12 18H7.5A3.5 3.5 0 0 1 4 14.5V6Z\"/></svg>","ui:chevron-right":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" width=\"16\" height=\"16\" fill=\"#8b8b96\"><path d=\"M7.65 4.15c.2-.2.5-.2.7 0l5.49 5.46c.21.22.21.57 0 .78l-5.49 5.46a.5.5 0 0 1-.7-.7L12.8 10 7.65 4.85a.5.5 0 0 1 0-.7Z\"/></svg>","ui:chevron-down":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" width=\"16\" height=\"16\" fill=\"#8b8b96\"><path d=\"M15.85 7.65c.2.2.2.5 0 .7l-5.46 5.49a.55.55 0 0 1-.78 0L4.15 8.35a.5.5 0 1 1 .7-.7L10 12.8l5.15-5.16c.2-.2.5-.2.7 0Z\"/></svg>","tenant settings":"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 20 20\" width=\"20\" height=\"20\" fill=\"#c5c5d0\"><path d=\"M1.91 7.38A8.5 8.5 0 0 1 3.7 4.3a.5.5 0 0 1 .54-.13l1.92.68a1 1 0 0 0 1.32-.76l.36-2a.5.5 0 0 1 .4-.4 8.53 8.53 0 0 1 3.55 0c.2.04.35.2.38.4l.37 2a1 1 0 0 0 1.32.76l1.92-.68a.5.5 0 0 1 .54.13 8.5 8.5 0 0 1 1.78 3.08c.06.2 0 .4-.15.54l-1.56 1.32a1 1 0 0 0 0 1.52l1.56 1.32a.5.5 0 0 1 .15.54 8.5 8.5 0 0 1-1.78 3.08.5.5 0 0 1-.54.13l-1.92-.68a1 1 0 0 0-1.32.76l-.37 2a.5.5 0 0 1-.38.4 8.53 8.53 0 0 1-3.56 0 .5.5 0 0 1-.39-.4l-.36-2a1 1 0 0 0-1.32-.76l-1.92.68a.5.5 0 0 1-.54-.13 8.5 8.5 0 0 1-1.78-3.08.5.5 0 0 1 .15-.54l1.56-1.32a1 1 0 0 0 0-1.52L2.06 7.92a.5.5 0 0 1-.15-.54Zm1.06 0 1.3 1.1a2 2 0 0 1 0 3.04l-1.3 1.1c.3.79.72 1.51 1.25 2.16l1.6-.58a2 2 0 0 1 2.63 1.53l.3 1.67a7.56 7.56 0 0 0 2.5 0l.3-1.67a2 2 0 0 1 2.64-1.53l1.6.58a7.5 7.5 0 0 0 1.24-2.16l-1.3-1.1a2 2 0 0 1 0-3.04l1.3-1.1a7.5 7.5 0 0 0-1.25-2.16l-1.6.58a2 2 0 0 1-2.63-1.53l-.3-1.67a7.55 7.55 0 0 0-2.5 0l-.3 1.67A2 2 0 0 1 5.81 5.8l-1.6-.58a7.5 7.5 0 0 0-1.24 2.16ZM7.5 10a2.5 2.5 0 1 1 5 0 2.5 2.5 0 0 1-5 0Zm1 0a1.5 1.5 0 1 0 3 0 1.5 1.5 0 0 0-3 0Z\"/></svg>"}
2
hooks/zone.tsx 22 lines
1import type { ClientModule } from 'claude-code'
2
3export type ZoneProps = { id: string }
4type Local = { ref: { unpoint?: () => void; id: string } }
5
6const Zone: ClientModule<ZoneProps, Local> = (props, surface) => {
7  const { Box } = surface.elements
8  let state = surface.state
9  if (state === undefined) {
10    state = { ref: { id: props.id } }
11    surface.setState(state)
12  }
13  const ref = state.ref
14  ref.id = props.id
15  ref.unpoint ??= surface.onPointer(e => {
16    if (e.type === 'up' && (e.button ?? 'left') === 'left') surface.post({ zone: ref.id, shift: Boolean(e.shift), ctrl: Boolean(e.ctrl) })
17  })
18  return <Box width="100%" height="100%" />
19}
20
21export default Zone
22
hooks/icons.ts 138 lines
1import type { FileNode } from '../types'
2
3const cp = (n: number) => String.fromCodePoint(n)
4
5export const CHEVRON_OPEN = cp(0xf47c)
6export const CHEVRON_CLOSED = cp(0xf460)
7
8const NAMES: Record<string, number> = {
9  'agents.md': 0xf0354,
10  'changelog.md': 0xf0354,
11  'contributing.md': 0xf0354,
12  'todo.md': 0xf0354,
13  'readme.md': 0xf0354,
14  license: 0xe60a,
15  dockerfile: 0xf0868,
16  makefile: 0xf1064,
17  'cmakelists.txt': 0xf1064,
18  justfile: 0xf05b7,
19  gemfile: 0xf0d2d,
20  rakefile: 0xf0d2d,
21  'cargo.toml': 0xe6b2,
22  'cargo.lock': 0xe6b2,
23  'pyproject.toml': 0xe6b2,
24  'requirements.txt': 0xf160e,
25  'go.mod': 0xf0afa,
26  'go.sum': 0xf07d3,
27  'package.json': 0xf0626,
28  'package-lock.json': 0xf0626,
29  'tsconfig.json': 0xf0626,
30  '.prettierrc': 0xf0626,
31  '.eslintrc': 0xf0626,
32  'pnpm-lock.yaml': 0xe6a8,
33  'yarn.lock': 0xe6a8,
34  '.gitignore': 0xf02a2,
35  '.gitmodules': 0xf0493,
36  '.editorconfig': 0xe652,
37}
38
39const EXTS: Record<string, number> = {
40  lua: 0xe620,
41  py: 0xe606,
42  pyi: 0xe606,
43  js: 0xe60c,
44  mjs: 0xe60c,
45  cjs: 0xe60c,
46  ts: 0xe628,
47  jsx: 0xe625,
48  tsx: 0xe7ba,
49  json: 0xe60b,
50  jsonc: 0xe60b,
51  yaml: 0xe6a8,
52  yml: 0xe6a8,
53  sh: 0xe795,
54  bash: 0xe795,
55  zsh: 0xe795,
56  fish: 0xe795,
57  md: 0xf0354,
58  markdown: 0xf0354,
59  css: 0xe6b8,
60  scss: 0xf031c,
61  html: 0xe736,
62  htm: 0xe736,
63  go: 0xe627,
64  rs: 0xe68b,
65  rb: 0xe791,
66  php: 0xe608,
67  java: 0xe738,
68  cs: 0xf031b,
69  sql: 0xe706,
70  graphql: 0xf20e,
71  gql: 0xf20e,
72  xml: 0xf05c0,
73  toml: 0xe6b2,
74  ini: 0xf0bc2,
75  conf: 0xf0493,
76  pdf: 0xeaeb,
77  svg: 0xf0721,
78  jpg: 0xf0225,
79  jpeg: 0xf0225,
80  png: 0xe60d,
81  gif: 0xf0d78,
82  webp: 0xf021f,
83  mp4: 0xf022b,
84  mkv: 0xf022b,
85  mov: 0xf022b,
86  mp3: 0xf0223,
87  wav: 0xf0223,
88  flac: 0xf0223,
89  zip: 0xf05c4,
90  gz: 0xf05c4,
91  xz: 0xf05c4,
92  tar: 0xf05c4,
93  qml: 0xf375,
94  cpp: 0xe61d,
95  cc: 0xe61d,
96  cxx: 0xe61d,
97  c: 0xe61e,
98  h: 0xf0af5,
99  hpp: 0xf0af5,
100  vue: 0xe6a0,
101  svelte: 0xe697,
102  csv: 0xe64a,
103  txt: 0xf09aa,
104}
105
106export function plainIcon(n: FileNode, open: boolean): string {
107  if (n.kind === 'link') return '↪'
108  if (n.kind === 'dir') return open ? '□' : '■'
109  return '▫'
110}
111
112export function fileIcon(n: FileNode, open: boolean, isRepo: boolean): string {
113  if (n.kind === 'link') return cp(0xf481)
114  if (n.kind === 'dir') return cp(isRepo ? 0xf02a2 : open ? 0xe5fe : 0xe5ff)
115  const lower = n.name.toLowerCase()
116  const named = NAMES[lower]
117  if (named) return cp(named)
118  const dot = lower.lastIndexOf('.')
119  const ext = dot >= 0 ? lower.slice(dot + 1) : ''
120  return cp(EXTS[ext] ?? 0xf0214)
121}
122
123export const GIT_COLOR: Record<string, string> = {
124  A: '#98c379',
125  '?': '#98c379',
126  R: '#61afef',
127  C: '#61afef',
128  M: '#e5c07b',
129  T: '#e5c07b',
130}
131
132const PRIORITY = ['U', 'D', 'M', 'T', 'R', 'C', 'A', '?']
133
134export function stronger(a: string | undefined, b: string): string {
135  if (!a) return b
136  return PRIORITY.indexOf(b) < PRIORITY.indexOf(a) ? b : a
137}
138
hooks/parse.ts 311 lines
1import type { Cli } from './apps'
2import { CLIS } from './clis'
3import { isAbsolute, posix, resolvePath } from './tree'
4
5export type Invocation = { head: string; args: string[]; cwd: string }
6export type CliCall = { cli: Cli; args: string[]; cwd: string }
7
8const SEPARATORS = new Set(['&&', '||', ';', '|', '&', '\n', '(', ')', '`'])
9const PREFIXES = new Set(['do', 'then', 'else', 'elif', 'if', '!', 'time', '{', 'env', 'command', 'builtin', 'exec', 'nohup', 'sudo', 'nice', 'xargs', 'timeout', 'while', 'until'])
10const PREFIX_VALUED: Record<string, Set<string>> = {
11  sudo: new Set(['-u', '-g', '-C', '-h', '-p', '-U', '-r', '-t', '-D']),
12  timeout: new Set(['-k', '-s', '--kill-after', '--signal']),
13  xargs: new Set(['-n', '-I', '-P', '-L', '-s', '-d', '-E', '-a']),
14  env: new Set(['-u', '-C', '-S', '--unset', '--chdir']),
15  nice: new Set(['-n']),
16  exec: new Set(['-a']),
17}
18const RUNNERS: Record<string, string[]> = { npx: [], bunx: [], pnpx: [], bun: ['x'], npm: ['exec', 'x'], pnpm: ['dlx', 'exec'], yarn: ['dlx', 'exec'] }
19const MAX_CALLS = 50
20const REDIRECT = /^(\d*>>?|\d*<|\d*>&\d*|&>>?)$/
21
22export function tokenize(command: string): string[] {
23  const out: string[] = []
24  let cur = ''
25  let quote = ''
26  let has = false
27  for (let i = 0; i < command.length; i++) {
28    const ch = command[i] ?? ''
29    if (!quote && ch === '#' && !has && !cur) {
30      while (i + 1 < command.length && command[i + 1] !== '\n') i++
31      continue
32    }
33    if (quote) {
34      if (ch === quote) quote = ''
35      else if (ch === '\\' && quote === '"' && i + 1 < command.length) cur += command[++i] ?? ''
36      else cur += ch
37      continue
38    }
39    if (ch === '"' || ch === "'") {
40      quote = ch
41      has = true
42    } else if (ch === '\\' && i + 1 < command.length) {
43      cur += command[++i] ?? ''
44      has = true
45    } else if (ch === '\n') {
46      if (has || cur) out.push(cur)
47      cur = ''
48      has = false
49      out.push('\n')
50    } else if (/\s/.test(ch)) {
51      if (has || cur) out.push(cur)
52      cur = ''
53      has = false
54    } else if (ch === '>' || ch === '<') {
55      let op = /^\d+$/.test(cur) || (cur === '&' && !has) ? cur : ''
56      if (!op && (has || cur)) out.push(cur)
57      op += ch
58      while (command[i + 1] === '>' || command[i + 1] === '&' || /\d/.test(command[i + 1] ?? '')) {
59        if (command[i + 1] === '&' && op.endsWith('&')) break
60        op += command[++i]
61      }
62      out.push(op)
63      cur = ''
64      has = false
65    } else if (ch === '(' || ch === ')' || ch === '`') {
66      if (has || cur) out.push(cur)
67      cur = ''
68      has = false
69      out.push(ch)
70    } else if (ch === ';' || ch === '|' || ch === '&') {
71      if (ch === '&' && command[i + 1] === '>') {
72        if (has || cur) out.push(cur)
73        cur = '&'
74        has = false
75        continue
76      }
77      if (has || cur) out.push(cur)
78      cur = ''
79      has = false
80      const two = command.slice(i, i + 2)
81      if (two === '&&' || two === '||') {
82        out.push(two)
83        i++
84      } else out.push(ch)
85    } else {
86      cur += ch
87      has = true
88    }
89  }
90  if (has || cur) out.push(cur)
91  if (!quote) return out
92  return command
93    .split(/(&&|\|\||[;|\n])/)
94    .flatMap(part => (/^(&&|\|\||[;|\n])$/.test(part) ? [part] : part.trim().split(/\s+/).filter(Boolean)))
95}
96
97function operators(line: string): { word: string; tabs: boolean; expand: boolean }[] {
98  const found: { word: string; tabs: boolean; expand: boolean }[] = []
99  const outer: boolean[] = []
100  let single = false
101  let double = false
102  for (let i = 0; i < line.length; i++) {
103    const ch = line[i]
104    if (single) {
105      if (ch === "'") single = false
106      continue
107    }
108    if (ch === '\\') {
109      i++
110      continue
111    }
112    if (ch === '$' && line[i + 1] === '(') {
113      outer.push(double)
114      double = false
115      i++
116      continue
117    }
118    if (ch === ')' && outer.length && !double) {
119      double = outer.pop() ?? false
120      continue
121    }
122    if (ch === '"') {
123      double = !double
124      continue
125    }
126    if (double) continue
127    if (ch === "'") {
128      single = true
129      continue
130    }
131    if (ch === '#' && (i === 0 || /\s/.test(line[i - 1] ?? ''))) break
132    if (ch === '<' && line[i + 1] === '<' && line[i + 2] !== '<') {
133      const m = line.slice(i).match(/^<<(-?)\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\2/)
134      if (m) {
135        found.push({ word: m[3] ?? '', tabs: m[1] === '-', expand: !m[2] })
136        i += m[0].length - 1
137      }
138    }
139  }
140  return found
141}
142
143function heredocless(command: string): string {
144  const out: string[] = []
145  const pending: { word: string; tabs: boolean; expand: boolean }[] = []
146  for (const line of command.split('\n')) {
147    const head = pending[0]
148    if (head) {
149      if ((head.tabs ? line.replace(/^\t+/, '') : line) === head.word) pending.shift()
150      else if (head.expand) out.push(...substitutions(line))
151      continue
152    }
153    out.push(line)
154    pending.push(...operators(line))
155  }
156  return out.join('\n')
157}
158
159function substitutions(command: string): string[] {
160  const out: string[] = []
161  let single = false
162  let double = false
163  for (let i = 0; i < command.length; i++) {
164    const ch = command[i]
165    if (single) {
166      if (ch === "'") single = false
167      continue
168    }
169    if (ch === '\\') {
170      i++
171      continue
172    }
173    if (ch === "'" && !double) {
174      single = true
175      continue
176    }
177    if (ch === '"') {
178      double = !double
179      continue
180    }
181    if (ch === '#' && !double && (i === 0 || /\s/.test(command[i - 1] ?? ''))) {
182      while (i + 1 < command.length && command[i + 1] !== '\n') i++
183      continue
184    }
185    if (ch === '$' && command[i + 1] === '(') {
186      let depth = 0
187      for (let j = i + 1; j < command.length; j++) {
188        if (command[j] === '(') depth++
189        else if (command[j] === ')' && --depth === 0) {
190          out.push(command.slice(i + 2, j))
191          i = j
192          break
193        }
194      }
195      continue
196    }
197    if (ch === '`') {
198      let j = i + 1
199      while (j < command.length && command[j] !== '`') j += command[j] === '\\' ? 2 : 1
200      if (j < command.length) out.push(command.slice(i + 1, j))
201      i = j
202    }
203  }
204  return out
205}
206
207function skipFlags(toks: string[], j: number, word: string): number {
208  const valued = PREFIX_VALUED[word]
209  while (j < toks.length && (toks[j] ?? '').startsWith('-') && !SEPARATORS.has(toks[j] ?? '')) j += valued?.has(toks[j] ?? '') ? 2 : 1
210  return j
211}
212
213export function cdTo(cwd: string, dir: string, home: string): string {
214  if (dir === '~' || dir.startsWith('~/')) return home && isAbsolute(home) ? resolvePath(home, dir.slice(2)) : ''
215  if (dir === '-' || /[~$`]/.test(dir)) return ''
216  if (isAbsolute(posix(dir))) return resolvePath('/', dir)
217  return cwd && isAbsolute(cwd) && !/[~$`]/.test(cwd) ? resolvePath(cwd, dir) : ''
218}
219
220export function invocations(command: string, sessionCwd: string, home: string, wanted: (head: string) => boolean): Invocation[] {
221  const text = heredocless(command)
222  const toks = tokenize(text)
223  const found: Invocation[] = []
224  let cwd = sessionCwd
225  let start = true
226  for (let i = 0; i < toks.length && found.length < MAX_CALLS; i++) {
227    const t = toks[i] ?? ''
228    if (SEPARATORS.has(t)) {
229      start = true
230      continue
231    }
232    if (!start) continue
233    start = false
234    let j = i
235    for (;;) {
236      const tok = toks[j] ?? ''
237      const word = tok.split('/').pop() ?? ''
238      if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(tok)) j++
239      else if (word === 'timeout') {
240        j = skipFlags(toks, j + 1, word)
241        if (/^\d/.test(toks[j] ?? '')) j++
242      } else if (word === 'command' && /^-[A-Za-z]*[vV]/.test(toks[j + 1] ?? '')) break
243      else if (PREFIXES.has(word)) j = skipFlags(toks, j + 1, word)
244      else break
245    }
246    const head = toks[j]?.split('/').pop() ?? ''
247    const next = toks[j + 1]
248    if (head === 'cd') {
249      cwd = next === undefined || SEPARATORS.has(next) ? cdTo(cwd, '~', home) : cdTo(cwd, next, home)
250      continue
251    }
252    if (!head || !wanted(head)) continue
253    const args: string[] = []
254    let k = j + 1
255    while (k < toks.length && !SEPARATORS.has(toks[k] ?? '')) {
256      const tok = toks[k++] ?? ''
257      if (REDIRECT.test(tok)) {
258        if (!/&\d*$/.test(tok) || tok.startsWith('&')) k++
259        continue
260      }
261      args.push(tok)
262    }
263    found.push({ head, args, cwd })
264    i = k - 1
265  }
266  const keyOf = (inv: Invocation) => [inv.head, ...inv.args].join('\0')
267  const seen = new Set(found.map(keyOf))
268  for (const body of substitutions(text)) {
269    for (const inv of invocations(body, cwd, home, wanted)) {
270      const key = keyOf(inv)
271      if (seen.has(key) || found.length >= MAX_CALLS) continue
272      seen.add(key)
273      found.push(inv)
274    }
275  }
276  return found
277}
278
279export function cliCalls(command: string, cwd: string, home: string): CliCall[] {
280  const names = new Set(CLIS.flatMap(c => c.commands))
281  const out: CliCall[] = []
282  for (const inv of invocations(command, cwd, home, head => names.has(head) || head in RUNNERS)) {
283    let head = inv.head
284    let args = inv.args
285    const subs = RUNNERS[head]
286    if (subs && !names.has(head)) {
287      let k = subs.length === 0 ? 0 : subs.includes(args[0] ?? '') ? 1 : -1
288      if (k < 0) continue
289      while (k < args.length && (args[k] ?? '').startsWith('-')) k++
290      head = (args[k] ?? '').replace(/(.)@[^/]*$/, '$1')
291      args = args.slice(k + 1)
292    }
293    const cli = CLIS.find(c => c.commands.includes(head) || c.packages.includes(head))
294    if (cli) out.push({ cli, args, cwd: inv.cwd })
295  }
296  return out
297}
298
299function asksHelp(call: CliCall): boolean {
300  return call.args.some(a => a === '--help' || a === '-h')
301}
302
303export function mutates(call: CliCall): boolean {
304  const verb = call.args.find(a => !a.startsWith('-'))
305  return !asksHelp(call) && verb !== undefined && call.cli.mutating.includes(verb)
306}
307
308export function deploys(call: CliCall): boolean {
309  return !asksHelp(call) && call.args.filter(a => !a.startsWith('-')).slice(0, 2).some(a => call.cli.deploy.includes(a))
310}
311
hooks/tree.ts 310 lines
1import type { FileNode, FileTree, Theme } from '../types'
2import { stronger } from './icons'
3
4export type Entry = { name: string; kind: 'file' | 'dir' | 'other'; mtimeMs: number; isLink: boolean }
5export type Row = { node: FileNode; depth: number; open: boolean }
6
7const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })
8
9export const DEFAULT_THEME: Theme = {
10  fg: '',
11  accent: '#5b9bd5',
12  muted: '#808a96',
13  urgent: '#d0605e',
14  selection: '#3e4451',
15}
16
17export function emptyTree(root: string): FileTree {
18  return {
19    root,
20    nodes: [],
21    expanded: [],
22    cursor: '',
23    selected: '',
24    query: '',
25    showHidden: true,
26    git: {},
27    ignored: [],
28    untrackedDirs: [],
29    diff: {},
30    counts: {},
31    status: '',
32    flash: [],
33    flashDim: [],
34    flashOn: false,
35    flashTones: {},
36    scroll: null,
37    top: '',
38    work: null,
39  }
40}
41
42export function parseTheme(toml: string): Theme {
43  const get = (k: string) => toml.match(new RegExp(`^${k}\\s*=\\s*"(#[0-9a-fA-F]{6})"`, 'm'))?.[1]
44  return {
45    fg: get('foreground') ?? get('color7') ?? DEFAULT_THEME.fg,
46    accent: get('accent') ?? get('color4') ?? DEFAULT_THEME.accent,
47    muted: get('muted') ?? get('color8') ?? DEFAULT_THEME.muted,
48    urgent: get('red') ?? get('color1') ?? DEFAULT_THEME.urgent,
49    selection: get('selection') ?? DEFAULT_THEME.selection,
50  }
51}
52
53export function join(dir: string, name: string): string {
54  return dir.endsWith('/') ? dir + name : `${dir}/${name}`
55}
56
57let drives = false
58
59export function dirname(path: string): string {
60  if (drives && /^[A-Za-z]:\/[^/]*$/.test(path)) return path.slice(0, 3)
61  const i = path.lastIndexOf('/')
62  return i <= 0 ? '/' : path.slice(0, i)
63}
64
65export function useDrives(on: boolean): void {
66  drives = on
67}
68
69export function posix(path: string): string {
70  if (!drives) return path
71  return path.replace(/\\/g, '/').replace(/^\/([A-Za-z])(\/|$)/, (_, d: string) => `${d.toUpperCase()}:/`)
72}
73
74export function isAbsolute(path: string): boolean {
75  return path.startsWith('/') || (drives && /^[A-Za-z]:\//.test(path))
76}
77
78export function resolvePath(base: string, path: string): string {
79  const p = posix(path)
80  const abs = isAbsolute(p) ? p : join(base, p)
81  const head = (drives ? abs.match(/^[A-Za-z]:\//)?.[0] : undefined) ?? '/'
82  const parts: string[] = []
83  for (const seg of abs.slice(head.length).split('/')) {
84    if (seg === '' || seg === '.') continue
85    if (seg === '..') parts.pop()
86    else parts.push(seg)
87  }
88  return head + parts.join('/')
89}
90
91export function toNodes(dir: string, list: Entry[]): FileNode[] {
92  return list
93    .map(e => ({
94      id: join(dir, e.name),
95      parent: dir,
96      name: e.name,
97      kind: e.isLink ? ('link' as const) : e.kind === 'dir' ? ('dir' as const) : ('file' as const),
98      hidden: e.name.startsWith('.'),
99      mtime: e.mtimeMs,
100      loaded: false,
101    }))
102    .sort((a, b) => (a.kind === 'dir' ? 0 : 1) - (b.kind === 'dir' ? 0 : 1) || collator.compare(a.name, b.name))
103}
104
105function under(id: string, set: Set<string>): boolean {
106  for (let i = id.lastIndexOf('/'); i > 0; i = id.lastIndexOf('/', i - 1)) if (set.has(id.slice(0, i))) return true
107  return false
108}
109
110export function replaceChildren(nodes: FileNode[], listed: Map<string, FileNode[]>): FileNode[] {
111  if (listed.size === 0) return nodes
112  const keep = new Map<string, FileNode>()
113  for (const n of nodes) if (listed.has(n.parent)) keep.set(n.id, n)
114  const fresh: FileNode[] = []
115  for (const kids of listed.values())
116    for (const k of kids) {
117      const old = keep.get(k.id)
118      fresh.push(old && old.kind === 'dir' && k.kind === 'dir' ? { ...k, loaded: old.loaded } : k)
119    }
120  const freshIds = new Set(fresh.map(k => k.id))
121  const gone = new Set([...keep.keys()].filter(id => !freshIds.has(id)))
122  const out: FileNode[] = []
123  for (const n of nodes) {
124    if (listed.has(n.parent) || (gone.size > 0 && under(n.id, gone))) continue
125    out.push(listed.has(n.id) ? { ...n, loaded: true } : n)
126  }
127  const taken = new Set(out.map(n => n.id))
128  return [...out, ...fresh.filter(k => !taken.has(k.id) && !(gone.size > 0 && under(k.id, gone)))]
129}
130
131export async function mapLimit<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {
132  const out: R[] = new Array(items.length)
133  let next = 0
134  const worker = async () => {
135    while (next < items.length) {
136      const i = next++
137      out[i] = await fn(items[i] as T)
138    }
139  }
140  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker))
141  return out
142}
143
144export type GitStatus = {
145  git: Record<string, string>
146  ignored: string[]
147  untrackedDirs: string[]
148  files: Record<string, Change>
149}
150
151export type Change = 'new' | 'mod' | 'del'
152
153export function mapper(root: string, prefix: string): (rel: string) => string | null {
154  return rel => (rel.startsWith(prefix) ? join(root, rel.slice(prefix.length).replace(/\/$/, '')).replace(/\/$/, '') : null)
155}
156
157export function parseGit(stdout: string, root: string, prefix: string): GitStatus {
158  const map = mapper(root, prefix)
159  const git: Record<string, string> = {}
160  const ignored: string[] = []
161  const untrackedDirs: string[] = []
162  const files: Record<string, Change> = {}
163  const parts = stdout.split('\0')
164  for (let i = 0; i < parts.length; i++) {
165    const rec = parts[i] ?? ''
166    if (rec.length < 4) continue
167    const xy = rec.slice(0, 2)
168    const raw = rec.slice(3)
169    if (xy[0] === 'R' || xy[0] === 'C') i++
170    const path = map(raw)
171    if (!path) continue
172    if (xy === '!!') {
173      ignored.push(path)
174      continue
175    }
176    if (xy === '??' && raw.endsWith('/')) untrackedDirs.push(path)
177    else files[path] = xy === '??' || (xy.includes('A') && !xy.includes('D')) ? 'new' : xy.includes('D') && !/U/.test(xy) ? 'del' : 'mod'
178    const letter =
179      xy === '??'
180        ? '?'
181        : /U/.test(xy) || xy === 'AA' || xy === 'DD'
182          ? 'U'
183          : (['D', 'M', 'R', 'C', 'A', 'T'].find(c => xy.includes(c)) ?? '')
184    if (!letter) continue
185    git[path] = stronger(git[path], letter)
186    let dir = dirname(path)
187    while (dir.length >= root.length && dir !== '/') {
188      git[dir] = stronger(git[dir], letter)
189      if (dir === root) break
190      dir = dirname(dir)
191    }
192  }
193  return { git, ignored, untrackedDirs, files }
194}
195
196export function parseNumstat(stdout: string, root: string, prefix: string, into: Record<string, [number, number]>): void {
197  const map = mapper(root, prefix)
198  const parts = stdout.split('\0')
199  for (let i = 0; i < parts.length; i++) {
200    const rec = parts[i] ?? ''
201    if (!rec) continue
202    const m = rec.match(/^(-|\d+)\t(-|\d+)\t(.*)$/s)
203    if (!m) continue
204    let path = m[3] ?? ''
205    if (path === '') {
206      i += 2
207      path = parts[i] ?? ''
208    }
209    if (!path) continue
210    const add = m[1] === '-' ? 0 : Number(m[1])
211    const del = m[2] === '-' ? 0 : Number(m[2])
212    const abs = map(path)
213    if (!abs) continue
214    const prev = into[abs] ?? [0, 0]
215    into[abs] = [prev[0] + add, prev[1] + del]
216  }
217}
218
219export function rollUp(diff: Record<string, [number, number]>, root: string): Record<string, [number, number]> {
220  const out: Record<string, [number, number]> = { ...diff }
221  for (const [path, [add, del]] of Object.entries(diff)) {
222    let dir = dirname(path)
223    while (dir.length >= root.length && dir !== '/') {
224      const prev = out[dir] ?? [0, 0]
225      out[dir] = [prev[0] + add, prev[1] + del]
226      if (dir === root) break
227      dir = dirname(dir)
228    }
229  }
230  return out
231}
232
233export function rollCounts(files: Record<string, Change>, root: string): Record<string, [number, number, number]> {
234  const out: Record<string, [number, number, number]> = {}
235  const slot = { new: 0, mod: 1, del: 2 } as const
236  for (const [path, change] of Object.entries(files)) {
237    let dir = dirname(path)
238    while (dir.length >= root.length && dir !== '/') {
239      const cur = out[dir] ?? [0, 0, 0]
240      cur[slot[change]] += 1
241      out[dir] = cur
242      if (dir === root) break
243      dir = dirname(dir)
244    }
245  }
246  return out
247}
248
249export function underAny(id: string, set: Set<string>, root: string): boolean {
250  if (set.size === 0) return false
251  let cur = id
252  while (cur.length >= root.length) {
253    if (set.has(cur)) return true
254    const up = dirname(cur)
255    if (up === cur) break
256    cur = up
257  }
258  return false
259}
260
261export function inside(root: string, path: string): boolean {
262  return path === root || path.startsWith(root.endsWith('/') ? root : `${root}/`)
263}
264
265export function ancestorsOf(id: string, root: string): string[] {
266  const out: string[] = []
267  if (!root) return out
268  for (let dir = dirname(id), prev = id; dir !== prev && dir !== root && inside(root, dir); prev = dir, dir = dirname(dir)) out.push(dir)
269  return out
270}
271
272export function visibleRows(t: FileTree, top = ''): Row[] {
273  const kids = new Map<string, FileNode[]>()
274  for (const n of t.nodes) {
275    if (!t.showHidden && n.hidden) continue
276    const list = kids.get(n.parent)
277    if (list) list.push(n)
278    else kids.set(n.parent, [n])
279  }
280  const q = t.query.trim().toLowerCase()
281  let keep: Set<string> | null = null
282  if (q) {
283    keep = new Set()
284    for (const n of t.nodes) {
285      if (!n.name.toLowerCase().includes(q)) continue
286      keep.add(n.id)
287      for (const a of ancestorsOf(n.id, t.root)) keep.add(a)
288    }
289  }
290  const open = new Set(t.expanded)
291  const rows: Row[] = []
292  const walk = (dir: string, depth: number) => {
293    for (const n of kids.get(dir) ?? []) {
294      if (keep && !keep.has(n.id)) continue
295      const isOpen = n.kind === 'dir' && (keep ? kids.has(n.id) : open.has(n.id))
296      rows.push({ node: n, depth, open: isOpen })
297      if (isOpen) walk(n.id, depth + 1)
298    }
299  }
300  walk(top || t.root, 0)
301  return rows
302}
303
304export function stamp(ms: number): string {
305  if (!ms) return ''
306  const d = new Date(ms)
307  const p = (v: number) => String(v).padStart(2, '0')
308  return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`
309}
310
hooks/rayfin.ts 84 lines
1import type { AppInfo } from '../types'
2import { type Cli, portalUrl, yamlScalar } from './apps'
3
4type Deployment = {
5  fabricItemId: string
6  fabricWorkspaceId: string
7  hostingUrl: string
8  fabricDeepLink: string
9  fabricTenantId: string
10  deployedAt: string
11}
12
13const DEPLOYMENT_FIELDS = ['fabricItemId', 'fabricWorkspaceId', 'hostingUrl', 'fabricDeepLink', 'fabricTenantId', 'deployedAt'] as const
14
15export function yamlName(yaml: string): string {
16  return yamlScalar(yaml.match(/^name:(.*)$/m)?.[1] ?? '')
17}
18
19function deploymentsOf(text: string): { all: Deployment[]; error: string } {
20  if (!text.trim()) return { all: [], error: '' }
21  let parsed: unknown
22  try {
23    parsed = JSON.parse(text)
24  } catch (err) {
25    return { all: [], error: `.deployments.json is not valid JSON: ${err instanceof Error ? err.message : String(err)}` }
26  }
27  const map = parsed && typeof parsed === 'object' ? (parsed as { deployments?: unknown }).deployments : undefined
28  if (map === undefined) return { all: [], error: '' }
29  if (!map || typeof map !== 'object' || Array.isArray(map)) return { all: [], error: '.deployments.json: "deployments" is not an object' }
30  const bad: string[] = []
31  const all: Deployment[] = []
32  for (const [key, raw] of Object.entries(map)) {
33    if (!raw || typeof raw !== 'object') {
34      bad.push(key)
35      continue
36    }
37    const d = raw as Record<string, unknown>
38    const out = { fabricItemId: '', fabricWorkspaceId: '', hostingUrl: '', fabricDeepLink: '', fabricTenantId: '', deployedAt: '' }
39    for (const f of DEPLOYMENT_FIELDS) {
40      const v = d[f]
41      if (typeof v === 'string') out[f] = v
42      else if (v !== undefined && v !== null) bad.push(`${key}.${f}`)
43    }
44    all.push(out)
45  }
46  return { all, error: bad.length ? `.deployments.json: ${bad.join(', ')} ${bad.length === 1 ? 'is' : 'are'} not of the expected type` : '' }
47}
48
49export function fromRayfin(dir: string, yaml: string, deployments: string): AppInfo {
50  const name = yamlName(yaml) || dir.split('/').pop() || dir
51  const { all, error } = deploymentsOf(deployments)
52  const best = all.filter(d => d.fabricItemId).sort((a, b) => b.deployedAt.localeCompare(a.deployedAt))[0]
53  const workspace = best?.fabricWorkspaceId ?? ''
54  const item = best?.fabricItemId ?? ''
55  const deep = best?.fabricDeepLink ?? ''
56  return {
57    dir,
58    name,
59    key: yamlScalar(yaml.match(/^id:(.*)$/m)?.[1] ?? ''),
60    title: name,
61    cli: 'rayfin',
62    tenant: best?.fabricTenantId ?? '',
63    workspace,
64    item,
65    portal: deep.startsWith('https://') ? deep : portalUrl(workspace, item),
66    hosting: best?.hostingUrl ?? '',
67    sources: [],
68    error,
69  }
70}
71
72export const rayfin: Cli = {
73  name: 'rayfin',
74  commands: ['rayfin'],
75  packages: ['@microsoft/rayfin-cli'],
76  mutating: ['init', 'new', 'create', 'link', 'up', 'deploy', 'env', 'functions', 'ai-files', 'skills', 'template', 'add', 'remove'],
77  deploy: ['up'],
78  marker: 'rayfin/rayfin.yml',
79  inputs: ['rayfin/.deployments.json'],
80  start: 'rayfin init',
81  skills: [],
82  read: async (dir, text) => fromRayfin(dir, await text('rayfin/rayfin.yml'), await text('rayfin/.deployments.json')),
83}
84