@tracken/cli 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/CHANGELOG.md +404 -0
  2. package/LICENSE +21 -0
  3. package/README.md +310 -2
  4. package/dist/bin/tracken.d.ts +2 -0
  5. package/dist/bin/tracken.js +5 -0
  6. package/dist/cli/args.d.ts +17 -0
  7. package/dist/cli/args.js +114 -0
  8. package/dist/cli/commands/api.d.ts +2 -0
  9. package/dist/cli/commands/api.js +73 -0
  10. package/dist/cli/commands/auth.d.ts +8 -0
  11. package/dist/cli/commands/auth.js +141 -0
  12. package/dist/cli/commands/mcp.d.ts +19 -0
  13. package/dist/cli/commands/mcp.js +89 -0
  14. package/dist/cli/commands/org.d.ts +24 -0
  15. package/dist/cli/commands/org.js +123 -0
  16. package/dist/cli/context.d.ts +54 -0
  17. package/dist/cli/context.js +135 -0
  18. package/dist/cli/execute.d.ts +16 -0
  19. package/dist/cli/execute.js +112 -0
  20. package/dist/cli/help.d.ts +8 -0
  21. package/dist/cli/help.js +153 -0
  22. package/dist/cli/main.d.ts +2 -0
  23. package/dist/cli/main.js +114 -0
  24. package/dist/cli/operation-args.d.ts +25 -0
  25. package/dist/cli/operation-args.js +245 -0
  26. package/dist/core/auth/oauth.d.ts +39 -0
  27. package/dist/core/auth/oauth.js +102 -0
  28. package/dist/core/auth/scopes.d.ts +19 -0
  29. package/dist/core/auth/scopes.js +49 -0
  30. package/dist/core/auth/secret-store.d.ts +60 -0
  31. package/dist/core/auth/secret-store.js +141 -0
  32. package/dist/core/auth/session.d.ts +75 -0
  33. package/dist/core/auth/session.js +200 -0
  34. package/dist/core/catalog.d.ts +12 -0
  35. package/dist/core/catalog.js +33 -0
  36. package/dist/core/client.d.ts +22 -0
  37. package/dist/core/client.js +45 -0
  38. package/dist/core/config.d.ts +27 -0
  39. package/dist/core/config.js +109 -0
  40. package/dist/core/environments.d.ts +21 -0
  41. package/dist/core/environments.js +53 -0
  42. package/dist/core/errors.d.ts +96 -0
  43. package/dist/core/errors.js +248 -0
  44. package/dist/core/index.d.ts +21 -0
  45. package/dist/core/index.js +22 -0
  46. package/dist/core/jobs.d.ts +15 -0
  47. package/dist/core/jobs.js +19 -0
  48. package/dist/core/operations.d.ts +108 -0
  49. package/dist/core/operations.js +7 -0
  50. package/dist/core/output/format.d.ts +19 -0
  51. package/dist/core/output/format.js +62 -0
  52. package/dist/core/output/render.d.ts +53 -0
  53. package/dist/core/output/render.js +229 -0
  54. package/dist/core/pagination.d.ts +2 -0
  55. package/dist/core/pagination.js +3 -0
  56. package/dist/core/request.d.ts +29 -0
  57. package/dist/core/request.js +109 -0
  58. package/dist/core/version.d.ts +10 -0
  59. package/dist/core/version.js +13 -0
  60. package/dist/generated/mcp-tools.d.ts +2 -0
  61. package/dist/generated/mcp-tools.js +5937 -0
  62. package/dist/generated/operations.d.ts +4 -0
  63. package/dist/generated/operations.js +17701 -0
  64. package/dist/mcp/errors.d.ts +34 -0
  65. package/dist/mcp/errors.js +100 -0
  66. package/dist/mcp/live.d.ts +3 -0
  67. package/dist/mcp/live.js +5 -0
  68. package/dist/mcp/prompts.d.ts +23 -0
  69. package/dist/mcp/prompts.js +101 -0
  70. package/dist/mcp/resources.d.ts +25 -0
  71. package/dist/mcp/resources.js +125 -0
  72. package/dist/mcp/server.d.ts +20 -0
  73. package/dist/mcp/server.js +59 -0
  74. package/dist/mcp/session.d.ts +60 -0
  75. package/dist/mcp/session.js +105 -0
  76. package/dist/mcp/tools.d.ts +17 -0
  77. package/dist/mcp/tools.js +181 -0
  78. package/dist/mcp/types.d.ts +25 -0
  79. package/dist/mcp/types.js +2 -0
  80. package/node_modules/@tracken/sdk/LICENSE +21 -0
  81. package/node_modules/@tracken/sdk/README.md +76 -0
  82. package/node_modules/@tracken/sdk/SOURCE.json +10 -0
  83. package/node_modules/@tracken/sdk/dist/client.d.ts +94 -0
  84. package/node_modules/@tracken/sdk/dist/client.js +258 -0
  85. package/node_modules/@tracken/sdk/dist/credentials.d.ts +60 -0
  86. package/node_modules/@tracken/sdk/dist/credentials.js +122 -0
  87. package/node_modules/@tracken/sdk/dist/decimal.d.ts +20 -0
  88. package/node_modules/@tracken/sdk/dist/decimal.js +67 -0
  89. package/node_modules/@tracken/sdk/dist/environments.d.ts +14 -0
  90. package/node_modules/@tracken/sdk/dist/environments.js +16 -0
  91. package/node_modules/@tracken/sdk/dist/errors.d.ts +150 -0
  92. package/node_modules/@tracken/sdk/dist/errors.js +190 -0
  93. package/node_modules/@tracken/sdk/dist/generated/operations.d.ts +1955 -0
  94. package/node_modules/@tracken/sdk/dist/generated/operations.js +2746 -0
  95. package/node_modules/@tracken/sdk/dist/generated/schema.d.ts +17988 -0
  96. package/node_modules/@tracken/sdk/dist/generated/schema.js +5 -0
  97. package/node_modules/@tracken/sdk/dist/index.d.ts +27 -0
  98. package/node_modules/@tracken/sdk/dist/index.js +24 -0
  99. package/node_modules/@tracken/sdk/dist/jobs.d.ts +23 -0
  100. package/node_modules/@tracken/sdk/dist/jobs.js +80 -0
  101. package/node_modules/@tracken/sdk/dist/operations.d.ts +23 -0
  102. package/node_modules/@tracken/sdk/dist/operations.js +2 -0
  103. package/node_modules/@tracken/sdk/dist/pagination.d.ts +19 -0
  104. package/node_modules/@tracken/sdk/dist/pagination.js +49 -0
  105. package/node_modules/@tracken/sdk/dist/request.d.ts +27 -0
  106. package/node_modules/@tracken/sdk/dist/request.js +10 -0
  107. package/node_modules/@tracken/sdk/dist/runtime.d.ts +22 -0
  108. package/node_modules/@tracken/sdk/dist/runtime.js +33 -0
  109. package/node_modules/@tracken/sdk/dist/tracken.d.ts +74 -0
  110. package/node_modules/@tracken/sdk/dist/tracken.js +203 -0
  111. package/node_modules/@tracken/sdk/dist/types.d.ts +130 -0
  112. package/node_modules/@tracken/sdk/dist/types.js +1 -0
  113. package/node_modules/@tracken/sdk/dist/version.d.ts +2 -0
  114. package/node_modules/@tracken/sdk/dist/version.js +2 -0
  115. package/node_modules/@tracken/sdk/package.json +42 -0
  116. package/node_modules/openapi-fetch/CHANGELOG.md +565 -0
  117. package/node_modules/openapi-fetch/CONTRIBUTING.md +102 -0
  118. package/node_modules/openapi-fetch/LICENSE +21 -0
  119. package/node_modules/openapi-fetch/README.md +122 -0
  120. package/node_modules/openapi-fetch/dist/index.cjs +547 -0
  121. package/node_modules/openapi-fetch/dist/index.cjs.map +1 -0
  122. package/node_modules/openapi-fetch/dist/index.d.cts +337 -0
  123. package/node_modules/openapi-fetch/dist/index.d.mts +335 -0
  124. package/node_modules/openapi-fetch/dist/index.d.ts +337 -0
  125. package/node_modules/openapi-fetch/dist/index.mjs +531 -0
  126. package/node_modules/openapi-fetch/dist/index.mjs.map +1 -0
  127. package/node_modules/openapi-fetch/package.json +77 -0
  128. package/node_modules/openapi-fetch/src/index.d.ts +345 -0
  129. package/node_modules/openapi-fetch/src/index.js +689 -0
  130. package/node_modules/openapi-typescript-helpers/CHANGELOG.md +98 -0
  131. package/node_modules/openapi-typescript-helpers/LICENSE +21 -0
  132. package/node_modules/openapi-typescript-helpers/README.md +5 -0
  133. package/node_modules/openapi-typescript-helpers/dist/index.cjs +3 -0
  134. package/node_modules/openapi-typescript-helpers/dist/index.cjs.map +1 -0
  135. package/node_modules/openapi-typescript-helpers/dist/index.d.cts +167 -0
  136. package/node_modules/openapi-typescript-helpers/dist/index.d.mts +167 -0
  137. package/node_modules/openapi-typescript-helpers/dist/index.d.ts +167 -0
  138. package/node_modules/openapi-typescript-helpers/dist/index.mjs +2 -0
  139. package/node_modules/openapi-typescript-helpers/dist/index.mjs.map +1 -0
  140. package/node_modules/openapi-typescript-helpers/package.json +39 -0
  141. package/openapi/SOURCE.json +10 -0
  142. package/openapi/openapi.yaml +30514 -0
  143. package/package.json +63 -4
