@esp-vision/device-core 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,48 @@
1
+ # Changelog
2
+
3
+ ## Unreleased
4
+
5
+ ### Added
6
+
7
+ - Default official firmware discovery reads dl.espressif.com config and per-version metadata; legacy unqualified releases remain visible without enabling unsafe writes. CLI uses --port and a built-in esptool process adapter, removing the user-supplied JavaScript loader requirement.
8
+
9
+ - Ship `esp-vision-device` management CLI: unified `inspect` passive/probed wired/LAN queries matching the SDK method name, platform-aware USB serial filtering with `--all-ports` for native UART/Bluetooth, numbered/grouped endpoints, strict configuration/control and catalog/version firmware commands. Reuse Core facade and one cross-platform Python serial/TCP adapter in both CLI and hardware checks.
10
+
11
+ - Added `device.firmware.check()` and `device.firmware.update()` for complete board-version listing, exact-version selection, ordered release catalogs, board selection, validated application download, exclusive ROM handoff, readback verification and explicit reset/reconnection results.
12
+ - Publish bilingual complete API documentation in the ESP-VISION documentation center from repository `docs/{en,zh_CN}/device-core/`; the npm README links to its online HTML pages.
13
+
14
+ ### Changed
15
+
16
+ - License the npm package and ESP-VISION contributions under Apache-2.0, matching the firmware; retain historical MIT copyright/permission notices in the distributed NOTICE file.
17
+
18
+ - Moved the SDK source and release checks from the IDE repository to `host/device-core` in the ESP-VISION firmware repository; npm name and independently versioned package contract are unchanged.
19
+
20
+ - **Breaking:** the package root exports only `createDevice()`; the device class stays internal. Use the grouped application API for discovery, connection, inspection, configuration, control, Python, files, capture and events. Existing protocol, action-contract and ROM-flashing integrations remain on their explicit subpaths; the README includes a migration table.
21
+ - Consolidated network mutations into `configure()` and reset/interrupt/download-mode requests into `control()`, with strict parameters, cancellation and shared-operation coordination.
22
+ - Unified file access under `files` and execution under `python`, with acknowledged upload progress, directory-scoped enumeration and execution of existing paths without rewriting their contents.
23
+
24
+ ### Fixed
25
+
26
+ - Align discovery output by Unicode display width instead of tabs; fall back to aligned, wrapped device blocks on narrow terminals without truncating identifiers.
27
+
28
+ - Generate script completion inside the executing statement so `input()` receives only user input; retain output arriving in the same frame as completion.
29
+ - Return binary image results correlated to the requesting sequence instead of a shared last-image slot. LCD capture uses the dedicated `debug.capture_screen` capability and never falls back to the camera; this refactor does not implement the planned high-throughput binary firmware protocol.
30
+ - Clean up subscriptions, pending work and transports on connection failure or session loss, and isolate event-listener exceptions from protocol delivery.
31
+
32
+ ## 0.1.0 — Initial public release
33
+
34
+ ### Added
35
+
36
+ - Added browser-safe and optional Node LAN discovery interfaces, TTL-aware DNS-SD collection, and selection-time device identity validation before EV-MUX acquisition.
37
+
38
+ - Standalone, UI-independent EV-MUX v4 sessions, strict ownership/epoch filtering, framed REPL, files, execution, Wi-Fi controls and device-action contracts.
39
+ - Verified firmware-flash adapter with injected ROM loader, image/security/partition checks, complete readback and masked P4 download-latch reset.
40
+ - Public npm metadata, protected default-branch publishing, isolated tarball checks and verified/idempotent release retries. The package has no Agent/IDE runtime dependency or bundle; the official firmware index uses a small TOML parser, and Node discovery optionally uses multicast-dns.
41
+
42
+ ### Fixed
43
+
44
+ - Preserve split mDNS address announcements during cache flush, reclaim expired cache entries, bound packet retention, and close discovery sockets when cancellation occurs during setup.
45
+ - Soft reset requires a newer ready epoch and a real REPL barrier within one deadline; caller cancellation reaches all stages and device-action adapters.
46
+ - Bounded file reads reject incomplete/changing content; serial startup drain, TCP frame deadlines and keepalive recovery follow the v4 contract.
47
+
48
+ The earlier v3 extraction existed only inside repository development history; it was not an npm release of this package. Version 0.1.0 is the first public v4-only package.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,32 @@
1
+ ESP-VISION Device Core
2
+ Copyright 2026 Espressif Systems (Shanghai) CO LTD
3
+
4
+ The package as a whole and ESP-VISION contributions are distributed under
5
+ the Apache License, Version 2.0. See LICENSE.
6
+
7
+ The following notices are retained from the Device Core source migrated
8
+ from ESP-VISION-IDE for previously MIT-licensed and upstream-derived portions.
9
+ Third-party dependencies retain their respective licenses.
10
+
11
+ MIT License
12
+
13
+ Copyright (c) 2026 ESP-VISION-IDE contributors
14
+ Copyright (c) 2024 Volodymyr Shymanskyy
15
+
16
+ Permission is hereby granted, free of charge, to any person obtaining a copy
17
+ of this software and associated documentation files (the "Software"), to deal
18
+ in the Software without restriction, including without limitation the rights
19
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
20
+ copies of the Software, and to permit persons to whom the Software is
21
+ furnished to do so, subject to the following conditions:
22
+
23
+ The above copyright notice and this permission notice shall be included in all
24
+ copies or substantial portions of the Software.
25
+
26
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
29
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
30
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
31
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
32
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,310 @@
1
- # Temporary Holding Version
1
+ # ESP Vision Device Core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [ESP-VISION](https://vision.espressif.com/) is Espressif's low-code edge AI and computer-vision framework for ESP32 boards. MicroPython APIs cover camera capture, image processing, inference and display on the device; browser flashing and the Web IDE provide the host development workflow. Device Core is its reusable, UI-independent host communication library.
4
+
5
+ - Project GitHub: [espressif/esp-vision](https://github.com/espressif/esp-vision)
6
+ - Official website: [vision.espressif.com](https://vision.espressif.com/)
7
+ - Web IDE: [ide.vision.espressif.com](https://ide.vision.espressif.com/)
8
+ - Firmware documentation: [ESP-VISION programming guide](https://docs.espressif.com/projects/esp-vision/en/latest/)
9
+
10
+ ## Package identity and installation
11
+
12
+ | Item | Value |
13
+ | --- | --- |
14
+ | Published name | `@esp-vision/device-core` |
15
+ | First public version | `0.1.0`, EV-MUX v4 only |
16
+ | Registry | `https://registry.npmjs.org/` |
17
+ | Package page | [npm: @esp-vision/device-core](https://www.npmjs.com/package/@esp-vision/device-core) |
18
+ | Publishing account | [`esp-vision`](https://www.npmjs.com/~esp-vision) |
19
+ | Visibility | Public; installation needs no npm login |
20
+ | Source location | `host/device-core` in the ESP-VISION firmware repository |
21
+
22
+ The npm page and installation become available only after the first publication succeeds. CI authenticates with the protected `NPM_PUBLISH_TOKEN` and verifies that `npm whoami` returns `esp-vision` before publishing. Tokens are not part of this package or its documentation.
23
+
24
+ ```sh
25
+ npm install --save-exact @esp-vision/device-core@0.1.0 --registry=https://registry.npmjs.org/
26
+ ```
27
+
28
+ EV-MUX v4 firmware is required. A v3 hello is rejected with `VERSION_MISMATCH`; applications should ask the user to update firmware. Core has no runtime dependency on the IDE, Agent, DOM or Node serial libraries. The host supplies the physical byte transport and discovery adapter; Core owns protocol parsing, session negotiation, REPL coordination and device operations.
29
+
30
+ ## Documentation
31
+
32
+ Read the Device Core guide in the **ESP-VISION Documentation Center**: [English](https://docs.espressif.com/projects/esp-vision/en/latest/esp32p4/device-core/index.html) | [简体中文](https://docs.espressif.com/projects/esp-vision/zh_CN/latest/esp32p4/device-core/index.html).
33
+
34
+ - [All application APIs](https://docs.espressif.com/projects/esp-vision/en/latest/esp32p4/device-core/api.html), including firmware version checks and updates.
35
+ - [Advanced exports](https://docs.espressif.com/projects/esp-vision/en/latest/esp32p4/device-core/advanced.html) and [TCP/Web Serial integration](https://docs.espressif.com/projects/esp-vision/en/latest/esp32p4/device-core/integration.html).
36
+
37
+ Documentation source lives in this repository under `docs/en/device-core/` and `docs/zh_CN/device-core/` and changes alongside SDK APIs in the same MR. The documentation site renders the RST as HTML; it does not redirect readers to npm or require downloading documentation. The npm package contains the runtime library and this README, not a second RST documentation distribution. Use the documentation center's version selector when reading a published firmware/documentation version; `latest` follows the current development documentation. These new chapter links become available after the corresponding documentation is deployed.
38
+
39
+ ## Management CLI
40
+
41
+ The npm package installs `esp-vision-device`. `inspect` combines passive wired/LAN enumeration and targeted queries. By default it lists USB serial candidates; `--all-ports` also includes native UART/Bluetooth ports. Explicit `--port` bypasses discovery filtering; `configure`, `control`, and `firmware check/update` cover management. See the [CLI guide](https://docs.espressif.com/projects/esp-vision/en/latest/esp32p4/device-core/cli.html) ([中文](https://docs.espressif.com/projects/esp-vision/zh_CN/latest/esp32p4/device-core/cli.html)).
42
+
43
+ ```sh
44
+ npm install -g @esp-vision/device-core@0.1.0
45
+ esp-vision-device inspect
46
+ esp-vision-device inspect --all-ports
47
+ esp-vision-device inspect --interface usj,usb --probe --json
48
+ esp-vision-device inspect --port COM3 --fields identity,capabilities
49
+ esp-vision-device inspect --tcp 192.168.1.100:3232 --fields network,storage --json
50
+ ```
51
+
52
+ Wired access/enumeration requires Python with pyserial (`--python` overrides the interpreter); LAN discovery uses optional `multicast-dns`, normally installed by npm. Windows/Linux/macOS paths are accepted. Passive enumeration never opens a serial port; `--probe` and targeted queries acquire a session and may interrupt Python. Unidentified ports, ROM candidates and USB-to-UART adapters remain numbered and visible. Board names are unknown until firmware identification; USB descriptors are hints only. Firmware versions are fetched automatically from dl.espressif.com. Firmware flashing uses the built-in serial adapter with separately installed Python esptool>=5.3,<6; no user loader module is required. Historical releases without qualified update metadata remain listed but cannot be installed by this flow. Installation becomes available after first npm publication.
53
+
54
+ ## Public device API
55
+
56
+ Import `createDevice` from the package root. Application code uses one device interface rather than constructing parsers, a REPL and a session separately.
57
+
58
+ | Area | Method | Responsibility |
59
+ | --- | --- | --- |
60
+ | Discovery | `discover(options)` | List LAN advertisements without acquiring devices |
61
+ | Connection | `connect(options)`, `disconnect()` | Negotiate/release an EV-MUX session and manage the injected transport |
62
+ | Query | `inspect({ fields })` | Read identity, capabilities, runtime, network and storage state |
63
+ | Configuration | `configure({ network })` | Change Wi-Fi credentials and enabled state |
64
+ | Control | `control({ action, mode })` | Stop Python, reset or enter the ROM downloader |
65
+ | Interactive Python | `python.input(data)` | Send terminal input without uploading a file |
66
+ | Python execution | `python.execute({ source, path, completion })` | Execute source or a device-side script |
67
+ | Files | `files.list/read/write/remove/mkdir(request)` | File and directory operations, with one object argument |
68
+ | Firmware | `firmware.check(request)`, `firmware.update(request)` | List board firmware versions, select an exact version and perform verified ROM application updates |
69
+ | Capture | `capture({ source, format, quality })` | Capture an image from a supported source |
70
+ | Events | `on(event, handler)` | Subscribe; returns an unsubscribe function |
71
+
72
+ Configuration and control are deliberately separate: configuration changes persistent settings, while control requests an immediate action. File upload never implicitly starts Python execution.
73
+
74
+ ### Transport and connection
75
+
76
+ The host owns serial/TCP/WebSocket details and implements this byte transport contract:
77
+
78
+ ```js
79
+ const transport = {
80
+ async writeBytes(bytes) {
81
+ // Resolve only after all bytes are accepted; reject on failure.
82
+ await byteConnection.write(bytes);
83
+ },
84
+ subscribe({ data, error, close }) {
85
+ // Forward received Uint8Array data and link errors/closure.
86
+ // Return a synchronous unsubscribe function; do not make this async.
87
+ return byteConnection.subscribe({ data, error, close });
88
+ },
89
+ async connect({ signal }) { await byteConnection.open({ signal }); }, // Optional.
90
+ async disconnect() { await byteConnection.close(); }, // Optional.
91
+ };
92
+ ```
93
+
94
+ `byteConnection` above represents your host adapter, not a Core class. Core subscribes before opening the connection or sending handshake bytes. If the host opens the connection itself, omit `connect()` and pass the open adapter. A closed connection terminates pending work; unsubscribe prevents further input from an old connection.
95
+
96
+ ```js
97
+ import { createDevice } from '@esp-vision/device-core';
98
+
99
+ const device = createDevice({ transport });
100
+ const unsubscribeOutput = device.on('python.output', text => console.log(text));
101
+ const unsubscribeState = device.on('state', state => console.log(state));
102
+ try {
103
+ await device.connect({ role: 'usj' }); // 'usb', 'uart' or 'tcp' on other links.
104
+ console.log(await device.inspect({ fields: ['identity', 'capabilities'] }));
105
+ console.log(await device.python.execute({ source: 'print(1)', completion: 'wait' }));
106
+ } finally {
107
+ await device.disconnect();
108
+ unsubscribeOutput();
109
+ unsubscribeState();
110
+ }
111
+ ```
112
+
113
+ A discovery-only instance can receive a transport later:
114
+
115
+ ```js
116
+ const [selected] = await device.discover({ timeout: 3000 });
117
+ await device.connect({ transport: tcpAdapter, role: 'tcp', expectedDevice: selected });
118
+ ```
119
+
120
+ Opening `tcpAdapter` from the selected address/bridge URL remains the host's responsibility. Supported query fields are `identity`, `capabilities`, `runtime`, `network` and `storage`. The default is identity/capabilities/runtime; `inspect` reads only the requested fields and does not change configuration. Network/storage queries require the corresponding firmware capabilities. `connect()` returns that default inspection result after negotiation.
121
+
122
+ ### Events
123
+
124
+ `on(name, handler)` returns an unsubscribe function. Register output handlers before connecting if you need to see startup output.
125
+
126
+ | Event | Payload |
127
+ | --- | --- |
128
+ | `python.output` | A string containing Python stdout/stderr text or interactive REPL prompts |
129
+ | `raw` | A string containing text outside EV-MUX framing |
130
+ | `log` | A string containing firmware diagnostic log text |
131
+ | `preview` | `{ data: Uint8Array, mimeType: 'image/jpeg', metadata }` |
132
+ | `state` | `{ state, identity?, reason? }`, including `connecting`, `ready` and `disconnected` |
133
+ | `diagnostic` | An object with `event` and diagnostic details; includes `rpc.request`, `rpc.response`, `rpc.timeout` |
134
+ | `rpc` | An inbound RPC object `{ channel, metadata, payload }` |
135
+
136
+ Preview frames are delivered as events, while `capture()` returns the requested one-shot image. Diagnostic event payloads are for troubleshooting, not a replacement for query/configuration methods. Network credentials are redacted from RPC diagnostics; applications should still avoid logging their own configuration requests. A throwing event listener cannot interrupt parser delivery or other listeners.
137
+
138
+ ### Configuration and control
139
+
140
+ Network configuration uses a partial update: an omitted property stays unchanged. `credentials: null` clears saved credentials and disables networking. Combining it with `enabled: true` is rejected. Supplying credentials requires both `ssid` and `password`; use an empty password for an open network.
141
+
142
+ ```js
143
+ await device.configure({
144
+ network: {
145
+ enabled: true,
146
+ credentials: { ssid: 'example', password: 'secret' },
147
+ },
148
+ });
149
+ await device.configure({ network: { enabled: false }, timeout: 45000 }); // Keep credentials.
150
+ await device.configure({ network: { credentials: null } });
151
+
152
+ await device.control({ action: 'stop' });
153
+ await device.control({ action: 'reset', mode: 'soft' });
154
+ await device.control({ action: 'reset', mode: 'hard' });
155
+ await device.control({ action: 'bootloader' });
156
+ ```
157
+
158
+ A combined configuration request is applied in sequence, not as a transaction. If it fails, `error.completed` describes acknowledged changes and `error.pending` identifies an unfinished operation; Core does not roll settings back. Pass `timeout` and `signal` in the same request object as `network`/`action`, not as a second options argument. Configuration timeout is the budget for the combined operation. Wi-Fi changes may disconnect a TCP connection. Hard reset and entering the downloader can also remove USB interfaces; reconnect through the host transport after the device returns. A successful reset request does not guarantee that the rebooted firmware is already online. Configuration does not return saved Wi-Fi passwords.
159
+
160
+ ### Interactive Python and scripts
161
+
162
+ ```js
163
+ const unsubscribe = device.on('python.output', text => terminal.write(text));
164
+ await device.python.input('print(1)\r');
165
+ await device.control({ action: 'stop' }); // Ctrl-C / stop.
166
+
167
+ const result = await device.python.execute({
168
+ source: 'print(1)',
169
+ completion: 'wait',
170
+ });
171
+ await device.python.execute({ path: '/main.py', completion: 'start' });
172
+ unsubscribe();
173
+ ```
174
+
175
+ `source` and `path` are mutually exclusive. `completion: 'wait'` (the default) returns `{ ok, path, output, outputTruncated }` after the program finishes. `'start'` returns `{ ok, path, done }` after starting it; await `done` for the execution result. Source started this way uses an internal temporary script that Core removes after execution. Terminal input, scripts and filesystem helpers share one MicroPython interpreter. The application should not send terminal input while an automated operation owns the REPL. Conflicting automated operations reject with `DEVICE_BUSY`; Core does not silently queue them or isolate user Python in a second interpreter. Terminal input remains available to an explicitly started interactive script.
176
+
177
+ ### Files and images
178
+
179
+ ```js
180
+ await device.files.mkdir({ path: '/models' });
181
+ await device.files.write({
182
+ path: '/models/model.espdl',
183
+ data: modelBytes, // Uint8Array; strings are UTF-8.
184
+ overwrite: true,
185
+ signal: abortController.signal,
186
+ onProgress: progress => console.log(progress),
187
+ });
188
+ const bytes = await device.files.read({ path: '/models/model.espdl' });
189
+ const entries = await device.files.list({ path: '/' });
190
+ await device.files.remove({ path: '/models/model.espdl' });
191
+
192
+ const image = await device.capture({ source: 'camera', format: 'jpeg', timeout: 15000 });
193
+ // image: { data: Uint8Array, mimeType: 'image/jpeg', metadata }
194
+ ```
195
+
196
+ Paths are absolute device paths. `files.list({ path: '/', recursive: false })` returns entries `{ name, path, type, size }`. `files.read({ path })` returns a `Uint8Array`; use `encoding: 'utf-8'` to return text, and `maxBytes` to bound a read. Writes default to `overwrite: true`; set it to `false` to require a new destination. Uploading and executing are separate operations; create an empty file with `files.write({ path, data: new Uint8Array() })` rather than a second touch API. Remove an empty directory with `files.remove({ path: '/models', type: 'directory' })`; there is no implicit recursive deletion. `files.mkdir({ path, recursive: true })` creates missing parents.
197
+
198
+ **Current firmware limits:** file upload still uses the existing `script.write` chunked RPC, including Base64/JSON overhead. This API cleanup does not implement the proposed high-throughput raw binary protocol or promise improved model-upload throughput. The filesystem must be mounted and allow writing, with room for the temporary upload and any existing destination file. File reads and directory operations currently use the REPL.
199
+
200
+ `capture({ source: 'screen', format: 'jpeg' })` uses the dedicated `debug.capture_screen` RPC to encode the LCD's last submitted RGB565 framebuffer, including the display's scaling and letterboxing. It does not read the panel electronics or capture the camera. Camera capture uses `debug.capture_frame`. Both return binary JPEG responses correlated to the request; optional `quality` is an integer from 1 to 100. Missing firmware capabilities reject with `UNSUPPORTED_OPERATION`; an uninitialized display returns `DISPLAY_NOT_READY`, and a board without an LCD returns `NOT_SUPPORTED`. Preview is a separate real-time stream and may drop frames under congestion.
201
+
202
+ ## Discovery and transport adapters
203
+
204
+ Firmware advertises `_esp-vision._tcp.local` with the main-chip device ID, full board name, firmware version, canonical hostname and EV-MUX version. The hostname is `esp-vision-<full-board-name>-<last-6-mac-hex>-<firmware-version>`; all transport queries return the same name. Discovery does not open a device TCP socket or acquire ownership. Occupancy is established during connection.
205
+
206
+ Node discovery uses the optional `multicast-dns` peer:
207
+
208
+ ```js
209
+ // npm install multicast-dns
210
+ import { createDevice } from '@esp-vision/device-core';
211
+ import { createNodeDiscovery } from '@esp-vision/device-core/discovery/node';
212
+
213
+ const device = createDevice({ discovery: createNodeDiscovery() });
214
+ const devices = await device.discover({ timeout: 3000 });
215
+ ```
216
+
217
+ Browser discovery uses an HTTP endpoint on a local bridge:
218
+
219
+ ```js
220
+ import { createDevice } from '@esp-vision/device-core';
221
+ import { createBridgeDiscovery } from '@esp-vision/device-core/discovery';
222
+
223
+ const device = createDevice({
224
+ discovery: createBridgeDiscovery('ws://127.0.0.1:8766/device'),
225
+ });
226
+ const devices = await device.discover({ timeout: 3000 });
227
+ ```
228
+
229
+ Results contain `deviceId`, `hostname` (without `.local`), `board`, `firmwareVersion`, `evMuxVersion`, `compatible`, `addresses`, `port`, and adapter-specific `expiresAt`/`connectionUrl`. Supply the selected result as `expectedDevice` when connecting: Core checks the stable ID and hostname before acquisition, protecting against stale DHCP addresses. This is identity matching, not authentication. Refresh expired bridge handles. Multicast filtering, VLANs and client isolation may require a manual address. Browsers have no native DNS-SD enumeration API; local-network permission does not remove the bridge requirement.
230
+
231
+ The root/browser entry points do not import Node networking modules. The optional Node discovery subpath dynamically loads `multicast-dns`. No Agent package is required.
232
+
233
+ ## Migration from the session API
234
+
235
+ This is the API boundary for the first public v4 release. The package root exports only `createDevice()`. The `Device` class is an internal implementation detail. Legacy implementation classes are not exported there. Protocol adapters and existing integrations can use explicit subpaths such as `/session`, `/evmux`, `/evrepl`, `/actions` and `/bindings` while migrating; new application code should use `createDevice`.
236
+
237
+ | Previous application call | Device API |
238
+ | --- | --- |
239
+ | Construct `DeviceSession` with `EvMuxParser`, `EvRepl`, `makeEvMuxFrame` | `createDevice({ transport, discovery })` |
240
+ | `NetworkDiscovery.list()` | `device.discover(options)` with an injected discovery provider |
241
+ | `negotiate()`, `release()`, `close()` | `connect()`, `disconnect()` |
242
+ | `snapshot()`, `hasFeature()`, `networkStatus()`, REPL information helpers | `inspect({ fields })` |
243
+ | `configureNetwork()`, `setNetworkEnabled()`, `forgetNetwork()` | `configure({ network })` |
244
+ | `interrupt()`, `stopForRepl()`, `control('soft-reset')` | `control({ action, mode })`; readiness barriers are internal |
245
+ | `repl.writeStdin()` | `python.input(data)` |
246
+ | `executePython()`, `runScript()`, `startScript()` | `python.execute({ source OR path, completion })` |
247
+ | `writeFile()`, `writeScript()`, `repl.writeFile()` | `files.write({ path, data, overwrite, signal, onProgress })` |
248
+ | `repl.walkFs/readFile/removeFile/removeDir/makePath()` | `files.list/read/remove/mkdir(request)` |
249
+ | `repl.touchFile()` | `files.write({ path, data: new Uint8Array() })` |
250
+ | `handlers.text/rawText/preview/log/...` | `on(event, handler)` |
251
+ | Action `frame.capture` | `capture({ source: 'camera' })` |
252
+ | Root firmware-flashing exports | `@esp-vision/device-core/firmware` |
253
+
254
+ IDE and Agent adapters that construct sessions or call `session.repl` must migrate at their own integration boundary. Do not implement a second parser or file-transfer protocol in the UI. Existing action contracts and protocol classes remain adapter implementation tools rather than a second application API.
255
+
256
+ ## Firmware flashing
257
+
258
+ ROM flashing remains a separate lifecycle under `@esp-vision/device-core/firmware`. Hosts inject the ROM loader, approved image manifest and reset policy. The adapter validates image integrity, chip/revision, security and partitions, verifies complete readback, and clears the P4 download latch before reset. It does not distribute firmware, open a browser picker or provide a flashing UI. EV-MUX `control({ action: 'bootloader' })` only requests entry into the downloader; it does not flash an image.
259
+
260
+ Agent workflows, MCP tool mappings, model providers, CLI bundles and plugin packaging belong to the independent Agent project and are not included here.
261
+
262
+ ## Validation and release
263
+
264
+ From this directory, using Node.js 22:
265
+
266
+ ```sh
267
+ npm test
268
+ npm run check:schema
269
+ npm run check:package
270
+ npm pack
271
+ ```
272
+
273
+ Set `TMPDIR`, `TMP` and `TEMP` to a project-local temporary directory when running package verification. The package check installs a tarball in an isolated temporary directory and imports public entry points. Node.js 22 is the supported Node host baseline. Browser hosts need Web Serial or a binary WebSocket-to-TCP bridge plus a bundler/import map for the package specifier.
274
+
275
+ Device Core is maintained alongside the firmware at `host/device-core` in [espressif/esp-vision](https://github.com/espressif/esp-vision). Protocol changes, host implementation, documentation and contract tests are reviewed together. SDK versions remain independent of firmware versions; compatibility is negotiated through EV-MUX v4 capabilities. IDE and Agent consume the same npm package and do not maintain protocol copies.
276
+
277
+ Run `npm run release:check` from this directory for unit tests, schema validation, an isolated package install and a publication dry run. SDK-only changes run these Node.js checks without compiling firmware. `ESP_VISION_DEVICE_CORE_ONLY=1` selects SDK checks in an API/web pipeline; `ESP_VISION_BUILD_FIRMWARE=1` requests the final firmware matrix when needed. SDK versions are tracked in `package.json` and npm; do not create SDK Git tags in this firmware repository, because firmware/documentation version discovery uses Git tags. CI defensively excludes accidental `device-core-v*` tags from firmware jobs, but creating these tags is not part of the SDK release workflow.
278
+
279
+ Only a protected default-branch push (`master` in this firmware repository) with matching SDK changes can publish, using the masked/protected `NPM_PUBLISH_TOKEN`. The account must be `esp-vision` with scope write access. This variable must be configured in the firmware project before its first publication; moving source does not transfer CI credentials. MR, feature-branch, local and SDK-tag runs never publish. The release job verifies registry metadata and integrity: identical content is skipped; different content under an existing version requires a version bump.
280
+
281
+ Before enabling this publisher, disable the old IDE-project package release job so there is only one authoritative publisher. Migration is staged: qualify this in-repository SDK and its publication pipeline, publish and verify its registry integrity, then update the IDE/Agent adapters to the fixed package version and remove the old IDE source copy. Until that consumer migration is complete the old worktree is preserved as a backup, not an additional source of future SDK changes. No npm publication is performed by local migration tests.
282
+
283
+ The package includes library source, schemas, license and documentation, with no IDE/Agent bundles or release scripts. Every future release must update its version and changelog.
284
+
285
+ ## Hardware acceptance
286
+
287
+ Run the checked-out SDK against one idle device using Node.js 22. These checks use the public `createDevice()` API and release the session and transport afterwards. The default check reads identity/capabilities/runtime and executes a short `print()` without creating a device file. Connecting negotiates the REPL, so use a device whose running Python application may safely be interrupted. The check does not configure Wi-Fi, reset the board or erase storage.
288
+
289
+ ```sh
290
+ npm run test:hardware -- --tcp 192.168.1.100:3232
291
+ npm run test:hardware -- --port /dev/serial/by-id/YOUR_DEVICE --role usj
292
+ npm run test:hardware -- --port /dev/serial/by-id/YOUR_USB_OTG_DEVICE --role usb --write
293
+ npm run test:hardware -- --tcp 192.168.1.100 --write --capture --timeout 90000
294
+ npm run test:hardware -- --port /dev/serial/by-id/YOUR_DEVICE --role usj --checks all --frames 30 --output camera.jpg
295
+ npm run test:hardware -- --tcp 192.168.1.100 --checks display --display-hold 2 --screen-output screen.jpg
296
+ ```
297
+
298
+ `--write` explicitly opts into creating a randomly named 1 KiB binary file, verifying every byte by readback, and deleting that file and its temporary upload sibling. Existing matching paths are refused; cleanup failures are reported with the test path and make the command fail. `--capture` opts into a camera JPEG check; `--output` optionally saves that JPEG. SIGINT/SIGTERM cancel the operation; cleanup has a separate bounded deadline. Output excludes network credentials, arbitrary device logs and Python tracebacks. A failing check exits nonzero.
299
+
300
+ `--checks all` runs the shared firmware/SDK hardware suite: `identity`, `memory`, `camera`, `framesizes`, `pixformats`, `orientation`, `ipa_stats`, `snapshot_rate`, `preview`, `image_ops`, `display`, and `display_stream`. Select a comma-separated subset with `--checks memory,camera,preview`. Timing controls are `--frames` (default 30), `--frame-timeout` (seconds, default 25), and `--display-hold` (seconds per backlight state, default zero). Sensor defaults are `--framesize QVGA --pixformat RGB565`; `--quality` defaults to 60. Functional checks default to a 600000 ms overall deadline; an explicit `--timeout` overrides it. Each result is a JSON line with PASS/FAIL/SKIP, measurements and duration, followed by a summary. Unsupported hardware is skipped; IPA absence remains a failure on boards whose camera requires IPA.
301
+
302
+ These functional checks intentionally exercise sensor settings, image processing, preview and the LCD. Their single Apache-2.0 MicroPython fixture is staged to a unique device path through `files.write()`, loaded through `python.execute()`, and removed. Subsequent checks use short `python.execute()` calls; preview reception uses the public event API. The suite removes its fixture and Python namespace, releases its display objects and disconnects. It does not overwrite application files or maintain a second EV-MUX/RPC implementation.
303
+
304
+ `--screen-output PATH` explicitly requests an LCD screenshot: it adds the `display` check when needed, draws red/green/blue/white bars with `ESP-VISION CI` text, validates backlight changes, captures that same display with `capture({ source: 'screen' })`, verifies JPEG completeness and panel dimensions, and writes the JPEG on the host before releasing the display. Missing LCD or screen capture support makes this explicit request fail instead of skip. Camera capture stays a separate source. Output images and logs should be placed under your project-local artifact directory when running this suite.
305
+
306
+ TCP needs only Node.js. Serial additionally needs a Python interpreter with the optional [pyserial](https://pyserial.readthedocs.io/) dependency installed in your environment (`python3 -m pip install pyserial`, BSD-3-Clause; not vendored or included in the npm package). Select another interpreter with `--python /path/to/python`. The Apache-2.0-licensed serial adapter in `src/node_serial.py` is shared by the CLI and hardware runner; it enumerates ports without opening them, forwards bytes and configures RTS/DTR before opening; serial control-line behavior still depends on the board and OS driver. Hardware-check scripts and their tests stay in the source tree and are excluded from the published package.
307
+
308
+ ## License
309
+
310
+ The npm package and ESP-VISION contributions use [Apache-2.0](LICENSE), matching the firmware. [NOTICE](NOTICE) retains the original copyright and MIT permission text for historical and upstream-derived portions. Third-party dependencies retain their own licenses; neither package metadata nor the project license overrides them.