SLOPSHOPPER

datatug

DataTug CLI plugin: skills that teach AI agents how to use the datatug CLI for data exploration, dataset management, schema scanning, and query execution.

panerowsguardcommandtoastprompt
v0.3.10MITupdated 2026-10-24datatug/ai-plugin
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · datatug
│ ┃ DataTug ✕ › fix the failing auth test and add an audit log call │ ┃ Project Could not list projects: failed │ ┃ ⏺ Read(src/auth.ts) │ ┃ Project Title Origin ⎿ Read 6 lines │ ┃ demo DataTug demo project not ⏺ Update(src/auth.ts) │ ┃ installe ⎿ Added 2 lines, removed 1 line │ ┃ : run ⏺ Bash(bun test) │ ┃ `datatug ⎿ 3 pass, 1 fail │ ┃ demo` │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ───────────────────────────────────────────… │ ┃ ✻ Worked for 42s · done 4:20 PM │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ 🛒 Context bag [ ☑ On ] │ › /datatug │ ┃ │ │ ⎿ datatug: DataTug panel opened. │ ┃ │ Empty. Use 🛒 to add items. │ │ ┃ ╰──────────────────────────────────────────╯ │ ┃ │ ┃ ───────────────────────────────────────────… │ ┃ │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ Databases │ │ ┃ │ │ │ ┃ │ Connection string or file path ⏎ Open │ │ ┃ ╰──────────────────────────────────────────╯ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · DataTug
Project Could not list projects: failed Project Title Origin demo DataTug demo project not installed : run `datatug demo` ──────────────────────────────────────────────────────── ╭──────────────────────────────────────────────────────────╮ │ 🛒 Context bag [ ☑ On ] │ │ │ │ Empty. Use 🛒 to add items. │ ╰──────────────────────────────────────────────────────────╯ ──────────────────────────────────────────────────────── ╭──────────────────────────────────────────────────────────╮ │ Databases │ │ │ │ Connection string or file path ⏎ Open │ ╰──────────────────────────────────────────────────────────╯
README

DataTug AI Plugin

AI plugin for DataTug - skills that teach AI agents how to use the datatug CLI for data exploration, dataset management, schema scanning, and query execution.

This repository contains the plugin source. It is installed on top of the datatug CLI; the CLI is a prerequisite.

Contents

DirectoryDescription
skills/Agent skills - one per major datatug CLI surface area, progressively loaded per-verb
.claude-plugin/Claude Code plugin manifest
hooks/, lib/, types/Claude Code mod: the /datatug panel and /datatug project pane (Claude Code only)
tests/Mod tests, run with claude plugin test
.codex-plugin/Codex plugin manifest
plugin.jsonPortable Agent Plugins manifest for Cursor and other compatible hosts
gemini-extension.jsonGemini CLI extension manifest
.github/plugin.jsonGitHub Copilot CLI / VS Code agent plugin manifest

Local MCP and MCP Apps

The MCP skill covers datatug mcp, a local stdio bridge to a separately running DataTug agent, for discovery and authorized saved SQLite queries. The saved-query Explorer is an MCP Apps developer preview accepted through the official reference host; desktop stdio setup establishes plain tools and model-visible rows. See the setup and privacy guide for the negotiated private App mode and its current acceptance scope. The query-builder skill preserves a planned tab-tool contract and requires those tools to be advertised by the server.

Claude Code mod

In Claude Code, the plugin also ships a mod with two views. Everything either shows comes from the datatug CLI; the mod reads no project file itself.

/datatug opens the DataTug panel, a column of cards beside the transcript:

  • Project: pick one of your registered projects.
  • Databases: the project's databases, plus a field that opens another one from a connection string or a file path and adds it to the project. Open a database to list its tables and views, and count their rows on request.
  • Table: columns, declared types, nullability, keys and foreign keys (press a foreign key to go to the table it points at), who references the table, and the column order you prefer (as defined, A to Z, or by type). Show records lists its first 100 records, 20 to a page; a row number opens the Record card, where a foreign-key value opens the record it points to. Column shows one column's facts.
  • Open in DataTug: the Table, Table records and Record cards of a database in a project link to the same table, its top records or that record in the DataTug web UI at https://datatug.app, which reads them from your own local DataTug agent (datatug daemon). The link comes from datatug daemon url; the mod draws it only after checking it (the hosted UI on https://datatug.app, the agent on 127.0.0.1, a one-time code and the record key only in the part after #, no credentials), refreshes it after a minute, and offers Check again. In its place a card says why there is none: the agent is not running (datatug daemon start), the web UI cannot open that view yet, the CLI is too old, the database is not in a project yet, or the card is shown somewhere other than a terminal on the machine that runs the agent (the Desktop app, VS Code, mobile, or a terminal over SSH). A PostgreSQL database added through an environment variable gets no link. Links, keys and rows never go into a prompt, a notice or the context bag.
  • Context bag: the cart buttons next to a table, a column or a field add it to your bag. Check what you want and press Ask Claude... to draft one question about it in the prompt box; the draft is never sent for you and ends where you type your question. Each item carries the datatug://<project>/<db>?env=<ENV> reference of its database, and the draft gives Claude the one command to run (datatug query run --db '<ref>' --from <table> --limit <N> --no-policies), so a simple question such as "show top 5 artists" is answered with a single call; the rows appear in the card, never to Claude. An item with no recorded database is resolved when the draft is built: the open database, the project's only one, or, with several, its local source (shown as "default: local"; never production by default).

The result card. With datatug 0.92.0 or later, the mod runs Claude's plain datatug query run (ad-hoc, or a saved query with --project --query) with --result-id <id> inserted right after query run (and --format json when Claude gave no --format), so the CLI writes the result to two private files under ~/.datatug/query-results/<id>/ and prints only a path-free line. The mod asks the CLI where the files are (datatug query results locate, never Claude's command or output), checks that they are regular files of the expected names under that folder and within the size bounds, reads them, and draws a card under the call with five views, switched by ● Table ○ Record ○ Columns ○ Sources ○ Related:

  • Table: the rows, 20 at first, then up to 50, then pages of 50, and at most 10 columns. A row number is a button, not a link: pressing it opens that row in Record, where Open row in DataTug ↗ opens the same row in the web UI.
  • Record: one row as type, name and value, with ◀ Prev / Next ▶. A foreign-key value opens the record it points at in the panel.
  • Columns: each column's type, declared type, nullability, key and source column; computed columns are marked.
  • Sources: the tables and views the query reads, with their join columns.
  • Related: the tables that can be joined to it by a foreign key, with the direction, cardinality and field pairs. All are listed; whether you may read one is decided when a query on it runs.

A table or column name opens its Table or Column card in the panel, and Records its Table records card, read through the result's own datatug://<project>/<db> reference, never the database you opened in the panel. A result from a database that is not in a project shows names as text. A native SQL saved query has no sources (nothing parses SQL), and a database whose driver reports no foreign keys says "No related tables found". In the Table view a column header is a Button: press it to sort the rows loaded in the card (up to 2000, then paged) ascending (▲), again descending (▼), a third time to clear. Numbers compare by value, text by letters, empty values last; equal values keep their order. The sort is per card, changes only what is drawn (a row number still opens that row of the result in Record) and runs nothing again. Copy CSV and Copy JSON put the rows loaded in the card (up to 2000, in the order shown, all columns) on your clipboard through the same $.ui.copy as the command's Copy; a toast says how many rows, or that the surface has no clipboard. CSV has a header row and quotes values holding commas, quotes or line breaks; JSON is an array of objects keyed by column name, numbers kept exact. The values are copied raw: nothing is prefixed, so a cell that starts with =, +, - or @ is a formula when the CSV is opened in a spreadsheet (CSV injection); review data you do not trust before opening it there. The clipboard text goes to your clipboard only, never to a log, a notice, a toast, Claude or a tool result. A press redraws only its own card. The rows of the last ten cards are kept; an older card, or one after a reload, shows Load, which reads the files again (results are kept 7 days). With datatug 0.94.0 or later, the card also has an Open in DataTug line for the same result in the web UI (drawn only once datatug daemon url --result reports the web UI can open it, and with the same checks as the panel's links) and the command datatug ui --result <id>, with Copy, which opens the same rows in the DataTug terminal UI. Claude reads a summary only: the row count, the column names, and the names of the source and related tables, never a value, a path, the id, the link or the command. A query that went to the background shows Load. An older datatug, an unusable result store (for example a home folder that is a Git repository, or a sandboxed shell that cannot write ~/.datatug/query-results) or a --format other than json keeps the private capture and the grid below, with a line saying why.

More rows. A result card that is a plain table read (--from, no policy, no offset, a database in a project) has Rows ○ 10 ○ 50 ○ 100 ○ 500 beside Copy CSV and JSON. Pressing a count reads the same table again with that many rows (datatug query run --db=<ref> --from=<table> --limit=<N> --no-policies, run by the mod, not by Claude) and shows it in the same card, in the transcript and the panel; Original goes back to the first result. A count read before is shown from the store, not read again. Claude is not told: it does not see the rows, the new result or the press. The new result is stored with the same prompt as the first. A saved query, a TugQL query, a read under a policy or from an offset, or a table name with anything beyond letters, digits, _, ., $ and - shows one dim line saying why there are no counts (the CLI takes --limit only with --from, and a replay without policies must not widen what a policy allowed).

Your prompt is stored with the result it led to. When a query's result card is ready, the mod hands the latest prompt you submitted (your own words, typed or from Ask Claude; never a notification or another session's message) to datatug query results annotate --id <id> --prompt-stdin on the CLI's standard input, once per result, so DataTug's own UI can show what you asked next to the rows. It is best effort and silent: a datatug older than 0.101.0, the first release with the command, a failure or no prompt seen sends nothing and shows nothing, and the card never waits for it. The prompt is the full text you submitted, including any context-bag boilerplate and clicked values Ask Claude wrote, cut by the CLI to 8 KiB. It is never an argument or environment variable, a log line, a toast, a notice or text Claude reads, and the card does not show it. It is written to the local result store (~/.datatug/query-results/<id>/meta.json, private to you), kept as long as the result (7 days) and shown on the loopback result page: a secret you type into a prompt is stored there too, so do not type one.

