@apet97/clockify-cli-115 5.0.4 → 7.0.0

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 (55) hide show
  1. package/README.md +255 -39
  2. package/dist/client.js +43 -17
  3. package/dist/closed-pipe.js +3 -0
  4. package/dist/commands/api.js +192 -103
  5. package/dist/commands/approvals.js +9 -10
  6. package/dist/commands/auditlog.js +11 -8
  7. package/dist/commands/auth.js +229 -0
  8. package/dist/commands/balanceAssignment.js +10 -8
  9. package/dist/commands/batch.js +226 -0
  10. package/dist/commands/clients.js +27 -72
  11. package/dist/commands/doctor.js +98 -82
  12. package/dist/commands/entries.js +29 -14
  13. package/dist/commands/expenses.js +75 -36
  14. package/dist/commands/helpers.js +74 -9
  15. package/dist/commands/invoices.js +12 -16
  16. package/dist/commands/leaf-command.js +15 -0
  17. package/dist/commands/log.js +4 -2
  18. package/dist/commands/manifest.js +63 -0
  19. package/dist/commands/operations.js +271 -0
  20. package/dist/commands/projects.js +28 -32
  21. package/dist/commands/reports.js +54 -21
  22. package/dist/commands/resolve-refs.js +30 -53
  23. package/dist/commands/scheduling.js +94 -40
  24. package/dist/commands/shared-report-body.js +127 -0
  25. package/dist/commands/sharedReports.js +19 -235
  26. package/dist/commands/skill.js +85 -0
  27. package/dist/commands/start.js +6 -4
  28. package/dist/commands/status.js +69 -27
  29. package/dist/commands/stop.js +7 -18
  30. package/dist/commands/tags.js +11 -11
  31. package/dist/commands/tasks.js +27 -133
  32. package/dist/commands/timeoff.js +23 -16
  33. package/dist/commands/users.js +11 -19
  34. package/dist/commands/webhook-delivery.js +331 -0
  35. package/dist/commands/webhooks.js +40 -104
  36. package/dist/completions.js +291 -55
  37. package/dist/config.js +168 -61
  38. package/dist/credentials.js +164 -0
  39. package/dist/duration.js +5 -4
  40. package/dist/failure.js +82 -0
  41. package/dist/flags.js +84 -0
  42. package/dist/generated/version.js +1 -1
  43. package/dist/index.js +68 -108
  44. package/dist/interrupts.js +28 -0
  45. package/dist/output.js +189 -66
  46. package/dist/receipt.js +2 -10
  47. package/dist/stdin.js +6 -0
  48. package/dist/stdout.js +38 -0
  49. package/dist/write-outcome.js +84 -0
  50. package/package.json +6 -4
  51. package/plugin/.claude-plugin/plugin.json +16 -0
  52. package/plugin/skills/clockify-cli/SKILL.md +88 -0
  53. package/plugin/skills/clockify-mcp/SKILL.md +48 -0
  54. package/plugin/skills/clockify-sdk/SKILL.md +85 -0
  55. package/dist/error-codes.js +0 -272
