Skip to content
Back to search

civitai

A repository of models, textual inversions, and more

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/civitai/civitai with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/civitai/civitai'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/civitai--civitai/badge.svg)](/listings/civitai--civitai)

HTML

<a href="/listings/civitai--civitai"><img src="/api/listings/civitai--civitai/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

<details open> <summary>To get a local copy up and running, follow these steps.</summary>

Prerequisites

- [Docker](https://www.docker.com/), with Compose v2 (`docker compose`, not the retired hyphenated `docker-compose`). The database, Redis, MinIO, Meilisearch, ClickHouse and the mail catcher all run as containers. - **Node.js `24.22.1`.** Not "20 or later" — `package.json` declares `engines.node: ">=24.0.0 <25"`. The exact version lives in [`.nvmrc`](.nvmrc); CI installs that file's version and the production image is built on the same one, so `nvm use` (or any tool that reads `.nvmrc`) is the right way to get it. Note that nothing stops you: `pnpm install` only prints `WARN Unsupported engine` and carries on, so the wrong major surfaces later as odd test failures rather than as a refusal at install time. - **pnpm.** This repo is pnpm-only, and this one *is* enforced — `npm install` exits 1 via the `preinstall` `only-allow pnpm` hook. `corepack enable` will pick up the `packageManager` field for you. - Make (optional).

Installation

Standard setup

git clone https://github.com/civitai/civitai.git
cd civitai
nvm use                                              # reads .nvmrc -> 24.22.1
corepack enable
git submodule update --init event-engine-common
cp .env-example .env.development
docker compose -f docker-compose.base.yml up -d
pnpm install
pnpm dev

Optional: Nix flake

> **Optional, and not the supported default.** The standard setup above is what the > project expects and what CI builds; nothing in the repo requires Nix, and you can > ignore this section entirely. It exists because NixOS cannot use Prisma's published > engines (there is no `linux-nixos` build), so a flake is the practical way to work on > this repo there. If you are not on NixOS and not already a flakes user, skip it.

The flake owns the toolchain, so you do not install Node or pnpm yourself:

git clone https://github.com/civitai/civitai.git
cd civitai
nix run .#dev

That single command checks Docker is usable, checks out the `event-engine-common` submodule, creates `.env.development` from `.env-example` if you do not already have one, starts the container stack, waits for Postgres, runs `pnpm install`, and then starts the dev server on [http://localhost:3000](http://localhost:3000). Every step is idempotent — it is safe to re-run in a checkout that already works, and it will not overwrite your `.env.development` or touch your data.

Useful variants:

nix run .#dev -- --no-start   # bootstrap only, leave the services running
nix run .#dev -- --full       # also start the signals/buzz containers (see below)
nix run .#doctor              # check the flake's pins against the repo
nix flake check               # the same checks, plus their own self-test

For an interactive shell with the same toolchain, use `nix develop`, or copy [`.envrc.example`](.envrc.example) to `.envrc` and run `direnv allow` to get it automatically on `cd`.

With devcontainers

> ⚠️ **Known out of step:** `.devcontainer/public/docker-compose.yml` pins > `mcr.microsoft.com/devcontainers/typescript-node:1-22`, i.e. Node 22, which is > outside this repo's `engines.node` range. `pnpm install` will warn rather than > stop, so the container comes up and then misbehaves in ways that look like your > branch. There is no `1-24` tag (the template major moved on); `3-24` is the > closest equivalent. Not changed here because it could not be exercised.

> ⚠️ Important Warning for Windows Users: Either clone this repo onto a WSL volume, or use the "clone repository in named container volume" command. Otherwise, you will see performance issues.

- Open the directory up in your IDE of choice - VS Code should prompt you to "Open in container" - If not, you may need to manually run `Dev Containers: Open Folder in Container`

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 260 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. [![Contributors][contributors-shield]][contributors-url]
  2. [![Forks][forks-shield]][forks-url]
  3. [![Stargazers][stars-shield]][stars-url]
  4. [![Issues][issues-shield]][issues-url]
  5. [![Apache License 2.0][license-shield]][license-url]
  6. [![Discord][discord-shield]][discord-url]
  7. <br />
  8. <div align="center">
  9. <a href="https://civitai.com/">
  10. <img src="media/logo.png" alt="Civitai Logo" width="120" height="auto">
  11. </a>
  12. </div>
  13. ## Table of Contents
  14. - [Table of Contents](#table-of-contents)
  15. - [About the Project](#about-the-project)
  16. - [Tech Stack](#tech-stack)
  17. - [Getting Started](#getting-started)
  18. - [Prerequisites](#prerequisites)
  19. - [Installation](#installation)
  20. - [Altering your user](#altering-your-user)
  21. - [Known limitations](#known-limitations)
  22. - [Contributing](#contributing)
  23. - [Data Migrations](#data-migrations)
  24. - [Sponsors](#sponsors)
  25. - [License](#license)
  26. ## About the Project
  27. Our goal with this project is to create a platform where people can share their stable diffusion models (textual inversions, hypernetworks, aesthetic
  28. gradients, VAEs, and any other crazy stuff people do to customize their AI generations), collaborate with others to improve them, and learn from each
  29. other's work. The platform allows users to create an account, upload their models, and browse models that have been shared by others. Users can also
  30. leave comments and feedback on each other's models to facilitate collaboration and knowledge sharing.
  31. ### Tech Stack
  32. We've built this project using a combination of modern web technologies, including Next.js for the frontend, TRPC for the API, and Prisma + Postgres
  33. for the database. By leveraging these tools, we've been able to create a scalable and maintainable platform that is both user-friendly and powerful.
  34. - **DB:** Prisma + Postgres
  35. - **API:** tRPC
  36. - **Front-end + Back-end:** NextJS
  37. - **UI Kit:** [Mantine](https://mantine.dev/)
  38. - **Storage:** Cloudflare
  39. ## Getting Started
  40. <details open>
  41. <summary>To get a local copy up and running, follow these steps.</summary>
  42. ### Prerequisites
  43. - [Docker](https://www.docker.com/), with Compose v2 (`docker compose`, not the
  44. retired hyphenated `docker-compose`). The database, Redis, MinIO, Meilisearch,
  45. ClickHouse and the mail catcher all run as containers.
  46. - **Node.js `24.22.3`.** Not "20 or later" — `package.json` declares
  47. `engines.node: ">=24.0.0 <25"`. The exact version lives in [`.nvmrc`](.nvmrc);
  48. CI installs that file's version and the production image is built on the same
  49. one, so `nvm use` (or any tool that reads `.nvmrc`) is the right way to get it.
  50. Note that nothing stops you: `pnpm install` only prints
  51. `WARN Unsupported engine` and carries on, so the wrong major surfaces later as
  52. odd test failures rather than as a refusal at install time.
  53. - **pnpm.** This repo is pnpm-only, and this one *is* enforced — `npm install`
  54. exits 1 via the `preinstall` `only-allow pnpm` hook. `corepack enable` will
  55. pick up the `packageManager` field for you.
  56. - Make (optional).
  57. ### Installation
  58. #### Standard setup
  59. ```sh
  60. git clone https://github.com/civitai/civitai.git
  61. cd civitai
  62. nvm use # reads .nvmrc -> 24.22.3
  63. corepack enable
  64. git submodule update --init event-engine-common
  65. cp .env-example .env.development
  66. docker compose -f docker-compose.base.yml up -d
  67. pnpm install
  68. pnpm dev
  69. ```
  70. #### Optional: Nix flake
  71. > **Optional, and not the supported default.** The standard setup above is what the
  72. > project expects and what CI builds; nothing in the repo requires Nix, and you can
  73. > ignore this section entirely. It exists because NixOS cannot use Prisma's published
  74. > engines (there is no `linux-nixos` build), so a flake is the practical way to work on
  75. > this repo there. If you are not on NixOS and not already a flakes user, skip it.
  76. The flake owns the toolchain, so you do not install Node or pnpm yourself:
  77. ```sh
  78. git clone https://github.com/civitai/civitai.git
  79. cd civitai
  80. nix run .#dev
  81. ```
  82. That single command checks Docker is usable, checks out the
  83. `event-engine-common` submodule, creates `.env.development` from `.env-example`
  84. if you do not already have one, starts the container stack, waits for Postgres,
  85. runs `pnpm install`, and then starts the dev server on
  86. [http://localhost:3000](http://localhost:3000). Every step is idempotent — it is
  87. safe to re-run in a checkout that already works, and it will not overwrite your
  88. `.env.development` or touch your data.
  89. Useful variants:
  90. ```sh
  91. nix run .#dev -- --no-start # bootstrap only, leave the services running
  92. nix run .#dev -- --full # also start the signals/buzz containers (see below)
  93. nix run .#doctor # check the flake's pins against the repo
  94. nix flake check # the same checks, plus their own self-test
  95. ```
  96. For an interactive shell with the same toolchain, use `nix develop`, or copy
  97. [`.envrc.example`](.envrc.example) to `.envrc` and run `direnv allow` to get it
  98. automatically on `cd`.
  99. #### With devcontainers
  100. > ⚠️ **Known out of step:** `.devcontainer/public/docker-compose.yml` pins
  101. > `mcr.microsoft.com/devcontainers/typescript-node:1-22`, i.e. Node 22, which is
  102. > outside this repo's `engines.node` range. `pnpm install` will warn rather than
  103. > stop, so the container comes up and then misbehaves in ways that look like your
  104. > branch. There is no `1-24` tag (the template major moved on); `3-24` is the
  105. > closest equivalent. Not changed here because it could not be exercised.
  106. > ⚠️ Important Warning for Windows Users: Either clone this repo onto a WSL volume, or use the "clone repository in named container volume"
  107. command. Otherwise, you will see performance issues.
  108. - Open the directory up in your IDE of choice
  109. - VS Code should prompt you to "Open in container"
  110. - If not, you may need to manually run `Dev Containers: Open Folder in Container`
  111. - For other IDEs, you may need to open the `.devcontainer/devcontainer.json` file, and click "Create devcontainer and mount sources"
  112. - _Note: this may take some time to run initially_
  113. - Run `make run`
  114. #### The signals and buzz services
  115. `docker-compose.base.yml` holds everything a contributor needs (and is also what
  116. `nix run .#dev` starts). The extra services in `docker-compose.yml`
  117. (signals, buzz) come from private `ghcr.io` images, so they only work for
  118. internal members:
  119. - create a GitHub personal access token with `read:packages`
  120. - set it as `CR_PAT`
  121. - `echo $CR_PAT | docker login ghcr.io -u USERNAME --password-stdin`
  122. - then `docker compose up -d` (or, with the flake, `nix run .#dev -- --full`)
  123. ### After the first start
  124. 1. Edit `.env.development`. Most defaults work out of the box; these do not:
  125. - **S3 upload credentials.** Open the MinIO console at
  126. [http://localhost:9001](http://localhost:9001) (username and password both
  127. `minioadmin`) — note it is port **9001**, port 9000 is the S3 API itself —
  128. go to "Access Keys", click "Create Access Key", and copy the key and secret
  129. into `S3_UPLOAD_KEY` / `S3_UPLOAD_SECRET` and `S3_IMAGE_UPLOAD_KEY` /
  130. `S3_IMAGE_UPLOAD_SECRET`.
  131. - `WEBHOOK_TOKEN` — any random string; it authenticates requests to the
  132. webhook endpoint.
  133. 2. On an empty database, populate it. These are slow and destructive, which is
  134. why no bootstrap runs them for you:
  135. ```sh
  136. make run-migrations
  137. make reseed
  138. ```
  139. 3. Visit [http://localhost:3000](http://localhost:3000).
  140. Please report any issues with these commands to us on [discord][discord-url].
  141. _&ast; Note that account creation will run emails through Mailpit, which can be accessed at [http://localhost:1080](http://localhost:1080)._
  142. ### Altering your user
  143. - First, create an account for yourself as you normally would through the UI.
  144. - You may wish to set yourself up as a moderator. To do so:
  145. - Use a database editor (like [DataGrip](https://www.jetbrains.com/datagrip/)) or connect directly to the
  146. DB (`PGPASSWORD=postgres psql -h localhost -p 15432 -U postgres civitai`)
  147. - Find your user (by email or username), and change `isModerator` to `true`
  148. ### Known limitations
  149. Services that require external input will currently not work locally. These include:
  150. - Orchestration (Generation, Training)
  151. - Signals (Chat, Notifications, other real-time updates)
  152. - Buzz
  153. </details>
  154. ## Contributing
  155. Any contributions you make are **greatly appreciated**.
  156. If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
  157. Don't forget to give the project a star! Thanks again!
  158. 1. Fork the repository to your own GitHub account.
  159. 2. Create a new branch for your changes.
  160. 3. Make your changes to the code.
  161. 4. Commit your changes and push the branch to your forked repository.
  162. 5. Open a pull request on our repository.
  163. If you would like to be more involved, consider joining the **Community Development Team**! For more information on the team as well as how to join,
  164. see [Calling All Developers: Join Civitai's Community Development Team](https://civitai.com/articles/7782).
  165. ### Data Migrations
  166. Over the course of development, you may need to change the structure of the database. To do this:
  167. 1. Make your changes to the `packages/civitai-db-schema/prisma/schema.full.prisma` file.
  168. **Not `schema.prisma`** — that one is gitignored and regenerated from
  169. `schema.full.prisma` by `scripts/generate-slim-schema.js` on every
  170. `pnpm run db:generate`, so edits to it are silently overwritten.
  171. 2. Run `pnpm run db:migrate:empty "brief description here"`. This creates
  172. `packages/civitai-db-schema/prisma/migrations/YYYYMMDDHHmmss_brief_description_here/migration.sql`
  173. for you, in the one directory Prisma reads.
  174. To create it by hand instead, use that same path — **not** the `prisma/migrations`
  175. directory at the repo root, which predates the monorepo layout and is no longer read.
  176. 3. Put your sql changes in the generated `migration.sql`
  177. - These are usually simple sql commands like `ALTER TABLE ...`
  178. 4. Run `make run-migrations` and `make gen-prisma`
  179. 5. If you are adding/changing a column or table, please try to keep the `gen_seed.ts` file up to date with these changes.
  180. ## Sponsors
  181. Support this project by becoming a sponsor. Your logo will show up here with a link to your website.
  182. ## License
  183. Apache License 2.0 - Please have a look at the [LICENSE](/LICENSE) for more details.
  184. [contributors-shield]: https://img.shields.io/github/contributors/civitai/civitai.svg?style=for-the-badge
  185. [contributors-url]: https://github.com/civitai/civitai/graphs/contributors
  186. [forks-shield]: https://img.shields.io/github/forks/civitai/civitai.svg?style=for-the-badge
  187. [forks-url]: https://github.com/civitai/civitai/network/members
  188. [stars-shield]: https://img.shields.io/github/stars/civitai/civitai.svg?style=for-the-badge
  189. [stars-url]: https://github.com/civitai/civitai/stargazers
  190. [issues-shield]: https://img.shields.io/github/issues/civitai/civitai.svg?style=for-the-badge
  191. [issues-url]: https://github.com/civitai/civitai/issues
  192. [license-shield]: https://img.shields.io/github/license/civitai/civitai.svg?style=for-the-badge
  193. [license-url]: https://github.com/civitai/civitai/blob/master/LICENSE
  194. [discord-shield]: https://img.shields.io/discord/1037799583784370196?style=for-the-badge
  195. [discord-url]: https://discord.gg/UwX5wKwm6c
.claude/skills/clickup/listen.mjs · Bundled script · 430 lines · 13 findings marked
  1. #!/usr/bin/env node
  2. /**
  3. * ClickUp Event Listener (webhook.site + local receiver)
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 4 on GitHub
  4. *
  5. * Receives ClickUp webhook events via webhook.site forwarding.
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 6 on GitHub
  6. * Designed to be run as a background task so the agent gets notified
  7. * when a watched event arrives (task status change, comment, etc.).
  8. *
  9. * KEY FEATURE: On startup, checks webhook.site API for events that
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 10 on GitHub
  10. * arrived since last seen timestamp. Prevents gaps between restarts.
  11. *
  12. * Modes:
  13. * 1. "wait" (default) — Check for missed events, then listen for ONE
  14. * new webhook, print it, and exit. Agent gets background task notification.
  15. *
  16. * 2. "server" — Stay running and log all events.
  17. *
  18. * Usage:
  19. * node listen.mjs [--since <ISO timestamp>] [--port 3458] [--timeout 600] [--mode wait|server]
  20. *
  21. * Configuration (accounts.json > webhookSiteToken):
  22. * Or environment: CLICKUP_WEBHOOK_SITE_TOKEN
  23. *
  24. * Exit codes:
  25. * 0 — webhook received (wait mode)
  26. * 1 — timeout or error
  27. */
  28. import { spawn } from 'child_process';
  29. import http from 'http';
  30. import https from 'https';
  31. import crypto from 'crypto';
  32. import fs from 'fs';
  33. import path from 'path';
  34. import { fileURLToPath } from 'url';
  35. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  36. const LOG_FILE = path.join(__dirname, 'webhooks.jsonl');
  37. const LATEST_FILE = path.join(__dirname, 'webhook-latest.json');
  38. const WEBHOOK_URL_FILE = path.join(__dirname, 'webhook-url.txt');
  39. const LAST_SEEN_FILE = path.join(__dirname, 'last-seen.txt');
  40. const WATCHERS_FILE = path.join(__dirname, 'watchers.json');
  41. // ── Load config ───────────────────────────────────────────────────────────
  42. // Try accounts.json first, then env
  43. function loadConfig() {
  44. const accountsPath = path.join(__dirname, 'accounts.json');
  45. if (fs.existsSync(accountsPath)) {
  46. try {
  47. const data = JSON.parse(fs.readFileSync(accountsPath, 'utf-8'));
  48. return {
  49. webhookSiteToken: data.webhookSiteToken || process.env.CLICKUP_WEBHOOK_SITE_TOKEN,
  50. webhookSiteApiKey: data.webhookSiteApiKey || process.env.WEBHOOK_SITE_API_KEY,
  51. };
  52. } catch {}
  53. }
  54. return {
  55. webhookSiteToken: process.env.CLICKUP_WEBHOOK_SITE_TOKEN,
  56. webhookSiteApiKey: process.env.WEBHOOK_SITE_API_KEY,
  57. };
  58. }
  59. const config = loadConfig();
  60. const WH_TOKEN = config.webhookSiteToken;
  61. const WH_API_KEY = config.webhookSiteApiKey;
  62. // ── Parse CLI args ────────────────────────────────────────────────────────
  63. const args = process.argv.slice(2);
  64. function getFlag(name) {
  65. const idx = args.indexOf(name);
  66. if (idx === -1 || idx + 1 >= args.length) return undefined;
  67. return args[idx + 1];
  68. }
  69. const PORT = parseInt(getFlag('--port') || '3458', 10);
  70. const TIMEOUT = parseInt(getFlag('--timeout') || '600', 10) * 1000;
  71. const MODE = getFlag('--mode') || 'wait';
  72. // Filters — only deliver events matching these criteria
  73. const FILTER_STATUS = getFlag('--filter-status'); // e.g. "qa review" — only deliver status changes TO this status
  74. const FILTER_EVENT = getFlag('--filter-event'); // e.g. "taskCommentPosted" — only deliver this event type
  75. const FILTER_TASK = getFlag('--filter-task'); // e.g. "868abc123" — only deliver events for this task
  76. let SINCE = getFlag('--since');
  77. if (!SINCE && fs.existsSync(LAST_SEEN_FILE)) {
  78. SINCE = fs.readFileSync(LAST_SEEN_FILE, 'utf8').trim();
  79. }
  80. if (!WH_TOKEN) {
  81. console.error('Error: No webhook.site token configured.');
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 94 on GitHub
  82. console.error('Add "webhookSiteToken" to accounts.json or set CLICKUP_WEBHOOK_SITE_TOKEN env var.');
  83. console.error('Visit https://webhook.site to get a token (the UUID in the URL).');
    • Note: Quoted as data in code: Links to a known data-relay/testing domain (webhook.site) without sending anything to it
    • Dismissed after review: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 96 on GitHub
  84. process.exit(1);
  85. }
  86. const WEBHOOK_URL = `https://webhook.site/${WH_TOKEN}`;
    • Note: Quoted as data in code: Links to a known data-relay/testing domain (webhook.site) without sending anything to it
    • Note: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 100 on GitHub
  87. // Write the webhook URL so other commands can read it
  88. fs.writeFileSync(WEBHOOK_URL_FILE, WEBHOOK_URL);
  89. // ── Load watcher secrets for signature verification ───────────────────────
  90. function loadWatcherSecrets() {
  91. if (!fs.existsSync(WATCHERS_FILE)) return {};
  92. try {
  93. const watchers = JSON.parse(fs.readFileSync(WATCHERS_FILE, 'utf-8'));
  94. const secrets = {};
  95. for (const w of watchers) {
  96. if (w.webhookId && w.secret) secrets[w.webhookId] = w.secret;
  97. }
  98. return secrets;
  99. } catch {
  100. return {};
  101. }
  102. }
  103. const WATCHER_SECRETS = loadWatcherSecrets();
  104. // ── Event Filtering ───────────────────────────────────────────────────────
  105. function matchesFilters(event) {
  106. // Filter by event type
  107. if (FILTER_EVENT) {
  108. const allowed = FILTER_EVENT.split(',').map(s => s.trim().toLowerCase());
  109. const eventType = (event.event || '').toLowerCase();
  110. if (!allowed.includes(eventType)) return false;
  111. }
  112. // Filter by task ID
  113. if (FILTER_TASK) {
  114. const allowed = FILTER_TASK.split(',').map(s => s.trim());
  115. if (!allowed.includes(event.task_id)) return false;
  116. }
  117. // Filter by target status (only deliver taskStatusUpdated where after.status matches)
  118. if (FILTER_STATUS) {
  119. const allowed = FILTER_STATUS.split(',').map(s => s.trim().toLowerCase());
  120. const items = event.history_items || [];
  121. // For status updates, check the "after" status
  122. const hasMatch = items.some(item => {
  123. const afterStatus = (item.after?.status || '').toLowerCase();
  124. return allowed.includes(afterStatus);
  125. });
  126. // For non-status events, FILTER_STATUS doesn't apply — let them through
  127. if (event.event === 'taskStatusUpdated' && !hasMatch) return false;
  128. }
  129. return true;
  130. }
  131. // ── Helpers ───────────────────────────────────────────────────────────────
  132. function verifySignature(rawBody, signature, webhookId) {
  133. if (!signature) return null;
  134. // Try the specific webhook's secret first
  135. const secret = WATCHER_SECRETS[webhookId];
  136. if (!secret) return null;
  137. const hash = crypto
  138. .createHmac('sha256', secret)
  139. .update(rawBody)
  140. .digest('hex');
  141. return hash === signature;
  142. }
  143. function saveLastSeen(timestamp) {
  144. fs.writeFileSync(LAST_SEEN_FILE, timestamp);
  145. }
  146. function processEvent(event, source = 'live', verified = 'skipped') {
  147. const entry = {
  148. received_at: new Date().toISOString(),
  149. source,
  150. verified,
  151. ...event,
  152. };
  153. fs.appendFileSync(LOG_FILE, JSON.stringify(entry) + '\n');
  154. fs.writeFileSync(LATEST_FILE, JSON.stringify(entry, null, 2));
  155. if (entry._wh_created_at) {
  156. saveLastSeen(entry._wh_created_at);
  157. } else {
  158. saveLastSeen(entry.received_at);
  159. }
  160. return entry;
  161. }
  162. function formatEventSummary(event) {
  163. const type = event.event || 'unknown';
  164. const taskId = event.task_id || '?';
  165. const webhookId = event.webhook_id || '?';
  166. const items = event.history_items || [];
  167. let detail = '';
  168. if (type === 'taskStatusUpdated' && items.length > 0) {
  169. const item = items[0];
  170. detail = ` | ${item.before?.status || '?'} → ${item.after?.status || '?'}`;
  171. } else if (type === 'taskCommentPosted' && items.length > 0) {
  172. const user = items[0]?.user?.username || '?';
  173. detail = ` | by ${user}`;
  174. } else if (items.length > 0) {
  175. const user = items[0]?.user?.username;
  176. if (user) detail = ` | by ${user}`;
  177. }
  178. return `${type} | task:${taskId} | wh:${webhookId}${detail}`;
  179. }
  180. // ── Catch-up: query webhook.site for missed events ────────────────────────
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 215 on GitHub
  181. function fetchMissedEvents(since) {
  182. return new Promise((resolve, reject) => {
  183. const sinceUtc = since.includes('Z') || since.includes('+') ? since : since.replace(' ', 'T') + 'Z';
  184. const d = new Date(sinceUtc);
  185. if (d.getMilliseconds() > 0) {
  186. d.setSeconds(d.getSeconds() + 1);
  187. d.setMilliseconds(0);
  188. }
  189. d.setSeconds(d.getSeconds() + 1);
  190. const dateFrom = d.toISOString().replace('T', ' ').replace(/\.\d+Z$/, '');
  191. const url = new URL(`https://webhook.site/token/${WH_TOKEN}/requests`);
    • Note: Quoted as data in code: Links to a known data-relay/testing domain (webhook.site) without sending anything to it
    • Note: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 228 on GitHub
  192. url.searchParams.set('date_from', dateFrom);
  193. url.searchParams.set('sorting', 'oldest');
  194. url.searchParams.set('per_page', '10');
  195. const headers = {};
  196. if (WH_API_KEY) headers['Api-Key'] = WH_API_KEY;
  197. https.get(url.toString(), { headers }, (res) => {
  198. let data = '';
  199. res.on('data', (chunk) => (data += chunk));
  200. res.on('end', () => {
  201. try {
  202. const json = JSON.parse(data);
  203. resolve(json);
  204. } catch {
  205. resolve({ data: [] });
  206. }
  207. });
  208. }).on('error', (err) => {
  209. process.stderr.write(`[catch-up] Failed to query webhook.site: ${err.message}\n`);
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 248 on GitHub
  210. resolve({ data: [] });
  211. });
  212. });
  213. }
  214. function parseWebhookSiteRequest(req) {
  215. try {
  216. const event = JSON.parse(req.content);
  217. event._wh_created_at = req.created_at;
  218. return event;
  219. } catch {
  220. return null;
  221. }
  222. }
  223. // ── Local HTTP server ─────────────────────────────────────────────────────
  224. let serverResolve;
  225. const server = http.createServer((req, res) => {
  226. if (req.method === 'GET') {
  227. res.writeHead(200, { 'Content-Type': 'application/json' });
  228. res.end(JSON.stringify({ status: 'listening', webhook_url: WEBHOOK_URL }));
  229. return;
  230. }
  231. if (req.method === 'POST') {
  232. let rawBody = '';
  233. req.on('data', (chunk) => (rawBody += chunk));
  234. req.on('end', () => {
  235. try {
  236. const event = JSON.parse(rawBody);
  237. const signature = req.headers['x-signature'];
  238. const webhookId = event.webhook_id;
  239. const verified = verifySignature(rawBody, signature, webhookId);
  240. const entry = {
  241. received_at: new Date().toISOString(),
  242. source: 'live',
  243. verified: verified === null ? 'skipped' : verified,
  244. ...event,
  245. };
  246. // Always ack the webhook to prevent ClickUp from marking it unhealthy
  247. res.writeHead(200, { 'Content-Type': 'application/json' });
  248. res.end(JSON.stringify({ ok: true }));
  249. // Always log and update cursor
  250. fs.appendFileSync(LOG_FILE, JSON.stringify(entry) + '\n');
  251. saveLastSeen(entry.received_at);
  252. // Check filters — only deliver to agent if event matches
  253. if (!matchesFilters(event)) {
  254. process.stderr.write(`[filtered] ${formatEventSummary(event)}\n`);
  255. return;
  256. }
  257. fs.writeFileSync(LATEST_FILE, JSON.stringify(entry, null, 2));
  258. if (MODE === 'server') {
  259. process.stderr.write(`[${entry.received_at}] ${formatEventSummary(event)}\n`);
  260. } else {
  261. console.log(JSON.stringify(entry, null, 2));
  262. if (serverResolve) serverResolve();
  263. }
  264. } catch (err) {
  265. res.writeHead(400, { 'Content-Type': 'application/json' });
  266. res.end(JSON.stringify({ error: 'Invalid JSON' }));
  267. }
  268. });
  269. return;
  270. }
  271. res.writeHead(404);
  272. res.end('Not found');
  273. });
  274. // ── whcli forward process ─────────────────────────────────────────────────
  275. function startForwarder() {
  276. const whArgs = [
  277. 'forward',
  278. `--token=${WH_TOKEN}`,
  279. `--target=http://localhost:${PORT}`,
  280. '--listen-timeout=5',
  281. ];
  282. if (WH_API_KEY) whArgs.push(`--api-key=${WH_API_KEY}`);
  283. const proc = spawn('whcli', whArgs, {
  284. stdio: ['pipe', 'pipe', 'pipe'],
  285. shell: true,
  286. });
  287. proc.stdout.on('data', (d) => process.stderr.write(`[whcli] ${d}`));
  288. proc.stderr.on('data', (d) => process.stderr.write(`[whcli:err] ${d}`));
  289. proc.on('error', (err) => process.stderr.write(`[whcli] Error: ${err.message}\n`));
  290. return proc;
  291. }
  292. // ── Main ──────────────────────────────────────────────────────────────────
  293. async function main() {
  294. process.stderr.write(`ClickUp Event Listener\n`);
  295. process.stderr.write(`Webhook URL: ${WEBHOOK_URL}\n`);
  296. process.stderr.write(`Mode: ${MODE} | Port: ${PORT} | Timeout: ${TIMEOUT / 1000}s\n`);
  297. process.stderr.write(`Since: ${SINCE || 'none (first run)'}\n`);
  298. process.stderr.write(`Tracked webhooks: ${Object.keys(WATCHER_SECRETS).length}\n`);
  299. if (FILTER_STATUS) process.stderr.write(`Filter status: ${FILTER_STATUS}\n`);
  300. if (FILTER_EVENT) process.stderr.write(`Filter event: ${FILTER_EVENT}\n`);
  301. if (FILTER_TASK) process.stderr.write(`Filter task: ${FILTER_TASK}\n`);
  302. process.stderr.write('\n');
  303. // ── Step 1: Check for missed events ─────────────────────────────────────
  304. if (SINCE && MODE === 'wait') {
  305. process.stderr.write(`Checking webhook.site for events since ${SINCE}...\n`);
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 364 on GitHub
  306. const result = await fetchMissedEvents(SINCE);
  307. const requests = result.data || [];
  308. if (requests.length > 0) {
  309. // Find the first missed event that passes our filters
  310. for (const req of requests) {
  311. const event = parseWebhookSiteRequest(req);
  312. if (!event) continue;
  313. // Always update cursor even for filtered events
  314. const entry = processEvent(event, 'catch-up');
  315. if (matchesFilters(event)) {
  316. process.stderr.write(`[catch-up] Found matching event (of ${requests.length} missed). Delivering.\n`);
  317. console.log(JSON.stringify(entry, null, 2));
  318. process.exit(0);
  319. } else {
  320. process.stderr.write(`[catch-up:filtered] ${event.event || 'unknown'} — skipped\n`);
  321. }
  322. }
  323. process.stderr.write(`[catch-up] ${requests.length} missed event(s), none matched filters. Starting live listener.\n`);
  324. } else {
  325. process.stderr.write(`[catch-up] No missed events. Starting live listener.\n`);
  326. }
  327. }
  328. // ── Step 2: Start live listener ─────────────────────────────────────────
  329. await new Promise((resolve) => server.listen(PORT, resolve));
  330. process.stderr.write(`Listening on port ${PORT}\n\n`);
  331. const forwarder = startForwarder();
  332. if (MODE === 'wait') {
  333. const gotWebhook = new Promise((resolve) => { serverResolve = resolve; });
  334. const timedOut = new Promise((_, reject) =>
  335. setTimeout(() => reject(new Error('timeout')), TIMEOUT)
  336. );
  337. try {
  338. await Promise.race([gotWebhook, timedOut]);
  339. forwarder.kill();
  340. server.close(() => process.exit(0));
  341. } catch {
  342. console.log(JSON.stringify({
  343. error: 'timeout',
  344. message: `No ClickUp event received within ${TIMEOUT / 1000}s`,
  345. webhook_url: WEBHOOK_URL,
  346. }));
  347. forwarder.kill();
  348. server.close(() => process.exit(1));
  349. }
  350. } else {
  351. process.stderr.write('Running in server mode. Press Ctrl+C to stop.\n\n');
  352. function cleanup() {
  353. process.stderr.write('\nShutting down...\n');
  354. forwarder.kill();
  355. server.close(() => process.exit(0));
  356. }
  357. process.on('SIGINT', cleanup);
  358. process.on('SIGTERM', cleanup);
  359. }
  360. }
  361. main();
.claude/skills/clickup/query.mjs · Bundled script · 2,389 lines · 9 findings marked
  1. #!/usr/bin/env node
  2. /**
  3. * ClickUp - Task and Document interaction skill
  4. *
  5. * Task Commands:
  6. * get <url|id> Get task details
  7. * comments <url|id> List task comments (--threads to expand)
  8. * thread <comment_id> View threaded replies on a comment
  9. * reply <comment_id> "msg" Reply to a comment thread
  10. * comment <url|id> "msg" Post a comment
  11. * status <url|id> "status" Update task status
  12. * tasks <list_id> List tasks in a list
  13. * me Show current user info
  14. * create [list_id] "title" Create a new task (list_id optional if default set)
  15. * my-tasks List all tasks assigned to me
  16. * search [query] Search tasks — requires a scope: --list, --folder, --me,
  17. * --assignee, --status, or --all. Text query optional.
  18. * find-list "name" Find lists/folders by name (fast structural walk, no task fetch)
  19. * assign <task> <user> Assign task to user
  20. * due <task> "date" Set due date
  21. * start <task> "date" Set start date
  22. * schedule <task> "start" "due" Set both start and due dates
  23. * rename <task> "new name" Rename a task
  24. * priority <task> <level> Set priority (urgent/high/normal/low)
  25. * subtask <task> "title" Create a subtask
  26. * parent <task> <parent_task> Make an existing task a subtask of another task
  27. * milestone <task> <on|off> Turn a task into a milestone, or back (reversible)
  28. * move <task> <list_id> Move task to different list
  29. * link <task> <url> ["desc"] Add external link reference
  30. * checklist <task> "item" Add checklist item
  31. * update-comment <comment_id> "text" Update a comment's text
  32. * resolve-comment <comment_id> Resolve/close a comment
  33. * delete-comment <comment_id> Delete a comment
  34. * watch <task> <user> Add a watcher to task
  35. * unwatch <task> <user> Remove a watcher from task
  36. * tag <task> "tag_name" Add a tag to task
  37. * remove-tag <task> "tag_name" Remove a tag from task
  38. * description <task> "text" Update task description (markdown supported)
  39. * depends <task> <other_task> Set task as waiting on another task
  40. * blocks <task> <other_task> Set task as blocking another task
  41. * task-link <task> <other> Create bidirectional link between tasks
  42. * archive <task> Archive a task
  43. * unarchive <task> Restore an archived task
  44. * claim <task> Link your session to a task (sets Session ID custom field)
  45. *
  46. * List Commands:
  47. * list <list_id> Get list details
  48. * lists <folder_id> List all lists in a folder
  49. * space-lists <space_id> List folderless lists in a space
  50. * create-list <space> "name" Create a new list in a space
  51. * update-list <list_id> Update list (--name, --content)
  52. * delete-list <list_id> Delete a list
  53. *
  54. * Document Commands:
  55. * docs ["query"] Search/list docs in workspace
  56. * doc <doc_id> Get doc details and page listing
  57. * create-doc "title" Create a new doc (--space to place in space)
  58. * page <doc_id> <page_id> Get page content
  59. * create-page <doc_id> "title" Create a new page in a doc
  60. * edit-page <doc_id> <page_id> Edit a page's content
  61. *
  62. * Attachment Commands:
  63. * attach <url|id> --file <path> Upload file attachment(s) to a task
  64. * fetch-image <url> Download attachment to local temp file (--output path)
  65. *
  66. * Options:
  67. * --json Output raw JSON
  68. * --subtasks Include subtasks (for get command)
  69. * --me Filter to tasks assigned to me (for tasks command)
  70. * --content Inline content (for short text)
  71. * --file Read content from a file path (preferred for long content)
  72. * --cleanup Delete --file after successful execution
  73. * --parent Parent page ID for create-page (creates subpage)
  74. */
  75. import { readFileSync, existsSync, unlinkSync, writeFileSync, mkdirSync, readdirSync, statSync } from 'fs';
  76. import { resolve, join } from 'path';
  77. import { tmpdir, homedir } from 'os';
  78. // API imports
  79. import { initClient, getActiveCredentials, getActiveAccountId } from './api/client.mjs';
  80. import { updateAccountField, listAccounts as listAccountsFn, setDefaultAccount, addAccount as addAccountFn, removeAccount as removeAccountFn } from './lib/accounts.mjs';
  81. import { getCurrentUser, getUserId, getTeamId, findUser } from './api/user.mjs';
  82. import {
  83. getTask,
  84. getTasksInList,
  85. getAvailableStatuses,
  86. updateTaskStatus,
  87. updateTask,
  88. createTask,
  89. createSubtask,
  90. setParent,
  91. getAncestorIds,
  92. findCustomItemByName,
  93. setCustomItemId,
  94. searchTasks,
  95. getMyTasks,
  96. assignTask,
  97. setDueDate,
  98. setStartDate,
  99. setDates,
  100. setPriority,
  101. moveTask,
  102. parseDateInput,
  103. addWatcher,
  104. addTag,
  105. addDependency,
  106. removeDependency,
  107. addTaskLink,
  108. removeTaskLink,
  109. archiveTask,
  110. unarchiveTask,
  111. removeWatcher,
  112. removeTag,
  113. setCustomField,
  114. findCustomFieldByName,
  115. } from './api/tasks.mjs';
  116. import { getComments, postComment, updateComment, deleteComment, getThreadedComments, replyToComment } from './api/comments.mjs';
  117. import { addChecklistItemToTask, getChecklists, editChecklistItem, deleteChecklistItem } from './api/checklists.mjs';
  118. import { addExternalLink } from './api/links.mjs';
  119. import { getList, createList, deleteList, updateList, getLists, getFolderlessLists, getListMembers, findListByName } from './api/lists.mjs';
  120. import {
  121. searchDocs,
  122. getDoc,
  123. createDoc,
  124. getDocPageListing,
  125. getPage,
  126. createPage,
  127. editPage,
  128. } from './api/docs.mjs';
  129. import { uploadAttachment, uploadAttachments } from './api/attachments.mjs';
  130. import {
  131. createWebhook,
  132. listWebhooks,
  133. deleteWebhook,
  134. addWatcherEntry,
  135. removeWatcherEntry,
  136. getWatcherEntries,
  137. clearAllWatcherEntries,
  138. DEFAULT_TASK_EVENTS,
  139. DEFAULT_LIST_EVENTS,
  140. DEFAULT_SPACE_EVENTS,
  141. } from './api/webhooks.mjs';
  142. // Lib imports
  143. import { executeBatchCreate } from './lib/batch-create.mjs';
  144. import { splitIds, isBulk, bulkExecute, formatBulkResults } from './lib/bulk.mjs';
  145. import { parseTaskId, parseListId, parseDocId, parsePageId, parseSpaceId } from './lib/parse.mjs';
  146. import {
  147. formatTask,
  148. formatTaskList,
  149. formatComments,
  150. formatThread,
  151. formatDoc,
  152. formatDocList,
  153. formatPage,
  154. formatPageList,
  155. formatList,
  156. } from './lib/format.mjs';
  157. // Parse arguments
  158. const args = process.argv.slice(2);
  159. let command = null;
  160. let targetInput = null;
  161. let arg2 = null;
  162. let arg3 = null;
  163. let jsonOutput = false;
  164. let includeSubtasks = false;
  165. let filterMe = false;
  166. let assigneeArg = null;
  167. let dueArg = null;
  168. let descriptionArg = null;
  169. let contentArg = null;
  170. let nameArg = null;
  171. let parentArg = null;
  172. let spaceArg = null;
  173. let fileArg = null;
  174. let cleanupFlag = false;
  175. let archiveFlag = false;
  176. let pageArg = null;
  177. let accountArg = null;
  178. let threadsFlag = false;
  179. let attachArgs = [];
  180. let eventsArg = null;
  181. let listScopeArg = null;
  182. let folderScopeArg = null;
  183. let statusScopeArg = null;
  184. let allScopeFlag = false;
  185. for (let i = 0; i < args.length; i++) {
  186. const arg = args[i];
  187. if (arg === '--json') {
  188. jsonOutput = true;
  189. } else if (arg === '--subtasks') {
  190. includeSubtasks = true;
  191. } else if (arg === '--me') {
  192. filterMe = true;
  193. } else if (arg === '--assignee' || arg === '-a') {
  194. assigneeArg = args[++i];
  195. } else if (arg === '--due' || arg === '-d') {
  196. dueArg = args[++i];
  197. } else if (arg === '--description' || arg === '--desc') {
  198. descriptionArg = args[++i];
  199. } else if (arg === '--content' || arg === '-c') {
  200. contentArg = args[++i];
  201. } else if (arg === '--file' || arg === '-f') {
  202. fileArg = args[++i];
  203. } else if (arg === '--cleanup') {
  204. cleanupFlag = true;
  205. } else if (arg === '--archive') {
  206. archiveFlag = true;
  207. } else if (arg === '--name' || arg === '-n') {
  208. nameArg = args[++i];
  209. } else if (arg === '--parent' || arg === '-p') {
  210. parentArg = args[++i];
  211. } else if (arg === '--space' || arg === '-s') {
  212. spaceArg = args[++i];
  213. } else if (arg === '--page') {
  214. pageArg = args[++i];
  215. } else if (arg === '--threads' || arg === '-t') {
  216. threadsFlag = true;
  217. } else if (arg === '--attach') {
  218. attachArgs.push(args[++i]);
  219. } else if (arg === '--events' || arg === '-e') {
  220. eventsArg = args[++i];
  221. } else if (arg === '--account') {
  222. accountArg = args[++i];
  223. } else if (arg === '--list') {
  224. listScopeArg = args[++i];
  225. } else if (arg === '--folder') {
  226. folderScopeArg = args[++i];
  227. } else if (arg === '--status') {
  228. statusScopeArg = args[++i];
  229. } else if (arg === '--all') {
  230. allScopeFlag = true;
  231. } else if (!command) {
  232. command = arg;
  233. } else if (!targetInput) {
  234. targetInput = arg;
  235. } else if (!arg2) {
  236. arg2 = arg;
  237. } else if (!arg3) {
  238. arg3 = arg;
  239. }
  240. }
  241. // Unescape literal \n and \t in text args (CLI passes them as-is)
  242. function unescapeText(str) {
  243. return str ? str.replace(/\\n/g, '\n').replace(/\\t/g, '\t') : str;
  244. }
  245. function detectClaudeSessionId() {
  246. if (process.env.CLAUDE_SESSION_ID) return process.env.CLAUDE_SESSION_ID;
  247. // Fallback: the active Claude Code session is the one currently writing to its
  248. // jsonl transcript. Find the most-recently-modified jsonl across every project
  249. // dir under ~/.claude/projects/. We can't key off process.cwd() because the
  250. // caller may have cd'd into a skill dir before invoking node.
  251. try {
  252. const root = join(homedir(), '.claude', 'projects');
  253. if (!existsSync(root)) return null;
  254. let freshest = null;
  255. for (const projectName of readdirSync(root)) {
  256. const projectDir = join(root, projectName);
  257. try {
  258. if (!statSync(projectDir).isDirectory()) continue;
  259. } catch {
  260. continue;
  261. }
  262. for (const f of readdirSync(projectDir)) {
  263. if (!f.endsWith('.jsonl')) continue;
  264. const mtime = statSync(join(projectDir, f)).mtimeMs;
  265. if (!freshest || mtime > freshest.mtime) {
  266. freshest = { id: f.replace(/\.jsonl$/, ''), mtime };
  267. }
  268. }
  269. }
  270. // Only trust the pick if it was written within the last 60s — otherwise
  271. // it's stale and could belong to any old session.
  272. if (!freshest || Date.now() - freshest.mtime > 60_000) return null;
  273. return freshest.id;
  274. } catch {
  275. return null;
  276. }
  277. }
  278. contentArg = unescapeText(contentArg);
  279. descriptionArg = unescapeText(descriptionArg);
  280. arg2 = unescapeText(arg2);
  281. // --file overrides --content: read file contents as the content/text argument
  282. if (fileArg) {
  283. const filePath = resolve(fileArg);
  284. if (!existsSync(filePath)) {
  285. console.error(`Error: File not found: ${filePath}`);
  286. process.exit(1);
  287. }
  288. const fileContent = readFileSync(filePath, 'utf-8');
  289. contentArg = fileContent;
  290. // Also set arg2 so commands that use positional text (comment, description) pick it up
  291. if (!arg2) arg2 = fileContent;
  292. }
  293. // Backward compatibility (commentText = arg2, which --file may have populated)
  294. const commentText = arg2;
  295. // Show usage
  296. function showUsage() {
  297. console.error(`Usage: node query.mjs <command> [options]
  298. Task Commands:
  299. get <url|id> Get task details
  300. comments <url|id> List task comments (--threads to expand)
  301. thread <comment_id> View threaded replies on a comment
  302. reply <comment_id> "msg" Reply to a comment thread
  303. comment <url|id> "msg" Post a comment
  304. status <url|id> "status" Update task status
  305. tasks <list_id> List tasks in a list
  306. me Show current user info
  307. create [list_id] "title" Create a new task (list_id optional if default set)
  308. my-tasks List all tasks assigned to me
  309. search [query] Search tasks — requires a scope flag (--list/--folder/--me/
  310. --assignee/--status) or --all. Text query optional.
  311. find-list "name" Find a list or folder by name (fast, structural only)
  312. assign <task> <user> Assign task to user
  313. due <task> "date" Set due date
  314. start <task> "date" Set start date
  315. schedule <task> "start" "due" Set both start and due dates
  316. rename <task> "new name" Rename a task
  317. priority <task> <level> Set priority (urgent/high/normal/low)
  318. subtask <task> "title" Create a subtask
  319. parent <task> <parent_task> Make an existing task a subtask of another task
  320. milestone <task> <on|off> Turn a task into a milestone, or back (reversible)
  321. move <task> <list_id> Move task to different list
  322. link <task> <url> ["desc"] Add external link reference
  323. checklist <task> "item" Add checklist item
  324. update-comment <comment_id> "text" Update a comment's text
  325. resolve-comment <comment_id> Resolve/close a comment
  326. delete-comment <comment_id> Delete a comment
  327. watch <task> <user> Add a watcher to task
  328. unwatch <task> <user> Remove a watcher from task
  329. tag <task> "tag_name" Add a tag to task
  330. remove-tag <task> "tag_name" Remove a tag from task
  331. description <task> "text" Update task description (markdown supported)
  332. depends <task> <other_task> Set task as waiting on another task
  333. blocks <task> <other_task> Set task as blocking another task
  334. task-link <task> <other> Create bidirectional link between tasks
  335. archive <task> Archive a task (remove from active views)
  336. unarchive <task> Restore an archived task
  337. claim <task> Link your session to this task (for resumability)
  338. List Commands:
  339. list <list_id> Get list details
  340. lists <folder_id> List all lists in a folder
  341. space-lists <space_id> List folderless lists in a space
  342. create-list <space> "name" Create a new list in a space (--content for description)
  343. update-list <list_id> Update list (--name "new name", --content "description")
  344. delete-list <list_id> Delete a list
  345. Document Commands:
  346. docs ["query"] Search/list docs in workspace
  347. doc <doc_id> Get doc details and page listing
  348. create-doc "title" Create a new doc (--content, --space)
  349. page <doc_id> <page_id> Get page content
  350. create-page <doc_id> "title" Add a new page to a doc (--content, --parent)
  351. edit-page <doc_id> <page_id> Edit a page's content (--content and/or --name)
  352. Attachment Commands:
  353. attach <url|id> Upload file(s) to a task (--attach path, repeatable)
  354. fetch-image <url> Download attachment to local temp file (--output path)
  355. Project Setup:
  356. batch-create --file plan.json Create multiple tasks from JSON (with deps, subtasks, assignments)
  357. batch-create --file plan.json --dry-run Preview without creating
  358. Watcher Commands (webhook-based event monitoring):
  359. watch-task <id>[,id2,...] Watch task(s) for events (--events to customize)
  360. watch-list <list_id> Watch a list for events
  361. watch-space <space_id> Watch a space for events
  362. watchers List active webhook watchers
  363. webhooks List all webhooks in workspace (from API)
  364. unwatch-webhook <wh_id> Delete a webhook watcher
  365. unwatch-webhook --all Delete all webhook watchers
  366. Listener (run as background task):
  367. node listen.mjs [--timeout 600] [--port 3458] [--mode wait|server]
  368. Account Commands:
  369. accounts List configured accounts
  370. switch-account <name> Change the default account
  371. add-account <name> Add a new account (--token required)
  372. remove-account <name> Remove an account
  373. Options:
  374. --account <name> Use a specific account for this command
  375. --json Output raw JSON
  376. --subtasks Include subtasks (for get command)
  377. --me Filter to tasks assigned to me (for tasks command)
  378. --content Inline content (markdown). For short text only.
  379. --file Read content from a file path (preferred for long content)
  380. --cleanup Delete the --file after successful execution
  381. --name New name for edit-page
  382. --parent Parent page ID for create-page (creates as subpage)
  383. --attach File path to upload as attachment (repeatable, for attach/comment)
  384. --space Space ID for create-doc (places doc in that space)
  385. --events Comma-separated event types for watch commands (e.g. taskStatusUpdated,taskCommentPosted)
  386. Bulk Operations (comma-separated IDs):
  387. node query.mjs get id1,id2,id3 Fetch multiple tasks at once
  388. node query.mjs status id1,id2 "complete" Update status on multiple tasks
  389. node query.mjs due id1,id2 "friday" Set due date on multiple tasks
  390. Examples:
  391. node query.mjs get 86a1b2c3d --subtasks
  392. node query.mjs comment 86a1b2c3d "Starting work on this"
  393. node query.mjs status 86a1b2c3d "in progress"
  394. node query.mjs tasks 901111220963 --me
  395. node query.mjs create 901111220963 "New feature: dark mode"
  396. node query.mjs create "Quick task" (uses CLICKUP_DEFAULT_LIST_ID)
  397. node query.mjs my-tasks
  398. node query.mjs search "dark mode" --list 901111220963
  399. node query.mjs search --me --status "in progress"
  400. node query.mjs search "bug" --all # full-workspace scan (slow)
  401. node query.mjs find-list "Red Launch" # locate a list/folder by name
  402. node query.mjs assign 86a1b2c3d jane
  403. node query.mjs due 86a1b2c3d "tomorrow"
  404. node query.mjs priority 86a1b2c3d high
  405. node query.mjs subtask 86a1b2c3d "Write unit tests"
  406. node query.mjs move 86a1b2c3d 901111220964
  407. node query.mjs link 86a1b2c3d "https://github.com/..." "PR #123"
  408. node query.mjs checklist 86a1b2c3d "Review code"
  409. node query.mjs delete-comment 90110200841741
  410. node query.mjs watch 86a1b2c3d john
  411. node query.mjs tag 86a1b2c3d "DevOps"
  412. node query.mjs description 86a1b2c3d "## Summary\\nThis is **bold** text"
  413. List Examples:
  414. node query.mjs list 901111220963 # Get list details
  415. node query.mjs create-list 20128955 "New List" # Create list in space
  416. node query.mjs create-list "https://app.clickup.com/.../v/s/20128955" "New List"
  417. node query.mjs delete-list 901111220963 # Delete a list
  418. Document Examples:
  419. node query.mjs docs # List all docs
  420. node query.mjs docs "API" # Search docs
  421. node query.mjs doc abc123 # Get doc details
  422. node query.mjs create-doc "Project Notes" # Create empty doc
  423. node query.mjs create-doc "Guide" --content "# Guide\\nContent here" # Short inline content
  424. node query.mjs page abc123 page456 # Get page content
  425. node query.mjs create-page abc123 "New Section" # Add additional page
  426. node query.mjs edit-page abc123 page456 --content "Updated content" --name "Renamed"
  427. File-based Content (recommended for anything longer than a sentence):
  428. node query.mjs create-doc "Spec" --file ./spec.md --space 90114072520
  429. node query.mjs edit-page abc123 p456 --file ./updated-content.md
  430. node query.mjs comment 86a1b2c3d --file ./review-notes.md
  431. node query.mjs description 86a1b2c3d --file ./task-description.md
  432. node query.mjs create-doc "Temp" --file ./draft.md --cleanup # Deletes draft.md after
  433. `);
  434. process.exit(1);
  435. }
  436. async function main() {
  437. // Account management commands (run before initClient since they manage the config)
  438. if (command === 'accounts') {
  439. const accounts = listAccountsFn();
  440. if (accounts.length === 0) {
  441. console.log('No accounts configured. Create accounts.json or .env in the skill directory.');
  442. } else {
  443. for (const a of accounts) {
  444. const marker = a.isDefault ? ' (default)' : '';
  445. const token = a.hasApiToken ? 'token' : 'no-token';
  446. const jwt = a.hasJwt ? ', jwt' : '';
  447. console.log(` ${a.id}${marker} [${token}${jwt}]${a.email ? ` - ${a.email}` : ''}`);
  448. }
  449. }
  450. return;
  451. }
  452. if (command === 'switch-account') {
  453. if (!targetInput) {
  454. console.error('Error: Account name required');
  455. console.error('Usage: node query.mjs switch-account <name>');
  456. process.exit(1);
  457. }
  458. setDefaultAccount(targetInput);
  459. console.log(`Default account set to: ${targetInput}`);
  460. return;
  461. }
  462. if (command === 'add-account') {
  463. if (!targetInput) {
  464. console.error('Error: Account name required');
  465. console.error('Usage: node query.mjs add-account <name> --token pk_...');
  466. process.exit(1);
  467. }
  468. // Look for --token in remaining args
  469. let token = null;
  470. for (let i = 0; i < args.length; i++) {
  471. if (args[i] === '--token' && args[i + 1]) {
  472. token = args[i + 1];
  473. break;
  474. }
  475. }
  476. if (!token) {
  477. console.error('Error: --token is required');
  478. console.error('Usage: node query.mjs add-account <name> --token pk_...');
  479. process.exit(1);
  480. }
  481. addAccountFn(targetInput, { apiToken: token });
  482. console.log(`Account "${targetInput}" added.`);
  483. return;
  484. }
  485. if (command === 'remove-account') {
  486. if (!targetInput) {
  487. console.error('Error: Account name required');
  488. console.error('Usage: node query.mjs remove-account <name>');
  489. process.exit(1);
  490. }
  491. removeAccountFn(targetInput);
  492. console.log(`Account "${targetInput}" removed.`);
  493. return;
  494. }
  495. // Initialize client with selected account
  496. initClient(accountArg);
  497. if (!command) {
  498. showUsage();
  499. }
  500. // Handle commands that don't require target input
  501. if (command === 'me') {
  502. try {
  503. const user = await getCurrentUser();
  504. if (jsonOutput) {
  505. console.log(JSON.stringify(user, null, 2));
  506. } else {
  507. console.log(`User: ${user.username}`);
  508. console.log(`Email: ${user.email}`);
  509. console.log(`ID: ${user.id}`);
  510. console.log(`Timezone: ${user.timezone || 'Not set'}`);
  511. }
  512. // Cache user ID if not already cached
  513. const creds = getActiveCredentials();
  514. if (!creds.userId) {
  515. updateAccountField(getActiveAccountId(), 'userId', user.id.toString());
  516. console.error('\nCached user ID to accounts.json');
  517. }
  518. } catch (err) {
  519. console.error('Error:', err.message);
  520. process.exit(1);
  521. }
  522. return;
  523. }
  524. if (command === 'my-tasks') {
  525. try {
  526. const teamId = await getTeamId();
  527. const userId = await getUserId();
  528. const tasks = await getMyTasks(teamId, userId);
  529. if (jsonOutput) {
  530. console.log(JSON.stringify(tasks, null, 2));
  531. } else {
  532. console.log(formatTaskList(tasks));
  533. }
  534. } catch (err) {
  535. console.error('Error:', err.message);
  536. process.exit(1);
  537. }
  538. return;
  539. }
  540. if (command === 'search') {
  541. const hasScope = !!(listScopeArg || folderScopeArg || statusScopeArg || filterMe || assigneeArg);
  542. if (!hasScope && !allScopeFlag) {
  543. console.error('Error: `search` requires a scope — text search across the entire workspace is expensive.');
  544. console.error('');
  545. console.error('Pick one of:');
  546. console.error(' --list <id> scope to a single list (fastest)');
  547. console.error(' --folder <id> scope to a folder');
  548. console.error(' --me tasks assigned to you');
  549. console.error(' --assignee <u> tasks assigned to a specific user');
  550. console.error(' --status <name> tasks with a given status (repeatable via comma)');
  551. console.error(' --all unscoped full-workspace scan (slow, use sparingly)');
  552. console.error('');
  553. console.error('Looking for a list or folder by name? Use `find-list "name"` instead.');
  554. process.exit(1);
  555. }
  556. try {
  557. const teamId = await getTeamId();
  558. const opts = {};
  559. if (listScopeArg) opts.list_ids = [listScopeArg];
  560. if (folderScopeArg) opts.project_ids = [folderScopeArg];
  561. if (statusScopeArg) opts.statuses = statusScopeArg.split(',').map(s => s.trim()).filter(Boolean);
  562. if (filterMe || assigneeArg) {
  563. const who = assigneeArg ? await findUser(teamId, assigneeArg) : null;
  564. opts.assigneeId = filterMe ? await getUserId() : (who?.id || who);
  565. }
  566. if (allScopeFlag) opts.all = true;
  567. const tasks = await searchTasks(teamId, targetInput || '', opts);
  568. if (jsonOutput) {
  569. console.log(JSON.stringify(tasks, null, 2));
  570. } else if (tasks.length === 0) {
  571. const q = targetInput ? ` matching "${targetInput}"` : '';
  572. console.log(`No tasks found${q}`);
  573. } else {
  574. console.log(formatTaskList(tasks));
  575. }
  576. } catch (err) {
  577. console.error('Error:', err.message);
  578. process.exit(1);
  579. }
  580. return;
  581. }
  582. if (command === 'find-list') {
  583. if (!targetInput) {
  584. console.error('Error: find-list requires a name query');
  585. console.error('Usage: node query.mjs find-list "partial name"');
  586. process.exit(1);
  587. }
  588. try {
  589. const teamId = await getTeamId();
  590. const { lists, folders } = await findListByName(teamId, targetInput);
  591. if (jsonOutput) {
  592. console.log(JSON.stringify({ lists, folders }, null, 2));
  593. } else if (!lists.length && !folders.length) {
  594. console.log(`No lists or folders matching "${targetInput}"`);
  595. } else {
  596. if (lists.length) {
  597. console.log(`Lists (${lists.length}):`);
  598. for (const l of lists) {
  599. const loc = l.folder ? `${l.space.name} / ${l.folder.name}` : `${l.space.name} (folderless)`;
  600. console.log(` ${l.name}`);
  601. console.log(` id: ${l.id} — ${loc}`);
  602. }
  603. }
  604. if (folders.length) {
  605. if (lists.length) console.log('');
  606. console.log(`Folders (${folders.length}):`);
  607. for (const f of folders) {
  608. console.log(` ${f.name}`);
  609. console.log(` id: ${f.id} — ${f.space.name} — ${f.listCount} list(s)`);
  610. for (const l of f.lists) {
  611. console.log(` • ${l.name} (list id: ${l.id})`);
  612. }
  613. }
  614. }
  615. }
  616. } catch (err) {
  617. console.error('Error:', err.message);
  618. process.exit(1);
  619. }
  620. return;
  621. }
  622. // Document commands that may not require a target
  623. if (command === 'docs') {
  624. try {
  625. const workspaceId = await getTeamId();
  626. const options = targetInput ? { query: targetInput } : {};
  627. const result = await searchDocs(workspaceId, options);
  628. const docs = result.docs || [];
  629. if (jsonOutput) {
  630. console.log(JSON.stringify(result, null, 2));
  631. } else {
  632. if (docs.length === 0) {
  633. console.log(targetInput ? `No docs found matching "${targetInput}"` : 'No docs found.');
  634. } else {
  635. console.log(formatDocList(docs));
  636. }
  637. }
  638. } catch (err) {
  639. console.error('Error:', err.message);
  640. process.exit(1);
  641. }
  642. return;
  643. }
  644. if (command === 'create-doc') {
  645. if (!targetInput) {
  646. console.error('Error: Doc title required');
  647. console.error('Usage: node query.mjs create-doc "Doc Title" [--space <space_id>] [--content "content"]');
  648. process.exit(1);
  649. }
  650. try {
  651. const workspaceId = await getTeamId();
  652. const options = {};
  653. if (contentArg) {
  654. options.content = contentArg;
  655. }
  656. if (spaceArg) {
  657. const spaceId = parseSpaceId(spaceArg);
  658. options.parent = { id: spaceId, type: 4 };
  659. }
  660. const doc = await createDoc(workspaceId, targetInput, options);
  661. if (jsonOutput) {
  662. console.log(JSON.stringify(doc, null, 2));
  663. } else {
  664. console.log(`Doc created: ${doc.name}`);
  665. console.log(`ID: ${doc.id}`);
  666. if (spaceArg) {
  667. console.log(`Space: ${spaceArg}`);
  668. }
  669. if (doc.firstPageId) {
  670. console.log(`First page populated with content`);
  671. }
  672. }
  673. } catch (err) {
  674. console.error('Error:', err.message);
  675. process.exit(1);
  676. }
  677. return;
  678. }
  679. if (command === 'lists') {
  680. if (!targetInput) {
  681. console.error('Error: Folder ID required');
  682. console.error('Usage: node query.mjs lists <folder_id>');
  683. process.exit(1);
  684. }
  685. try {
  686. const folderId = targetInput;
  687. const lists = await getLists(folderId);
  688. if (jsonOutput) {
  689. console.log(JSON.stringify(lists, null, 2));
  690. } else {
  691. if (lists.length === 0) {
  692. console.log('No lists found in this folder.');
  693. } else {
  694. for (const l of lists) {
  695. console.log(` ${l.name} (ID: ${l.id})`);
  696. }
  697. console.log(`\nTotal: ${lists.length} list(s)`);
  698. }
  699. }
  700. } catch (err) {
  701. console.error('Error:', err.message);
  702. process.exit(1);
  703. }
  704. return;
  705. }
  706. if (command === 'space-lists') {
  707. if (!targetInput) {
  708. console.error('Error: Space ID required');
  709. console.error('Usage: node query.mjs space-lists <space_id>');
  710. process.exit(1);
  711. }
  712. try {
  713. const spaceId = parseSpaceId(targetInput);
  714. const lists = await getFolderlessLists(spaceId);
  715. if (jsonOutput) {
  716. console.log(JSON.stringify(lists, null, 2));
  717. } else {
  718. if (lists.length === 0) {
  719. console.log('No folderless lists found in this space.');
  720. } else {
  721. for (const l of lists) {
  722. console.log(` ${l.name} (ID: ${l.id})`);
  723. }
  724. console.log(`\nTotal: ${lists.length} list(s)`);
  725. }
  726. }
  727. } catch (err) {
  728. console.error('Error:', err.message);
  729. process.exit(1);
  730. }
  731. return;
  732. }
  733. // Batch create from JSON file
  734. if (command === 'batch-create') {
  735. if (!fileArg && !contentArg) {
  736. console.error('Error: --file or --content required with a JSON plan');
  737. console.error('Usage: node query.mjs batch-create --file plan.json');
  738. console.error(' node query.mjs batch-create --content \'{"listId":"...","tasks":[...]}\'');
  739. process.exit(1);
  740. }
  741. try {
  742. const planText = contentArg || readFileSync(resolve(fileArg), 'utf-8');
  743. const plan = JSON.parse(planText);
  744. const dryRun = args.includes('--dry-run');
  745. const verbose = !jsonOutput; // verbose by default unless --json
  746. const result = await executeBatchCreate(plan, { verbose, dryRun });
  747. if (jsonOutput) {
  748. console.log(JSON.stringify(result, null, 2));
  749. } else {
  750. console.log(`\n${result.message}`);
  751. if (result.errors.length > 0) {
  752. console.log('\nErrors:');
  753. for (const e of result.errors) {
  754. console.log(` ${e.ref || e.name || '?'}: ${e.error}`);
  755. }
  756. }
  757. }
  758. } catch (err) {
  759. console.error('Error:', err.message);
  760. process.exit(1);
  761. }
  762. return;
  763. }
  764. // Watcher commands that don't require a target
  765. if (command === 'watchers') {
  766. const entries = getWatcherEntries();
  767. if (entries.length === 0) {
  768. console.log('No active watchers. Use watch-task, watch-list, or watch-space to create one.');
  769. } else if (jsonOutput) {
  770. console.log(JSON.stringify(entries, null, 2));
  771. } else {
  772. console.log(`Active watchers (${entries.length}):\n`);
  773. for (const e of entries) {
  774. console.log(` ${e.webhookId} | ${e.scope}:${e.scopeId} | ${e.events.length} events | ${e.createdAt}`);
  775. }
  776. }
  777. return;
  778. }
  779. if (command === 'webhooks') {
  780. try {
  781. const webhooks = await listWebhooks();
  782. if (webhooks.length === 0) {
  783. console.log('No webhooks registered in workspace.');
  784. } else if (jsonOutput) {
  785. console.log(JSON.stringify(webhooks, null, 2));
  786. } else {
  787. console.log(`Webhooks in workspace (${webhooks.length}):\n`);
  788. for (const wh of webhooks) {
  789. const health = wh.health?.status || '?';
  790. const fails = wh.health?.fail_count || 0;
  791. const scope = wh.task_id ? `task:${wh.task_id}` :
  792. wh.list_id ? `list:${wh.list_id}` :
  793. wh.folder_id ? `folder:${wh.folder_id}` :
  794. wh.space_id ? `space:${wh.space_id}` : 'workspace';
  795. console.log(` ${wh.id} | ${scope} | ${wh.events?.length || 0} events | ${health} (${fails} fails)`);
  796. console.log(` → ${wh.endpoint}`);
  797. }
  798. }
  799. } catch (err) {
  800. console.error('Error:', err.message);
  801. process.exit(1);
  802. }
  803. return;
  804. }
  805. // All other commands require a target
  806. if (!targetInput) {
  807. showUsage();
  808. }
  809. try {
  810. switch (command) {
  811. case 'get': {
  812. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  813. if (ids.length === 0) {
  814. console.error('Error: Could not parse task ID from input');
  815. process.exit(1);
  816. }
  817. if (ids.length === 1) {
  818. const task = await getTask(ids[0], includeSubtasks);
  819. if (jsonOutput) {
  820. console.log(JSON.stringify(task, null, 2));
  821. } else {
  822. console.log(formatTask(task));
  823. }
  824. } else {
  825. const results = await bulkExecute(ids, id => getTask(id, includeSubtasks));
  826. if (jsonOutput) {
  827. console.log(JSON.stringify(results.succeeded.map(s => s.result), null, 2));
  828. } else {
  829. for (const s of results.succeeded) {
  830. console.log(formatTask(s.result));
  831. console.log('');
  832. }
  833. if (results.failed.length > 0) {
  834. console.log(formatBulkResults({ ...results, succeeded: [] }));
  835. }
  836. }
  837. }
  838. break;
  839. }
  840. case 'comments': {
  841. const taskId = parseTaskId(targetInput);
  842. if (!taskId) {
  843. console.error('Error: Could not parse task ID from input');
  844. process.exit(1);
  845. }
  846. const comments = await getComments(taskId);
  847. // If --threads flag, auto-expand all threads with replies
  848. let threadMap = {};
  849. if (threadsFlag) {
  850. const threaded = comments.filter(c => parseInt(c.reply_count, 10) > 0);
  851. if (threaded.length > 0) {
  852. const threadResults = await Promise.all(
  853. threaded.map(c => getThreadedComments(c.id).then(replies => [c.id, replies]))
  854. );
  855. for (const [id, replies] of threadResults) {
  856. threadMap[id] = replies;
  857. }
  858. }
  859. }
  860. if (jsonOutput) {
  861. if (threadsFlag) {
  862. // Embed replies into each comment for JSON output
  863. const enriched = comments.map(c => ({
  864. ...c,
  865. replies: threadMap[c.id] || [],
  866. }));
  867. console.log(JSON.stringify(enriched, null, 2));
  868. } else {
  869. console.log(JSON.stringify(comments, null, 2));
  870. }
  871. } else {
  872. console.log(formatComments(comments, threadMap));
  873. }
  874. break;
  875. }
  876. case 'thread': {
  877. const commentId = targetInput;
  878. if (!commentId) {
  879. console.error('Error: Comment ID required');
  880. console.error('Usage: node query.mjs thread <comment_id>');
  881. process.exit(1);
  882. }
  883. const replies = await getThreadedComments(commentId);
  884. if (jsonOutput) {
  885. console.log(JSON.stringify(replies, null, 2));
  886. } else {
  887. console.log(formatThread(null, replies));
  888. }
  889. break;
  890. }
  891. case 'reply': {
  892. const commentId = targetInput;
  893. if (!commentId) {
  894. console.error('Error: Comment ID required');
  895. console.error('Usage: node query.mjs reply <comment_id> "reply text"');
  896. process.exit(1);
  897. }
  898. if (!commentText) {
  899. console.error('Error: Reply text required');
  900. console.error('Usage: node query.mjs reply <comment_id> "reply text"');
  901. process.exit(1);
  902. }
  903. const result = await replyToComment(commentId, commentText);
  904. if (jsonOutput) {
  905. console.log(JSON.stringify(result, null, 2));
  906. } else {
  907. console.log(`Reply posted successfully (ID: ${result.id || 'ok'})`);
  908. }
  909. break;
  910. }
  911. case 'comment': {
  912. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  913. if (ids.length === 0) {
  914. console.error('Error: Could not parse task ID from input');
  915. process.exit(1);
  916. }
  917. if (!commentText) {
  918. console.error('Error: Comment text required');
  919. console.error('Usage: node query.mjs comment <url|id[,id,...]> "Your comment" [--attach ./file.png]');
  920. process.exit(1);
  921. }
  922. // Resolve --attach file paths for comment attachments
  923. const commentAttachFiles = attachArgs.map(f => resolve(f));
  924. if (commentAttachFiles.length > 0) {
  925. for (const fp of commentAttachFiles) {
  926. if (!existsSync(fp)) {
  927. console.error(`Error: Attachment file not found: ${fp}`);
  928. process.exit(1);
  929. }
  930. }
  931. }
  932. if (ids.length === 1) {
  933. const result = await postComment(ids[0], commentText);
  934. if (jsonOutput) {
  935. const output = { comment: result };
  936. if (commentAttachFiles.length > 0) {
  937. output.attachments = await uploadAttachments(ids[0], commentAttachFiles);
  938. }
  939. console.log(JSON.stringify(output, null, 2));
  940. } else {
  941. console.log(`Comment posted successfully (ID: ${result.id})`);
  942. if (commentAttachFiles.length > 0) {
  943. const attResults = await uploadAttachments(ids[0], commentAttachFiles);
  944. for (const r of attResults) {
  945. const att = r.attachment || r;
  946. console.log(` Attached: ${att.title || att.name || 'file'}`);
  947. }
  948. }
  949. }
  950. } else {
  951. const results = await bulkExecute(ids, async (id) => {
  952. const comment = await postComment(id, commentText);
  953. let attachments;
  954. if (commentAttachFiles.length > 0) {
  955. attachments = await uploadAttachments(id, commentAttachFiles);
  956. }
  957. return { comment, attachments };
  958. });
  959. if (jsonOutput) {
  960. console.log(JSON.stringify(results, null, 2));
  961. } else {
  962. console.log(formatBulkResults(results, { action: 'Comment posted on' }));
  963. if (commentAttachFiles.length > 0) {
  964. console.log(` (${commentAttachFiles.length} file(s) attached to each task)`);
  965. }
  966. }
  967. }
  968. break;
  969. }
  970. case 'status': {
  971. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  972. if (ids.length === 0) {
  973. console.error('Error: Could not parse task ID from input');
  974. process.exit(1);
  975. }
  976. if (!commentText) {
  977. // No status provided - show available statuses (single task only)
  978. const statuses = await getAvailableStatuses(ids[0]);
  979. console.log('Available statuses:');
  980. for (const s of statuses) {
  981. console.log(` - "${s.status}" (${s.type})`);
  982. }
  983. break;
  984. }
  985. if (ids.length === 1) {
  986. const { task, matchedStatus } = await updateTaskStatus(ids[0], commentText);
  987. if (jsonOutput) {
  988. console.log(JSON.stringify(task, null, 2));
  989. } else {
  990. console.log(`Status updated to "${matchedStatus.status}"`);
  991. }
  992. } else {
  993. const results = await bulkExecute(ids, id => updateTaskStatus(id, commentText));
  994. if (jsonOutput) {
  995. console.log(JSON.stringify(results, null, 2));
  996. } else {
  997. console.log(formatBulkResults(results, {
  998. action: 'Updated',
  999. formatItem: s => `${s.id}: status → "${s.result.matchedStatus.status}"`,
  1000. }));
  1001. }
  1002. }
  1003. break;
  1004. }
  1005. case 'tasks': {
  1006. const listId = parseListId(targetInput);
  1007. if (!listId) {
  1008. console.error('Error: Could not parse list ID from input');
  1009. process.exit(1);
  1010. }
  1011. let assigneeId = null;
  1012. if (filterMe) {
  1013. assigneeId = await getUserId();
  1014. }
  1015. const tasks = await getTasksInList(listId, assigneeId);
  1016. if (jsonOutput) {
  1017. console.log(JSON.stringify(tasks, null, 2));
  1018. } else {
  1019. console.log(formatTaskList(tasks));
  1020. }
  1021. break;
  1022. }
  1023. case 'create': {
  1024. // Support: create <list_id> "title" [options] OR create "title" [options] (uses default list)
  1025. // Options: --assignee/-a <user>, --due/-d <date>, --description/--desc <text>
  1026. let listId = parseListId(targetInput);
  1027. let title = arg2;
  1028. // If targetInput doesn't parse as a list ID, treat it as the title
  1029. if (!listId) {
  1030. title = targetInput;
  1031. listId = getActiveCredentials().defaultListId;
  1032. if (!listId) {
  1033. console.error('Error: No list ID provided and no defaultListId set for this account');
  1034. console.error('Usage: node query.mjs create <list_id> "Task title" [options]');
  1035. console.error(' Or: Set defaultListId in accounts.json to use: node query.mjs create "Task title"');
  1036. console.error('Options: --assignee/-a <user>, --due/-d <date>, --description/--desc <text>');
  1037. process.exit(1);
  1038. }
  1039. }
  1040. if (!title) {
  1041. console.error('Error: Task title required');
  1042. console.error('Usage: node query.mjs create <list_id> "Task title" [options]');
  1043. console.error('Options: --assignee/-a <user>, --due/-d <date>, --description/--desc <text>');
  1044. process.exit(1);
  1045. }
  1046. // Build options from flags
  1047. const options = {};
  1048. // --file/--content populate contentArg; accept them here too so a long
  1049. // description doesn't have to go through a second `description` call.
  1050. const createDescription = descriptionArg || contentArg;
  1051. if (createDescription) {
  1052. // Use markdown_description for proper markdown rendering in ClickUp
  1053. // Note: Task descriptions use markdown_description (ClickUp parses),
  1054. // while comments use JSON array format (we parse via markdownToClickUp)
  1055. options.markdown_description = createDescription;
  1056. }
  1057. if (dueArg) {
  1058. const dueDate = parseDateInput(dueArg);
  1059. options.due_date = dueDate.getTime();
  1060. }
  1061. if (assigneeArg) {
  1062. let assigneeId;
  1063. if (assigneeArg.toLowerCase() === 'me') {
  1064. // Special case: "me" means the current authenticated user
  1065. assigneeId = await getUserId();
  1066. } else {
  1067. const teamId = await getTeamId();
  1068. const user = await findUser(teamId, assigneeArg);
  1069. if (!user) {
  1070. console.error(`Error: User "${assigneeArg}" not found in team`);
  1071. process.exit(1);
  1072. }
  1073. assigneeId = user.id;
  1074. }
  1075. options.assignees = [assigneeId];
  1076. }
  1077. const task = await createTask(listId, title, options);
  1078. if (jsonOutput) {
  1079. console.log(JSON.stringify(task, null, 2));
  1080. } else {
  1081. console.log(`Task created: ${task.name}`);
  1082. console.log(`ID: ${task.id}`);
  1083. if (task.assignees?.length) {
  1084. console.log(`Assignees: ${task.assignees.map(a => a.username).join(', ')}`);
  1085. }
  1086. if (task.due_date) {
  1087. console.log(`Due: ${new Date(parseInt(task.due_date, 10)).toLocaleDateString()}`);
  1088. }
  1089. console.log(`URL: ${task.url}`);
  1090. }
  1091. break;
  1092. }
  1093. case 'assign': {
  1094. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  1095. if (ids.length === 0) {
  1096. console.error('Error: Could not parse task ID from input');
  1097. process.exit(1);
  1098. }
  1099. if (!arg2) {
  1100. console.error('Error: User required');
  1101. console.error('Usage: node query.mjs assign <task[,task,...]> <user>');
  1102. process.exit(1);
  1103. }
  1104. const teamId = await getTeamId();
  1105. const user = await findUser(teamId, arg2);
  1106. if (!user) {
  1107. console.error(`Error: User "${arg2}" not found in team`);
  1108. process.exit(1);
  1109. }
  1110. if (ids.length === 1) {
  1111. const task = await assignTask(ids[0], [user.id]);
  1112. if (jsonOutput) {
  1113. console.log(JSON.stringify(task, null, 2));
  1114. } else {
  1115. console.log(`Task assigned to ${user.username || user.email}`);
  1116. }
  1117. } else {
  1118. const results = await bulkExecute(ids, id => assignTask(id, [user.id]));
  1119. if (jsonOutput) {
  1120. console.log(JSON.stringify(results, null, 2));
  1121. } else {
  1122. console.log(formatBulkResults(results, { action: `Assigned to ${user.username || user.email}:` }));
  1123. }
  1124. }
  1125. break;
  1126. }
  1127. case 'due': {
  1128. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  1129. if (ids.length === 0) {
  1130. console.error('Error: Could not parse task ID from input');
  1131. process.exit(1);
  1132. }
  1133. if (!arg2) {
  1134. console.error('Error: Due date required');
  1135. console.error('Usage: node query.mjs due <task[,task,...]> "date"');
  1136. console.error('Examples: "tomorrow", "next friday", "2024-01-15", "+3d"');
  1137. process.exit(1);
  1138. }
  1139. if (ids.length === 1) {
  1140. const task = await setDueDate(ids[0], arg2);
  1141. if (jsonOutput) {
  1142. console.log(JSON.stringify(task, null, 2));
  1143. } else {
  1144. const dueDate = task.due_date ? new Date(parseInt(task.due_date, 10)).toLocaleDateString() : 'cleared';
  1145. console.log(`Due date set to: ${dueDate}`);
  1146. }
  1147. } else {
  1148. const results = await bulkExecute(ids, id => setDueDate(id, arg2));
  1149. if (jsonOutput) {
  1150. console.log(JSON.stringify(results, null, 2));
  1151. } else {
  1152. console.log(formatBulkResults(results, { action: 'Due date set on' }));
  1153. }
  1154. }
  1155. break;
  1156. }
  1157. case 'start': {
  1158. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  1159. if (ids.length === 0) {
  1160. console.error('Error: Could not parse task ID from input');
  1161. process.exit(1);
  1162. }
  1163. if (!arg2) {
  1164. console.error('Error: Start date required');
  1165. console.error('Usage: node query.mjs start <task[,task,...]> "date"');
  1166. console.error('Examples: "today", "tomorrow", "2024-01-15", "+3d"');
  1167. process.exit(1);
  1168. }
  1169. if (ids.length === 1) {
  1170. const task = await setStartDate(ids[0], arg2);
  1171. if (jsonOutput) {
  1172. console.log(JSON.stringify(task, null, 2));
  1173. } else {
  1174. const startDate = task.start_date ? new Date(parseInt(task.start_date, 10)).toLocaleDateString() : 'cleared';
  1175. console.log(`Start date set to: ${startDate}`);
  1176. }
  1177. } else {
  1178. const results = await bulkExecute(ids, id => setStartDate(id, arg2));
  1179. if (jsonOutput) {
  1180. console.log(JSON.stringify(results, null, 2));
  1181. } else {
  1182. console.log(formatBulkResults(results, { action: 'Start date set on' }));
  1183. }
  1184. }
  1185. break;
  1186. }
  1187. case 'schedule': {
  1188. const taskId = parseTaskId(targetInput);
  1189. if (!taskId) {
  1190. console.error('Error: Could not parse task ID from input');
  1191. process.exit(1);
  1192. }
  1193. if (!arg2 || !arg3) {
  1194. console.error('Error: Both start and due dates required');
  1195. console.error('Usage: node query.mjs schedule <task> "start_date" "due_date"');
  1196. console.error('Examples: node query.mjs schedule abc123 "today" "friday"');
  1197. process.exit(1);
  1198. }
  1199. const task = await setDates(taskId, { start: arg2, due: arg3 });
  1200. if (jsonOutput) {
  1201. console.log(JSON.stringify(task, null, 2));
  1202. } else {
  1203. const startDate = task.start_date ? new Date(parseInt(task.start_date, 10)).toLocaleDateString() : 'not set';
  1204. const dueDate = task.due_date ? new Date(parseInt(task.due_date, 10)).toLocaleDateString() : 'not set';
  1205. console.log(`Scheduled: ${startDate} → ${dueDate}`);
  1206. }
  1207. break;
  1208. }
  1209. case 'rename': {
  1210. const taskId = parseTaskId(targetInput);
  1211. if (!taskId) {
  1212. console.error('Error: Could not parse task ID from input');
  1213. process.exit(1);
  1214. }
  1215. if (!arg2) {
  1216. console.error('Error: New name required');
  1217. console.error('Usage: node query.mjs rename <task> "new name"');
  1218. process.exit(1);
  1219. }
  1220. const task = await updateTask(taskId, { name: arg2 });
  1221. if (jsonOutput) {
  1222. console.log(JSON.stringify(task, null, 2));
  1223. } else {
  1224. console.log(`Task renamed to: ${task.name}`);
  1225. }
  1226. break;
  1227. }
  1228. case 'priority': {
  1229. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  1230. if (ids.length === 0) {
  1231. console.error('Error: Could not parse task ID from input');
  1232. process.exit(1);
  1233. }
  1234. if (!arg2) {
  1235. console.error('Error: Priority level required');
  1236. console.error('Usage: node query.mjs priority <task[,task,...]> <level>');
  1237. console.error('Levels: urgent, high, normal, low, none');
  1238. process.exit(1);
  1239. }
  1240. if (ids.length === 1) {
  1241. const { task, priority } = await setPriority(ids[0], arg2);
  1242. if (jsonOutput) {
  1243. console.log(JSON.stringify(task, null, 2));
  1244. } else {
  1245. console.log(`Priority set to: ${priority}`);
  1246. }
  1247. } else {
  1248. const results = await bulkExecute(ids, id => setPriority(id, arg2));
  1249. if (jsonOutput) {
  1250. console.log(JSON.stringify(results, null, 2));
  1251. } else {
  1252. console.log(formatBulkResults(results, {
  1253. action: 'Priority set on',
  1254. formatItem: s => `${s.id}: priority → ${s.result.priority}`,
  1255. }));
  1256. }
  1257. }
  1258. break;
  1259. }
  1260. case 'subtask': {
  1261. const taskId = parseTaskId(targetInput);
  1262. if (!taskId) {
  1263. console.error('Error: Could not parse task ID from input');
  1264. process.exit(1);
  1265. }
  1266. if (!arg2) {
  1267. console.error('Error: Subtask title required');
  1268. console.error('Usage: node query.mjs subtask <task> "Subtask title"');
  1269. process.exit(1);
  1270. }
  1271. const subtask = await createSubtask(taskId, arg2);
  1272. if (jsonOutput) {
  1273. console.log(JSON.stringify(subtask, null, 2));
  1274. } else {
  1275. console.log(`Subtask created: ${subtask.name}`);
  1276. console.log(`ID: ${subtask.id}`);
  1277. console.log(`URL: ${subtask.url}`);
  1278. }
  1279. break;
  1280. }
  1281. case 'parent': {
  1282. const taskId = parseTaskId(targetInput);
  1283. if (!taskId) {
  1284. console.error('Error: Could not parse task ID from input');
  1285. process.exit(1);
  1286. }
  1287. if (!arg2) {
  1288. console.error('Error: Parent task ID required');
  1289. console.error('Usage: node query.mjs parent <task> <parent_task>');
  1290. console.error(
  1291. 'ClickUp has no detach: a subtask cannot be turned back into a top-level task.'
  1292. );
  1293. process.exit(1);
  1294. }
  1295. const newParentId = parseTaskId(arg2);
  1296. if (!newParentId) {
  1297. console.error('Error: Could not parse parent task ID');
  1298. process.exit(1);
  1299. }
  1300. if (newParentId === taskId) {
  1301. console.error(`Error: Task ${taskId} cannot be its own parent`);
  1302. process.exit(1);
  1303. }
  1304. const before = await getTask(taskId);
  1305. const parentAncestors = await getAncestorIds(newParentId);
  1306. if (parentAncestors.includes(taskId)) {
  1307. console.error(
  1308. `Error: ${newParentId} is already a descendant of ${taskId} — this would create a cycle`
  1309. );
  1310. console.error(`Chain: ${newParentId} -> ${parentAncestors.join(' -> ')}`);
  1311. process.exit(1);
  1312. }
  1313. if (before.parent === newParentId) {
  1314. console.log(`No change: ${taskId} is already a subtask of ${newParentId}`);
  1315. break;
  1316. }
  1317. await setParent(taskId, newParentId);
  1318. // Report the server's state, not the request we sent — and fail before
  1319. // printing anything success-shaped, because ClickUp can accept an
  1320. // UpdateTask and ignore the `parent` in it.
  1321. const after = await getTask(taskId);
  1322. if (after.parent !== newParentId) {
  1323. console.error(
  1324. `Error: re-read shows parent ${after.parent ?? 'none'}, expected ${newParentId}`
  1325. );
  1326. process.exit(1);
  1327. }
  1328. if (jsonOutput) {
  1329. console.log(JSON.stringify(after, null, 2));
  1330. } else {
  1331. console.log(`Parent now: ${after.parent} (was ${before.parent ?? 'none'})`);
  1332. if (after.list?.id !== before.list?.id) {
  1333. console.log(
  1334. `List moved: ${before.list?.name ?? before.list?.id} -> ${
  1335. after.list?.name ?? after.list?.id
  1336. }`
  1337. );
  1338. }
  1339. console.log(
  1340. `Status: ${after.status?.status ?? 'unknown'}, priority: ${
  1341. after.priority?.priority ?? 'none'
  1342. }`
  1343. );
  1344. if (after.url) console.log(`URL: ${after.url}`);
  1345. }
  1346. break;
  1347. }
  1348. case 'milestone': {
  1349. const taskId = parseTaskId(targetInput);
  1350. if (!taskId) {
  1351. console.error('Error: Could not parse task ID from input');
  1352. process.exit(1);
  1353. }
  1354. if (!arg2) {
  1355. console.error('Error: Mode required');
  1356. console.error('Usage: node query.mjs milestone <task> <on|off>');
  1357. process.exit(1);
  1358. }
  1359. const mode = arg2.toLowerCase();
  1360. if (!['on', 'off'].includes(mode)) {
  1361. console.error(`Error: Unknown mode "${arg2}"`);
  1362. console.error('Usage: node query.mjs milestone <task> <on|off>');
  1363. process.exit(1);
  1364. }
  1365. const workspaceId = await getTeamId();
  1366. const milestoneType = await findCustomItemByName(workspaceId, 'milestone');
  1367. if (!milestoneType) {
  1368. console.error('Error: This workspace has no "milestone" task type');
  1369. process.exit(1);
  1370. }
  1371. // Clearing the type is WRITTEN as null but READS BACK as 0 (measured
  1372. // against a real task), so the wanted value for `off` is 0, not null.
  1373. const wanted = mode === 'on' ? milestoneType.id : 0;
  1374. const before = await getTask(taskId);
  1375. const beforeId = before.custom_item_id;
  1376. // A missing field is not evidence of anything, so it must not satisfy
  1377. // the no-op — fall through and let the re-read decide.
  1378. if (typeof beforeId === 'number' && beforeId === wanted) {
  1379. console.log(
  1380. `No change: ${taskId} is already ${mode === 'on' ? 'a milestone' : 'a regular task'}`
  1381. );
  1382. break;
  1383. }
  1384. await setCustomItemId(taskId, mode === 'on' ? milestoneType.id : null);
  1385. const after = await getTask(taskId);
  1386. const afterId = after.custom_item_id;
  1387. if (afterId !== wanted) {
  1388. console.error(
  1389. `Error: re-read shows custom_item_id ${afterId ?? 'absent'}, expected ${wanted}`
  1390. );
  1391. process.exit(1);
  1392. }
  1393. if (jsonOutput) {
  1394. console.log(JSON.stringify(after, null, 2));
  1395. } else {
  1396. console.log(
  1397. `Type now: ${
  1398. afterId === milestoneType.id ? 'milestone' : 'task'
  1399. } (custom_item_id ${afterId}, was ${beforeId ?? 'absent'})`
  1400. );
  1401. if (after.url) console.log(`URL: ${after.url}`);
  1402. }
  1403. break;
  1404. }
  1405. case 'move': {
  1406. const taskId = parseTaskId(targetInput);
  1407. if (!taskId) {
  1408. console.error('Error: Could not parse task ID from input');
  1409. process.exit(1);
  1410. }
  1411. if (!arg2) {
  1412. console.error('Error: Target list ID required');
  1413. console.error('Usage: node query.mjs move <task> <list_id>');
  1414. process.exit(1);
  1415. }
  1416. const listId = parseListId(arg2);
  1417. const workspaceId = await getTeamId();
  1418. const task = await moveTask(taskId, listId, workspaceId);
  1419. if (jsonOutput) {
  1420. console.log(JSON.stringify(task, null, 2));
  1421. } else {
  1422. console.log(`Task moved successfully`);
  1423. if (task.url) console.log(`URL: ${task.url}`);
  1424. }
  1425. break;
  1426. }
  1427. case 'link': {
  1428. const taskId = parseTaskId(targetInput);
  1429. if (!taskId) {
  1430. console.error('Error: Could not parse task ID from input');
  1431. process.exit(1);
  1432. }
  1433. if (!arg2) {
  1434. console.error('Error: URL required');
  1435. console.error('Usage: node query.mjs link <task> <url> ["description"]');
  1436. process.exit(1);
  1437. }
  1438. const result = await addExternalLink(taskId, arg2, arg3);
  1439. if (jsonOutput) {
  1440. console.log(JSON.stringify(result, null, 2));
  1441. } else {
  1442. console.log(`Link added as comment (ID: ${result.id})`);
  1443. }
  1444. break;
  1445. }
  1446. case 'checklist': {
  1447. const taskId = parseTaskId(targetInput);
  1448. if (!taskId) {
  1449. console.error('Error: Could not parse task ID from input');
  1450. process.exit(1);
  1451. }
  1452. if (!arg2) {
  1453. console.error('Error: Checklist item required');
  1454. console.error('Usage: node query.mjs checklist <task> "Item text"');
  1455. process.exit(1);
  1456. }
  1457. const { checklist, item } = await addChecklistItemToTask(taskId, arg2);
  1458. if (jsonOutput) {
  1459. console.log(JSON.stringify({ checklist, item }, null, 2));
  1460. } else {
  1461. console.log(`Added to checklist "${checklist.name}"`);
  1462. }
  1463. break;
  1464. }
  1465. case 'update-comment': {
  1466. const commentId = targetInput;
  1467. if (!commentId) {
  1468. console.error('Error: Comment ID required');
  1469. console.error('Usage: node query.mjs update-comment <comment_id> "new text"');
  1470. process.exit(1);
  1471. }
  1472. if (!arg2) {
  1473. console.error('Error: Comment text required');
  1474. console.error('Usage: node query.mjs update-comment <comment_id> "new text"');
  1475. process.exit(1);
  1476. }
  1477. const result = await updateComment(commentId, { comment_text: arg2 });
  1478. if (jsonOutput) {
  1479. console.log(JSON.stringify(result, null, 2));
  1480. } else {
  1481. console.log(`Comment ${commentId} updated`);
  1482. }
  1483. break;
  1484. }
  1485. case 'resolve-comment': {
  1486. const commentId = targetInput;
  1487. if (!commentId) {
  1488. console.error('Error: Comment ID required');
  1489. console.error('Usage: node query.mjs resolve-comment <comment_id>');
  1490. process.exit(1);
  1491. }
  1492. const result = await updateComment(commentId, { resolved: true });
  1493. if (jsonOutput) {
  1494. console.log(JSON.stringify(result, null, 2));
  1495. } else {
  1496. console.log(`Comment ${commentId} resolved`);
  1497. }
  1498. break;
  1499. }
  1500. case 'delete-comment': {
  1501. const commentId = targetInput;
  1502. if (!commentId) {
  1503. console.error('Error: Comment ID required');
  1504. console.error('Usage: node query.mjs delete-comment <comment_id>');
  1505. process.exit(1);
  1506. }
  1507. await deleteComment(commentId);
  1508. if (jsonOutput) {
  1509. console.log(JSON.stringify({ deleted: true, commentId }, null, 2));
  1510. } else {
  1511. console.log(`Comment ${commentId} deleted`);
  1512. }
  1513. break;
  1514. }
  1515. case 'watch': {
  1516. const taskId = parseTaskId(targetInput);
  1517. if (!taskId) {
  1518. console.error('Error: Could not parse task ID from input');
  1519. process.exit(1);
  1520. }
  1521. if (!arg2) {
  1522. console.error('Error: User required');
  1523. console.error('Usage: node query.mjs watch <task> <user>');
  1524. process.exit(1);
  1525. }
  1526. const teamId = await getTeamId();
  1527. const user = await findUser(teamId, arg2);
  1528. if (!user) {
  1529. console.error(`Error: User "${arg2}" not found in team`);
  1530. process.exit(1);
  1531. }
  1532. const result = await addWatcher(taskId, user.id);
  1533. if (jsonOutput) {
  1534. console.log(JSON.stringify(result, null, 2));
  1535. } else {
  1536. console.log(`Added ${user.username || user.email} as watcher`);
  1537. }
  1538. break;
  1539. }
  1540. case 'unwatch': {
  1541. const taskId = parseTaskId(targetInput);
  1542. if (!taskId) {
  1543. console.error('Error: Could not parse task ID from input');
  1544. process.exit(1);
  1545. }
  1546. if (!arg2) {
  1547. console.error('Error: User required');
  1548. console.error('Usage: node query.mjs unwatch <task> <user>');
  1549. process.exit(1);
  1550. }
  1551. const teamId = await getTeamId();
  1552. const user = await findUser(teamId, arg2);
  1553. if (!user) {
  1554. console.error(`Error: User "${arg2}" not found in team`);
  1555. process.exit(1);
  1556. }
  1557. const result = await removeWatcher(taskId, user.id);
  1558. if (jsonOutput) {
  1559. console.log(JSON.stringify(result, null, 2));
  1560. } else {
  1561. console.log(`Removed ${user.username || user.email} as watcher`);
  1562. }
  1563. break;
  1564. }
  1565. case 'tag': {
  1566. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  1567. if (ids.length === 0) {
  1568. console.error('Error: Could not parse task ID from input');
  1569. process.exit(1);
  1570. }
  1571. if (!arg2) {
  1572. console.error('Error: Tag name required');
  1573. console.error('Usage: node query.mjs tag <task[,task,...]> "tag_name"');
  1574. process.exit(1);
  1575. }
  1576. if (ids.length === 1) {
  1577. await addTag(ids[0], arg2);
  1578. if (jsonOutput) {
  1579. console.log(JSON.stringify({ tagged: true, taskId: ids[0], tag: arg2 }, null, 2));
  1580. } else {
  1581. console.log(`Tag "${arg2}" added to task`);
  1582. }
  1583. } else {
  1584. const results = await bulkExecute(ids, id => addTag(id, arg2));
  1585. if (jsonOutput) {
  1586. console.log(JSON.stringify(results, null, 2));
  1587. } else {
  1588. console.log(formatBulkResults(results, { action: `Tagged "${arg2}" on` }));
  1589. }
  1590. }
  1591. break;
  1592. }
  1593. case 'remove-tag': {
  1594. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  1595. if (ids.length === 0) {
  1596. console.error('Error: Could not parse task ID from input');
  1597. process.exit(1);
  1598. }
  1599. if (!arg2) {
  1600. console.error('Error: Tag name required');
  1601. console.error('Usage: node query.mjs remove-tag <task[,task,...]> "tag_name"');
  1602. process.exit(1);
  1603. }
  1604. if (ids.length === 1) {
  1605. await removeTag(ids[0], arg2);
  1606. if (jsonOutput) {
  1607. console.log(JSON.stringify({ removed: true, taskId: ids[0], tag: arg2 }, null, 2));
  1608. } else {
  1609. console.log(`Tag "${arg2}" removed from task`);
  1610. }
  1611. } else {
  1612. const results = await bulkExecute(ids, id => removeTag(id, arg2));
  1613. if (jsonOutput) {
  1614. console.log(JSON.stringify(results, null, 2));
  1615. } else {
  1616. console.log(formatBulkResults(results, { action: `Removed tag "${arg2}" from` }));
  1617. }
  1618. }
  1619. break;
  1620. }
  1621. case 'description': {
  1622. const taskId = parseTaskId(targetInput);
  1623. if (!taskId) {
  1624. console.error('Error: Could not parse task ID from input');
  1625. process.exit(1);
  1626. }
  1627. if (!arg2) {
  1628. console.error('Error: Description text required');
  1629. console.error('Usage: node query.mjs description <task> "description text"');
  1630. console.error('Markdown formatting is supported.');
  1631. process.exit(1);
  1632. }
  1633. // Use markdown_description for proper markdown rendering in ClickUp
  1634. // Note: Unlike comments (which use JSON array format via markdownToClickUp),
  1635. // task descriptions use ClickUp's native markdown_description field
  1636. const task = await updateTask(taskId, { markdown_description: arg2 });
  1637. if (jsonOutput) {
  1638. console.log(JSON.stringify(task, null, 2));
  1639. } else {
  1640. console.log('Task description updated');
  1641. console.log(`URL: ${task.url}`);
  1642. }
  1643. break;
  1644. }
  1645. case 'depends': {
  1646. // Set task as waiting on another task
  1647. const taskId = parseTaskId(targetInput);
  1648. if (!taskId) {
  1649. console.error('Error: Could not parse task ID from input');
  1650. process.exit(1);
  1651. }
  1652. if (!arg2) {
  1653. console.error('Error: Other task ID required');
  1654. console.error('Usage: node query.mjs depends <task> <waits_on_task>');
  1655. console.error('This sets the first task as waiting on/blocked by the second task.');
  1656. process.exit(1);
  1657. }
  1658. const dependsOnId = parseTaskId(arg2);
  1659. if (!dependsOnId) {
  1660. console.error('Error: Could not parse dependency task ID');
  1661. process.exit(1);
  1662. }
  1663. const result = await addDependency(taskId, { depends_on: dependsOnId });
  1664. if (jsonOutput) {
  1665. console.log(JSON.stringify(result, null, 2));
  1666. } else {
  1667. console.log(`Task ${taskId} now waits on task ${dependsOnId}`);
  1668. }
  1669. break;
  1670. }
  1671. case 'blocks': {
  1672. // Set task as blocking another task
  1673. const taskId = parseTaskId(targetInput);
  1674. if (!taskId) {
  1675. console.error('Error: Could not parse task ID from input');
  1676. process.exit(1);
  1677. }
  1678. if (!arg2) {
  1679. console.error('Error: Other task ID required');
  1680. console.error('Usage: node query.mjs blocks <task> <blocked_task>');
  1681. console.error('This sets the first task as blocking the second task.');
  1682. process.exit(1);
  1683. }
  1684. const blocksId = parseTaskId(arg2);
  1685. if (!blocksId) {
  1686. console.error('Error: Could not parse blocked task ID');
  1687. process.exit(1);
  1688. }
  1689. const result = await addDependency(taskId, { dependency_of: blocksId });
  1690. if (jsonOutput) {
  1691. console.log(JSON.stringify(result, null, 2));
  1692. } else {
  1693. console.log(`Task ${taskId} now blocks task ${blocksId}`);
  1694. }
  1695. break;
  1696. }
  1697. case 'task-link': {
  1698. // Create bidirectional link between tasks
  1699. const taskId = parseTaskId(targetInput);
  1700. if (!taskId) {
  1701. console.error('Error: Could not parse task ID from input');
  1702. process.exit(1);
  1703. }
  1704. if (!arg2) {
  1705. console.error('Error: Other task ID required');
  1706. console.error('Usage: node query.mjs task-link <task> <other_task>');
  1707. console.error('This creates a bidirectional link between tasks.');
  1708. process.exit(1);
  1709. }
  1710. const linksToId = parseTaskId(arg2);
  1711. if (!linksToId) {
  1712. console.error('Error: Could not parse target task ID');
  1713. process.exit(1);
  1714. }
  1715. const result = await addTaskLink(taskId, linksToId);
  1716. if (jsonOutput) {
  1717. console.log(JSON.stringify(result, null, 2));
  1718. } else {
  1719. console.log(`Tasks ${taskId} and ${linksToId} are now linked`);
  1720. }
  1721. break;
  1722. }
  1723. case 'archive': {
  1724. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  1725. if (ids.length === 0) {
  1726. console.error('Error: Could not parse task ID from input');
  1727. process.exit(1);
  1728. }
  1729. if (ids.length === 1) {
  1730. const task = await archiveTask(ids[0]);
  1731. if (jsonOutput) {
  1732. console.log(JSON.stringify(task, null, 2));
  1733. } else {
  1734. console.log(`Task archived: ${task.name || ids[0]}`);
  1735. if (task.url) console.log(`URL: ${task.url}`);
  1736. }
  1737. } else {
  1738. const results = await bulkExecute(ids, id => archiveTask(id));
  1739. if (jsonOutput) {
  1740. console.log(JSON.stringify(results, null, 2));
  1741. } else {
  1742. console.log(formatBulkResults(results, { action: 'Archived' }));
  1743. }
  1744. }
  1745. break;
  1746. }
  1747. case 'unarchive': {
  1748. const ids = splitIds(targetInput).map(parseTaskId).filter(Boolean);
  1749. if (ids.length === 0) {
  1750. console.error('Error: Could not parse task ID from input');
  1751. process.exit(1);
  1752. }
  1753. if (ids.length === 1) {
  1754. const task = await unarchiveTask(ids[0]);
  1755. if (jsonOutput) {
  1756. console.log(JSON.stringify(task, null, 2));
  1757. } else {
  1758. console.log(`Task restored: ${task.name || ids[0]}`);
  1759. if (task.url) console.log(`URL: ${task.url}`);
  1760. }
  1761. } else {
  1762. const results = await bulkExecute(ids, id => unarchiveTask(id));
  1763. if (jsonOutput) {
  1764. console.log(JSON.stringify(results, null, 2));
  1765. } else {
  1766. console.log(formatBulkResults(results, { action: 'Restored' }));
  1767. }
  1768. }
  1769. break;
  1770. }
  1771. case 'claim': {
  1772. const sessionId = detectClaudeSessionId();
  1773. if (!sessionId) {
  1774. console.error('Error: Could not determine Claude Code session ID.');
  1775. console.error('Tried: $CLAUDE_SESSION_ID, then most-recently-modified');
  1776. console.error(' ~/.claude/projects/*/*.jsonl (within 60s).');
  1777. console.error('Set CLAUDE_SESSION_ID explicitly if running outside a live session.');
  1778. process.exit(1);
  1779. }
  1780. const taskId = parseTaskId(targetInput);
  1781. if (!taskId) {
  1782. console.error('Error: Could not parse task ID from input');
  1783. process.exit(1);
  1784. }
  1785. const field = await findCustomFieldByName(taskId, 'session');
  1786. if (!field) {
  1787. console.error('Error: No "Session ID" custom field found on this task.');
  1788. console.error('Add a text custom field named "Session ID" to the task\'s list in ClickUp.');
  1789. process.exit(1);
  1790. }
  1791. await setCustomField(taskId, field.id, sessionId);
  1792. if (jsonOutput) {
  1793. console.log(JSON.stringify({ taskId, fieldId: field.id, fieldName: field.name, sessionId }, null, 2));
  1794. } else {
  1795. console.log(`Session linked to task ${taskId}`);
  1796. console.log(`Field: ${field.name}`);
  1797. console.log(`Session: ${sessionId}`);
  1798. }
  1799. break;
  1800. }
  1801. // List commands
  1802. case 'list': {
  1803. const listId = parseListId(targetInput);
  1804. if (!listId) {
  1805. console.error('Error: Could not parse list ID from input');
  1806. process.exit(1);
  1807. }
  1808. const list = await getList(listId);
  1809. if (jsonOutput) {
  1810. console.log(JSON.stringify(list, null, 2));
  1811. } else {
  1812. console.log(formatList(list));
  1813. }
  1814. break;
  1815. }
  1816. case 'create-list': {
  1817. const spaceId = parseSpaceId(targetInput);
  1818. if (!spaceId) {
  1819. console.error('Error: Could not parse space ID from input');
  1820. console.error('Usage: node query.mjs create-list <space_id|space_url> "List Name"');
  1821. process.exit(1);
  1822. }
  1823. if (!arg2) {
  1824. console.error('Error: List name required');
  1825. console.error('Usage: node query.mjs create-list <space_id|space_url> "List Name"');
  1826. process.exit(1);
  1827. }
  1828. const options = {};
  1829. if (contentArg) {
  1830. options.content = contentArg;
  1831. }
  1832. const list = await createList(spaceId, arg2, options);
  1833. if (jsonOutput) {
  1834. console.log(JSON.stringify(list, null, 2));
  1835. } else {
  1836. console.log(`List created: ${list.name}`);
  1837. console.log(`ID: ${list.id}`);
  1838. }
  1839. break;
  1840. }
  1841. case 'update-list': {
  1842. const listId = parseListId(targetInput);
  1843. if (!listId) {
  1844. console.error('Error: Could not parse list ID from input');
  1845. console.error('Usage: node query.mjs update-list <list_id> --name "new name" --content "description"');
  1846. process.exit(1);
  1847. }
  1848. if (!nameArg && !contentArg) {
  1849. console.error('Error: At least --name or --content is required');
  1850. console.error('Usage: node query.mjs update-list <list_id> --name "new name" --content "description"');
  1851. process.exit(1);
  1852. }
  1853. const updates = {};
  1854. if (nameArg) {
  1855. updates.name = nameArg;
  1856. }
  1857. if (contentArg) {
  1858. updates.content = contentArg;
  1859. }
  1860. const list = await updateList(listId, updates);
  1861. if (jsonOutput) {
  1862. console.log(JSON.stringify(list, null, 2));
  1863. } else {
  1864. console.log(`List updated: ${list.name || listId}`);
  1865. if (list.id) console.log(`ID: ${list.id}`);
  1866. }
  1867. break;
  1868. }
  1869. case 'delete-list': {
  1870. const listId = parseListId(targetInput);
  1871. if (!listId) {
  1872. console.error('Error: Could not parse list ID from input');
  1873. console.error('Usage: node query.mjs delete-list <list_id>');
  1874. process.exit(1);
  1875. }
  1876. await deleteList(listId);
  1877. if (jsonOutput) {
  1878. console.log(JSON.stringify({ deleted: true, listId }, null, 2));
  1879. } else {
  1880. console.log(`List ${listId} deleted`);
  1881. }
  1882. break;
  1883. }
  1884. // Document commands
  1885. case 'doc': {
  1886. const docId = parseDocId(targetInput);
  1887. if (!docId) {
  1888. console.error('Error: Could not parse doc ID from input');
  1889. process.exit(1);
  1890. }
  1891. const workspaceId = await getTeamId();
  1892. const doc = await getDoc(workspaceId, docId);
  1893. const pages = await getDocPageListing(workspaceId, docId);
  1894. if (jsonOutput) {
  1895. console.log(JSON.stringify({ doc, pages }, null, 2));
  1896. } else {
  1897. console.log(formatDoc(doc));
  1898. console.log('');
  1899. console.log('Pages:');
  1900. console.log(formatPageList(pages));
  1901. }
  1902. break;
  1903. }
  1904. case 'page': {
  1905. const docId = parseDocId(targetInput);
  1906. if (!docId) {
  1907. console.error('Error: Could not parse doc ID from input');
  1908. process.exit(1);
  1909. }
  1910. if (!arg2) {
  1911. console.error('Error: Page ID required');
  1912. console.error('Usage: node query.mjs page <doc_id> <page_id>');
  1913. process.exit(1);
  1914. }
  1915. const pageId = parsePageId(arg2);
  1916. const workspaceId = await getTeamId();
  1917. const page = await getPage(workspaceId, docId, pageId);
  1918. if (jsonOutput) {
  1919. console.log(JSON.stringify(page, null, 2));
  1920. } else {
  1921. console.log(formatPage(page));
  1922. }
  1923. break;
  1924. }
  1925. case 'create-page': {
  1926. const docId = parseDocId(targetInput);
  1927. if (!docId) {
  1928. console.error('Error: Could not parse doc ID from input');
  1929. process.exit(1);
  1930. }
  1931. if (!arg2) {
  1932. console.error('Error: Page title required');
  1933. console.error('Usage: node query.mjs create-page <doc_id> "Page Title" [--content "content"]');
  1934. process.exit(1);
  1935. }
  1936. const workspaceId = await getTeamId();
  1937. const options = {};
  1938. if (contentArg) {
  1939. options.content = contentArg;
  1940. }
  1941. if (parentArg) {
  1942. options.parentPageId = parentArg;
  1943. }
  1944. const page = await createPage(workspaceId, docId, arg2, options);
  1945. if (jsonOutput) {
  1946. console.log(JSON.stringify(page, null, 2));
  1947. } else {
  1948. console.log(`Page created: ${page.name}`);
  1949. console.log(`ID: ${page.id}`);
  1950. if (parentArg) {
  1951. console.log(`Parent: ${parentArg}`);
  1952. }
  1953. }
  1954. break;
  1955. }
  1956. case 'edit-page': {
  1957. const docId = parseDocId(targetInput);
  1958. if (!docId) {
  1959. console.error('Error: Could not parse doc ID from input');
  1960. process.exit(1);
  1961. }
  1962. if (!arg2) {
  1963. console.error('Error: Page ID required');
  1964. console.error('Usage: node query.mjs edit-page <doc_id> <page_id> [--content "content"] [--name "name"]');
  1965. process.exit(1);
  1966. }
  1967. if (!contentArg && !nameArg && !archiveFlag) {
  1968. console.error('Error: At least --content, --name, or --archive is required');
  1969. console.error('Usage: node query.mjs edit-page <doc_id> <page_id> [--content "content"] [--name "name"] [--archive]');
  1970. process.exit(1);
  1971. }
  1972. const pageId = parsePageId(arg2);
  1973. const workspaceId = await getTeamId();
  1974. const updates = {};
  1975. if (contentArg) {
  1976. updates.content = contentArg;
  1977. }
  1978. if (nameArg) {
  1979. updates.name = nameArg;
  1980. }
  1981. if (archiveFlag) {
  1982. updates.archived = true;
  1983. }
  1984. const page = await editPage(workspaceId, docId, pageId, updates);
  1985. if (jsonOutput) {
  1986. console.log(JSON.stringify(page, null, 2));
  1987. } else {
  1988. if (archiveFlag) {
  1989. console.log('Page archived successfully');
  1990. } else {
  1991. console.log('Page updated successfully');
  1992. }
  1993. if (page.id) {
  1994. console.log(`ID: ${page.id}`);
  1995. }
  1996. }
  1997. break;
  1998. }
  1999. case 'attach': {
  2000. const taskId = parseTaskId(targetInput);
  2001. if (!taskId) {
  2002. console.error('Error: Task ID or URL required');
  2003. console.error('Usage: node query.mjs attach <url|id> --attach ./file1.png --attach ./file2.pdf');
  2004. console.error('');
  2005. console.error('You can also use --file for a single file:');
  2006. console.error(' node query.mjs attach <url|id> --file ./screenshot.png');
  2007. process.exit(1);
  2008. }
  2009. // Collect files from --attach args and --file arg
  2010. const filesToUpload = [...attachArgs.map(f => resolve(f))];
  2011. if (fileArg && !filesToUpload.includes(resolve(fileArg))) {
  2012. filesToUpload.push(resolve(fileArg));
  2013. }
  2014. if (filesToUpload.length === 0) {
  2015. console.error('Error: At least one file required');
  2016. console.error('Usage: node query.mjs attach <url|id> --attach ./file1.png [--attach ./file2.pdf]');
  2017. process.exit(1);
  2018. }
  2019. // Validate all files exist before uploading
  2020. for (const fp of filesToUpload) {
  2021. if (!existsSync(fp)) {
  2022. console.error(`Error: File not found: ${fp}`);
  2023. process.exit(1);
  2024. }
  2025. }
  2026. const attachResults = await uploadAttachments(taskId, filesToUpload);
  2027. if (jsonOutput) {
  2028. console.log(JSON.stringify(attachResults, null, 2));
  2029. } else {
  2030. for (const result of attachResults) {
  2031. const att = result.attachment || result;
  2032. const title = att.title || att.name || 'file';
  2033. const url = att.url || att.url_w_query || '';
  2034. console.log(`Attached: ${title}${url ? ` (${url})` : ''}`);
  2035. }
  2036. console.log(`\n${filesToUpload.length} file(s) attached to task ${taskId}`);
  2037. }
  2038. break;
  2039. }
  2040. case 'fetch-image':
  2041. case 'fetch-attachment': {
  2042. const url = targetInput;
  2043. if (!url) {
  2044. console.error('Error: Attachment URL required');
  2045. console.error('Usage: node query.mjs fetch-image <url> [--output path]');
  2046. console.error('');
  2047. console.error('Downloads a ClickUp attachment to a local temp file.');
  2048. console.error('The URL is shown in comment output as [Attachment: name](url)');
  2049. process.exit(1);
  2050. }
  2051. // Determine output path
  2052. const outputFlag = args.indexOf('--output');
  2053. let outputPath;
  2054. if (outputFlag !== -1 && args[outputFlag + 1]) {
  2055. outputPath = resolve(args[outputFlag + 1]);
  2056. } else {
  2057. // Extract filename from URL or use a default
  2058. const urlPath = new URL(url).pathname;
  2059. const filename = urlPath.split('/').pop() || 'attachment';
  2060. const clickupTmp = join(tmpdir(), 'clickup-attachments');
  2061. mkdirSync(clickupTmp, { recursive: true });
  2062. outputPath = join(clickupTmp, filename);
  2063. }
  2064. // Fetch the attachment
  2065. const creds = getActiveCredentials();
  2066. const resp = await fetch(url, {
  2067. headers: { Authorization: creds.apiToken },
  2068. });
  2069. if (!resp.ok) {
  2070. // Retry without auth (CDN URLs may not need it)
  2071. const resp2 = await fetch(url);
  2072. if (!resp2.ok) {
  2073. console.error(`Error: Failed to fetch attachment (${resp2.status})`);
  2074. process.exit(1);
  2075. }
  2076. const buffer = Buffer.from(await resp2.arrayBuffer());
  2077. writeFileSync(outputPath, buffer);
  2078. } else {
  2079. const buffer = Buffer.from(await resp.arrayBuffer());
  2080. writeFileSync(outputPath, buffer);
  2081. }
  2082. if (jsonOutput) {
  2083. console.log(JSON.stringify({ path: outputPath, url }, null, 2));
  2084. } else {
  2085. console.log(`Downloaded: ${outputPath}`);
  2086. }
  2087. break;
  2088. }
  2089. // ── Webhook Watcher Commands ──────────────────────────────────────────
  2090. case 'watch-task': {
  2091. // watch-task <task_id>[,task_id2,...] [--events evt1,evt2]
  2092. if (!targetInput) {
  2093. console.error('Error: Task ID(s) required');
  2094. console.error('Usage: node query.mjs watch-task <task_id>[,id2,...] [--events evt1,evt2]');
  2095. process.exit(1);
  2096. }
  2097. const webhookUrlPath = join(resolve(import.meta.dirname), 'webhook-url.txt');
  2098. let webhookUrl;
  2099. if (existsSync(webhookUrlPath)) {
  2100. webhookUrl = readFileSync(webhookUrlPath, 'utf-8').trim();
  2101. } else {
  2102. // Read from accounts.json
  2103. const accountsPath = join(resolve(import.meta.dirname), 'accounts.json');
  2104. const accts = JSON.parse(readFileSync(accountsPath, 'utf-8'));
  2105. if (!accts.webhookSiteToken) {
  2106. console.error('Error: No webhook.site token configured.');
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 2,214 on GitHub
  2107. console.error('Add "webhookSiteToken" to accounts.json.');
  2108. process.exit(1);
  2109. }
  2110. webhookUrl = `https://webhook.site/${accts.webhookSiteToken}`;
    • Note: Quoted as data in code: Links to a known data-relay/testing domain (webhook.site) without sending anything to it
    • Note: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 2,218 on GitHub
  2111. }
  2112. const events = eventsArg ? eventsArg.split(',') : DEFAULT_TASK_EVENTS;
  2113. const taskIds = targetInput.split(',').map(id => parseTaskId(id));
  2114. const results = [];
  2115. for (const taskId of taskIds) {
  2116. const wh = await createWebhook(webhookUrl, events, { taskId });
  2117. const entry = {
  2118. webhookId: wh.id,
  2119. secret: wh.secret,
  2120. scope: 'task',
  2121. scopeId: taskId,
  2122. events,
  2123. endpoint: webhookUrl,
  2124. createdAt: new Date().toISOString(),
  2125. };
  2126. addWatcherEntry(entry);
  2127. results.push(entry);
  2128. }
  2129. if (jsonOutput) {
  2130. console.log(JSON.stringify(results, null, 2));
  2131. } else {
  2132. for (const r of results) {
  2133. console.log(`Watching task ${r.scopeId} (webhook: ${r.webhookId})`);
  2134. console.log(` Events: ${r.events.join(', ')}`);
  2135. }
  2136. console.log(`\nStart listener: node query.mjs listen`);
  2137. }
  2138. break;
  2139. }
  2140. case 'watch-list': {
  2141. if (!targetInput) {
  2142. console.error('Error: List ID required');
  2143. console.error('Usage: node query.mjs watch-list <list_id> [--events evt1,evt2]');
  2144. process.exit(1);
  2145. }
  2146. const webhookUrlPath = join(resolve(import.meta.dirname), 'webhook-url.txt');
  2147. let webhookUrl;
  2148. if (existsSync(webhookUrlPath)) {
  2149. webhookUrl = readFileSync(webhookUrlPath, 'utf-8').trim();
  2150. } else {
  2151. const accountsPath = join(resolve(import.meta.dirname), 'accounts.json');
  2152. const accts = JSON.parse(readFileSync(accountsPath, 'utf-8'));
  2153. if (!accts.webhookSiteToken) {
  2154. console.error('Error: No webhook.site token configured.');
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 2,265 on GitHub
  2155. process.exit(1);
  2156. }
  2157. webhookUrl = `https://webhook.site/${accts.webhookSiteToken}`;
    • Note: Quoted as data in code: Links to a known data-relay/testing domain (webhook.site) without sending anything to it
    • Note: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 2,268 on GitHub
  2158. }
  2159. const listId = parseListId(targetInput);
  2160. const events = eventsArg ? eventsArg.split(',') : DEFAULT_LIST_EVENTS;
  2161. const wh = await createWebhook(webhookUrl, events, { listId });
  2162. const entry = {
  2163. webhookId: wh.id,
  2164. secret: wh.secret,
  2165. scope: 'list',
  2166. scopeId: listId,
  2167. events,
  2168. endpoint: webhookUrl,
  2169. createdAt: new Date().toISOString(),
  2170. };
  2171. addWatcherEntry(entry);
  2172. if (jsonOutput) {
  2173. console.log(JSON.stringify(entry, null, 2));
  2174. } else {
  2175. console.log(`Watching list ${listId} (webhook: ${wh.id})`);
  2176. console.log(` Events: ${events.join(', ')}`);
  2177. console.log(`\nStart listener: node query.mjs listen`);
  2178. }
  2179. break;
  2180. }
  2181. case 'watch-space': {
  2182. if (!targetInput) {
  2183. console.error('Error: Space ID required');
  2184. console.error('Usage: node query.mjs watch-space <space_id> [--events evt1,evt2]');
  2185. process.exit(1);
  2186. }
  2187. const webhookUrlPath = join(resolve(import.meta.dirname), 'webhook-url.txt');
  2188. let webhookUrl;
  2189. if (existsSync(webhookUrlPath)) {
  2190. webhookUrl = readFileSync(webhookUrlPath, 'utf-8').trim();
  2191. } else {
  2192. const accountsPath = join(resolve(import.meta.dirname), 'accounts.json');
  2193. const accts = JSON.parse(readFileSync(accountsPath, 'utf-8'));
  2194. if (!accts.webhookSiteToken) {
  2195. console.error('Error: No webhook.site token configured.');
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 2,308 on GitHub
  2196. process.exit(1);
  2197. }
  2198. webhookUrl = `https://webhook.site/${accts.webhookSiteToken}`;
    • Note: Quoted as data in code: Links to a known data-relay/testing domain (webhook.site) without sending anything to it
    • Note: Talks to a raw IP address or throwaway host, where malware is often staged
    • Line 2,311 on GitHub
  2199. }
  2200. const spaceId = parseSpaceId(targetInput);
  2201. const events = eventsArg ? eventsArg.split(',') : DEFAULT_SPACE_EVENTS;
  2202. const wh = await createWebhook(webhookUrl, events, { spaceId });
  2203. const entry = {
  2204. webhookId: wh.id,
  2205. secret: wh.secret,
  2206. scope: 'space',
  2207. scopeId: spaceId,
  2208. events,
  2209. endpoint: webhookUrl,
  2210. createdAt: new Date().toISOString(),
  2211. };
  2212. addWatcherEntry(entry);
  2213. if (jsonOutput) {
  2214. console.log(JSON.stringify(entry, null, 2));
  2215. } else {
  2216. console.log(`Watching space ${spaceId} (webhook: ${wh.id})`);
  2217. console.log(` Events: ${events.join(', ')}`);
  2218. console.log(`\nStart listener: node query.mjs listen`);
  2219. }
  2220. break;
  2221. }
  2222. case 'unwatch-webhook': {
  2223. if (!targetInput) {
  2224. console.error('Error: Webhook ID required (or --all to remove all)');
  2225. console.error('Usage: node query.mjs unwatch-webhook <webhook_id>');
  2226. console.error(' node query.mjs unwatch-webhook --all');
  2227. process.exit(1);
  2228. }
  2229. if (targetInput === '--all') {
  2230. const entries = getWatcherEntries();
  2231. if (entries.length === 0) {
  2232. console.log('No watchers to remove.');
  2233. break;
  2234. }
  2235. let removed = 0;
  2236. for (const e of entries) {
  2237. try {
  2238. await deleteWebhook(e.webhookId);
  2239. removed++;
  2240. } catch (err) {
  2241. console.error(` Failed to delete ${e.webhookId}: ${err.message}`);
  2242. }
  2243. }
  2244. clearAllWatcherEntries();
  2245. console.log(`Removed ${removed}/${entries.length} webhook(s).`);
  2246. } else {
  2247. await deleteWebhook(targetInput);
  2248. removeWatcherEntry(targetInput);
  2249. console.log(`Webhook ${targetInput} deleted.`);
  2250. }
  2251. break;
  2252. }
  2253. default:
  2254. console.error(`Unknown command: ${command}`);
  2255. showUsage();
  2256. }
  2257. } catch (err) {
  2258. console.error('Error:', err.message);
  2259. process.exit(1);
  2260. }
  2261. }
  2262. main().then(() => {
  2263. // --cleanup: delete the source file after successful execution
  2264. if (cleanupFlag && fileArg) {
  2265. const filePath = resolve(fileArg);
  2266. try {
  2267. unlinkSync(filePath);
  2268. } catch {
  2269. // Silently ignore cleanup failures
  2270. }
  2271. }
  2272. });
.claude/skills/clickup/watch.mjs · Bundled script · 358 lines · 1 finding marked
  1. #!/usr/bin/env node
  2. /**
  3. * watch.mjs — Polling-based watcher for ClickUp tasks (and lists)
  4. *
  5. * Snapshots a task's baseline (status, comment count / latest comment id,
  6. * assignees, date_updated) then polls the ClickUp API on an interval. When a
  7. * watched change is detected vs the baseline it prints a concise JSON summary
  8. * of what changed and EXITS 0 — so a parent agent running this with
  9. * run_in_background=true gets woken by the task-notification. On timeout it
  10. * also exits 0 with a "timeout" summary.
  11. *
  12. * Unlike watch-task/listen.mjs (webhook.site + whcli relay), this watcher is
    • Note: Quoted as data in code: Mentions a known data-relay/testing domain (webhook.site) without linking or sending anything to it
    • Line 13 on GitHub
  13. * fully self-contained: it needs nothing beyond a working ClickUp API token,
  14. * so it runs anywhere the rest of the skill runs.
  15. *
  16. * Usage:
  17. * node watch.mjs <taskId|taskUrl>
  18. * node watch.mjs --list <listId|listUrl>
  19. *
  20. * Flags:
  21. * --timeout <sec> Max seconds to watch before giving up (default 3600)
  22. * --interval <sec> Poll cadence in seconds (default 45; min 10)
  23. * --on <types> Comma list of change types that wake the watcher:
  24. * status,comments,assignee (default: all three)
  25. * --until-status <statuses> Only wake when the task reaches one of these
  26. * statuses (comma list). Implies --on status.
  27. * --account <name> Use a specific named account from accounts.json
  28. * --json (default output is already JSON)
  29. * --state-file <path> Optional: write latest change/snapshot JSON here
  30. *
  31. * Exit codes:
  32. * 0 — a watched change fired, OR the watch timed out (both print JSON)
  33. * 1 — fatal setup/config error (bad task id, no auth, etc.)
  34. */
  35. import { writeFileSync } from 'fs';
  36. import { resolve, dirname } from 'path';
  37. import { fileURLToPath } from 'url';
  38. import { initClient } from './api/client.mjs';
  39. import { getTask, getTasksInList } from './api/tasks.mjs';
  40. import { getComments } from './api/comments.mjs';
  41. import { parseTaskId, parseListId } from './lib/parse.mjs';
  42. const __dirname = dirname(fileURLToPath(import.meta.url));
  43. // ---------------------------------------------------------------------------
  44. // Args
  45. // ---------------------------------------------------------------------------
  46. const argv = process.argv.slice(2);
  47. function flag(name) {
  48. const i = argv.indexOf(`--${name}`);
  49. if (i === -1) return undefined;
  50. return argv[i + 1];
  51. }
  52. function has(name) {
  53. return argv.includes(`--${name}`);
  54. }
  55. function fatal(msg) {
  56. console.error(`ERROR: ${msg}`);
  57. process.exit(1);
  58. }
  59. // First positional (not a flag, not a flag value) is the task id/url.
  60. const positional = [];
  61. for (let i = 0; i < argv.length; i++) {
  62. const a = argv[i];
  63. if (a.startsWith('--')) {
  64. // Boolean flags take no value; value flags consume the next token.
  65. if (!['json'].includes(a.slice(2))) i++;
  66. continue;
  67. }
  68. positional.push(a);
  69. }
  70. const listInput = flag('list');
  71. const taskInput = positional[0];
  72. if (!listInput && !taskInput) {
  73. fatal(
  74. 'Provide a task id/url, or --list <listId>.\n' +
  75. 'Usage: node watch.mjs <taskId> [--timeout 3600] [--interval 45] ' +
  76. '[--on status,comments,assignee] [--until-status "in progress,complete"]'
  77. );
  78. }
  79. const timeoutSec = Math.max(parseInt(flag('timeout') || '3600', 10), 5);
  80. const intervalSec = Math.max(parseInt(flag('interval') || '45', 10), 10);
  81. const account = flag('account');
  82. const stateFile = flag('state-file');
  83. const untilStatusRaw = flag('until-status');
  84. const untilStatuses = untilStatusRaw
  85. ? untilStatusRaw.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean)
  86. : null;
  87. let onTypes;
  88. const onRaw = flag('on');
  89. if (onRaw) {
  90. onTypes = new Set(onRaw.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean));
  91. } else {
  92. onTypes = new Set(['status', 'comments', 'assignee']);
  93. }
  94. // --until-status is a status-based wake condition; make sure status is watched.
  95. if (untilStatuses) onTypes.add('status');
  96. // ---------------------------------------------------------------------------
  97. // Init
  98. // ---------------------------------------------------------------------------
  99. try {
  100. initClient(account);
  101. } catch (err) {
  102. fatal(err.message);
  103. }
  104. const mode = listInput ? 'list' : 'task';
  105. let targetId;
  106. if (mode === 'list') {
  107. targetId = parseListId(listInput) || listInput;
  108. } else {
  109. targetId = parseTaskId(taskInput);
  110. }
  111. if (!targetId) fatal(`Could not parse ${mode} id from input.`);
  112. const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  113. function writeState(obj) {
  114. if (!stateFile) return;
  115. try {
  116. const p = resolve(stateFile);
  117. writeFileSync(p, JSON.stringify(obj, null, 2) + '\n');
  118. } catch {
  119. /* best-effort */
  120. }
  121. }
  122. // ---------------------------------------------------------------------------
  123. // Snapshotting
  124. // ---------------------------------------------------------------------------
  125. // Reduce a raw task to the fields we compare across polls.
  126. function snapshotTask(task, comments) {
  127. const assignees = (task.assignees || [])
  128. .map((a) => a.id)
  129. .sort((x, y) => String(x).localeCompare(String(y)));
  130. const latest = comments && comments.length ? comments[comments.length - 1] : null;
  131. return {
  132. id: task.id,
  133. name: task.name,
  134. status: task.status?.status ?? null,
  135. statusType: task.status?.type ?? null,
  136. dateUpdated: task.date_updated ?? null,
  137. assignees,
  138. assigneeNames: (task.assignees || []).map((a) => a.username || a.email || String(a.id)),
  139. commentCount: comments ? comments.length : null,
  140. latestCommentId: latest ? latest.id : null,
  141. };
  142. }
  143. async function snapshotTaskById(id) {
  144. const task = await getTask(id);
  145. let comments = null;
  146. if (onTypes.has('comments')) {
  147. try {
  148. comments = await getComments(id);
  149. } catch {
  150. comments = null; // don't let a comment fetch failure abort snapshotting
  151. }
  152. }
  153. return snapshotTask(task, comments);
  154. }
  155. // Compare two task snapshots and return array of change descriptors.
  156. function diffTask(prev, cur) {
  157. const changes = [];
  158. if (onTypes.has('status') && prev.status !== cur.status) {
  159. changes.push({ type: 'status', from: prev.status, to: cur.status });
  160. }
  161. if (onTypes.has('assignee')) {
  162. const a = new Set(prev.assignees.map(String));
  163. const b = new Set(cur.assignees.map(String));
  164. const added = [...b].filter((x) => !a.has(x));
  165. const removed = [...a].filter((x) => !b.has(x));
  166. if (added.length || removed.length) {
  167. changes.push({
  168. type: 'assignee',
  169. added,
  170. removed,
  171. current: cur.assigneeNames,
  172. });
  173. }
  174. }
  175. if (onTypes.has('comments')) {
  176. if (
  177. prev.latestCommentId !== cur.latestCommentId ||
  178. (prev.commentCount != null && cur.commentCount != null && cur.commentCount > prev.commentCount)
  179. ) {
  180. changes.push({
  181. type: 'comments',
  182. newCount: cur.commentCount,
  183. prevCount: prev.commentCount,
  184. latestCommentId: cur.latestCommentId,
  185. });
  186. }
  187. }
  188. return changes;
  189. }
  190. // A change only satisfies --until-status when the new status matches.
  191. function passesUntilStatus(changes, cur) {
  192. if (!untilStatuses) return true;
  193. const s = (cur.status || '').toLowerCase();
  194. return untilStatuses.includes(s);
  195. }
  196. // ---------------------------------------------------------------------------
  197. // List-mode snapshot (map of taskId -> per-task snapshot)
  198. // ---------------------------------------------------------------------------
  199. async function snapshotList(id) {
  200. const tasks = await getTasksInList(id);
  201. const map = {};
  202. for (const t of tasks) {
  203. // In list mode we skip per-task comment fetches to stay gentle on the API;
  204. // status + assignee + date_updated are compared. New/removed tasks tracked too.
  205. map[t.id] = snapshotTask(t, null);
  206. }
  207. return map;
  208. }
  209. function diffList(prev, cur) {
  210. const changes = [];
  211. const prevIds = new Set(Object.keys(prev));
  212. const curIds = new Set(Object.keys(cur));
  213. for (const id of curIds) {
  214. if (!prevIds.has(id)) {
  215. changes.push({ type: 'taskCreated', taskId: id, name: cur[id].name, status: cur[id].status });
  216. continue;
  217. }
  218. const sub = diffTask(prev[id], cur[id]);
  219. for (const c of sub) {
  220. changes.push({ ...c, taskId: id, name: cur[id].name });
  221. }
  222. if (onTypes.has('status') && prev[id].dateUpdated !== cur[id].dateUpdated && prev[id].status === cur[id].status) {
  223. // date_updated moved without a status/assignee change we track; note as generic update
  224. // (kept lightweight — only surfaced if nothing else fired for this task)
  225. }
  226. }
  227. for (const id of prevIds) {
  228. if (!curIds.has(id)) {
  229. changes.push({ type: 'taskDeleted', taskId: id, name: prev[id].name });
  230. }
  231. }
  232. return changes;
  233. }
  234. // ---------------------------------------------------------------------------
  235. // Main watch loop
  236. // ---------------------------------------------------------------------------
  237. async function main() {
  238. const startedAt = Date.now();
  239. const deadline = startedAt + timeoutSec * 1000;
  240. let baseline;
  241. try {
  242. baseline = mode === 'list' ? await snapshotList(targetId) : await snapshotTaskById(targetId);
  243. } catch (err) {
  244. fatal(`Failed to snapshot ${mode} ${targetId}: ${err.message}`);
  245. }
  246. const baseInfo = {
  247. mode,
  248. targetId,
  249. interval: intervalSec,
  250. timeout: timeoutSec,
  251. on: [...onTypes],
  252. untilStatus: untilStatuses,
  253. baseline: mode === 'task' ? baseline : { taskCount: Object.keys(baseline).length },
  254. startedAt: new Date(startedAt).toISOString(),
  255. };
  256. writeState({ event: 'baseline', ...baseInfo });
  257. let prev = baseline;
  258. let consecutiveErrors = 0;
  259. while (Date.now() < deadline) {
  260. // Sleep first — the baseline was just taken, so poll after one interval.
  261. const remaining = deadline - Date.now();
  262. await sleep(Math.min(intervalSec * 1000, Math.max(remaining, 0)));
  263. if (Date.now() >= deadline) break;
  264. let cur;
  265. try {
  266. cur = mode === 'list' ? await snapshotList(targetId) : await snapshotTaskById(targetId);
  267. consecutiveErrors = 0;
  268. } catch (err) {
  269. // Graceful backoff on API/network/rate-limit errors; never crash the loop.
  270. consecutiveErrors++;
  271. const backoff = Math.min(60, intervalSec * Math.pow(2, consecutiveErrors));
  272. console.error(`poll error (${consecutiveErrors}): ${err.message} — backing off ${backoff}s`);
  273. await sleep(backoff * 1000);
  274. continue;
  275. }
  276. const changes = mode === 'list' ? diffList(prev, cur) : diffTask(prev, cur);
  277. if (changes.length) {
  278. const curSnap = mode === 'task' ? cur : { taskCount: Object.keys(cur).length };
  279. if (mode === 'task' && !passesUntilStatus(changes, cur)) {
  280. // A change happened but the until-status gate isn't satisfied yet;
  281. // advance the baseline so we don't re-report the same change, keep waiting.
  282. prev = cur;
  283. continue;
  284. }
  285. const result = {
  286. event: 'change',
  287. mode,
  288. targetId,
  289. name: mode === 'task' ? cur.name : undefined,
  290. changes,
  291. snapshot: curSnap,
  292. elapsedSec: Math.round((Date.now() - startedAt) / 1000),
  293. url: mode === 'task' ? `https://app.clickup.com/t/${targetId}` : undefined,
  294. };
  295. writeState(result);
  296. console.log(JSON.stringify(result));
  297. process.exit(0);
  298. }
  299. prev = cur;
  300. }
  301. const result = {
  302. event: 'timeout',
  303. mode,
  304. targetId,
  305. timeout: timeoutSec,
  306. elapsedSec: Math.round((Date.now() - startedAt) / 1000),
  307. message: 'No watched change detected within timeout.',
  308. };
  309. writeState(result);
  310. console.log(JSON.stringify(result));
  311. process.exit(0);
  312. }
  313. main().catch((err) => {
  314. fatal(`Unexpected error: ${err.message}`);
  315. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.