If the transcript folds the call into a count line ("Ran 1 shell command"), the mod unfolds that group so the card is drawn inline. In the transcript the card is a bordered, padded block with a blank line above and below, headed by a line naming what it is (for example Customer · chinook-local (local) · 10 rows x 13 columns: the tables it reads, or the saved query's id, or "SQL query"; the database and environment; the row count, "at least N" when more exist), with Open in DataTug ↗ at the top right of that row (below it where the line leaves no room) and Check again beside it, or beside the "Columns 1-10 of N" note when the Table view has one, and the terminal command is a labelled section (a dim frame, Copy under it). The row above it shows a short line instead of the sentence Claude reads. The same card (the newest result) also shows in the DataTug panel as Latest result, opened without taking the keyboard, with the five views, the Open in DataTug line and the Copy controls (the view buttons have no digit keys: a plain Button draws its hotkey as a "1:" prefix, and the engine cannot hide it, so Tab or the arrows and Enter move between the views). The panel's order is Project, Context bag, Latest result, then what you open (Databases, table, records, record, column), with a horizontal rule between sections. With two or more results, a ◀ 2/5 ▶ row and the result's title switch between the last five; the newest is shown when a result arrives. ✕ (key x while the panel has the keys; drawn as [ ✕ ], with no "x:" hint) removes the shown result only; the transcript cards stay. A table wider than ten columns shows ten at a time: ◀ columns and columns ▶ move the window ("Columns 11-13 of 13"), and sort and the Copy buttons still cover every column. A value the grid cuts is a button: press it to see the whole value, as text, under the grid, with Copy and Close. A panel narrower than 60 columns opens on the Record view until you pick a view. Press ctrl+x tab to focus the panel, press Esc to return to the prompt. Where the terminal is too narrow to place the panel, run /datatug. The first result of a session leaves one dim line saying where the card is (later results leave none); ctrl+o expands folded tool calls.

Otherwise (the private capture), when Claude runs a plain datatug query run ... command, the rows are shown to you as a grid under the call and Claude is given only a summary (row and column counts and column names), not the rows. A plain command is datatug query run with its own flags, optionally after env, time or VAR=value, with quotes only around whole arguments, which may hold spaces (--db 'datatug://demo/chinook?env=local', --sql 'select 1'). Any other command that runs datatug query run is denied, and Claude is told to run it plainly: one with a pipe, redirect, comment, &&, a loop, a substitution or other shell syntax, a wrapper such as timeout, nice, nohup, sudo or env -i, an unbalanced or in-word quote, a bare --, its own --result-id, --result-rows or --client, or a run in the background. datatug query run --help alone runs as it is. A row number in the grid opens its Record card. The rows are written to an owner-only folder under your temporary folder (with set -C, so a file already there is never written through) and the file is removed once read (or, when it cannot be read or the call fails, as soon as the call ends; a session killed mid-call can leave one file). An explicit --format other than json is written the same way and shown nowhere; Claude is told to leave it out. A call that goes to the background is not read and its file is removed. Claude's own file tools (Read, Grep, Glob, Edit, Write, NotebookEdit) and Bash commands that name that folder, ~/.datatug/query-results or anything under ~/.datatug by path, or run datatug query results locate, datatug daemon url --result or datatug ui --result are denied. The rows of the last ten results are kept in the session's plugin state for the cards. This is a convenience that keeps rows out of the transcript, not a security boundary: Claude can still read data with a command the mod does not see as one, such as bash -c '...' or a script file. A database you opened with a connection string reaches the CLI in the DATATUG_OPEN_DB environment variable only, never in an argument, a prompt or a link, and the prompts the panel drafts name a database by its datatug://<project>/<db> reference. The one place a value enters a prompt is the context bag: a value you added to the bag and checked is part of the Ask Claude... draft because you chose it.

/datatug project opens a read-only pane for the DataTug project in the session's working directory, with four tabs (Overview, Environments, Queries, Boards), from datatug show, datatug queries and datatug board list, each with --format json. Where nothing can draw (VS Code chat, claude -p), it prints a text summary instead. On the Queries tab, Tab moves between queries and Enter opens one (title, ID, type and parameters). Press a there to draft a request in the prompt box without sending it, so you can add details first; this closes the pane, and /datatug project opens it again. b goes back to the list.

The mod runs the datatug found first on your PATH, in the session's working directory, as the plugin's skills do.

It requires Claude Code 2.1.287 or later and datatug 0.84.1 or later (what the panel needs: datatug:// database references, datatug db add, datatug db schema --columns and the --client flag); the Open in DataTug links need datatug 0.86.0 or later (the record key and a one-time code in the link fragment, and an agent that admits only the hosted web UI), and with an older one the cards say to update it. The result card needs datatug 0.92.0 or later, and its web link and terminal command 0.94.0 or later; with an older one Claude's queries keep the grid. Every datatug command the mod runs carries DATATUG_CLIENT=claude-mod, so the CLI keeps the local agent running for the links; the mod never starts it itself. A database you open by path or connection string is added to the selected project's local environment under a source id of its own (a SQLite file by its path, any other database through an environment variable of its own). To link to a web UI you run locally, set the plugin's Development web UI host setting (/config) to exactly http://datatug.localhost (or https://, with an optional port); nothing else is accepted, and the mod never takes it from the CLI. Other hosts do not run the mod (GitHub Copilot CLI logs one error line about the root hooks/hooks.json when it loads the plugin, and still loads its skills). If the CLI is missing or older, /datatug says so and names the fix.

Develop and test it from this directory with claude --plugin-dir ., claude plugin validate . and claude plugin test.

Install

The same skills/<name>/SKILL.md payload is shared across package formats; each host reads its own manifest. This repository has native inventory receipts for Claude Code and Codex. The Gemini CLI, GitHub Copilot, and Cursor metadata is declarative here and needs host-runtime validation in those environments.

Claude Code

Via the DataTug AI marketplace:

/plugin marketplace add datatug/ai-marketplace
/plugin install datatug@datatug

Codex

codex plugin marketplace add datatug/ai-marketplace

Then enable the datatug plugin from Codex's plugin directory. Codex reads .codex-plugin/plugin.json.

Gemini CLI

gemini extensions install https://github.com/datatug/ai-plugin

gemini-extension.json declares the bundled skills/ tree for Gemini CLI; Gemini runtime discovery is not exercised in this repository.

GitHub Copilot CLI

copilot plugin install datatug/ai-plugin

.github/plugin.json declares the skills for GitHub Copilot; Copilot runtime discovery is not exercised in this repository.

Cursor

The root plugin.json declares the portable Agent Plugins schema supported by Cursor. For local development, follow Cursor's local plugin folder guidance: place this repository under ~/.cursor/plugins/local/datatug and reload Cursor. Cursor runtime discovery is not exercised in this repository.

First use

The datatug CLI must be on your PATH before any wrapper skill can run. Options:

Verify with datatug --help.

Relationship to the CLI

The plugin wraps the datatug CLI - it does not replace it. Skills encode when to call a command, which flags to pass, and how to interpret exit codes. The CLI's commands are documented in the CLI reference.

A change in the CLI surface typically produces a matching skill update in this repository; the two evolve together but release independently.

Relationship to other plugins

datatug is a base-layer CLI wrapper plugin, in the same shape as:

Development

Pull requests and pushes to main run .github/workflows/ci.yml. It has three checks, each runnable locally from the repository root:

CheckWhat it runsLocally
modclaude plugin validate . --strict and claude plugin test (the mod tests in tests/), with Claude Code pinned in the workflow; needs no login or API keyclaude plugin validate . --strict and claude plugin test
manifestsParses every manifest, checks that name and version agree and that every referenced path exists, and runs the checker's own testsnode --test scripts/check-manifests.test.js && node scripts/check-manifests.js
specspecscore spec lint on spec/, with specscore pinned in the workflowspecscore spec lint (install)

When you bump the version, change it in every manifest; the manifests check fails if they differ.

Releases

Releases are tagged as datatug--v<version> on this repository to support Claude Code's dependency resolution.

License

MIT - see LICENSE.

Source 16 files
hooks/register.tsx 3354 lines
1import { atom, memberOf, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import { MIN_CLI_VERSION, VERSION_ARGS, isOlder, missingCliText, parseVersion, tooOldText } from '../lib/cli.js'
5import { LINK_MIN_CLI_VERSION, LINK_TTL_MS, MESSAGES, STATUS_ARGS, bigIntegers, fingerprint, isSameHost, isUnknownCommand, parseDevHost, readLink, recordKey, sourceUnavailableText, urlArgs } from '../lib/links.js'
6import { CARD_MIN_CLI_VERSION, LEGACY_TEXT, MAX_DATA_BYTES, MAX_META_BYTES, OPEN_MIN_CLI_VERSION, RESULT_VIEW_MIN_CLI_VERSION, STATE_TEXT, TEXT, UNAVAILABLE_TEXT, VIEWS, VIEW_LABELS, fallbackOf, isRef, readData, readLocator, readMeta, resultId, resultSummary, resultUrlArgs, statLandsAt, storeProblem, uiCommand } from '../lib/results.js'
7import { ANNOTATE_MIN_CLI_VERSION, annotateArgs, keptPrompt } from '../lib/annotate.js'
8import { MORE_TEXT, ROW_COUNTS, failureReason, moreArgs, moreErrorText, moreGate, moreId } from '../lib/more.js'
9import { isProjectView } from '../lib/command.js'
10import { FAILED_TEXT, STORE_TEXT, bashNamesStore, classify, normalizePath, pathInStore } from '../lib/bash.js'
11import { columnPage, headerLine, historyKeys, historyPick, nextSort, resultTitle, sortedOrder, toCsv, toJson } from '../lib/rows.js'
12import { stripUnsafe } from '../lib/text.js'
13import { canDrawPane } from '../lib/view.js'
14import { registerProject } from './project.js'
15
16import type { Bag, BagEntry, CardMeta, CardState, CardView, DbRecordsState, DatabasesState, DbTableState, GridResult, GridView, LinkState, OpenDbState, ProjectsState, SchemaColumn, SchemaFk, SchemaState, SchemaTable } from '../types'
17
18const PANE = 'datatug'
19const TITLE = 'DataTug'
20const NO_BAG: Bag = { isEnabled: true, entries: [] }
21const MAX_ROWS = 2000
22const MAX_CELL = 200
23const CHAT_ROWS = 20
24const MAX_COLS = 10
25// A panel narrower than this many columns shows the Record view until the person picks a view.
26const NARROW_COLS = 60
27// The results the panel can switch between: the newest of the cards that hold rows.
28const MAX_HISTORY = 5
29const BASE = 'https://datatug.invalid/'
30
31const results = atom({ plugin: 'datatug', key: 'results' } as const, {} as Record<string, GridResult>)
32const shownRows = atom({ plugin: 'datatug', key: 'shownRows' } as const, {} as Record<string, number>)
33const projects = atom({ plugin: 'datatug', key: 'projects' } as const, {
34  status: 'idle',
35  items: [],
36  message: '',
37} as ProjectsState)
38const project = atom({ plugin: 'datatug', key: 'project' } as const, { selected: null } as { selected: string | null; isOpen?: boolean })
39const bags = atom({ plugin: 'datatug', key: 'bags' } as const, {} as Record<string, Bag>)
40const schema = atom({ plugin: 'datatug', key: 'schema' } as const, {
41  projectId: null,
42  status: 'idle',
43  tables: [],
44  message: '',
45} as SchemaState)
46const openDb = atom({ plugin: 'datatug', key: 'openDb' } as const, {
47  status: 'idle',
48  provider: '',
49  note: '',
50  target: '',
51  url: '',
52  items: [],
53  message: '',
54} as OpenDbState)
55const databases = atom({ plugin: 'datatug', key: 'databases' } as const, {
56  projectId: null,
57  status: 'idle',
58  items: [],
59  message: '',
60  note: '',
61} as DatabasesState)
62const columnOrder = atom({ plugin: 'datatug', key: 'columnOrder' } as const, 'defined' as 'defined' | 'alpha' | 'type')
63const dbRecords = atom({ plugin: 'datatug', key: 'dbRecords' } as const, {
64  name: null,
65  status: 'idle',
66  message: '',
67  resultId: null,
68  page: 0,
69} as DbRecordsState)
70const dbTable = atom({ plugin: 'datatug', key: 'dbTable' } as const, {
71  name: null,
72  status: 'idle',
73  message: '',
74  result: null,
75} as DbTableState)
76const view = atom({ plugin: 'datatug', key: 'view' } as const, {
77  current: null,
78  selected: null,
79  offset: 0,
80} as GridView)
81// The "Open in DataTug" state of each linked card (table, records, record): what it shows and when it
82// was checked. Never the link itself, a key value or a row: the link is kept in memory only (`hrefs`).
83const links = atom({ plugin: 'datatug', key: 'links' } as const, {} as Record<string, LinkState>)
84// One result card per `datatug query run` the model ran with result files, keyed by its tool call id:
85// what a press changes redraws that card alone. A card reads only its member and `columnOrder`.
86const NO_CARD: CardState = { status: 'none', id: '', view: 'table', row: 0, shown: 20, page: 0 }
87const cards = atom({ plugin: 'datatug', key: 'cards' } as const, NO_CARD)
88// The cards that hold rows, oldest first: at most MAX_CARDS (a family cannot be listed).
89const cardRows = atom({ plugin: 'datatug', key: 'cardRows' } as const, [] as string[])
90const MAX_CARDS = 10
91// The results the person closed in the panel (their card keys; the transcript rows keep their cards).
92// A closed result is not in the panel's history; loading it again brings it back.
93const latestClosed = atom({ plugin: 'datatug', key: 'latestClosed' } as const, [] as string[])
94// The result the panel shows, a card key, or '' for the newest. A new result selects the newest.
95const latestShown = atom({ plugin: 'datatug', key: 'latestShown' } as const, '')
96// Whether the person has been told, in the transcript, where the result card is: said once per session.
97const noticeShown = atom({ plugin: 'datatug', key: 'noticeShown' } as const, false)
98// The latest prompt the person submitted (their own words, not a notification or a peer's message), kept in
99// session state for the next result to be stored with. It is never drawn, logged, toasted or sent to the model.
100const lastPrompt = atom({ plugin: 'datatug', key: 'lastPrompt' } as const, '')
101
102// Every datatug call the mod makes names the mod as its caller, so the CLI keeps the local DataTug
103// agent (the daemon the web links open) running as a side effect of the cards' own calls.
104const CLIENT = { DATATUG_CLIENT: 'claude-mod' } as const
105const cliEnv = (env: Record<string, string> = {}) => ({ ...env, ...CLIENT })
106
107// The datatug version `/datatug` found (null: a development build; undefined: not checked since load).
108let cliVersion: number[] | null | undefined
109// How this session runs the model's `datatug query run`: with result files ('new') or through the
110// private capture ('legacy'); undefined until the first query asks. `legacyWhy` is a key of
111// LEGACY_TEXT, or null when the version probe failed. `bashVersion` is what the probe read.
112let bashMode: 'new' | 'legacy' | undefined
113let legacyWhy: string | null = null
114let bashVersion: number[] | null = null
115// The development web UI origin the person configured in the plugin's settings, or null.
116let devOrigin: string | null = null
117// Links the CLI printed and the mod checked, by card, with the request they answer. Memory only:
118// a link carries a one-time code.
119const hrefs = new Map<string, { req: string; href: string }>()
120// The request each card is fetching now, so a render does not start a second fetch.
121const fetching = new Map<string, string>()
122
123const NO_PANE_TEXT = 'The DataTug panel needs the terminal or the Desktop app. Run `/datatug project` for a text summary of the project in this folder.'
124const ROWS_DIR = 'datatug-claude-mod'
125
126// The temporary folder the capture folder goes in: the per-user one when the session has TMPDIR
127// (absolute, with no quote, backslash or white space), else /tmp.
128async function tmpBase($: Host): Promise<string> {
129  try {
130    const t = await $.env.get('TMPDIR')
131    if (typeof t === 'string' && t.startsWith('/') && !/['\\\s]/.test(t)) return t.replace(/\/+$/, '') || '/tmp'
132  } catch {
133    // no environment here: the fixed folder stands
134  }
135  return '/tmp'
136}
137
138// Where a run's rows are written for the mod to read: a folder of its own under the temporary
139// folder, made owner-only. The model never reads it.
140async function rowsDir($: Host): Promise<string> {
141  return `${await tmpBase($)}/${ROWS_DIR}`
142}
143
144async function homeDir($: Host): Promise<string | undefined> {
145  try {
146    const h = await $.env.get('HOME')
147    return typeof h === 'string' && h.startsWith('/') && h.length > 1 ? h.replace(/\/+$/, '') : undefined
148  } catch {
149    return undefined
150  }
151}
152
153// The folders the model's own tools must not reach: the result store and the capture folder, each
154// with the folder directly above it, as spelled and as resolved where they exist.
155async function storeRoots($: Host): Promise<{ dir: string; parent: string }[]> {
156  const home = await homeDir($)
157  const base = await tmpBase($)
158  const roots = [{ dir: `${base}/${ROWS_DIR}`, parent: base }]
159  if (home !== undefined) roots.push({ dir: `${home}/.datatug/query-results`, parent: `${home}/.datatug` })
160  const real = async (p: string) => {
161    try {
162      return (await $.fs.exists(p)) ? ((await $.fs.stat(p, { resolve: true })).realPath ?? p) : p
163    } catch {
164      return p
165    }
166  }
167  const resolved = await Promise.all(roots.map(async r => ({ dir: await real(r.dir), parent: await real(r.parent) })))
168  return [...roots, ...resolved]
169}
170
171// Whether any of the paths a model tool was given names the store or the capture folder: by its
172// spelling (folded, a glob pattern by the folder before its first wildcard), and where it resolves
173// when it exists.
174async function namesStore($: Host, paths: unknown[]): Promise<boolean> {
175  const given = paths.filter((p): p is string => typeof p === 'string' && p.trim() !== '')
176  if (given.length === 0) return false
177  const roots = await storeRoots($)
178  const home = await homeDir($)
179  const cwd = await $.session.cwd().catch(() => undefined)
180  for (const p of given) {
181    if (/\.datatug\/query-results|(?:^|\/)datatug-claude-mod(?:\/|$)|\.datatug\/[^/]*[*?[{]/i.test(p)) return true
182    const wild = p.search(/[*?[{]/)
183    const plain = wild < 0 ? p : p.slice(0, wild).replace(/[^/]*$/, '')
184    const n = normalizePath(plain === '' ? '.' : plain, home, cwd)
185    if (pathInStore(n, roots)) return true
186    if (n !== null && wild < 0) {
187      try {
188        if (await $.fs.exists(n)) {
189          const realPath = (await $.fs.stat(n, { resolve: true })).realPath
190          if (realPath !== undefined && pathInStore(realPath, roots)) return true
191        }
192      } catch {
193        // a path that cannot be looked at is judged by its spelling alone
194      }
195    }
196  }
197  return false
198}
199
200// Removes a capture file through the shell (the mod's file access cannot delete), else empties it.
201async function removeCapture($: Host, file: string) {
202  try {
203    const r = await $.process.run(['rm', '-f', file], { timeoutMs: 10000 })
204    if (r.exitCode === 0) return
205  } catch {
206    // emptied below instead
207  }
208  try {
209    if (await $.fs.exists(file)) await $.fs.write(file, '')
210  } catch {
211    // a file that can be neither removed nor emptied is left as it is
212  }
213}
214
215// Control characters and line breaks would let a data value act on the terminal.
216// An error with a message this module wrote itself: the only kind whose text is shown. Anything else
217// (a failed spawn, a JSON error quoting CLI output) is shown as 'failed'.
218class ModError extends Error {}
219const failure = (err: unknown, max: number) => (err instanceof ModError ? scrub(err.message).slice(0, max) : 'failed')
220
221function clean(text: string): string {
222  return stripUnsafe(text)
223}
224
225// A connection string anywhere in text (an error message that repeats `--db`, a stored command) is
226// blanked up to the last @ that follows it, so a password with an @ or a / in it cannot survive.
227export function scrub(text: string): string {
228  return stripUnsafe(text)
229    .replace(/[a-z][a-z0-9+.-]*:\/\/[^\n]*@\S*|[a-z][a-z0-9+.-]*:\/\/\S*/gi, '***')
230    .replace(/\b[a-z][a-z0-9+.-]*:[a-z0-9_]+=\S*/gi, '***')
231    .replace(/\S+:\S+@\S+/g, '***')
232        .replace(/--?(?:password|passwd|pwd|token|secret)[ =]+\S+/gi, '***')
233    .replace(/\b(password|passwd|pwd|pass|secret|token|api_?key)\s*[=:]\s*[^\s;&]+/gi, '$1=***')
234}
235
236// A cell of the card's table: plain Text, never Markdown. A web or file address is broken so no
237// terminal turns a value into a clickable link.
238function gridText(value: unknown, max = 60): string {
239  return cell(value)
240    .slice(0, max)
241    .replace(/(https?|file):\/\//gi, '$1:\u200b//')
242}
243
244function cell(value: unknown): string {
245  if (value === null || value === undefined) return ''
246  const text = typeof value === 'object' ? JSON.stringify(value) : String(value)
247  return clean(text)
248}
249
250// Data goes into a Markdown table: neutralise syntax and autolinks.
251function md(value: unknown, max = 60): string {
252  return cell(value)
253    .slice(0, max)
254    .replace(/(https?|file):\/\//gi, '$1:\u200b//')
255    .replace(/[\\`*_[\]<>|~&]/g, m => '\\' + m)
256}
257
258// A column is numeric when every value it holds in the first rows is a number.
259function isNumeric(result: GridResult, name: string): boolean {
260  let seen = false
261  for (const row of result.rows.slice(0, 200)) {
262    const v = row[name]
263    if (v === null || v === undefined) continue
264    if (typeof v !== 'number') return false
265    seen = true
266  }
267  return seen
268}
269
270// What the model reads in place of the rows: shape only, never values.
271function summary(result: GridResult): string {
272  const cols = result.columns.slice(0, 40).map(c => clean(c).slice(0, 60)).join(', ')
273  return [
274    `DataTug query returned ${result.total} row${result.total === 1 ? '' : 's'} x ${result.columns.length} column${result.columns.length === 1 ? '' : 's'}: ${cols}.`,
275    result.isTruncated ? `The grid holds the first ${result.rows.length} rows.` : '',
276    'The rows are shown to the user in a DataTug result grid and are withheld from you.',
277  ]
278    .filter(Boolean)
279    .join(' ')
280}
281
282// The JSON output carries no declared column types, so they are read off the
283// values: integer, number, string(<=longest seen), boolean, object, array, or
284// several joined by `|`. A CLI that reports declared types (VARCHAR(10),
285// NUMERIC(5,2)) would replace these.
286export function inferType(rows: Record<string, unknown>[], name: string): string {
287  const kinds = new Set<string>()
288  let longest = 0
289  let whole = 0
290  let decimals = 0
291  for (const row of rows.slice(0, 200)) {
292    const v = row[name]
293    if (v === null || v === undefined) continue
294    if (typeof v === 'number') {
295      if (Number.isInteger(v)) {
296        kinds.add('integer')
297      } else {
298        kinds.add('number')
299        const [int, frac = ''] = String(Math.abs(v)).split('.')
300        whole = Math.max(whole, int.length)
301        decimals = Math.max(decimals, frac.length)
302      }
303    } else if (typeof v === 'string') {
304      kinds.add('string')
305      longest = Math.max(longest, [...v].length)
306    } else if (typeof v === 'boolean') kinds.add('boolean')
307    else kinds.add(Array.isArray(v) ? 'array' : 'object')
308  }
309  if (kinds.size === 0) return 'null'
310  return [...kinds]
311    .map(k => (k === 'string' ? `string(≤${longest})` : k === 'number' ? `number(${whole + decimals},${decimals})` : k))
312    .join('|')
313}
314
315// What the loaded rows say about one column (never the declared schema).
316export function profileColumn(result: GridResult, name: string) {
317  let nonNull = 0
318  let nulls = 0
319  const seen = new Set<string>()
320  const samples: string[] = []
321  let min: number | string | undefined
322  let max: number | string | undefined
323  let minLen = Infinity
324  let maxLen = 0
325  for (const row of result.rows) {
326    const v = row[name]
327    if (v === null || v === undefined) {
328      nulls++
329      continue
330    }
331    nonNull++
332    const text = cell(v)
333    if (seen.size < 5000) seen.add(text)
334    if (samples.length < 4 && !samples.includes(text.slice(0, 40))) samples.push(text.slice(0, 40))
335    if (typeof v === 'number') {
336      if (min === undefined || v < (min as number)) min = v
337      if (max === undefined || v > (max as number)) max = v
338    } else if (typeof v === 'string') {
339      if (min === undefined || v < (min as string)) min = v
340      if (max === undefined || v > (max as string)) max = v
341      minLen = Math.min(minLen, [...v].length)
342      maxLen = Math.max(maxLen, [...v].length)
343    }
344  }
345  return { nonNull, nulls, distinct: seen.size, min, max, minLen: minLen === Infinity ? 0 : minLen, maxLen, samples }
346}
347
348// `$key` is dalgo's internal record key. It is never metadata, and a data view drops it once the
349// table's own primary key is known.
350const KEY = '$key'
351export function metaColumns(columns: string[]): string[] {
352  return columns.filter(c => c !== KEY)
353}
354export function dataColumns(columns: string[], table: SchemaTable | undefined): string[] {
355  const hasPk = table?.columns.some(c => c.pk !== null) === true
356  return hasPk ? metaColumns(columns) : columns
357}
358
359// The key mark of a column: just 🔑 when the primary key has one column, 🔑 and its position when it has several.
360export function keyMark(table: SchemaTable | undefined, pk: number | null): string {
361  if (pk === null) return ''
362  const parts = table?.columns.filter(c => c.pk !== null).length ?? 0
363  return parts > 1 ? `🔑 ${pk}` : '🔑'
364}
365
366// The prompt for the checked context bag items: the items (each with its database reference), the one
367// command to run, and the user's own question. Short and imperative so a small model runs the command at
368// once; the rows reach the card, never the model. `openDb` is the database the panel has open, for an
369// item that carries none.
370export type BagSource = { id: string; env: string }
371
372// The database an item without a recorded reference is asked against: the one it carries, else the open
373// database, else the project's only database, else (several) the one source whose environment is
374// `local`, never a production one by default. '' when still ambiguous: the prompt then lets Claude ask.
375// Applied when the prompt is built, so an item bagged before the reference was recorded is upgraded too.
376export function resolveBagDb(entryDb: string | undefined, openDb: string, projectId: string | null, sources: BagSource[]): { ref: string; rule: string } {
377  if (entryDb !== undefined && isDbRef(entryDb)) return { ref: entryDb, rule: '' }
378  if (isDbRef(openDb)) return { ref: openDb, rule: '' }
379  if (projectId === null || projectId === '') return { ref: '', rule: '' }
380  if (sources.length === 1) return { ref: dbRef(projectId, sources[0]), rule: ', default: the only database' }
381  const local = sources.filter(s => s.env.toLowerCase() === 'local')
382  if (local.length === 1) return { ref: dbRef(projectId, local[0]), rule: ', default: local' }
383  return { ref: '', rule: '' }
384}
385
386export function bagPrompt(entries: BagEntry[], projectId: string | null, openDb = '', sources: BagSource[] = []): string {
387  const shown = entries.slice(0, 50)
388  const resolve = (e: BagEntry) => resolveBagDb(e.db, openDb, projectId, sources)
389  const lines = shown.map(e => {
390    const kind = e.kind ?? (e.address === 'contextBag.table' ? 'table' : e.address === 'contextBag.column' ? 'column' : 'value')
391    const what = kind === 'value' ? `${clean(e.address).replace(/^contextBag\./, '')} = ${clean(e.value).slice(0, 200)}` : `${kind} ${clean(e.value).slice(0, 200)}`
392    const r = resolve(e)
393    return `- ${what} (${r.ref === '' ? 'database not recorded' : `database ${r.ref}${r.rule}`})`
394  })
395  const where = projectId !== null && projectId !== '' ? ` (project ${clean(projectId).slice(0, 80)})` : ''
396  const dbOf = shown.map(e => resolve(e).ref).find(r => r !== '') ?? ''
397  const shape = `datatug query run --db '${dbOf === '' ? '<datatug:// database ref>' : dbOf}' --from <table> --limit <N> --no-policies`
398  return (
399    `My DataTug context bag${where}:\n${lines.join('\n')}\n\n` +
400    `Answer by running this at once, without asking and without loading skills: ${shape}\n` +
401    `Quote the reference as shown; use --db with it only (never --project with --db). Never look for connection strings and never read the DataTug store. ` +
402    `The rows appear in the card in the chat, not to you. "Top N" with no ranking column named means the first N rows (--limit N). The environment is the one in the reference. ` +
403    `Ask only if the database is not recorded and the project has several. Then reply with one line saying the result is in the card above; do not offer to read, list or paste rows.\n\n`
404  )
405}
406
407// The tables a column's foreign keys point at.
408export function fkTargets(table: SchemaTable | undefined, name: string): { table: string; column: string }[] {
409  return (table?.foreignKeys ?? []).flatMap(fk => fk.columns.flatMap((c, i) => (c.toLowerCase() === name.toLowerCase() ? [{ table: fk.refTable, column: fk.refColumns[i] ?? '' }] : [])))
410}
411
412export type ColumnOrder = 'defined' | 'alpha' | 'type'
413
414// The family of a column type, for grouping: numeric, text, date, boolean, binary, json, other.
415export function baseType(type: string): string {
416  const x = type.toLowerCase()
417  if (/bool|\bbit\b/.test(x)) return 'boolean'
418  if (/blob|binary|bytea|image/.test(x)) return 'binary'
419  if (/date|time|year|interval/.test(x)) return 'date'
420  if (/\b(tiny|small|medium|big)?int(eger)?\b|serial|numeric|decimal|number|real|float|double|money/.test(x)) return 'numeric'
421  if (/char|text|string|clob|uuid|enum|name/.test(x)) return 'text'
422  if (/json|object|array|xml/.test(x)) return 'json'
423  return 'other'
424}
425// Column names in the order asked for. `declared` is the table's definition order when a scan holds
426// the table; without it "as defined" keeps the order the rows came in (alphabetical, from the CLI).
427// `$key` always leads. Grouped by type, a family keeps the definition order inside it.
428export function orderColumns(names: string[], mode: ColumnOrder, declared: string[] | undefined, typeOf: (name: string) => string): string[] {
429  const at = (n: string) => {
430    const i = declared?.findIndex(d => d.toLowerCase() === n.toLowerCase()) ?? -1
431    return i < 0 ? Number.MAX_SAFE_INTEGER : i
432  }
433  const alpha = (a: string, b: string) => a.localeCompare(b, undefined, { sensitivity: 'base' })
434  const defined = (a: string, b: string) => (at(a) === at(b) ? names.indexOf(a) - names.indexOf(b) : at(a) < at(b) ? -1 : 1)
435  const family = (n: string) => baseType(typeOf(n))
436  const cmp = mode === 'alpha' ? alpha : mode === 'type' ? (a: string, b: string) => family(a).localeCompare(family(b)) || alpha(a, b) : defined
437  return [...names.filter(n => n === KEY), ...names.filter(n => n !== KEY).sort(cmp)]
438}
439
440// A table by name (any case); one in the same environment and source as `near` wins.
441export function findTable(tables: SchemaTable[], name: string, near?: SchemaTable): SchemaTable | undefined {
442  const wanted = name.toLowerCase()
443  const named = tables.filter(t => t.name.toLowerCase() === wanted)
444  return named.find(t => near !== undefined && t.env === near.env && t.source === near.source) ?? named[0]
445}
446
447const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase()
448
449// "3 tables": how many distinct tables hold a foreign key to the table (one table with two keys counts once).
450export function tablesCount(refs: { table: SchemaTable }[]): string {
451  const n = new Set(refs.map(r => `${r.table.schema}.${r.table.name}`.toLowerCase())).size
452  return `${n} ${n === 1 ? 'table' : 'tables'}`
453}
454
455// The tables that hold a foreign key to `t`, with the key: what `t` is referenced by.
456export function referrers(tables: SchemaTable[], t: SchemaTable): { table: SchemaTable; fk: SchemaFk }[] {
457  const out: { table: SchemaTable; fk: SchemaFk }[] = []
458  for (const x of tables) {
459    if (x.env !== t.env || x.source !== t.source || x.schema !== t.schema) continue
460    for (const fk of x.foreignKeys) if (same(fk.refTable, t.name) && (fk.refSchema === '' || same(fk.refSchema, t.schema))) out.push({ table: x, fk })
461  }
462  return out
463}
464
465export function parseRows(stdout: string, id: string, command: string): GridResult | null {
466  const start = stdout.indexOf('[')
467  if (start < 0) return null
468  let data: unknown
469  try {
470    data = JSON.parse(stdout.slice(start))
471  } catch {
472    return null
473  }
474  if (!Array.isArray(data) || !data.every(r => r !== null && typeof r === 'object' && !Array.isArray(r))) return null
475  const rows = (data as Record<string, unknown>[]).slice(0, MAX_ROWS)
476  const columns: string[] = []
477  for (const row of rows.slice(0, 200)) for (const key of Object.keys(row)) if (!columns.includes(key)) columns.push(key)
478  const types = Object.fromEntries(columns.map(c => [c, inferType(rows, c)]))
479  const collection = /--from\s+(\S+)/.exec(command)?.[1] ?? /--query\s+(\S+)/.exec(command)?.[1] ?? 'result'
480  const dbArg = /--db\s+(\S+)/.exec(command)?.[1] ?? ''
481  const db = /^[a-z][a-z0-9+.-]*:\/\//i.test(dbArg) && redact(dbArg) === dbArg ? dbArg : ''
482  return { id, command: scrub(command).slice(0, 300), collection: clean(collection).slice(0, 60), db, columns, types, rows, total: data.length, isTruncated: data.length > rows.length }
483}
484
485type Host = Parameters<typeof update>[0] & {
486  process: { run: (argv: string[], init?: { cwd?: string; timeoutMs?: number; env?: Record<string, string> }) => Promise<{ exitCode: number; stdout: string; stderr?: string }> }
487  session: { cwd: () => Promise<string> }
488}
489
490// What the Open DB field holds. A module variable on purpose: the connection string may carry a
491// password, so it never goes into session state, and it is emptied once the database is opened.
492let dbDraft = ''
493// The opened database's connection string, for the table pressed next. Memory only, like the draft.
494let dbUrl = ''
495// The project reference `db add` returned for the opened database: the only address a prompt carries.
496let dbPromptRef = ''
497// Counts which open is current, so a slow row count from an earlier open is ignored.
498let openRun = 0
499
500// A connection string without its credentials or query: safe to show.
501// Only a string of a known harmless shape is shown or kept; anything else is hidden entirely.
502const SHOWN = /^[a-z][a-z0-9+.-]*:\/\/(\*\*\*@)?[A-Za-z0-9.-]*(:\d+)?(\/[A-Za-z0-9._~\/ -]*)?$/i
503export function redact(url: string): string {
504  if (isDbRef(url)) return url
505  // Up to the LAST @ is credentials, even when the password holds an @, a / or a ?.
506  const scheme0 = /^([a-z][a-z0-9+.-]*):\/\//i.exec(url.trim())?.[1].toLowerCase()
507  // An @ together with a ? or # may sit in a query or fragment: nothing can be told apart, so hide it all.
508  if (url.includes('@') && /[?#]/.test(url)) return scheme0 === undefined ? '***' : `${scheme0}://***`
509  const cut = url.replace(/^([a-z][a-z0-9+.-]*:\/\/).*@/is, '$1***@').replace(/[?#].*$/s, '')
510  if (SHOWN.test(cut)) return cut
511  const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(url.trim())?.[1].toLowerCase()
512  return scheme === undefined ? '***' : `${scheme}://***`
513}
514
515// A project database reference (datatug://<project>/<db-id>[?env=<ENV>]) holds no credentials: it
516// is passed as written and is the one URL that may go into a prompt together with its query.
517export function isDbRef(url: string): boolean {
518  const part = String.raw`(?:[A-Za-z0-9._~-]|%(?!40|3a)[0-9a-f]{2})`
519  return new RegExp(`^datatug://${part}*/${part}+(\\?env=${part}+)?$`, 'i').test(url)
520}
521
522// The reference of a database the project holds: what the CLI resolves back to its source.
523export function dbRef(projectId: string | null, d: { env: string; id: string }): string {
524  return `datatug://${encodeURIComponent(projectId ?? '')}/${encodeURIComponent(d.id)}?env=${encodeURIComponent(d.env)}`
525}
526
527// How a database is handed to the CLI: a reference as it is, anything else through an environment
528// variable so a password never sits in the argument list.
529export function dbArg(url: string): { arg: string; env: Record<string, string> } {
530  return isDbRef(url) ? { arg: url, env: {} } : { arg: 'env:DATATUG_OPEN_DB', env: { DATATUG_OPEN_DB: url } }
531}
532
533// What to call a database: its id in the project for a reference, else the file or database name
534// at the end of its address (never the credentials: the target is already redacted).
535export function dbName(target: string): string {
536  const ref = isDbRef(target) ? /^datatug:\/\/[^/?#]*\/([^/?#]+)/i.exec(target.trim()) : null
537  const raw = ref !== null ? ref[1] : (/([^/\\?#]+)\/*(?:[?#].*)?$/.exec(target.trim().replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]*@?/i, ''))?.[1] ?? 'database')
538  try {
539    return decodeURIComponent(raw)
540  } catch {
541    return raw
542  }
543}
544
545export function providerOf(url: string): string {
546  return /^([a-z][a-z0-9+.-]*):\/\//i.exec(url.trim())?.[1].toLowerCase() ?? ''
547}
548
549const TOP = 100
550const REC_PAGE = 20
551const NO_RECORDS: DbRecordsState = { name: null, status: 'idle', message: '', resultId: null, page: 0 }
552
553const SQLITE_FILE = /\.(sqlite3?|db3?|s3db|sl3)$/i
554
555type Detected = { url: string; provider: string; note: string } | { error: string }
556
557// A connection string is used as written. A file path is recognised by its name (.sqlite, .db, ...)
558// or, failing that, by its first bytes: every SQLite file starts with "SQLite format 3".
559// A path is echoed only when it looks like one: text typed as a connection string without a scheme is not.
560function shownPath(typed: string, path: string): string {
561  return /^[\w ./~+-]+$/.test(path) && /[/.]/.test(typed) ? clean(path).slice(0, 160) : 'that path'
562}
563
564async function detectDatabase($: Host, raw: string): Promise<Detected> {
565  const text = raw.trim()
566  if (text === '') return { error: 'Enter a connection string or the path of a database file, for example sqlite:///path/to.db' }
567  if (/^[a-z][a-z0-9+.-]*:/i.test(text)) return { url: text, provider: providerOf(text), note: '' }
568  let path = text
569  if (path.startsWith('~/')) path = `${(await $.env.get('HOME')) ?? ''}${path.slice(1)}`
570  if (!path.startsWith('/')) path = `${await $.session.cwd()}/${path.replace(/^\.\//, '')}`
571  if (!(await $.fs.exists(path))) return { error: `No file at ${shownPath(text, path)}` }
572  if (SQLITE_FILE.test(path)) return { url: `sqlite://${path}`, provider: 'sqlite', note: 'from the file name' }
573  const head = await $.process.run(['head', '-c', '16', path], { timeoutMs: 5000 })
574  if (head.exitCode === 0 && head.stdout.startsWith('SQLite format 3')) return { url: `sqlite://${path}`, provider: 'sqlite', note: 'from the file content' }
575  return { error: `Could not tell what kind of database ${shownPath(text, path)} is. Use a connection string such as sqlite:///path/to.db` }
576}
577
578type DeclaredTable = {
579  schema?: string
580  name: string
581  kind?: string
582  columns?: { name: string; type?: string; nullable?: boolean; primaryKeyPosition?: number }[]
583  foreignKeys?: { name?: string; columns?: string[]; refTable?: { schema?: string; name?: string }; refColumns?: string[] }[]
584}
585
586// A table as `datatug db schema --columns` declares it, in the shape the cards read.
587function declaredTable(t: DeclaredTable, driver: string): SchemaTable {
588  return {
589    env: '',
590    source: 'opened',
591    driver: clean(driver).slice(0, 40),
592    schema: clean(String(t.schema ?? '')).slice(0, 60),
593    name: clean(t.name).slice(0, 80),
594    columns: (t.columns ?? []).slice(0, 200).map(c => ({
595      name: clean(String(c.name)).slice(0, 80),
596      type: clean(String(c.type ?? '')).slice(0, 60),
597      pk: typeof c.primaryKeyPosition === 'number' ? c.primaryKeyPosition : null,
598      nullable: typeof c.nullable === 'boolean' ? c.nullable : null,
599    })),
600    foreignKeys: (t.foreignKeys ?? []).slice(0, 50).flatMap(fk =>
601      Array.isArray(fk.columns) && Array.isArray(fk.refColumns) && fk.refTable?.name !== undefined
602        ? [{
603            name: clean(String(fk.name ?? '')).slice(0, 80),
604            columns: fk.columns.slice(0, 8).map(c => clean(String(c)).slice(0, 80)),
605            refSchema: clean(String(fk.refTable.schema ?? '')).slice(0, 60),
606            refTable: clean(String(fk.refTable.name)).slice(0, 80),
607            refColumns: fk.refColumns.slice(0, 8).map(c => clean(String(c)).slice(0, 80)),
608          }]
609        : [],
610    ),
611  }
612}
613
614// Opens a database from a connection string or a file path and lists its tables and views. The CLI
615// has no schema command yet, so SQLite is read through sqlite_master; other providers say so.
616async function openDatabase($: Host, raw: string) {
617  dbDraft = ''
618  const found = await detectDatabase($, raw)
619  if ('error' in found) {
620    await update($, openDb, () => ({ status: 'error', provider: '', note: '', target: '', url: '', items: [], message: found.error }))
621    return
622  }
623  const { url, note } = found
624  let provider = found.provider
625  const target = redact(url).slice(0, 160)
626  dbUrl = ''
627  dbPromptRef = ''
628  const run = ++openRun
629  await update($, dbTable, () => ({ name: null, status: 'idle', message: '', result: null }))
630  await update($, dbRecords, () => NO_RECORDS)
631  await update($, openDb, () => ({ status: 'loading', provider, note, target, url: '', items: [], message: '' }))
632  try {
633    // The URL goes in an environment variable, never in the argument list.
634    const cwd = await $.session.cwd()
635    const { arg, env } = dbArg(url)
636    const sch = await $.process.run(['datatug', 'db', 'schema', '--db', arg, '--columns', '--format', 'json'], { cwd, timeoutMs: 30000, env: cliEnv(env) })
637    const doc = sch.exitCode === 0 && sch.stdout.trimStart().startsWith('{') ? (JSON.parse(sch.stdout) as { provider?: string; tables?: DeclaredTable[] }) : null
638    if (doc !== null && Array.isArray(doc.tables)) {
639      if (isDbRef(url) && typeof doc.provider === 'string') provider = clean(doc.provider).slice(0, 30)
640      const declared = doc.tables.filter(t => typeof t.name === 'string' && !t.name.startsWith('sqlite_')).slice(0, 500)
641      const items = declared
642        .map(t => ({ name: clean(t.name).slice(0, 80), kind: t.kind === 'view' ? 'view' : 'table' }))
643        .sort((x, y) => (x.kind === y.kind ? x.name.localeCompare(y.name) : x.kind.localeCompare(y.kind)))
644      const tables = declared.map(t => declaredTable(t, provider))
645      dbUrl = url
646      const plain = redact(url) === url
647      await update($, openDb, () => ({ status: 'ready', provider, note, target, url: plain ? url : '', items, tables, message: '', ref: isDbRef(url) ? url : '' }))
648      if (!isDbRef(url)) void addToProject($, url)
649      return
650    }
651    if (!provider.startsWith('sqlite')) throw new ModError(`${provider}: this datatug CLI cannot list the schema; update it`)
652    // An older CLI: SQLite is read through sqlite_master.
653    const out = await $.process.run(
654      ['datatug', 'query', 'run', '--db', dbArg(url).arg, '--from', 'sqlite_master', '--no-policies', '--format', 'json'],
655      { cwd: await $.session.cwd(), timeoutMs: 20000, env: cliEnv(dbArg(url).env) },
656    )
657    const start = out.stdout.indexOf('[')
658    if (out.exitCode !== 0 || start < 0) throw new ModError('could not open the database')
659    const rows = JSON.parse(out.stdout.slice(start)) as { name?: string; type?: string }[]
660    const items = rows
661      .filter(r => (r.type === 'table' || r.type === 'view') && typeof r.name === 'string' && !r.name.startsWith('sqlite_'))
662      .map(r => ({ name: clean(String(r.name)).slice(0, 80), kind: r.type as string }))
663      .sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind.localeCompare(b.kind)))
664      .slice(0, 500)
665    dbUrl = url
666    // A URL with no credentials or query also goes in state, so a table pressed after the mod
667    // reloads still works. One with credentials lives in memory only.
668    const plain = redact(url) === url
669    await update($, openDb, () => ({ status: 'ready', provider, note, target, url: plain ? url : '', items, message: '', ref: isDbRef(url) ? url : '' }))
670    if (!isDbRef(url)) void addToProject($, url)
671  } catch (err) {
672    await update($, openDb, () => ({ status: 'error', provider, note, target, url: '', items: [], message: failure(err, 120) }))
673  }
674}
675
676// Row counts for tables of the opened database (views are left out), on request only. The CLI has no count, so
677// each table is streamed as JSON lines and the lines are counted; a table too large to read
678// whole is shown as at least the rows seen. Three at a time, so a big schema does not stall.
679async function countRows($: Host, items: OpenDbState['items'], url: string, run: number) {
680  const tables = items.filter(i => i.kind === 'table').slice(0, 100)
681  const cwd = await $.session.cwd()
682  const names = new Set(tables.map(t => t.name))
683  await update($, openDb, cur => ({ ...cur, items: cur.items.map(i => (i.kind === 'table' && names.has(i.name) ? { ...i, counting: true } : i)) }))
684  let next = 0
685  const worker = async () => {
686    while (next < tables.length) {
687      const t = tables[next++]
688      let rows: number | null = null
689      let atLeast = false
690      try {
691        if (t.name.startsWith('-')) throw new ModError('unsupported table name')
692        const out = await $.process.run(
693          ['datatug', 'query', 'run', '--db', dbArg(url).arg, '--from', t.name, '--no-policies', '--format', 'jsonl'],
694          { cwd, timeoutMs: 30000, env: cliEnv(dbArg(url).env) },
695        )
696        if (out.exitCode === 0) {
697          rows = out.stdout.split('\n').filter(l => l.startsWith('{') && l.endsWith('}')).length
698          atLeast = (out as { isStdoutTruncated?: boolean }).isStdoutTruncated === true
699        }
700      } catch {
701        rows = null
702      }
703      if (run !== openRun) return
704      await update($, openDb, cur => ({ ...cur, items: cur.items.map(i => (i.name === t.name && i.kind === 'table' ? { ...i, rows, atLeast, counting: false } : i)) }))
705    }
706  }
707  await Promise.all([worker(), worker(), worker()])
708}
709
710// Loads the selected project's schema unless it is already there (or loading).
711async function ensureSchema($: Host) {
712  const sel = (await read($, project)).selected
713  const cur = await read($, schema)
714  if (sel !== null && (cur.projectId !== sel || cur.status === 'idle' || cur.status === 'error')) await loadSchema($, sel)
715}
716
717// The record of `table` whose `column` equals `value`: the rows are streamed as JSON lines and the
718// stream is cut at the first match. The CLI has no lookup by key yet.
719async function fetchReferenced($: Host, url: string, table: string, column: string, value: string): Promise<{ obj: Record<string, unknown>; line: string } | null> {
720  if (table.startsWith('-') || url === '') return null
721  const child = $.process.spawn({
722    argv: ['datatug', 'query', 'run', '--db', dbArg(url).arg, '--from', table, '--no-policies', '--format', 'jsonl'],
723    cwd: await $.session.cwd(),
724    env: cliEnv(dbArg(url).env),
725  })
726  let buf = ''
727  let seen = 0
728  for await (const piece of child) {
729    if (!('text' in piece) || piece.stream !== 'stdout') continue
730    buf += piece.text
731    let nl = buf.indexOf('\n')
732    while (nl >= 0) {
733      const line = buf.slice(0, nl)
734      buf = buf.slice(nl + 1)
735      if (line.startsWith('{') && line.endsWith('}')) {
736        if (++seen > 200000) return null
737        try {
738          const obj = JSON.parse(line) as Record<string, unknown>
739          if (String(obj[column]) === value) return { obj, line }
740        } catch {
741          // a line that is not a record
742        }
743      }
744      nl = buf.indexOf('\n')
745    }
746  }
747  return null
748}
749
750// Opens the record of `table` whose `column` equals `value` in the Record card; false when it is not found.
751async function openRecordByKey($: Host, db: string, table: string, column: string, value: string): Promise<boolean> {
752  const found0 = await fetchReferenced($, db, table, column, value)
753  if (found0 === null) return false
754  const id = `ref:${table}:${column}:${value}`
755  const parsed = parseRows(`[${JSON.stringify(found0.obj)}]`, id, `datatug query run --from ${table}`)
756  if (parsed === null) return false
757  const found: GridResult = { ...parsed, collection: clean(table).slice(0, 80), total: 1, db }
758  await update($, results, all => ({ ...Object.fromEntries(Object.entries(all).slice(-9)), [id]: found }))
759  await update($, view, cur => ({ ...cur, trail: [], current: id, selected: 0, column: null, showTable: false, tableName: null }))
760  void $.ui.scroll({ to: { key: 'card-record' }, in: PANE, block: 'start' }).catch(() => undefined)
761  return true
762}
763
764// The first 100 records of a table of the opened database. The CLI has no row limit yet, so the
765// rows are streamed as JSON lines and the stream is cut once 100 have arrived. They are stored as a
766// result, so pressing a row number opens the Record card like a row of a chat grid.
767// With `explicit` (a datatug:// reference a result card names) it reads through that reference
768// alone, never the opened database.
769async function openDbRecords($: Host, name: string, kept: string, known: number | null | undefined, explicit?: string) {
770  const run0 = openRun
771  const refOnly = explicit !== undefined ? { ref: explicit } : {}
772  await update($, dbRecords, () => ({ ...NO_RECORDS, name, status: 'loading', ...refOnly }))
773  try {
774    if (explicit !== undefined && !isRef(explicit)) throw new ModError('this database has no project reference')
775    const url = explicit ?? (dbUrl !== '' ? dbUrl : kept)
776    if (url === '') throw new ModError('Open the database again: its connection string is not kept.')
777    if (name.startsWith('-')) throw new ModError('unsupported table name')
778    const child = $.process.spawn({
779      argv: ['datatug', 'query', 'run', '--db', dbArg(url).arg, '--from', name, '--no-policies', '--format', 'jsonl'],
780      cwd: await $.session.cwd(),
781      env: cliEnv(dbArg(url).env),
782    })
783    const lines: string[] = []
784    let buf = ''
785    for await (const piece of child) {
786      if (!('text' in piece) || piece.stream !== 'stdout') continue
787      buf += piece.text
788      let nl = buf.indexOf('\n')
789      while (nl >= 0 && lines.length < TOP) {
790        const line = buf.slice(0, nl)
791        buf = buf.slice(nl + 1)
792        if (line.startsWith('{') && line.endsWith('}')) lines.push(line)
793        nl = buf.indexOf('\n')
794      }
795      if (lines.length >= TOP) break
796    }
797    if (lines.length < TOP && buf.startsWith('{') && buf.endsWith('}')) lines.push(buf)
798    const id = `db:${name}`
799    const parsed = parseRows(`[${lines.join(',')}]`, id, 'datatug query run')
800    if (parsed === null || lines.length === 0) throw new ModError('the table has no records')
801    const linkRef = explicit ?? (await read($, openDb)).ref ?? ''
802    const result: GridResult = {
803      ...parsed,
804      db: redact(url) === url ? url : '',
805      collection: clean(name).slice(0, 80),
806      total: Math.max(known ?? 0, lines.length),
807      isTruncated: (known ?? 0) > lines.length,
808      // Only the key-sized facts a Record link needs beside the parsed rows: the integers they round.
809      ...(linkRef !== '' ? { linkRef } : {}),
810      ...(explicit === undefined ? { openRun: run0 } : {}),
811      bigInts: lines.map(l => bigIntegers(l)),
812    }
813    await update($, results, all => ({ ...Object.fromEntries(Object.entries(all).slice(-9)), [id]: result }))
814    await update($, dbRecords, () => ({ name, status: 'ready', message: '', resultId: id, page: 0, ...refOnly }))
815  } catch (err) {
816    await update($, dbRecords, () => ({ ...NO_RECORDS, name, status: 'error', message: failure(err, 140), ...refOnly }))
817  }
818}
819
820// A table of the opened database. Nothing is read from it: its columns come from a scan (or, later,
821// from the CLI), because profiling a table by reading its rows can be costly. Rows are read only when
822// the person asks for the records or for a count.
823async function openDbTable($: Host, name: string) {
824  // The Table card takes the place of an open Table records card.
825  await update($, dbRecords, () => NO_RECORDS)
826  await update($, dbTable, () => ({ name, status: 'ready', message: '', result: null }))
827  void ensureSchema($)
828}
829
830// The databases the selected project already holds, from the CLI (sources of each environment).
831async function loadDatabases($: Host, projectId: string | null, note = '') {
832  if (projectId === null) return
833  await update($, databases, cur => ({ projectId, status: 'loading', items: cur.projectId === projectId ? cur.items : [], message: '', note }))
834  try {
835    const out = await $.process.run(['datatug', 'show', '--format', 'json', '--depth', 'sources', '--project', projectId], {
836      cwd: await $.session.cwd(),
837      timeoutMs: 15000,
838      env: cliEnv(),
839    })
840    if (out.exitCode !== 0) throw new ModError('datatug show failed')
841    const doc = JSON.parse(out.stdout.slice(out.stdout.indexOf('{')))
842    const items: DatabasesState['items'] = []
843    for (const env of doc.environments ?? [])
844      for (const src of env.sources ?? [])
845        if (items.length < 200) items.push({
846            env: clean(String(env.id)).slice(0, 60),
847            id: clean(String(src.id)).slice(0, 80),
848            driver: clean(String(src.driver ?? '')).slice(0, 40),
849            ...(typeof src.dsnEnv === 'string' && /^[A-Za-z_][A-Za-z0-9_]{0,127}$/.test(src.dsnEnv) ? { dsnEnv: src.dsnEnv } : {}),
850          })
851    await update($, databases, () => ({ projectId, status: 'ready', items, message: '', note }))
852  } catch (err) {
853    await update($, databases, () => ({ projectId, status: 'error', items: [], message: failure(err, 120), note }))
854  }
855}
856
857// The id an opened database is added to a project under: its file name without the extension, or
858// its database name, as a plain name (letters, digits, `.`, `_` and `-`, starting with a letter or
859// a digit).
860export function sourceName(url: string): string {
861  const raw = dbName(redact(url)).replace(/\.[A-Za-z0-9]{1,8}$/, '')
862  const plain = raw.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[^A-Za-z0-9]+/, '').slice(0, 64)
863  return plain === '' ? 'db' : plain
864}
865
866// The path of a SQLite database to hand `db add`, which takes a SQLite file by its path: only an
867// absolute path with no credentials, query or fragment, else null (such a database is not added).
868export function sqlitePath(url: string): string | null {
869  const m = /^sqlite3?:\/\/(\/[^?#@\n\r]+)$/i.exec(url.trim())
870  return m === null ? null : m[1]
871}
872
873// Adds an opened database to the selected project through the CLI, unless it is already there,
874// then refreshes the list. A SQLite file is named by its path; any other URL travels in an
875// environment variable of its own (one per database, so two databases are never taken for one),
876// never in the arguments. Each database gets its own source id; a taken id gets a -2, -3, ... suffix.
877async function addToProject($: Host, url: string) {
878  const sel = (await read($, project)).selected
879  if (sel === null) return
880  const isSqlite = providerOf(url).startsWith('sqlite')
881  const path = isSqlite ? sqlitePath(url) : null
882  if (isSqlite && path === null) {
883    await loadDatabases($, sel, 'Not added to the project: a SQLite database is added by its file path, without credentials or options.')
884    return
885  }
886  const base = sourceName(url)
887  try {
888    for (let n = 1; n <= 5; n++) {
889      const name = n === 1 ? base : `${base.slice(0, 60)}-${n}`
890      // The id's own fingerprint keeps names that fold together (shop-db, shop_db, Shop.db) apart.
891      const envName = `DATATUG_OPEN_DB_${name.toUpperCase().replace(/[^A-Z0-9]/g, '_')}_${fingerprint(name).slice(0, 6).toUpperCase()}`
892      const out = await $.process.run(['datatug', 'db', 'add', '--project', sel, '--db', path ?? `env:${envName}`, '--name', name, '--env', 'local', '--format', 'json'], {
893        cwd: await $.session.cwd(),
894        timeoutMs: 20000,
895        env: cliEnv(path === null ? { [envName]: url } : {}),
896      })
897      if (out.exitCode === 2 && /use another --name/i.test(`${out.stderr}`)) continue
898      if (out.exitCode !== 0) {
899        const old = /unknown command|unknown flag|no such command|invalid command/i.test(`${out.stderr}${out.stdout}`)
900        await loadDatabases($, sel, old ? 'Adding to the project needs a newer datatug CLI.' : `Not added to the project (datatug exit code ${out.exitCode}).`)
901        return
902      }
903      const res = JSON.parse(out.stdout.slice(out.stdout.indexOf('{'))) as { added?: boolean; dbRef?: string; id?: unknown; env?: unknown }
904      if (dbUrl === url) {
905        if (typeof res.dbRef === 'string' && isDbRef(res.dbRef)) dbPromptRef = res.dbRef.slice(0, 300)
906        // A link names this database only by the id and environment `db add` returned for it.
907        const plainId = (v: unknown) => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(v)
908        if (plainId(res.id) && plainId(res.env)) {
909          const ref = dbRef(sel, { id: res.id as string, env: res.env as string })
910          await update($, openDb, cur => (dbUrl === url ? { ...cur, ref, sourceEnv: path === null ? envName : undefined } : cur))
911        }
912      }
913      await loadDatabases($, sel, res.added === true ? 'Added to the project.' : 'Already in the project.')
914      return
915    }
916    await loadDatabases($, sel, 'Not added to the project: every name tried is taken by another database.')
917  } catch {
918    await loadDatabases($, sel, 'Could not add it to the project.')
919  }
920}
921
922// The projects registered for this user, from the CLI (never from its files).
923async function loadProjects($: Host) {
924  await update($, projects, cur => ({ ...cur, status: 'loading' }))
925  try {
926    const out = await $.process.run(['datatug', 'projects', '--format', 'json'], { cwd: await $.session.cwd(), timeoutMs: 15000, env: cliEnv() })
927    const data = out.exitCode === 0 ? JSON.parse(out.stdout.slice(out.stdout.indexOf('['))) : null
928    if (!Array.isArray(data)) throw new ModError('datatug projects did not answer')
929    const items = data
930      .filter(p => p && typeof p.id === 'string')
931      .slice(0, 100)
932      .map(p => ({ id: clean(p.id).slice(0, 80), title: clean(String(p.title ?? '')).slice(0, 80), origin: clean(String(p.origin ?? '')).slice(0, 120) }))
933    await update($, projects, () => ({ status: 'ready', items, message: '' }))
934    await update($, project, cur => ({ isOpen: false, selected: cur.selected !== null && items.some(i => i.id === cur.selected) ? cur.selected : (items[0]?.id ?? null) }))
935    await loadDatabases($, (await read($, project)).selected)
936  } catch (err) {
937    await update($, projects, () => ({ status: 'error', items: [], message: failure(err, 120) }))
938  }
939}
940
941// The declared schema of the selected project, from the CLI: tables with their columns.
942// What one linked card asks `datatug daemon url` for.
943export type LinkReq = { kind: 'table' | 'records' | 'record'; db: string; table: string; schema?: string; isView?: boolean; limit?: number; key?: Record<string, unknown> }
944
945async function nowMs($: Host): Promise<number> {
946  try {
947    return await $.clock.now()
948  } catch {
949    return Date.now()
950  }
951}
952
953// Whether the mod runs in a terminal reached over SSH, where a link would open on another machine.
954// When the environment cannot be read, the same machine cannot be established either.
955async function overSsh($: Host): Promise<boolean> {
956  try {
957    const a = await $.env.get('SSH_CONNECTION')
958    const b = await $.env.get('SSH_TTY')
959    return (a ?? '') !== '' || (b ?? '') !== ''
960  } catch {
961    return true
962  }
963}
964
965const reqId = (req: LinkReq): string | null => {
966  const args = urlArgs(req)
967  return args === null ? null : fingerprint(JSON.stringify(args))
968}
969
970// Where one link's state is kept: the panel's `links` atom, or a result card's own member.
971type LinkStore = { get: () => Promise<LinkState | undefined>; set: (fn: (cur: LinkState | undefined) => LinkState | undefined) => Promise<unknown> }
972
973// Asks the CLI for one card's link (`daemon status` for the port, then `daemon url`; neither starts
974// the daemon or sends it a request) and keeps what the checks allow. Called once the card's own data
975// call has resolved; again when the link is older than LINK_TTL_MS, and on "Check again".
976async function fetchLinkInto($: Host, card: string, args: string[], kind: string, store: LinkStore, force: boolean, minimum: string, rid?: string) {
977  const id = fingerprint(JSON.stringify(args))
978  if (fetching.get(card) === id) return
979  // Claimed before any await, so two drawings at once never ask twice (each ask mints a code).
980  fetching.set(card, id)
981  let t = 0
982  try {
983    const cur = await store.get()
984    t = await nowMs($)
985    if (!force && cur !== undefined && cur.req === id && cur.status !== 'checking' && cur.isStale !== true && t - cur.at < LINK_TTL_MS) return
986    hrefs.delete(card)
987    await store.set(() => ({ req: id, status: 'checking', at: t }))
988    let next: { status: LinkState['status']; href?: string }
989    if (cliVersion !== undefined && cliVersion !== null && isOlder(cliVersion, parseVersion(minimum) as number[])) {
990      next = { status: 'old-cli' }
991    } else {
992      const cwd = await $.session.cwd()
993      const run = (argv: string[]) =>
994        $.process
995          .run(['datatug', ...argv], { cwd, timeoutMs: 10000, env: cliEnv() })
996          .then(r => ({ exitCode: r.exitCode, stdout: r.stdout, stderr: r.stderr ?? '' }))
997          .catch(() => null)
998      const status = await run(STATUS_ARGS)
999      next = readLink(status, status === null ? null : await run(args), kind, devOrigin, rid)
1000    }
1001    const at = await nowMs($)
1002    if (next.status === 'ok' && next.href !== undefined) hrefs.set(card, { req: id, href: next.href })
1003    await store.set(c => (c?.req === id ? { req: id, status: next.status, at } : c))
1004    // Once the link is old the card is drawn again, which asks the CLI again.
1005    try {
1006      $.clock.after(LINK_TTL_MS, () => {
1007        void store.set(c => (c?.req === id && c.at === at ? { ...c, isStale: true } : c))
1008      })
1009    } catch {
1010      // no timer here: the next drawing checks the age
1011    }
1012  } catch {
1013    await store.set(c => (c?.req === id ? { req: id, status: 'unavailable', at: t } : c)).catch(() => undefined)
1014  } finally {
1015    if (fetching.get(card) === id) fetching.delete(card)
1016  }
1017}
1018
1019async function fetchLink($: Host, card: string, req: LinkReq, force: boolean) {
1020  const args = urlArgs(req)
1021  if (args === null) return
1022  const store: LinkStore = {
1023    get: async () => (await read($, links))[card],
1024    set: fn =>
1025      update($, links, all => {
1026        const next = fn(all[card])
1027        return next === all[card] ? all : next === undefined ? all : { ...all, [card]: next }
1028      }),
1029  }
1030  await fetchLinkInto($, card, args, req.kind, store, force, LINK_MIN_CLI_VERSION)
1031}
1032
1033// A result card's link, for its current view (and row, in the Record view).
1034async function fetchCardLink($: Host, key: string, force: boolean) {
1035  const card = await read($, memberOf(cards, { requestId: key }))
1036  const args = resultUrlArgs(card.id, card.view, card.view === 'record' ? card.row + 1 : undefined, hasResultView())
1037  if (args === null) return
1038  const store: LinkStore = {
1039    get: async () => (await read($, memberOf(cards, { requestId: key }))).link,
1040    set: fn => update($, memberOf(cards, { requestId: key }), c => ({ ...c, link: fn(c.link) })),
1041  }
1042  await fetchLinkInto($, `qr:${key}`, args, 'result', store, force, OPEN_MIN_CLI_VERSION, card.id)
1043}
1044
1045async function loadSchema($: Host, projectId: string | null) {
1046  if (projectId === null) return
1047  await update($, schema, () => ({ projectId, status: 'loading', tables: [], message: '' }))
1048  try {
1049    const out = await $.process.run(['datatug', 'show', '--format', 'json', '--depth', 'columns', '--project', projectId], {
1050      cwd: await $.session.cwd(),
1051      timeoutMs: 20000,
1052      env: cliEnv(),
1053    })
1054    if (out.exitCode !== 0) throw new ModError('datatug show failed')
1055    const doc = JSON.parse(out.stdout.slice(out.stdout.indexOf('{')))
1056    const tables: SchemaTable[] = []
1057    for (const env of doc.environments ?? [])
1058      for (const src of env.sources ?? [])
1059        for (const sch of src.schemas ?? [])
1060          for (const tbl of sch.tables ?? []) {
1061            if (tables.length >= 500) break
1062            tables.push({
1063              env: clean(String(env.id)).slice(0, 60),
1064              source: clean(String(src.id)).slice(0, 60),
1065              driver: clean(String(src.driver ?? '')).slice(0, 40),
1066              schema: clean(String(sch.name ?? '')).slice(0, 60),
1067              name: clean(String(tbl.name)).slice(0, 80),
1068              foreignKeys: (Array.isArray(tbl.foreignKeys) ? tbl.foreignKeys : []).slice(0, 50).flatMap(
1069                (fk: { name?: string; columns?: string[]; refTable?: string | { schema?: string; name?: string }; refColumns?: string[] }) => {
1070                  const ref = typeof fk.refTable === 'string' ? { name: fk.refTable, schema: '' } : fk.refTable
1071                  if (!Array.isArray(fk.columns) || !Array.isArray(fk.refColumns) || ref?.name === undefined) return []
1072                  return [{
1073                    name: clean(String(fk.name ?? '')).slice(0, 80),
1074                    columns: fk.columns.slice(0, 8).map(c => clean(String(c)).slice(0, 80)),
1075                    refSchema: clean(String(ref.schema ?? '')).slice(0, 60),
1076                    refTable: clean(String(ref.name)).slice(0, 80),
1077                    refColumns: fk.refColumns.slice(0, 8).map(c => clean(String(c)).slice(0, 80)),
1078                  }]
1079                },
1080              ),
1081              columns: (tbl.columns ?? []).slice(0, 200).map((c: { name: string; type?: string; primaryKeyPosition?: number; nullable?: boolean; isNullable?: boolean }) => ({
1082                name: clean(String(c.name)).slice(0, 80),
1083                type: clean(String(c.type ?? '')).slice(0, 60),
1084                pk: typeof c.primaryKeyPosition === 'number' ? c.primaryKeyPosition : null,
1085                nullable: typeof c.nullable === 'boolean' ? c.nullable : typeof c.isNullable === 'boolean' ? c.isNullable : null,
1086              })),
1087            })
1088          }
1089    await update($, schema, () => ({ projectId, status: 'ready', tables, message: '' }))
1090  } catch (err) {
1091    await update($, schema, () => ({ projectId, status: 'error', tables: [], message: failure(err, 120) }))
1092  }
1093}
1094
1095// The project, source and environment a datatug:// reference names, or null.
1096export function refParts(ref: string | null | undefined): { project: string; source: string; env: string | null } | null {
1097  if (typeof ref !== 'string' || !isRef(ref)) return null
1098  const m = /^datatug:\/\/([^/?#]+)\/([^/?#]+)(?:\?env=([^&#]+))?$/.exec(ref)
1099  if (m === null) return null
1100  const dec = (x: string) => {
1101    try {
1102      return decodeURIComponent(x)
1103    } catch {
1104      return x
1105    }
1106  }
1107  return { project: dec(m[1]), source: dec(m[2]), env: m[3] === undefined ? null : dec(m[3]) }
1108}
1109
1110// A table of the project schema by its full identity: environment, source, schema and name together.
1111export function findRef(tables: SchemaTable[], r: { env: string; source: string; schema: string; name: string }): SchemaTable | undefined {
1112  return tables.find(t => t.source === r.source && (r.env === '' || t.env === r.env) && same(t.name, r.name) && (r.schema === '' || t.schema === '' || same(t.schema, r.schema)))
1113}
1114
1115// Opens the panel on the project a reference names: selects it and loads its databases and schema.
1116async function panelOnProject($: Host, project0: string) {
1117  const sel = (await read($, project)).selected
1118  if (sel !== project0) {
1119    await update($, project, () => ({ selected: project0, isOpen: false }))
1120    void loadDatabases($, project0)
1121  }
1122  const ps = await read($, projects)
1123  if (ps.status === 'idle' || ps.status === 'error') void loadProjects($)
1124  const cur = await read($, schema)
1125  if (cur.projectId !== project0 || cur.status === 'idle' || cur.status === 'error') void loadSchema($, project0)
1126  await $.ui.open({ id: PANE, title: TITLE })
1127}
1128
1129// The side panel's Table or Column card for a table a result card names, found in the schema of the
1130// reference's project by environment, source, schema and name. Module level: the result cards and
1131// the panel both call it. It runs no query.
1132async function gotoPanel($: Host, ref: string, target: { schema: string; table: string; column?: string | null; showTable?: boolean }) {
1133  const parts = refParts(ref)
1134  if (parts === null) return
1135  await panelOnProject($, parts.project)
1136  await update($, dbTable, () => ({ name: null, status: 'idle', message: '', result: null }))
1137  await update($, dbRecords, () => NO_RECORDS)
1138  await update($, view, cur => ({
1139    ...cur,
1140    tableName: target.table,
1141    tableRef: { env: parts.env ?? '', source: parts.source, schema: target.schema, name: target.table },
1142    column: target.column ?? null,
1143    showTable: target.showTable === true,
1144  }))
1145  const go = () => void $.ui.scroll({ to: { key: 'card-detail' }, in: PANE, block: 'start' }).catch(() => undefined)
1146  go()
1147  try {
1148    $.clock.after(150, go)
1149  } catch {
1150    // no timer here: the first attempt stands
1151  }
1152}
1153
1154// The side panel's Table records card for a table a result card names, read through that reference.
1155async function openRefRecords($: Host, ref: string, table: string) {
1156  const parts = refParts(ref)
1157  if (parts === null) return
1158  await panelOnProject($, parts.project)
1159  await update($, dbTable, () => ({ name: null, status: 'idle', message: '', result: null }))
1160  await openDbRecords($, table, '', undefined, ref)
1161  void $.ui.scroll({ to: { key: 'card-dbrecords' }, in: PANE, block: 'start' }).catch(() => undefined)
1162}
1163
1164// The record a foreign-key value of a result card points at, in the side panel's Record card.
1165async function openRefRecord($: Host, ref: string, table: string, column: string, value: string) {
1166  const parts = refParts(ref)
1167  if (parts === null) return
1168  await panelOnProject($, parts.project)
1169  if (!(await openRecordByKey($, ref, table, column, value))) void $.ui.toast(`No ${clean(table).slice(0, 60)} record with ${clean(column).slice(0, 60)} = ${clean(value).slice(0, 40)}`)
1170}
1171
1172// Decides, once per session, how the model's queries run: result files when the CLI is new enough and
1173// its store is usable, else the private capture. A probe that fails takes the capture.
1174async function sessionMode($: Host): Promise<'new' | 'legacy'> {
1175  if (bashMode !== undefined) return bashMode
1176  const cwd = await $.session.cwd().catch(() => undefined)
1177  const run = (argv: string[]) => $.process.run(['datatug', ...argv], { ...(cwd === undefined ? {} : { cwd }), timeoutMs: 15000, env: cliEnv() }).catch(() => null)
1178  const v = await run(VERSION_ARGS)
1179  if (v === null || v.exitCode !== 0) {
1180    legacyWhy = null
1181    return (bashMode = 'legacy')
1182  }
1183  // A version that cannot be read is a development build: it is taken as new.
1184  const found = parseVersion(v.stdout)
1185  if (cliVersion === undefined) cliVersion = found
1186  if (found !== null && isOlder(found, parseVersion(CARD_MIN_CLI_VERSION) as number[])) {
1187    legacyWhy = 'old-cli'
1188    return (bashMode = 'legacy')
1189  }
1190  bashVersion = found
1191  const check = await run(['query', 'results', 'check', '--format', 'json'])
1192  const problem = check === null ? 'results-store-unwritable' : check.exitCode !== 0 ? (isUnknownCommand(`${check.stderr ?? ''}${check.stdout}`) ? 'old-cli' : 'results-store-unwritable') : storeProblem(check.stdout)
1193  if (problem !== null) {
1194    legacyWhy = problem
1195    return (bashMode = 'legacy')
1196  }
1197  return (bashMode = 'new')
1198}
1199
1200// Whether the CLI takes `--result-view` (a version that cannot be read is taken as the older flag).
lib/cli.js 85 lines
1// What the mod asks of the datatug CLI, and how it reads the answers. Pure:
2// starting a process is the hooks module's job.
3import { cleanText } from './text.js'
4
5// The first datatug release with everything the mod runs: `board list`, `queries --format json`
6// and `show --depth` for the project pane, and for the panel `datatug://` database references
7// (`--db datatug://<project>/<db>`), `db add`, `db schema --columns` and the `--client` caller flag.
8export const MIN_CLI_VERSION = '0.84.1'
9
10// Argument lists, without the leading `datatug`. All four are read-only.
11export const VERSION_ARGS = ['--version']
12export const LISTINGS = {
13  show: ['show', '--format', 'json', '--depth', 'tables'],
14  queries: ['queries', '--format', 'json'],
15  boards: ['board', 'list', '--format', 'json'],
16}
17
18// The CLI's exit code for a folder that is not a project.
19export const EXIT_NOT_A_PROJECT = 3
20
21const COMMAND_NAMES = {
22  show: 'datatug show',
23  queries: 'datatug queries',
24  boards: 'datatug board list',
25}
26
27const ANSI_STYLE = /\u001b\[[0-9;]*m/g
28
29export function parseVersion(text) {
30  const m = /(\d+)\.(\d+)\.(\d+)/.exec(text ?? '')
31  return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null
32}
33
34export function isOlder(version, minimum) {
35  for (let i = 0; i < 3; i += 1) {
36    if (version[i] !== minimum[i]) return version[i] < minimum[i]
37  }
38  return false
39}
40
41const MAX_ERROR_LENGTH = 300
42
43// The CLI prints a failure as a banner line "ERROR" between blank lines, then
44// the message, wrapped over several lines when it is long. A warning row
45// carries the message as one line.
46export function errorMessage(stderr, exitCode) {
47  const text = cleanText(
48    String(stderr ?? '')
49      .replace(ANSI_STYLE, '')
50      .split('\n')
51      .map((line) => line.trim())
52      .filter((line) => line !== '' && line !== 'ERROR')
53      .join(' '),
54    MAX_ERROR_LENGTH,
55  )
56  return text === '' ? 'exit code ' + exitCode : text
57}
58
59// Turns one finished listing command into its parsed JSON, or a warning.
60export function readListing(name, result) {
61  if (result.exitCode !== 0) {
62    return { data: null, warning: COMMAND_NAMES[name] + ': ' + errorMessage(result.stderr, result.exitCode) }
63  }
64  if (result.isStdoutTruncated === true) {
65    return { data: null, warning: COMMAND_NAMES[name] + ': its output is too large to read' }
66  }
67  try {
68    return { data: JSON.parse(result.stdout), warning: null }
69  } catch {
70    return { data: null, warning: COMMAND_NAMES[name] + ': its output is not JSON' }
71  }
72}
73
74export function missingCliText() {
75  return 'The datatug CLI could not be started, or did not answer in 15 seconds. If it is not installed, use the datatug:datatug-install skill, then run /datatug again.'
76}
77
78export function tooOldText(found) {
79  return 'datatug ' + found + ' is too old for this pane: it needs ' + MIN_CLI_VERSION + ' or later. Run `datatug self-update`, then /datatug again.'
80}
81
82export function notAProjectText(cwd) {
83  return cwd + ' is not a DataTug project: run /datatug from a project\'s root folder.'
84}
85
lib/links.js 323 lines
1// "Open in DataTug" links of the panel's Table, Table records and Record cards. Pure: running the
2// CLI is the hooks module's job. The mod never builds a web UI address: `datatug daemon url` does,
3// and this module only decides whether what the CLI printed may be drawn as a link.
4
5// The first datatug release whose `daemon url` puts the record key and a one-time code in the link
6// fragment, and whose agent admits only the hosted web UI's origin.
7export const LINK_MIN_CLI_VERSION = '0.86.0'
8
9// How long a fetched link is drawn before `daemon url` is asked again.
10export const LINK_TTL_MS = 60000
11
12// The one web UI a link may open.
13export const UI_ORIGIN = 'https://datatug.app'
14
15// The web UI origin of a development host the person named in the plugin's settings: exactly
16// http(s)://datatug.localhost with an optional port, else null. Never taken from the CLI.
17export function parseDevHost(value) {
18  if (typeof value !== 'string') return null
19  const m = /^(https?):\/\/datatug\.localhost(?::(\d{1,5}))?\/?$/.exec(value.trim())
20  if (m === null) return null
21  if (m[2] !== undefined && (Number(m[2]) < 1 || Number(m[2]) > 65535 || m[2].startsWith('0'))) return null
22  return `${m[1]}://datatug.localhost${m[2] === undefined ? '' : `:${m[2]}`}`
23}
24
25// The three kinds `daemon url` prints, one per card.
26export const KINDS = { table: 'table-metadata', records: 'table-records', record: 'record', result: 'query-result' }
27
28// The views of a result page, as `daemon url --result --view=<view>` takes them.
29const RESULT_VIEWS = ['table', 'record', 'columns', 'sources', 'related']
30
31// The arguments after `datatug` for one card's link, or null when the request is not well formed.
32// `req`: { kind: 'table' | 'records' | 'record', db: a datatug:// reference, table, schema?,
33// isView?, limit?, key? (an object of primary-key column to value) }.
34export function urlArgs(req) {
35  if (req === null || typeof req !== 'object') return null
36  if (typeof req.db !== 'string' || !req.db.startsWith('datatug://')) return null
37  if (typeof req.table !== 'string' || req.table === '' || req.table.startsWith('-')) return null
38  const args = ['daemon', 'url', '--db', req.db, '--table', req.table]
39  if (typeof req.schema === 'string' && req.schema !== '') {
40    if (req.schema.startsWith('-')) return null
41    args.push('--schema', req.schema)
42  }
43  if (req.isView === true) args.push('--view')
44  if (req.kind === 'records') args.push('--records', '--limit', String(req.limit ?? 50))
45  else if (req.kind === 'record') {
46    if (req.key === null || typeof req.key !== 'object' || Object.keys(req.key).length === 0) return null
47    args.push('--record', JSON.stringify(req.key))
48  } else if (req.kind !== 'table') return null
49  args.push('--format', 'json')
50  return args
51}
52
53// The `startError` of a daemon that cannot start because a policy set exists and it names no principal.
54const START_POLICY = 'policy-principal-required'
55
56export const STATUS_ARGS = ['daemon', 'status', '--format', 'json']
57
58// What a card shows in place of a link, by state. None of them carries a link, a key or a row.
59export const MESSAGES = {
60  checking: 'Checking the DataTug web link…',
61  down: 'DataTug web link unavailable: the local DataTug agent is not running (datatug daemon start)',
62  'policy-principal': 'DataTug web link unavailable: a policy set exists but the DataTug agent has no principal. Run `datatug serve --as <principal>` or remove the policy set',
63  pending: 'The DataTug web UI cannot open this view yet',
64  'old-cli': `Open in DataTug needs datatug ${LINK_MIN_CLI_VERSION} or later: update the DataTug CLI (datatug self-update)`,
65  dev: 'This DataTug CLI points at a development web UI; no link',
66  unavailable: 'DataTug web link unavailable: the CLI did not give a link the mod can check',
67  'same-host': 'Open in DataTug works only on the machine that runs the agent',
68  'not-in-project': 'Add this database to a project to open it in DataTug',
69  'no-result': 'DataTug has no saved result for this call, so there is no web link',
70}
71
72export function sourceUnavailableText(name) {
73  return `No DataTug web link: start the DataTug agent from an environment that sets ${name}`
74}
75
76// Whether a link may be drawn where the card is drawn. Only the terminal is known to open a link on
77// the machine that runs the agent: the Desktop app, VS Code and mobile are remote surfaces, and a
78// terminal reached over SSH opens links on another machine.
79export function isSameHost(surface, ssh) {
80  return surface === 'terminal' && !ssh
81}
82
83function parseJson(text) {
84  try {
85    const at = String(text ?? '').indexOf('{')
86    return at < 0 ? null : JSON.parse(String(text).slice(at))
87  } catch {
88    return null
89  }
90}
91
92// An older CLI says so on stderr.
93export function isUnknownCommand(text) {
94  return /unknown (command|flag|shorthand flag)|no such command|invalid command|flag provided but not defined/i.test(String(text ?? ''))
95}
96
97// The port the daemon listens on, from `datatug daemon status --format json`, or null.
98export function statusPort(run) {
99  if (run === null || run.exitCode !== 0) return null
100  const doc = parseJson(run.stdout)
101  const port = doc?.port
102  return Number.isInteger(port) && port > 0 && port < 65536 ? port : null
103}
104
105// Decides what a card draws from the answers of `daemon status` and `daemon url`:
106// { status: 'ok', href } or { status } with a key of MESSAGES. `kind` is the card's (table, records,
107// record, result), `devOrigin` the configured development origin or null, `resultId` the id a
108// result link must name.
109export function readLink(statusRun, urlRun, kind, devOrigin, resultId) {
110  if (urlRun === null) return { status: 'down' }
111  if (urlRun.exitCode !== 0) return { status: isUnknownCommand(`${urlRun.stderr ?? ''}${urlRun.stdout ?? ''}`) ? 'old-cli' : 'unavailable' }
112  const doc = parseJson(urlRun.stdout)
113  if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) return { status: 'unavailable' }
114  if (doc.kind !== KINDS[kind]) return { status: typeof doc.kind === 'string' ? 'unavailable' : 'old-cli' }
115  if (kind === 'result' && doc.resultExists !== true) return { status: 'no-result' }
116  // A daemon that could not start for a named reason (`startError` of `daemon status` / `daemon start`).
117  if (doc.running !== true && (doc.startError === START_POLICY || parseJson(statusRun?.stdout)?.startError === START_POLICY)) return { status: 'policy-principal' }
118  if (doc.uiSupport !== 'available') return { status: 'pending' }
119  if (doc.running !== true) return { status: 'down' }
120  const port = statusPort(statusRun)
121  if (port === null) return { status: 'unavailable' }
122  return checkHref(doc.url, kind, port, devOrigin, resultId)
123}
124
125// What encodeURIComponent leaves as it is, and percent escapes.
126const PARAM = /^[A-Za-z0-9._~%!'()*-]*$/
127
128function params(text) {
129  const out = new Map()
130  if (text === '') return out
131  for (const part of text.split('&')) {
132    const eq = part.indexOf('=')
133    if (eq <= 0) return null
134    const name = part.slice(0, eq)
135    const value = part.slice(eq + 1)
136    if (out.has(name) || !PARAM.test(value)) return null
137    out.set(name, value)
138  }
139  return out
140}
141
142// Re-checks a link the CLI printed against the fixed allow-list before it is drawn:
143// https://datatug.app (or the configured development origin), the agent's own store path on
144// 127.0.0.1:<port>, no credentials, no second scheme, at most 2048 characters, only the expected
145// query and fragment parameters, and a one-time code in the fragment.
146export function checkHref(url, kind, port, devOrigin, resultId) {
147  if (typeof url !== 'string' || url === '' || url.length > 2048) return { status: 'unavailable' }
148  const m = /^(https?:\/\/[^/?#]*)([^?#]*)(?:\?([^#]*))?(?:#(.*))?$/s.exec(url)
149  if (m === null) return { status: 'unavailable' }
150  const [, origin, path, query = '', fragment = ''] = m
151  if (origin !== UI_ORIGIN && (devOrigin === null || origin !== devOrigin)) return { status: /^https?:\/\/[A-Za-z0-9.-]+(:\d+)?$/.test(origin) ? 'dev' : 'unavailable' }
152  const rest = url.slice(origin.length)
153  if (url.split('#')[0].includes('@') || rest.includes('://') || /[\s\\<>"`{}|^]/.test(url)) return { status: 'unavailable' }
154  const store = `/store/http-127.0.0.1:${port}/`
155  // A dot segment, written plainly or percent-encoded, would climb out of the agent's store path.
156  if (!path.startsWith(store) || /(^|\/)(\.|%2e){1,2}(\/|$)/i.test(path)) return { status: 'unavailable' }
157  const q = params(query)
158  const f = params(fragment)
159  if (q === null || f === null) return { status: 'unavailable' }
160  // A result link names the result by its id alone: exactly <store>result/<id>?view=<view>[&row=<n>].
161  if (kind === 'result') {
162    if (typeof resultId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(resultId) || path !== `${store}result/${resultId}`) return { status: 'unavailable' }
163    if (![...q.keys()].every(k => k === 'view' || k === 'row') || !RESULT_VIEWS.includes(q.get('view') ?? '')) return { status: 'unavailable' }
164    if (q.has('row') && !/^[1-9]\d{0,4}$/.test(q.get('row'))) return { status: 'unavailable' }
165    if (![...f.keys()].every(k => k === 'code')) return { status: 'unavailable' }
166    if (!f.has('code') || f.get('code') === '') return { status: 'old-cli' }
167    return { status: 'ok', href: url }
168  }
169  const wantQuery = kind === 'records' ? ['limit', 'schema'] : ['schema']
170  if (![...q.keys()].every(k => wantQuery.includes(k)) || !q.has('schema') || (kind === 'records' && !q.has('limit'))) return { status: 'unavailable' }
171  if (![...f.keys()].every(k => k === 'code' || (kind === 'record' && k === 'pk'))) return { status: 'unavailable' }
172  // A link with no one-time code does not open: it comes from a CLI older than the access model.
173  if (!f.has('code') || f.get('code') === '') return { status: 'old-cli' }
174  if (kind === 'record' && (!f.has('pk') || f.get('pk') === '')) return { status: 'unavailable' }
175  return { status: 'ok', href: url }
176}
177
178// The raw JSON text of each top-level field of one JSON object (one line of `--format jsonl`), so
179// a key column is read without JSON.parse rounding an integer above 2^53 - 1. Null when the text is
180// not one object.
181export function rawFields(line) {
182  const s = String(line ?? '')
183  let i = 0
184  const ws = () => {
185    while (i < s.length && ' \t\r\n'.includes(s[i])) i++
186  }
187  const str = () => {
188    const start = i
189    if (s[i] !== '"') return null
190    i++
191    while (i < s.length && s[i] !== '"') i += s[i] === '\\' ? 2 : 1
192    if (i >= s.length) return null
193    i++
194    return s.slice(start, i)
195  }
196  const value = () => {
197    const start = i
198    if (s[i] === '"') return str()
199    if (s[i] === '{' || s[i] === '[') {
200      let depth = 0
201      while (i < s.length) {
202        const c = s[i]
203        if (c === '"') {
204          if (str() === null) return null
205          continue
206        }
207        if (c === '{' || c === '[') depth++
208        if (c === '}' || c === ']') depth--
209        i++
210        if (depth === 0) return s.slice(start, i)
211      }
212      return null
213    }
214    while (i < s.length && !',}] \t\r\n'.includes(s[i])) i++
215    return i > start ? s.slice(start, i) : null
216  }
217  const out = {}
218  ws()
219  if (s[i] !== '{') return null
220  i++
221  ws()
222  if (s[i] === '}') return out
223  while (i < s.length) {
224    ws()
225    const k = str()
226    if (k === null) return null
227    ws()
228    if (s[i] !== ':') return null
229    i++
230    ws()
231    const v = value()
232    if (v === null) return null
233    let name
234    try {
235      name = JSON.parse(k)
236    } catch {
237      return null
238    }
239    out[name] = v
240    ws()
241    if (s[i] === ',') {
242      i++
243      continue
244    }
245    if (s[i] === '}') return out
246    return null
247  }
248  return null
249}
250
251const MAX_SAFE = 9007199254740991n
252const MAX_KEY_TEXT = 256
253
254// One key value from its raw JSON text: an integer stays a number while JavaScript holds it exactly
255// and becomes its digits as a string above that; a string stays a string. Null, an object, an
256// array, a boolean or a value over 256 characters gives no record link.
257export function keyValue(raw) {
258  if (typeof raw !== 'string') return { why: 'a key value is missing' }
259  const text = raw.trim()
260  if (text.startsWith('"')) {
261    let v
262    try {
263      v = JSON.parse(text)
264    } catch {
265      return { why: 'a key value cannot be read' }
266    }
267    if (v === '' || Array.from(v).length > MAX_KEY_TEXT) return { why: 'a key value is empty or longer than 256 characters' }
268    return { value: v }
269  }
270  if (/^-?(0|[1-9]\d*)$/.test(text)) {
271    const big = BigInt(text)
272    return { value: big > MAX_SAFE || big < -MAX_SAFE ? text : Number(text) }
273  }
274  if (/^-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?$/.test(text)) return { why: 'a key value is not a whole number or text' }
275  return { why: 'a key value is empty, binary or not a plain value' }
276}
277
278// The top-level integer fields of one JSON line that JavaScript cannot hold exactly, as their
279// digits (JSON.parse would round them), or null when there are none: all a row needs kept besides
280// its parsed values for a lossless record key.
281export function bigIntegers(line) {
282  const fields = rawFields(line)
283  if (fields === null) return null
284  const out = {}
285  for (const [name, raw] of Object.entries(fields)) {
286    const v = /^-?(0|[1-9]\d*)$/.test(raw) ? keyValue(raw) : null
287    if (v !== null && typeof v.value === 'string') out[name] = v.value
288  }
289  return Object.keys(out).length === 0 ? null : out
290}
291
292// The record key for a Record link, from the declared primary-key columns (in key order), the
293// parsed row and its big integers (bigIntegers): { key } or { why } (the one line the card shows in
294// place of the link).
295export function recordKey(pkColumns, row, big) {
296  if (!Array.isArray(pkColumns) || pkColumns.length === 0) return { why: 'the table has no declared primary key' }
297  if (row === null || typeof row !== 'object') return { why: 'the record cannot be read' }
298  const key = {}
299  for (const col of pkColumns) {
300    const name = Object.keys(row).find(f => f !== '$key' && f.toLowerCase() === String(col).toLowerCase())
301    if (name === undefined) return { why: 'a key value is missing' }
302    const value = row[name]
303    let v
304    if (big != null && typeof big[name] === 'string') v = { value: big[name] }
305    else if (typeof value === 'number') v = Number.isSafeInteger(value) ? { value } : { why: 'a key value is not a whole number or text' }
306    else if (typeof value === 'string') v = keyValue(JSON.stringify(value))
307    else v = { why: 'a key value is empty, binary or not a plain value' }
308    if ('why' in v) return v
309    key[name] = v.value
310  }
311  return { key }
312}
313
314// A short, stable fingerprint of a request, so session state never holds a key value or a link.
315export function fingerprint(text) {
316  let h = 0x811c9dc5
317  for (let i = 0; i < text.length; i++) {
318    h ^= text.charCodeAt(i)
319    h = Math.imul(h, 0x01000193) >>> 0
320  }
321  return h.toString(16).padStart(8, '0')
322}
323
lib/results.js 270 lines
1// The result files `datatug query run --result-id` writes, as the chat card reads them. Pure: the
2// hooks module runs the CLI and reads the files.
3import { stripUnsafe } from './text.js'
4
5// The first datatug release that writes both result files with columns, sources and related tables.
6export const CARD_MIN_CLI_VERSION = '0.92.0'
7// The first release with `datatug ui --result` and `daemon url --result`: the command and the link.
8export const OPEN_MIN_CLI_VERSION = '0.94.0'
9
10// The first release with `daemon url --result-view <view>`; older ones take `--view=<view>`.
11export const RESULT_VIEW_MIN_CLI_VERSION = '0.98.0'
12
13export const VIEWS = ['table', 'record', 'columns', 'sources', 'related']
14export const VIEW_LABELS = { table: 'Table', record: 'Record', columns: 'Columns', sources: 'Sources', related: 'Related' }
15
16// Bounds the mod holds itself to, whatever the files say.
17export const MAX_META_BYTES = 1 << 20
18export const MAX_DATA_BYTES = 4_000_000
19export const MAX_ROWS = 2000
20export const MAX_COLUMNS = 400
21export const MAX_PARTICIPANTS = 32
22export const MAX_RELATED = 200
23const NAME = 80
24
25const ID = /^[A-Za-z0-9_-]{1,128}$/
26
27// The result id of a tool call: its tool_use_id with every other character made `_`.
28export function resultId(toolUseId) {
29  const id = String(toolUseId ?? '').replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 128)
30  return ID.test(id) ? id : null
31}
32
33export const isResultId = id => typeof id === 'string' && ID.test(id)
34
35// What the model or the card reads when a step fails.
36export const TEXT = {
37  oldCli: 'DataTug is older than the mod expects; run the query again',
38  rerun: 'Run the query again',
39  ran: 'The DataTug query ran; its result is shown to the user in a card, not to Claude.',
40  background: 'The DataTug query went to the background; the user can load its result in the card when it is done. Its rows are withheld from you.',
41}
42
43// The line the card shows for a state that has no result to draw.
44export const STATE_TEXT = {
45  load: 'Press Load to show these results again',
46  loading: 'Reading the result files…',
47  expired: 'These results expired (DataTug keeps them 7 days). Run the query again',
48  'not-found': 'No saved result for this call (removed, or run without result files)',
49  incomplete: 'The result files are not complete yet. Press Load to try again',
50  unreadable: 'The result files are not readable, so nothing was read',
51  'too-large': 'This result is too large to show here, so nothing was read',
52  inconsistent: 'The result files do not agree with each other, so nothing was read. Run the query again',
53  version: 'Update the DataTug mod: these result files are of a newer version',
54  'no-locator': 'DataTug did not report its result files',
55}
56
57// Why the session went back to the plain grid, as the card's dim line says it.
58export const LEGACY_TEXT = {
59  'old-cli': 'Update the DataTug CLI for the Record, Columns, Sources and Related views',
60  sandbox: "Allow DataTug's result store (~/.datatug/query-results) in the sandbox's writable paths to see every view",
61  'inside-git': 'Every view needs the result store, and your home directory is a Git repository',
62  symlink: 'Every view needs the result store, and ~/.datatug/query-results is a symbolic link',
63  owner: 'Every view needs the result store, and ~/.datatug/query-results belongs to another user',
64  'results-store-unwritable': 'Every view needs the result store, and ~/.datatug/query-results cannot be written',
65}
66
67export const UNAVAILABLE_TEXT = {
68  'native-sql': 'Sources are not known for a native SQL query',
69  'no-relationship-metadata': 'No related tables found',
70  'schema-unreadable': 'The schema of this database could not be read',
71  'too-many': 'Only the first entries are listed',
72  'too-large': 'The query was too large to keep',
73}
74
75function parseLine(text, prefix) {
76  for (const line of String(text ?? '').split('\n')) {
77    const t = line.trim()
78    if (!t.startsWith(prefix)) continue
79    try {
80      return JSON.parse(t)
81    } catch {
82      return null
83    }
84  }
85  return null
86}
87
88// How a failed `query run --result-id` turns the session back to the plain grid: an older CLI
89// prints `unknown flag: --result-id`; a sandboxed shell gets the store failure line. Null otherwise.
90export function fallbackOf(errorText) {
91  const text = String(errorText ?? '')
92  if (/^\s*unknown flag: --result-id\.?\s*$/m.test(text)) return 'old-cli'
93  const doc = parseLine(text, '{"resultFiles"')
94  if (doc !== null && doc.resultFiles === null && doc.reason === 'results-store-unwritable') return 'sandbox'
95  return null
96}
97
98// `query results check --format json`: null when usable, else the reason code.
99export function storeProblem(stdout) {
100  const doc = parseLine(stdout, '{')
101  if (doc === null || typeof doc !== 'object') return 'results-store-unwritable'
102  if (doc.usable === true) return null
103  return typeof doc.reason === 'string' && LEGACY_TEXT[doc.reason] !== undefined ? doc.reason : 'results-store-unwritable'
104}
105
106const hasDots = p => p.split('/').some(s => s === '.' || s === '..')
107
108// Checks the answer of `query results locate --id <id> --format json`:
109// { files: { root, data, meta } } or { state } (a key of STATE_TEXT).
110export function readLocator(stdout, id) {
111  const doc = parseLine(stdout, '{"resultFiles"')
112  if (doc === null || typeof doc !== 'object') return { state: 'no-locator' }
113  if (doc.resultFiles === null) return { state: doc.reason === 'expired' ? 'expired' : doc.reason === 'incomplete' ? 'incomplete' : 'not-found' }
114  const f = doc.resultFiles
115  if (f === null || typeof f !== 'object' || f.version !== 1 || f.id !== id || !isResultId(id)) return { state: 'unreadable' }
116  const { root, data, meta } = f
117  if (typeof root !== 'string' || !root.startsWith('/') || root.length < 2 || root.endsWith('/') || hasDots(root) || /[\0\n\r]/.test(root)) return { state: 'unreadable' }
118  if (data !== `${root}/${id}/data.json` || meta !== `${root}/${id}/meta.json`) return { state: 'unreadable' }
119  return { files: { root, data, meta } }
120}
121
122// Whether a stat answer is a regular file that resolves to exactly `want` under the resolved root.
123export function statLandsAt(stat, realRoot, want) {
124  return stat !== null && typeof stat === 'object' && stat.kind === 'file' && typeof stat.realPath === 'string' && typeof realRoot === 'string' && stat.realPath === want && stat.realPath.startsWith(`${realRoot}/`)
125}
126
127const name = v => stripUnsafe(String(v ?? '')).replace(/\s+/g, ' ').trim().slice(0, NAME)
128const optName = v => (v === null || v === undefined ? null : name(v))
129const ref = v => (typeof v === 'string' && isRef(v) ? v : null)
130
131// A datatug://<project>/<db>[?env=<env>] reference: plain characters, no credential.
132export function isRef(url) {
133  const part = String.raw`(?:[A-Za-z0-9._~-]|%(?!40|3a)[0-9a-f]{2})`
134  return new RegExp(`^datatug://${part}+/${part}+(\\?env=${part}+)?$`, 'i').test(url)
135}
136
137// What "More rows" needs to read a table again: kept as written (a cleaned name would be a different
138// table), and only when it is a bounded plain string. Nothing is drawn from these.
139const MAX_QUERY_TEXT = 4096
140const raw = (v, max) => (typeof v === 'string' && v.length <= max && !/[\0-\x1f\x7f]/.test(v) ? v : null)
141const queryOf = q => ({
142  from: raw(q?.from, 256),
143  policy: raw(q?.policy, 40),
144  dbRef: raw(q?.dbRef, 512),
145  text: typeof q?.text === 'string' && q.text.length <= MAX_QUERY_TEXT ? q.text : null,
146})
147
148// meta.json as the card keeps it: names cleaned and cut, bounds applied, nothing else.
149// { meta } or { state } ('version' for a version the mod does not know, 'unreadable').
150export function readMeta(text, id) {
151  let doc
152  try {
153    doc = JSON.parse(text)
154  } catch {
155    return { state: 'unreadable' }
156  }
157  if (doc === null || typeof doc !== 'object' || doc.format !== 'datatug.query-result.meta') return { state: 'unreadable' }
158  if (doc.version !== 1) return { state: 'version' }
159  if (doc.id !== id || !Number.isSafeInteger(doc.dataBytes) || doc.dataBytes < 0) return { state: 'unreadable' }
160  const db = doc.db ?? {}
161  const rows = doc.rows ?? {}
162  const un = doc.unavailable ?? {}
163  const reason = v => (typeof v === 'string' && /^[a-z-]{1,40}$/.test(v) ? v : undefined)
164  const columns = (Array.isArray(doc.columns) ? doc.columns : []).slice(0, MAX_COLUMNS).map(c => ({
165    name: name(c?.name),
166    type: name(c?.type),
167    declaredType: optName(c?.declaredType),
168    nullable: typeof c?.nullable === 'boolean' ? c.nullable : null,
169    pk: Number.isSafeInteger(c?.pk) && c.pk > 0 ? c.pk : null,
170    source: c?.source && typeof c.source === 'object' ? { instance: name(c.source.instance), schema: name(c.source.schema), relation: name(c.source.relation), column: name(c.source.column) } : null,
171    foreignKeys: (Array.isArray(c?.foreignKeys) ? c.foreignKeys : []).slice(0, 8).map(f => ({ refSchema: name(f?.refSchema), refRelation: name(f?.refRelation), refColumn: name(f?.refColumn) })),
172    encoding: optName(c?.encoding),
173  }))
174  const participants = (Array.isArray(doc.participants) ? doc.participants : []).slice(0, MAX_PARTICIPANTS).map(p => ({
175    instance: name(p?.instance),
176    schema: name(p?.schema),
177    relation: name(p?.relation),
178    alias: name(p?.alias),
179    db: ref(p?.db),
180    kind: name(p?.kind),
181    role: name(p?.role),
182    on: (Array.isArray(p?.join?.on) ? p.join.on : []).slice(0, 8).map(o => ({ left: name(o?.left), right: name(o?.right) })),
183  }))
184  const related = (Array.isArray(doc.related) ? doc.related : []).slice(0, MAX_RELATED).map(r => ({
185    fromInstance: name(r?.fromInstance),
186    schema: name(r?.target?.schema),
187    relation: name(r?.target?.relation),
188    kind: name(r?.target?.kind),
189    direction: r?.direction === 'incoming' ? 'incoming' : 'outgoing',
190    cardinality: name(r?.cardinality),
191    fields: (Array.isArray(r?.fields) ? r.fields : []).slice(0, 8).map(f => ({ source: name(f?.sourceField), target: name(f?.targetField) })),
192  }))
193  const dbRef = ref(db.ref)
194  return {
195    meta: {
196      dataBytes: doc.dataBytes,
197      db: { ref: dbRef, project: dbRef === null ? null : optName(db.project), env: dbRef === null ? null : optName(db.env), source: dbRef === null ? null : optName(db.source), driver: name(db.driver) },
198      kind: name(doc.query?.kind),
199      savedId: optName(doc.query?.savedQueryId) || null,
200      query: queryOf(doc.query),
201      rows: { kept: Number.isSafeInteger(rows.kept) ? rows.kept : 0, hasMore: rows.hasMore === true },
202      columns,
203      participants,
204      related,
205      unavailable: { participants: reason(un.participants), related: reason(un.related), declaredTypes: reason(un.declaredTypes), columns: reason(un.columns), query: reason(un.query) },
206      counts: { columns: Array.isArray(doc.columns) ? doc.columns.length : 0, participants: participants.length, related: related.length },
207    },
208  }
209}
210
211// data.json: the column names and, per row, each cell as its text (null for a null), at most
212// MAX_ROWS rows. An integer stays the digits the CLI wrote. Null when it is not a data file of `id`.
213export function readData(text, id) {
214  let doc
215  try {
216    doc = JSON.parse(text)
217  } catch {
218    return null
219  }
220  if (doc === null || typeof doc !== 'object' || doc.format !== 'datatug.query-result.data' || doc.version !== 1 || doc.id !== id) return null
221  const rs = doc.recordset
222  if (rs === null || typeof rs !== 'object' || !Array.isArray(rs.columns) || !Array.isArray(rs.rows)) return null
223  const columns = rs.columns.map(c => String(c?.name ?? ''))
224  const types = rs.columns.map(c => String(c?.type ?? ''))
225  const rows = rs.rows.slice(0, MAX_ROWS).map(r =>
226    columns.map((_, i) => {
227      const v = Array.isArray(r) ? r[i]?.value : undefined
228      return v === null || v === undefined ? null : typeof v === 'object' ? JSON.stringify(v) : String(v)
229    }),
230  )
231  return { columns, types, rows }
232}
233
234const list = (names, max) => {
235  const shown = names.slice(0, max).map(n => name(n)).filter(n => n !== '')
236  return names.length > max ? `${shown.join(', ')} and ${names.length - max} more` : shown.join(', ')
237}
238
239// What the model reads in place of the result: the row count, the column, source and related
240// table names, and never a value, a path, an id, a link or a command.
241export function resultSummary(meta) {
242  const kept = meta.rows.kept
243  const cols = meta.columns.map(c => c.name).filter(n => n !== '$key')
244  const more = meta.counts.columns - meta.columns.length
245  const parts = [
246    `DataTug query returned ${kept} row${kept === 1 ? '' : 's'}${meta.rows.hasMore ? ` (at least ${kept + 1} exist; the first ${kept} were kept)` : ''} x ${cols.length + Math.max(0, more)} column${cols.length === 1 ? '' : 's'}: ${list(cols, 40)}${more > 0 ? ` (and ${more} more)` : ''}.`,
247  ]
248  const sources = meta.participants.map(p => (p.schema === '' || p.schema === 'main' ? p.relation : `${p.schema}.${p.relation}`))
249  if (sources.length > 0) parts.push(`It reads ${list(sources, 32)}.`)
250  const related = [...new Set(meta.related.map(r => (r.schema === '' || r.schema === 'main' ? r.relation : `${r.schema}.${r.relation}`)))]
251  if (related.length > 0) parts.push(`Tables that can be joined to it: ${list(related, 50)}.`)
252  parts.push('The rows are shown to the user in a DataTug result card and are withheld from you.')
253  return parts.join(' ')
254}
255
256// The arguments after `datatug` for the link of a result's view, or null. `isViewFlag`: the CLI
257// has `--result-view` (RESULT_VIEW_MIN_CLI_VERSION); otherwise the view goes as `--view=<view>`.
258export function resultUrlArgs(id, view, row, isViewFlag = false) {
259  if (!isResultId(id) || !VIEWS.includes(view)) return null
260  const args = ['daemon', 'url', '--result', id, ...(isViewFlag ? ['--result-view', view] : [`--view=${view}`])]
261  if (view === 'record' && Number.isSafeInteger(row) && row >= 1 && row <= 10000) args.push('--row', String(row))
262  args.push('--format', 'json')
263  return args
264}
265
266// The command that opens the result in the terminal UI, or null for an id that would need quoting.
267export function uiCommand(id) {
268  return isResultId(id) ? `datatug ui --result ${id}` : null
269}
270
lib/annotate.js 32 lines
1// The person's prompt, handed to the datatug CLI so it is stored with the result it led to. Pure:
2// the hooks module runs the CLI.
3
4// The first datatug release with `query results annotate`: v0.101.0, cut at datatug-cli#431's merge
5// commit 1423e765. A CLI without the verb is not an error either way: the call is best effort and silent.
6export const ANNOTATE_MIN_CLI_VERSION = '0.101.0'
7
8// The CLI cuts the prompt to 8 KiB itself; the mod only keeps a pasted novel from becoming a huge stdin.
9// Characters are at least one byte each, so this is always above the CLI's own cut.
10export const MAX_PROMPT_CHARS = 16384
11
12// The origins that are the person's own words: Enter at the prompt, a Remote Control client, an SDK or
13// `claude -p` turn, or a plugin's prompt submitted as the person's (`asUser`). A notification, a peer
14// session, a schedule or a plugin speaking for itself is not a prompt the person wrote.
15export function isPersonPrompt(origin) {
16  const kind = origin?.kind
17  if (kind === 'composer' || kind === 'bridge' || kind === 'sdk') return true
18  return kind === 'plugin' && origin.asUser === true
19}
20
21// What the mod keeps of a submitted prompt, or null for text that is not a prompt of the person's.
22export function keptPrompt(text, origin) {
23  if (!isPersonPrompt(origin) || typeof text !== 'string') return null
24  const t = text.trim()
25  return t === '' ? null : t.slice(0, MAX_PROMPT_CHARS)
26}
27
28// The arguments after `datatug`. The prompt is never among them: it goes to the process's standard input.
29export function annotateArgs(id) {
30  return ['query', 'results', 'annotate', '--id', id, '--prompt-stdin']
31}
32
lib/more.js 87 lines
1// "More rows" for a result card: when a result is a plain table read, the card can read the same table
2// again with another row count. Pure: the hooks module runs the CLI. Nothing here reads a row, and the
3// model is never told: the re-run is the card's own call, not a tool call.
4import { LEGACY_TEXT, isRef, isResultId } from './results.js'
5
6// The row counts the buttons offer; 500 is the cap (the CLI keeps 2000 rows by default, so none needs
7// --result-rows).
8export const ROW_COUNTS = [10, 50, 100, 500]
9
10// A table name the card will put in an argument: plain characters, nothing a CLI flag, a path or a
11// shell could read as more than a name. `--from=<table>` is also one argument, never `--from <table>`.
12const TABLE = /^[A-Za-z0-9_][A-Za-z0-9_.$-]*$/
13const MAX_TABLE = 128
14
15// The dim line the card shows in place of the buttons, per reason: names the reason, never a value.
16export const MORE_TEXT = {
17  saved: 'Rows buttons need a table read; this result is a saved query',
18  kind: 'Rows buttons need a table read; this result is a query written in TugQL',
19  policy: 'Rows buttons need a table read without policies',
20  ref: 'Rows buttons need a database that is in a project',
21  offset: 'Rows buttons need a table read from the first row',
22  table: 'Rows buttons need a plain table name',
23  id: 'Rows buttons need a shorter result id',
24  old: 'Rows buttons need a newer DataTug CLI',
25}
26
27// The id of the result a row count writes: the first result's id, `-r`, the count. A result id is at
28// most 128 characters of `A-Za-z0-9_-`; null for anything else.
29export function moreId(base, n) {
30  if (!ROW_COUNTS.includes(n) || !isResultId(base)) return null
31  const id = `${base}-r${n}`
32  return isResultId(id) ? id : null
33}
34
35// Whether the displayed result (its CardMeta, `base` the first result's id) may be read again with
36// another row count: { ok: true, table, dbRef } or { ok: false, reason } (a key of MORE_TEXT).
37// Only a table read without policies qualifies: the CLI takes --limit only with --from, and a replay with
38// --no-policies must never be wider than the original run.
39export function moreGate(meta, base) {
40  const q = meta?.query
41  if (meta?.kind === 'saved') return { ok: false, reason: 'saved' }
42  if (meta?.kind !== 'from') return { ok: false, reason: 'kind' }
43  if (q === undefined || q === null || typeof q.policy !== 'string' || typeof q.text !== 'string' || typeof q.from !== 'string') return { ok: false, reason: 'old' }
44  if (q.policy !== 'none') return { ok: false, reason: 'policy' }
45  if (typeof q.dbRef !== 'string' || !isRef(q.dbRef)) return { ok: false, reason: 'ref' }
46  if (/offset["']?\s*:/i.test(q.text)) return { ok: false, reason: 'offset' }
47  if (q.from.length > MAX_TABLE || !TABLE.test(q.from)) return { ok: false, reason: 'table' }
48  // The longest id there is, so one verdict holds for every button.
49  if (moreId(base, 500) === null) return { ok: false, reason: 'id' }
50  return { ok: true, table: q.from, dbRef: q.dbRef }
51}
52
53// The arguments after `datatug` for the re-run, or null when anything is off. Fixed shape, no shell:
54// each value is one argument, and the table cannot be read as a flag (it follows `--from=`).
55export function moreArgs(dbRef, table, n, id) {
56  if (!ROW_COUNTS.includes(n) || typeof dbRef !== 'string' || !isRef(dbRef)) return null
57  if (typeof table !== 'string' || table.length > MAX_TABLE || !TABLE.test(table)) return null
58  if (typeof id !== 'string' || !isResultId(id) || !id.endsWith(`-r${n}`)) return null
59  return ['query', 'run', `--db=${dbRef}`, `--from=${table}`, `--limit=${n}`, '--no-policies', '--result-id', id, '--format', 'json']
60}
61
62// The reason code of a failed `query run --result-id`: the failure line on stdout, else the store's
63// message on stderr. Null for anything else; never any other text.
64export function failureReason(stdout, stderr) {
65  for (const line of String(stdout ?? '').split('\n')) {
66    const t = line.trim()
67    if (!t.startsWith('{"resultFiles"')) continue
68    try {
69      const doc = JSON.parse(t)
70      if (doc?.resultFiles === null && typeof doc.reason === 'string' && /^[a-z-]{1,40}$/.test(doc.reason)) return doc.reason
71    } catch {
72      return null
73    }
74  }
75  const m = /query results: ([a-z-]{1,40})\s*$/m.exec(String(stderr ?? ''))
76  return m === null ? null : m[1]
77}
78
79// The card's line for a failed re-run: path-free, and the reasons the store names are said as the
80// card says them elsewhere.
81export function moreErrorText(reason) {
82  if (reason !== null && Object.hasOwn(LEGACY_TEXT, reason)) return LEGACY_TEXT[reason]
83  if (reason === 'unreachable') return 'The DataTug CLI did not answer. Try again'
84  if (reason === 'unshown') return 'The new rows could not be shown. Try again'
85  return 'DataTug could not read those rows. Try again'
86}
87
lib/command.js 10 lines
1// How `/datatug` is told apart from `/datatug project`. Pure.
2
3// The argument that asks for the project pane of the folder (the four tabs and the text summary)
4// instead of the panel.
5export const PROJECT_ARG = 'project'
6
7export function isProjectView(args) {
8  return typeof args === 'string' && args.trim().toLowerCase() === PROJECT_ARG
9}
10
lib/bash.js 376 lines
1// Which Bash commands run `datatug query run`, which of them the mod may rewrite, and which name
2// the private result files. Pure: the hooks module runs the commands and answers the model.
3
4// The reasons the model reads for a refused command.
5export const PLAIN_TEXT =
6  'Run DataTug queries as a plain `datatug query run ...` command, without shell syntax or unbalanced quotes (quote only whole arguments); put a complex query in a TugQL file and pass it with -f'
7export const BACKGROUND_TEXT = 'DataTug queries cannot run in the background'
8export const STORE_TEXT =
9  "DataTug query results are shown in the card, not to Claude. Run `datatug query run --db '<datatug:// ref>' --from <table> --limit N --no-policies`, quoting the ref (it is in the prompt); the rows appear in the card; never read the store or look for connection strings"
10// The one answer of a hook that failed: constant, so answering it can never fail.
11export const FAILED_TEXT = 'The DataTug mod could not show the result of this query, so it did not hand it to Claude'
12
13// Shell syntax a plain command never holds, quoted or not.
14const SHELL = /[|;&<>$`()\n\r#\\]/
15
16// Words after which the next word is a command again.
17const RESERVED = new Set(['then', 'do', 'else', 'elif', 'while', 'until', 'if', '!', '{'])
18// Words that run the command they are given, with options of their own before it.
19// Compared by the word's basename, ignoring case (`/usr/bin/env` is env). zsh's precommand
20// modifiers (`noglob`, `nocorrect`, `-`) and `repeat N` are among them.
21const WRAPPERS = new Set(['env', 'time', 'timeout', 'gtimeout', 'nice', 'nohup', 'stdbuf', 'caffeinate', 'watch', 'command', 'exec', 'sudo', 'doas', 'xargs', 'builtin', 'script', 'unbuffer', 'npx', 'chronic', 'ionice', 'taskset', 'flock', 'setsid', 'noglob', 'nocorrect', '-', 'repeat', 'arch', 'coproc', 'ltrace', 'strace', 'sandbox-exec'])
22// Commands whose words are never run: a `datatug ... query run` among their arguments is text.
23const READERS = new Set(['echo', 'printf', 'rg', 'grep', 'egrep', 'fgrep', 'git', 'gh', 'specscore', 'man', 'which', 'type', 'whatis', 'apropos'])
24const base = w => String(w).toLowerCase().replace(/^.*\//, '')
25// Options of another command after which the next word is a command (`find ... -exec`).
26const EXEC_OPTIONS = new Set(['-exec', '-execdir', '-ok', '-okdir'])
27const ASSIGNMENT = /^[A-Za-z_]\w*=/
28// The datatug command: a path ending in it, zsh's `=datatug`, in any case (macOS disks ignore case).
29const DATATUG = /^=?(?:.*\/)?datatug$/i
30
31// A double-quoted part that substitutes a command (`$(` or a backtick) is made plain text: the shell
32// runs what is inside it, so it is looked at as commands.
33export function unsubstitute(text) {
34  const s = String(text ?? '')
35  let out = ''
36  let i = 0
37  while (i < s.length) {
38    const c = s[i]
39    if (c === '\\') {
40      out += s.slice(i, i + 2)
41      i += 2
42      continue
43    }
44    if (c === "'") {
45      const end = s.indexOf("'", i + 1)
46      const stop = end < 0 ? s.length : end + 1
47      out += s.slice(i, stop)
48      i = stop
49      continue
50    }
51    if (c === '"') {
52      let j = i + 1
53      while (j < s.length && s[j] !== '"') j += s[j] === '\\' ? 2 : 1
54      const stop = Math.min(s.length, j + 1)
55      const part = s.slice(i + 1, Math.min(j, s.length))
56      out += /\$\(|`/.test(part) ? ` ${part} ` : s.slice(i, stop)
57      i = stop
58      continue
59    }
60    out += c
61    i++
62  }
63  return out
64}
65
66// Splits text into words and separators as the shell reads them: quotes and backslashes are removed
67// from a word (`'query'`, `"run"` and `\datatug` are the words query, run and datatug), and a quoted
68// space does not end one. `$(` is one separator; `<` and `>` count as separators too, so a word after
69// a redirection is looked at as a command (safe in the direction that matters).
70export function lex(text) {
71  const out = []
72  let word = ''
73  let started = false
74  const flush = () => {
75    if (started) out.push({ word })
76    word = ''
77    started = false
78  }
79  for (let i = 0; i < text.length; i++) {
80    const c = text[i]
81    if (c === '$' && (text[i + 1] === "'" || text[i + 1] === '"')) {
82      // `$'...'` (ANSI-C quoting, escapes decoded) and `$"..."` (a locale string) are quotes too.
83      if (text[i + 1] === '"') continue
84      let j = i + 2
85      while (j < text.length && text[j] !== "'") {
86        if (text[j] === '\\' && j + 1 < text.length) {
87          const m = /^(?:x([0-9a-fA-F]{1,2})|u([0-9a-fA-F]{1,4})|U([0-9a-fA-F]{1,8})|([0-7]{1,3})|(.))/s.exec(text.slice(j + 1))
88          const code = m[1] ?? m[2] ?? m[3]
89          const named = { n: '\n', t: '\t', r: '\r', a: '\u0007', b: '\b', e: '\u001b', E: '\u001b', f: '\f', v: '\v' }
90          word += code !== undefined ? String.fromCodePoint(parseInt(code, 16) || 0) : m[4] !== undefined ? String.fromCharCode(parseInt(m[4], 8)) : (named[m[5]] ?? m[5])
91          j += 1 + m[0].length
92        } else word += text[j++]
93      }
94      started = true
95      i = j
96    } else if (c === '\\') {
97      if (text[i + 1] === '\n') {
98        i++
99        continue
100      }
101      if (i + 1 < text.length) word += text[++i]
102      started = true
103    } else if (c === "'") {
104      const end = text.indexOf("'", i + 1)
105      const stop = end < 0 ? text.length : end
106      word += text.slice(i + 1, stop)
107      started = true
108      i = stop
109    } else if (c === '"') {
110      let j = i + 1
111      while (j < text.length && text[j] !== '"') {
112        if (text[j] === '\\' && j + 1 < text.length) {
113          word += text[j + 1]
114          j += 2
115        } else word += text[j++]
116      }
117      started = true
118      i = j
119    } else if (c === ' ' || c === '\t') {
120      flush()
121    } else if (c === '$' && text[i + 1] === '(') {
122      flush()
123      out.push({ sep: '$(' })
124      i++
125    } else if ('\n\r;&|()`{}!<>'.includes(c)) {
126      // `{`, `}` and `!` are separators only as words of their own.
127      if ('{}!'.includes(c) && (started || (text[i + 1] !== undefined && !' \t\n'.includes(text[i + 1])))) {
128        word += c
129        started = true
130        continue
131      }
132      flush()
133      out.push({ sep: c })
134    } else {
135      word += c
136      started = true
137    }
138  }
139  flush()
140  return out
141}
142
143// The words after `datatug` of each datatug command in command position: at the start, after a
144// separator or a reserved word, after `VAR=` assignments, as the command a wrapper runs (its
145// options and their values skipped), or after `-exec`. `firstOnly` looks at the first command only.
146function datatugCalls(text, firstOnly) {
147  const calls = []
148  const items = lex(text)
149  let atCommand = true
150  let wrapped = false
151  for (let i = 0; i < items.length; i++) {
152    const it = items[i]
153    if (it.sep !== undefined) {
154      if (firstOnly) break
155      atCommand = true
156      wrapped = false
157      continue
158    }
159    const w = it.word
160    if (EXEC_OPTIONS.has(w)) {
161      atCommand = true
162      wrapped = true
163      continue
164    }
165    if (!atCommand) continue
166    if (DATATUG.test(w)) {
167      const words = []
168      for (let j = i + 1; j < items.length && items[j].sep === undefined; j++) words.push(items[j].word)
169      calls.push(words)
170      atCommand = false
171      continue
172    }
173    if (wrapped || RESERVED.has(w) || ASSIGNMENT.test(w)) continue
174    if (WRAPPERS.has(base(w))) {
175      wrapped = true
176      continue
177    }
178    atCommand = false
179  }
180  return calls
181}
182
183const has = (words, seq) => words.some((_, i) => seq.every((s, k) => words[i + k] === s))
184
185// Every datatug command the text runs, by both detectors: command position in the text as the shell
186// reads it, and the first command of each line as written (a heredoc body).
187function allCalls(text) {
188  const s = String(text ?? '')
189  return [...datatugCalls(unsubstitute(s), false), ...s.split(/[\n\r]/).flatMap(line => datatugCalls(line, true))]
190}
191
192// The command's words as the shell reads them, joined by spaces: quotes and backslashes removed.
193const flat = text => lex(unsubstitute(String(text ?? ''))).map(x => x.word ?? ` ${x.sep} `).join(' ')
194
195// Whether a command runs `datatug ... query run`.
196export function runsQuery(text) {
197  return allCalls(text).some(words => has(words, ['query', 'run']))
198}
199
200// The default that keeps unknown forms out: whether any simple command (split at separators and
201// lines) holds the word datatug, in any case or as a path, followed later by the words of `seq`
202// (`query` then `run`, ...), unless that command is one that never runs its words (`echo`, `rg`,
203// `git`, ...). Used when the detectors above did not find the command, so a wrapper they do not know
204// is denied rather than run.
205export function mentions(text, seq) {
206  const items = lex(unsubstitute(String(text ?? '')))
207  const commands = [[]]
208  for (const it of items) {
209    if (it.sep !== undefined) commands.push([])
210    else commands[commands.length - 1].push(it.word.toLowerCase())
211  }
212  return commands.some(words0 => {
213    // A comment ends the command.
214    const hash = words0.findIndex(w => w.startsWith('#'))
215    const words = hash < 0 ? words0 : words0.slice(0, hash)
216    if (words.length > 0 && READERS.has(base(words[0]))) return false
217    const at = words.findIndex(w => DATATUG.test(w))
218    if (at < 0) return false
219    let k = 0
220    for (const w of words.slice(at + 1)) if ((w === seq[k] || (seq[k].startsWith('--') && w.startsWith(`${seq[k]}=`))) && ++k === seq.length) return true
221    return false
222  })
223}
224
225const isFlag = (token, name) => token === name || token.startsWith(`${name}=`)
226const HELP = new Set(['--help', '-h'])
227
228// Splits a command into its tokens, each a whole word or a whole quoted argument (which may hold
229// spaces): null when a quote is unbalanced, sits inside a word, or a quoted argument holds the other
230// kind of quote.
231export function tokens(text) {
232  const out = []
233  let i = 0
234  while (i < text.length) {
235    if (text[i] === ' ' || text[i] === '\t') {
236      i++
237      continue
238    }
239    const q = text[i]
240    if (q === "'" || q === '"') {
241      const close = text.indexOf(q, i + 1)
242      if (close < 0) return null
243      const value = text.slice(i + 1, close)
244      if (/['"]/.test(value) || (close + 1 < text.length && text[close + 1] !== ' ' && text[close + 1] !== '\t')) return null
245      out.push({ raw: text.slice(i, close + 1), value, quoted: true, end: close + 1 })
246      i = close + 1
247      continue
248    }
249    let j = i
250    while (j < text.length && text[j] !== ' ' && text[j] !== '\t') j++
251    const raw = text.slice(i, j)
252    if (/['"]/.test(raw)) return null
253    out.push({ raw, value: raw, quoted: false, end: j })
254    i = j
255  }
256  return out
257}
258
259// What to do with a command:
260// - { kind: 'none' }: it does not run `datatug query run`; it runs as it is.
261// - { kind: 'help' }: `datatug query run --help` (or -h) and nothing else; it runs as it is.
262// - { kind: 'deny', reason }: it runs `datatug query run` in a form the mod does not rewrite.
263// - { kind: 'plain', head, tail, format }: the plain form. `head` is the command up to and
264//   including `query run`, `tail` the rest, `format` the model's own --format value or null.
265export function classify(command, isBackground) {
266  const text = String(command ?? '')
267  const deny = { kind: 'deny', reason: PLAIN_TEXT }
268  if (!runsQuery(text)) return mentions(text, ['query', 'run']) ? deny : { kind: 'none' }
269  const t = text.trim()
270  const toks = SHELL.test(t) ? null : tokens(t)
271  // A word the shell would expand (a brace, a wildcard) could become a flag after the check.
272  if (toks === null || toks.some(x => !x.quoted && /[{}*?[\]]/.test(x.value))) return deny
273  let at = 0
274  while (at < toks.length && !toks[at].quoted && (toks[at].value === 'env' || toks[at].value === 'time' || ASSIGNMENT.test(toks[at].value))) at++
275  // $DATATUG_CLIENT is the CLI's fallback for --client.
276  if (toks.slice(0, at).some(x => /^DATATUG_CLIENT=/i.test(x.value))) return deny
277  if (at >= toks.length || toks[at].quoted || !DATATUG.test(toks[at].value)) return deny
278  let q = at + 1
279  while (q + 1 < toks.length && !(toks[q].value === 'query' && toks[q + 1].value === 'run' && !toks[q].quoted && !toks[q + 1].quoted)) q++
280  if (q + 1 >= toks.length) return deny
281  const global = toks.slice(at + 1, q)
282  if (global.some(x => x.quoted || isFlag(x.value, '--client'))) return deny
283  const rest = toks.slice(q + 2)
284  if (rest.length > 0 && rest.every(x => !x.quoted && HELP.has(x.value))) return { kind: 'help' }
285  if (isBackground) return { kind: 'deny', reason: BACKGROUND_TEXT }
286  // Quoted or not: the shell removes the quotes, and the CLI gets the flag.
287  // A quoted argument with spaces is one argument, but its first word is looked at too.
288  for (const x of rest) {
289    if (HELP.has(x.value) || x.value === '--') return deny
290    for (const v of x.quoted ? [x.value, x.value.trim().split(/\s+/)[0]] : [x.value]) if (['--result-id', '--result-rows', '--client'].some(name => isFlag(v, name))) return deny
291  }
292  let format = null
293  for (let i = 0; i < rest.length; i++) {
294    if (rest[i].value === '--format') format = rest[i + 1]?.value ?? ''
295    else if (rest[i].value.startsWith('--format=')) format = rest[i].value.slice('--format='.length)
296  }
297  const cut = toks[q + 1].end
298  return { kind: 'plain', head: t.slice(0, cut), tail: t.slice(cut), format }
299}
300
301// Whether a Bash command names the result store or the capture folder by path, runs the commands
302// that print where results are, or changes into DataTug's folder. `home` is the literal home path
303// when known.
304export function bashNamesStore(command, home) {
305  const raw = String(command ?? '')
306  const homes = ['~[A-Za-z0-9._-]*', '\\$HOME', '\\$\\{HOME\\}']
307  if (typeof home === 'string' && home.startsWith('/') && home.length > 1) homes.push(home.replace(/\/+$/, '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
308  const base = `(?:${homes.join('|')})\\/\\.datatug`
309  // Any path into the home folder's .datatug (the folder above the store, which a recursive command
310  // walks into), the store or the capture folder by name, or a wildcard after `.datatug/`. Judged on
311  // the command as written and as the shell reads it, ignoring case (macOS folders ignore it).
312  const patterns = [
313    /\.datatug\/query-results/i,
314    /\/datatug-claude-mod/i,
315    /\/datatug-claude[^\s/;&|()<>]*[*?[]/i,
316    /\.datatug\/[^\s;&|()<>]*[*?[]/i,
317    new RegExp(`${base}(?=$|[\\/\\s;&|()<>'"*?[{])`, 'i'),
318    new RegExp(`(?:^|[\\s;&|(])(?:cd|pushd)\\s+['"]?${base}`, 'i'),
319  ]
320  for (const s of [raw, flat(raw)]) if (patterns.some(p => p.test(s) || p.test(foldPaths(s)))) return true
321  if (mentions(raw, ['query', 'results', 'locate']) || mentions(raw, ['daemon', 'url', '--result']) || mentions(raw, ['ui', '--result'])) return true
322  return allCalls(raw).some(
323    words =>
324      has(words, ['query', 'results', 'locate']) ||
325      ((has(words, ['daemon', 'url']) || words[0] === 'ui' || has(words, ['ui'])) && words.some(w => isFlag(w, '--result'))),
326  )
327}
328
329// The text with every path folded as the file system reads it: `//` made `/`, `/./` removed and
330// `/name/../` taken back, so `~//.datatug` or `/Users/u/./.datatug` reads as `~/.datatug`.
331export function foldPaths(text) {
332  let s = String(text ?? '').replace(/\/{2,}/g, '/')
333  let prev
334  do {
335    prev = s
336    s = s.replace(/\/\.(?=\/|$|[\s;&|()<>'"])/g, '').replace(/\/(?!\.\.(?:\/|$))[^/\s;&|()<>'"]+\/\.\.(?=\/|$|[\s;&|()<>'"])/g, '')
337  } while (s !== prev)
338  return s
339}
340
341// A path as written, made absolute and folded: `~`, `$HOME` and `${HOME}` expanded, relative paths
342// taken from `cwd`, `.` and `..` removed, no trailing slash. Null when it cannot be placed.
343export function normalizePath(path, home, cwd) {
344  let p = String(path ?? '').trim()
345  if (p === '') return null
346  const h = typeof home === 'string' && home.startsWith('/') ? home.replace(/\/+$/, '') : null
347  const m = /^(~|\$HOME|\$\{HOME\})(?=\/|$)/.exec(p)
348  if (m !== null) {
349    if (h === null) return null
350    p = h + p.slice(m[0].length)
351  }
352  if (!p.startsWith('/')) {
353    if (typeof cwd !== 'string' || !cwd.startsWith('/')) return null
354    p = `${cwd.replace(/\/+$/, '')}/${p}`
355  }
356  const parts = []
357  for (const part of p.split('/')) {
358    if (part === '' || part === '.') continue
359    if (part === '..') parts.pop()
360    else parts.push(part)
361  }
362  return `/${parts.join('/')}`
363}
364
365// Whether a folded path is one of the protected folders, inside one, or the folder directly above
366// one (a recursive search there walks into it). `roots`: [{ dir, parent }].
367export function pathInStore(path, roots) {
368  if (typeof path !== 'string') return false
369  // Case is ignored: the folders of a macOS disk ignore it.
370  const p = path.toLowerCase()
371  return roots.some(({ dir, parent }) => {
372    const d = dir.toLowerCase()
373    return p === d || p.startsWith(`${d}/`) || p === parent.toLowerCase()
374  })
375}
376
lib/rows.js 143 lines
1// The rows of a result card as the person works with them: sorted for the Table view and as the
2// text of the clipboard. Pure. A value is only ever handled here; it goes to the screen and to the
3// person's clipboard and nowhere else (never a log, a tool result, a prompt or a notice).
4
5const DECIMAL = /^([+-]?)(\d+(?:\.\d*)?|\.\d+)(?:[eE]([+-]?\d+))?$/
6const JSON_NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/
7
8// Normalize decimal digits and their position, without expanding exponents or rounding through Number.
9function decimal(value) {
10  const match = DECIMAL.exec(value.trim())
11  if (!match) return null
12  const parts = match[2].split('.')
13  const digits = parts.join('').replace(/^0+/, '')
14  if (!digits) return { sign: 0, digits: '', position: 0n }
15  return {
16    sign: match[1] === '-' ? -1 : 1,
17    digits,
18    position: BigInt(digits.length) + BigInt(match[3] || '0') - BigInt((parts[1] || '').length),
19  }
20}
21
22function compareDecimal(x, y) {
23  if (x.sign !== y.sign) return x.sign < y.sign ? -1 : 1
24  if (x.sign === 0) return 0
25  if (x.position !== y.position) return (x.position < y.position ? -1 : 1) * x.sign
26  for (let i = 0; i < Math.max(x.digits.length, y.digits.length); i++) {
27    const a = x.digits[i] || '0'
28    const b = y.digits[i] || '0'
29    if (a !== b) return (a < b ? -1 : 1) * x.sign
30  }
31  return 0
32}
33
34// -1: a before b, 1: after, 0: equal. Decimal strings retain every digit; text follows numbers.
35function compareNumeric(a, b) {
36  // Retain the existing Number-compatible nondecimal forms (hex, Infinity, etc.). Decimal
37  // strings, including values outside Number's finite range, always take the exact path.
38  const number = value => {
39    const exact = decimal(value)
40    if (exact) return { exact }
41    const n = Number(value)
42    return value.trim() === '' || Number.isNaN(n) ? null
43      : Number.isFinite(n) ? { exact: decimal(String(n)) } : { infinity: n }
44  }
45  const x = number(a)
46  const y = number(b)
47  if (x && y) {
48    if (x.exact && y.exact) return compareDecimal(x.exact, y.exact)
49    if (x.infinity === y.infinity) return 0
50    if (x.infinity !== undefined) return x.infinity < 0 ? -1 : 1
51    return y.infinity < 0 ? 1 : -1
52  }
53  if (!!x !== !!y) return x ? -1 : 1
54  return compareText(a, b)
55}
56const compareText = (a, b) => a.localeCompare(b, 'en', { sensitivity: 'base' })
57
58// The indices of `rows` in the order of column `col`: ascending, or descending when `desc`; a null
59// is last either way; equal values keep their order (stable). Nothing is changed in `rows`.
60export function sortedOrder(rows, col, numeric, desc) {
61  const order = rows.map((_, i) => i)
62  if (col < 0) return order
63  const cmp = numeric ? compareNumeric : compareText
64  return order.sort((i, j) => {
65    const a = rows[i][col]
66    const b = rows[j][col]
67    if (a === null || a === undefined) return b === null || b === undefined ? i - j : 1
68    if (b === null || b === undefined) return -1
69    const c = cmp(a, b)
70    return c === 0 ? i - j : desc ? -c : c
71  })
72}
73
74// RFC 4180: a field with a quote, comma or line break is quoted and its quotes doubled. A null is an
75// empty field. Values are raw (no formula prefix): the README says so.
76const field = v => {
77  const s = v === null || v === undefined ? '' : String(v)
78  return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s
79}
80
81// `columns` are names; `rows` are arrays of cells in the same order. A header row first.
82export function toCsv(columns, rows) {
83  return [columns, ...rows].map(r => r.map(field).join(',')).join('\n') + '\n'
84}
85
86// An array of objects keyed by column name, one per row. A number-typed cell that is a JSON number
87// keeps its exact digits; anything else is a string; a null is null. `types` match `columns`.
88export function toJson(columns, types, rows) {
89  const cell = (v, t) => {
90    if (v === null || v === undefined) return 'null'
91    if ((t === 'integer' || t === 'number' || t === 'decimal') && JSON_NUMBER.test(v)) return v
92    if (t === 'boolean' && (v === 'true' || v === 'false')) return v
93    return JSON.stringify(String(v))
94  }
95  const objects = rows.map(r => '  {' + columns.map((c, i) => `${JSON.stringify(c)}: ${cell(r[i], types[i])}`).join(', ') + '}')
96  return rows.length === 0 ? '[]\n' : `[\n${objects.join(',\n')}\n]\n`
97}
98
99// The cycle of a header press: none, ascending, descending, none.
100export function nextSort(sort, col) {
101  if (sort === undefined || sort === null || sort.col !== col) return { col, desc: false }
102  return sort.desc ? undefined : { col, desc: true }
103}
104
105// What a result is, in a few words: the tables it reads, or the saved query's id, or "SQL query".
106// Names from meta.json only; never a value, a path or a result id.
107export function resultTitle(meta) {
108  const nm = p => (p.schema === '' || p.schema === 'main' ? p.relation : `${p.schema}.${p.relation}`)
109  const sources = [...new Set(meta.participants.map(nm).filter(n => n !== ''))]
110  if (meta.savedId) return `Saved query ${meta.savedId}`
111  if (sources.length > 0) return sources.length > 3 ? `${sources.slice(0, 3).join(', ')} and ${sources.length - 3} more` : sources.join(', ')
112  return meta.unavailable.participants === 'native-sql' ? 'SQL query' : 'Query'
113}
114
115// The header line of a card: what it is, where it ran and how much it holds.
116export function headerLine(meta, columnCount) {
117  const what = resultTitle(meta)
118  const db = meta.db.source === null ? '' : meta.db.env ? `${meta.db.source} (${meta.db.env})` : meta.db.source
119  const kept = meta.rows.kept
120  const rows = `${kept} row${kept === 1 ? '' : 's'}${meta.rows.hasMore ? ` (at least ${kept + 1})` : ''} x ${columnCount} column${columnCount === 1 ? '' : 's'}`
121  return [what, db, rows].filter(p => p !== '').join(' · ')
122}
123
124// The window of `size` columns the Table view shows out of `total`: page `page` (0-based, clamped), the
125// pages there are, and the first and one past the last column index. Any number of columns, one included.
126export function columnPage(total, page, size) {
127  const pages = Math.max(1, Math.ceil(total / size))
128  const p = Math.min(Math.max(0, Math.trunc(Number(page)) || 0), pages - 1)
129  const start = p * size
130  return { page: p, pages, start, end: Math.min(total, start + size) }
131}
132
133// The results the panel can switch between: the newest `max` of `keys` (oldest first) that the person
134// has not closed.
135export function historyKeys(keys, closed, max) {
136  return keys.slice(-max).filter(k => !closed.includes(k))
137}
138
139// The shown one: `want` while it is still in `keys`, else the newest; undefined for no results.
140export function historyPick(keys, want) {
141  return keys.includes(want) ? want : keys.at(-1)
142}
143
lib/text.js 31 lines
1// Makes text that comes from a project file or from the CLI safe to show:
2// pure, and the one place that decides what "safe" means.
3
4// C0 controls (with tab, newline and carriage return), DEL, C1 controls, the
5// soft hyphen, bidirectional controls, the line and paragraph separators,
6// zero-width and invisible formatting characters, the byte order mark and the
7// tag block. Built with `new RegExp` and the `u` flag so the astral range
8// works.
9const UNSAFE = new RegExp(
10  '[\u0000-\u001f\u007f-\u009f­؜᠎​-‏‪-‮⁠-⁤⁦-⁩

\u{e0000}-\u{e007f}]',
11  'gu',
12)
13
14// Cuts text to `maxLength` code points, with an ellipsis as the last one when
15// it was cut. Never splits a surrogate pair.
16export function truncate(text, maxLength) {
17  const points = Array.from(text)
18  return points.length > maxLength ? points.slice(0, maxLength - 1).join('') + '…' : text
19}
20
21export function cleanText(value, maxLength = 200) {
22  if (typeof value !== 'string') return ''
23  return truncate(value.replace(UNSAFE, ' ').replace(/\s+/g, ' ').trim(), maxLength)
24}
25
26// The same characters as cleanText treats as unsafe, each replaced by a space, with no trimming,
27// collapsing or cutting: for values that are shown as they are.
28export function stripUnsafe(value) {
29  return String(value ?? '').replace(UNSAFE, ' ')
30}
31
lib/view.js 83 lines
1import { isPlainPath } from './draft.js'
2import { SECTIONS, findQuery, queryHeadLines, queryParamLines, sectionLines } from './lines.js'
3
4// Only the terminal and the Desktop app show a mod's panes. `surfaces` is the
5// list `$.session.surfaces()` returns.
6export function canDrawPane(surfaces) {
7  return Array.isArray(surfaces) && (surfaces.includes('terminal') || surfaces.includes('desktop'))
8}
9
10const textOf = (Text, row) =>
11  Text({
12    wrap: 'truncate-end',
13    ...(row.tone === 'warn' ? { color: 'yellow' } : {}),
14    ...(row.tone === 'dim' ? { dimColor: true } : {}),
15    children: [row.text],
16  })
17
18// `elements` is `{ Box, Text, Button }` from `$.ui.resolve(e)`. `selected` is
19// the path of the chosen query, or null; `on` has the callbacks `onTab(id)`,
20// `onSelect(path)`, `onBack()` and `onAsk()`. `focusPath` is the query row
21// that takes the focus on the Queries tab (the first row when null or absent).
22export function buildPane({ Box, Text, Button }, project, tab, selected, on, focusPath = null) {
23  const tabs = SECTIONS.map((section) =>
24    Button({
25      key: 'tab-' + section.id,
26      label: section.label,
27      hotkey: section.hotkey,
28      plain: true,
29      dimColor: tab !== section.id,
30      onPress: () => on.onTab(section.id),
31    }),
32  )
33
34  const query = selected === null ? null : findQuery(project, selected)
35  let body
36  if (query !== null) {
37    const canAsk = isPlainPath(query.path)
38    body = [
39      ...queryHeadLines(query).map((row) => textOf(Text, row)),
40      Text({ children: [' '] }),
41      Box({
42        flexDirection: 'row',
43        columnGap: 2,
44        children: [
45          ...(canAsk
46            ? [Button({ key: 'ask-claude', label: 'Ask Claude', hotkey: 'a', plain: true, autoFocus: true, onPress: () => on.onAsk() })]
47            : [textOf(Text, { text: "This query's ID cannot be named in a request.", tone: 'dim' })]),
48          Button({
49            key: 'query-back',
50            label: 'Back',
51            hotkey: 'b',
52            plain: true,
53            ...(canAsk ? {} : { autoFocus: true }),
54            onPress: () => on.onBack(),
55          }),
56        ],
57      }),
58      Text({ children: [' '] }),
59      ...queryParamLines(query).map((row) => textOf(Text, row)),
60    ]
61  } else {
62    const rows = sectionLines(project, tab)
63    const paths = rows.filter((row) => row.path !== undefined).map((row) => row.path)
64    const focus = focusPath !== null && paths.includes(focusPath) ? focusPath : paths[0]
65    body = rows.map((row) =>
66      row.path === undefined
67        ? textOf(Text, row)
68        : Button({
69            key: 'query-' + row.path,
70            label: row.text,
71            plain: true,
72            ...(row.path === focus ? { autoFocus: true } : {}),
73            onPress: () => on.onSelect(row.path),
74          }),
75    )
76  }
77
78  return Box({
79    flexDirection: 'column',
80    children: [Box({ flexDirection: 'row', columnGap: 2, children: tabs }), Text({ children: [' '] }), ...body],
81  })
82}
83
hooks/project.js 146 lines
1import {
2  EXIT_NOT_A_PROJECT,
3  LISTINGS,
4  MIN_CLI_VERSION,
5  VERSION_ARGS,
6  isOlder,
7  missingCliText,
8  notAProjectText,
9  parseVersion,
10  tooOldText,
11} from '../lib/cli.js'
12import { isProjectView } from '../lib/command.js'
13import { appendPrefix, queryDraft } from '../lib/draft.js'
14import { findQuery, summaryText } from '../lib/lines.js'
15import { buildProject } from '../lib/project.js'
16import { buildPane, canDrawPane } from '../lib/view.js'
17
18const PANE = 'datatug-project'
19const TIMEOUT_MS = 15000
20
21// What the pane shows: the loaded project and the open tab.
22let project = null
23let tab = 'overview'
24let selected = null // path of the chosen query, or null
25let focusPath = null // the query row that takes the focus after Back
26let isAsking = false // an Ask Claude press is running
27
28// Runs one read-only datatug command, with no shell. A command that cannot be
29// started, or runs past the timeout, resolves with isStarted false.
30async function runDatatug($, args, cwd) {
31  try {
32    const result = await $.process.run(['datatug', ...args], { cwd, timeoutMs: TIMEOUT_MS, env: { DATATUG_CLIENT: 'claude-mod' } })
33    return {
34      isStarted: true,
35      exitCode: result.exitCode,
36      stdout: result.stdout,
37      stderr: result.stderr,
38      isStdoutTruncated: result.isStdoutTruncated === true,
39    }
40  } catch (err) {
41    return { isStarted: false, exitCode: -1, stdout: '', stderr: err instanceof Error ? err.message : String(err) }
42  }
43}
44
45export function registerProject(on) {
46  on('session.start', async ($, e, next) => {
47    await $.command.register({
48      name: 'datatug',
49      description: 'Open the DataTug panel (/datatug project: the project in this directory)',
50    })
51    return next(e)
52  })
53
54  on('command.run', { command: 'datatug' }, async ($, e, next) => {
55    // Plain `/datatug` is the panel (hooks/register.tsx); only `/datatug project` is this pane.
56    if (!isProjectView(e.args)) return next(e)
57    const cwd = await $.session.cwd()
58
59    const version = await runDatatug($, VERSION_ARGS, cwd)
60    if (!version.isStarted) return { text: missingCliText() }
61    // A version that cannot be read is a development build: let it through.
62    const found = parseVersion(version.stdout)
63    if (found !== null && isOlder(found, parseVersion(MIN_CLI_VERSION))) {
64      return { text: tooOldText(found.join('.')) }
65    }
66
67    const [show, queries, boards] = await Promise.all([
68      runDatatug($, LISTINGS.show, cwd),
69      runDatatug($, LISTINGS.queries, cwd),
70      runDatatug($, LISTINGS.boards, cwd),
71    ])
72    if (show.exitCode === EXIT_NOT_A_PROJECT) return { text: notAProjectText(cwd) }
73
74    project = buildProject({ show, queries, boards })
75    tab = 'overview'
76    selected = null
77    focusPath = null
78    // An open pane is redrawn only when asked: re-opening its id just retitles it.
79    $.ui.invalidate('ui.render')
80
81    // Where no surface shows panes (a `-p` run names none), reply with a
82    // plain-text summary: `$.ui.open` would report a pane placed that nothing draws.
83    const surfaces = await $.session.surfaces()
84    if (!canDrawPane(surfaces)) return { text: summaryText(project) }
85
86    try {
87      const opened = await $.ui.open({ id: PANE, title: 'DataTug', focus: true, closeOnEscape: true })
88      if (opened.isPlaced) return {}
89    } catch {
90      // fall through to the text summary
91    }
92    return { text: summaryText(project) }
93  }).catch(() => ({ text: 'The DataTug project could not be read. Run `/datatug project` again.' }))
94
95  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
96    if (e.requestId !== PANE) return next(e)
97    const elements = $.ui.resolve(e)
98    if (project === null) {
99      return elements.Text({ dimColor: true, children: ['Run /datatug to load the project.'] })
100    }
101    return buildPane(elements, project, tab, selected, {
102      onTab: (id) => {
103        tab = id
104        selected = null
105        focusPath = null
106        $.ui.invalidate('ui.render')
107      },
108      onSelect: (path) => {
109        selected = path
110        focusPath = path
111        $.ui.invalidate('ui.render')
112      },
113      onBack: () => {
114        selected = null
115        $.ui.invalidate('ui.render')
116      },
117      onAsk: async () => {
118        if (isAsking) return
119        const query = selected === null || project === null ? null : findQuery(project, selected)
120        if (query === null) return
121        const draft = queryDraft(query)
122        if (draft === null) return
123        isAsking = true
124        try {
125          let isFilled = false
126          try {
127            const box = await $.prompt.read()
128            const filled = await $.prompt.fill({ text: appendPrefix(box.text) + draft, mode: 'append' })
129            isFilled = filled.isFilled === true
130            // No call hands the keys back and leaves the pane open, so close
131            // it. The draft is in the box by now: a close that fails is not
132            // a failed draft.
133            if (isFilled) await $.ui.close({ id: PANE })
134          } catch {
135            if (!isFilled) $.ui.toast(draft, { timeoutMs: 15000 })
136            return
137          }
138          if (!isFilled) $.ui.toast(draft, { timeoutMs: 15000 })
139        } finally {
140          isAsking = false
141        }
142      },
143    }, focusPath)
144  })
145}
146