zelos-recad 0.1.0 → 0.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.
Files changed (166) hide show
  1. package/README.md +18 -5
  2. package/UPSTREAM-LICENSE +21 -21
  3. package/build-info.json +26 -0
  4. package/mcp/index.js +2 -1
  5. package/package.json +22 -10
  6. package/protocol/src/bundle.d.ts +7 -1
  7. package/protocol/src/contracts.d.ts +18 -6
  8. package/protocol/src/contracts.js +20 -7
  9. package/protocol/src/native-evidence.d.ts +20 -0
  10. package/service/app.js +4 -2
  11. package/service/options.d.ts +2 -1
  12. package/service/options.js +2 -1
  13. package/shared/build-identity.d.mts +6 -0
  14. package/shared/build-identity.mjs +63 -0
  15. package/shared/client.d.mts +1 -0
  16. package/shared/client.mjs +9 -0
  17. package/shared/command.d.mts +1 -0
  18. package/shared/command.mjs +22 -4
  19. package/shared/contracts/src/paths.d.ts +3 -0
  20. package/shared/contracts/src/paths.js +31 -0
  21. package/shared/mcp.d.mts +1 -0
  22. package/shared/service-storage/src/capacity.d.ts +36 -0
  23. package/shared/service-storage/src/capacity.js +71 -0
  24. package/shared/service-storage/src/consumption.d.ts +15 -0
  25. package/shared/service-storage/src/consumption.js +27 -0
  26. package/shared/service-storage/src/documents.d.ts +43 -0
  27. package/shared/service-storage/src/documents.js +210 -0
  28. package/shared/service-storage/src/downloads.d.ts +10 -0
  29. package/shared/service-storage/src/downloads.js +58 -0
  30. package/shared/service-storage/src/files.d.ts +18 -0
  31. package/shared/service-storage/src/files.js +118 -0
  32. package/shared/service-storage/src/footprint.d.ts +14 -0
  33. package/shared/service-storage/src/footprint.js +72 -0
  34. package/shared/service-storage/src/process-temp.d.ts +22 -0
  35. package/shared/service-storage/src/process-temp.js +181 -0
  36. package/shared/service-storage/src/quota.d.ts +30 -0
  37. package/shared/service-storage/src/quota.js +166 -0
  38. package/shared/service-storage/src/retention.d.ts +38 -0
  39. package/shared/service-storage/src/retention.js +148 -0
  40. package/shared/service-storage/src/staging.d.ts +15 -0
  41. package/shared/service-storage/src/staging.js +116 -0
  42. package/source/README.md +1 -3
  43. package/source/mcp/index.ts +2 -1
  44. package/source/package.json +4 -2
  45. package/source/protocol/src/contracts.ts +20 -7
  46. package/source/protocol/src/native-evidence.ts +21 -0
  47. package/source/rebuild.mjs +12 -4
  48. package/source/service/app.ts +6 -2
  49. package/source/service/options.ts +3 -2
  50. package/source/shared/build-identity.d.mts +6 -0
  51. package/source/shared/build-identity.mjs +63 -0
  52. package/source/shared/client.d.mts +1 -0
  53. package/source/shared/client.mjs +9 -0
  54. package/source/shared/command.d.mts +1 -0
  55. package/source/shared/command.mjs +22 -4
  56. package/source/shared/contracts/src/paths.ts +33 -0
  57. package/source/shared/mcp.d.mts +1 -0
  58. package/source/shared/service-storage/src/capacity.ts +101 -0
  59. package/source/shared/service-storage/src/consumption.ts +45 -0
  60. package/source/shared/service-storage/src/documents.ts +262 -0
  61. package/source/shared/service-storage/src/downloads.ts +62 -0
  62. package/source/shared/service-storage/src/files.ts +135 -0
  63. package/source/shared/service-storage/src/footprint.ts +78 -0
  64. package/source/shared/service-storage/src/process-temp.ts +205 -0
  65. package/source/shared/service-storage/src/quota.ts +198 -0
  66. package/source/shared/service-storage/src/retention.ts +180 -0
  67. package/source/shared/service-storage/src/staging.ts +106 -0
  68. package/source/src/application-objects.ts +2 -2
  69. package/source/src/assets.ts +15 -0
  70. package/source/src/block-clip.ts +1 -1
  71. package/source/src/block-metadata.ts +12 -5
  72. package/source/src/build-info.ts +15 -0
  73. package/source/src/cad-engine.ts +18 -8
  74. package/source/src/command.ts +2 -2
  75. package/source/src/constraints.ts +2 -2
  76. package/source/src/conversion.ts +2 -0
  77. package/source/src/dwg-fallback.ts +2 -0
  78. package/source/src/dwg.ts +7 -0
  79. package/source/src/dxf-export.ts +3 -3
  80. package/source/src/dxf.ts +7 -4
  81. package/source/src/native-evidence.ts +33 -1
  82. package/source/src/native-segmented-path.ts +22 -35
  83. package/source/src/point-dictionaries.ts +65 -0
  84. package/source/src/readback.ts +7 -6
  85. package/source/src/reader.ts +19 -10
  86. package/source/src/render-operation.ts +39 -7
  87. package/source/src/runner.ts +5 -4
  88. package/source/src/runtime/documents.ts +23 -142
  89. package/source/src/runtime/index.ts +71 -17
  90. package/source/src/runtime/jobs.ts +176 -153
  91. package/source/src/runtime/managed-worker.ts +37 -0
  92. package/source/src/runtime/storage-policy.ts +39 -0
  93. package/source/src/runtime/storage.ts +9 -44
  94. package/source/src/source-scene.ts +125 -23
  95. package/source/src/text/glyphs.ts +63 -0
  96. package/source/src/text/ink-bounds.ts +7 -36
  97. package/source/src/text/scene-geometry.ts +92 -0
  98. package/source/src/text/source-fonts.ts +31 -0
  99. package/source/src/vendor-object-data.ts +265 -0
  100. package/source/src/xref.ts +4 -3
  101. package/source/tsconfig.json +4 -2
  102. package/src/application-objects.js +2 -2
  103. package/src/assets.d.ts +9 -0
  104. package/src/assets.js +14 -0
  105. package/src/block-clip.js +1 -1
  106. package/src/block-metadata.js +11 -5
  107. package/src/build-info.d.ts +2 -0
  108. package/src/build-info.js +14 -0
  109. package/src/cad-engine.js +19 -8
  110. package/src/command.js +2 -2
  111. package/src/constraints.js +2 -2
  112. package/src/conversion.d.ts +2 -0
  113. package/src/conversion.js +2 -0
  114. package/src/dwg-fallback.d.ts +1 -0
  115. package/src/dwg-fallback.js +2 -0
  116. package/src/dwg.d.ts +3 -0
  117. package/src/dwg.js +7 -0
  118. package/src/dxf-export.js +3 -3
  119. package/src/dxf.d.ts +14 -1
  120. package/src/dxf.js +7 -3
  121. package/src/native-evidence.d.ts +33 -1
  122. package/src/native-evidence.js +33 -0
  123. package/src/native-segmented-path.js +1 -3
  124. package/src/point-dictionaries.d.ts +12 -0
  125. package/src/point-dictionaries.js +88 -0
  126. package/src/readback.d.ts +12 -4
  127. package/src/readback.js +7 -6
  128. package/src/reader.d.ts +12 -1
  129. package/src/reader.js +22 -11
  130. package/src/render-operation.js +36 -7
  131. package/src/runner.js +5 -4
  132. package/src/runtime/documents.d.ts +8 -20
  133. package/src/runtime/documents.js +17 -116
  134. package/src/runtime/index.d.ts +41 -4
  135. package/src/runtime/index.js +72 -18
  136. package/src/runtime/jobs.d.ts +21 -2
  137. package/src/runtime/jobs.js +120 -100
  138. package/src/runtime/managed-worker.d.ts +8 -0
  139. package/src/runtime/managed-worker.js +29 -0
  140. package/src/runtime/storage-policy.d.ts +25 -0
  141. package/src/runtime/storage-policy.js +29 -0
  142. package/src/runtime/storage.d.ts +1 -7
  143. package/src/runtime/storage.js +1 -38
  144. package/src/source-scene.d.ts +4 -2
  145. package/src/source-scene.js +136 -20
  146. package/src/text/glyphs.d.ts +12 -0
  147. package/src/text/glyphs.js +53 -0
  148. package/src/text/ink-bounds.d.ts +2 -1
  149. package/src/text/ink-bounds.js +6 -34
  150. package/src/text/scene-geometry.d.ts +21 -0
  151. package/src/text/scene-geometry.js +70 -0
  152. package/src/text/source-fonts.d.ts +7 -0
  153. package/src/text/source-fonts.js +30 -0
  154. package/src/vendor-object-data.d.ts +19 -0
  155. package/src/vendor-object-data.js +241 -0
  156. package/src/xref.js +3 -3
  157. package/vendor/libredwg/COPYING +674 -674
  158. package/vendor/libredwg/Dockerfile +2 -0
  159. package/vendor/libredwg/README.md +41 -28
  160. package/vendor/libredwg/build-local.sh +1 -1
  161. package/vendor/libredwg/libredwg-web.wasm +0 -0
  162. package/vendor/libredwg/manifest.json +5 -3
  163. package/vendor/libredwg/opaque-object-binding.patch +29 -0
  164. package/vendor/libredwg/rebuild.mjs +2 -1
  165. package/source/service/README.md +0 -152
  166. package/source/src/text/UPSTREAM.md +0 -26
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # zelos-recad
2
2
 