package/README.md CHANGED
@@ -3,8 +3,8 @@
3
3
  Command-line interface for [Clockify](https://clockify.me/), built on
4
4
  top of `clockify-sdk-ts-115`.
5
5
 
6
- Current release: `5.0.4`. Requires Node.js `>=22.13.0` and
7
- `clockify-sdk-ts-115 ^5.2.0`.
6
+ Version in this checkout: `7.0.0`. Requires Node.js `>=22.13.0` and
7
+ `clockify-sdk-ts-115 ^7.0.0`.
8
8
 
9
9
  Two binaries, identical behavior:
10
10
 
@@ -15,11 +15,9 @@ Two binaries, identical behavior:
15
15
  npm ci && make sdk-codegen # from the repo root, once
16
16
  npm run build -w clockify-sdk-ts-115 # build the workspace-linked SDK
17
17
  cd cli
18
- npm install
19
18
  npm run build
20
19
  npm link
21
- export CLOCKIFY_API_KEY=... # from Clockify > Profile > API Keys
22
- export CLOCKIFY_WORKSPACE_ID=... # from a workspace URL
20
+ clk115 auth login # or: export CLOCKIFY_API_KEY=... and CLOCKIFY_WORKSPACE_ID=...
23
21
 
24
22
  clk115 status
25
23
  clk115 projects list --limit 5
@@ -27,13 +25,45 @@ clk115 start "WIP refactor" -p "Acme Corp"
27
25
  clk115 stop
28
26
  ```
29
27
 
28
+ See the [MCP host compatibility guide](../docs/mcp-host-compatibility.md) for client setup and Reports App support.
29
+
30
+ ## Credentials
31
+
32
+ `clk115 auth login` reads the API key from stdin or a hidden prompt, checks it with Clockify, and keeps it in the OS
33
+ keychain (macOS keychain, or the Secret Service through `secret-tool` on Linux). Other platforms have no store: set
34
+ `CLOCKIFY_API_KEY` there. A key is never read from an argument and never written to a file.
35
+
36
+ ```sh
37
+ clk115 auth login # the first profile becomes the current one
38
+ clk115 auth login --profile sandbox --workspace 64c777ddd3fcab07cfbb210c
39
+ clk115 auth use sandbox
40
+ clk115 auth status --json # which key is used, checked with Clockify
41
+ clk115 auth exec -- clockify115-mcp # run a program with the credential in its environment
42
+ ```
43
+
44
+ - `CLOCKIFY_API_KEY` in the environment wins over the current profile. An explicit `--profile` wins over the whole
45
+ environment: no `CLOCKIFY_*` key, workspace or route applies. `CLOCKIFY_API_KEY` and `CLOCKIFY_PROFILE` together are
46
+ an error.
47
+ - A stored key belongs to one profile and one route: the region and subdomain, or the scheme, host and port of
48
+ `--base-url`. With another route it is not found, so it is never sent there. A route without `--base-url` has up to three hosts, all of them Clockify's: the API,
49
+ the reports, and the audit log, which Clockify serves for every region from one host.
50
+ - `auth login` takes the route from its flags or from the profile it replaces, not from the environment or the top of
51
+ the rc file. A new profile uses the global host unless you pass `--region`, `--subdomain` or `--base-url`.
52
+ - `auth exec` gives the program the route that the key was stored for, whatever its own environment or rc file says.
53
+ Ctrl-C in a terminal reaches the program directly. SIGTERM and SIGHUP are passed on to it; a SIGINT sent to `clk115`
54
+ alone is passed on only without a terminal, because it would reach a program in the same terminal twice.
55
+ - `auth logout` deletes the key from the keychain. It stays valid in Clockify until you replace it there.
56
+ - Any program that runs as you can ask the keychain for the key. The gain over a shell profile is that the key is
57
+ encrypted at rest and appears in no file, argument or host configuration.
58
+
30
59
  ## Configuration
31
60
 
32
61
  In precedence order (highest wins):
33
62
 
34
- 1. **Command-line flags:** `--workspace`, `--base-url`, `--region`, `--subdomain`
63
+ 1. **Command-line flags:** `--workspace`, `--base-url`, `--region`, `--subdomain`, `--profile`
35
64
  (credentials are never accepted on argv)
36
65
  2. **Environment variables:** `CLOCKIFY_API_KEY`, `CLOCKIFY_WORKSPACE_ID`,
66
+ `CLOCKIFY_PROFILE`,
37
67
  optional `CLOCKIFY_BASE_URL` for mock/replay or private gateway tests,
38
68
  optional `CLOCKIFY_REGION`/`CLOCKIFY_SUBDOMAIN` for regional routing
39
69
  3. **Rc file:** `clockifyrc.json`, then `.clockifyrc.json`, both looked up in
@@ -51,12 +81,20 @@ Rc file shape:
51
81
  ```json
52
82
  {
53
83
  "workspaceId": "65b382b6…",
54
- "baseUrl": "https://api.clockify.me/api/v1",
55
84
  "region": "eu",
56
- "subdomain": "acme"
85
+ "subdomain": "acme",
86
+ "profile": "sandbox",
87
+ "profiles": { "sandbox": { "workspaceId": "64c777dd…" } }
57
88
  }
58
89
  ```
59
90
 
91
+ `auth login`, `auth use` and `auth logout` maintain `profile` and `profiles`. A selected profile uses its own workspace
92
+ and route, not the ones beside it in the file.
93
+
94
+ A route in the rc file or the profile is used as a whole. When a flag or a variable names a base URL or a region,
95
+ `baseUrl`, `region` and `subdomain` of the file do not apply. A subdomain alone (`--subdomain`, `CLOCKIFY_SUBDOMAIN`)
96
+ refines that route. Flags and variables combine: `--region us` with `CLOCKIFY_SUBDOMAIN=acme` is `acme` in the US.
97
+
60
98
  For each unknown rc-file key, the CLI writes one warning to stderr, names the
61
99
  nearest known key, ignores the unknown key, and continues.
62
100
 
@@ -70,23 +108,81 @@ touching production credentials.
70
108
  ## Output modes
71
109
 
72
110
  - **Default:** human-friendly tables via `cli-table3`.
73
- - **`--output <mode>`:** `table`, `json`, or `ndjson`. `--json` is a
111
+ - **`--output <mode>`:** `table`, `json`, `ndjson`, or `csv`. `--json` is a
74
112
  shortcut for `--output json`.
113
+ - **`--fields <a,b.c>`:** print only these fields, in this order; dots reach nested fields. Works in every mode. A field
114
+ that no record has prints as null (empty in a table or CSV), with a warning. Where the fields do not depend on what
115
+ Clockify answers (`batch`, `operations`, `webhooks listen`, `doctor` and others), an unknown one is a usage error
116
+ before anything is sent.
75
117
  - **`--compact`:** single-line JSON without indentation.
76
118
  - **`--select <path>`:** print a dot-path (e.g. `--select data.id` or
77
- `--select 0.name`) before emitting JSON or NDJSON.
119
+ `--select 0.name`) before emitting JSON or NDJSON. An unknown path is treated like an unknown field.
78
120
 
79
121
  With `--output ndjson`, the CLI writes each array item as one JSON value on its
80
122
  own line, without a wrapping array; a non-array result is one line.
81
123
 
124
+ With `--output csv`, quoting follows RFC 4180, and text that a spreadsheet would run as a formula (it starts with `=`,
125
+ `+`, `-`, `@`, the full-width form of one of them, a tab or a line break) gets a leading `'`. Every line break in a cell
126
+ is written as a line feed, and an empty cell that is alone on its line as `""`. `clk115 reports` prints the rows of a
127
+ report, one entry or group each; other commands print what Clockify answers, one line per record. `reports detailed`
128
+ reads one page, and warns when that page is full.
129
+
130
+ Output that cannot be written exits 1 with `fatal: the output could not be written`. A reader that closes the pipe
131
+ (`| head -1`) ends the command quietly, except where that would hide something: `batch` and `webhooks listen` stop and
132
+ exit 1.
133
+
82
134
  In `json` and `ndjson` modes, errors go to stderr as `{"ok": false, "error":
83
- "...", "code": "...", "recovery": "...", "retryable": true|false}`.
135
+ "...", "code": "...", "recovery": "...", "retryable": true|false}`. An API
136
+ failure also carries `"status"` (the HTTP status) and, when Clockify returned
137
+ one, `"serverCode"` (its numeric body code, e.g. `403` with `4030`); usage and
138
+ local errors omit both. Mutation failures also report `stage` and `replaySafe`.
139
+ A failed prerequisite read can be retried when `retryable` is true. After an
140
+ ambiguous or applied write, read the record back before taking further action.
141
+ A raw response that cannot be rendered exits 1 with its HTTP status.
84
142
  Successful write commands in JSON and NDJSON include receipt fields:
85
143
  `ok`, `action`, `entity`, `ids`, `changed`, `warnings`, and `next`.
86
144
  Legacy top-level fields such as `id` remain for simple shell scripts.
87
145
  Read-only commands (e.g. `status`, `entries list`) print the requested
88
146
  object or array directly, with no `ok` wrapper. `--no-color` disables
89
- ANSI codes, and the CLI also auto-disables color when stdout is not a TTY.
147
+ ANSI codes, and color is off when a stream is not a TTY unless `FORCE_COLOR`
148
+ enables it.
149
+
150
+ A failed delete can follow a successful update. For tasks, clients and projects,
151
+ the error includes `completedStage` (`marked_done` or `archived`) and a `next`
152
+ command to inspect the resource. The command exits 1 and leaves concurrent
153
+ edits intact after the delete attempt. `completedStage` names the state the
154
+ resource had reached. For clients and projects, `archiveAction` says who brought
155
+ it there: `archived_by_call`, or `already_archived` before this command ran.
156
+
157
+ `status` reports `timerState`. An `unavailable` state carries `timerStateReason`:
158
+ `user_id_missing`, `response_unrecognized` or `workspace_not_set`. Only a list
159
+ that Clockify returned and that holds no running entry of yours is `idle`.
160
+
161
+ Scheduling with `--publish` publishes all drafts for the selected user in the
162
+ start/end window. The receipt identifies that window in `publishScope`.
163
+ A create response that identifies no assignment exits 1 and publishes nothing.
164
+ The write may have applied, so the error has `replaySafe: false` and gives the
165
+ command that lists the window.
166
+ When a scheduling publish response is lost, the CLI reads the assignment back.
167
+ A verified publication exits 0. A refused publish or verified draft exits 1
168
+ with the created assignment ID and publish request. If the read cannot verify
169
+ publication, the receipt says `published: "unknown"` and gives a read-back
170
+ command to run before retrying.
171
+
172
+ `expenses list` prints a JSON array, one expense per NDJSON line, or a table.
173
+ Reaching `--limit` returns the requested prefix. Reaching `--max-pages` first
174
+ can leave matching expenses unexamined. In either case the command exits 0
175
+ and warns on stderr, or exits 1 with `--require-complete`. To continue, keep
176
+ the same filters and page size and append the printed
177
+ `--page N --offset M --max-pages K` flags. At the last supported page the
178
+ warning says when there is no further cursor.
179
+
180
+ Add `--with-meta` for machine-readable scan metadata. JSON then returns
181
+ `{"items":[…],"meta":{…}}`. NDJSON appends one final `{"meta":{…}}` line,
182
+ even for zero expenses. With NDJSON, `--select` applies to the expense rows.
183
+ Complete scans report `meta.hasMore: false`. When a cursor is available,
184
+ `nextPage`, `nextOffset` (defaults to zero), and `nextMaxPages` provide the
185
+ three continuation values.
90
186
 
91
187
  ### Money units
92
188
 
@@ -94,11 +190,19 @@ Clockify's wire units are not uniform, and the CLI keeps its established
94
190
  `amount` field names for JSON compatibility:
95
191
 
96
192
  - `expenses create --amount` and `expenses update --amount` accept major
97
- currency units, so `42.50` means 42.50 in the selected currency.
98
- - `expenses list` emits the response `total` as `amount` in minor units
99
- (cents for two-decimal currencies), so 42.50 is returned as `4250`.
193
+ currency units, so `42.50` means 42.50 in the selected currency. An amount
194
+ above 9007199254740991 exits 2, because the number sent could differ from the
195
+ one typed.
196
+ - `expenses list` exposes the response total as `totalMinor` in minor units
197
+ (42.50 is `4250` for a two-decimal currency), with `amountSource: "total"`.
198
+ An omitted total gives `totalMinor: null`, `amountSource: "unavailable"`, and
199
+ an em dash in the table. Legacy JSON `amount` falls back to the per-unit
200
+ amount, quantity or zero.
100
201
  - Invoice `amount` values from `invoices list` and `invoices create` receipts
101
- are also minor units.
202
+ are also minor units. `invoices list` adds `totalMinor` and `amountSource` with
203
+ the same rules: an omitted amount gives `totalMinor: null`,
204
+ `amountSource: "unavailable"`, and an em dash in the table, while legacy JSON
205
+ `amount` stays `0`.
102
206
 
103
207
  Use an emitted `currency` value when present; otherwise apply the workspace or
104
208
  entity currency. The raw `api` command always returns Clockify's response
@@ -111,11 +215,25 @@ without unit conversion.
111
215
  |---|---|
112
216
  | `clk115 status` | Print workspace, current user, and running timer. |
113
217
  | `clk115 doctor` | Check local CLI configuration without contacting Clockify. |
218
+ | `clk115 auth login` | Check an API key with Clockify, then keep it in the OS keychain under a profile. The key is read from stdin or a hidden prompt. |
219
+ | `clk115 auth status` | Show which credential is used, and check it with Clockify. |
220
+ | `clk115 auth list` | List the profiles and whether each has a key in the keychain. |
221
+ | `clk115 auth use <profile>` | Make a profile the current one. |
222
+ | `clk115 auth logout` | Delete a profile and its key from the keychain. |
223
+ | `clk115 auth exec -- <command…>` | Run a program with the selected credential in its environment. |
224
+ | `clk115 operations list [words…] [--effect effect] [--tag tag] [--limit N] [--all]` | Search the catalog of every public API operation. Needs no credentials. |
225
+ | `clk115 operations show <operation>` | Print the method, path, effect and input schema of an operation. Needs no credentials. |
226
+ | `clk115 operations call <operation> [-p key=value…] [-q key=value…] [--body json] [--file path] [--output-file path] [--dry-run]` | Call any operation. The input is checked against its schema before anything is sent. |
227
+ | `clk115 batch [@file\|-] [--on-error stop\|continue] [--concurrency N] [--max-requests N] [--dry-run]` | Run many operations from NDJSON rows. Every row is checked before the first request. |
228
+ | `clk115 commands` | List every command with its arguments, options and risk, for scripts and agents. |
229
+ | `clk115 skill list` | List the agent skills that come with this command line. |
230
+ | `clk115 skill show <name>` | Print an agent skill. |
231
+ | `clk115 skill install [names…] [--dir path] [--personal] [--force]` | Copy agent skills into a directory an agent reads. |
114
232
  | `clk115 start [description] [-p project] [-t task] [--tag tag…] [--billable]` | Start a timer. Resolves project, task, and tag names to IDs. |
115
233
  | `clk115 stop` | Stop the running timer for the current user. |
116
234
  | `clk115 log <duration> <description> [-p project] [-t task] [--tag tag…] [--billable] [--end iso]` | Log a finished entry. Resolves project, task, and tag names to IDs. Duration accepts `1h30m`, `90m`, or `PT1H30M`. |
117
- | `clk115 entries list [--limit N] [--page N] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--description text]` | List time entries for the current user. |
118
- | `clk115 entries get-many --ids id1,id2 [--hydrated]` | Look up several time entries by ID in one call. |
235
+ | `clk115 entries list [--limit N] [--page N] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--description text] [--time-view-mode mode]` | List time entries for the current user. |
236
+ | `clk115 entries get-many --ids id1,id2 [--hydrated]` | Look up several time entries by ID. Hydrated rows include project, task and tag detail. |
119
237
  | `clk115 entries delete <id>` | Delete a time entry. |
120
238
  | `clk115 projects list [--limit N] [--page N] [--name text] [--archived] [--client id]` | List projects. |
121
239
  | `clk115 projects create <name> [--client id] [--color hex] [--billable]` | Create a project. |
@@ -140,9 +258,13 @@ without unit conversion.
140
258
  | `clk115 webhooks list [--type type]` | List outbound webhooks. |
141
259
  | `clk115 webhooks create --name X --url U --event E [--trigger-source-type T --trigger-source ids]` | Create a webhook subscription. |
142
260
  | `clk115 webhooks delete <id>` | Delete a webhook subscription. |
261
+ | `clk115 webhooks events` | List the event names a webhook can subscribe to. |
262
+ | `clk115 webhooks listen --webhook id\|--secret-stdin [--port N] [--forward url] [--max N]` | Receive deliveries on a loopback port, verify each one and print it as a JSON line. |
263
+ | `clk115 webhooks trigger <event> --data json --webhook id\|--secret-stdin [--url url]` | Send a signed delivery to a handler on this machine. |
264
+ | `clk115 webhooks recover <id> [--status FAILED\|RETRYING] [--forward url] [--limit N]` | List the deliveries of a webhook that Clockify could not complete, and optionally hand them to a local handler. |
143
265
  | `clk115 invoices list [--limit N] [--page N]` | List invoices in the workspace. |
144
266
  | `clk115 invoices create --client id --number N --currency USD --issued YYYY-MM-DD --due YYYY-MM-DD [--time-view-mode mode]` | Create an invoice draft. |
145
- | `clk115 expenses list [--limit N] [--page-size N] [--max-pages N] [--page N] [--start date] [--end date]` | List workspace expenses; date bounds are applied client-side across bounded pages. |
267
+ | `clk115 expenses list [--limit N] [--page-size N] [--max-pages N] [--page N] [--offset N] [--with-meta] [--require-complete] [--start date] [--end date]` | List workspace expenses; date bounds are applied client-side across bounded pages. |
146
268
  | `clk115 expenses get <id>` | Get one expense by ID. |
147
269
  | `clk115 expenses create --amount N --category id --date YYYY-MM-DD [--user id] [--project id] [--task id] [--notes text] [--billable\|--no-billable]` | Create an expense (scalar body; --user defaults to the API-key owner). |
148
270
  | `clk115 expenses update <id> --amount N --category id --date YYYY-MM-DD --user id [--project id] [--task id] [--notes text] [--billable\|--no-billable]` | Update an expense (full replace of amount, category, date). |
@@ -156,12 +278,12 @@ without unit conversion.
156
278
  | `clk115 scheduling list --from date --to date [--limit N] [--page N] [--name text]` | List scheduling assignments. |
157
279
  | `clk115 scheduling create --user id --project id --start date --end date --hours-per-day N [--task id --note text --billable --include-non-working-days --publish]` | Create a scheduling assignment. Drafts by default; pass `--publish` to publish. |
158
280
  | `clk115 audit-log search --start RFC3339 --end RFC3339 --actions A,B,… [--authors ids --authors-mode CONTAINS\|DOES_NOT_CONTAIN --page N --limit N]` | Search the workspace audit log. Window must be ≤ 31 days. |
159
- | `clk115 reports summary [--period p] [--from date] [--to date] [--groups PROJECT,TASK] [--billable] [--project name\|id…] [--client name\|id…]` | Summary report totals over a date range, grouped per --groups. Read-only. |
160
- | `clk115 reports detailed [--period p] [--from date] [--to date] [--page N] [--page-size N]` | Detailed report listing individual time entries over a date range. Read-only. |
161
- | `clk115 reports weekly [--period p] [--from date] [--to date] [--group USER\|PROJECT] [--subgroup TIME]` | Weekly report over exactly one seven-calendar-day window. Read-only. |
162
- | `clk115 reports attendance [--period p] [--from date] [--to date]` | Attendance report of clock-in/out activity over a date range. Read-only. |
281
+ | `clk115 reports summary [--period p] [--from date] [--to date] [--groups PROJECT,TASK] [--billable] [--project name\|id…] [--client name\|id…] [--time-view-mode mode]` | Summary report totals over a date range, grouped per --groups. Read-only. |
282
+ | `clk115 reports detailed [--period p] [--from date] [--to date] [--page N] [--page-size N] [--time-view-mode mode]` | Detailed report listing individual time entries over a date range. Read-only. |
283
+ | `clk115 reports weekly [--period p] [--from date] [--to date] [--group USER\|PROJECT] [--subgroup TIME] [--time-view-mode mode]` | Weekly report over exactly one seven-calendar-day window. Read-only. |
284
+ | `clk115 reports attendance [--period p] [--from date] [--to date] [--time-view-mode mode]` | Attendance report of clock-in/out activity over a date range. Read-only. |
163
285
  | `clk115 shared-reports list` | List the workspace's shared (public-link) reports. Read-only. |
164
- | `clk115 shared-reports view <id> [--export-type JSON_V1\|JSON\|CSV]` | View a shared report's text-safe rendered data by ID (not workspace-scoped). XLSX/PDF are rejected before the request until output-file streaming exists. Read-only. |
286
+ | `clk115 shared-reports view <id> [--export-type JSON_V1\|JSON\|CSV] [--time-view-mode mode]` | View a shared report's text-safe rendered data by ID (not workspace-scoped). XLSX/PDF are rejected before the request until output-file streaming exists. Read-only. |
165
287
  | `clk115 shared-reports create --name X --type T --filter json [--public\|--no-public]` | Create a shared (public-link) report. |
166
288
  | `clk115 shared-reports update <id> --name X --type T --filter json [--public\|--no-public]` | Replace a shared report by ID (full replace of name, type, and filter). |
167
289
  | `clk115 shared-reports delete <id>` | Delete a shared report. |
@@ -169,7 +291,7 @@ without unit conversion.
169
291
  | `clk115 users list [--limit N] [--page N] [--name text]` | List members of the workspace. Read-only. |
170
292
  | `clk115 users invite <email> [--no-send-email]` | Invite (add) a user to the workspace by email. |
171
293
  | `clk115 users update-profile <userId> [--name text] [--image-url url] [--remove-image] [--week-start day] [--work-capacity iso] [--working-days days…]` | Update one user's member profile. |
172
- | `clk115 api <method> <path> [-q key=value…] [-H key=value…] [--body json\|@file\|-] [--all] [--page-size N] [--max-pages N] [--include-headers]` | Call a Clockify API path directly through the SDK client. Fills {workspaceId} from --workspace or CLOCKIFY_WORKSPACE_ID. |
294
+ | `clk115 api <method> <path> [-q key=value…] [-H key=value…] [--body json\|@file\|-] [--all] [--page-size N] [--max-pages N] [--require-complete] [--include-headers]` | Call a Clockify API path directly through the SDK client. Fills {workspaceId} from --workspace or CLOCKIFY_WORKSPACE_ID. |
173
295
  | `clk115 approvals submit-with-type --type TIMESHEET\|EXPENSE --period-start date [--period WEEKLY\|SEMI_MONTHLY\|MONTHLY]` | Submit the current user's approval request with an explicit type. |
174
296
  | `clk115 approvals submit-for-user-with-type --user id --type TIMESHEET\|EXPENSE\|TIMESHEET_AND_EXPENSE --period-start date [--period WEEKLY\|SEMI_MONTHLY\|MONTHLY]` | Submit another user's approval request with an explicit type. |
175
297
  | `clk115 completion [zsh\|bash\|fish]` | Print a shell completion script for zsh, bash, or fish. |
@@ -191,7 +313,7 @@ Log a 90-minute entry that ended now:
191
313
  clk115 log 1h30m "RFC review"
192
314
  ```
