@deepdockai/cli 1.1.2 → 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,12 @@
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
+
3
10
  ## 1.1.2
4
11
 
5
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`.
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.2";
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.2",
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,7 +139,7 @@ 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
 
@@ -8,15 +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
11
12
  import time
12
13
  from dataclasses import dataclass, field, replace
13
- from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
14
- 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
15
16
 
16
17
  import httpx
17
18
 
18
19
  # A flat JSON value as the action's schema declares it: a number is a number, never its text.
19
20
  InputValue = Union[str, int, float, bool]
21
+ T = TypeVar("T")
20
22
 
21
23
 
22
24
  class DeepdockError(Exception):
@@ -66,6 +68,45 @@ class WriteResult:
66
68
  replayed: bool
67
69
 
68
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
+
69
110
  class Deepdock:
70
111
  def __init__(self, api_key: str, base: Optional[str] = None, timeout: float = 35.0,
71
112
  client: Optional[httpx.Client] = None, max_attempts: int = 3, sleep=time.sleep):
@@ -80,35 +121,44 @@ class Deepdock:
80
121
  self.c = client or httpx.Client(base_url=base.rstrip("/"), timeout=timeout)
81
122
  self.c.headers["Authorization"] = f"Bearer {api_key}"
82
123
 
83
- def _send(self, method: str, path: str, **kw: Any) -> Tuple[Any, httpx.Headers]:
124
+ def _retrying(self, once: Callable[[], T]) -> T:
84
125
  attempt = 1
85
126
  while True:
86
127
  try:
87
- return self._send_once(method, path, **kw)
128
+ return once()
88
129
  except DeepdockError as e:
89
130
  if attempt >= self.max_attempts or e.status != 503 or e.code != "target_busy":
90
131
  raise
91
132
  self._sleep(_retry_wait(e.retry_after))
92
133
  attempt += 1
93
134
 
94
- def _send_once(self, method: str, path: str, **kw: Any) -> Tuple[Any, httpx.Headers]:
135
+ def _request(self, method: str, path: str, **kw: Any) -> httpx.Response:
95
136
  try:
96
- r = self.c.request(method, path, **kw)
97
- 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
98
139
  raise DeepdockTransportError(f"no answer from Deepdock: {type(e).__name__}") from e
99
- try:
100
- body = r.json()
101
- except ValueError:
102
- raise DeepdockTransportError(f"non-JSON answer with status {r.status_code}")
103
- if isinstance(body, dict) and "error" in body:
104
- e = body["error"]
105
- err = DeepdockError(r.status_code, e["code"], e["message"], e.get("requestId"), e.get("systems"),
106
- e.get("version"), e.get("reason"), e.get("created"), e.get("uncertain"))
107
- err.retry_after = r.headers.get("retry-after")
108
- raise err
109
- 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)
110
152
  raise DeepdockTransportError(f"unexpected body with status {r.status_code}")
111
- 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")))
112
162
 
113
163
  @staticmethod
114
164
  def _action_path(device_id: str, system: str, action: str) -> str:
@@ -116,15 +166,21 @@ class Deepdock:
116
166
 
117
167
  def read(self, device_id: str, system: str, action: str, params: Dict[str, InputValue],
118
168
  limit: Optional[int] = None, cursor: Optional[str] = None) -> Page:
119
- """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
120
170
  Idempotency-Key. Pass `next_cursor` back as `cursor` for the next page."""
121
171
  body: Dict[str, InputValue] = dict(params)
122
172
  if limit is not None:
123
173
  body["limit"] = limit
124
174
  if cursor is not None:
125
175
  body["cursor"] = cursor
126
- data, _ = self._send("POST", self._action_path(device_id, system, action), json=body)
127
- 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
128
184
 
129
185
  def read_all(self, device_id: str, system: str, action: str, params: Dict[str, InputValue],
130
186
  limit: Optional[int] = None) -> Iterator[Dict[str, Any]]:
@@ -137,6 +193,13 @@ class Deepdock:
137
193
  return
138
194
  cursor = page.next_cursor
139
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
+
140
203
  def write(self, device_id: str, system: str, action: str, operation: str, idempotency_key: str,
141
204
  body: Dict[str, InputValue]) -> WriteResult:
142
205
  """Runs a write action: POST for operation "create", PATCH for "update" (from the action index; any
@@ -144,14 +207,14 @@ class Deepdock:
144
207
  action's schema declares. Any other `operation` raises ValueError before anything is sent."""
145
208
  if operation not in ("create", "update"):
146
209
  raise ValueError(f"operation must be 'create' or 'update', got {operation!r}")
147
- data, headers = self._send("PATCH" if operation == "update" else "POST",
210
+ data, headers, _ = self._send("PATCH" if operation == "update" else "POST",
148
211
  self._action_path(device_id, system, action), json=body,
149
212
  headers={"Idempotency-Key": idempotency_key})
150
213
  return WriteResult(data=data, replayed=headers.get("Idempotent-Replayed") == "true")
151
214
 
152
215
  def systems(self, device_id: str) -> List[Dict[str, Any]]:
153
216
  """The device's systems and each action's state. A live call: can answer device_offline."""
154
- 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")
155
218
  return data
156
219
 
157
220
  def pair(self, code: str, label: Optional[str] = None) -> Dict[str, Any]:
@@ -159,7 +222,7 @@ class Deepdock:
159
222
  body: Dict[str, str] = {"code": code}
160
223
  if label is not None:
161
224
  body["label"] = label
162
- data, _ = self._send("POST", "/v1/devices", json=body)
225
+ data, _, _ = self._send("POST", "/v1/devices", json=body)
163
226
  return data
164
227
 
165
228
  def release(self, device_id: str) -> None:
@@ -53,8 +53,9 @@ export class DeepdockTransportError extends Error {
53
53
  }
54
54
 
55
55
  type ErrorBody = { code: string; message: string; requestId?: string; systems?: string[]; version?: string | null; reason?: string; created?: { chartId?: string } | null; uncertain?: boolean }
56
- type Envelope<T> = { data: T } | { error: ErrorBody }
56
+ type Envelope<T> = { data: T; nextCursor?: string | null } | { error: ErrorBody }
57
57
 
58
+ /** One page of a `many` read: `items` is the answer's `data` array, `nextCursor` its top-level sibling. */
58
59
  export type Page<Item> = { items: Item[]; nextCursor: string | null }
59
60
  export type WriteResult<T> = { data: T; replayed: boolean }
60
61
  /** A flat JSON value as the action's schema declares it: a number is a number, never its text. */
@@ -142,6 +143,45 @@ export type DeepdockOptions = {
142
143
  sleep?: (ms: number) => Promise<void>
143
144
  }
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
+
145
185
  /** Longest wait between two attempts, whatever `Retry-After` asks for. */
146
186
  const MAX_RETRY_WAIT_MS = 15_000
147
187
  const DEFAULT_RETRY_WAIT_MS = 1_000
@@ -189,13 +229,10 @@ export class Deepdock {
189
229
  this.sleep = sleep
190
230
  }
191
231
 
192
- private async send<T>(
193
- path: string,
194
- init: { method: string; headers?: Record<string, string>; body?: string },
195
- ): Promise<{ data: T; headers: Headers }> {
232
+ private async retrying<R>(once: () => Promise<R>): Promise<R> {
196
233
  for (let attempt = 1; ; attempt++) {
197
234
  try {
198
- return await this.sendOnce<T>(path, init)
235
+ return await once()
199
236
  } catch (err) {
200
237
  if (
201
238
  attempt >= this.maxAttempts ||
@@ -210,38 +247,75 @@ export class Deepdock {
210
247
  }
211
248
  }
212
249
 
213
- private async sendOnce<T>(
214
- path: string,
215
- init: { method: string; headers?: Record<string, string>; body?: string },
216
- ): Promise<{ data: T; headers: Headers }> {
217
- let res: Response
250
+ private async fetchOnce(path: string, init: SendInit, signal: AbortSignal): Promise<Response> {
218
251
  try {
219
- res = await this.fetchImpl(`${this.base}${path}`, {
252
+ return await this.fetchImpl(`${this.base}${path}`, {
220
253
  method: init.method,
221
254
  headers: { Authorization: `Bearer ${this.apiKey}`, ...init.headers },
222
255
  body: init.body,
223
- signal: AbortSignal.timeout(this.timeoutMs),
256
+ signal,
224
257
  })
225
258
  } catch (err) {
226
259
  // TimeoutError from AbortSignal.timeout, AbortError, or a network TypeError.
227
260
  throw new DeepdockTransportError(`no answer from Deepdock: ${(err as Error).name}`)
228
261
  }
229
- 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
230
279
  try {
231
- body = (await res.json()) as Envelope<T>
232
- } catch {
233
- 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)
300
+ }
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
234
306
  }
235
- if (body !== null && typeof body === 'object' && 'error' in body) {
236
- const { code, message, requestId, systems, version, reason, created, uncertain } = body.error
237
- const error = new DeepdockError(res.status, code, message, requestId, systems, version, reason, created, uncertain)
238
- error.retryAfter = res.headers.get('retry-after') ?? undefined
239
- throw error
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`)
240
313
  }