3
+ 以下说明对应 0.2.0。实际发布版本与通道以 npm dist-tags 为准。
4
+
3
5
  DWG/DXF 读取、布局、场景证据、结构读回,以及 PDF/PNG 渲染。一个 npm 包统一提供代码调用、REST 服务、stdio 与 Streamable HTTP MCP。各入口共用持久任务、文档存储及成果核验。
4
6
 
5
7
  ## 安装
@@ -7,13 +9,15 @@ DWG/DXF 读取、布局、场景证据、结构读回,以及 PDF/PNG 渲染。
7
9
  需要 Node.js >=24.13.0。本地处理需要 Python >=3.10;首次本地服务/MCP 启动会在用户数据目录准备固定版本的 PyMuPDF 和 fonttools。也可用 RECAD_PYTHON 指向已有的匹配环境。
8
10
 
9
11
  ```sh
10
- npm install zelos-recad@0.1.0
12
+ npm install zelos-recad@0.2.0
11
13
  npx zelos-recad setup
12
14
  npx zelos-recad doctor
13
15
  ```
14
16
 
15
17
  运行数据默认位于 env-paths 的 recad 用户数据目录,Windows 为 %LOCALAPPDATA%/recad/Data。用 --data-dir 或 RECAD_DATA_DIR 配置。安装目录仅放代码和资源。Python 准备阶段需要访问包源,后续启动复用已准备环境。
16
18
 
19
+ 默认端口:REST `18771`,HTTP MCP `18773`。`--port` 优先于 `RECAD_PORT`,`--port 0` 由系统分配端口;stdio 使用进程管道。
20
+
17
21
  ## MCP
18
22
 
19
23
  本机 stdio:
@@ -25,7 +29,7 @@ npx zelos-recad mcp --transport stdio --backend local --input-root /project/draw
25
29
  Streamable HTTP:先通过部署环境配置 RECAD_TOKEN(至少16字符),再启动:
26
30
 
27
31
  ```sh
28
- npx zelos-recad mcp --transport http --backend local --host 127.0.0.1 --port 18474 --data-dir /project/recad-data
32
+ npx zelos-recad mcp --transport http --backend local --host 127.0.0.1 --port 18773 --data-dir /project/recad-data
29
33
  ```
30
34
 
31
35
  客户端连接 /mcp,Authorization: Bearer <token>。同一凭据用于 POST /v1/documents?fileName=source.dxf 上传原始字节(Content-Type: application/octet-stream),以及 GET /v1/jobs/<jobId>/artifacts/<name> 下载。HTTP 工具使用上传回执中的 documentId。授权按实例配置;不同调用系统分配独立数据根和凭据。外部域名配置 --allowed-host domain:port,浏览器请求额外配置 --allowed-origin https://domain,并由部署入口提供 TLS。
@@ -39,23 +43,32 @@ HTTP会话重建和进程重启后可以查询同一jobId。stdio local退出时
39
43
  ## 独立 REST 服务
40
44
 
41
45
  ```sh
42
- npx zelos-recad serve --host 127.0.0.1 --port 18472 --data-dir /project/recad-data
46
+ npx zelos-recad serve --host 127.0.0.1 --port 18771 --data-dir /project/recad-data
43
47
  ```
44
48
 
45
49
  继续使用 /v1/documents、/v1/documents/:id/jobs、/v1/jobs/:id、/v1/owners/:owner 和成果下载接口。RECAD_TOKEN 配置实例凭据。并发、执行超时、保留期和容量可通过 --concurrency、--timeout-ms、--retention-days、--max-storage-mib 配置。
46
50
 
