@deepdockai/cli 1.1.1 → 1.2.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.2.0
4
+
5
+ - Every `/v1` answer uses one `data` envelope. A list (a `many` action read, `GET /v1/devices`) answers `{ "data": [...], "nextCursor": ... }` (was `{ "data": { "items": [...], "nextCursor": ... } }`); `nextCursor` sits beside `data` and appears only on a list that pages. A single-record read (`cardinality: one`) answers `{ "data": { ...record } }` and a record that is not found answers `404 not_found`. Writes and error bodies are unchanged.
6
+ - Every refused action input (type, length, enum, bounds, a missing or unknown field, a bad `limit` or `cursor`) answers `422 invalid_input` with `error.fields`; `400 invalid_request` is for a malformed request only.
7
+ - The bundled TypeScript and Python clients read the new shape (`Page.items` keeps its name and holds `data`) and gain `readOne` / `read_one` for a single-record read. The skill and its references show the new answers.
8
+ - The bundled TypeScript and Python clients gain `download` for a file action (`file: true` in the action index): it posts the inputs like a read and returns the bytes, the content type and the file name from `Content-Disposition` (`filename*` first). A body shorter than its `Content-Length` throws `DeepdockTransportError`; a refusal is a `DeepdockError` as for any action, and `503 target_busy` is retried the same way. The skill describes file actions in `calling-actions.md`.
9
+
10
+ ## 1.1.2
11
+
12
+ - The bundled TypeScript and Python clients wait 35 seconds per attempt (was 30): a call can wait up to 10 seconds for the device's slot and then up to 20 seconds on the device. They also retry `503 target_busy` up to three attempts (`maxAttempts` / `max_attempts`), waiting the `Retry-After` seconds (at most 15, one second without the header) and sending the same request, so a write keeps its idempotency key. `DeepdockError` carries the header as `retryAfter` / `retry_after`.
13
+
3
14
  ## 1.1.1
4
15
 
5
16
  - A new error code, `partner_deactivated` (403): Deepdock has deactivated the organisation, so none of its keys work and its devices are disconnected until Deepdock reactivates it. The CLI exits with 2 on it, as on `partner_not_approved`. The bundled device types and the skill's error reference include it.
package/dist/deepdock.js CHANGED
@@ -11441,7 +11441,7 @@ import { spawn } from "node:child_process";
11441
11441
  import { homedir, hostname } from "node:os";
11442
11442
 
11443
11443
  // src/version.ts
11444
- var VERSION = "1.1.1";
11444
+ var VERSION = "1.2.0";
11445
11445
 
11446
11446
  // src/runtime.ts
11447
11447
  var DEFAULT_BASE_URL = "https://api.deepdock.ai";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@deepdockai/cli",
3
- "version": "1.1.1",
3
+ "version": "1.2.0",
4
4
  "description": "Deepdock partner CLI: pair devices, see systems and actions, create the API key your code runs them with.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/skill/SKILL.md CHANGED
@@ -107,7 +107,7 @@ and what your code does with the result.
107
107
  | [references/concepts.md](references/concepts.md) | you need the vocabulary: device, system, action, pause, incident, release |
108
108
  | [references/auth-and-keys.md](references/auth-and-keys.md) | creating, storing, sending or revoking a key; pairing or releasing a device |
109
109
  | [references/discovery.md](references/discovery.md) | reading the action index or the OpenAPI document |
110
- | [references/calling-actions.md](references/calling-actions.md) | writing the client: reads, writes, paging, authoring fields, timeouts |
110
+ | [references/calling-actions.md](references/calling-actions.md) | writing the client: reads, writes, paging, file downloads, authoring fields, timeouts |
111
111
  | [references/errors.md](references/errors.md) | handling any `error.code` |
112
112
  | [references/idempotency.md](references/idempotency.md) | retries, replays, unknown outcomes |
113
113
  | [references/cli.md](references/cli.md) | any `deepdock ...` command |
@@ -88,7 +88,7 @@ curl -X POST "$BASE/v1/devices" \
88
88
  (`id`, `label`, `hostname`, `os`, `clientVersion`, `status`, `lastSeenAt`, `lastKnownAt`, `claimedAt`, `outdated`, `systems`,
89
89
  and `updateAvailable` when it runs an older build); `hostname`, `os` and `clientVersion` are `null`
90
90
  until the device has reported them. Keep `id`: it is the `deviceId` of every later call.
91
- `GET /v1/devices` lists your devices a page at a time (`{ items, nextCursor }`; pass `nextCursor` back as `cursor` until it is `null`, `limit` 1 to 500, default 100), and `GET /v1/devices/{deviceId}` reads one; each device has the same shape. `GET /v1/incidents` pages the same way.
91
+ `GET /v1/devices` lists your devices a page at a time (`{ data: [...], nextCursor }`; pass `nextCursor` back as `cursor` until it is `null`, `limit` 1 to 500, default 100), and `GET /v1/devices/{deviceId}` reads one; each device has the same shape. `GET /v1/incidents` pages the same way.
92
92
 
93
93
  4. Release with `DELETE /v1/devices/{deviceId}`; the device then shows a new code.
94
94
 
@@ -13,7 +13,7 @@ is refused, not run.
13
13
 
14
14
  Inputs are typed as the action's schema declares them and are never sent as text when they are not:
15
15
  an integer is a JSON number (`"patientId": 4711`, not `"4711"`; the text form is refused with
16
- `400 invalid_request`). Text is normalised to Unicode NFC before anything else happens; a composed
16
+ `422 invalid_input`). Text is normalised to Unicode NFC before anything else happens; a composed
17
17
  and a decomposed spelling are the same value.
18
18
 
19
19
  **Never put an input in the URL.** A value in a URL reaches request logs, proxies and browser
@@ -24,8 +24,8 @@ needs no escaping.
24
24
 
25
25
  ### Reads
26
26
 
27
- A read takes its inputs, and `limit` (a JSON integer from 1 to 250, default 25) and `cursor` (a
28
- string) for paging, in the same body. No `Idempotency-Key`: a repeated read changes nothing, and the
27
+ A read takes its inputs, and, when it can page, `limit` (a JSON integer from 1 to 250, default 25)
28
+ and `cursor` (a string), in the same body. No `Idempotency-Key`: a repeated read changes nothing, and the
29
29
  header is ignored.
