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
@@ -0,0 +1,148 @@
1
+ import { existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { atomicJson, checkedId, directoryBytes, idPattern, removeJob, StorageError, } from "./files.js";
4
+ import { DownloadLeases } from "./downloads.js";
5
+ import { sweepProcessTemporary } from "./process-temp.js";
6
+ import { consumptionHash } from "./consumption.js";
7
+ export const DEFAULT_RETENTION_MS = 2 * 86400000;
8
+ /** One cleanup algorithm for both services; persistent tombstones also resume partial deletions. */
9
+ export class JobRetention {
10
+ context;
11
+ downloads = new DownloadLeases();
12
+ constructor(context) {
13
+ this.context = context;
14
+ }
15
+ protected(id) {
16
+ return this.context.running(id) || this.downloads.has(id);
17
+ }
18
+ checkedConsumption(job) {
19
+ if (job.consumed &&
20
+ (!Number.isFinite(Date.parse(job.consumed.at)) ||
21
+ job.consumed.sha256 !== consumptionHash(this.context.consumption(job))))
22
+ throw new StorageError('CONSUMPTION_CHANGED', '已保存消费回执与任务记录不一致', 409);
23
+ return job.consumed;
24
+ }
25
+ consume(id, raw) {
26
+ checkedId(id);
27
+ const { data, jobs } = this.context, sha256 = consumptionHash(raw);
28
+ const marker = path.join(data, '.retired', id + '.json');
29
+ if (existsSync(marker)) {
30
+ if (lstatSync(marker).isSymbolicLink())
31
+ throw new StorageError('STORAGE_LINK', '回收凭据包含链接');
32
+ const retired = JSON.parse(readFileSync(marker, 'utf8'));
33
+ if (retired.id !== id ||
34
+ retired.consumed?.sha256 !== sha256 ||
35
+ !Number.isFinite(Date.parse(retired.consumed?.at)))
36
+ throw new StorageError('CONSUMPTION_CONFLICT', '消费回执与已回收成果不一致', 409);
37
+ return { id, consumedAt: retired.consumed.at };
38
+ }
39
+ const job = jobs.get(id);
40
+ if (!job)
41
+ throw new StorageError('NOT_FOUND', '任务不存在', 404);
42
+ if (!job.endedAt || ['queued', 'running'].includes(job.status) || this.context.running(id))
43
+ throw new StorageError('CONSUMPTION_PENDING', '任务仍在执行,请在成果保存后提交回执', 409);
44
+ if (consumptionHash(this.context.consumption(job)) !== sha256)
45
+ throw new StorageError('CONSUMPTION_CONFLICT', '消费回执与终态成果不一致', 409);
46
+ const consumed = this.checkedConsumption(job) ?? { at: new Date().toISOString(), sha256 };
47
+ // Persist before acknowledging; a disk failure leaves the original job available for download.
48
+ if (!job.consumed) {
49
+ atomicJson(path.join(data, id, 'job.json'), { ...job, consumed });
50
+ job.consumed = consumed;
51
+ }
52
+ this.cleanup();
53
+ return { id, consumedAt: consumed.at };
54
+ }
55
+ cleanup(now = Date.now()) {
56
+ const { data, jobs, options, warn } = this.context, removed = [];
57
+ for (const job of jobs.values()) {
58
+ if (['queued', 'running'].includes(job.status) || this.protected(job.id))
59
+ continue;
60
+ for (const workspace of this.context.temporaryWorkspaces?.(job) ?? [
61
+ path.join(data, job.id),
62
+ ]) {
63
+ try {
64
+ sweepProcessTemporary(workspace, (_id, error) => warn(job.id, error));
65
+ }
66
+ catch (error) {
67
+ warn(job.id, error);
68
+ }
69
+ }
70
+ }
71
+ const markerRoot = path.join(data, '.retired');
72
+ const remove = (id) => {
73
+ const directory = path.join(data, checkedId(id));
74
+ if (existsSync(directory))
75
+ removeJob(data, id);
76
+ jobs.delete(id);
77
+ removed.push(id);
78
+ };
79
+ // A previous rm may have removed job.json before failing. The tombstone is sufficient ownership.
80
+ try {
81
+ for (const name of readdirSync(markerRoot)) {
82
+ const id = name.slice(0, -5);
83
+ if (!name.endsWith('.json') ||
84
+ !idPattern.test(id) ||
85
+ this.protected(id) ||
86
+ !existsSync(path.join(data, id)))
87
+ continue;
88
+ try {
89
+ const file = path.join(markerRoot, name);
90
+ if (lstatSync(file).isSymbolicLink() || JSON.parse(readFileSync(file, 'utf8')).id !== id)
91
+ continue;
92
+ remove(id);
93
+ }
94
+ catch (error) {
95
+ warn(id, error);
96
+ }
97
+ }
98
+ }
99
+ catch (error) {
100
+ warn('.retired', error);
101
+ }
102
+ let bytes;
103
+ if (options.maxStorageBytes) {
104
+ try {
105
+ bytes = directoryBytes(data);
106
+ }
107
+ catch (error) {
108
+ warn('.', error);
109
+ }
110
+ }
111
+ const candidates = [...jobs.values()]
112
+ .filter((job) => ['succeeded', 'failed', 'cancelled', 'interrupted'].includes(job.status) &&
113
+ !this.protected(job.id) &&
114
+ job.endedAt &&
115
+ Number.isFinite(Date.parse(job.endedAt)) &&
116
+ (job.consumed || now - Date.parse(job.endedAt) >= (options.downloadGraceMs ?? 3600000)))
117
+ .sort((a, b) => a.endedAt.localeCompare(b.endedAt));
118
+ for (const job of candidates) {
119
+ try {
120
+ this.checkedConsumption(job);
121
+ }
122
+ catch (error) {
123
+ warn(job.id, error);
124
+ continue;
125
+ }
126
+ const expired = now - Date.parse(job.endedAt) >= (options.retentionMs ?? DEFAULT_RETENTION_MS);
127
+ if (!job.consumed &&
128
+ !expired &&
129
+ !(options.maxStorageBytes && bytes !== undefined && bytes > options.maxStorageBytes))
130
+ continue;
131
+ try {
132
+ directoryBytes(path.join(data, job.id));
133
+ atomicJson(path.join(markerRoot, job.id + '.json'), {
134
+ ...this.context.receipt(job, now),
135
+ consumed: job.consumed,
136
+ });
137
+ remove(job.id);
138
+ // A removed source link may still be retained by another job or document.
139
+ if (bytes !== undefined)
140
+ bytes = directoryBytes(data);
141
+ }
142
+ catch (error) {
143
+ warn(job.id, error);
144
+ }
145
+ }
146
+ return { removed };
147
+ }
148
+ }
@@ -0,0 +1,15 @@
1
+ /** Durable ownership for a UUID directory before its commit receipt exists. */
2
+ export declare class StagedDirectories {
3
+ private root;
4
+ private markers;
5
+ private receipt;
6
+ private warn;
7
+ private active;
8
+ constructor(root: string, markers: string, receipt: string | undefined, warn: (id: string, error: unknown) => void);
9
+ begin(id: string): {
10
+ retire: () => void;
11
+ commit: () => void;
12
+ close: () => void;
13
+ };
14
+ cleanup(readyOnly?: boolean): void;
15
+ }
@@ -0,0 +1,116 @@
1
+ import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { atomicJson, checkedId, dataRoot, idPattern, removeJob, StorageError } from "./files.js";
4
+ function identity(folder) {
5
+ const stat = lstatSync(folder, { bigint: true });
6
+ if (stat.isSymbolicLink() || !stat.isDirectory())
7
+ throw new StorageError('STORAGE_LINK', '待提交路径需要普通目录');
8
+ return `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
9
+ }
10
+ /** Durable ownership for a UUID directory before its commit receipt exists. */
11
+ export class StagedDirectories {
12
+ root;
13
+ markers;
14
+ receipt;
15
+ warn;
16
+ active = new Set();
17
+ constructor(root, markers, receipt, warn) {
18
+ this.root = root;
19
+ this.markers = markers;
20
+ this.receipt = receipt;
21
+ this.warn = warn;
22
+ this.root = dataRoot(root);
23
+ this.markers = dataRoot(markers);
24
+ }
25
+ begin(id) {
26
+ checkedId(id);
27
+ const folder = path.join(this.root, id), marker = path.join(this.markers, id + '.json');
28
+ if (existsSync(folder) || existsSync(marker))
29
+ throw new StorageError('STORAGE_CONFLICT', '待提交目录已存在,请检查存储诊断', 409);
30
+ atomicJson(marker, { id });
31
+ this.active.add(id);
32
+ let owned;
33
+ try {
34
+ mkdirSync(folder);
35
+ owned = identity(folder);
36
+ atomicJson(marker, { id, identity: owned });
37
+ }
38
+ catch (error) {
39
+ this.active.delete(id);
40
+ try {
41
+ if (owned && identity(folder) === owned)
42
+ removeJob(this.root, id);
43
+ if (!existsSync(folder))
44
+ rmSync(marker, { force: true });
45
+ }
46
+ catch (cleanupError) {
47
+ this.warn(id, cleanupError);
48
+ }
49
+ this.warn(id, error);
50
+ throw error;
51
+ }
52
+ let committed = false;
53
+ return {
54
+ retire: () => {
55
+ atomicJson(marker, { id, identity: owned, cleanupReady: true });
56
+ },
57
+ commit: () => {
58
+ committed = true;
59
+ },
60
+ close: () => {
61
+ this.active.delete(id);
62
+ try {
63
+ if (existsSync(folder) && identity(folder) !== owned)
64
+ throw new StorageError('STORAGE_CHANGED', '待提交目录身份已变化');
65
+ if (!committed && existsSync(folder))
66
+ removeJob(this.root, id);
67
+ rmSync(marker, { force: true });
68
+ }
69
+ catch (error) {
70
+ this.warn(id, error);
71
+ }
72
+ },
73
+ };
74
+ }
75
+ cleanup(readyOnly = false) {
76
+ let names;
77
+ try {
78
+ names = readdirSync(this.markers);
79
+ }
80
+ catch (error) {
81
+ this.warn('.', error);
82
+ return;
83
+ }
84
+ for (const name of names) {
85
+ const id = name.slice(0, -5);
86
+ if (!name.endsWith('.json') || !idPattern.test(id) || this.active.has(id))
87
+ continue;
88
+ try {
89
+ const marker = path.join(this.markers, name), folder = path.join(this.root, id);
90
+ if (lstatSync(marker).isSymbolicLink())
91
+ throw new StorageError('STORAGE_LINK', '待提交凭据包含链接');
92
+ const owner = JSON.parse(readFileSync(marker, 'utf8'));
93
+ if (readyOnly && owner.cleanupReady !== true)
94
+ continue;
95
+ if (owner.id !== id)
96
+ throw new StorageError('STORAGE_CHANGED', '待提交目录的拥有者凭据无效');
97
+ if (existsSync(folder)) {
98
+ const receipt = this.receipt && path.join(folder, this.receipt);
99
+ if (identity(folder) !== owner.identity)
100
+ throw new StorageError('STORAGE_CHANGED', '待提交目录身份已变化');
101
+ if (receipt && existsSync(receipt)) {
102
+ if (lstatSync(receipt).isSymbolicLink() ||
103
+ JSON.parse(readFileSync(receipt, 'utf8')).id !== id)
104
+ throw new StorageError('STORAGE_CHANGED', '提交记录与目录身份不一致');
105
+ }
106
+ else
107
+ removeJob(this.root, id);
108
+ }
109
+ rmSync(marker);
110
+ }
111
+ catch (error) {
112
+ this.warn(id, error);
113
+ }
114
+ }
115
+ }
116
+ }
package/source/README.md CHANGED
@@ -1,5 +1,3 @@
1
1
  # Corresponding source
2
2
 
3
- AGPL-3.0-or-later. The parent directory contains Python scripts, fonts and their licenses, and (ReCAD) the modified LibreDWG source archive, patches and rebuild recipe under vendor/libredwg. The shared JavaScript in this source tree is also editable source.
4
-
5
- In a writable extracted copy of this package, run `cd source`, `npm install --ignore-scripts`, and `node rebuild.mjs` to compile the TypeScript and replace the parent runtime. Node >=24.13.0 is required. Third-party dependency sources are identified in ../THIRD_PARTY_NOTICES.md.
3
+ In this writable source directory run `npm install --ignore-scripts` and `node rebuild.mjs` with Node >=24.13.0. Runtime assets and licenses are in the parent package. Shared sources are included in `shared/`.
@@ -3,6 +3,7 @@ import { requestSchema, CAD_INPUT_LIMITS } from '../protocol/src/contracts.ts'
3
3
  import { CAD_BUNDLE_LIMITS } from '../protocol/src/bundle.ts'
4
4
  import { createRecadClient } from '../protocol/src/client.ts'
5
5
  import { recadOptions } from '../service/options.ts'
6
+ import { getRecadBuildInfo } from '../src/build-info.ts'
6
7
  export type { McpOptions } from '../shared/mcp.mjs'
7
8
 
8
9
  export async function startRecadMcp(options: McpOptions = {}): Promise<McpHandle> {
@@ -10,6 +11,6 @@ export async function startRecadMcp(options: McpOptions = {}): Promise<McpHandle
10
11
  const backend = options.backend === 'remote'
11
12
  ? createRecadClient({ url: options.url || '', token: options.backendToken, timeoutMs: options.timeoutMs })
12
13
  : (await import('../src/runtime/index.ts')).createRecadRuntime(await recadOptions(options))
13
- try { return await startDocumentMcp({ ...options, engine: 'recad', version: '0.1.0', requestSchema, inputBytes: CAD_INPUT_LIMITS.inputBytes, bundleBytes: CAD_BUNDLE_LIMITS.bodyBytes, backend }) }
14
+ try { return await startDocumentMcp({ ...options, engine: 'recad', version: getRecadBuildInfo().packageVersion, requestSchema, inputBytes: CAD_INPUT_LIMITS.inputBytes, bundleBytes: CAD_BUNDLE_LIMITS.bodyBytes, backend }) }
14
15
  catch (error) { await backend.close(); throw error }
15
16
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zelos-recad",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-or-later",
@@ -18,7 +18,9 @@
18
18
  "./protocol/resource-manifest": "./protocol/src/resource-manifest.ts",
19
19
  "./client": "./protocol/src/client.ts",
20
20
  "./mcp": "./mcp/index.ts",
21
- "./setup": "./src/setup.ts"
21
+ "./setup": "./src/setup.ts",
22
+ "./conversion": "./src/conversion.ts",
23
+ "./assets": "./src/assets.ts"
22
24
  },
23
25
  "dependencies": {
24
26
  "@mlightcad/data-model": "1.15.2",
@@ -70,13 +70,20 @@ export const requestSchema = z.discriminatedUnion('operation', [
70
70
  })
71
71
  .strict(),
72
72
  z.object({ operation: z.literal('readback') }).strict(),
73
+ z.object({ operation: z.literal('source-records'), layout:z.string().min(1).max(256).optional() }).strict(),
73
74
  z
74
- .object({ operation: z.literal('scene'), layout: z.string().min(1).max(256).optional() })
75
+ .object({
76
+ operation: z.literal('scene'),
77
+ layout: z.string().min(1).max(256).optional(),
78
+ sheetMode: z.enum(['auto', 'single']).optional(),
79
+ textGeometry: z.boolean().optional(),
80
+ fontResources: z.boolean().optional(),
81
+ })
75
82
  .strict(),
76
83
  z
77
84
  .object({
78
85
  operation: z.literal('render'),
79
- print: renderSchema,
86
+ print: z.union([renderSchema, z.literal('auto')]),
80
87
  layout: z.string().min(1).max(256).optional(),
81
88
  })
82
89
  .strict(),
@@ -126,10 +133,15 @@ export const resourceSchema = z
126
133
 
127
134
  export const capabilities = {
128
135
  format: 'XDTrace.RecadCapabilities',
129
- version: 30,
136
+ version: 34,
130
137
  layouts: { version: 1, selection: true, planarRectangularViewports: true },
131
- sourceScene: { version: 1, coordinates: 'cad-world-y-up-v1', sheetPolicy: 1 },
132
- nativeEvidence: { version: 1, operation: 'scene', xdata: 'registered-apps', snapshot: 'before-print-adapters' },
138
+ sourceScene: { version: 1, coordinates: 'cad-world-y-up-v1', sheetPolicy: 1, sheetModes: ['auto', 'single'], textGeometry: 1, fontResources: 1 },
139
+ nativeEvidence: {
140
+ version: 1,
141
+ operation: 'scene',
142
+ xdata: 'registered-apps',
143
+ snapshot: 'before-print-adapters',
144
+ },
133
145
  documentUploads: { version: 1, streaming: true, reuse: true },
134
146
  limits: CAD_INPUT_LIMITS,
135
147
  dwgDxfFallback: {
@@ -139,11 +151,11 @@ export const capabilities = {
139
151
  sourceHashBinding: true,
140
152
  },
141
153
  maturity: 'experimental',
142
- operations: ['inspect', 'render', 'readback', 'scene', 'layouts'],
154
+ operations: ['inspect', 'render', 'readback', 'scene', 'layouts', 'source-records'],
143
155
  input: ['dwg', 'ascii-dxf', 'binary-dxf-8bit-groups', 'binary-dxf-16bit-groups'],
144
156
  output: ['pdf', 'png', 'readback-json', 'source-scene-json'],
145
157
  layout: 'Model (default); named paper layouts via layout selection',
146
- rendering: ['fit-window', 'fixed-scale'],
158
+ rendering: ['fit-window', 'fixed-scale', 'auto-overview'],
147
159
  printPlanVersion: 1,
148
160
  colorModes: ['monochrome', 'source'],
149
161
  minimumDpi: 300,
@@ -159,6 +171,7 @@ export const capabilities = {
159
171
  '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',
160
172
  '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',
161
173
  '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',
174
+ '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',
162
175
  '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',
163
176
  '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',
164
177
  '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',
@@ -50,8 +50,29 @@ export interface CadNativeRecord {
50
50
  xdataStatus: 'registered-apps-read' | 'partial'
51
51
  }
52
52
 
53
+ export interface CadPointDictionaryEvidence {
54
+ format: 'XDTrace.NativePointDictionaryEvidence/1'
55
+ sourceSha256: string
56
+ pointHandle: string
57
+ dictionaryHandles: string[]
58
+ semanticStatus: 'uninterpreted'
59
+ recordsJson: string
60
+ sha256: string
61
+ }
62
+
53
63
  export interface CadNativeDocument {
54
64
  sourceSha256: string
65
+ /** A large scene may carry the complete referenced-block closure instead of unused definitions. */
66
+ selection?: {
67
+ basis: 'scene-referenced-block-closure'
68
+ parsedRecords: number
69
+ parsedBlocks: number
70
+ excludedRecords: number
71
+ excludedBlocks: number
72
+ }
73
+ /** Non-graphical application records, including raw payloads and interpretation state. */
74
+ applicationObjects?: unknown[]
75
+ pointDictionaries?: CadPointDictionaryEvidence[]
55
76
  records: CadNativeRecord[]
56
77
  blocks: { id: string; handle: string; name: string; space: CadNativeRecord['space'] }[]
57
78
  coverage: {
@@ -1,8 +1,9 @@
1
1
  import { spawnSync } from 'node:child_process'
2
2
  import { createRequire } from 'node:module'
3
- import { cpSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
3
+ import { cpSync, existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
4
4
  import { fileURLToPath } from 'node:url'
5
5
  import path from 'node:path'
6
+ import { buildIdentity } from './shared/build-identity.mjs'
6
7
 
7
8
  // Run in a writable extracted copy of the package: cd source; npm install --ignore-scripts; node rebuild.mjs
8
9
  const source = path.dirname(fileURLToPath(import.meta.url)), packageRoot = path.dirname(source)
@@ -10,8 +11,14 @@ const require = createRequire(path.join(source, 'package.json'))
10
11
  const result = spawnSync(process.execPath, [require.resolve('typescript/bin/tsc'), '-p', path.join(source, 'tsconfig.json')], { cwd: source, windowsHide: true, stdio: 'inherit' })
11
12
  if (result.error) throw result.error
12
13
  if (result.status !== 0) process.exit(result.status ?? 1)
13
- for (const name of ['src', 'service', 'protocol', 'mcp']) cpSync(path.join(source, 'compiled', name), path.join(packageRoot, name), { recursive: true })
14
- cpSync(path.join(source, 'shared'), path.join(packageRoot, 'shared'), { recursive: true })
14
+ for (const name of ['src', 'service', 'protocol', 'mcp', 'shared']) {
15
+ const compiled = path.join(source, 'compiled', name)
16
+ if (existsSync(compiled)) cpSync(compiled, path.join(packageRoot, name), { recursive: true })
17
+ }
18
+ cpSync(path.join(source, 'shared'), path.join(packageRoot, 'shared'), {
19
+ recursive: true,
20
+ filter: file => !file.endsWith('.ts') || file.endsWith('.d.mts'),
21
+ })
15
22
  function rewrite(directory) {
16
23
  for (const item of readdirSync(directory, { withFileTypes: true })) {
17
24
  const file = path.join(directory, item.name)
@@ -19,5 +26,6 @@ function rewrite(directory) {
19
26
  else if (file.endsWith('.d.ts')) writeFileSync(file, readFileSync(file, 'utf8').replace(/((?:from\s+|import\s*\(\s*)['"])(\.[^'"]+)\.ts(['"])/g, '$1$2.js$3'))
20
27
  }
21
28
  }
22
- for (const name of ['src', 'service', 'protocol', 'mcp']) rewrite(path.join(packageRoot, name))
29
+ for (const name of ['src', 'service', 'protocol', 'mcp', 'shared']) rewrite(path.join(packageRoot, name))
30
+ writeFileSync(path.join(packageRoot, 'build-info.json'), JSON.stringify(buildIdentity(packageRoot), null, 2) + '\n')
23
31
  console.log('Rebuilt package runtime from the included source.')
@@ -94,9 +94,13 @@ export function createRecadApp(options: ServiceOptions) {
94
94
  )
95
95
  app.get('/v1/jobs/:id/artifacts/:name', async (request, reply) => {
96
96
  const { id, name } = request.params as { id: string; name: string }
97
- const artifact = runtime.artifact(id, name)
98
- return reply.type(artifact.contentType).send(artifact.buffer)
97
+ const artifact = await runtime.streamArtifact(id, name)
98
+ return reply.header('Content-Length', artifact.bytes).header('X-Content-SHA256', artifact.sha256)
99
+ .type(artifact.contentType).send(artifact.stream)
99
100
  })
101
+ app.post('/v1/jobs/:id/consumed', { bodyLimit: 2 * 1024 * 1024 }, async request =>
102
+ runtime.consume((request.params as { id: string }).id, request.body),
103
+ )
100
104
  app.setErrorHandler((error: any, _request, reply) => {
101
105
  const status =
102
106
  error.code === 'NOT_FOUND'
@@ -5,8 +5,9 @@ import { indexFontDirectory } from '../src/runtime/font-catalog.ts'
5
5
  import { runtimePython } from '../src/runtime-paths.ts'
6
6
  import { prepareRecadRuntime } from '../src/setup.ts'
7
7
  import type { RuntimeOptions } from '../src/runtime/index.ts'
8
+ import { recadStorageOptions, type StorageSettings } from '../src/runtime/storage-policy.ts'
8
9
 
9
- export async function recadOptions(options: Partial<RuntimeOptions> = {}, prepare = true): Promise<RuntimeOptions> {
10
+ export async function recadOptions(options: Partial<RuntimeOptions> & StorageSettings = {}, prepare = true): Promise<RuntimeOptions> {
10
11
  const data = path.resolve(options.data || process.env.RECAD_DATA_DIR || envPaths('recad', { suffix: '' }).data)
11
12
  const python = prepare ? (await prepareRecadRuntime({ python: options.python })).python : options.python || runtimePython()
12
13
  const resources = options.resources || process.env.RECAD_RESOURCES || path.join(data, 'resources/manifest.json')
@@ -14,7 +15,7 @@ export async function recadOptions(options: Partial<RuntimeOptions> = {}, prepar
14
15
  if (process.env.RECAD_BASE_FONTS && !['0', '1'].includes(process.env.RECAD_BASE_FONTS)) throw new Error('RECAD_BASE_FONTS must be 0 or 1')
15
16
  if (process.env.RECAD_MISSING_TEXT && !['strict', 'noto-sans-sc', 'best-effort'].includes(process.env.RECAD_MISSING_TEXT)) 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 as RuntimeOptions['missingText'],
@@ -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
  }
@@ -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>;