51
+ 临时任务默认保留两天。存储保护默认预留 5 GiB 磁盘空间,暂停后恢复额外要求 2 GiB,估算系数 1.2,每个 worker 初始预算 600 MiB。分别用 `RECAD_RETENTION_DAYS`、`RECAD_MIN_FREE_GIB`、`RECAD_RESUME_EXTRA_GIB`、`RECAD_STORAGE_ESTIMATE_FACTOR`、`RECAD_WORKER_STORAGE_MIB` 或对应 CLI 参数配置。`RECAD_MAX_STORAGE_MIB` 为实例逻辑配额,默认 0 表示使用磁盘水位保护。
52
+
53
+ 成果在调用方持久保存并核验后,可向 `POST /v1/jobs/:id/consumed` 发送 `{status, sourceSha256, artifacts}`,artifacts 包含完整成果及诊断的 `{name, sha256, bytes}`。成功返回 `{id, consumedAt}`;兼容已有 `{owner, sourceSha256, artifacts}` 成功任务回执,并附带 `consumed: true`。消费确认可提前释放临时工件,活动上传、执行和下载由运行层保护。
54
+
47
55
  ## 代码入口
48
56
 
49
57
  - zelos-recad:原专业引擎。
50
58
  - zelos-recad/protocol:请求/结果 schema 与能力合同。
51
59
  - zelos-recad/client:createRecadClient({url, token}),异步提交与查询、上传、带大小/SHA256核验的成果流。
52
60
  - zelos-recad/runtime:createRecadRuntime({data, python}),复用持久任务队列和隔离worker;使用后await close()。
61
+ - zelos-recad/runtime:runManagedWorker(options, controls, storage),供本地逐次处理共用磁盘准入和增长检查;输出临时目录由宿主创建和清理。withRecadStorage 可将同一保护用于转换调用。
62
+ - zelos-recad/assets:getRecadAssets() 返回字体、替代表、Python requirements 及 decoder manifest 的安装路径;getRecadBuildInfo() 返回版本、代码/资源/decoder SHA 和稳定 fingerprint,供派生缓存绑定制品身份。
63
+ - zelos-recad/conversion:createNativeDxfCandidate(dwgBytes) 复用既有 DWG 到 DXF 候选转换和诊断;调用方继续核验生成结果。
53
64
  - zelos-recad/service:createRecadApp,供宿主挂载REST。
54
65
  - zelos-recad/mcp:startRecadMcp,供宿主启动MCP。
55
66
  - zelos-recad/setup:prepareRecadRuntime,返回已准备的Python路径。
56
67
 
57
- 旧 recad/repdf 文件处理命令与 recad-service/repdf-service 启动别名保留。统一命令 run 接受 --input FILE --output NEW_DIRECTORY --request REQUEST_JSON。
68
+ 旧 recad 文件处理命令与 recad-service 启动别名保留。统一命令 run 接受 --input FILE --output NEW_DIRECTORY --request REQUEST_JSON。
69
+
70
+ 能力版本 34 汇合自动图幅 `render.print: "auto"`、整模型单页 `scene.sheetMode: "single"`、文字字形/字体资源、原生 `source-records` 读回和既有原生对象修复。每个操作仍沿公开请求 schema,报告附带构建身份;服务 UUID 幂等继续使用原请求及资源身份。
58
71
 
59
72
  ## 开源、来源与重建
60
73
 
61
- AGPL-3.0-or-later。随包 LICENSE、THIRD_PARTY_NOTICES.md、source/提供许可、来源和可编辑源码。源码重建步骤见 source/README.md。LibreDWG对应源码、补丁、哈希及重建说明位于vendor/libredwg;字体许可证随assets/fonts提供。服务器运营方应按许可证向用户提供所运行版本的对应源码。版本固定为0.1.0;升级前保留原版本、配置和数据目录备份,保持一个运行实例持有一个数据根。
74
+ AGPL-3.0-or-later。随包 LICENSE、THIRD_PARTY_NOTICES.md、source/提供许可、来源和可编辑源码。源码重建步骤见 source/README.md。LibreDWG对应源码、补丁、哈希及重建说明位于vendor/libredwg;字体许可证随assets/fonts提供。服务器运营方应按许可证向用户提供所运行版本的对应源码。升级前保留原版本、配置和数据目录备份,保持一个运行实例持有一个数据根。
package/UPSTREAM-LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 mlightcad
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mlightcad
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,26 @@
1
+ {
2
+ "format": "DocumentService.BuildIdentity",
3
+ "version": 1,
4
+ "packageName": "zelos-recad",
5
+ "packageVersion": "0.2.0",
6
+ "codeSha256": "7e694cd92b9122737c43c46021c0b1587f6b57a9cc4393ad4927d084f2ded7d1",
7
+ "sourceSha256": "c647b0f4d3f18ac598d8ddf2225888a5014049b416463937fe8fd82435be1073",
8
+ "resourceManifestSha256": "bc7ae805eac4f4ed096c7a9a83b2110b663bde612ca8b859a69100c549d3391e",
9
+ "decoderSha256": "4f4cbe260255ee289ed041cc9209ca076444060b43832404154c3cc0d0340089",
10
+ "dependencies": {
11
+ "@mlightcad/data-model": "1.15.2",
12
+ "@mlightcad/libredwg-converter": "3.15.2",
13
+ "@mlightcad/libredwg-web": "0.7.15",
14
+ "@mlightcad/mtext-parser": "1.5.3",
15
+ "@mlightcad/pdf-renderer": "1.7.4",
16
+ "@mlightcad/shx-parser": "1.4.5",
17
+ "@modelcontextprotocol/sdk": "1.32.2",
18
+ "env-paths": "3.0.0",
19
+ "fastify": "5.12.5",
20
+ "iconv-lite": "0.7.0",
21
+ "pdf-lib": "1.17.1",
22
+ "proper-lockfile": "4.1.2",
23
+ "zod": "4.6.7"
24
+ },
25
+ "fingerprint": "f8c6fe72ada11088046dba35214ab65fc812405d406d4b01273872a058c10784"
26
+ }
package/mcp/index.js CHANGED
@@ -3,6 +3,7 @@ import { requestSchema, CAD_INPUT_LIMITS } from "../protocol/src/contracts.js";
3
3
  import { CAD_BUNDLE_LIMITS } from "../protocol/src/bundle.js";
4
4
  import { createRecadClient } from "../protocol/src/client.js";
5
5
  import { recadOptions } from "../service/options.js";