193
315
 
194
- Log a 30-minute entry that ended yesterday at 17:00 UTC, in JSON for
316
+ Log a 30-minute entry ending at a specific UTC time, in JSON for
195
317
  piping into `jq`:
196
318
 
197
319
  ```sh
@@ -204,8 +326,78 @@ List the 50 most recent entries, filtered by description:
204
326
  clk115 entries list --limit 50 --description deploy
205
327
  ```
206
328
 
207
- Call a long-tail endpoint directly through the SDK client when no curated
208
- command exists yet:
329
+ The scripts in [`examples/`](./examples) are ready to run with `CLOCKIFY_API_KEY` and `CLOCKIFY_WORKSPACE_ID` set:
330
+ `status.sh`, `list-projects.sh`, `log-time.sh [project]`, `daily-timesheet.sh [day]`, and `export-json.sh [directory]`,
331
+ which never leaves a partial export behind its final name. `mock-run.sh` needs no key: start `make mock-clockify` in the
332
+ repository first.
333
+
334
+ ## Every operation
335
+
336
+ When no command fits, search the catalog of all public API operations, read the schema, and call it. `list` and `show`
337
+ need no credentials. The input of `call` is checked before anything is sent.
338
+
339
+ ```sh
340
+ clk115 operations list archive a project
341
+ clk115 operations show projects.update --json
342
+ clk115 operations call tags.list -q archived=false --output csv --fields id,name
343
+ clk115 operations call tags.create --body '{"name":"focus"}' --dry-run
344
+ clk115 operations call invoices.export -p invoiceId=64c777ddd3fcab07cfbb210c -q userLocale=en-US --output-file invoice.pdf
345
+ ```
346
+
347
+ A file goes to `--output-file`, which must not exist yet, or to a redirected stdout, byte for byte. `operations call`
348
+ and `batch` leave out a webhook's signing token, and show nothing of an answer that may hold one and is not JSON.
349
+
350
+ `clk115 commands --json` describes every command, with its options, defaults and risk: `read`, `local` (changes only
351
+ this machine), `write` or `destructive`.
352
+
353
+ ## Batches
354
+
355
+ `batch` runs one operation per NDJSON row. Every row is checked before the first request, so one bad row means that
356
+ nothing is sent (exit 2).
357
+
358
+ ```sh
359
+ echo '{"operation":"tags.create","body":{"name":"focus"},"id":"row-1"}' | clk115 batch --dry-run
360
+ clk115 batch @rows.ndjson --on-error continue > results.ndjson
361
+ ```
362
+
363
+ Each row gets one result line with its `index`, `id`, `operation`, `outcome` and `data` or `error`:
364
+
365
+ | Outcome | Meaning |
366
+ |---|---|
367
+ | `ok` | Clockify answered with success. |
368
+ | `rejected` | Clockify refused the write. Nothing changed. |
369
+ | `unknown` | The write may have applied. Read the record back before you send the row again. |
370
+ | `failed` | A read failed. |
371
+ | `skipped` | The row was not sent. |
372
+
373
+ A row is sent again only after a 429, which changed nothing: up to three times, after the wait that Clockify asks for,
374
+ when that is at most a minute. A rate limit that outlasts this stops the batch. So does a write with an unknown outcome.
375
+ Both do so with `--on-error continue` too. Interrupting the batch (Ctrl-C, SIGTERM, or a terminal that closes) lets the
376
+ requests in flight finish. Interrupting it again gives them up, and a write that was given up is `unknown`. When the
377
+ output cannot be written the batch stops, and every result goes to stderr; so it does when nobody reads the output
378
+ within a second after the second interrupt. Each way, every row is reported. Requests run one at a time unless
379
+ `--concurrency` says otherwise (8 at most). `--max-requests` (1000) guards against a wrong file.
380
+
381
+ ## Webhooks on this machine
382
+
383
+ `webhooks listen` verifies deliveries on a loopback port, prints each one as a JSON line, and can pass it to a local
384
+ handler. Clockify delivers to public `https://` URLs only, so put your own tunnel in front. A delivery that cannot be
385
+ printed or handed on is answered with 500, so that Clockify sends it again. `--max` counts what was printed. `--forward`
386
+ passes on the bytes that arrived. An interrupt finishes the deliveries that have arrived in full, and drops the others.
387
+ `webhooks trigger` sends a signed delivery to a local handler, and `webhooks recover` reads what Clockify could not
388
+ deliver in the last 7 days. The signing secret comes from Clockify (`--webhook`) or from stdin (`--secret-stdin`), and
389
+ goes to loopback addresses only.
390
+
391
+ ## Agent skills
392
+
393
+ `clk115 skill install` copies the skills that come with this version to `.claude/skills` (`--personal` for your home,
394
+ `--dir` for another agent). It refuses a skill directory or a `SKILL.md` that is a symbolic link; the directories above
395
+ may be links. In Claude Code the skills and the MCP server also come as one plugin:
396
+ `/plugin install clockify115 --marketplace apet97/clockify-ts-sdk`.
397
+
398
+ ## The raw API
399
+
400
+ Call a path directly through the SDK client:
209
401
 