241
- if (body === null || typeof body !== 'object' || !('data' in body)) {
242
- throw new DeepdockTransportError(`unexpected body with status ${res.status}`)
314
+ return {
315
+ bytes,
316
+ contentType: res.headers.get('content-type') ?? 'application/octet-stream',
317
+ filename: filenameOf(res.headers.get('content-disposition')),
243
318
  }
244
- return { data: body.data, headers: res.headers }
245
319
  }
246
320
 
247
321
  private actionPath(deviceId: string, system: string, action: string): string {
@@ -249,7 +323,7 @@ export class Deepdock {
249
323
  }
250
324
 
251
325
  /**
252
- * 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
253
327
  * Idempotency-Key. Pass `nextCursor` back as `cursor` for the next page.
254
328
  */
255
329
  async read<Item>(
@@ -262,11 +336,24 @@ export class Deepdock {
262
336
  const body: ActionInput = { ...input }
263
337
  if (page.limit !== undefined) body.limit = page.limit
264
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> {
265
352
  return (
266
- await this.send<Page<Item>>(this.actionPath(deviceId, system, action), {
353
+ await this.send<Row>(this.actionPath(deviceId, system, action), {
267
354
  method: 'POST',
268
355
  headers: { 'Content-Type': 'application/json' },
269
- body: JSON.stringify(body),
356
+ body: JSON.stringify(input),
270
357
  })
271
358
  ).data
272
359
  }
@@ -287,6 +374,21 @@ export class Deepdock {
287
374
  } while (cursor !== undefined)
288
375
  }
289
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
+
290
392
  /**
291
393
  * Runs a write action: POST for a `create`, PATCH for an `update`. Take `operation` from the
292
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" |
@@ -23,6 +23,7 @@ import { Deepdock, DeepdockError, DeepdockTransportError, attempt, type PendingW
23
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
 
@@ -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.