diff --git a/CHANGELOG.md b/CHANGELOG.md index c1f62d5..e1848b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,48 @@ Notable changes to `@wirecat/bitrix24-cli`. One section per version, newest first. +## 0.27.0 — 24.11.2026 + +### Added + +- **Client files: `files list`, `files download` and `files sync`.** `files list --deal 12` (or `--lead`, `--person`, + `--organization`) reads one record's files from the portal: the files in its file fields, the documents made from + templates (the PDF when the portal has made it, else the Word file), and the Drive files attached to its activities + and timeline comments. `files download ` saves one under the state folder and reads its text, which `search all` + then finds. A source the webhook may not read, such as activity files without the `disk` scope, is named under + `issues` and the others are still listed. Each download asks the portal for a fresh link and fetches it from the + portal alone; no link reaches the store or an answer. `files: deny` also holds on `api call` of the methods these + commands read through. See [Client files](docs/usage.md#client-files). + +### Changed — may break callers + +- **`api call` hides more links.** It now uses cli-core's rule: besides the download keys and the portal's tokened + paths, any link that carries `auth=`, `access_token=`, `api_token=` or `X-Amz-Signature=` prints as + `[link removed]`, whatever its host. Drive's `ERROR_NOT_FOUND` (such as `api call disk.file.get` of a missing file) + is now `not_found`, exit 6, not `validation_error`. +- **`search all` can answer a new hit kind, `crm_file`**, the text of a downloaded file. A script that switches over + `kind` gets it. It comes with `@wirecat/cli-core` 0.710.0, whose store moves to version 69 (forward-only). +- **`account remove --delete-data` refuses with `account-remove.account-shared`, detail `account`.** It was + `account-remove.portal-shared` with detail `portal`. The command is now cli-core's shared CRM one (`@wirecat/cli-core` + 0.722.0). It still refuses while another profile here reads the same portal, even one whose session ended. Under + `--dry-run` it now warns and lists what would go, where it used to fail. +- **`account remove --delete-data` refuses when b24 cannot tell which portal another profile holds** + (`account-remove.account-unknown`, detail `profile`): a profile whose saved webhook is unreadable and that + `session start` never remembered. `--keep-data` still removes. +- **`session start` refuses a second sign-in to the same portal and user with the shared words.** The reason stays + `session.duplicate`; its detail `portal` is now `account`, and the message says to end the other profile with + `b24 session end`. A webhook sign-in to a profile named `files` or `foreign-contacts`, folders every + portal shares, is refused with `profile.reserved`. +- **An MCP server no longer offers `schedule exec`, and it runs only a schedule file in b24's own schedules folder** + (`@wirecat/cli-core` 0.739.0). A link or `..` that leads elsewhere is refused with `schedule.outside-folder`. + Installed timers keep running. An agent runs a saved schedule with `schedule run `. + +### Fixed + +- **A deal that enters a stage in the same second its `stage-tasks` rules were set now opens its task** + (`@wirecat/cli-core` 0.739.0). The portal's stage history keeps whole seconds, so such a move read as made before + the rules and opened none. + ## 0.26.0 — 18.11.2026 ### Changed — may break callers diff --git a/bin/b24-live b/bin/b24-live index 09100de..a663fde 100755 --- a/bin/b24-live +++ b/bin/b24-live @@ -5,7 +5,9 @@ # # bin/b24-live # builds this checkout, syncs into the throwaway store and reads; changes nothing # bin/b24-live --write # also creates one lead and one deal "WireCat test …", -# # changes, moves and deletes each, then syncs again and asks the portal that none is left; +# # changes, moves and deletes each; puts a PDF in the deal's file field, lists and downloads +# # it; creates a contact and a company, lists their files, deletes them; +# # then syncs again and asks the portal that none is left; # # when every step passed, appends # # the version and commit to docs/dev/live-checks.txt, which bin/release checks # B24_KEYRING_ACCOUNT= bin/b24-live [--write] @@ -291,9 +293,129 @@ if [ -z "$on" ]; then fail "the portal has no deal titled \"$title\""; else console.log("ok: the sync read the comment into deals show") })' "$title comment" || fail "deals show has not the timeline comment" fi +# A small PDF in the deal's first file field, then `files list` and `files download` of it. Not a comment's or an +# activity's file: those land on the webhook user's Drive, which deleting the deal does not empty. +printf '\n== b24 live files\n' +marker="WireCat test file $(date +%s)" +pdf="$sandbox/wirecat-test.pdf" +node -e ' + const [path, text] = process.argv.slice(1) + const stream = `BT /F1 12 Tf 72 720 Td (${text}) Tj ET` + const objects = [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>", + `<< /Length ${stream.length} >>\nstream\n${stream}\nendstream`, + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + ] + let out = "%PDF-1.4\n" + const offsets = objects.map((body, i) => { + const at = out.length + out += `${i + 1} 0 obj\n${body}\nendobj\n` + return at + }) + const xref = out.length + out += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n` + out += offsets.map((at) => `${String(at).padStart(10, "0")} 00000 n \n`).join("") + out += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n` + require("fs").writeFileSync(path, out)' "$pdf" "$marker" +slot=$(b24 api call crm.item.fields --body '{"entityTypeId":2,"useOriginalUfNames":"Y"}' --json 2>/dev/null | node -e ' + let s = "" + process.stdin.on("data", (d) => (s += d)).on("end", () => { + let fields = {} + try { fields = JSON.parse(s).item.result.fields ?? {} } catch {} + const found = Object.entries(fields).find(([, one]) => one.type === "file" && !one.isReadOnly) + if (found) console.log(`${found[0]}|${found[1].isMultiple ? 1 : 0}`) + })') || true +if [ -z "$on" ]; then fail "no deal id to attach a file to" +elif [ -z "$slot" ]; then echo "deals have no file field — files list and download skipped" +else + code=${slot%|*} + body=$(node -e ' + const [id, code, multiple, path] = process.argv.slice(1) + const one = ["wirecat-test.pdf", require("fs").readFileSync(path).toString("base64")] + const fields = { [code]: multiple === "1" ? [one] : one } + console.log(JSON.stringify({ entityTypeId: 2, id: Number(id), useOriginalUfNames: "Y", fields }))' \ + "$on" "$code" "${slot#*|}" "$pdf") + b24 api call crm.item.update --yes --body "$body" >/dev/null 2>&1 || fail "crm.item.update with a file: exit $?" + # How a file field reads with original names: only the keys and the kinds of their values are printed. + b24 api call crm.item.get --body "{\"entityTypeId\":2,\"id\":$on,\"useOriginalUfNames\":\"Y\"}" --json 2>/dev/null | + node -e ' + let s = "" + process.stdin.on("data", (d) => (s += d)).on("end", () => { + let value + try { value = JSON.parse(s).item.result.item[process.argv[1]] } catch {} + const one = Array.isArray(value) ? value[0] : value + const shape = one && typeof one === "object" + ? Object.entries(one).map(([k, v]) => `${k}:${typeof v}`).join(",") : typeof one + console.log(`the file field reads as ${Array.isArray(value) ? "a list of " : ""}{${shape}}`) + })' "$code" + listed=$(b24 files list --deal "$on" --json 2>/dev/null) || true + printf '%s' "$listed" | node -e ' + let s = "" + process.stdin.on("data", (d) => (s += d)).on("end", () => { + let answer = {} + try { answer = JSON.parse(s) } catch {} + const items = answer.items ?? [] + const kinds = items.map((one) => one.source).join(",") || "none" + const issues = (answer.meta?.issues ?? []).map((one) => `${one.code}/${one.reason ?? ""}`).join(",") || "none" + console.log(`files list: ${items.length} file(s) of sources ${kinds}; issues ${issues}`) + })' + file=$(printf '%s' "$listed" | node -e ' + let s = "" + process.stdin.on("data", (d) => (s += d)).on("end", () => { + let items = [] + try { items = JSON.parse(s).items ?? [] } catch {} + const fields = items.filter((one) => one.source === "field") + console.log(fields.length === 1 ? fields[0].id : "") + })') + if [ -z "$file" ]; then fail "files list did not show the one file in the deal's field"; else + got=$(b24 files download "$file" --json 2>&1) || true + printf '%s' "$got" | node -e ' + let s = "" + process.stdin.on("data", (d) => (s += d)).on("end", () => { + const fs = require("fs") + const [sent, marker] = process.argv.slice(1) + let answer = {} + try { answer = JSON.parse(s) } catch {} + const item = answer.item + if (!item) { + console.log(`download failed: ${answer.error?.code ?? "no answer"} ${answer.error?.reason ?? ""}`) + process.exit(1) + } + const same = item.path && fs.existsSync(item.path) && fs.readFileSync(item.path).equals(fs.readFileSync(sent)) + const read = item.text_status !== "extracted" || (item.text ?? "").includes(marker) + console.log(`download: the same bytes ${Boolean(same)}, text ${item.text_status}, the marker found ${read}`) + if (!same || !read) process.exit(1) + })' "$pdf" "$marker" || fail "files download did not save the file that was attached" + fi +fi step deals delete "$deal" --yes --json=ref,removed echo "deleted $deal" +# A contact and a company: `files list` reads each, its activities by the record's binding included, without failing. +# `api call` may not add an activity (crm.activity.* is denied by default), so none is attached here. +printf '\n== b24 live files of a contact and a company\n' +for pair in "3 person name" "4 organization title"; do + read -r type kind name <<<"$pair" + record=$(b24 api call crm.item.add --yes --body "{\"entityTypeId\":$type,\"fields\":{\"$name\":\"$title\"}}" --json \ + 2>/dev/null | value item.result.item.id) || true + [ -n "$record" ] || { fail "crm.item.add of a $kind gave no id"; continue; } + echo "created $kind $record: $title" + b24 files list "--$kind" "$record" --json 2>/dev/null | node -e ' + let s = "" + process.stdin.on("data", (d) => (s += d)).on("end", () => { + let answer + try { answer = JSON.parse(s) } catch {} + if (!answer?.items) process.exit(1) + const issues = (answer.meta?.issues ?? []).map((one) => `${one.code}/${one.reason ?? ""}`).join(",") || "none" + console.log(`files list --${process.argv[1]}: ${answer.items.length} file(s); issues ${issues}`) + })' "$kind" || fail "files list --$kind failed" + b24 api call crm.item.delete --yes --body "{\"entityTypeId\":$type,\"id\":$record}" >/dev/null 2>&1 || + fail "crm.item.delete of the $kind: exit $?" + echo "deleted $kind $record" +done + # A sync from the cursor (the updatedTime filter), then a rescan with the id pass: neither brings the deleted ones back. changed # Asked of the portal itself: a rescan that finds the deletions does not finish in one run on a large portal. @@ -306,6 +428,14 @@ for type in lead deal; do fi done done +for pair in "3 contact name" "4 company title"; do + read -r type kind name <<<"$pair" + left=$(b24 api call crm.item.list --body "{\"entityTypeId\":$type,\"select\":[\"id\"],\"filter\":{\"=$name\":\"$title\"}}" \ + --json | value item.result.items.length) + if [ "$left" = 0 ]; then echo "ok: the portal has no $kind named \"$title\""; else + fail "the portal answered '$left' ${kind}s named \"$title\"" + fi +done [ "$failed" = 0 ] || { echo "a step failed: no live record" >&2; exit 1; } (cd "$root" && pnpm exec cli-dev live record --script bin/b24-live) diff --git a/changes/feat-crm-files.md b/changes/feat-crm-files.md deleted file mode 100644 index 5c54921..0000000 --- a/changes/feat-crm-files.md +++ /dev/null @@ -1,19 +0,0 @@ -### Added - -- **Client files: `files list`, `files download` and `files sync`.** `files list --deal 12` (or `--lead`, `--person`, - `--organization`) reads one record's files from the portal: the files in its file fields, the documents made from - templates (the PDF when the portal has made it, else the Word file), and the Drive files attached to its activities - and timeline comments. `files download ` saves one under the state folder and reads its text, which `search all` - then finds. A source the webhook may not read, such as activity files without the `disk` scope, is named under - `issues` and the others are still listed. Each download asks the portal for a fresh link and fetches it from the - portal alone; no link reaches the store or an answer. See [Client files](../docs/usage.md#client-files). - -### Changed — may break callers - -- **`api call` hides more links.** It now uses cli-core's rule: besides the download keys and the portal's tokened - paths, any link that carries `auth=`, `access_token=`, `api_token=` or `X-Amz-Signature=` prints as - `[link removed]`, whatever its host. Drive's `ERROR_NOT_FOUND` (such as `api call disk.file.get` of a missing file) - is now `not_found`, exit 6, not `validation_error`. - -- **`search all` can answer a new hit kind, `crm_file`**, the text of a downloaded file. A script that switches over - `kind` gets it. It comes with `@wirecat/cli-core` 0.710.0, whose store moves to version 69 (forward-only). diff --git a/changes/refactor-shared-account-remove.md b/changes/refactor-shared-account-remove.md deleted file mode 100644 index c966a7f..0000000 --- a/changes/refactor-shared-account-remove.md +++ /dev/null @@ -1,13 +0,0 @@ -### Changed — may break callers - -- **`account remove --delete-data` refuses with `account-remove.account-shared`, detail `account`.** It was - `account-remove.portal-shared` with detail `portal`. The command is now cli-core's shared CRM one (`@wirecat/cli-core` - 0.722.0). It still refuses while another profile here reads the same portal, even one whose session ended. Under - `--dry-run` it now warns and lists what would go, where it used to fail. -- **`account remove --delete-data` refuses when b24 cannot tell which portal another profile holds** - (`account-remove.account-unknown`, detail `profile`): a profile whose saved webhook is unreadable and that - `session start` never remembered. `--keep-data` still removes. -- **`session start` refuses a second sign-in to the same portal and user with the shared words.** The reason stays - `session.duplicate`; its detail `portal` is now `account`, and the message says to end the other profile with - `b24 session end`. A webhook sign-in to a profile named `files` or `foreign-contacts`, folders every - portal shares, is refused with `profile.reserved`. diff --git a/contracts/help.snap b/contracts/help.snap index 243f567..ecbc458 100644 --- a/contracts/help.snap +++ b/contracts/help.snap @@ -23,6 +23,7 @@ Works with: memo context one person across messengers, mail, notes and meetings mail IMAP mail in the same local store: search your mailbox offline, next to your other WireCat data amo amoCRM and Kommo: deals, contacts and companies, searchable with your other WireCat data + attio Attio CRM: deals, people and companies, searchable with your other WireCat data pbx Asterisk PBX calls and recordings, searchable with your other WireCat data notion Notion pages and databases as local text, searchable with your other WireCat data ydisk Yandex Disk folders as local text, searchable with your other WireCat data diff --git a/docs/commands.md b/docs/commands.md index e2b67b7..1bae977 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -789,7 +789,7 @@ b24 people show | Argument | | What it is | |---|---|---| -| `person` | required | the CRM's id of the person, as list prints it, or its exact name. | +| `person` | required | the CRM's id of the person, as list prints it, the person: a deal gives, or its exact name. | **Returns:** crm person — id, name, first_name, last_name, position, organization_ids, assigned_to, created_at, and 6 more; every field: b24 commands info people show @@ -885,7 +885,7 @@ b24 organizations show | Argument | | What it is | |---|---|---| -| `organization` | required | the CRM's id of the organization, as list prints it, or its exact name. | +| `organization` | required | the CRM's id of the organization, as list prints it, the organization: a deal gives, or its exact name. | **Returns:** crm organization — id, name, type, own, person_ids, assigned_to, created_at, updated_at, and 5 more; every field: b24 commands info organizations show @@ -1118,7 +1118,7 @@ b24 search all [options] | `--exact` | bare words and quotes match their exact form only, as exact:word does. | | `--timezone ` | the IANA timezone for calendar date boundaries. | -**Returns:** hit — kind, ref, provider, account, title, timestamp, excerpt, url, and 18 more; every field: b24 commands info search all +**Returns:** hit — kind, ref, provider, account, title, timestamp, excerpt, url, and 19 more; every field: b24 commands info search all **Example:** `b24 work search all Example LLC`, `b24 work search all website --only crm --json` diff --git a/docs/dev/DESIGN.md b/docs/dev/DESIGN.md index 55b9b15..5bdc1e0 100644 --- a/docs/dev/DESIGN.md +++ b/docs/dev/DESIGN.md @@ -287,7 +287,12 @@ and `type`); field names are from the REST 3.0 field pages and the `user.get` an - A document is its PDF when `pdfId` is set at listing, else its DOCX; never waited for (apidocs: 30-40 s). - Activity and comment files are Drive files: `disk.file.get` gives the name and size of an activity's (its `FILES` has none) and, at each download, `DOWNLOAD_URL`. That an activity's `FILES[].id` is a Drive id is not yet checked - on a live portal. + on a live portal: the owner's webhook has no `disk` scope. +- Checked live on 2026-11-19 (`bin/b24-live --write`): a file field read with original names is a list of + `{ id, url, urlMachine }`, and its `urlMachine` downloads from the portal's own host, no redirect to another. + `crm.documentgenerator.document.list` answers with the `crm` scope alone; for a record that does not exist it + answers `ACCESS_DENIED`. The activity filter by `BINDINGS` is accepted for contacts and companies; that it + returns only their activities is not checked, since `api call` may not add an activity. - Every `open` asks for a fresh link and fetches it through `BitrixTransport.openFile`: cli-core's `fetchCrmFile`, the portal's host only, redirects too, with the headers apidocs asks for. A portal that redirects a download to another host fails it. diff --git a/docs/dev/live-checks.txt b/docs/dev/live-checks.txt index 88da562..3436246 100644 --- a/docs/dev/live-checks.txt +++ b/docs/dev/live-checks.txt @@ -25,3 +25,4 @@ 0.24.0 ccf5f0257e6af2294587c52a01599b36f512a3c5 2026-11-17 bin/b24-live v2:b3c61d9b4c07c66cc67dc77723649ff48e312e97c8e74679046a2091d9813a04 0.25.0 b529eb44a3edf18f6a19af22f51b8725dcaf6b58 2026-11-17 bin/b24-live v2:d692e2b1a5f74db57737f89adf84072d5fda87f78f978f886fedc28c1319a31e 0.25.0 073b6ef7042bdbe4cd0537ad808a09ef2612abf0 2026-11-17 bin/b24-live v2:eb62bc83277e8677822f44cccf67f15033aa36d73dd88f0f62122df10ebf9576 +0.27.0 cb3f544c08d9f05b6496931bdc459ec4e12ac887 2026-11-24 bin/b24-live v2:3e6a5695ff605b08812fa99879dbb006da708db3898370e7caca9472d3b59180 diff --git a/docs/security.md b/docs/security.md index ee80f15..7390934 100644 --- a/docs/security.md +++ b/docs/security.md @@ -122,8 +122,9 @@ not offered over MCP. terminal. The timer runs `b24 schedule exec `, and the schedule file in the state folder holds the words, the profile, your `PATH` and the folders `b24` uses (`B24_CONFIG_DIR`, `B24_STATE_DIR`, `MESSAGING_STORE`), never the webhook's address. Each run checks the permissions again. `B24_READ_ONLY` refuses -`schedule command`, `remove`, `run` and `exec`. Over MCP an agent may run `schedule run` and `schedule exec`, each -behind its own permission key (`schedule.run`, `schedule.exec`). Adding, pausing, resuming or removing a timer over MCP +`schedule command`, `remove`, `run` and `exec`. Over MCP an agent may run a saved schedule with `schedule run`, +behind the permission key `schedule.run`; `schedule exec` runs only a file in the tool's own schedules folder and is +not offered over MCP. Adding, pausing, resuming or removing a timer over MCP is refused unless the profile sets `permissions.mcp.authority` to `allow`. ## MCP in the browser diff --git a/docs/usage.md b/docs/usage.md index e17ee62..660d129 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -46,7 +46,7 @@ Make an inbound webhook in Bitrix24 (Developer resources → Common use cases | `task` | Tasks / Задачи | The Bitrix24 tasks on your deals ([Activities and tasks](#activities-and-tasks-on-a-deal)). | | `telephony` | Telephony / Телефония | The portal's calls ([Calls](calls.md)). The employee also needs the right to view call statistics. | | `disk` | Drive / Диск | The files attached to activities and timeline comments ([Client files](#client-files)). | -| `documentgenerator` | Document Generator / Генератор документов | Documents made from templates ([Client files](#client-files)). Bitrix24's docs name `crm` on the method pages and this scope in the scope table, so tick both. | +| `documentgenerator` | Document Generator / Генератор документов | Documents made from templates ([Client files](#client-files)). Bitrix24's docs name `crm` on the method pages and this scope in the scope table. A webhook with `crm` alone lists them too. | `b24 work setup` shows the same steps in the terminal, and WireCat Desktop draws them. Or sign in directly: @@ -341,7 +341,7 @@ A record's files come from four places on the portal: | Source | What it is | Scope | |---|---|---| | `field` | A file in one of the record's own file fields | `crm` | -| `document` | A document made from a template: a contract, an invoice, a quote. The PDF when the portal has made it, else the Word file | `crm` (and `documentgenerator`) | +| `document` | A document made from a template: a contract, an invoice, a quote. The PDF when the portal has made it, else the Word file | `crm` | | `activity` | A file attached to an e-mail, a call or another activity | `crm` and `disk` | | `comment` | A file attached to a timeline comment | `crm` and `disk` | diff --git a/package.json b/package.json index f0a6a44..4b7a3bf 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@wirecat/bitrix24-cli", - "version": "0.26.0", + "version": "0.27.0", "description": "Read and change a Bitrix24 portal's CRM — deals, leads, contacts, companies — from the terminal, scripts and AI agents", "license": "Apache-2.0", "author": "Viacheslav Ptsarev", @@ -60,7 +60,7 @@ "docs:spell": "cspell lint --config cspell.json --no-progress --no-summary README.md SECURITY.md CHANGELOG.md AGENTS.md CLAUDE.md 'docs/*.md' 'skills/**/*.md'" }, "dependencies": { - "@wirecat/cli-core": "0.722.0", + "@wirecat/cli-core": "0.739.0", "commander": "15.0.0", "valibot": "1.5.0" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7ada9be..266eba4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -13,8 +13,8 @@ importers: .: dependencies: '@wirecat/cli-core': - specifier: 0.722.0 - version: 0.722.0(@wirecat/cli-base@0.127.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7) + specifier: 0.739.0 + version: 0.739.0(@wirecat/cli-base@0.127.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7) commander: specifier: 15.0.0 version: 15.0.0 @@ -1189,8 +1189,8 @@ packages: '@wirecat/cli-core-sqlite@1.1.0': resolution: {integrity: sha512-GpGlh/dAIX/nblBYCdT6DfWSLFxav9mxxeELQAfEuw+QZdT9unKxbi5xa02s/s4JS1P7n0PQx2sCABj4FlMRNw==} - '@wirecat/cli-core@0.722.0': - resolution: {integrity: sha512-nJM/EA3qpHRi+g7OWLhogNH1ZKVhbu6LdAQP+rNW7Fha6tcdmBCYCoSI9T0V+yb9FkxnOPPj7qNWOsEkAsJGfQ==} + '@wirecat/cli-core@0.739.0': + resolution: {integrity: sha512-gBZG5Wdf0a0r6OVi/4YTPYjFk+83uAmX1OokMvuG53/DMVmS63guhU9SMhlnBxf2qqNCpxZ4notmg2FCwKSMnQ==} engines: {node: ^22.16.0 || >=24} hasBin: true peerDependencies: @@ -3303,7 +3303,7 @@ snapshots: '@wirecat/cli-core-sqlite@1.1.0': {} - '@wirecat/cli-core@0.722.0(@wirecat/cli-base@0.127.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)': + '@wirecat/cli-core@0.739.0(@wirecat/cli-base@0.127.0(commander@15.0.0)(esbuild@0.28.2)(typescript@7.0.2)(vitest@5.0.5))(commander@15.0.0)(typescript@7.0.2)(zod@4.6.7)': dependencies: '@anthropic-ai/sdk': 1.3.0(zod@4.6.7) '@bomb.sh/tab': 0.0.22(commander@15.0.0) diff --git a/src/api-keys.ts b/src/api-keys.ts index b5f1de5..31ab9eb 100644 --- a/src/api-keys.ts +++ b/src/api-keys.ts @@ -198,6 +198,10 @@ const readKeysOf = (method: string, body: Body): string[] => { if (method.startsWith("crm.mycompany.")) return ["organizations.list"] if (method.startsWith("crm.category.")) return ["pipelines.list"] if (method.startsWith("crm.status.")) return ["stages.list"] + // The methods `files` reads through: a list names the files, a get hands over a download link. + if (/^crm\.documentgenerator\.document\.(list|get)$/.test(method) || method === "disk.file.get") + return method.endsWith(".list") ? ["files.list"] : ["files.download"] + if (method.startsWith("crm.timeline.comment.")) return ["files.list"] return [] } diff --git a/src/crm/stage-tasks.test.ts b/src/crm/stage-tasks.test.ts new file mode 100644 index 0000000..1b19f55 --- /dev/null +++ b/src/crm/stage-tasks.test.ts @@ -0,0 +1,44 @@ +import { mkdtempSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { afterEach, describe, expect, it, vi } from "vitest" +import { fakeCrm } from "../testing/fake-crm.js" +import { ok } from "../testing/fake-portal.js" +import { b24 } from "../testing/harness.js" + +const RULES = "crm.bitrix24:example.bitrix24.test.stage-tasks" + +describe("stage tasks from the portal's stage history", () => { + afterEach(() => { + vi.useRealTimers() + vi.unstubAllEnvs() + }) + + it("opens a task when a deal moves into a stage the rules name, as bin/b24-live checks", async () => { + vi.stubEnv("MESSAGING_STORE", join(mkdtempSync(join(tmpdir(), "stage-tasks-")), "store.db")) + const history: Record[] = [] + const portal = fakeCrm({ + "crm.stagehistory.list": ({ body }) => ok({ items: body.entityTypeId === 2 ? history : [] }), + }) + const deal = portal.put("deal", { title: "Example kitchen", categoryId: 0, stageId: "NEW" }) + expect((await b24(["work", "sync", "--json"], { portal })).code).toBe(0) + // The portal keeps whole seconds: a move in the second the rules were set reads as made before them. + vi.useFakeTimers({ toFake: ["Date"], now: Date.parse("2026-11-19T21:43:07.300Z") }) + const rules = JSON.stringify({ PREPARATION: { title: "Example task", due_days: 0 } }) + expect((await b24(["work", "config", "set", RULES, rules, "--json"])).code).toBe(0) + portal.put("deal", { ...portal.row("deal", deal), stageId: "PREPARATION" }) + vi.setSystemTime(Date.parse("2026-11-19T21:43:09.000Z")) + const moved = "2026-11-19T22:43:07+01:00" + history.push({ + ID: "11", + TYPE_ID: "2", + OWNER_ID: String(deal), + CREATED_TIME: moved, + STAGE_ID: "PREPARATION", + CATEGORY_ID: "0", + }) + const synced = await b24(["work", "sync", "--json"], { portal }) + expect(synced.code).toBe(0) + expect((synced.json() as { item: { stage_tasks: number } }).item.stage_tasks).toBe(1) + }) +}) diff --git a/src/mcp.test.ts b/src/mcp.test.ts index bae0222..c2b6f7f 100644 --- a/src/mcp.test.ts +++ b/src/mcp.test.ts @@ -28,7 +28,7 @@ it("serves search, read and write, and runs a command through the CLI", async () } }) -it("pins b24's own commands an agent can find, and offers schedule run and exec but never api call", async () => { +it("pins b24's own commands an agent can find, and offers schedule run but never schedule exec or api call", async () => { const program = createProgram() const authority = changesAuthorityAt(program) const options = { @@ -49,7 +49,6 @@ it("pins b24's own commands an agent can find, and offers schedule run and exec "schedule list", "schedule agents list", "schedule run", - "schedule exec", ]) expect(catalogue["deals update"]).toBe("write") }) diff --git a/src/permissions.test.ts b/src/permissions.test.ts index 31408b1..dd40f56 100644 --- a/src/permissions.test.ts +++ b/src/permissions.test.ts @@ -509,6 +509,10 @@ describe("api call reads check the command key of what they read", () => { ["fields.list", "crm.deal.userfield.list", {}], ["pipelines.list", "crm.category.list", { entityTypeId: 2 }], ["stages.list", "crm.status.list", {}], + ["files.list", "crm.documentgenerator.document.list", {}], + ["files.download", "crm.documentgenerator.document.get", { id: 5 }], + ["files.list", "crm.timeline.comment.list", {}], + ["files.download", "disk.file.get", { id: 5 }], ])("%s: deny refuses api call %s before any request", async (key, method, body) => { const portal = fakePortal({ [method]: ok([]) }) await withPermissions({ [key]: "deny" }, async () => { diff --git a/src/program.ts b/src/program.ts index 0cf6512..3c7d134 100644 --- a/src/program.ts +++ b/src/program.ts @@ -61,6 +61,7 @@ const mcpCommand = () => "whatever api call returns", "the messages, notes and events search all finds", "call titles, descriptions and transcripts: a caller's own words", + "file names and the text of downloaded files", ], permissionExample: "deals.delete=deny", skill: SKILL, diff --git a/src/version.ts b/src/version.ts index b802d96..03f3ccb 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const VERSION = "0.26.0" +export const VERSION = "0.27.0"