210
402
  ```sh
211
403
  clk115 api GET '/workspaces/{workspaceId}/tags' --query page-size=20 --output json
@@ -217,8 +409,24 @@ clk115 api POST '/workspaces/{workspaceId}/tags' --body '{"name":"billable"}' --
217
409
  `--all` walks `page`/`page-size` until a short or empty page (bounded by
218
410
  `--max-pages`), and `--body` also accepts `@file` or `-` for stdin. If the walk
219
411
  stops because it hit `--max-pages`, the collection is incomplete and a `WARN`
220
- line goes to **stderr**; stdout stays byte-identical either way, so pipelines
221
- are unaffected and a script can detect truncation without parsing output.
412
+ line goes to **stderr**; stdout stays byte-identical either way. A script that
413
+ must not continue with a partial collection adds `--require-complete`: the rows
414
+ are printed and the command exits 1.
415
+
416
+ An exact duplicate of the previous page stops the walk before adding its rows.
417
+ The warning identifies an endpoint that ignores pagination. Raw HTTP errors
418
+ use the same Clockify body-code classification as curated commands. A failed
419
+ response whose body cannot be read keeps its HTTP status, and `--include-headers`
420
+ prints it with `data: null` and the read failure as `bodyError`.
421
+
422
+ ### Binary responses
423
+
424
+ For binary exports, redirect stdout to a file or pipe it to another program.
425
+ The CLI writes the response bytes verbatim. A terminal, JSON/NDJSON mode,
426
+ `--include-headers` and `--all` cannot carry them. An `Accept` header that names
427
+ only binary types then fails before any request is sent (exit 2). Without one,
428
+ the CLI learns the type from the response and fails after the request was sent
429
+ (exit 1), so a write may already have applied.
222
430
 
223
431
  ## Shell completion
224
432
 
@@ -228,24 +436,33 @@ completion location:
228
436
 
229
437
  ```sh