package/README.md CHANGED
@@ -1,3 +1,311 @@
1
- # Temporary Holding Version
1
+ # tracken — the Tracken command line
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `tracken` works with Tracken Accounts' public API from a terminal or a script: every operation the
4
+ API serves is a command, generated from the public API document, with sign-in through Tracken ID.
5
+
6
+ ```
7
+ tracken <resource> <verb> [ids…] [flags]
8
+ tracken contacts list --type company --since 7d
9
+ tracken contacts archive 0b8f0c2e-5f3c-4a52-9d7e-1c2b3a4d5e6f
10
+ tracken items list --all --ndjson
11
+ tracken api GET /contacts?limit=5
12
+ ```
13
+
14
+ Published on npm as `@tracken/cli` (with the SDK, `@tracken/sdk`, beside it) from v0.2.0 (owner
15
+ decision 14.11.2026), under the MIT license (`LICENSE`); the API it calls is still a draft. The
16
+ repository stays private.
17
+
18
+ ## Install
19
+
20
+ Node.js 22 or later.
21
+
22
+ ```
23
+ npm i -g @tracken/cli
24
+ tracken --version # the CLI's version and the API document it was built from
25
+ ```
26
+
27
+ Each release is also a git tag `v<version>` and a GitHub release carrying the same `npm pack`
28
+ tarballs: `gh release download v<version> -R Tracken-Technologies/tracken-cli`, then
29
+ `npm i -g ./tracken-cli-<version>.tgz`. From a clone: `npm ci && npm link`.
30
+
31
+ ## Sign in
32
+
33
+ ```
34
+ tracken login # read-only
35
+ tracken login --write # read, plus the write scopes of the operations the API serves
36
+ tracken login --scope invoices:read invoices:write reports:read
37
+ ```
38
+
39
+ `login` uses the OAuth device authorization grant: it prints a link and a code such as
40
+ `BCDF-GHJK`; open the link in any browser, check the code and confirm. The CLI always names its
41
+ API scopes, and Tracken ID decides how long the session lasts from them:
42
+
43
+ | Scopes | Stays signed in |
44
+ |---|---|
45
+ | read-only (`read`, `*:read`) | 7 days unused, 30 days at most |
46
+ | any write or manage scope | 24 hours unused, 7 days at most |
47
+
48
+ `--write` asks only for the write scopes that operations the API serves today need, so you
49
+ approve no more than the CLI can use. After an upgrade that brings new operations, a write session
50
+ signed in before it may lack a scope one of them needs: the API answers `403`, and the CLI exits 5
51
+ printing the exact command that keeps the session's scopes and adds the missing one, such as
52
+ `tracken login --scope read contacts:write invoices:write`. Run it, or `tracken login --write`
53
+ again.
54
+
55
+ Tokens are kept in the OS keychain (macOS Keychain, Windows Credential Manager, the Secret Service
56
+ on Linux). Where there is no keychain (a headless server, a container) the CLI says so and keeps
57
+ them in `~/.config/tracken/credentials.json`, readable only by you. Access tokens are refreshed
58
+ automatically; the refresh token rotates on every use. `tracken logout` revokes the session.
59
+
60
+ A person may belong to several organizations, and every command acts in one:
61
+
62
+ ```
63
+ tracken org list # * marks the current one
64
+ tracken org use <organization-id>
65
+ tracken whoami # environment, person, scopes, organization (no API call)
66
+ tracken whoami --verify # the same, confirmed by the API (GET /users/me)
67
+ ```
68
+
69
+ `org list` and `org use` ask the API who you are (`GET /users/me`), which needs no scope, so any
70
+ session can choose its organization; `org use` refuses one you cannot open. `--org <id>` (or
71
+ `TRACKEN_ORG`) overrides the choice for one command. For an API credential, `whoami --verify`
72
+ shows its name, how it authenticates, when it expires and its idle limit.
73
+
74
+ Every request names the CLI in `Tracken-Agent: tracken-cli/<version>` (the MCP server sends its
75
+ client's name and version instead), which Accounts' audit log records beside the token's client.
76
+ It is a label only and changes nothing the token may do.
77
+
78
+ ## Commands
79
+
80
+ Commands exist for the operations the API serves. The document also specifies operations the API
81
+ does not serve yet; `tracken --help` and `tracken <resource> --help` list them under "Coming", and
82
+ running one exits 2 without calling the API ("not yet in the public API"). When an environment is
83
+ ahead of the CLI (dev before a new release) `tracken api` reaches it; when it is behind (prod),
84
+ the API answers `403 OPERATION_NOT_PUBLIC` and the CLI says "not yet available in prod" (exit 5).
85
+
86
+ The resource is the API path's first segment and the verb the operation's: `list`, `get`,
87
+ `create`, `update`, `delete`, or an action after the colon (`issue`, `void`, `archive`,
88
+ `reconcile`, `import`…). Sub-resources add their name: `tracken dimensions list-values <dimension_id>`.
89
+ `tracken --help`, `tracken <resource> --help` and `tracken <resource> <verb> --help` list
90
+ everything, with each operation's flags and body fields.
91
+
92
+ - Query parameters are flags: `--status issued --status paid`, `--expand lines,payments`,
93
+ `--sort -date`.
94
+ - Bodies: `--data '{"contact_id": "…", "lines": […]}'`, `--data @invoice.json`, `--data @-`
95
+ (stdin), and `--set field=value` for single fields (typed by the schema; money stays a decimal
96
+ string). The CLI wraps the record in `{"data": …}`; options such as `--on-conflict return` sit
97
+ beside it.
98
+ - `--all` follows the cursor to the last page.
99
+ - `--since 2h` (or `7d`, `2026-10-24`, an RFC 3339 instant) asks for records changed since then,
100
+ in the order they changed (`sort=updated_at`, unless `--sort` says otherwise); on
101
+ `tracken deletions list` it is the deletions' own `since`. The answer says where the next read
102
+ starts: `meta.sync.next_since` in JSON (with `--all`, one document for every page), else
103
+ `next: --since <instant>` on stderr. Start the next read there, never at "now": it is 16 minutes
104
+ before this read began, so a change still being committed is not missed. A record can come in
105
+ two reads; keep the one with the newer `updated_at`.
106
+ - `--dry-run` asks the API to check a write and store, post and send nothing; the CLI says whether
107
+ the API confirmed it.
108
+ - `--wait` waits for a job an operation started (`202 Accepted`), such as a billing run or a bank
109
+ statement import; `--wait-timeout <seconds>` (default 600).
110
+ - Every POST carries an automatic `Idempotency-Key`, reused on the CLI's own retries.
111
+ `--idempotency-key <key>` chooses it, for scripts that may run twice: within 24 hours the API
112
+ answers the same key with the first result instead of creating again. Keys are per credential,
113
+ so a person's and an API credential's never collide; a dry run neither uses nor spends one.
114
+ Rate limits (`429`) are retried after `Retry-After`.
115
+ - `--format pdf --out invoice.pdf` saves a rendition. The API answers it with a short-lived
116
+ pre-signed link (`303`), which the CLI downloads without your token.
117
+
118
+ Output: `-o json` (the API's answer as it is; the default in a pipe), `-o table` (the default in
119
+ a terminal; money and dates in Estonian format in every language: `1 234,50`, `12.10.2026`),
120
+ `-o csv`, or `--ndjson` (`-o ndjson`: one record per line, streamed, for agents and large reads). `--columns number,date,total` picks fields.
121
+
122
+ `tracken api <METHOD> <path>` sends any request as the API takes it (include the `{"data": …}`
123
+ envelope yourself), with the same sign-in, headers and output.
124
+
125
+ ## Errors and exit codes
126
+
127
+ Errors print the API's code, message, each field problem with its JSON pointer, and the request
128
+ id to quote to support. With JSON output the error envelope is printed as it came, on stderr.
129
+
130
+ A `401` is never hidden. A person's session is refreshed once and the request sent again; when
131
+ Tracken ID refuses the refresh (the session's time limit, a sign-out of the browser that approved
132
+ it, a revoked token) the CLI forgets the session and exits 4 with the API's answer: run
133
+ `tracken login`. An API credential gets one fresh token; refused again, the CLI exits 4 saying
134
+ the credential was refused (disabled, expired or rotated?). The CLI never switches between your
135
+ session and an API credential to get past a 401. A `403 INSUFFICIENT_SCOPE` exits 5 and prints
136
+ the exact `tracken login --scope …` that keeps your session's scopes and adds one that admits the
137
+ call (for an API credential: the scope to grant it).
138
+
139
+ The subscription's refusals say who can act, and the CLI retries none of them. A `402
140
+ SUBSCRIPTION_INACTIVE` (the organization's subscription is not active: every command but
141
+ `users get-me` and `organization get` is refused) exits 13, says why and until when the data can
142
+ still be exported in the app, and asks you to have an owner reopen the subscription. A `409
143
+ WORK_MONTH_CONFIRM_REQUIRED` or `EXTRA_MONTH_CONFIRM_REQUIRED` means the write starts a month the
144
+ subscription bills: a person confirms it in the app (an API credential cannot), then you run the
145
+ same command again. `409 PLAN_LIMIT_REACHED` and `403 PLAN_FEATURE_NOT_INCLUDED` name the plan an
146
+ owner moves to. A `409 TRIAL_LIMIT_REACHED` means a company on a free trial has used one of the
147
+ trial's allowances (the day's customer e-mails, the month's digitized documents): it exits 7, names
148
+ the allowance and the day it resets, and says not to retry before then; an owner choosing a plan in
149
+ the app lifts it at once.
150
+
151
+ | Exit | Meaning |
152
+ |---|---|
153
+ | 0 | done |
154
+ | 1 | other failure |
155
+ | 2 | wrong command line, or an operation the API does not serve yet |
156
+ | 3 | network: the API or Tracken ID unreachable |
157
+ | 4 | 401 or not signed in: run `tracken login` |
158
+ | 5 | 403: missing scope or role |
159
+ | 6 | 404 |
160
+ | 7 | 409: state conflict, or the record exists |
161
+ | 8 | 412: changed since read (`--if-match`) |
162
+ | 9 | 400 or 422: invalid request |
163
+ | 10 | 429 after retries |
164
+ | 11 | 5xx after retries |
165
+ | 12 | `--wait`: the job failed |
166
+ | 13 | 402: the organization's subscription is not active |
167
+
168
+ ## Machine mode
169
+
170
+ Scripts and integrations that should not depend on a person use an API credential created in
171
+ Accounts under Settings → API access:
172
+
173
+ ```
174
+ export TRACKEN_CLIENT_ID=oc_…
175
+ export TRACKEN_CLIENT_SECRET=ocs_…
176
+ export TRACKEN_SCOPE="invoices:read reports:read" # optional; default: all the credential holds
177
+ tracken sales-invoices list --since 1d
178
+ ```
179
+
180
+ The CLI exchanges them for a short-lived token (client credentials, for the integration audience).
181
+ A credential belongs to one organization, so no organization is chosen or sent.
182
+
183
+ ## Environments
184
+
185
+ `--env prod|dev|local` or `TRACKEN_ENV` (default `prod`):
186
+
187
+ | Environment | Tracken ID | API |
188
+ |---|---|---|
189
+ | prod | https://id.tracken.ee | https://accounts-api.tracken.ee/v1 |
190
+ | dev | https://id.dev.tracken.ee | https://accounts-api.dev.tracken.ee/v1 |
191
+ | local | https://id.dev.tracken.ee | http://localhost:8000/v1 |
192
+
193
+ `local` is Accounts' local stack (`uv run uvicorn local_server:app`), which verifies dev Tracken ID tokens: it signs in at the dev issuer with the dev CLI client, keeps its own session, and calls the API on this machine.
194
+ `TRACKEN_ISSUER` and `TRACKEN_API_URL` point an environment elsewhere. Sessions and the chosen
195
+ organization are kept per environment. Other settings: `TRACKEN_CONFIG_DIR` (default
196
+ `~/.config/tracken`), `TRACKEN_TOKEN_STORE=keychain|file`, `TRACKEN_OUTPUT`, `TRACKEN_LANG=et|en`
197
+ (the language of API error messages).
198
+
199
+ ## The MCP server
200
+
201
+ `tracken mcp` is a local [Model Context Protocol](https://modelcontextprotocol.io) server on stdio:
202
+ it lets Claude Code, Claude Desktop, Cursor or VS Code work in Tracken Accounts as you, through the
203
+ same public API, sign-in and organization as the CLI. It runs on your computer and stores nothing.
204
+
205
+ ```
206
+ tracken login # or --write; the server uses this session
207
+ tracken mcp --print-config claude # also: cursor, vscode
208
+ ```
209
+
210
+ `--print-config` prints the JSON to paste into the client (it names this Node and CLI by absolute
211
+ path, so desktop apps that do not see your shell's PATH can start it; print it again after
212
+ upgrading Node). Add `--env dev` or `--org <id>` and they are carried into the configuration.
213
+
214
+ - **Claude Code**: save it as `.mcp.json` in a project, or `claude mcp add tracken -- tracken mcp`.
215
+ - **Claude Desktop**: merge it into `claude_desktop_config.json` (Settings → Developer → Edit Config).
216
+ - **Cursor**: `.cursor/mcp.json` in a project, or `~/.cursor/mcp.json`.
217
+ - **VS Code**: `.vscode/mcp.json` (its format is `{"servers": {…}}` with `"type": "stdio"`).
218
+
219
+ What it offers:
220
+
221
+ - **Tools**: the served public API operations marked for assistants (`x-mcp` in the document),
222
+ named like `list_sales_invoices`, `create_purchase_invoice`, `run_report`, each with a description
223
+ written for a model, MCP annotations (read-only, destructive, idempotent, open-world; the generator
224
+ refuses a tool whose annotations are missing or at odds with its method) and an input schema generated from
225
+ the document, nested bodies included. Inputs are the operation's parameters and its `data`
226
+ record, plus options such as `on_conflict` and `dry_run`; the organization is never an input.
227
+ Answers are structured content (the API's `data`, with `next_cursor` to page) and a short summary;
228
+ errors come back as tool errors with the API's code, message, field pointers and request id, and
229
+ an `action` saying what the assistant should do: a 401 that outlived the client's one refresh asks
230
+ it to have you run `tracken login` (an API credential's asks for the credential to be fixed),
231
+ a 403 names the scope to add; neither is retried. The server's `serverInfo` names the API document
232
+ version its tools were generated from.
233
+ Renditions (PDF, CSV, XLSX) are not offered: tools answer JSON. Operations that start background
234
+ work take `wait=true` to wait up to two minutes; `import_bank_statement` reads `file_path` from
235
+ this computer.
236
+ - **Resources**: reference data read through the API: `tracken://accounts`, `tracken://tax-codes`,
237
+ `tracken://dimensions` (with values), `tracken://items`, `tracken://object-types`,
238
+ `tracken://fiscal-years`, `tracken://periods`, `tracken://reports`.
239
+ - **Prompts**: `month_end_check`, `record_supplier_invoice`, `explain_report`,
240
+ `billing_run_preview`; each names the tools to use and where to stop for your confirmation.
241
+
242
+ Sign-in, organization and scopes:
243
+
244
+ - Only the operations the API serves are tools; a resource or prompt that needs one the API does not
245
+ serve yet is left out until it does.
246
+ - The server uses your `tracken login` session from the keychain, read again on every call: sign in,
247
+ sign in with `--write`, or `tracken org use` another organization in a terminal and the next tool
248
+ call follows, with no restart. Before anyone has signed in it still starts and lists its tools;
249
+ calls answer "run `tracken login`". It shares the CLI's refresh lock, so both can run at once.
250
+ - `--org <id>` or `TRACKEN_ORG_ID` pins the organization for this server; otherwise the one chosen
251
+ with `tracken org use` applies. `--env` (or `TRACKEN_ENV`) picks the environment as for the CLI.
252
+ - With `TRACKEN_CLIENT_ID`/`TRACKEN_CLIENT_SECRET` in the server's environment it acts as that
253
+ machine credential instead (its organization and scopes are the credential's).
254
+
255
+ Safety:
256
+
257
+ - **Read-only by default.** A session from plain `tracken login` can only read; a tool that changes
258
+ data answers "run `tracken login --write`" without calling the API. A write session stays signed
259
+ in 24 hours unused (7 days at most), a read-only one 7 days (30 at most), so give an assistant a
260
+ write session only while you need it, and `tracken logout` when done.
261
+ - Every write tool supports `dry_run=true` (the API checks it and stores, posts and sends nothing)
262
+ and the description of every tool the document marks destructive (issue, send, post, payment,
263
+ reconcile, billing run) asks the model to call it with `dry_run=true` first, show you the result
264
+ and get your confirmation before calling it for real. Your client's own tool approval still applies: do not
265
+ auto-approve write tools.
266
+ - The server runs as you on your computer: it can read a file you name for `import_bank_statement`
267
+ and upload it to your organization. It writes nothing to disk except what the CLI's session
268
+ refresh writes.
269
+
270
+ ## Development
271
+
272
+ ```
273
+ npm test # vitest, offline: fake Tracken ID and API on loopback (CLI, then SDK)
274
+ npm run typecheck
275
+ npm run lint
276
+ npm run tracken -- --help
277
+ npm run build # the SDK first, then the CLI against it
278
+ npm run pack:sdk # artifacts/tracken-sdk-<version>.tgz
279
+ ```
280
+
281
+ The public API document is vendored in `openapi/openapi.yaml`, copied from accounting_software
282
+ with `scripts/sync-openapi.sh --ref origin/main ~/repos/accounting_software` (re-run at every API
283
+ wave that lands). It reads the document at that commit with `git show`, never the checkout's
284
+ working tree, records the commit in `openapi/SOURCE.json`, and regenerates (`npm run generate`)
285
+ the command tree and MCP tools in `src/generated/` and the SDK's types (openapi-typescript, as the
286
+ web app) and operation table in `packages/sdk/src/generated/`. Which operations are served comes
287
+ from the document's own `x-availability` (`live|planned|later`) on every operation; the sync
288
+ refuses a document without it. Tests fail when the generated files or the recorded checksum drift
289
+ from the document.
290
+
291
+ Releasing: bump `version` in both package.json files (the root's `@tracken/sdk` dependency too),
292
+ `src/core/version.ts` and `packages/sdk/src/version.ts`, add the release's entry to `CHANGELOG.md`,
293
+ merge, then tag `v<version>` on main and push the tag. The Release workflow checks the tag matches
294
+ package.json, runs every check, and publishes a GitHub release with the CLI's `npm pack` tarball
295
+ (the SDK bundled inside) and the SDK's own tarball. Then the owner publishes those two tarballs to
296
+ npm by hand, the SDK first: `npm publish ./tracken-sdk-<version>.tgz`, then
297
+ `npm publish ./tracken-cli-<version>.tgz` (both public, `publishConfig.access`). No workflow
298
+ publishes to npm or holds an npm token.
299
+
300
+ The repository is an npm workspace: the CLI at the root and the SDK, `@tracken/sdk`, in
301
+ `packages/sdk/` (see its README). The CLI's API client is the SDK's: `src/core/client.ts`,
302
+ `pagination.ts` and `jobs.ts` reuse the SDK's transport, pagination and job polling, and its errors
303
+ are the SDK's, mapped to exit codes. The `tracken-source` export condition (set in `tsconfig.json`,
304
+ `vitest.config.ts` and `npm run tracken`) resolves the SDK to its sources during development; the
305
+ build compiles the SDK first and the CLI against its `dist/`. The CLI bundles the SDK
306
+ (`bundleDependencies`), so its tarball installs without the SDK on npm.
307
+
308
+ `src/core/` (environments, sign-in and sessions, request building, output) is independent of the
309
+ command line; `src/cli/` holds the commands and `src/mcp/` the
310
+ MCP server, whose tool list `src/generated/mcp-tools.ts` the generator also makes from the
311
+ document (`codegen/mcp.ts`), so a re-sync picks up new tools, descriptions and annotations.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env node
2
+ import { run } from "../cli/main.js";
3
+ import { processIo } from "../cli/context.js";
4
+ process.exitCode = await run(process.argv.slice(2), processIo());
5
+ //# sourceMappingURL=tracken.js.map
@@ -0,0 +1,17 @@
1
+ export declare const GLOBAL_SWITCHES: readonly ["all", "wait", "dry-run", "write", "help", "debug", "version", "verify", "ndjson"];
2
+ export declare class ParsedArgs {
3
+ readonly positionals: string[];
4
+ /** Every occurrence, in order; a switch given bare is `"true"`. */
5
+ readonly flags: Map<string, string[]>;
6
+ constructor(positionals: string[],
7
+ /** Every occurrence, in order; a switch given bare is `"true"`. */
8
+ flags: Map<string, string[]>);
9
+ has(name: string): boolean;
10
+ /** The last value given (a later flag overrides an earlier one). */
11
+ value(name: string): string | undefined;
12
+ values(name: string): string[];
13
+ switch(name: string): boolean;
14
+ /** Flag names other than the ones listed. */
15
+ others(known: Iterable<string>): string[];
16
+ }
17
+ export declare function parseArgs(argv: readonly string[]): ParsedArgs;
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The command line tokenizer. A flag takes a value unless it is a known switch, so `--all` never
3
+ * swallows the next word and `--limit 5` always takes `5`. The switch set is the CLI's own switches
4
+ * plus every boolean parameter of every operation (the generator refuses a flag that is a switch in
5
+ * one operation and valued in another, so this never depends on the command).
6
+ */
7
+ import { OPERATIONS } from "../generated/operations.js";
8
+ import { UsageError } from "../core/errors.js";
9
+ export const GLOBAL_SWITCHES = ["all", "wait", "dry-run", "write", "help", "debug", "version", "verify", "ndjson"];
10
+ const SHORT = { o: "output", h: "help", H: "header" };
11
+ function switches() {
12
+ const set = new Set(GLOBAL_SWITCHES);
13
+ for (const operation of OPERATIONS) {
14
+ for (const param of operation.params)
15
+ if (param.type === "boolean")
16
+ set.add(param.flag);
17
+ for (const field of [...(operation.body?.options ?? []), ...(operation.body?.form ?? [])])
18
+ if (field.type === "boolean")
19
+ set.add(field.flag);
20
+ }
21
+ return set;
22
+ }
23
+ const SWITCHES = switches();
24
+ export class ParsedArgs {
25
+ positionals;
26
+ flags;
27
+ constructor(positionals,
28
+ /** Every occurrence, in order; a switch given bare is `"true"`. */
29
+ flags) {
30
+ this.positionals = positionals;
31
+ this.flags = flags;
32
+ }
33
+ has(name) {
34
+ return this.flags.has(name);
35
+ }
36
+ /** The last value given (a later flag overrides an earlier one). */
37
+ value(name) {
38
+ const values = this.flags.get(name);
39
+ return values?.[values.length - 1];
40
+ }
41
+ values(name) {
42
+ return this.flags.get(name) ?? [];
43
+ }
44
+ switch(name) {
45
+ const value = this.value(name);
46
+ if (value === undefined)
47
+ return false;
48
+ if (value === "true")
49
+ return true;
50
+ if (value === "false")
51
+ return false;
52
+ throw new UsageError(`--${name} is a switch; give it alone or as --${name}=true|false.`);
53
+ }
54
+ /** Flag names other than the ones listed. */
55
+ others(known) {
56
+ const set = new Set(known);
57
+ return [...this.flags.keys()].filter((name) => !set.has(name));
58
+ }
59
+ }
60
+ const isFlag = (token) => token.startsWith("-") && token !== "-" && !/^-\d/.test(token);
61
+ export function parseArgs(argv) {
62
+ const positionals = [];
63
+ const flags = new Map();
64
+ const add = (name, value) => flags.set(name, [...(flags.get(name) ?? []), value]);
65
+ for (let index = 0; index < argv.length; index++) {
66
+ const token = argv[index];
67
+ if (token === "--") {
68
+ positionals.push(...argv.slice(index + 1));
69
+ break;
70
+ }
71
+ if (!isFlag(token)) {
72
+ positionals.push(token);
73
+ continue;
74
+ }
75
+ let name;
76
+ let inline;
77
+ if (token.startsWith("--")) {
78
+ const equals = token.indexOf("=");
79
+ name = equals === -1 ? token.slice(2) : token.slice(2, equals);
80
+ inline = equals === -1 ? undefined : token.slice(equals + 1);
81
+ }
82
+ else {
83
+ const short = SHORT[token.slice(1, 2)];
84
+ if (!short)
85
+ throw new UsageError(`Unknown option ${token}.`);
86
+ name = short;
87
+ inline = token.length > 2 ? token.slice(2).replace(/^=/, "") : undefined;
88
+ }
89
+ if (!name)
90
+ throw new UsageError(`Malformed option ${token}.`);
91
+ // Snake-case spellings of parameters work too: --updated_since is --updated-since.
92
+ name = name.replace(/_/g, "-");
93
+ if (inline !== undefined) {
94
+ add(name, inline);
95
+ continue;
96
+ }
97
+ if (name.startsWith("no-") && SWITCHES.has(name.slice(3))) {
98
+ add(name.slice(3), "false");
99
+ continue;
100
+ }
101
+ if (SWITCHES.has(name)) {
102
+ add(name, "true");
103
+ continue;
104
+ }
105
+ // A value may start with one dash (`--sort -date` sorts descending); a long flag is never a value.
106
+ const next = argv[index + 1];
107
+ if (next === undefined || next.startsWith("--"))
108
+ throw new UsageError(`--${name} needs a value.`);
109
+ add(name, next);
110
+ index++;
111
+ }
112
+ return new ParsedArgs(positionals, flags);
113
+ }
114
+ //# sourceMappingURL=args.js.map
@@ -0,0 +1,2 @@
1
+ import type { Context } from "../context.js";
2
+ export declare function api(context: Context): Promise<number>;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * `tracken api <METHOD> <path>`: any request as the API takes it, with the same sign-in,
3
+ * organization, Idempotency-Key, retries and output as the generated commands. The body is sent as
4
+ * given (include the `{"data": …}` envelope yourself).
5
+ */
6
+ import { matchOperation } from "../../core/catalog.js";
7
+ import { UsageError } from "../../core/errors.js";
8
+ import { execute } from "../execute.js";
9
+ import { GLOBAL_FLAGS, idempotencyKey } from "../operation-args.js";
10
+ const METHODS = ["get", "post", "put", "patch", "delete"];
11
+ async function body(context) {
12
+ const raw = context.args.value("data");
13
+ if (raw === undefined)
14
+ return undefined;
15
+ const text = raw === "@-" ? (await context.io.readStdin()).toString("utf8") : raw.startsWith("@") ? (await context.io.readFile(raw.slice(1))).toString("utf8") : raw;
16
+ try {
17
+ return JSON.parse(text);
18
+ }
19
+ catch (error) {
20
+ throw new UsageError(`--data is not valid JSON: ${error.message}`);
21
+ }
22
+ }
23
+ export async function api(context) {
24
+ const [, rawMethod, rawPath, ...extra] = context.args.positionals;
25
+ if (!rawMethod || !rawPath || extra.length)
26
+ throw new UsageError("Usage: tracken api <GET|POST|PUT|PATCH|DELETE> </path?query> [--data '{…}'] [-H 'Name: value']");
27
+ const method = rawMethod.toLowerCase();
28
+ if (!METHODS.includes(method))
29
+ throw new UsageError(`Unknown method ${rawMethod}; use GET, POST, PUT, PATCH or DELETE.`);
30
+ const unknown = context.args.others([...GLOBAL_FLAGS, "header", "dry-run"]);
31
+ if (unknown.length)
32
+ throw new UsageError(`Unknown flag --${unknown[0]} for tracken api.`);
33
+ if (context.args.has("set"))
34
+ throw new UsageError("tracken api sends --data as given; --set belongs to the generated commands.");
35
+ // A full URL on the API host works as well as a path relative to it.
36
+ const base = new URL(context.environment.apiBaseUrl);
37
+ const url = new URL(rawPath.startsWith("/") ? `${base.pathname.replace(/\/$/, "")}${rawPath}` : rawPath, base.origin);
38
+ if (url.origin !== base.origin)
39
+ throw new UsageError(`${rawPath} is not on ${base.origin}.`);
40
+ const prefix = base.pathname.replace(/\/$/, "");
41
+ const path = url.pathname.startsWith(`${prefix}/`) ? url.pathname.slice(prefix.length) : url.pathname;
42
+ if (/[{}]/.test(path))
43
+ throw new UsageError("Put the real ids in the path; {placeholders} are for the generated commands.");
44
+ const query = [...url.searchParams];
45
+ const dryRun = context.args.switch("dry-run");
46
+ if (dryRun)
47
+ query.push(["dry_run", "true"]);
48
+ const headers = {};
49
+ for (const header of context.args.values("header")) {
50
+ const colon = header.indexOf(":");
51
+ if (colon <= 0)
52
+ throw new UsageError(`--header takes "Name: value"; got "${header}".`);
53
+ const name = header.slice(0, colon).trim();
54
+ if (/^(authorization|user-agent)$/i.test(name))
55
+ throw new UsageError(`${name} is set by the CLI.`);
56
+ headers[name] = header.slice(colon + 1).trim();
57
+ }
58
+ const key = idempotencyKey(context.args, method, `tracken api ${method.toUpperCase()}`);
59
+ if (key) {
60
+ if (Object.keys(headers).some((name) => name.toLowerCase() === "idempotency-key"))
61
+ throw new UsageError("Give --idempotency-key or -H 'Idempotency-Key: …', not both.");
62
+ headers["Idempotency-Key"] = key;
63
+ }
64
+ const operation = matchOperation(method, path);
65
+ // The literal path goes through openapi-fetch's templating untouched; it has no {placeholders}.
66
+ const request = { method, path, pathParams: {}, query, headers, body: await body(context) };
67
+ if (operation)
68
+ request.operation = operation;
69
+ const client = await context.client();
70
+ await execute(context, client, request, { hints: operation?.display, dryRun, pageable: true });
71
+ return 0;
72
+ }
73
+ //# sourceMappingURL=api.js.map
@@ -0,0 +1,8 @@
1
+ import type { Context } from "../context.js";
2
+ export declare function login(context: Context): Promise<number>;
3
+ export declare function logout(context: Context): Promise<number>;
4
+ /**
5
+ * Which environment, credential, scopes and organization the next command uses: local facts, with
6
+ * no API call, unless `--verify` asks the API (getCurrentUser) to confirm them.
7
+ */
8
+ export declare function whoami(context: Context): Promise<number>;