6
+ import { getRecadBuildInfo } from "../src/build-info.js";
6
7
  export async function startRecadMcp(options = {}) {
7
8
  if (options.backend && !['local', 'remote'].includes(options.backend))
8
9
  throw new Error('backend must be local or remote');
@@ -10,7 +11,7 @@ export async function startRecadMcp(options = {}) {
10
11
  ? createRecadClient({ url: options.url || '', token: options.backendToken, timeoutMs: options.timeoutMs })
11
12
  : (await import("../src/runtime/index.js")).createRecadRuntime(await recadOptions(options));
12
13
  try {
13
- return await startDocumentMcp({ ...options, engine: 'recad', version: '0.1.0', requestSchema, inputBytes: CAD_INPUT_LIMITS.inputBytes, bundleBytes: CAD_BUNDLE_LIMITS.bodyBytes, backend });
14
+ return await startDocumentMcp({ ...options, engine: 'recad', version: getRecadBuildInfo().packageVersion, requestSchema, inputBytes: CAD_INPUT_LIMITS.inputBytes, bundleBytes: CAD_BUNDLE_LIMITS.bodyBytes, backend });
14
15
  }
15
16
  catch (error) {
16
17
  await backend.close();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zelos-recad",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "exports": {
@@ -73,6 +73,16 @@
73
73
  "types": "./src/setup.d.ts",
74
74
  "import": "./src/setup.js",
75
75
  "default": "./src/setup.js"
76
+ },
77
+ "./conversion": {
78
+ "types": "./src/conversion.d.ts",
79
+ "import": "./src/conversion.js",
80
+ "default": "./src/conversion.js"
81
+ },
82
+ "./assets": {
83
+ "types": "./src/assets.d.ts",
84
+ "import": "./src/assets.js",
85
+ "default": "./src/assets.js"
76
86
  }
77
87
  },
78
88
  "dependencies": {
@@ -95,11 +105,20 @@
95
105
  "node": ">=24.13.0"
96
106
  },
97
107
  "license": "AGPL-3.0-or-later",
108
+ "repository": {
109
+ "type": "git",
110
+ "url": "git+https://github.com/Hopesy/recad.git"
111
+ },
98
112
  "author": "Zelos contributors",
99
113
  "publishConfig": {
100
114
  "access": "public",
101
115
  "registry": "https://registry.npmjs.org/"
102
116
  },
117
+ "bin": {
118
+ "recad": "./src/cli.js",
119
+ "recad-service": "./service/main.js",
120
+ "zelos-recad": "./src/command.js"
121
+ },
103
122
  "files": [
104
123
  "src",
105
124
  "service",
@@ -107,6 +126,7 @@
107
126
  "mcp",
108
127
  "shared",
109
128
  "source",
129
+ "build-info.json",
110
130
  "scripts/check_runtime.py",
111
131
  "scripts/extract_font_face.py",
112
132
  "scripts/finish_pdf.py",
@@ -118,13 +138,5 @@
118
138
  "UPSTREAM-LICENSE",
119
139
  "LICENSE",
120
140
  "THIRD_PARTY_NOTICES.md"
121
- ],
122
- "bin": {
123
- "recad": "./src/cli.js",
124
- "recad-service": "./service/main.js",
125
- "zelos-recad": "./src/command.js"
126
- },
127
- "scripts": {
128
- "start": "node service/main.js"
129
- }
141
+ ]
130
142
  }
@@ -22,9 +22,15 @@ export declare function decodeBundle(raw: unknown): {
22
22
  layout?: string | undefined;
23
23
  } | {
24
24
  operation: "readback";
25
+ } | {
26
+ operation: "source-records";
27
+ layout?: string | undefined;
25
28
  } | {
26
29
  operation: "scene";
27
30
  layout?: string | undefined;
31
+ sheetMode?: "auto" | "single" | undefined;
32
+ textGeometry?: boolean | undefined;
33
+ fontResources?: boolean | undefined;
28
34
  } | {
29
35
  operation: "render";
30
36
  print: {
@@ -61,7 +67,7 @@ export declare function decodeBundle(raw: unknown): {
61
67
  defaultLineweightMm: number;
62
68
  dpi: number;
63
69
  png: boolean;
64
- };
70
+ } | "auto";
65
71
  layout?: string | undefined;
66
72
  };
67
73
  resources: {
@@ -67,12 +67,21 @@ export declare const requestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
67
67
  layout: z.ZodOptional<z.ZodString>;
68
68
  }, z.core.$strict>, z.ZodObject<{
69
69
  operation: z.ZodLiteral<"readback">;
70
+ }, z.core.$strict>, z.ZodObject<{
71
+ operation: z.ZodLiteral<"source-records">;
72
+ layout: z.ZodOptional<z.ZodString>;
70
73
  }, z.core.$strict>, z.ZodObject<{
71
74
  operation: z.ZodLiteral<"scene">;
72
75
  layout: z.ZodOptional<z.ZodString>;
76
+ sheetMode: z.ZodOptional<z.ZodEnum<{
77
+ auto: "auto";
78
+ single: "single";
79
+ }>>;
80
+ textGeometry: z.ZodOptional<z.ZodBoolean>;
81
+ fontResources: z.ZodOptional<z.ZodBoolean>;
73
82
  }, z.core.$strict>, z.ZodObject<{
74
83
  operation: z.ZodLiteral<"render">;
75
- print: z.ZodObject<{
84
+ print: z.ZodUnion<readonly [z.ZodObject<{
76
85
  paperWidthMm: z.ZodNumber;
77
86
  paperHeightMm: z.ZodNumber;
78
87
  window: z.ZodObject<{
@@ -117,7 +126,7 @@ export declare const requestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
117
126
  defaultLineweightMm: z.ZodDefault<z.ZodNumber>;
118
127
  dpi: z.ZodDefault<z.ZodNumber>;
119
128
  png: z.ZodDefault<z.ZodBoolean>;
120
- }, z.core.$strict>;
129
+ }, z.core.$strict>, z.ZodLiteral<"auto">]>;
121
130
  layout: z.ZodOptional<z.ZodString>;
122
131
  }, z.core.$strict>], "operation">;
123
132
  export type CadRequest = z.input<typeof requestSchema>;
@@ -151,7 +160,7 @@ export declare const resourceSchema: z.ZodObject<{
151
160
  }, z.core.$strict>;