230
438
  # bash (Linux)
439
+ mkdir -p ~/.local/share/bash-completion/completions
231
440
  clk115 completion bash > ~/.local/share/bash-completion/completions/clk115
232
441
 
233
- # zsh — write into a directory on your $fpath, then restart the shell
234
- clk115 completion zsh > "${fpath[1]}/_clk115"
442
+ # zsh — add ~/.zfunc to fpath before running compinit in .zshrc
443
+ mkdir -p ~/.zfunc
444
+ clk115 completion zsh > ~/.zfunc/_clk115
235
445
 
236
446
  # fish
447
+ mkdir -p ~/.config/fish/completions
237
448
  clk115 completion fish > ~/.config/fish/completions/clk115.fish
238
449
  ```
239
450
 
451
+ With `--json` or `--output ndjson`, the completion script is one JSON string.
452
+
240
453
  For a one-off in the current shell: `source <(clk115 completion bash)`. The
241
- `clockify115` binary accepts the same subcommand. See `examples/` for runnable
242
- scripts.
454
+ `clockify115` binary accepts the same subcommand.
243
455
 
244
456
  ## Exit codes
245
457
 
246
- - `0` — success
247
- - `1` — any error (API failure, validation, missing config)
248
- - `2` — commander argument error (unknown flag, missing required arg)
458
+ - `0` — success, including `--help` and `--version`
459
+ - `1` — runtime or API failure (missing credentials, HTTP errors, network failures)
460
+ - `2` — usage or local input validation error (unknown flag, missing required argument, invalid enum, date or filter). Nothing was changed: only reads, such as a name lookup, can have been sent before it.
461
+
462
+ `auth exec` exits as the program it ran, with `128` plus the signal number when a signal ended it. `batch`,
463
+ `webhooks recover` and `webhooks listen --max` exit with `129` (SIGHUP), `130` (SIGINT) or `143` (SIGTERM) exactly when
464
+ an interrupt cut their work short, and report what they did. Any other command that a signal ends prints nothing more: a
465
+ write that was in flight may have applied.
249
466
 
250
467
  ## Development
251
468
 
@@ -254,7 +471,6 @@ git clone https://github.com/apet97/clockify-ts-sdk
254
471
  cd clockify-ts-sdk && npm ci && make sdk-codegen # populate the gitignored generated SDK sources
255
472
  npm run build -w clockify-sdk-ts-115 # build the workspace-linked SDK
256
473
  cd cli
257
- npm install
258
474
  npm run dev -- status # via tsx, no build needed
259
475
  npm test # unit tests across duration / config / output / CLI contract / mock server
260
476
  npm run build # tsc → dist/
@@ -262,7 +478,7 @@ node dist/index.js status # smoke test (or invoke installed clk115/clockify11
262
478
  ```