30
30
 
31
31
  ```bash
@@ -36,20 +36,51 @@ curl -X POST "$BASE/v1/devices/$DEVICE/systems/example-erp/actions/searchCustome
36
36
  ```
37
37
 
38
38
  ```json
39
- { "data": { "items": [ { "customerId": 1001, "lastName": "Müller", "city": "Beispielstadt" } ], "nextCursor": null } }
39
+ { "data": [ { "customerId": 1001, "lastName": "Müller", "city": "Beispielstadt" } ], "nextCursor": null }
40
40
  ```
41
41
 
42
+ - A read with `cardinality: many` answers `data` as an array; `nextCursor` is a sibling of `data`
43
+ (present only on a read that can page). A read with `cardinality: one` (for example
44
+ `readPatient`) answers `data` as the record itself, `{ "data": { "customerId": 1001, ... } }`, and
45
+ answers `404 not_found` when no record matches.
42
46
  - Pass `nextCursor` back as `cursor` unchanged while it is not `null`, and stop only on `null`,
43
47
  never on a short page: a page of long entries (notes) ends before `limit` rows to keep the
44
48
  device's answer under 1 MiB and still carries a cursor. It is opaque: never parse, build or store
45
49
  it beyond the next request.
46
- - Items are the customer's records. Values can be `null` where the schema says so. Dates and other
50
+ - Rows are the customer's records. Values can be `null` where the schema says so. Dates and other
47
51
  non-numeric values arrive as text in the system's own format (the schema and description say
48
52
  which); numbers as JSON numbers.
49
53
  - A read's description may say a field is a **prefix match** and what it ignores (case,
50
54
  punctuation, umlaut spelling). Design your search UI around that rule rather than filtering
51
55
  client-side.
52
56
 
57
+ ### File actions
58
+
59
+ An action marked `file: true` in the action index (for example a document download) is a read
60
+ that answers with the file itself instead of JSON. Call it like a read: `POST` with its inputs in
61
+ the JSON body, no `limit` or `cursor`, no `Idempotency-Key`.
62
+
63
+ ```bash
64
+ curl -X POST "$BASE/v1/devices/$DEVICE/systems/example-erp/actions/downloadDocument" \
65
+ -H "Authorization: Bearer $DEEPDOCK_API_KEY" \
66
+ -H "Content-Type: application/json" \
67
+ -d '{"documentId":7}' -o document.pdf
68
+ ```
69
+
70
+ - `200` carries the bytes. `Content-Type` is the type the action declares (or
71
+ `application/octet-stream`), `Content-Disposition` names the file (`filename*` in UTF-8 beside
72
+ an ASCII `filename`), and `Content-Length` is sent when the size is known.
73
+ - A refusal before the file starts is the usual JSON error (`404 not_found` when there is no such
74
+ file, `503 target_busy`, `503 device_offline`, ...).
75
+ - Once the bytes flow, a failure can only end the body early: compare the bytes received with
76
+ `Content-Length` and treat a short body as a failed download, never as the file. Run it again.
77
+ - The file name is already safe to save on Windows, macOS and Linux, but it is the customer's data
78
+ (a document title can name a patient): store and show it like any other record value.
79
+ - The bundled clients do all of this in `download` (TypeScript: `{ bytes, contentType, filename }`;
80
+ Python: `Download(content, content_type, filename)`), and throw `DeepdockTransportError` for a
81
+ short body. A large file can take longer than 35 seconds to transfer, so their timeout bounds the
82
+ wait for the answer and each gap between two reads, not the whole transfer.
83
+
53
84
  ### Writes (create and update)
54
85
 
55
86
  Body: a flat JSON object with only the fields the schema lists (`additionalProperties: false`) and
@@ -95,7 +126,7 @@ Never invent an id, copy one from another device, or hard-code one from a test r
95
126
  - **Send each input as the type its schema declares.** An id the schema declares as an integer goes
96
127
  in as a JSON number (`"customerId": 1001`), one it declares as text goes in as text
97
128
  (`"customerId": "1001"`: digits only, no leading zero, at most 10 characters). A value of the
98
- wrong type is refused with `400 invalid_request`, never converted. Result field types also come
129
+ wrong type is refused with `422 invalid_input`, never converted. Result field types also come
99
130
  from the action's own output schema.
100
131
  - **Mark every test text `TEST-DEEPDOCK-<id>`** on the demo device only, and list what you created
101
132
  ([testing.md](testing.md)).
@@ -108,14 +139,18 @@ Never invent an id, copy one from another device, or hard-code one from a test r
108
139
  |---|---|---|
109
140
  | `405 invalid_request`, `Allow: POST` or `Allow: PATCH` | a method other than the action's own (for example `POST` to an update, or `PATCH` to a read or create) | use the method `Allow` names: `POST` for a read or create, `PATCH` for an update |
110
141
  | `400 invalid_request` | a query string on an action path | move every value into the JSON body |
111
- | `400 invalid_request` | an input of the wrong type, such as `"4711"` where an integer is declared | send the type the schema declares |
142
+ | `422 invalid_input` (`error.fields` names each input) | an input of the wrong type, such as `"4711"` where an integer is declared | send the type the schema declares |
112
143
 
113
144
  ## Timeouts and latency
114
145
 
115
146
  - Every action call is sent to the customer's PC and run there. Expect a read to take from a few
116
147
  hundred milliseconds to a few seconds; a write about the same plus its verification.
117
- - Deepdock waits at most 20 seconds for the device, then answers `503 device_offline`. Set your HTTP
118
- client timeout to 30 seconds so you receive the code instead of timing out first. A write that
148
+ - A call can wait up to 10 seconds for the device's slot (`503 target_busy` with a `Retry-After`
149
+ header when it stays taken), then gets up to 20 seconds on the device (`503 device_offline`), so
150
+ the worst answer takes about 30 seconds. Set your HTTP client timeout to at least 35 seconds so
151
+ you receive the code instead of timing out first. The bundled clients do this and retry
152
+ `503 target_busy` up to three attempts, waiting the `Retry-After` seconds (at most 15), with the
153
+ same `Idempotency-Key`. A write that
119
154
  timed out or failed on the network on your side may still have landed: retry with the same
120
155
  `Idempotency-Key`.