152
161
  export declare const capabilities: {
153
162
  readonly format: "XDTrace.RecadCapabilities";
154
- readonly version: 30;
163
+ readonly version: 34;
155
164
  readonly layouts: {
156
165
  readonly version: 1;
157
166
  readonly selection: true;
@@ -161,6 +170,9 @@ export declare const capabilities: {
161
170
  readonly version: 1;
162
171
  readonly coordinates: "cad-world-y-up-v1";
163
172
  readonly sheetPolicy: 1;
173
+ readonly sheetModes: readonly ["auto", "single"];
174
+ readonly textGeometry: 1;
175
+ readonly fontResources: 1;
164
176
  };
165
177
  readonly nativeEvidence: {
166
178
  readonly version: 1;
@@ -183,18 +195,18 @@ export declare const capabilities: {
183
195
  readonly sourceHashBinding: true;
184
196
  };
185
197
  readonly maturity: "experimental";
186
- readonly operations: readonly ["inspect", "render", "readback", "scene", "layouts"];
198
+ readonly operations: readonly ["inspect", "render", "readback", "scene", "layouts", "source-records"];
187
199
  readonly input: readonly ["dwg", "ascii-dxf", "binary-dxf-8bit-groups", "binary-dxf-16bit-groups"];
188
200
  readonly output: readonly ["pdf", "png", "readback-json", "source-scene-json"];
189
201
  readonly layout: "Model (default); named paper layouts via layout selection";
190
- readonly rendering: readonly ["fit-window", "fixed-scale"];
202
+ readonly rendering: readonly ["fit-window", "fixed-scale", "auto-overview"];
191
203
  readonly printPlanVersion: 1;
192
204
  readonly colorModes: readonly ["monochrome", "source"];
193
205
  readonly minimumDpi: 300;
194
206
  readonly maxPixels: 150000000;
195
207
  readonly independentCadVerification: true;
196
208
  readonly productionReplacementReady: false;
197
- readonly limitations: readonly ["Ordinary source CAD jobs isolate bounded unsupported application objects, failed HATCH/REGION and BLOCKLOOKUPACTION records with per-object receipts; structural/CRC/section/critical failures remain blocking. Core strict mode, explicit bundles and final readback never certify recovery as complete parsing", "R2007 VLO-VL ASCII payloads retain typed data; other VLO/application payloads are omitted with handles and source hashes in source recovery mode, never executed", "Straight planar LEADER retains dimension styles, annotations and verified DSTYLE overrides, prints closed filled and DOT arrows; dimension-only overrides retain values without modifying saved leader geometry", "Saved anonymous dynamic-block representations can be plotted in source recovery mode with explicit unevaluated-program metadata; no editing/constraint solver is claimed", "Measured print suggestions retain all content and offer spatial regions and aspect-matched 300 DPI paper; they do not claim authored sheet frames and never silently discard distant geometry", "3DFACE plots saved visible edges in 2D wireframe, respecting hidden-edge flags and double-precision coordinates; no shaded 3D rendering or hidden-surface solver is claimed", "R2004/R2007 version-2 ASSOC2DCONSTRAINTGROUP retains five verified node types, graph connections and raw payload; source recovery may plot saved geometry with pending-evaluation receipts; strict/readback rejects pending evaluation, unknown nodes and broken graphs", "Verified electrical-application INSERT dictionary/XRECORD records retain typed payloads and ownership receipts; unknown extensions still fail; final readback rejects business metadata until independent replay is supported", "Ordinary service CAD plotting defaults to best-effort text: bundled Noto Sans SC substitutes missing faces, uncovered glyphs leave spaces, unsupported text emits omission receipts; explicit resource bundles and readback remain strict; SHAPE libraries are not text substitutes", "Bundled DWG/DXF XREF loads explicit hashed dependencies, nested attachments and overlay non-propagation, model basepoints, affine/mirrored instances, scoped fonts/images and host VISRETAIN 0/1 layer properties; unknown INSERT extension programs and non-default XREFOVERRIDE/VISRETAINMODE fail explicitly", "2D block/XREF positive rectangular and simple polygon clipping supports nested affine instances, disabled filters and validated inverse matrices; inverse clips, depth planes, non-identity clip-space matrices, printed clip frames and clipped arrays remain explicit failures; final readback rejects block clipping until its semantics can be replayed", "XREF cache geometry never substitutes for missing dependencies; final readback rejects every external drawing reference, including unused and cached definitions", "Collected stroke/fill vector bounds use the final composed instance coordinates instead of repeatedly transformed AABBs; text/image/specialized operations retain conservative loaded-resource bounds", "Horizontal SHX TEXT/ATTRIB/ATTDEF percent underline/overline/strike toggles preserve pen advances, alignment bounds, spaces, mirrors, obliquing, negative-Z and block affine transforms; decorated custom TTF and vertical TEXT remain explicit failures", "MINSERT DXF/R2000/R2007/R2018 retains array dispatch, rotated unscaled spacing, repeated attributes, nested transforms and readback subclass grammar; per-array and total-instance limits apply", "Planar negative-Z single-line SHX placement is verified across 36 alignment/mirror cases; nonplanar TEXT remains unsupported", "SHX shapes/unifont, ordinary and extended BigFont, fractional arcs, dual-mode vertical writing are covered by explicit font fixtures; this is not universal font compatibility", "Extended BigFont signed basepoint drawing and unsigned cursor restoration are verified; nested extended calls, vertical MTEXT and vertical non-baseline alignment remain explicit failures", "SHX/TTF TEXT Aligned/Fit and combined entity/STYLE mirrors, explicit TTC faceIndex, and R2018 multiline attributes with masks/columns are supported", "MTEXT static/equal-height/manual-height columns preserve widths, gutters, flow, rotation and per-column masks; complete legacy XDATA/EED linked columns normalize to the same layout, ambiguous or broken links fail", "GROUP references to legacy linked child columns preserve original handles and source programs in readback without duplicate rendering", "Multiline attributes retain embedded styles, indexed/true-color masks, frames and three column modes; malformed embedded programs fail explicitly", "DWG ATTRIB STYLE/layer/flags verified on R2000–R2018 fixtures; original and remaining native statuses are retained; unresolved structural decode failures remain explicit", "Explicit print policy; no arbitrary CTB/STB equivalence", "Binary DXF R12/R2000/R2007/R2018 fixtures are verified, including R12 markerless geometry, attribute sequences and one-byte group envelopes; unresolved XREF and unsupported entities fail explicitly", "Complex A-aligned linetypes retain source text/shape STYLE, offsets, rotation and physical lineweights; missing definitions fail", "Monochrome uses black vectors and grayscale images; PNG retains antialiasing", "DXF/DWG MTEXT masks preserve rotation and authored column widths; monochrome makes all masks white, source mode preserves color", "PNG/JPEG IMAGE supports block instances, affine placement and polygon/inverse clipping; non-default brightness/contrast/fade still fail", "Model reachability filters unused definitions; unresolved DWG decoder omissions remain conservative failures", "Independent readback supplies evidence; the application must compare geometry/resources/GROUP and recompute topology, then separately review appearance", "Inspect measureBounds=true loads actual resources and collects layout before paper clipping; plain parserBounds remains a diagnostic estimate"];
209
+ readonly limitations: readonly ["Ordinary source CAD jobs isolate bounded unsupported application objects, failed HATCH/REGION and BLOCKLOOKUPACTION records with per-object receipts; structural/CRC/section/critical failures remain blocking. Core strict mode, explicit bundles and final readback never certify recovery as complete parsing", "R2007 VLO-VL ASCII payloads retain typed data; other VLO/application payloads are omitted with handles and source hashes in source recovery mode, never executed", "Straight planar LEADER retains dimension styles, annotations and verified DSTYLE overrides, prints closed filled and DOT arrows; dimension-only overrides retain values without modifying saved leader geometry", "Saved anonymous dynamic-block representations can be plotted in source recovery mode with explicit unevaluated-program metadata; no editing/constraint solver is claimed", "Measured print suggestions retain all content and offer spatial regions and aspect-matched 300 DPI paper; they do not claim authored sheet frames and never silently discard distant geometry", "3DFACE plots saved visible edges in 2D wireframe, respecting hidden-edge flags and double-precision coordinates; no shaded 3D rendering or hidden-surface solver is claimed", "R2004/R2007 version-2 ASSOC2DCONSTRAINTGROUP retains five verified node types, graph connections and raw payload; source recovery may plot saved geometry with pending-evaluation receipts; strict/readback rejects pending evaluation, unknown nodes and broken graphs", "Verified electrical-application INSERT dictionary/XRECORD records retain typed payloads and ownership receipts; unknown extensions still fail; final readback rejects business metadata until independent replay is supported", "Owned empty INSERT extension dictionaries retain dictionary identity and source hash; source reading and final readback accept the empty declaration, while malformed references and unknown entries remain rejected", "Ordinary service CAD plotting defaults to best-effort text: bundled Noto Sans SC substitutes missing faces, uncovered glyphs leave spaces, unsupported text emits omission receipts; explicit resource bundles and readback remain strict; SHAPE libraries are not text substitutes", "Bundled DWG/DXF XREF loads explicit hashed dependencies, nested attachments and overlay non-propagation, model basepoints, affine/mirrored instances, scoped fonts/images and host VISRETAIN 0/1 layer properties; unknown INSERT extension programs and non-default XREFOVERRIDE/VISRETAINMODE fail explicitly", "2D block/XREF positive rectangular and simple polygon clipping supports nested affine instances, disabled filters and validated inverse matrices; inverse clips, depth planes, non-identity clip-space matrices, printed clip frames and clipped arrays remain explicit failures; final readback rejects block clipping until its semantics can be replayed", "XREF cache geometry never substitutes for missing dependencies; final readback rejects every external drawing reference, including unused and cached definitions", "Collected stroke/fill vector bounds use the final composed instance coordinates instead of repeatedly transformed AABBs; text/image/specialized operations retain conservative loaded-resource bounds", "Horizontal SHX TEXT/ATTRIB/ATTDEF percent underline/overline/strike toggles preserve pen advances, alignment bounds, spaces, mirrors, obliquing, negative-Z and block affine transforms; decorated custom TTF and vertical TEXT remain explicit failures", "MINSERT DXF/R2000/R2007/R2018 retains array dispatch, rotated unscaled spacing, repeated attributes, nested transforms and readback subclass grammar; per-array and total-instance limits apply", "Planar negative-Z single-line SHX placement is verified across 36 alignment/mirror cases; nonplanar TEXT remains unsupported", "SHX shapes/unifont, ordinary and extended BigFont, fractional arcs, dual-mode vertical writing are covered by explicit font fixtures; this is not universal font compatibility", "Extended BigFont signed basepoint drawing and unsigned cursor restoration are verified; nested extended calls, vertical MTEXT and vertical non-baseline alignment remain explicit failures", "SHX/TTF TEXT Aligned/Fit and combined entity/STYLE mirrors, explicit TTC faceIndex, and R2018 multiline attributes with masks/columns are supported", "MTEXT static/equal-height/manual-height columns preserve widths, gutters, flow, rotation and per-column masks; complete legacy XDATA/EED linked columns normalize to the same layout, ambiguous or broken links fail", "GROUP references to legacy linked child columns preserve original handles and source programs in readback without duplicate rendering", "Multiline attributes retain embedded styles, indexed/true-color masks, frames and three column modes; malformed embedded programs fail explicitly", "DWG ATTRIB STYLE/layer/flags verified on R2000–R2018 fixtures; original and remaining native statuses are retained; unresolved structural decode failures remain explicit", "Explicit print policy; no arbitrary CTB/STB equivalence", "Binary DXF R12/R2000/R2007/R2018 fixtures are verified, including R12 markerless geometry, attribute sequences and one-byte group envelopes; unresolved XREF and unsupported entities fail explicitly", "Complex A-aligned linetypes retain source text/shape STYLE, offsets, rotation and physical lineweights; missing definitions fail", "Monochrome uses black vectors and grayscale images; PNG retains antialiasing", "DXF/DWG MTEXT masks preserve rotation and authored column widths; monochrome makes all masks white, source mode preserves color", "PNG/JPEG IMAGE supports block instances, affine placement and polygon/inverse clipping; non-default brightness/contrast/fade still fail", "Model reachability filters unused definitions; unresolved DWG decoder omissions remain conservative failures", "Independent readback supplies evidence; the application must compare geometry/resources/GROUP and recompute topology, then separately review appearance", "Inspect measureBounds=true loads actual resources and collects layout before paper clipping; plain parserBounds remains a diagnostic estimate"];
198
210
  readonly dependencies: {
199
211
  readonly dataModel: "1.15.2";
200
212
  readonly dwgConverter: "3.15.2";
@@ -56,13 +56,20 @@ export const requestSchema = z.discriminatedUnion('operation', [
56
56
  })
57
57
  .strict(),
58
58
  z.object({ operation: z.literal('readback') }).strict(),
59
+ z.object({ operation: z.literal('source-records'), layout: z.string().min(1).max(256).optional() }).strict(),
59
60
  z
60
- .object({ operation: z.literal('scene'), layout: z.string().min(1).max(256).optional() })
61
+ .object({
62
+ operation: z.literal('scene'),
63
+ layout: z.string().min(1).max(256).optional(),
64
+ sheetMode: z.enum(['auto', 'single']).optional(),
65
+ textGeometry: z.boolean().optional(),
66
+ fontResources: z.boolean().optional(),
67
+ })
61
68
  .strict(),
62
69
  z
63
70
  .object({
64
71
  operation: z.literal('render'),
65
- print: renderSchema,
72
+ print: z.union([renderSchema, z.literal('auto')]),
66
73
  layout: z.string().min(1).max(256).optional(),
67
74
  })
68
75
  .strict(),
@@ -104,10 +111,15 @@ export const resourceSchema = z
104
111
  .strict();
105
112
  export const capabilities = {
106
113
  format: 'XDTrace.RecadCapabilities',
107
- version: 30,
114
+ version: 34,
108
115
  layouts: { version: 1, selection: true, planarRectangularViewports: true },
109
- sourceScene: { version: 1, coordinates: 'cad-world-y-up-v1', sheetPolicy: 1 },
110
- nativeEvidence: { version: 1, operation: 'scene', xdata: 'registered-apps', snapshot: 'before-print-adapters' },
116
+ sourceScene: { version: 1, coordinates: 'cad-world-y-up-v1', sheetPolicy: 1, sheetModes: ['auto', 'single'], textGeometry: 1, fontResources: 1 },
117
+ nativeEvidence: {
118
+ version: 1,
119
+ operation: 'scene',
120
+ xdata: 'registered-apps',
121
+ snapshot: 'before-print-adapters',
122
+ },
111
123
  documentUploads: { version: 1, streaming: true, reuse: true },
112
124
  limits: CAD_INPUT_LIMITS,
113
125
  dwgDxfFallback: {
@@ -117,11 +129,11 @@ export const capabilities = {
117
129
  sourceHashBinding: true,
118
130
  },
119
131
  maturity: 'experimental',
120
- operations: ['inspect', 'render', 'readback', 'scene', 'layouts'],
132
+ operations: ['inspect', 'render', 'readback', 'scene', 'layouts', 'source-records'],
121
133
  input: ['dwg', 'ascii-dxf', 'binary-dxf-8bit-groups', 'binary-dxf-16bit-groups'],
122
134
  output: ['pdf', 'png', 'readback-json', 'source-scene-json'],
123
135
  layout: 'Model (default); named paper layouts via layout selection',
124
- rendering: ['fit-window', 'fixed-scale'],
136
+ rendering: ['fit-window', 'fixed-scale', 'auto-overview'],
125
137
  printPlanVersion: 1,
126
138
  colorModes: ['monochrome', 'source'],
127
139
  minimumDpi: 300,
@@ -137,6 +149,7 @@ export const capabilities = {
137
149
  '3DFACE plots saved visible edges in 2D wireframe, respecting hidden-edge flags and double-precision coordinates; no shaded 3D rendering or hidden-surface solver is claimed',
138
150
  'R2004/R2007 version-2 ASSOC2DCONSTRAINTGROUP retains five verified node types, graph connections and raw payload; source recovery may plot saved geometry with pending-evaluation receipts; strict/readback rejects pending evaluation, unknown nodes and broken graphs',
139
151
  'Verified electrical-application INSERT dictionary/XRECORD records retain typed payloads and ownership receipts; unknown extensions still fail; final readback rejects business metadata until independent replay is supported',
152
+ 'Owned empty INSERT extension dictionaries retain dictionary identity and source hash; source reading and final readback accept the empty declaration, while malformed references and unknown entries remain rejected',
140
153
  'Ordinary service CAD plotting defaults to best-effort text: bundled Noto Sans SC substitutes missing faces, uncovered glyphs leave spaces, unsupported text emits omission receipts; explicit resource bundles and readback remain strict; SHAPE libraries are not text substitutes',
141
154
  'Bundled DWG/DXF XREF loads explicit hashed dependencies, nested attachments and overlay non-propagation, model basepoints, affine/mirrored instances, scoped fonts/images and host VISRETAIN 0/1 layer properties; unknown INSERT extension programs and non-default XREFOVERRIDE/VISRETAINMODE fail explicitly',
142
155
  '2D block/XREF positive rectangular and simple polygon clipping supports nested affine instances, disabled filters and validated inverse matrices; inverse clips, depth planes, non-identity clip-space matrices, printed clip frames and clipped arrays remain explicit failures; final readback rejects block clipping until its semantics can be replayed',
@@ -83,8 +83,28 @@ export interface CadNativeRecord {
83
83
  }[];
84
84
  xdataStatus: 'registered-apps-read' | 'partial';
85
85
  }
86
+ export interface CadPointDictionaryEvidence {
87
+ format: 'XDTrace.NativePointDictionaryEvidence/1';
88
+ sourceSha256: string;
89
+ pointHandle: string;
90
+ dictionaryHandles: string[];
91
+ semanticStatus: 'uninterpreted';
92
+ recordsJson: string;
93
+ sha256: string;
94
+ }
86
95
  export interface CadNativeDocument {
87
96
  sourceSha256: string;
97
+ /** A large scene may carry the complete referenced-block closure instead of unused definitions. */
98
+ selection?: {
99
+ basis: 'scene-referenced-block-closure';
100
+ parsedRecords: number;
101
+ parsedBlocks: number;
102
+ excludedRecords: number;
103
+ excludedBlocks: number;
104
+ };
105
+ /** Non-graphical application records, including raw payloads and interpretation state. */
106
+ applicationObjects?: unknown[];
107
+ pointDictionaries?: CadPointDictionaryEvidence[];
88
108
  records: CadNativeRecord[];
89
109
  blocks: {
90
110
  id: string;
package/service/app.js CHANGED
@@ -83,9 +83,11 @@ export function createRecadApp(options) {
83
83
  app.delete('/v1/owners/:owner', async (request) => runtime.cancelOwner(request.params.owner));
84
84
  app.get('/v1/jobs/:id/artifacts/:name', async (request, reply) => {
85
85
  const { id, name } = request.params;
86
- const artifact = runtime.artifact(id, name);
87
- return reply.type(artifact.contentType).send(artifact.buffer);
86
+ const artifact = await runtime.streamArtifact(id, name);
87
+ return reply.header('Content-Length', artifact.bytes).header('X-Content-SHA256', artifact.sha256)
88
+ .type(artifact.contentType).send(artifact.stream);
88
89
  });
90
+ app.post('/v1/jobs/:id/consumed', { bodyLimit: 2 * 1024 * 1024 }, async (request) => runtime.consume(request.params.id, request.body));
89
91
  app.setErrorHandler((error, _request, reply) => {
90
92
  const status = error.code === 'NOT_FOUND'
91
93
  ? 404
@@ -1,2 +1,3 @@
1
1
  import type { RuntimeOptions } from '../src/runtime/index.js';
2
- export declare function recadOptions(options?: Partial<RuntimeOptions>, prepare?: boolean): Promise<RuntimeOptions>;
2
+ import { type StorageSettings } from '../src/runtime/storage-policy.js';
3
+ export declare function recadOptions(options?: Partial<RuntimeOptions> & StorageSettings, prepare?: boolean): Promise<RuntimeOptions>;
@@ -4,6 +4,7 @@ import envPaths from 'env-paths';
4
4
  import { indexFontDirectory } from "../src/runtime/font-catalog.js";
5
5
  import { runtimePython } from "../src/runtime-paths.js";
6
6
  import { prepareRecadRuntime } from "../src/setup.js";
7
+ import { recadStorageOptions } from "../src/runtime/storage-policy.js";
7
8
  export async function recadOptions(options = {}, prepare = true) {
8
9
  const data = path.resolve(options.data || process.env.RECAD_DATA_DIR || envPaths('recad', { suffix: '' }).data);
9
10
  const python = prepare ? (await prepareRecadRuntime({ python: options.python })).python : options.python || runtimePython();
@@ -14,7 +15,7 @@ export async function recadOptions(options = {}, prepare = true) {
14
15
  if (process.env.RECAD_MISSING_TEXT && !['strict', 'noto-sans-sc', 'best-effort'].includes(process.env.RECAD_MISSING_TEXT))
15
16
  throw new Error('Invalid RECAD_MISSING_TEXT policy');
16
17
  return {
17
- ...options, data, python,
18
+ ...options, ...recadStorageOptions(options), data, python,
18
19
  resources: options.resources || process.env.RECAD_RESOURCES || existsSync(resources) ? path.resolve(resources) : undefined,
19
20
  baseFonts: options.baseFonts ?? process.env.RECAD_BASE_FONTS !== '0',
20
21
  missingText: options.missingText || process.env.RECAD_MISSING_TEXT,
@@ -0,0 +1,6 @@
1
+ export interface BuildIdentity {
2
+ format: 'DocumentService.BuildIdentity'; version: 1; packageName: string; packageVersion: string;
3
+ codeSha256: string; sourceSha256: string; resourceManifestSha256: string;
4
+ decoderSha256?: string; dependencies: Record<string, string>; fingerprint: string;
5
+ }
6
+ export function buildIdentity(root: string): BuildIdentity;
@@ -0,0 +1,63 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
3
+ import { createRequire } from 'node:module'
4
+ import path from 'node:path'
5
+
6
+ const hash = bytes => createHash('sha256').update(bytes).digest('hex')
7
+ const read = file => JSON.parse(readFileSync(file, 'utf8'))
8
+ function collect(root, directories, prefix = '', sources = false) {
9
+ const rows = []
10
+ function walk(directory) {
11
+ if (!existsSync(directory)) return
12
+ for (const entry of readdirSync(directory, { withFileTypes: true })) {
13
+ const file = path.join(directory, entry.name)
14
+ if (entry.isDirectory()) walk(file)
15
+ else if (entry.isFile() && (sources ? /\.(?:ts|mts|mjs)$/.test(file) : /\.(?:js|mjs)$/.test(file)))
16
+ rows.push(prefix + path.relative(root, file).split(path.sep).join('/') + '\0' + hash(readFileSync(file)))
17
+ }
18
+ }
19
+ for (const directory of directories) walk(path.join(root, directory))
20
+ return rows
21
+ }
22
+
23
+ /** Deterministic code/resource identity; timestamps and installation paths are excluded. */
24
+ export function buildIdentity(root) {
25
+ const manifest = read(path.join(root, 'package.json'))
26
+ const directories = ['src', 'service', 'protocol', 'mcp', 'shared']
27
+ const development = !!manifest.documentService
28
+ const rows = collect(root, directories, '', development)
29
+ if (development) {
30
+ const require = createRequire(path.join(root, 'package.json'))
31
+ const sharedRoot = path.dirname(require.resolve('@xdtrace/document-service-tooling/client'))
32
+ rows.push(...collect(sharedRoot, ['.'], 'tooling/', true))
33
+ for (const spec of manifest.documentService.sharedSources || []) {
34
+ let directory = path.dirname(require.resolve(spec.package + '/' + spec.entry))
35
+ while (directory !== path.dirname(directory)) {
36
+ const file = path.join(directory, 'package.json')
37
+ if (existsSync(file) && read(file).name === spec.package) break
38
+ directory = path.dirname(directory)
39
+ }
40
+ for (const entry of spec.files) {
41
+ if (entry.endsWith('.ts')) rows.push(spec.package + '/' + entry + '\0' + hash(readFileSync(path.join(directory, entry))))
42
+ else rows.push(...collect(directory, [entry], spec.package + '/', true))
43
+ }
44
+ }
45
+ }
46
+ const lockFile = path.join(root, 'package-lock.json')
47
+ const lock = existsSync(lockFile) ? read(lockFile) : undefined
48
+ const dependencies = Object.fromEntries(Object.keys(manifest.dependencies).sort().map(name =>
49
+ [name, lock?.packages?.['node_modules/' + name]?.version || manifest.dependencies[name]]))
50
+ const sourceRoot = existsSync(path.join(root, 'source', 'package.json')) ? path.join(root, 'source') : root
51
+ const sourceRows = development ? rows : collect(sourceRoot, directories, '', true)
52
+ const files = ['assets/fonts/sources.json', 'assets/fonts/manifest.json', 'assets/fonts/substitutions.json', 'requirements.txt']
53
+ const resourceRows = files.filter(file => existsSync(path.join(root, file))).map(file => file + '\0' + hash(readFileSync(path.join(root, file))))
54
+ const decoder = path.join(root, 'vendor/libredwg/libredwg-web.wasm')
55
+ const value = {
56
+ format: 'DocumentService.BuildIdentity', version: 1, packageName: manifest.name, packageVersion: manifest.version,
57
+ codeSha256: hash(rows.sort().join('\n')), sourceSha256: hash(sourceRows.sort().join('\n')),
58
+ resourceManifestSha256: hash(resourceRows.sort().join('\n')),
59
+ decoderSha256: existsSync(decoder) ? hash(readFileSync(decoder)) : undefined,
60
+ dependencies,
61
+ }
62
+ return { ...value, fingerprint: hash(JSON.stringify(value)) }
63
+ }
@@ -12,6 +12,7 @@ export interface DocumentClient {
12
12
  submitBundle?(bundle: unknown, identity?: Identity): Promise<JobReceipt>;
13
13
  job(id: string, signal?: AbortSignal): Promise<JobReceipt>;
14
14
  cancel(id: string): Promise<any>; owner(id: string): Promise<any>; cancelOwner(id: string): Promise<any>;
15
+ consume(id: string, receipt: unknown): Promise<{ id: string; consumedAt: string }>;
15
16
  artifact(id: string, name: string): Promise<ArtifactReceipt>;
16
17
  close(): Promise<void>;
17
18
  }
package/shared/client.mjs CHANGED
@@ -74,6 +74,15 @@ export function createDocumentClient({ url, token, timeoutMs = 180000 }, { engin
74
74
  cancel: id => json('/v1/jobs/' + uuid.parse(id), { method: 'DELETE' }),
75
75
  owner: id => json('/v1/owners/' + uuid.parse(id)),
76
76
  cancelOwner: id => json('/v1/owners/' + uuid.parse(id), { method: 'DELETE' }),
77
+ async consume(id, receipt) {
78
+ const expected = uuid.parse(id)
79
+ const acknowledgement = await json('/v1/jobs/' + expected + '/consumed', {
80
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(receipt),
81
+ })
82
+ if (acknowledgement.id !== expected || !Number.isFinite(Date.parse(acknowledgement.consumedAt)))
83
+ throw serviceError('PROVENANCE', 'Consumption acknowledgement differs from the submitted job')
84
+ return acknowledgement
85
+ },
77
86
  async artifact(id, name) {
78
87
  if (!/^[a-zA-Z0-9_.-]{1,200}$/.test(name)) throw serviceError('INVALID_ARTIFACT', 'Invalid artifact name')
79
88
  const job = await api.job(id)
@@ -1,6 +1,7 @@
1
1
  import type { McpOptions } from './mcp.mjs'
2
2
  export function runDocumentCommand(config: {
3
3
  engine: string;
4
+ defaultPorts?: { serve?: number; mcp?: number };
4
5
  startMcp(options: McpOptions): Promise<{close(): Promise<void>; address?: string}>;
5
6
  serve(options: McpOptions): Promise<{close(): Promise<void>; address?: string}>;
6
7
  doctor(options: McpOptions): Promise<any>;