263
479
 
264
480
  `clockify-sdk-ts-115` is workspace-linked for local development and is a
265
- `^5.2.0` peer dependency for published consumers.
481
+ `^7.0.0` peer dependency for published consumers.
266
482
 
267
483
  ## License
268
484
 
package/dist/client.js CHANGED
@@ -1,12 +1,18 @@
1
- import { requireApiKey } from "./config.js";
1
+ import { isMutationCommand } from "./commands/leaf-command.js";
2
+ import { missingApiKey } from "./config.js";
3
+ import { UsageError } from "./failure.js";
4
+ import { observeWriteTransport } from "./write-outcome.js";
2
5
  export const REGIONAL_PREFIXES = ["eu", "us", "uk", "au"];
3
6
  export const KNOWN_REGIONS = ["global", ...REGIONAL_PREFIXES, "developer"];
4
- export function buildRoutingOptions(region, subdomain) {
7
+ export function buildRoutingOptions(region, subdomain, baseUrl) {
5
8
  if (region === undefined && subdomain === undefined)
6
9
  return undefined;
10
+ if (baseUrl !== undefined) {
11
+ throw new UsageError("clk115: --region/--subdomain and --base-url configure the same thing two different ways; provide only one of them.");
12
+ }
7
13
  if (subdomain !== undefined) {
8
14
  if (region === undefined || !REGIONAL_PREFIXES.includes(region)) {
9
- throw new Error(`--subdomain requires --region (got ${JSON.stringify(region)}). Provide one of: ${REGIONAL_PREFIXES.join(", ")}.`);
15
+ throw new UsageError(`--subdomain requires --region (got ${JSON.stringify(region)}). Provide one of: ${REGIONAL_PREFIXES.join(", ")}.`);
10
16
  }
11
17
  return {
12
18
  profile: "subdomain",
@@ -18,7 +24,7 @@ export function buildRoutingOptions(region, subdomain) {
18
24
  if (region === "global")
19
25
  return { profile: "global" };
20
26
  if (region === undefined || !KNOWN_REGIONS.includes(region)) {
21
- throw new Error(`Unrecognized Clockify region ${JSON.stringify(region)}. Provide one of ${KNOWN_REGIONS.join(", ")}.`);
27
+ throw new UsageError(`Unrecognized Clockify region ${JSON.stringify(region)}. Provide one of ${KNOWN_REGIONS.join(", ")}.`);
22
28
  }
23
29
  return {
24
30
  profile: region,
@@ -31,22 +37,42 @@ export function unconfirmedRegionNotice(routing) {
31
37
  const host = routing.profile === "subdomain" ? `${routing.subdomain} (${routing.region})` : routing.profile;
32
38
  return `clk115: using the unconfirmed "${host}" Clockify profile. Only the global profile is live-confirmed; drop --region/--subdomain (and CLOCKIFY_REGION/CLOCKIFY_SUBDOMAIN or the rc-file entry) to route to api.clockify.me.`;
33
39
  }
34
- export async function buildClient(config) {
35
- const apiKey = requireApiKey(config);
36
- const routing = buildRoutingOptions(config.region, config.subdomain);
37
- if (routing !== undefined && config.baseUrl !== undefined) {
38
- throw new Error("clk115: --region/--subdomain and --base-url configure the same thing two different ways; provide only one of them.");
40
+ async function profileApiKey(config, store) {
41
+ const credentials = await import("./credentials.js");
42
+ return await credentials.storedApiKey(config, store ?? credentials.systemCredentialStore);
43
+ }
44
+ export function requireHeaderValue(apiKey) {
45
+ try {
46
+ new Headers().set("X-Api-Key", apiKey);
47
+ return apiKey;
39
48
  }
49
+ catch {
50
+ throw new UsageError("The API key has a character that no request header can carry. Provide the key exactly as Clockify shows it.");
51
+ }
52
+ }
53
+ export async function buildClient(config, command, credentials) {
54
+ const apiKey = config.apiKey ?? (await profileApiKey(config, credentials));
55
+ if (apiKey === undefined)
56
+ throw missingApiKey(config);
57
+ const transport = command && isMutationCommand(command) ? observeWriteTransport(command) : undefined;
58
+ const { client, routing } = await createRoutedClient(config, requireHeaderValue(apiKey), transport);
40
59
  const notice = unconfirmedRegionNotice(routing);
41
60
  if (notice !== undefined)
42
61
  process.stderr.write(`${notice}\n`);
62
+ return client;
63
+ }
64
+ const offline = () => {
65
+ throw new Error("This client only checks its route.");
66
+ };
67
+ export async function requireRoute(config) {
68
+ await createRoutedClient(config, offline);
69
+ }
70
+ async function createRoutedClient(config, apiKey, transport) {
71
+ const routing = buildRoutingOptions(config.region, config.subdomain, config.baseUrl);
43
72
  const { createClockifyClient } = await import("clockify-sdk-ts-115");
44
- if (routing !== undefined) {
45
- return createClockifyClient({ apiKey, allowNonClockifyHttpsHost: false, routing });
46
- }
47
- return createClockifyClient({
48
- apiKey,
49
- allowNonClockifyHttpsHost: false,
50
- ...(config.baseUrl !== undefined ? { environment: config.baseUrl } : {}),
51
- });
73
+ const options = { apiKey, allowNonClockifyHttpsHost: false, ...(transport && { fetch: transport }) };
74
+ const client = routing === undefined
75
+ ? createClockifyClient({ ...options, ...(config.baseUrl !== undefined && { environment: config.baseUrl }) })
76
+ : createClockifyClient({ ...options, routing });
77
+ return { client, routing };
52
78
  }
@@ -0,0 +1,3 @@
1
+ export function isClosedPipeError(err) {
2
+ return err?.code === "EPIPE" || err?.code === "ENOTCONN";
3
+ }