121
156
  - An answer that is not JSON (a proxy's 502 or 504 page) is a transport failure: for a write, the
@@ -8,14 +8,17 @@ Everything action-specific (fields, types, patterns) comes from the live OpenAPI
8
8
  from __future__ import annotations
9
9
 
10
10
  import os
11
+ import re
12
+ import time
11
13
  from dataclasses import dataclass, field, replace
12
- from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
13
- from urllib.parse import quote
14
+ from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, TypeVar, Union
15
+ from urllib.parse import quote, unquote
14
16
 
15
17
  import httpx
16
18
 
17
19
  # A flat JSON value as the action's schema declares it: a number is a number, never its text.
18
20
  InputValue = Union[str, int, float, bool]
21
+ T = TypeVar("T")
19
22
 
20
23
 
21
24
  class DeepdockError(Exception):
@@ -33,9 +36,22 @@ class DeepdockError(Exception):
33
36
  self.version = version # system_version_unverified: the version the system last reported, None when it reported none
34
37
  self.reason = reason # system_version_unverified: unverified_version, unparseable or unreported
35
38
  self.created = created # applied_unverified, outcome_unknown with no rollback: {"chartId"} or None
39
+ self.retry_after: Optional[str] = None # the Retry-After header as sent (seconds), when the answer carried one
36
40
  self.uncertain = uncertain # outcome_unknown: True when the write may or may not have landed
37
41
 
38
42
 
43
+ MAX_RETRY_WAIT = 15.0 # longest wait between two attempts, whatever Retry-After asks for
44
+ DEFAULT_RETRY_WAIT = 1.0
45
+
46
+
47
+ def _retry_wait(header: Optional[str]) -> float:
48
+ try:
49
+ seconds = float(header) if header is not None else -1.0
50
+ except ValueError:
51
+ seconds = -1.0
52
+ return min(seconds, MAX_RETRY_WAIT) if seconds >= 0 else DEFAULT_RETRY_WAIT
53
+
54
+
39
55
  class DeepdockTransportError(Exception):
40
56
  """No answer, or not Deepdock's envelope (timeout, network, a proxy page): a write may still have landed."""
41
57
 
@@ -52,31 +68,97 @@ class WriteResult:
52
68
  replayed: bool
53
69
 
54
70
 
71
+ @dataclass
72
+ class Download:
73
+ """A file action's answer: the bytes, the type the action declares, and the name to save it under."""
74
+ content: bytes
75
+ content_type: str
76
+ filename: Optional[str]
77
+
78
+
79
+ def _filename(disposition: Optional[str]) -> Optional[str]:
80
+ # Deepdock sends filename* (UTF-8) beside an ASCII filename; the name is already safe to save on
81
+ # Windows, and can carry personal data (a patient's name in a document title).
82
+ if disposition is None:
83
+ return None
84
+ extended = re.search(r"filename\*=UTF-8''([^;]+)", disposition, re.IGNORECASE)
85
+ if extended:
86
+ try:
87
+ return unquote(extended.group(1).strip(), errors="strict")
88
+ except UnicodeDecodeError:
89
+ pass # a malformed escape: fall back to the ASCII name
90
+ plain = re.search(r'filename="([^"]*)"', disposition, re.IGNORECASE)
91
+ return plain.group(1) if plain else None
92
+
93
+
94
+ def _unwrap(r: httpx.Response) -> Tuple[Any, Optional[str]]:
95
+ try:
96
+ body = r.json()
97
+ except ValueError:
98
+ raise DeepdockTransportError(f"non-JSON answer with status {r.status_code}")
99
+ if isinstance(body, dict) and "error" in body:
100
+ e = body["error"]
101
+ err = DeepdockError(r.status_code, e["code"], e["message"], e.get("requestId"), e.get("systems"),
102
+ e.get("version"), e.get("reason"), e.get("created"), e.get("uncertain"))
103
+ err.retry_after = r.headers.get("retry-after")
104
+ raise err
105
+ if not isinstance(body, dict) or "data" not in body:
106
+ raise DeepdockTransportError(f"unexpected body with status {r.status_code}")
107
+ return body["data"], body.get("nextCursor")
108
+
109
+
55
110
  class Deepdock:
56
- def __init__(self, api_key: str, base: Optional[str] = None, timeout: float = 30.0,
57
- client: Optional[httpx.Client] = None):
58
- # 30 s is above Deepdock's 20 s device wait, so device_offline arrives before a client timeout.
111
+ def __init__(self, api_key: str, base: Optional[str] = None, timeout: float = 35.0,
112
+ client: Optional[httpx.Client] = None, max_attempts: int = 3, sleep=time.sleep):
113
+ # 35 s is above the worst answer (up to 10 s for the device's slot, then up to 20 s on the
114
+ # device), so the error code arrives before a client timeout.
115
+ # max_attempts: attempts per call on 503 target_busy (1 turns the retry off). The same
116
+ # request is sent again, so a write keeps its idempotency key.
117
+ self.max_attempts = max(1, int(max_attempts))
118
+ self._sleep = sleep
59
119
  # Default: DEEPDOCK_BASE_URL from the environment (the CLI's own variable), else production.
60
120
  base = base or os.environ.get("DEEPDOCK_BASE_URL") or "https://api.deepdock.ai"
61
121
  self.c = client or httpx.Client(base_url=base.rstrip("/"), timeout=timeout)
62
122
  self.c.headers["Authorization"] = f"Bearer {api_key}"
63
123
 
64
- def _send(self, method: str, path: str, **kw: Any) -> Tuple[Any, httpx.Headers]:
124
+ def _retrying(self, once: Callable[[], T]) -> T:
125
+ attempt = 1
126
+ while True:
127
+ try:
128
+ return once()
129
+ except DeepdockError as e:
130
+ if attempt >= self.max_attempts or e.status != 503 or e.code != "target_busy":
131
+ raise
132
+ self._sleep(_retry_wait(e.retry_after))
133
+ attempt += 1
134
+
135
+ def _request(self, method: str, path: str, **kw: Any) -> httpx.Response:
65
136
  try:
66
- r = self.c.request(method, path, **kw)
67
- except httpx.HTTPError as e: # timeouts and network errors
137
+ return self.c.request(method, path, **kw)
138
+ except httpx.HTTPError as e: # timeouts, network errors, and a body cut off mid-way
68
139
  raise DeepdockTransportError(f"no answer from Deepdock: {type(e).__name__}") from e
69
- try:
70
- body = r.json()
71
- except ValueError:
72
- raise DeepdockTransportError(f"non-JSON answer with status {r.status_code}")
73
- if isinstance(body, dict) and "error" in body:
74
- e = body["error"]
75
- raise DeepdockError(r.status_code, e["code"], e["message"], e.get("requestId"), e.get("systems"),
76
- e.get("version"), e.get("reason"), e.get("created"), e.get("uncertain"))
77
- if not isinstance(body, dict) or "data" not in body:
140
+
141
+ def _send(self, method: str, path: str, **kw: Any) -> Tuple[Any, httpx.Headers, Optional[str]]:
142
+ def once() -> Tuple[Any, httpx.Headers, Optional[str]]:
143
+ r = self._request(method, path, **kw)
144
+ data, next_cursor = _unwrap(r)
145
+ return data, r.headers, next_cursor
146
+ return self._retrying(once)
147
+
148
+ def _download_once(self, path: str, params: Dict[str, InputValue]) -> Download:
149
+ r = self._request("POST", path, json=params)
150
+ if not 200 <= r.status_code < 300:
151
+ _unwrap(r)
78
152
  raise DeepdockTransportError(f"unexpected body with status {r.status_code}")
79
- return body["data"], r.headers
153
+ # Once the bytes flow, a failure can only end the body early. Content-Length counts encoded
154
+ # bytes, so it is compared only on a body sent as is.
155
+ declared = r.headers.get("content-length")
156
+ encoded = r.headers.get("content-encoding", "identity") != "identity"
157
+ if declared is not None and not encoded and int(declared) != len(r.content):
158
+ raise DeepdockTransportError(f"download ended at {len(r.content)} of {declared} bytes")
159
+ return Download(content=r.content,
160
+ content_type=r.headers.get("content-type", "application/octet-stream"),
161
+ filename=_filename(r.headers.get("content-disposition")))
80
162
 
81
163
  @staticmethod
82
164
  def _action_path(device_id: str, system: str, action: str) -> str:
@@ -84,15 +166,21 @@ class Deepdock:
84
166
 
85
167
  def read(self, device_id: str, system: str, action: str, params: Dict[str, InputValue],
86
168
  limit: Optional[int] = None, cursor: Optional[str] = None) -> Page:
87
- """Runs a read action: a POST whose JSON body holds the inputs and the paging fields, no
169
+ """Runs a read action with `cardinality: many`: a POST whose JSON body holds the inputs and the paging fields, no
88
170
  Idempotency-Key. Pass `next_cursor` back as `cursor` for the next page."""
89
171
  body: Dict[str, InputValue] = dict(params)
90
172
  if limit is not None:
91
173
  body["limit"] = limit
92
174
  if cursor is not None:
93
175
  body["cursor"] = cursor
94
- data, _ = self._send("POST", self._action_path(device_id, system, action), json=body)
95
- return Page(items=data["items"], next_cursor=data.get("nextCursor"))
176
+ data, _, next_cursor = self._send("POST", self._action_path(device_id, system, action), json=body)
177
+ return Page(items=data, next_cursor=next_cursor)
178
+
179
+ def read_one(self, device_id: str, system: str, action: str, params: Dict[str, InputValue]) -> Dict[str, Any]:
180
+ """Runs a single-record read (`cardinality: one`): the answer's `data` is the record itself.
181
+ A record that does not exist raises DeepdockError with status 404 and code "not_found"."""
182
+ data, _, _ = self._send("POST", self._action_path(device_id, system, action), json=params)
183
+ return data
96
184
 
97
185
  def read_all(self, device_id: str, system: str, action: str, params: Dict[str, InputValue],
98
186
  limit: Optional[int] = None) -> Iterator[Dict[str, Any]]:
@@ -105,6 +193,13 @@ class Deepdock:
105
193
  return
106
194
  cursor = page.next_cursor
107
195
 
196
+ def download(self, device_id: str, system: str, action: str, params: Dict[str, InputValue]) -> Download:
197
+ """Runs a file action (`file: true` in the action index): a POST like a read, answered with the file's
198
+ bytes instead of JSON. A refusal raises DeepdockError as for any action; a body that ends short of its
199
+ Content-Length raises DeepdockTransportError, and the download can be run again. The client's timeout
200
+ applies between bytes, so a large file streams as long as it keeps moving."""
201
+ return self._retrying(lambda: self._download_once(self._action_path(device_id, system, action), params))
202
+
108
203
  def write(self, device_id: str, system: str, action: str, operation: str, idempotency_key: str,
109
204
  body: Dict[str, InputValue]) -> WriteResult:
110
205
  """Runs a write action: POST for operation "create", PATCH for "update" (from the action index; any
@@ -112,14 +207,14 @@ class Deepdock:
112
207
  action's schema declares. Any other `operation` raises ValueError before anything is sent."""
113
208
  if operation not in ("create", "update"):
114
209
  raise ValueError(f"operation must be 'create' or 'update', got {operation!r}")
115
- data, headers = self._send("PATCH" if operation == "update" else "POST",
210
+ data, headers, _ = self._send("PATCH" if operation == "update" else "POST",
116
211
  self._action_path(device_id, system, action), json=body,
117
212
  headers={"Idempotency-Key": idempotency_key})
118
213
  return WriteResult(data=data, replayed=headers.get("Idempotent-Replayed") == "true")
119
214
 
120
215
  def systems(self, device_id: str) -> List[Dict[str, Any]]:
121
216
  """The device's systems and each action's state. A live call: can answer device_offline."""
122
- data, _ = self._send("GET", f"/v1/devices/{quote(device_id, safe='')}/systems")
217
+ data, _, _ = self._send("GET", f"/v1/devices/{quote(device_id, safe='')}/systems")
123
218
  return data
124
219
 
125
220
  def pair(self, code: str, label: Optional[str] = None) -> Dict[str, Any]:
@@ -127,7 +222,7 @@ class Deepdock:
127
222
  body: Dict[str, str] = {"code": code}
128
223
  if label is not None:
129
224
  body["label"] = label
130
- data, _ = self._send("POST", "/v1/devices", json=body)
225
+ data, _, _ = self._send("POST", "/v1/devices", json=body)
131
226
  return data
132
227
 
133
228
  def release(self, device_id: str) -> None:
@@ -21,6 +21,8 @@ export class DeepdockError extends Error {
21
21
  readonly created?: { chartId?: string } | null
22
22
  /** outcome_unknown: `true` when the write may or may not have landed. */
23
23
  readonly uncertain?: boolean
24
+ /** The `Retry-After` header as sent (seconds), when the answer carried one. */
25
+ retryAfter?: string
24
26
 
25
27
  constructor(status: number, code: string, message: string, requestId?: string,
26
28
  systems?: string[],
@@ -51,8 +53,9 @@ export class DeepdockTransportError extends Error {
51
53
  }
52
54
 
53
55
  type ErrorBody = { code: string; message: string; requestId?: string; systems?: string[]; version?: string | null; reason?: string; created?: { chartId?: string } | null; uncertain?: boolean }
54
- type Envelope<T> = { data: T } | { error: ErrorBody }
56
+ type Envelope<T> = { data: T; nextCursor?: string | null } | { error: ErrorBody }
55
57
 
58
+ /** One page of a `many` read: `items` is the answer's `data` array, `nextCursor` its top-level sibling. */
56
59
  export type Page<Item> = { items: Item[]; nextCursor: string | null }
57
60
  export type WriteResult<T> = { data: T; replayed: boolean }
58
61
  /** A flat JSON value as the action's schema declares it: a number is a number, never its text. */
@@ -131,9 +134,63 @@ export type DeviceSystem = {
131
134
  export type DeepdockOptions = {
132
135
  /** Default: `DEEPDOCK_BASE_URL` from the environment (the CLI's own variable), else production. */
133
136
  base?: string
134
- /** Above Deepdock's 20 s device wait, so you receive device_offline instead of timing out first. */
137
+ /** Per attempt, default 35 s: above the worst answer (up to 10 s for the device's slot, then up to 20 s on the device), so you receive the code instead of timing out first. */
135
138
  timeoutMs?: number
139
+ /** Attempts per call on `503 target_busy`, default 3; 1 turns the retry off. The same request is sent again, so a write keeps its idempotency key. */
140
+ maxAttempts?: number
136
141
  fetch?: typeof fetch
142
+ /** Waits between attempts; replace it in tests. */
143
+ sleep?: (ms: number) => Promise<void>
144
+ }
145
+
146
+ type SendInit = { method: string; headers?: Record<string, string>; body?: string }
147
+
148
+ /** A file action's answer: the bytes, the type the action declares, and the name to save it under. */
149
+ export type Download = { bytes: Uint8Array; contentType: string; filename: string | null }
150
+
151
+ const unwrap = async <T>(res: Response): Promise<{ data: T; nextCursor: string | null }> => {
152
+ let body: Envelope<T>
153
+ try {
154
+ body = (await res.json()) as Envelope<T>
155
+ } catch {
156
+ throw new DeepdockTransportError(`non-JSON answer with status ${res.status}`)
157
+ }
158
+ if (body !== null && typeof body === 'object' && 'error' in body) {
159
+ const { code, message, requestId, systems, version, reason, created, uncertain } = body.error
160
+ const error = new DeepdockError(res.status, code, message, requestId, systems, version, reason, created, uncertain)
161
+ error.retryAfter = res.headers.get('retry-after') ?? undefined
162
+ throw error
163
+ }
164
+ if (body === null || typeof body !== 'object' || !('data' in body)) {
165
+ throw new DeepdockTransportError(`unexpected body with status ${res.status}`)
166
+ }
167
+ return { data: body.data, nextCursor: body.nextCursor ?? null }
168
+ }
169
+
170
+ // Deepdock sends `filename*` (UTF-8) beside an ASCII `filename`; the name is already safe to save
171
+ // on Windows, and can carry personal data (a patient's name in a document title).
172
+ const filenameOf = (disposition: string | null): string | null => {
173
+ if (disposition === null) return null
174
+ const extended = /filename\*=UTF-8''([^;]+)/i.exec(disposition)?.[1]
175
+ if (extended !== undefined) {
176
+ try {
177
+ return decodeURIComponent(extended.trim())
178
+ } catch {
179
+ // A malformed escape: fall back to the ASCII name.
180
+ }
181
+ }
182
+ return /filename="([^"]*)"/i.exec(disposition)?.[1] ?? null
183
+ }
184
+
185
+ /** Longest wait between two attempts, whatever `Retry-After` asks for. */
186
+ const MAX_RETRY_WAIT_MS = 15_000
187
+ const DEFAULT_RETRY_WAIT_MS = 1_000
188
+
189
+ const retryWaitMs = (header: string | null): number => {
190
+ const seconds = header === null ? Number.NaN : Number(header)
191
+ return Number.isFinite(seconds) && seconds >= 0
192
+ ? Math.min(seconds * 1000, MAX_RETRY_WAIT_MS)
193
+ : DEFAULT_RETRY_WAIT_MS
137
194
  }
138
195
 
139
196
  // `process` is absent in a browser, and Deno throws on `process.env` without --allow-env; then the
@@ -150,48 +207,115 @@ export class Deepdock {
150
207
  private readonly apiKey: string
151
208
  private readonly base: string
152
209
  private readonly timeoutMs: number
210
+ private readonly maxAttempts: number
153
211
  private readonly fetchImpl: typeof fetch
212
+ private readonly sleep: (ms: number) => Promise<void>
154
213
 
155
214
  constructor(
156
215
  apiKey: string,
157
- { base = envBase() ?? 'https://api.deepdock.ai', timeoutMs = 30_000, fetch: fetchImpl = fetch }: DeepdockOptions = {},
216
+ {
217
+ base = envBase() ?? 'https://api.deepdock.ai',
218
+ timeoutMs = 35_000,
219
+ maxAttempts = 3,
220
+ fetch: fetchImpl = fetch,
221
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
222
+ }: DeepdockOptions = {},
158
223
  ) {
159
224
  this.apiKey = apiKey
160
225
  this.base = base.replace(/\/$/, '')
161
226
  this.timeoutMs = timeoutMs
227
+ this.maxAttempts = Math.max(1, Math.floor(maxAttempts))
162
228
  this.fetchImpl = fetchImpl
229
+ this.sleep = sleep
163
230
  }
164
231
 
165
- private async send<T>(
166
- path: string,
167
- init: { method: string; headers?: Record<string, string>; body?: string },
168
- ): Promise<{ data: T; headers: Headers }> {
169
- let res: Response
232
+ private async retrying<R>(once: () => Promise<R>): Promise<R> {
233
+ for (let attempt = 1; ; attempt++) {
234
+ try {
235
+ return await once()
236
+ } catch (err) {
237
+ if (
238
+ attempt >= this.maxAttempts ||
239
+ !(err instanceof DeepdockError) ||
240
+ err.status !== 503 ||
241
+ err.code !== 'target_busy'
242
+ ) {
243
+ throw err
244
+ }
245
+ await this.sleep(retryWaitMs(err.retryAfter ?? null))
246
+ }
247
+ }
248
+ }
249
+
250
+ private async fetchOnce(path: string, init: SendInit, signal: AbortSignal): Promise<Response> {
170
251
  try {
171
- res = await this.fetchImpl(`${this.base}${path}`, {
252
+ return await this.fetchImpl(`${this.base}${path}`, {
172
253
  method: init.method,
173
254
  headers: { Authorization: `Bearer ${this.apiKey}`, ...init.headers },
174
255
  body: init.body,
175
- signal: AbortSignal.timeout(this.timeoutMs),
256
+ signal,
176
257
  })
177
258
  } catch (err) {
178
259
  // TimeoutError from AbortSignal.timeout, AbortError, or a network TypeError.
179
260
  throw new DeepdockTransportError(`no answer from Deepdock: ${(err as Error).name}`)
180
261
  }
181
- let body: Envelope<T>
262
+ }
263
+
264
+ private send<T>(path: string, init: SendInit): Promise<{ data: T; headers: Headers; nextCursor: string | null }> {
265
+ return this.retrying(async () => {
266
+ const res = await this.fetchOnce(path, init, AbortSignal.timeout(this.timeoutMs))
267
+ return { ...(await unwrap<T>(res)), headers: res.headers }
268
+ })
269
+ }
270
+
271
+ private async downloadOnce(path: string, init: SendInit): Promise<Download> {
272
+ // The timeout bounds the wait for the answer and then each gap between two chunks, not the
273
+ // whole transfer: a large file streams for longer than one attempt's timeout.
274
+ const deadline = new AbortController()
275
+ let timer = setTimeout(() => deadline.abort(), this.timeoutMs)
276
+ const chunks: Uint8Array[] = []
277
+ let size = 0
278
+ let res: Response
182
279
  try {
183
- body = (await res.json()) as Envelope<T>
184
- } catch {
185
- throw new DeepdockTransportError(`non-JSON answer with status ${res.status}`)
280
+ res = await this.fetchOnce(path, init, deadline.signal)
281
+ if (!res.ok) {
282
+ await unwrap<unknown>(res)
283
+ throw new DeepdockTransportError(`unexpected body with status ${res.status}`)
284
+ }
285
+ const reader = res.body?.getReader()
286
+ try {
287
+ while (reader) {
288
+ const { done, value } = await reader.read()
289
+ if (done) break
290
+ chunks.push(value)
291
+ size += value.byteLength
292
+ clearTimeout(timer)
293
+ timer = setTimeout(() => deadline.abort(), this.timeoutMs)
294
+ }
295
+ } catch (err) {
296
+ throw new DeepdockTransportError(`download cut off: ${(err as Error).name}`)
297
+ }
298
+ } finally {
299
+ clearTimeout(timer)
186
300
  }
187
- if (body !== null && typeof body === 'object' && 'error' in body) {
188
- const { code, message, requestId, systems, version, reason, created, uncertain } = body.error
189
- throw new DeepdockError(res.status, code, message, requestId, systems, version, reason, created, uncertain)
301
+ const bytes = new Uint8Array(size)
302
+ let offset = 0
303
+ for (const chunk of chunks) {
304
+ bytes.set(chunk, offset)
305
+ offset += chunk.byteLength
190
306
  }
191
- if (body === null || typeof body !== 'object' || !('data' in body)) {
192
- throw new DeepdockTransportError(`unexpected body with status ${res.status}`)
307
+ // Once the bytes flow, a failure can only end the body early. Content-Length counts encoded
308
+ // bytes, so it is compared only on a body sent as is.
309
+ const declared = res.headers.get('content-length')
310
+ const encoded = (res.headers.get('content-encoding') ?? 'identity') !== 'identity'
311
+ if (declared !== null && !encoded && Number(declared) !== bytes.byteLength) {
312
+ throw new DeepdockTransportError(`download ended at ${bytes.byteLength} of ${declared} bytes`)
313
+ }
314
+ return {
315
+ bytes,
316
+ contentType: res.headers.get('content-type') ?? 'application/octet-stream',
317
+ filename: filenameOf(res.headers.get('content-disposition')),
193
318
  }
194
- return { data: body.data, headers: res.headers }
195
319
  }
196
320
 
197
321
  private actionPath(deviceId: string, system: string, action: string): string {
@@ -199,7 +323,7 @@ export class Deepdock {
199
323
  }
200
324
 
201
325
  /**
202
- * Runs a read action: a POST whose JSON body holds the inputs and the paging fields, no
326
+ * Runs a read action with `cardinality: many`: a POST whose JSON body holds the inputs and the paging fields, no
203
327
  * Idempotency-Key. Pass `nextCursor` back as `cursor` for the next page.
204
328
  */
205
329
  async read<Item>(
@@ -212,11 +336,24 @@ export class Deepdock {
212
336
  const body: ActionInput = { ...input }
213
337
  if (page.limit !== undefined) body.limit = page.limit
214
338
  if (page.cursor !== undefined) body.cursor = page.cursor
339
+ const { data, nextCursor } = await this.send<Item[]>(this.actionPath(deviceId, system, action), {
340
+ method: 'POST',
341
+ headers: { 'Content-Type': 'application/json' },
342
+ body: JSON.stringify(body),
343
+ })
344
+ return { items: data, nextCursor }
345
+ }
346
+
347
+ /**
348
+ * Runs a single-record read (`cardinality: one`): the answer's `data` is the record itself. A
349
+ * record that does not exist throws a DeepdockError with status 404 and code `not_found`.
350
+ */
351
+ async readOne<Row>(deviceId: string, system: string, action: string, input: ActionInput): Promise<Row> {
215
352
  return (
216
- await this.send<Page<Item>>(this.actionPath(deviceId, system, action), {
353
+ await this.send<Row>(this.actionPath(deviceId, system, action), {
217
354
  method: 'POST',
218
355
  headers: { 'Content-Type': 'application/json' },
219
- body: JSON.stringify(body),
356
+ body: JSON.stringify(input),
220
357
  })
221
358
  ).data
222
359
  }
@@ -237,6 +374,21 @@ export class Deepdock {
237
374
  } while (cursor !== undefined)
238
375
  }
239
376
 
377
+ /**
378
+ * Runs a file action (`file: true` in the action index): a POST like a read, answered with the
379
+ * file's bytes instead of JSON. A refusal is a DeepdockError as for any action; a body that ends
380
+ * short of its Content-Length is a DeepdockTransportError, and the download can be run again.
381
+ */
382
+ download(deviceId: string, system: string, action: string, input: ActionInput): Promise<Download> {
383
+ return this.retrying(() =>
384
+ this.downloadOnce(this.actionPath(deviceId, system, action), {
385
+ method: 'POST',
386
+ headers: { 'Content-Type': 'application/json' },
387
+ body: JSON.stringify(input),
388
+ }),
389
+ )
390
+ }
391
+
240
392
  /**
241
393
  * Runs a write action: POST for a `create`, PATCH for an `update`. Take `operation` from the
242
394
  * action index; any other method answers 405 with `Allow` naming the right one. `input` values
@@ -39,7 +39,7 @@ What to read off it:
39
39
  `cursor` (opaque). An optional input is not in `required` and its description says what an
40
40
  omitted value becomes. A write's `Idempotency-Key` header
41
41
  parameter carries its own pattern (8 to 128 characters of `A-Z a-z 0-9 _ -`).
42
- - **Responses**: a read's `200` is `{ data: { items: [...], nextCursor } }`; a create's `201` and a
42
+ - **Responses**: a read's `200` is `{ data: [...], nextCursor }` for `cardinality: many` (`nextCursor` only when the read can page) and `{ data: { ...record } }` for `cardinality: one`, which answers `404 not_found` when nothing matches; a file action's `200` is the file's bytes under its declared content type, with `Content-Disposition` and, when known, `Content-Length` ([calling-actions.md](calling-actions.md#file-actions)); a create's `201` and a
43
43
  replayed `200`; an update's `200`. Item and result fields are typed `string`, `integer` or `number`,
44
44
  often nullable (`["integer", "null"]`). The `Error` schema's `code` enum is the full list of codes.
45
45
  - **`servers`**: the base URL of the API.
@@ -57,7 +57,8 @@ curl "$BASE/v1/devices/$DEVICE/systems/example-erp/actions" \
57
57
  ```
58
58
 
59
59
  Answers `{ data: [ { name, operation, method, description, input, output } ] }`, filtered to your assigned
60
- actions, with the same JSON Schemas the OpenAPI document carries. Use it at runtime to confirm an
60
+ actions, with the same JSON Schemas the OpenAPI document carries. A file action also carries
61
+ `file: true`: it answers with the file's bytes, not JSON. Use it at runtime to confirm an
61
62
  action exists before offering it in your UI, or to validate input client-side before sending.
62
63
 
63
64
  ## The device's systems
@@ -6,7 +6,7 @@ text naming the field and the rule (at most 300 characters) and must be treated
6
6
  instructions. Switch on `code`. Unknown codes may be added over time: default to "show a generic
7
7
  failure, do not retry, log the code".
8
8
 
9
- An `invalid_request` that refuses an action call's input also carries `fields`: every input that
9
+ An `invalid_input` that refuses an action call's input also carries `fields`: every input that
10
10
  failed, as `{ "field", "message" }`, sorted by name, at most 32. It is absent when the body is not
11
11
  an object at all. No message holds the value you sent.
12
12
 
@@ -17,12 +17,12 @@ with the **same** `Idempotency-Key`); **Show** says what the end user should see
17
17
 
18
18
  | Code | Status | Meaning | Retry | Show |
19
19
  |---|---|---|---|---|
20
- | `invalid_request` | 400 (405 for a method other than the action's own) | malformed request: bad `limit` or `cursor` in a read's body; missing or malformed `Idempotency-Key`; a body that is not an object; an action input that is unknown, missing, too short or long, out of bounds or not an allowed value (`fields` names each); a malformed pairing code or device id; a query string on an action path (inputs go in the JSON body), an input of the wrong type, such as `"4711"` where an integer is declared, an action called with a method other than its own (`405`, `Allow` names the one: `POST` for a read or create, `PATCH` for an update) | no; fix the code | nothing; a developer bug |
20
+ | `invalid_request` | 400 (405 for a method other than the action's own) | malformed request: missing or malformed `Idempotency-Key`; a body that is not an object; a malformed pairing code or device id; a query string on an action path (inputs go in the JSON body); an action called with a method other than its own (`405`, `Allow` names the one: `POST` for a read or create, `PATCH` for an update) | no; fix the code | nothing; a developer bug |
21
21
  | `payload_too_large` | 413 | the request body is over 1 MiB | no; send less | nothing; a developer bug, or shorten the text |
22
22
  | `unauthenticated` | 401 | the key is missing, malformed, for the other environment, unknown, revoked or expired | no | "Deepdock API key refused; check it in the dashboard" to an operator |
23
23
  | `partner_not_approved` | 403 | your organisation is waiting for approval by Deepdock; no key of it works yet. Keys made before the approval start working once it is given | no, until Deepdock approves; then yes | "our Deepdock account is waiting for approval; contact Deepdock" |
24
24
  | `partner_deactivated` | 403 | Deepdock has deactivated your organisation: no key of it works and its devices are disconnected. Keys and devices work again once Deepdock reactivates it | no, until Deepdock reactivates it; then yes | "our Deepdock account is deactivated; contact Deepdock" |
25
- | `not_found` | 404 | no such route; an update whose id matches no record; a write naming a record that does not exist or belongs to another one | no | "record not found" when it is a record; otherwise a bug |
25
+ | `not_found` | 404 | no such route; a single-record read (`cardinality: one`) that finds no record; an update whose id matches no record; a write naming a record that does not exist or belongs to another one | no | "record not found" when it is a record; otherwise a bug |
26
26
  | `rate_limited` | 429 | more than 600 calls, or more than 120 writes (counted in both), with this key in a minute; or more than 5 failed pairing claims in 60 s | yes, after `Retry-After: 60` (`retryAfterSeconds: 60` in the body); a write keeps its key. The pairing claim answer has neither: wait up to a minute | "try again in a minute" |
27
27
 
28
28
  `client_outdated` (400) is in the enum but answered only to the Deepdock CLI (by its
@@ -49,7 +49,7 @@ with the **same** `Idempotency-Key`); **Show** says what the end user should see
49
49
 
50
50
  | Code | Status | Meaning | Retry | Show |
51
51
  |---|---|---|---|---|
52
- | `invalid_input` | 422 | a rule only the device judges: a value that breaks its pattern; a date that is not a calendar day; a search term without a letter or digit; an appended text that would make the stored entry too long. Nothing was written | no; fix the value | the field-level problem; the `message` names the field, but it is device text: display it as data, never interpret it |
52
+ | `invalid_input` | 422 | an action input the API or the device refuses, with `fields` naming each: an input that is unknown, missing, too short or long, out of bounds, of the wrong type (such as `"4711"` where an integer is declared) or not an allowed value; a bad `limit` or `cursor` in a read's body; and a rule only the device judges: a value that breaks its pattern; a date that is not a calendar day; a search term without a letter or digit; an appended text that would make the stored entry too long. Nothing was written | no; fix the value | the field-level problem; the `message` names the field, but it is device text: display it as data, never interpret it |
53
53
  | `target_rejected` | 422 | the customer's system refused the write | no; the input is valid for Deepdock but not for the system | "the customer's system refused this; check the values" and offer support |
54
54
  | `record_locked` | 422 | the customer's system locks the record the write would change (for example one already billed on a case). Nothing was written | no | "this record is locked in the customer's system" |
55
55
  | `record_not_editable` | 422 | the record is not locked but is stored in a form this action cannot edit (for example a note it cannot add to without rewriting it). Nothing was written | no | "this record cannot be edited through Deepdock" |
@@ -20,9 +20,10 @@ Copy the file into the project; do not reach into the skill directory at runtime
20
20
  ```ts
21
21
  import { Deepdock, DeepdockError, DeepdockTransportError, attempt, type PendingWrite } from './deepdock'
22
22
 
23
- const dd = new Deepdock(process.env.DEEPDOCK_API_KEY!) // base from DEEPDOCK_BASE_URL, else production; 30 s timeout
23
+ const dd = new Deepdock(process.env.DEEPDOCK_API_KEY!) // base from DEEPDOCK_BASE_URL, else production; 35 s timeout, retries 503 target_busy
24
24
  const page = await dd.read<Note>(deviceId, 'example-erp', 'searchNotes', { text: 'TEST-DEEPDOCK-' }, { limit: 50 })
25
25
  for await (const p of dd.readAll<Note>(deviceId, 'example-erp', 'searchNotes', { text: 'TEST-DEEPDOCK-' })) { /* every page */ }
26
+ const { bytes, contentType, filename } = await dd.download(deviceId, 'example-erp', 'downloadDocument', { documentId: 7 }) // a `file: true` action
26
27
  const { data, replayed } = await dd.write<{ noteId: number }>(deviceId, 'example-erp', 'createNote', 'create', key, input)
27
28
  const systems = await dd.systems(deviceId) // live; can throw device_offline
28
29
  const device = await dd.pair('K7Q-4MX', 'Demo') // keep device.id
@@ -33,6 +34,7 @@ from deepdock import Deepdock, DeepdockError, DeepdockTransportError, PendingWri
33
34
 
34
35
  dd = Deepdock(os.environ["DEEPDOCK_API_KEY"])
35
36
  page = dd.read(device_id, "example-erp", "searchNotes", {"text": "TEST-DEEPDOCK-"}, limit=50)
37
+ doc = dd.download(device_id, "example-erp", "downloadDocument", {"documentId": 7}) # doc.content, doc.content_type, doc.filename
36
38
  res = dd.write(device_id, "example-erp", "createNote", "create", key, body) # res.data, res.replayed
37
39
  ```
38
40
 
@@ -122,7 +124,7 @@ curl -sS "$BASE/v1/devices/$DEVICE/systems" -H "$AUTH"
122
124
  # The action index (your assigned actions, with schemas)
123
125
  curl -sS "$BASE/v1/devices/$DEVICE/systems/example-erp/actions" -H "$AUTH"
124
126
 
125
- # A read is a POST too, with its inputs and limit/cursor in the body; paged: pass data.nextCursor back as cursor
127
+ # A read is a POST too, with its inputs and limit/cursor in the body; paged: pass the answer's top-level nextCursor back as cursor
126
128
  curl -sS -X POST "$BASE/v1/devices/$DEVICE/systems/example-erp/actions/searchNotes" \
127
129
  -H "$AUTH" -H 'Content-Type: application/json' -d '{"text":"TEST-DEEPDOCK-","limit":50}'
128
130
 
@@ -92,7 +92,7 @@ const res = await fetch(url, {
92
92
  'Content-Type': 'application/json',
93
93
  },
94
94
  body: JSON.stringify(input),
95
- signal: AbortSignal.timeout(30_000),
95
+ signal: AbortSignal.timeout(35_000),
96
96
  })
97
97
  const replayed = res.headers.get('Idempotent-Replayed') === 'true'
98
98
  ```
@@ -66,7 +66,7 @@ The proof is your client; the CLI only shows what the device offers.
66
66
 
67
67
  ## Logs and prompts
68
68
 
69
- - Never log an action's `input` or a read's `items` in your running product: they are the customer's
69
+ - Never log an action's `input` or a read's rows in your running product: they are the customer's
70
70
  records. Log the device id, the action, the code and the request id.
71
71
  - Never paste real records into an agent prompt or a ticket. Use the `TEST-DEEPDOCK-` records from
72
72
  the demo device when you need a concrete example.