@studio8collective/patent-render 0.0.0-stage → 1.0.1
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 +26 -0
- package/LICENSE +9 -0
- package/README.md +246 -2
- package/dist/core.d.ts +1105 -0
- package/dist/core.js +1144 -0
- package/dist/core.js.map +1 -0
- package/dist/index.d.ts +1295 -0
- package/dist/index.js +6024 -0
- package/dist/index.js.map +1 -0
- package/dist/server-actions.d.ts +342 -0
- package/dist/server-actions.js +1150 -0
- package/dist/server-actions.js.map +1 -0
- package/dist/server.d.ts +414 -0
- package/dist/server.js +3238 -0
- package/dist/server.js.map +1 -0
- package/dist/theme.css +110 -0
- package/docs/nextjs.md +717 -0
- package/package.json +85 -4
package/dist/server.js
ADDED
|
@@ -0,0 +1,3238 @@
|
|
|
1
|
+
// ../../src/patent-render/server/handler.ts
|
|
2
|
+
import {
|
|
3
|
+
chat as chat2,
|
|
4
|
+
chatParamsFromRequest,
|
|
5
|
+
maxIterations,
|
|
6
|
+
toServerSentEventsResponse
|
|
7
|
+
} from "@tanstack/ai";
|
|
8
|
+
|
|
9
|
+
// ../../src/patent-render/server/llm.ts
|
|
10
|
+
import { createAnthropicChat } from "@tanstack/ai-anthropic";
|
|
11
|
+
import { createOpenaiChat } from "@tanstack/ai-openai";
|
|
12
|
+
import { createOpenRouterText } from "@tanstack/ai-openrouter";
|
|
13
|
+
var LLM_KEY_ENV = "PATENT_GFX_LLM_KEY";
|
|
14
|
+
var factories = {
|
|
15
|
+
anthropic: (model, apiKey) => createAnthropicChat(model, apiKey),
|
|
16
|
+
openai: (model, apiKey) => createOpenaiChat(model, apiKey),
|
|
17
|
+
openrouter: (model, apiKey) => createOpenRouterText(model, apiKey)
|
|
18
|
+
};
|
|
19
|
+
var DEFAULT_MODELS = {
|
|
20
|
+
anthropic: { drawer: "claude-opus-5-5", planner: "claude-sonnet-5-5", critic: "claude-sonnet-5-5" },
|
|
21
|
+
openai: { drawer: "gpt-6-sol", planner: "gpt-6-luna", critic: "gpt-6-luna" },
|
|
22
|
+
openrouter: {
|
|
23
|
+
drawer: "anthropic/claude-opus-5.5",
|
|
24
|
+
planner: "anthropic/claude-sonnet-5.5",
|
|
25
|
+
critic: "anthropic/claude-sonnet-5.5"
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
function detectKeyProvider(apiKey) {
|
|
29
|
+
if (apiKey.startsWith("sk-ant-")) return "anthropic";
|
|
30
|
+
if (apiKey.startsWith("sk-or-")) return "openrouter";
|
|
31
|
+
if (apiKey.startsWith("sk-")) return "openai";
|
|
32
|
+
return void 0;
|
|
33
|
+
}
|
|
34
|
+
function llmModels(config, env = process.env) {
|
|
35
|
+
const create = factories[config.provider];
|
|
36
|
+
if (!create) {
|
|
37
|
+
throw new Error(`Unknown LLM provider "${config.provider}". Use one of: ${Object.keys(factories).join(", ")}`);
|
|
38
|
+
}
|
|
39
|
+
const resolve = (role) => () => {
|
|
40
|
+
const apiKey = config.apiKey ?? env[LLM_KEY_ENV];
|
|
41
|
+
if (!apiKey) throw new Error(`${LLM_KEY_ENV} is not set (needed for ${config.provider})`);
|
|
42
|
+
const keyProvider = detectKeyProvider(apiKey);
|
|
43
|
+
if (keyProvider && keyProvider !== config.provider) {
|
|
44
|
+
throw new Error(
|
|
45
|
+
`${LLM_KEY_ENV} looks like an ${keyProvider} key, but the route uses provider "${config.provider}". Use a ${config.provider} key, or switch the route to provider "${keyProvider}".`
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
return create(config[role] ?? DEFAULT_MODELS[config.provider][role], apiKey);
|
|
49
|
+
};
|
|
50
|
+
return { drawer: resolve("drawer"), planner: resolve("planner"), critic: resolve("critic") };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// ../../src/patent-render/schema/document.ts
|
|
54
|
+
import { z } from "zod";
|
|
55
|
+
function vec(n2) {
|
|
56
|
+
return z.array(z.number()).length(n2);
|
|
57
|
+
}
|
|
58
|
+
var Point = vec(2);
|
|
59
|
+
var StrokeStyle = z.enum(["solid", "dashed", "centre", "phantom"]);
|
|
60
|
+
var Stroke = z.object({
|
|
61
|
+
width: z.number().positive().default(0.35),
|
|
62
|
+
style: StrokeStyle.default("solid")
|
|
63
|
+
});
|
|
64
|
+
var Fill = z.enum(["none", "black", "white"]);
|
|
65
|
+
var base = {
|
|
66
|
+
id: z.string().min(1),
|
|
67
|
+
name: z.string().optional(),
|
|
68
|
+
/** Degrees, clockwise, about the item's bounding-box centre. */
|
|
69
|
+
rotation: z.number().default(0),
|
|
70
|
+
locked: z.boolean().default(false),
|
|
71
|
+
hidden: z.boolean().default(false)
|
|
72
|
+
};
|
|
73
|
+
var stroked = { stroke: Stroke.default({ width: 0.35, style: "solid" }) };
|
|
74
|
+
var LineItem = z.object({ ...base, ...stroked, type: z.literal("line"), a: Point, b: Point });
|
|
75
|
+
var PolylineItem = z.object({
|
|
76
|
+
...base,
|
|
77
|
+
...stroked,
|
|
78
|
+
type: z.literal("polyline"),
|
|
79
|
+
points: z.array(Point).min(2),
|
|
80
|
+
closed: z.boolean().default(false),
|
|
81
|
+
fill: Fill.default("none")
|
|
82
|
+
});
|
|
83
|
+
var PathItem = z.object({ ...base, ...stroked, type: z.literal("path"), d: z.string().min(1), fill: Fill.default("none") });
|
|
84
|
+
var RectItem = z.object({
|
|
85
|
+
...base,
|
|
86
|
+
...stroked,
|
|
87
|
+
type: z.literal("rect"),
|
|
88
|
+
x: z.number(),
|
|
89
|
+
y: z.number(),
|
|
90
|
+
w: z.number().positive(),
|
|
91
|
+
h: z.number().positive(),
|
|
92
|
+
radius: z.number().min(0).default(0),
|
|
93
|
+
fill: Fill.default("none")
|
|
94
|
+
});
|
|
95
|
+
var EllipseItem = z.object({
|
|
96
|
+
...base,
|
|
97
|
+
...stroked,
|
|
98
|
+
type: z.literal("ellipse"),
|
|
99
|
+
cx: z.number(),
|
|
100
|
+
cy: z.number(),
|
|
101
|
+
rx: z.number().positive(),
|
|
102
|
+
ry: z.number().positive(),
|
|
103
|
+
fill: Fill.default("none")
|
|
104
|
+
});
|
|
105
|
+
var ArcItem = z.object({
|
|
106
|
+
...base,
|
|
107
|
+
...stroked,
|
|
108
|
+
type: z.literal("arc"),
|
|
109
|
+
cx: z.number(),
|
|
110
|
+
cy: z.number(),
|
|
111
|
+
r: z.number().positive(),
|
|
112
|
+
/** Degrees, 0 = +x axis, clockwise (SVG convention). */
|
|
113
|
+
start: z.number(),
|
|
114
|
+
end: z.number()
|
|
115
|
+
});
|
|
116
|
+
var TextAnchor = z.enum(["start", "middle", "end"]);
|
|
117
|
+
var TextItem = z.object({
|
|
118
|
+
...base,
|
|
119
|
+
type: z.literal("text"),
|
|
120
|
+
x: z.number(),
|
|
121
|
+
y: z.number(),
|
|
122
|
+
text: z.string().min(1),
|
|
123
|
+
/** Cap height in mm. */
|
|
124
|
+
size: z.number().positive().default(3.5),
|
|
125
|
+
anchor: TextAnchor.default("start")
|
|
126
|
+
});
|
|
127
|
+
var NumeralItem = z.object({
|
|
128
|
+
...base,
|
|
129
|
+
type: z.literal("numeral"),
|
|
130
|
+
/** Numeral text, e.g. "102" or "102a". Looked up in Document.numerals. */
|
|
131
|
+
n: z.string().regex(/^\d+[a-z']*$/i),
|
|
132
|
+
at: Point,
|
|
133
|
+
target: Point,
|
|
134
|
+
leader: z.enum(["straight", "curved", "none"]).default("curved"),
|
|
135
|
+
/** When true, numeral is underlined (refers to the whole assembly). */
|
|
136
|
+
underline: z.boolean().default(false),
|
|
137
|
+
size: z.number().positive().default(3.5)
|
|
138
|
+
});
|
|
139
|
+
var FigLabelItem = z.object({
|
|
140
|
+
...base,
|
|
141
|
+
type: z.literal("figLabel"),
|
|
142
|
+
x: z.number(),
|
|
143
|
+
y: z.number(),
|
|
144
|
+
size: z.number().positive().default(5)
|
|
145
|
+
});
|
|
146
|
+
var Side = z.enum(["top", "bottom", "left", "right"]);
|
|
147
|
+
var ConnectorEnd = z.union([
|
|
148
|
+
z.object({ itemId: z.string() }),
|
|
149
|
+
z.object({ point: Point })
|
|
150
|
+
]);
|
|
151
|
+
var ConnectorItem = z.object({
|
|
152
|
+
...base,
|
|
153
|
+
...stroked,
|
|
154
|
+
type: z.literal("connector"),
|
|
155
|
+
from: ConnectorEnd,
|
|
156
|
+
to: ConnectorEnd,
|
|
157
|
+
routing: z.enum(["straight", "orthogonal", "curved"]).default("orthogonal"),
|
|
158
|
+
/** Which side of an attached item the connector leaves/enters; auto when omitted. */
|
|
159
|
+
fromSide: Side.optional(),
|
|
160
|
+
toSide: Side.optional(),
|
|
161
|
+
arrow: z.enum(["none", "end", "start", "both"]).default("end"),
|
|
162
|
+
arrowStyle: z.enum(["filled", "open"]).default("filled"),
|
|
163
|
+
label: z.string().optional()
|
|
164
|
+
});
|
|
165
|
+
var HatchItem = z.object({
|
|
166
|
+
...base,
|
|
167
|
+
type: z.literal("hatch"),
|
|
168
|
+
points: z.array(Point).min(3),
|
|
169
|
+
angle: z.number().default(45),
|
|
170
|
+
spacing: z.number().positive().default(1.5),
|
|
171
|
+
lineWidth: z.number().positive().default(0.25)
|
|
172
|
+
});
|
|
173
|
+
var SectionLineItem = z.object({
|
|
174
|
+
...base,
|
|
175
|
+
...stroked,
|
|
176
|
+
type: z.literal("sectionLine"),
|
|
177
|
+
a: Point,
|
|
178
|
+
b: Point,
|
|
179
|
+
label: z.string().min(1).max(3)
|
|
180
|
+
});
|
|
181
|
+
var Item = z.discriminatedUnion("type", [
|
|
182
|
+
LineItem,
|
|
183
|
+
PolylineItem,
|
|
184
|
+
PathItem,
|
|
185
|
+
RectItem,
|
|
186
|
+
EllipseItem,
|
|
187
|
+
ArcItem,
|
|
188
|
+
TextItem,
|
|
189
|
+
NumeralItem,
|
|
190
|
+
FigLabelItem,
|
|
191
|
+
ConnectorItem,
|
|
192
|
+
HatchItem,
|
|
193
|
+
SectionLineItem
|
|
194
|
+
]);
|
|
195
|
+
var Offset = z.object({ dx: z.number(), dy: z.number() });
|
|
196
|
+
var Layer = z.object({
|
|
197
|
+
id: z.string().min(1),
|
|
198
|
+
name: z.string().min(1),
|
|
199
|
+
visible: z.boolean().default(true),
|
|
200
|
+
locked: z.boolean().default(false),
|
|
201
|
+
/** Where this component moves to in the exploded view (mm). */
|
|
202
|
+
explode: Offset.optional(),
|
|
203
|
+
items: z.array(Item).default([])
|
|
204
|
+
});
|
|
205
|
+
var JurisdictionId = z.enum(["uspto", "pct", "epo", "ipo"]);
|
|
206
|
+
var SheetSize = z.enum(["a4", "letter"]);
|
|
207
|
+
var Sheet = z.object({
|
|
208
|
+
size: SheetSize.default("a4"),
|
|
209
|
+
orientation: z.enum(["portrait", "landscape"]).default("portrait")
|
|
210
|
+
});
|
|
211
|
+
var LetteringStyle = z.object({
|
|
212
|
+
numeralWeight: z.enum(["regular", "bold"]).default("regular"),
|
|
213
|
+
figLabel: z.enum(["sans-bold", "serif-italic"]).default("sans-bold")
|
|
214
|
+
});
|
|
215
|
+
var NumeralRegistry = z.record(z.string(), z.string());
|
|
216
|
+
var ChatTranscript = z.array(z.unknown());
|
|
217
|
+
var PatentDocument = z.object({
|
|
218
|
+
version: z.literal(1).default(1),
|
|
219
|
+
id: z.string().min(1),
|
|
220
|
+
figureNumber: z.string().min(1),
|
|
221
|
+
/** Patent office whose drawing rules apply. Defaults to India (IPO). */
|
|
222
|
+
jurisdiction: JurisdictionId.default("ipo"),
|
|
223
|
+
sheet: Sheet.default({ size: "a4", orientation: "portrait" }),
|
|
224
|
+
layers: z.array(Layer).default([]),
|
|
225
|
+
numerals: NumeralRegistry.default({}),
|
|
226
|
+
lettering: LetteringStyle.default({ numeralWeight: "regular", figLabel: "sans-bold" }),
|
|
227
|
+
/** Which view of the same model is shown and exported. */
|
|
228
|
+
view: z.enum(["composite", "exploded"]).default("composite"),
|
|
229
|
+
/** Exploded view: dash-dot alignment lines between separated components. */
|
|
230
|
+
explodeLines: z.boolean().default(true),
|
|
231
|
+
/** Sheet number shown top-centre inside the sight, e.g. "1/3" (37 CFR 1.84(t)). Set by the host. */
|
|
232
|
+
sheetLabel: z.string().max(12).optional(),
|
|
233
|
+
chat: ChatTranscript.default([])
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// ../../src/patent-render/schema/plan.ts
|
|
237
|
+
import { z as z2 } from "zod";
|
|
238
|
+
var FigureType = z2.enum([
|
|
239
|
+
"flowchart",
|
|
240
|
+
"blockDiagram",
|
|
241
|
+
"mechanical2d",
|
|
242
|
+
"uiScreen",
|
|
243
|
+
"perspective3d",
|
|
244
|
+
"circuit",
|
|
245
|
+
"chemical"
|
|
246
|
+
]);
|
|
247
|
+
var FigurePlan = z2.object({
|
|
248
|
+
figureType: FigureType,
|
|
249
|
+
/** e.g. "Cross-sectional view taken along line A-A of FIG. 2" */
|
|
250
|
+
view: z2.string(),
|
|
251
|
+
summary: z2.string(),
|
|
252
|
+
/**
|
|
253
|
+
* Full generation spec: overall form and proportions (mm), every component's
|
|
254
|
+
* shape, position and relationships, counts, surface details and what faces
|
|
255
|
+
* the viewer. Written so a draftsperson can draw without guessing.
|
|
256
|
+
*/
|
|
257
|
+
spec: z2.string().default(""),
|
|
258
|
+
components: z2.array(z2.object({
|
|
259
|
+
numeral: z2.string(),
|
|
260
|
+
name: z2.string(),
|
|
261
|
+
description: z2.string().optional(),
|
|
262
|
+
reused: z2.boolean().default(false)
|
|
263
|
+
// numeral came from the host registry
|
|
264
|
+
})),
|
|
265
|
+
layers: z2.array(z2.object({ id: z2.string(), name: z2.string() })),
|
|
266
|
+
notes: z2.array(z2.string()).default([])
|
|
267
|
+
});
|
|
268
|
+
var DrawingStyle = z2.enum(["standard", "detailed", "minimal"]);
|
|
269
|
+
var STYLE_LABEL = {
|
|
270
|
+
standard: { label: "Standard line art", hint: "Clean outlines and key details, as most filings" },
|
|
271
|
+
detailed: { label: "Detailed rendering", hint: "Shading strokes, glare, textures, fine features" },
|
|
272
|
+
minimal: { label: "Minimal outline", hint: "Essential outlines only, fewest lines" }
|
|
273
|
+
};
|
|
274
|
+
var GenerationPrefs = z2.object({
|
|
275
|
+
figureType: FigureType.optional(),
|
|
276
|
+
// undefined = let the planner decide
|
|
277
|
+
style: DrawingStyle.default("standard")
|
|
278
|
+
});
|
|
279
|
+
var FIGURE_TYPE_LABEL = {
|
|
280
|
+
flowchart: "Flowchart",
|
|
281
|
+
blockDiagram: "Block diagram",
|
|
282
|
+
mechanical2d: "Mechanical 2D",
|
|
283
|
+
uiScreen: "UI screen",
|
|
284
|
+
perspective3d: "Perspective 3D",
|
|
285
|
+
circuit: "Circuit",
|
|
286
|
+
chemical: "Chemical structure"
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
// ../../src/patent-render/schema/patch.ts
|
|
290
|
+
import { z as z3 } from "zod";
|
|
291
|
+
var ItemChanges = z3.record(z3.string(), z3.unknown());
|
|
292
|
+
var LayerChanges = Layer.omit({ id: true, items: true }).partial();
|
|
293
|
+
var Patch = z3.discriminatedUnion("op", [
|
|
294
|
+
z3.object({ op: z3.literal("addLayer"), layer: Layer, index: z3.number().int().optional() }),
|
|
295
|
+
z3.object({ op: z3.literal("updateLayer"), id: z3.string(), changes: LayerChanges }),
|
|
296
|
+
z3.object({ op: z3.literal("removeLayer"), id: z3.string() }),
|
|
297
|
+
z3.object({ op: z3.literal("moveLayer"), id: z3.string(), toIndex: z3.number().int() }),
|
|
298
|
+
z3.object({ op: z3.literal("addItem"), layerId: z3.string(), item: Item, index: z3.number().int().optional() }),
|
|
299
|
+
z3.object({ op: z3.literal("updateItem"), id: z3.string(), changes: ItemChanges }),
|
|
300
|
+
z3.object({ op: z3.literal("removeItem"), id: z3.string() }),
|
|
301
|
+
z3.object({ op: z3.literal("moveItem"), id: z3.string(), toLayerId: z3.string(), toIndex: z3.number().int().optional() }),
|
|
302
|
+
z3.object({ op: z3.literal("setNumeral"), n: z3.string(), label: z3.string().nullable() }),
|
|
303
|
+
z3.object({ op: z3.literal("setSheet"), sheet: Sheet }),
|
|
304
|
+
z3.object({ op: z3.literal("setJurisdiction"), jurisdiction: JurisdictionId }),
|
|
305
|
+
z3.object({ op: z3.literal("setLettering"), lettering: LetteringStyle }),
|
|
306
|
+
z3.object({ op: z3.literal("setView"), view: z3.enum(["composite", "exploded"]), explodeLines: z3.boolean().optional() }),
|
|
307
|
+
z3.object({ op: z3.literal("setSheetLabel"), sheetLabel: z3.string().max(12).nullable() }),
|
|
308
|
+
z3.object({ op: z3.literal("batch"), patches: z3.array(z3.lazy(() => Patch)) })
|
|
309
|
+
]);
|
|
310
|
+
var PatchError = class extends Error {
|
|
311
|
+
};
|
|
312
|
+
function findItem(doc, id) {
|
|
313
|
+
for (let li = 0; li < doc.layers.length; li++) {
|
|
314
|
+
const ii = doc.layers[li].items.findIndex((it) => it.id === id);
|
|
315
|
+
if (ii >= 0) return { layerIndex: li, itemIndex: ii, item: doc.layers[li].items[ii] };
|
|
316
|
+
}
|
|
317
|
+
return null;
|
|
318
|
+
}
|
|
319
|
+
function layerIndex(doc, id) {
|
|
320
|
+
const i = doc.layers.findIndex((l) => l.id === id);
|
|
321
|
+
if (i < 0) throw new PatchError(`Layer not found: ${id}`);
|
|
322
|
+
return i;
|
|
323
|
+
}
|
|
324
|
+
function clampIndex(i, len) {
|
|
325
|
+
if (i === void 0) return len;
|
|
326
|
+
return Math.max(0, Math.min(len, i));
|
|
327
|
+
}
|
|
328
|
+
function withLayers(doc, layers) {
|
|
329
|
+
return { ...doc, layers };
|
|
330
|
+
}
|
|
331
|
+
function replaceLayer(doc, i, layer) {
|
|
332
|
+
const layers = doc.layers.slice();
|
|
333
|
+
layers[i] = layer;
|
|
334
|
+
return withLayers(doc, layers);
|
|
335
|
+
}
|
|
336
|
+
function idExists(doc, id) {
|
|
337
|
+
return doc.layers.some((l) => l.id === id || l.items.some((it) => it.id === id));
|
|
338
|
+
}
|
|
339
|
+
function applyPatch(doc, patch) {
|
|
340
|
+
switch (patch.op) {
|
|
341
|
+
case "addLayer": {
|
|
342
|
+
if (idExists(doc, patch.layer.id)) throw new PatchError(`Duplicate id: ${patch.layer.id}`);
|
|
343
|
+
const layers = doc.layers.slice();
|
|
344
|
+
layers.splice(clampIndex(patch.index, layers.length), 0, patch.layer);
|
|
345
|
+
return { doc: withLayers(doc, layers), inverse: { op: "removeLayer", id: patch.layer.id } };
|
|
346
|
+
}
|
|
347
|
+
case "updateLayer": {
|
|
348
|
+
const i = layerIndex(doc, patch.id);
|
|
349
|
+
const prev = doc.layers[i];
|
|
350
|
+
const before = {};
|
|
351
|
+
for (const k of Object.keys(patch.changes)) before[k] = prev[k];
|
|
352
|
+
return {
|
|
353
|
+
doc: replaceLayer(doc, i, { ...prev, ...patch.changes }),
|
|
354
|
+
inverse: { op: "updateLayer", id: patch.id, changes: before }
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
case "removeLayer": {
|
|
358
|
+
const i = layerIndex(doc, patch.id);
|
|
359
|
+
const layers = doc.layers.slice();
|
|
360
|
+
const [removed] = layers.splice(i, 1);
|
|
361
|
+
return { doc: withLayers(doc, layers), inverse: { op: "addLayer", layer: removed, index: i } };
|
|
362
|
+
}
|
|
363
|
+
case "moveLayer": {
|
|
364
|
+
const from = layerIndex(doc, patch.id);
|
|
365
|
+
const layers = doc.layers.slice();
|
|
366
|
+
const [l] = layers.splice(from, 1);
|
|
367
|
+
const to = clampIndex(patch.toIndex, layers.length);
|
|
368
|
+
layers.splice(to, 0, l);
|
|
369
|
+
return { doc: withLayers(doc, layers), inverse: { op: "moveLayer", id: patch.id, toIndex: from } };
|
|
370
|
+
}
|
|
371
|
+
case "addItem": {
|
|
372
|
+
if (idExists(doc, patch.item.id)) throw new PatchError(`Duplicate id: ${patch.item.id}`);
|
|
373
|
+
const li = layerIndex(doc, patch.layerId);
|
|
374
|
+
const items = doc.layers[li].items.slice();
|
|
375
|
+
items.splice(clampIndex(patch.index, items.length), 0, patch.item);
|
|
376
|
+
return {
|
|
377
|
+
doc: replaceLayer(doc, li, { ...doc.layers[li], items }),
|
|
378
|
+
inverse: { op: "removeItem", id: patch.item.id }
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
case "updateItem": {
|
|
382
|
+
const loc = findItem(doc, patch.id);
|
|
383
|
+
if (!loc) throw new PatchError(`Item not found: ${patch.id}`);
|
|
384
|
+
if ("type" in patch.changes || "id" in patch.changes) {
|
|
385
|
+
throw new PatchError("updateItem cannot change id or type");
|
|
386
|
+
}
|
|
387
|
+
const next = Item.parse({ ...loc.item, ...patch.changes });
|
|
388
|
+
const before = {};
|
|
389
|
+
for (const k of Object.keys(patch.changes)) before[k] = loc.item[k];
|
|
390
|
+
const items = doc.layers[loc.layerIndex].items.slice();
|
|
391
|
+
items[loc.itemIndex] = next;
|
|
392
|
+
return {
|
|
393
|
+
doc: replaceLayer(doc, loc.layerIndex, { ...doc.layers[loc.layerIndex], items }),
|
|
394
|
+
inverse: { op: "updateItem", id: patch.id, changes: before }
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
case "removeItem": {
|
|
398
|
+
const loc = findItem(doc, patch.id);
|
|
399
|
+
if (!loc) throw new PatchError(`Item not found: ${patch.id}`);
|
|
400
|
+
const layer = doc.layers[loc.layerIndex];
|
|
401
|
+
const items = layer.items.slice();
|
|
402
|
+
items.splice(loc.itemIndex, 1);
|
|
403
|
+
return {
|
|
404
|
+
doc: replaceLayer(doc, loc.layerIndex, { ...layer, items }),
|
|
405
|
+
inverse: { op: "addItem", layerId: layer.id, item: loc.item, index: loc.itemIndex }
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
case "moveItem": {
|
|
409
|
+
const loc = findItem(doc, patch.id);
|
|
410
|
+
if (!loc) throw new PatchError(`Item not found: ${patch.id}`);
|
|
411
|
+
const fromLayer = doc.layers[loc.layerIndex];
|
|
412
|
+
const removed = applyPatch(doc, { op: "removeItem", id: patch.id }).doc;
|
|
413
|
+
const added = applyPatch(removed, {
|
|
414
|
+
op: "addItem",
|
|
415
|
+
layerId: patch.toLayerId,
|
|
416
|
+
item: loc.item,
|
|
417
|
+
index: patch.toIndex
|
|
418
|
+
}).doc;
|
|
419
|
+
return {
|
|
420
|
+
doc: added,
|
|
421
|
+
inverse: { op: "moveItem", id: patch.id, toLayerId: fromLayer.id, toIndex: loc.itemIndex }
|
|
422
|
+
};
|
|
423
|
+
}
|
|
424
|
+
case "setNumeral": {
|
|
425
|
+
const prev = doc.numerals[patch.n] ?? null;
|
|
426
|
+
const numerals = { ...doc.numerals };
|
|
427
|
+
if (patch.label === null) delete numerals[patch.n];
|
|
428
|
+
else numerals[patch.n] = patch.label;
|
|
429
|
+
return { doc: { ...doc, numerals }, inverse: { op: "setNumeral", n: patch.n, label: prev } };
|
|
430
|
+
}
|
|
431
|
+
case "setSheet": {
|
|
432
|
+
return { doc: { ...doc, sheet: patch.sheet }, inverse: { op: "setSheet", sheet: doc.sheet } };
|
|
433
|
+
}
|
|
434
|
+
case "setJurisdiction": {
|
|
435
|
+
return {
|
|
436
|
+
doc: { ...doc, jurisdiction: patch.jurisdiction },
|
|
437
|
+
inverse: { op: "setJurisdiction", jurisdiction: doc.jurisdiction }
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
case "setLettering": {
|
|
441
|
+
return { doc: { ...doc, lettering: patch.lettering }, inverse: { op: "setLettering", lettering: doc.lettering } };
|
|
442
|
+
}
|
|
443
|
+
case "setView": {
|
|
444
|
+
return {
|
|
445
|
+
doc: { ...doc, view: patch.view, explodeLines: patch.explodeLines ?? doc.explodeLines },
|
|
446
|
+
inverse: { op: "setView", view: doc.view, explodeLines: doc.explodeLines }
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
case "setSheetLabel": {
|
|
450
|
+
const next = { ...doc };
|
|
451
|
+
if (patch.sheetLabel === null) delete next.sheetLabel;
|
|
452
|
+
else next.sheetLabel = patch.sheetLabel;
|
|
453
|
+
return { doc: next, inverse: { op: "setSheetLabel", sheetLabel: doc.sheetLabel ?? null } };
|
|
454
|
+
}
|
|
455
|
+
case "batch": {
|
|
456
|
+
let cur = doc;
|
|
457
|
+
const inverses = [];
|
|
458
|
+
for (const p of patch.patches) {
|
|
459
|
+
const r = applyPatch(cur, p);
|
|
460
|
+
cur = r.doc;
|
|
461
|
+
inverses.unshift(r.inverse);
|
|
462
|
+
}
|
|
463
|
+
return { doc: cur, inverse: { op: "batch", patches: inverses } };
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
// ../../src/patent-render/geometry/transform.ts
|
|
469
|
+
var ARITY = { m: 2, l: 2, h: 1, v: 1, c: 6, s: 4, q: 4, t: 2, a: 7, z: 0 };
|
|
470
|
+
function parsePath(d) {
|
|
471
|
+
const out = [];
|
|
472
|
+
const re = /([MLHVCSQTAZmlhvcsqtaz])|(-?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)/g;
|
|
473
|
+
let cur = null;
|
|
474
|
+
let m;
|
|
475
|
+
while (m = re.exec(d)) {
|
|
476
|
+
if (m[1]) {
|
|
477
|
+
cur = { c: m[1], v: [] };
|
|
478
|
+
out.push(cur);
|
|
479
|
+
} else if (cur) {
|
|
480
|
+
const n2 = ARITY[cur.c.toLowerCase()];
|
|
481
|
+
if (n2 > 0 && cur.v.length === n2) {
|
|
482
|
+
const c = cur.c === "M" ? "L" : cur.c === "m" ? "l" : cur.c;
|
|
483
|
+
cur = { c, v: [] };
|
|
484
|
+
out.push(cur);
|
|
485
|
+
}
|
|
486
|
+
cur.v.push(Number(m[2]));
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return out;
|
|
490
|
+
}
|
|
491
|
+
var fmt = (n2) => String(Math.round(n2 * 1e3) / 1e3);
|
|
492
|
+
function serializePath(cmds) {
|
|
493
|
+
return cmds.map((k) => [k.c, ...k.v.map(fmt)].join(" ")).join(" ");
|
|
494
|
+
}
|
|
495
|
+
function cubicPoint(a, c1, c2, b, t) {
|
|
496
|
+
const u = 1 - t;
|
|
497
|
+
return [
|
|
498
|
+
u * u * u * a[0] + 3 * u * u * t * c1[0] + 3 * u * t * t * c2[0] + t * t * t * b[0],
|
|
499
|
+
u * u * u * a[1] + 3 * u * u * t * c1[1] + 3 * u * t * t * c2[1] + t * t * t * b[1]
|
|
500
|
+
];
|
|
501
|
+
}
|
|
502
|
+
function pathPoints(d) {
|
|
503
|
+
const pts2 = [];
|
|
504
|
+
let x = 0, y = 0, sx = 0, sy = 0;
|
|
505
|
+
parsePath(d).forEach((k, i) => {
|
|
506
|
+
const rel = k.c === k.c.toLowerCase() && !(i === 0 && k.c === "m");
|
|
507
|
+
const ox = rel ? x : 0, oy = rel ? y : 0;
|
|
508
|
+
const v = k.v;
|
|
509
|
+
switch (k.c.toLowerCase()) {
|
|
510
|
+
case "m":
|
|
511
|
+
case "l":
|
|
512
|
+
case "t":
|
|
513
|
+
x = ox + v[0];
|
|
514
|
+
y = oy + v[1];
|
|
515
|
+
pts2.push([x, y]);
|
|
516
|
+
if (k.c.toLowerCase() === "m") {
|
|
517
|
+
sx = x;
|
|
518
|
+
sy = y;
|
|
519
|
+
}
|
|
520
|
+
break;
|
|
521
|
+
case "h":
|
|
522
|
+
x = (rel ? x : 0) + v[0];
|
|
523
|
+
pts2.push([x, y]);
|
|
524
|
+
break;
|
|
525
|
+
case "v":
|
|
526
|
+
y = (rel ? y : 0) + v[0];
|
|
527
|
+
pts2.push([x, y]);
|
|
528
|
+
break;
|
|
529
|
+
case "c": {
|
|
530
|
+
const p0 = [x, y], c1 = [ox + v[0], oy + v[1]], c2 = [ox + v[2], oy + v[3]];
|
|
531
|
+
x = ox + v[4];
|
|
532
|
+
y = oy + v[5];
|
|
533
|
+
for (let k2 = 1; k2 <= 16; k2++) pts2.push(cubicPoint(p0, c1, c2, [x, y], k2 / 16));
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
case "q": {
|
|
537
|
+
const p0 = [x, y], q = [ox + v[0], oy + v[1]];
|
|
538
|
+
x = ox + v[2];
|
|
539
|
+
y = oy + v[3];
|
|
540
|
+
for (let k2 = 1; k2 <= 16; k2++) {
|
|
541
|
+
const t = k2 / 16, u = 1 - t;
|
|
542
|
+
pts2.push([u * u * p0[0] + 2 * u * t * q[0] + t * t * x, u * u * p0[1] + 2 * u * t * q[1] + t * t * y]);
|
|
543
|
+
}
|
|
544
|
+
break;
|
|
545
|
+
}
|
|
546
|
+
case "s":
|
|
547
|
+
pts2.push([ox + v[0], oy + v[1]]);
|
|
548
|
+
x = ox + v[2];
|
|
549
|
+
y = oy + v[3];
|
|
550
|
+
pts2.push([x, y]);
|
|
551
|
+
break;
|
|
552
|
+
case "a":
|
|
553
|
+
x = ox + v[5];
|
|
554
|
+
y = oy + v[6];
|
|
555
|
+
pts2.push([x - v[0], y - v[1]], [x + v[0], y + v[1]]);
|
|
556
|
+
break;
|
|
557
|
+
case "z":
|
|
558
|
+
x = sx;
|
|
559
|
+
y = sy;
|
|
560
|
+
break;
|
|
561
|
+
}
|
|
562
|
+
});
|
|
563
|
+
return pts2;
|
|
564
|
+
}
|
|
565
|
+
function mapPath(d, s, t, origin = [0, 0]) {
|
|
566
|
+
const ax = (x) => origin[0] + (x - origin[0]) * s[0] + t[0];
|
|
567
|
+
const ay = (y) => origin[1] + (y - origin[1]) * s[1] + t[1];
|
|
568
|
+
const cmds = parsePath(d).map((k, i) => {
|
|
569
|
+
const abs = k.c === k.c.toUpperCase() || i === 0 && k.c === "m";
|
|
570
|
+
const v = k.v.slice();
|
|
571
|
+
const lc = k.c.toLowerCase();
|
|
572
|
+
if (lc === "h") v[0] = abs ? ax(v[0]) : v[0] * s[0];
|
|
573
|
+
else if (lc === "v") v[0] = abs ? ay(v[0]) : v[0] * s[1];
|
|
574
|
+
else if (lc === "a") {
|
|
575
|
+
v[0] *= Math.abs(s[0]);
|
|
576
|
+
v[1] *= Math.abs(s[1]);
|
|
577
|
+
if (s[0] * s[1] < 0) v[4] = v[4] ? 0 : 1;
|
|
578
|
+
v[5] = abs ? ax(v[5]) : v[5] * s[0];
|
|
579
|
+
v[6] = abs ? ay(v[6]) : v[6] * s[1];
|
|
580
|
+
} else {
|
|
581
|
+
for (let j = 0; j + 1 < v.length; j += 2) {
|
|
582
|
+
v[j] = abs ? ax(v[j]) : v[j] * s[0];
|
|
583
|
+
v[j + 1] = abs ? ay(v[j + 1]) : v[j + 1] * s[1];
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
return { c: k.c, v };
|
|
587
|
+
});
|
|
588
|
+
return serializePath(cmds);
|
|
589
|
+
}
|
|
590
|
+
var tp = ([x, y], dx, dy) => [x + dx, y + dy];
|
|
591
|
+
function translateChanges(item, dx, dy) {
|
|
592
|
+
switch (item.type) {
|
|
593
|
+
case "line":
|
|
594
|
+
case "sectionLine":
|
|
595
|
+
return { a: tp(item.a, dx, dy), b: tp(item.b, dx, dy) };
|
|
596
|
+
case "polyline":
|
|
597
|
+
case "hatch":
|
|
598
|
+
return { points: item.points.map((p) => tp(p, dx, dy)) };
|
|
599
|
+
case "path":
|
|
600
|
+
return { d: mapPath(item.d, [1, 1], [dx, dy]) };
|
|
601
|
+
case "rect":
|
|
602
|
+
case "text":
|
|
603
|
+
case "figLabel":
|
|
604
|
+
return { x: item.x + dx, y: item.y + dy };
|
|
605
|
+
case "ellipse":
|
|
606
|
+
case "arc":
|
|
607
|
+
return { cx: item.cx + dx, cy: item.cy + dy };
|
|
608
|
+
case "numeral":
|
|
609
|
+
return { at: tp(item.at, dx, dy), target: tp(item.target, dx, dy) };
|
|
610
|
+
case "connector": {
|
|
611
|
+
const ch = {};
|
|
612
|
+
if ("point" in item.from) ch.from = { point: tp(item.from.point, dx, dy) };
|
|
613
|
+
if ("point" in item.to) ch.to = { point: tp(item.to.point, dx, dy) };
|
|
614
|
+
return ch;
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
function scaleChanges(item, origin, sx, sy) {
|
|
619
|
+
const sp = ([x, y]) => [origin[0] + (x - origin[0]) * sx, origin[1] + (y - origin[1]) * sy];
|
|
620
|
+
const ax = Math.abs(sx), ay = Math.abs(sy);
|
|
621
|
+
switch (item.type) {
|
|
622
|
+
case "line":
|
|
623
|
+
case "sectionLine":
|
|
624
|
+
return { a: sp(item.a), b: sp(item.b) };
|
|
625
|
+
case "polyline":
|
|
626
|
+
case "hatch":
|
|
627
|
+
return { points: item.points.map(sp) };
|
|
628
|
+
case "path":
|
|
629
|
+
return { d: mapPath(item.d, [sx, sy], [0, 0], origin) };
|
|
630
|
+
case "rect": {
|
|
631
|
+
const [x0, y0] = sp([item.x, item.y]);
|
|
632
|
+
const [x1, y1] = sp([item.x + item.w, item.y + item.h]);
|
|
633
|
+
return { x: Math.min(x0, x1), y: Math.min(y0, y1), w: Math.max(0.1, Math.abs(x1 - x0)), h: Math.max(0.1, Math.abs(y1 - y0)) };
|
|
634
|
+
}
|
|
635
|
+
case "ellipse": {
|
|
636
|
+
const [cx, cy] = sp([item.cx, item.cy]);
|
|
637
|
+
return { cx, cy, rx: Math.max(0.05, item.rx * ax), ry: Math.max(0.05, item.ry * ay) };
|
|
638
|
+
}
|
|
639
|
+
case "arc": {
|
|
640
|
+
const [cx, cy] = sp([item.cx, item.cy]);
|
|
641
|
+
return { cx, cy, r: Math.max(0.05, item.r * Math.sqrt(ax * ay)) };
|
|
642
|
+
}
|
|
643
|
+
case "text": {
|
|
644
|
+
const [x, y] = sp([item.x, item.y]);
|
|
645
|
+
return { x, y, size: Math.max(0.5, item.size * ay) };
|
|
646
|
+
}
|
|
647
|
+
case "figLabel": {
|
|
648
|
+
const [x, y] = sp([item.x, item.y]);
|
|
649
|
+
return { x, y };
|
|
650
|
+
}
|
|
651
|
+
case "numeral":
|
|
652
|
+
return { at: sp(item.at), target: sp(item.target) };
|
|
653
|
+
case "connector": {
|
|
654
|
+
const ch = {};
|
|
655
|
+
if ("point" in item.from) ch.from = { point: sp(item.from.point) };
|
|
656
|
+
if ("point" in item.to) ch.to = { point: sp(item.to.point) };
|
|
657
|
+
return ch;
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
// ../../src/patent-render/geometry/index.ts
|
|
663
|
+
var SHEET_MM = {
|
|
664
|
+
a4: { w: 210, h: 297 },
|
|
665
|
+
letter: { w: 215.9, h: 279.4 }
|
|
666
|
+
};
|
|
667
|
+
function sheetDims(sheet) {
|
|
668
|
+
const d = SHEET_MM[sheet.size];
|
|
669
|
+
return sheet.orientation === "portrait" ? { w: d.w, h: d.h } : { w: d.h, h: d.w };
|
|
670
|
+
}
|
|
671
|
+
var CAP_RATIO = 0.7;
|
|
672
|
+
var AVG_CHAR_W = 0.6;
|
|
673
|
+
function fontSize(capHeight) {
|
|
674
|
+
return capHeight / CAP_RATIO;
|
|
675
|
+
}
|
|
676
|
+
function textBox(x, y, text, capHeight, anchor) {
|
|
677
|
+
const fs = fontSize(capHeight);
|
|
678
|
+
const w = text.length * fs * AVG_CHAR_W;
|
|
679
|
+
const left = anchor === "start" ? x : anchor === "middle" ? x - w / 2 : x - w;
|
|
680
|
+
return { x: left, y: y - capHeight, w, h: capHeight + fs * 0.2 };
|
|
681
|
+
}
|
|
682
|
+
function boxFromPoints(pts2) {
|
|
683
|
+
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
|
|
684
|
+
for (const [x, y] of pts2) {
|
|
685
|
+
x0 = Math.min(x0, x);
|
|
686
|
+
y0 = Math.min(y0, y);
|
|
687
|
+
x1 = Math.max(x1, x);
|
|
688
|
+
y1 = Math.max(y1, y);
|
|
689
|
+
}
|
|
690
|
+
return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
|
|
691
|
+
}
|
|
692
|
+
function unionBox(boxes) {
|
|
693
|
+
if (!boxes.length) return null;
|
|
694
|
+
return boxFromPoints(boxes.flatMap((b) => [[b.x, b.y], [b.x + b.w, b.y + b.h]]));
|
|
695
|
+
}
|
|
696
|
+
function centre(b) {
|
|
697
|
+
return [b.x + b.w / 2, b.y + b.h / 2];
|
|
698
|
+
}
|
|
699
|
+
function pathBox(d) {
|
|
700
|
+
const pts2 = pathPoints(d);
|
|
701
|
+
return pts2.length ? boxFromPoints(pts2) : { x: 0, y: 0, w: 0, h: 0 };
|
|
702
|
+
}
|
|
703
|
+
function figLabelText(doc) {
|
|
704
|
+
return `FIG. ${doc.figureNumber}`;
|
|
705
|
+
}
|
|
706
|
+
function itemBox(doc, item) {
|
|
707
|
+
switch (item.type) {
|
|
708
|
+
case "line":
|
|
709
|
+
case "sectionLine":
|
|
710
|
+
return boxFromPoints([item.a, item.b]);
|
|
711
|
+
case "polyline":
|
|
712
|
+
case "hatch":
|
|
713
|
+
return boxFromPoints(item.points);
|
|
714
|
+
case "path":
|
|
715
|
+
return pathBox(item.d);
|
|
716
|
+
case "rect":
|
|
717
|
+
return { x: item.x, y: item.y, w: item.w, h: item.h };
|
|
718
|
+
case "ellipse":
|
|
719
|
+
return { x: item.cx - item.rx, y: item.cy - item.ry, w: item.rx * 2, h: item.ry * 2 };
|
|
720
|
+
case "arc":
|
|
721
|
+
return { x: item.cx - item.r, y: item.cy - item.r, w: item.r * 2, h: item.r * 2 };
|
|
722
|
+
case "text":
|
|
723
|
+
return textBox(item.x, item.y, item.text, item.size, item.anchor);
|
|
724
|
+
case "figLabel":
|
|
725
|
+
return textBox(item.x, item.y, figLabelText(doc), item.size, "middle");
|
|
726
|
+
case "numeral": {
|
|
727
|
+
const label = numeralLabelBox(item.at, item.n, item.size);
|
|
728
|
+
return unionBox([label, boxFromPoints([item.target, item.target])]);
|
|
729
|
+
}
|
|
730
|
+
case "connector": {
|
|
731
|
+
const [a, b] = connectorEnds(doc, item);
|
|
732
|
+
return boxFromPoints([a, b]);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
function numeralLabelBox(at, n2, size) {
|
|
737
|
+
const b = textBox(at[0], at[1], n2, size, "middle");
|
|
738
|
+
return { ...b, y: at[1] - b.h / 2 };
|
|
739
|
+
}
|
|
740
|
+
function rotatePoint([x, y], [cx, cy], deg) {
|
|
741
|
+
const r = deg * Math.PI / 180;
|
|
742
|
+
const c = Math.cos(r), s = Math.sin(r);
|
|
743
|
+
return [cx + (x - cx) * c - (y - cy) * s, cy + (x - cx) * s + (y - cy) * c];
|
|
744
|
+
}
|
|
745
|
+
function itemBoundsRotated(doc, item) {
|
|
746
|
+
const b = itemBox(doc, item);
|
|
747
|
+
if (!item.rotation) return b;
|
|
748
|
+
const c = centre(b);
|
|
749
|
+
const corners = [
|
|
750
|
+
[b.x, b.y],
|
|
751
|
+
[b.x + b.w, b.y],
|
|
752
|
+
[b.x + b.w, b.y + b.h],
|
|
753
|
+
[b.x, b.y + b.h]
|
|
754
|
+
].map((p) => rotatePoint(p, c, item.rotation));
|
|
755
|
+
return boxFromPoints(corners);
|
|
756
|
+
}
|
|
757
|
+
function boxExitPoint(b, toward) {
|
|
758
|
+
const [cx, cy] = centre(b);
|
|
759
|
+
const dx = toward[0] - cx, dy = toward[1] - cy;
|
|
760
|
+
if (dx === 0 && dy === 0) return [cx, cy];
|
|
761
|
+
const sx = dx === 0 ? Infinity : b.w / 2 / Math.abs(dx);
|
|
762
|
+
const sy = dy === 0 ? Infinity : b.h / 2 / Math.abs(dy);
|
|
763
|
+
const s = Math.min(sx, sy);
|
|
764
|
+
return [cx + dx * s, cy + dy * s];
|
|
765
|
+
}
|
|
766
|
+
function endTargetBox(doc, end) {
|
|
767
|
+
if ("point" in end) return end.point;
|
|
768
|
+
const loc = findItem(doc, end.itemId);
|
|
769
|
+
if (!loc || loc.item.type === "connector") return [0, 0];
|
|
770
|
+
return itemBoundsRotated(doc, loc.item);
|
|
771
|
+
}
|
|
772
|
+
function facingSide(b, toward) {
|
|
773
|
+
const [cx, cy] = centre(b);
|
|
774
|
+
const dx = toward[0] - cx, dy = toward[1] - cy;
|
|
775
|
+
if (Math.abs(dy) / (b.h || 1) >= Math.abs(dx) / (b.w || 1)) return dy >= 0 ? "bottom" : "top";
|
|
776
|
+
return dx >= 0 ? "right" : "left";
|
|
777
|
+
}
|
|
778
|
+
function sidePoint(b, s) {
|
|
779
|
+
const [cx, cy] = centre(b);
|
|
780
|
+
return s === "top" ? [cx, b.y] : s === "bottom" ? [cx, b.y + b.h] : s === "left" ? [b.x, cy] : [b.x + b.w, cy];
|
|
781
|
+
}
|
|
782
|
+
function connectorGeometry(doc, item) {
|
|
783
|
+
const A = endTargetBox(doc, item.from);
|
|
784
|
+
const B = endTargetBox(doc, item.to);
|
|
785
|
+
const aC = Array.isArray(A) ? A : centre(A);
|
|
786
|
+
const bC = Array.isArray(B) ? B : centre(B);
|
|
787
|
+
let a = aC, b = bC, sideA = null, sideB = null;
|
|
788
|
+
if (!Array.isArray(A)) {
|
|
789
|
+
sideA = item.fromSide ?? facingSide(A, bC);
|
|
790
|
+
a = sidePoint(A, sideA);
|
|
791
|
+
}
|
|
792
|
+
if (!Array.isArray(B)) {
|
|
793
|
+
sideB = item.toSide ?? facingSide(B, a);
|
|
794
|
+
b = sidePoint(B, sideB);
|
|
795
|
+
}
|
|
796
|
+
return { a, b, sideA, sideB };
|
|
797
|
+
}
|
|
798
|
+
function connectorEnds(doc, item) {
|
|
799
|
+
const g = connectorGeometry(doc, item);
|
|
800
|
+
return [g.a, g.b];
|
|
801
|
+
}
|
|
802
|
+
var DIR = { top: [0, -1], bottom: [0, 1], left: [-1, 0], right: [1, 0] };
|
|
803
|
+
var STUB = 6;
|
|
804
|
+
var isV = (s) => s === "top" || s === "bottom";
|
|
805
|
+
function inferSide(from, to) {
|
|
806
|
+
const dx = to[0] - from[0], dy = to[1] - from[1];
|
|
807
|
+
return Math.abs(dy) >= Math.abs(dx) ? dy >= 0 ? "bottom" : "top" : dx >= 0 ? "right" : "left";
|
|
808
|
+
}
|
|
809
|
+
function simplify(pts2) {
|
|
810
|
+
const out = [];
|
|
811
|
+
for (const p of pts2) {
|
|
812
|
+
const last = out[out.length - 1];
|
|
813
|
+
if (last && Math.abs(last[0] - p[0]) < 1e-6 && Math.abs(last[1] - p[1]) < 1e-6) continue;
|
|
814
|
+
if (out.length >= 2) {
|
|
815
|
+
const q = out[out.length - 2];
|
|
816
|
+
const collinear = Math.abs(q[0] - last[0]) < 1e-6 && Math.abs(last[0] - p[0]) < 1e-6 || Math.abs(q[1] - last[1]) < 1e-6 && Math.abs(last[1] - p[1]) < 1e-6;
|
|
817
|
+
if (collinear) {
|
|
818
|
+
out[out.length - 1] = p;
|
|
819
|
+
continue;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
out.push(p);
|
|
823
|
+
}
|
|
824
|
+
return out;
|
|
825
|
+
}
|
|
826
|
+
function orthogonalRoute(a, b, sideA = null, sideB = null) {
|
|
827
|
+
const sA = sideA ?? inferSide(a, b);
|
|
828
|
+
const sB = sideB ?? (isV(sA) ? b[1] >= a[1] ? "top" : "bottom" : b[0] >= a[0] ? "left" : "right");
|
|
829
|
+
const dA = DIR[sA], dB = DIR[sB];
|
|
830
|
+
const aheadA = (b[0] - a[0]) * dA[0] + (b[1] - a[1]) * dA[1];
|
|
831
|
+
const aheadB = (a[0] - b[0]) * dB[0] + (a[1] - b[1]) * dB[1];
|
|
832
|
+
if (isV(sA) && isV(sB) && sA !== sB && aheadA > STUB && aheadB > STUB) {
|
|
833
|
+
const my = (a[1] + b[1]) / 2;
|
|
834
|
+
return simplify([a, [a[0], my], [b[0], my], b]);
|
|
835
|
+
}
|
|
836
|
+
if (!isV(sA) && !isV(sB) && sA !== sB && aheadA > STUB && aheadB > STUB) {
|
|
837
|
+
const mx = (a[0] + b[0]) / 2;
|
|
838
|
+
return simplify([a, [mx, a[1]], [mx, b[1]], b]);
|
|
839
|
+
}
|
|
840
|
+
if (isV(sA) !== isV(sB) && aheadA > 0 && aheadB > 0) {
|
|
841
|
+
return simplify(isV(sA) ? [a, [a[0], b[1]], b] : [a, [b[0], a[1]], b]);
|
|
842
|
+
}
|
|
843
|
+
if (sA === sB) {
|
|
844
|
+
if (isV(sA)) {
|
|
845
|
+
const y = sA === "bottom" ? Math.max(a[1], b[1]) + STUB : Math.min(a[1], b[1]) - STUB;
|
|
846
|
+
return simplify([a, [a[0], y], [b[0], y], b]);
|
|
847
|
+
}
|
|
848
|
+
const x = sA === "right" ? Math.max(a[0], b[0]) + STUB : Math.min(a[0], b[0]) - STUB;
|
|
849
|
+
return simplify([a, [x, a[1]], [x, b[1]], b]);
|
|
850
|
+
}
|
|
851
|
+
const a1 = [a[0] + dA[0] * STUB, a[1] + dA[1] * STUB];
|
|
852
|
+
const b1 = [b[0] + dB[0] * STUB, b[1] + dB[1] * STUB];
|
|
853
|
+
const corner = isV(sA) ? [b1[0], a1[1]] : [a1[0], b1[1]];
|
|
854
|
+
return simplify([a, a1, corner, b1, b]);
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
// ../../src/patent-render/compliance/profiles.ts
|
|
858
|
+
var STD_MARGINS = { top: 25, left: 25, right: 15, bottom: 10 };
|
|
859
|
+
var PROFILES = {
|
|
860
|
+
uspto: {
|
|
861
|
+
id: "uspto",
|
|
862
|
+
name: "USPTO",
|
|
863
|
+
citation: "37 CFR 1.84",
|
|
864
|
+
sheetSizes: ["letter", "a4"],
|
|
865
|
+
margins: STD_MARGINS,
|
|
866
|
+
minCapHeight: 3.2,
|
|
867
|
+
minStrokeWidth: 0.2,
|
|
868
|
+
text: { mode: "lenient", maxWordsPerText: 8, maxWordsPerCatchword: 6 }
|
|
869
|
+
},
|
|
870
|
+
pct: {
|
|
871
|
+
id: "pct",
|
|
872
|
+
name: "PCT / WIPO",
|
|
873
|
+
citation: "PCT Rule 11",
|
|
874
|
+
sheetSizes: ["a4"],
|
|
875
|
+
margins: STD_MARGINS,
|
|
876
|
+
minCapHeight: 3.2,
|
|
877
|
+
minStrokeWidth: 0.2,
|
|
878
|
+
text: { mode: "strict", maxWordsPerText: 3, maxWordsPerCatchword: 5 }
|
|
879
|
+
},
|
|
880
|
+
epo: {
|
|
881
|
+
id: "epo",
|
|
882
|
+
name: "EPO",
|
|
883
|
+
citation: "EPC Rule 46",
|
|
884
|
+
sheetSizes: ["a4"],
|
|
885
|
+
margins: STD_MARGINS,
|
|
886
|
+
minCapHeight: 3.2,
|
|
887
|
+
minStrokeWidth: 0.2,
|
|
888
|
+
text: { mode: "strict", maxWordsPerText: 3, maxWordsPerCatchword: 5 }
|
|
889
|
+
},
|
|
890
|
+
ipo: {
|
|
891
|
+
id: "ipo",
|
|
892
|
+
name: "IPO India",
|
|
893
|
+
citation: "Patents Rules 2003, Rule 15",
|
|
894
|
+
sheetSizes: ["a4"],
|
|
895
|
+
margins: { top: 40, left: 40, right: 30, bottom: 30 },
|
|
896
|
+
minCapHeight: 3.2,
|
|
897
|
+
minStrokeWidth: 0.2,
|
|
898
|
+
text: { mode: "strict", maxWordsPerText: 4, maxWordsPerCatchword: 5 }
|
|
899
|
+
}
|
|
900
|
+
};
|
|
901
|
+
function effectiveMargins(p, orientation) {
|
|
902
|
+
const m = p.margins;
|
|
903
|
+
if (orientation === "portrait") return m;
|
|
904
|
+
return { top: m.left, right: m.top, bottom: m.right, left: m.bottom };
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
// ../../src/patent-render/geometry/explode.ts
|
|
908
|
+
var EXPLODE_LINES_LAYER = "__explode-lines";
|
|
909
|
+
var isAnnotationLayer = (l) => l.id === "annotations" || l.items.every((i) => i.type === "numeral" || i.type === "figLabel" || i.type === "text" || (i.type === "line" || i.type === "polyline") && (i.stroke.style === "centre" || i.stroke.style === "phantom"));
|
|
910
|
+
var off = (l) => l.explode && (l.explode.dx || l.explode.dy) ? l.explode : null;
|
|
911
|
+
function hasExplode(doc) {
|
|
912
|
+
return doc.layers.some((l) => off(l));
|
|
913
|
+
}
|
|
914
|
+
var shift = (item, dx, dy) => ({ ...item, ...translateChanges(item, dx, dy) });
|
|
915
|
+
function contains(b, p, pad = 1.5) {
|
|
916
|
+
return p[0] >= b.x - pad && p[0] <= b.x + b.w + pad && p[1] >= b.y - pad && p[1] <= b.y + b.h + pad;
|
|
917
|
+
}
|
|
918
|
+
function hostLayer(doc, target) {
|
|
919
|
+
for (let i = doc.layers.length - 1; i >= 0; i--) {
|
|
920
|
+
const l = doc.layers[i];
|
|
921
|
+
if (isAnnotationLayer(l)) continue;
|
|
922
|
+
for (const it of l.items) {
|
|
923
|
+
if (it.type === "numeral" || it.type === "figLabel" || it.type === "connector") continue;
|
|
924
|
+
if (contains(itemBoundsRotated(doc, it), target)) return l;
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
return null;
|
|
928
|
+
}
|
|
929
|
+
function viewDocument(doc) {
|
|
930
|
+
if (doc.view !== "exploded" || !hasExplode(doc)) return doc;
|
|
931
|
+
const layers = doc.layers.map((l) => {
|
|
932
|
+
const o = off(l);
|
|
933
|
+
return {
|
|
934
|
+
...l,
|
|
935
|
+
items: l.items.map((it) => {
|
|
936
|
+
if (it.type === "numeral") {
|
|
937
|
+
const host = hostLayer(doc, it.target);
|
|
938
|
+
const ho = host && off(host);
|
|
939
|
+
return ho ? shift(it, ho.dx, ho.dy) : it;
|
|
940
|
+
}
|
|
941
|
+
if (o && !isAnnotationLayer(l) && it.type !== "figLabel") return shift(it, o.dx, o.dy);
|
|
942
|
+
return it;
|
|
943
|
+
})
|
|
944
|
+
};
|
|
945
|
+
});
|
|
946
|
+
const fig = layers.flatMap((l) => l.items).find((i) => i.type === "figLabel");
|
|
947
|
+
if (fig && fig.type === "figLabel") {
|
|
948
|
+
const partBoxes = layers.filter((l) => !isAnnotationLayer(l)).flatMap((l) => l.items.map((it) => itemBoundsRotated(doc, it)));
|
|
949
|
+
const fb = itemBoundsRotated(doc, fig);
|
|
950
|
+
const overlaps = partBoxes.some((b) => fb.x < b.x + b.w && b.x < fb.x + fb.w && fb.y < b.y + b.h && b.y < fb.y + fb.h);
|
|
951
|
+
const all = unionBox(partBoxes);
|
|
952
|
+
if (overlaps && all) {
|
|
953
|
+
const { h } = sheetDims(doc.sheet);
|
|
954
|
+
const m = effectiveMargins(PROFILES[doc.jurisdiction], doc.sheet.orientation);
|
|
955
|
+
const y = Math.min(all.y + all.h + 14, h - m.bottom - 4);
|
|
956
|
+
for (const l of layers) l.items = l.items.map((it) => it.id === fig.id ? { ...fig, y: Math.round(y * 10) / 10 } : it);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
if (doc.explodeLines) {
|
|
960
|
+
const lines = [];
|
|
961
|
+
const parts = doc.layers.filter((l) => l.visible && !isAnnotationLayer(l) && l.items.length);
|
|
962
|
+
const boxes = parts.map((l) => unionBox(l.items.map((it) => itemBoundsRotated(doc, it))));
|
|
963
|
+
parts.forEach((l, i) => {
|
|
964
|
+
const o = off(l), b = boxes[i];
|
|
965
|
+
if (!o || !b) return;
|
|
966
|
+
const [cx, cy] = centre(b);
|
|
967
|
+
const len = Math.hypot(o.dx, o.dy) || 1;
|
|
968
|
+
const ux = o.dx / len, uy = o.dy / len;
|
|
969
|
+
const ext = Math.min(b.w, b.h) * 0.6;
|
|
970
|
+
const { w: sw, h: sh } = sheetDims(doc.sheet);
|
|
971
|
+
const mm = effectiveMargins(PROFILES[doc.jurisdiction], doc.sheet.orientation);
|
|
972
|
+
const clampP = (p) => [
|
|
973
|
+
Math.min(sw - mm.right - 1, Math.max(mm.left + 1, p[0])),
|
|
974
|
+
Math.min(sh - mm.bottom - 1, Math.max(mm.top + 1, p[1]))
|
|
975
|
+
];
|
|
976
|
+
lines.push({
|
|
977
|
+
id: `${EXPLODE_LINES_LAYER}-${l.id}`,
|
|
978
|
+
type: "line",
|
|
979
|
+
a: clampP([cx - ux * ext, cy - uy * ext]),
|
|
980
|
+
b: clampP([cx + o.dx + ux * ext, cy + o.dy + uy * ext]),
|
|
981
|
+
stroke: { width: 0.25, style: "phantom" },
|
|
982
|
+
rotation: 0,
|
|
983
|
+
locked: true,
|
|
984
|
+
hidden: false
|
|
985
|
+
});
|
|
986
|
+
});
|
|
987
|
+
if (lines.length) layers.unshift({ id: EXPLODE_LINES_LAYER, name: "Explode lines", visible: true, locked: true, items: lines });
|
|
988
|
+
}
|
|
989
|
+
return { ...doc, layers };
|
|
990
|
+
}
|
|
991
|
+
function autoExplodePatch(doc, axis = "y", gap = 8) {
|
|
992
|
+
const parts = doc.layers.filter((l) => !isAnnotationLayer(l) && l.items.length).map((l) => ({ l, b: unionBox(l.items.map((it) => itemBoundsRotated(doc, it))) })).sort((a, b) => axis === "y" ? centre(a.b)[1] - centre(b.b)[1] : centre(a.b)[0] - centre(b.b)[0]);
|
|
993
|
+
if (parts.length < 2) return { op: "batch", patches: [] };
|
|
994
|
+
const size = (b) => axis === "y" ? b.h : b.w;
|
|
995
|
+
const pos = (b) => axis === "y" ? b.y : b.x;
|
|
996
|
+
const placed = [];
|
|
997
|
+
let cursor = 0;
|
|
998
|
+
for (const p of parts) {
|
|
999
|
+
placed.push(cursor);
|
|
1000
|
+
cursor += size(p.b) + gap;
|
|
1001
|
+
}
|
|
1002
|
+
const total = cursor - gap;
|
|
1003
|
+
const all = unionBox(parts.map((p) => p.b));
|
|
1004
|
+
const { w, h } = sheetDims(doc.sheet);
|
|
1005
|
+
const m = effectiveMargins(PROFILES[doc.jurisdiction], doc.sheet.orientation);
|
|
1006
|
+
const lo = axis === "y" ? m.top + 16 : m.left + 18;
|
|
1007
|
+
const hi = axis === "y" ? h - m.bottom - 26 : w - m.right - 18;
|
|
1008
|
+
let start = (axis === "y" ? centre(all)[1] : centre(all)[0]) - total / 2;
|
|
1009
|
+
start = Math.max(lo, Math.min(start, hi - total));
|
|
1010
|
+
const squeeze = total > hi - lo ? (hi - lo) / total : 1;
|
|
1011
|
+
return {
|
|
1012
|
+
op: "batch",
|
|
1013
|
+
patches: parts.map((p, i) => {
|
|
1014
|
+
const target = start + placed[i] * squeeze;
|
|
1015
|
+
const d = Math.round((target - pos(p.b)) * 10) / 10;
|
|
1016
|
+
return { op: "updateLayer", id: p.l.id, changes: { explode: axis === "y" ? { dx: 0, dy: d } : { dx: d, dy: 0 } } };
|
|
1017
|
+
})
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
// ../../src/patent-render/compliance/validate.ts
|
|
1022
|
+
var EPS = 0.01;
|
|
1023
|
+
function intersects(a, b) {
|
|
1024
|
+
return a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
|
|
1025
|
+
}
|
|
1026
|
+
var sheetSizeRule = ({ doc, profile }) => profile.sheetSizes.includes(doc.sheet.size) ? [] : [{
|
|
1027
|
+
rule: "sheet-size",
|
|
1028
|
+
severity: "error",
|
|
1029
|
+
message: `${profile.name} requires ${profile.sheetSizes.map((s) => s.toUpperCase()).join(" or ")} sheets.`
|
|
1030
|
+
}];
|
|
1031
|
+
var marginsRule = ({ doc, profile, items }) => {
|
|
1032
|
+
const { w, h } = sheetDims(doc.sheet);
|
|
1033
|
+
const m = effectiveMargins(profile, doc.sheet.orientation);
|
|
1034
|
+
const area = { x0: m.left, y0: m.top, x1: w - m.right, y1: h - m.bottom };
|
|
1035
|
+
const out = [];
|
|
1036
|
+
for (const { item, layerId } of items) {
|
|
1037
|
+
const b = itemBoundsRotated(doc, item);
|
|
1038
|
+
if (b.x < area.x0 - EPS || b.y < area.y0 - EPS || b.x + b.w > area.x1 + EPS || b.y + b.h > area.y1 + EPS) {
|
|
1039
|
+
out.push({
|
|
1040
|
+
rule: "margins",
|
|
1041
|
+
severity: "error",
|
|
1042
|
+
message: `"${item.name ?? item.id}" extends into the ${profile.name} margin.`,
|
|
1043
|
+
itemId: item.id,
|
|
1044
|
+
layerId
|
|
1045
|
+
});
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
return out;
|
|
1049
|
+
};
|
|
1050
|
+
var minTextHeightRule = ({ profile, items }) => {
|
|
1051
|
+
const out = [];
|
|
1052
|
+
for (const { item, layerId } of items) {
|
|
1053
|
+
if ((item.type === "text" || item.type === "numeral" || item.type === "figLabel") && item.size < profile.minCapHeight - EPS) {
|
|
1054
|
+
out.push({
|
|
1055
|
+
rule: "min-text-height",
|
|
1056
|
+
severity: "error",
|
|
1057
|
+
message: `Text height ${item.size} mm is below the ${profile.minCapHeight} mm minimum.`,
|
|
1058
|
+
itemId: item.id,
|
|
1059
|
+
layerId
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
return out;
|
|
1064
|
+
};
|
|
1065
|
+
var figLabelRule = ({ doc, items }) => {
|
|
1066
|
+
const labels = items.filter((v) => v.item.type === "figLabel");
|
|
1067
|
+
if (labels.length === 1) return [];
|
|
1068
|
+
return [{
|
|
1069
|
+
rule: "fig-label",
|
|
1070
|
+
severity: "error",
|
|
1071
|
+
message: labels.length === 0 ? `Missing "FIG. ${doc.figureNumber}" label.` : `Figure has ${labels.length} "FIG." labels; exactly one is required.`
|
|
1072
|
+
}];
|
|
1073
|
+
};
|
|
1074
|
+
var strokeWidthRule = ({ profile, items }) => {
|
|
1075
|
+
const out = [];
|
|
1076
|
+
for (const { item, layerId } of items) {
|
|
1077
|
+
if ("stroke" in item && item.stroke.width < profile.minStrokeWidth - EPS) {
|
|
1078
|
+
out.push({
|
|
1079
|
+
rule: "stroke-width",
|
|
1080
|
+
severity: "warning",
|
|
1081
|
+
message: `Line weight ${item.stroke.width} mm may not reproduce clearly (min ${profile.minStrokeWidth} mm).`,
|
|
1082
|
+
itemId: item.id,
|
|
1083
|
+
layerId
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
return out;
|
|
1088
|
+
};
|
|
1089
|
+
var numeralRegistryRule = ({ doc, items }) => {
|
|
1090
|
+
const out = [];
|
|
1091
|
+
for (const { item, layerId } of items) {
|
|
1092
|
+
if (item.type === "numeral" && !(item.n in doc.numerals)) {
|
|
1093
|
+
out.push({
|
|
1094
|
+
rule: "numeral-undefined",
|
|
1095
|
+
severity: "warning",
|
|
1096
|
+
message: `Reference numeral ${item.n} has no description in the registry.`,
|
|
1097
|
+
itemId: item.id,
|
|
1098
|
+
layerId
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
}
|
|
1102
|
+
return out;
|
|
1103
|
+
};
|
|
1104
|
+
var numeralOverlapRule = ({ items }) => {
|
|
1105
|
+
const nums = items.filter((v) => v.item.type === "numeral");
|
|
1106
|
+
const boxes = nums.map((v) => numeralLabelBox(v.item.at, v.item.n, v.item.size));
|
|
1107
|
+
const out = [];
|
|
1108
|
+
for (let i = 0; i < nums.length; i++) {
|
|
1109
|
+
for (let j = i + 1; j < nums.length; j++) {
|
|
1110
|
+
if (intersects(boxes[i], boxes[j])) {
|
|
1111
|
+
out.push({
|
|
1112
|
+
rule: "numeral-overlap",
|
|
1113
|
+
severity: "warning",
|
|
1114
|
+
message: `Numerals ${nums[i].item.n} and ${nums[j].item.n} overlap.`,
|
|
1115
|
+
itemId: nums[j].item.id,
|
|
1116
|
+
layerId: nums[j].layerId
|
|
1117
|
+
});
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
return out;
|
|
1122
|
+
};
|
|
1123
|
+
var textDensityRule = ({ profile, items }) => {
|
|
1124
|
+
const out = [];
|
|
1125
|
+
const check = (text, limit, kind, itemId, layerId) => {
|
|
1126
|
+
const n2 = countWords(text);
|
|
1127
|
+
if (n2 > limit) {
|
|
1128
|
+
out.push({
|
|
1129
|
+
rule: "text-density",
|
|
1130
|
+
severity: "warning",
|
|
1131
|
+
message: `${kind} has ${n2} words; ${profile.citation} allows ${limit} at most. Move the explanation to the description.`,
|
|
1132
|
+
itemId,
|
|
1133
|
+
layerId
|
|
1134
|
+
});
|
|
1135
|
+
}
|
|
1136
|
+
};
|
|
1137
|
+
for (const { item, layerId } of items) {
|
|
1138
|
+
if (item.type === "text") check(item.text, profile.text.maxWordsPerText, "Text", item.id, layerId);
|
|
1139
|
+
else if (item.type === "connector" && item.label) {
|
|
1140
|
+
check(item.label, profile.text.maxWordsPerCatchword, "Connector label", item.id, layerId);
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
return out;
|
|
1144
|
+
};
|
|
1145
|
+
function countWords(text) {
|
|
1146
|
+
return text.split(/\s+/).filter((t) => /[a-z]/i.test(t) && !/^[a-z]?\d+[a-z']*$/i.test(t) && !/^[a-z]$/i.test(t)).length;
|
|
1147
|
+
}
|
|
1148
|
+
var DEFAULT_RULES = [
|
|
1149
|
+
sheetSizeRule,
|
|
1150
|
+
marginsRule,
|
|
1151
|
+
minTextHeightRule,
|
|
1152
|
+
figLabelRule,
|
|
1153
|
+
strokeWidthRule,
|
|
1154
|
+
numeralRegistryRule,
|
|
1155
|
+
numeralOverlapRule,
|
|
1156
|
+
textDensityRule
|
|
1157
|
+
];
|
|
1158
|
+
function visibleItems(doc) {
|
|
1159
|
+
return doc.layers.filter((l) => l.visible).flatMap((l) => l.items.filter((it) => !it.hidden).map((item) => ({ item, layerId: l.id })));
|
|
1160
|
+
}
|
|
1161
|
+
function validate(model, rules = DEFAULT_RULES) {
|
|
1162
|
+
const doc = viewDocument(model);
|
|
1163
|
+
const profile = PROFILES[doc.jurisdiction];
|
|
1164
|
+
const ctx = { doc, profile, items: visibleItems(doc) };
|
|
1165
|
+
const issues = rules.flatMap((r) => r(ctx));
|
|
1166
|
+
const errors = issues.filter((i) => i.severity === "error");
|
|
1167
|
+
const warnings = issues.filter((i) => i.severity === "warning");
|
|
1168
|
+
return { jurisdiction: doc.jurisdiction, ok: errors.length === 0, errors, warnings };
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
// ../../src/patent-render/protocol.ts
|
|
1172
|
+
var EVENTS = {
|
|
1173
|
+
patch: "pr.patch",
|
|
1174
|
+
plan: "pr.plan",
|
|
1175
|
+
status: "pr.status",
|
|
1176
|
+
review: "pr.review"
|
|
1177
|
+
};
|
|
1178
|
+
|
|
1179
|
+
// ../../src/patent-render/server/session.ts
|
|
1180
|
+
var DrawingSession = class {
|
|
1181
|
+
doc;
|
|
1182
|
+
selection;
|
|
1183
|
+
context;
|
|
1184
|
+
/** Images the user attached on the latest turn (for planner/critic). */
|
|
1185
|
+
attachments;
|
|
1186
|
+
/** Figure type / style picked in the composer for this turn. */
|
|
1187
|
+
prefs;
|
|
1188
|
+
plan = null;
|
|
1189
|
+
reviews = 0;
|
|
1190
|
+
patchesApplied = 0;
|
|
1191
|
+
lastStatus = "";
|
|
1192
|
+
constructor(init) {
|
|
1193
|
+
this.doc = init.doc;
|
|
1194
|
+
this.selection = init.selection ?? [];
|
|
1195
|
+
this.context = init.context;
|
|
1196
|
+
this.attachments = init.attachments ?? [];
|
|
1197
|
+
this.prefs = init.prefs;
|
|
1198
|
+
}
|
|
1199
|
+
/** Applies a patch; returns null on success or the error message. */
|
|
1200
|
+
apply(patch, emit) {
|
|
1201
|
+
try {
|
|
1202
|
+
this.doc = applyPatch(this.doc, patch).doc;
|
|
1203
|
+
} catch (e) {
|
|
1204
|
+
return e instanceof Error ? e.message : String(e);
|
|
1205
|
+
}
|
|
1206
|
+
this.patchesApplied += 1;
|
|
1207
|
+
emit?.(EVENTS.patch, { patch });
|
|
1208
|
+
return null;
|
|
1209
|
+
}
|
|
1210
|
+
status(emit, phase, label) {
|
|
1211
|
+
const key = `${phase}:${label}`;
|
|
1212
|
+
if (key === this.lastStatus) return;
|
|
1213
|
+
this.lastStatus = key;
|
|
1214
|
+
emit?.(EVENTS.status, { phase, label });
|
|
1215
|
+
}
|
|
1216
|
+
/**
|
|
1217
|
+
* Applies patches one by one, keeping those that succeed, and streams the
|
|
1218
|
+
* accepted ones as a single batch. Returns per-patch errors.
|
|
1219
|
+
*/
|
|
1220
|
+
applyMany(patches, emit) {
|
|
1221
|
+
const ok = [];
|
|
1222
|
+
const errors = [];
|
|
1223
|
+
for (const p of patches) {
|
|
1224
|
+
try {
|
|
1225
|
+
this.doc = applyPatch(this.doc, p).doc;
|
|
1226
|
+
ok.push(p);
|
|
1227
|
+
} catch (e) {
|
|
1228
|
+
errors.push(e instanceof Error ? e.message : String(e));
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
if (ok.length) {
|
|
1232
|
+
this.patchesApplied += ok.length;
|
|
1233
|
+
emit?.(EVENTS.patch, { patch: ok.length === 1 ? ok[0] : { op: "batch", patches: ok } });
|
|
1234
|
+
}
|
|
1235
|
+
return { accepted: ok.length, errors };
|
|
1236
|
+
}
|
|
1237
|
+
report() {
|
|
1238
|
+
return validate(this.doc);
|
|
1239
|
+
}
|
|
1240
|
+
/** Issues for specific items, for compact tool results. */
|
|
1241
|
+
issuesFor(ids) {
|
|
1242
|
+
const set = new Set(ids);
|
|
1243
|
+
const r = this.report();
|
|
1244
|
+
return [...r.errors, ...r.warnings].filter((i) => i.itemId && set.has(i.itemId));
|
|
1245
|
+
}
|
|
1246
|
+
};
|
|
1247
|
+
function summariseIssues(issues) {
|
|
1248
|
+
return issues.map((i) => `${i.severity.toUpperCase()} ${i.rule}${i.itemId ? ` [${i.itemId}]` : ""}: ${i.message}`);
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
// ../../src/patent-render/server/tools.ts
|
|
1252
|
+
import { toolDefinition as toolDefinition8 } from "@tanstack/ai";
|
|
1253
|
+
import { z as z11 } from "zod";
|
|
1254
|
+
|
|
1255
|
+
// ../../src/patent-render/server/describe.ts
|
|
1256
|
+
var n = (v) => Math.round(v * 10) / 10;
|
|
1257
|
+
var pt = (p) => `(${n(p[0])},${n(p[1])})`;
|
|
1258
|
+
function itemLine(doc, it) {
|
|
1259
|
+
const b = itemBoundsRotated(doc, it);
|
|
1260
|
+
const flags = [it.hidden && "hidden", it.locked && "locked", it.rotation && `rot=${n(it.rotation)}`].filter(Boolean).join(",");
|
|
1261
|
+
const box = `bbox=${n(b.x)},${n(b.y)} ${n(b.w)}x${n(b.h)}`;
|
|
1262
|
+
let extra = "";
|
|
1263
|
+
switch (it.type) {
|
|
1264
|
+
case "text":
|
|
1265
|
+
extra = `"${it.text.replace(/\n/g, "\\n")}" size=${it.size}`;
|
|
1266
|
+
break;
|
|
1267
|
+
case "numeral":
|
|
1268
|
+
extra = `n=${it.n} at=${pt(it.at)} target=${pt(it.target)}`;
|
|
1269
|
+
break;
|
|
1270
|
+
case "connector":
|
|
1271
|
+
extra = `from=${"itemId" in it.from ? it.from.itemId : pt(it.from.point)} to=${"itemId" in it.to ? it.to.itemId : pt(it.to.point)}${it.label ? ` label="${it.label}"` : ""}`;
|
|
1272
|
+
break;
|
|
1273
|
+
case "line":
|
|
1274
|
+
case "sectionLine":
|
|
1275
|
+
extra = `${pt(it.a)}-${pt(it.b)}`;
|
|
1276
|
+
break;
|
|
1277
|
+
case "rect":
|
|
1278
|
+
extra = it.radius ? `r=${it.radius}` : "";
|
|
1279
|
+
break;
|
|
1280
|
+
case "ellipse":
|
|
1281
|
+
extra = `c=${pt([it.cx, it.cy])} r=${n(it.rx)}x${n(it.ry)}`;
|
|
1282
|
+
break;
|
|
1283
|
+
}
|
|
1284
|
+
const stroke3 = "stroke" in it && it.stroke.style !== "solid" ? ` ${it.stroke.style}` : "";
|
|
1285
|
+
return ` - ${it.id} ${it.type}${it.name ? ` "${it.name}"` : ""} ${box}${extra ? " " + extra : ""}${stroke3}${flags ? ` [${flags}]` : ""}`;
|
|
1286
|
+
}
|
|
1287
|
+
function describeDocument(doc, selection = []) {
|
|
1288
|
+
const { w, h } = sheetDims(doc.sheet);
|
|
1289
|
+
const p = PROFILES[doc.jurisdiction];
|
|
1290
|
+
const m = effectiveMargins(p, doc.sheet.orientation);
|
|
1291
|
+
const lines = [
|
|
1292
|
+
`FIG. ${doc.figureNumber} \xB7 ${p.name} (${p.citation}) \xB7 sheet ${doc.sheet.size.toUpperCase()} ${doc.sheet.orientation} ${n(w)}x${n(h)} mm`,
|
|
1293
|
+
`Usable area (inside margins): x ${m.left}..${n(w - m.right)}, y ${m.top}..${n(h - m.bottom)} mm. Origin top-left, y grows downward.`,
|
|
1294
|
+
`Text and numerals: cap height >= ${p.minCapHeight} mm (use 3.5). Text policy: ${p.text.mode}, max ${p.text.maxWordsPerText} words per text, ${p.text.maxWordsPerCatchword} per connector label.`,
|
|
1295
|
+
`View: ${doc.view}${doc.view === "exploded" ? " (item coordinates below are ASSEMBLED positions; each layer is drawn shifted by its explode offset)" : ""}.`,
|
|
1296
|
+
"",
|
|
1297
|
+
"Layers (first = bottom of z-order):"
|
|
1298
|
+
];
|
|
1299
|
+
for (const l of doc.layers) {
|
|
1300
|
+
const ex = l.explode && (l.explode.dx || l.explode.dy) ? ` explode=(${n(l.explode.dx)},${n(l.explode.dy)})` : "";
|
|
1301
|
+
lines.push(`- layer ${l.id} "${l.name}"${l.visible ? "" : " [hidden]"}${l.locked ? " [locked]" : ""}${ex} (${l.items.length} items)`);
|
|
1302
|
+
for (const it of l.items) lines.push(itemLine(doc, it));
|
|
1303
|
+
}
|
|
1304
|
+
const reg = Object.entries(doc.numerals);
|
|
1305
|
+
lines.push("", reg.length ? `Numeral registry: ${reg.map(([k, v]) => `${k}=${v || "(undescribed)"}`).join("; ")}` : "Numeral registry: empty");
|
|
1306
|
+
if (selection.length) lines.push(`User's current selection: ${selection.join(", ")}`);
|
|
1307
|
+
return lines.join("\n");
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
// ../../src/patent-render/server/skills/diagram.ts
|
|
1311
|
+
import { toolDefinition } from "@tanstack/ai";
|
|
1312
|
+
import { z as z4 } from "zod";
|
|
1313
|
+
import ELK from "elkjs/lib/elk.bundled.js";
|
|
1314
|
+
|
|
1315
|
+
// ../../src/patent-render/geometry/shapes.ts
|
|
1316
|
+
var SHAPE_KINDS = [
|
|
1317
|
+
"process",
|
|
1318
|
+
"block",
|
|
1319
|
+
"decision",
|
|
1320
|
+
"terminal",
|
|
1321
|
+
"io",
|
|
1322
|
+
"document",
|
|
1323
|
+
"database",
|
|
1324
|
+
"subroutine",
|
|
1325
|
+
"manualInput",
|
|
1326
|
+
"preparation",
|
|
1327
|
+
"manualOperation",
|
|
1328
|
+
"delay",
|
|
1329
|
+
"display",
|
|
1330
|
+
"storedData",
|
|
1331
|
+
"connector",
|
|
1332
|
+
"offPage",
|
|
1333
|
+
"annotation"
|
|
1334
|
+
];
|
|
1335
|
+
var SHAPES = [
|
|
1336
|
+
{ kind: "process", label: "Process", hint: "A step or operation", size: { w: 40, h: 16 }, text: "STEP" },
|
|
1337
|
+
{ kind: "block", label: "Block", hint: "A system component (block diagrams)", size: { w: 40, h: 22 }, text: "BLOCK" },
|
|
1338
|
+
{ kind: "decision", label: "Decision", hint: "A yes/no branch", size: { w: 44, h: 26 }, text: "TEST?" },
|
|
1339
|
+
{ kind: "terminal", label: "Terminator", hint: "Start or end", size: { w: 32, h: 12 }, text: "START" },
|
|
1340
|
+
{ kind: "io", label: "Data", hint: "Input or output", size: { w: 40, h: 16 }, text: "DATA" },
|
|
1341
|
+
{ kind: "document", label: "Document", hint: "A document or report", size: { w: 36, h: 20 }, text: "DOC" },
|
|
1342
|
+
{ kind: "database", label: "Database", hint: "Stored data", size: { w: 28, h: 26 }, text: "DB" },
|
|
1343
|
+
{ kind: "subroutine", label: "Predefined process", hint: "A subroutine defined elsewhere", size: { w: 42, h: 16 }, text: "MODULE" },
|
|
1344
|
+
{ kind: "manualInput", label: "Manual input", hint: "Data entered by a person", size: { w: 40, h: 18 }, text: "INPUT" },
|
|
1345
|
+
{ kind: "preparation", label: "Preparation", hint: "Setup or initialisation", size: { w: 42, h: 16 }, text: "INIT" },
|
|
1346
|
+
{ kind: "manualOperation", label: "Manual operation", hint: "A step done by hand", size: { w: 40, h: 16 }, text: "MANUAL" },
|
|
1347
|
+
{ kind: "delay", label: "Delay", hint: "Waiting period", size: { w: 32, h: 16 }, text: "WAIT" },
|
|
1348
|
+
{ kind: "display", label: "Display", hint: "Information shown to a user", size: { w: 40, h: 16 }, text: "SHOW" },
|
|
1349
|
+
{ kind: "storedData", label: "Stored data", hint: "Generic storage", size: { w: 40, h: 16 }, text: "STORE" },
|
|
1350
|
+
{ kind: "connector", label: "On-page connector", hint: "Joins flow lines", size: { w: 10, h: 10 }, text: "A" },
|
|
1351
|
+
{ kind: "offPage", label: "Off-page connector", hint: "Continues on another figure", size: { w: 14, h: 14 }, text: "B" },
|
|
1352
|
+
{ kind: "annotation", label: "Annotation", hint: "Comment bracket", size: { w: 30, h: 16 }, text: "" }
|
|
1353
|
+
];
|
|
1354
|
+
var SHAPE_BY_KIND = Object.fromEntries(SHAPES.map((s) => [s.kind, s]));
|
|
1355
|
+
var r1 = (n2) => Math.round(n2 * 10) / 10;
|
|
1356
|
+
var base2 = { rotation: 0, locked: false, hidden: false };
|
|
1357
|
+
var stroke = { width: 0.35, style: "solid" };
|
|
1358
|
+
function poly(id, name, pts2, closed = true) {
|
|
1359
|
+
return { id, name, type: "polyline", closed, fill: "none", stroke, ...base2, points: pts2.map(([x, y]) => [r1(x), r1(y)]) };
|
|
1360
|
+
}
|
|
1361
|
+
function path(id, name, d) {
|
|
1362
|
+
return { id, name, type: "path", d, fill: "none", stroke, ...base2 };
|
|
1363
|
+
}
|
|
1364
|
+
function shapeItems(id, name, kind, x, y, w, h) {
|
|
1365
|
+
const X = x + w, Y = y + h, cx = x + w / 2, cy = y + h / 2;
|
|
1366
|
+
switch (kind) {
|
|
1367
|
+
case "decision":
|
|
1368
|
+
return [poly(id, name, [[cx, y], [X, cy], [cx, Y], [x, cy]])];
|
|
1369
|
+
case "terminal":
|
|
1370
|
+
return [{ id, name, type: "rect", x, y, w, h, radius: h / 2, fill: "none", stroke, ...base2 }];
|
|
1371
|
+
case "io": {
|
|
1372
|
+
const k = Math.min(6, w * 0.15);
|
|
1373
|
+
return [poly(id, name, [[x + k, y], [X, y], [X - k, Y], [x, Y]])];
|
|
1374
|
+
}
|
|
1375
|
+
case "database": {
|
|
1376
|
+
const ry = Math.min(3.5, h * 0.15);
|
|
1377
|
+
return [path(id, name, `M ${r1(x)} ${r1(y + ry)} A ${r1(w / 2)} ${r1(ry)} 0 0 1 ${r1(X)} ${r1(y + ry)} L ${r1(X)} ${r1(Y - ry)} A ${r1(w / 2)} ${r1(ry)} 0 0 1 ${r1(x)} ${r1(Y - ry)} Z M ${r1(x)} ${r1(y + ry)} A ${r1(w / 2)} ${r1(ry)} 0 0 0 ${r1(X)} ${r1(y + ry)}`)];
|
|
1378
|
+
}
|
|
1379
|
+
case "subroutine":
|
|
1380
|
+
return [
|
|
1381
|
+
{ id, name, type: "rect", x, y, w, h, radius: 0, fill: "none", stroke, ...base2 },
|
|
1382
|
+
{ id: `${id}-bar-l`, type: "line", a: [r1(x + 4), y], b: [r1(x + 4), Y], stroke, ...base2 },
|
|
1383
|
+
{ id: `${id}-bar-r`, type: "line", a: [r1(X - 4), y], b: [r1(X - 4), Y], stroke, ...base2 }
|
|
1384
|
+
];
|
|
1385
|
+
case "document": {
|
|
1386
|
+
const wave = Math.min(4, h * 0.2);
|
|
1387
|
+
return [path(id, name, `M ${r1(x)} ${r1(y)} L ${r1(X)} ${r1(y)} L ${r1(X)} ${r1(Y - wave)} C ${r1(x + w * 0.75)} ${r1(Y - wave * 2.2)} ${r1(x + w * 0.25)} ${r1(Y + wave * 0.8)} ${r1(x)} ${r1(Y - wave)} Z`)];
|
|
1388
|
+
}
|
|
1389
|
+
case "manualInput":
|
|
1390
|
+
return [poly(id, name, [[x, y + h * 0.3], [X, y], [X, Y], [x, Y]])];
|
|
1391
|
+
case "preparation": {
|
|
1392
|
+
const k = Math.min(w * 0.2, h * 0.5);
|
|
1393
|
+
return [poly(id, name, [[x + k, y], [X - k, y], [X, cy], [X - k, Y], [x + k, Y], [x, cy]])];
|
|
1394
|
+
}
|
|
1395
|
+
case "manualOperation": {
|
|
1396
|
+
const k = Math.min(6, w * 0.15);
|
|
1397
|
+
return [poly(id, name, [[x, y], [X, y], [X - k, Y], [x + k, Y]])];
|
|
1398
|
+
}
|
|
1399
|
+
case "delay": {
|
|
1400
|
+
const r = h / 2;
|
|
1401
|
+
return [path(id, name, `M ${r1(x)} ${r1(y)} L ${r1(X - r)} ${r1(y)} A ${r1(r)} ${r1(r)} 0 0 1 ${r1(X - r)} ${r1(Y)} L ${r1(x)} ${r1(Y)} Z`)];
|
|
1402
|
+
}
|
|
1403
|
+
case "display": {
|
|
1404
|
+
const k = Math.min(6, w * 0.15);
|
|
1405
|
+
return [path(id, name, `M ${r1(x + k)} ${r1(y)} L ${r1(X - k)} ${r1(y)} Q ${r1(X + k * 0.4)} ${r1(cy)} ${r1(X - k)} ${r1(Y)} L ${r1(x + k)} ${r1(Y)} L ${r1(x)} ${r1(cy)} Z`)];
|
|
1406
|
+
}
|
|
1407
|
+
case "storedData": {
|
|
1408
|
+
const k = Math.min(5, w * 0.12);
|
|
1409
|
+
return [path(id, name, `M ${r1(x + k)} ${r1(y)} L ${r1(X)} ${r1(y)} Q ${r1(X - k * 1.4)} ${r1(cy)} ${r1(X)} ${r1(Y)} L ${r1(x + k)} ${r1(Y)} Q ${r1(x - k * 0.4)} ${r1(cy)} ${r1(x + k)} ${r1(y)} Z`)];
|
|
1410
|
+
}
|
|
1411
|
+
case "connector": {
|
|
1412
|
+
const r = Math.min(w, h) / 2;
|
|
1413
|
+
return [{ id, name, type: "ellipse", cx: r1(cx), cy: r1(cy), rx: r1(r), ry: r1(r), fill: "none", stroke, ...base2 }];
|
|
1414
|
+
}
|
|
1415
|
+
case "offPage":
|
|
1416
|
+
return [poly(id, name, [[x, y], [X, y], [X, y + h * 0.65], [cx, Y], [x, y + h * 0.65]])];
|
|
1417
|
+
case "annotation":
|
|
1418
|
+
return [poly(id, name, [[x + 6, y], [x, y], [x, Y], [x + 6, Y]], false)];
|
|
1419
|
+
default:
|
|
1420
|
+
return [{ id, name, type: "rect", x, y, w, h, radius: 0, fill: "none", stroke, ...base2 }];
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
// ../../src/patent-render/server/tool-utils.ts
|
|
1425
|
+
var emitOf = (ctx) => ctx?.emitCustomEvent.bind(ctx);
|
|
1426
|
+
function usableArea(doc, reserveBottom = 22) {
|
|
1427
|
+
const { w, h } = sheetDims(doc.sheet);
|
|
1428
|
+
const m = effectiveMargins(PROFILES[doc.jurisdiction], doc.sheet.orientation);
|
|
1429
|
+
return { x: m.left + 2, y: m.top + 2, w: w - m.left - m.right - 4, h: h - m.top - m.bottom - 4 - reserveBottom };
|
|
1430
|
+
}
|
|
1431
|
+
function ensureLayers(doc, layers) {
|
|
1432
|
+
const out = [];
|
|
1433
|
+
const existing = new Set(doc.layers.map((l) => l.id));
|
|
1434
|
+
let annIdx = doc.layers.findIndex((l) => l.id === "annotations");
|
|
1435
|
+
for (const l of layers) {
|
|
1436
|
+
if (existing.has(l.id)) continue;
|
|
1437
|
+
const layer = { id: l.id, name: l.name, visible: true, locked: false, items: [] };
|
|
1438
|
+
out.push({ op: "addLayer", layer, index: annIdx >= 0 ? annIdx : void 0 });
|
|
1439
|
+
if (annIdx >= 0) annIdx += 1;
|
|
1440
|
+
existing.add(l.id);
|
|
1441
|
+
}
|
|
1442
|
+
return out;
|
|
1443
|
+
}
|
|
1444
|
+
var base3 = { rotation: 0, locked: false, hidden: false };
|
|
1445
|
+
var stroke2 = (width = 0.35, style = "solid") => ({ width, style });
|
|
1446
|
+
function addItemsPatches(layerId, items) {
|
|
1447
|
+
return items.map((item) => ({ op: "addItem", layerId, item }));
|
|
1448
|
+
}
|
|
1449
|
+
function textWidth(text, cap = 3.5) {
|
|
1450
|
+
return text.length * (cap / 0.7) * 0.6;
|
|
1451
|
+
}
|
|
1452
|
+
var r12 = (n2) => Math.round(n2 * 10) / 10;
|
|
1453
|
+
|
|
1454
|
+
// ../../src/patent-render/server/skills/diagram.ts
|
|
1455
|
+
var elk = new ELK();
|
|
1456
|
+
var Shape = z4.enum(SHAPE_KINDS);
|
|
1457
|
+
var CAP = 3.5;
|
|
1458
|
+
var LINE_H = CAP / 0.7 * 1.2;
|
|
1459
|
+
function nodeSize(shape, lines) {
|
|
1460
|
+
const tw = Math.max(...lines.map((l) => textWidth(l, CAP)));
|
|
1461
|
+
const th = lines.length * LINE_H;
|
|
1462
|
+
switch (shape) {
|
|
1463
|
+
case "decision":
|
|
1464
|
+
return { w: Math.max(44, tw * 1.6 + 8), h: Math.max(24, th * 2 + 8) };
|
|
1465
|
+
case "terminal":
|
|
1466
|
+
return { w: Math.max(32, tw + 14), h: Math.max(12, th + 5) };
|
|
1467
|
+
case "io":
|
|
1468
|
+
return { w: Math.max(40, tw + 18), h: Math.max(16, th + 8) };
|
|
1469
|
+
case "database":
|
|
1470
|
+
return { w: Math.max(28, tw + 10), h: Math.max(24, th + 14) };
|
|
1471
|
+
default:
|
|
1472
|
+
return { w: Math.max(36, tw + 12), h: Math.max(16, th + 8) };
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
var LayoutInput = z4.object({
|
|
1476
|
+
direction: z4.enum(["DOWN", "RIGHT"]).default("DOWN"),
|
|
1477
|
+
layers: z4.object({
|
|
1478
|
+
shapes: z4.string().default("steps"),
|
|
1479
|
+
labels: z4.string().default("labels"),
|
|
1480
|
+
flow: z4.string().default("flow"),
|
|
1481
|
+
annotations: z4.string().default("annotations")
|
|
1482
|
+
}).default({ shapes: "steps", labels: "labels", flow: "flow", annotations: "annotations" }),
|
|
1483
|
+
nodes: z4.array(z4.object({
|
|
1484
|
+
id: z4.string(),
|
|
1485
|
+
label: z4.string().meta({ description: "Short label; use \\n for a second line. Keep within the jurisdiction's word limit." }),
|
|
1486
|
+
shape: Shape.default("process"),
|
|
1487
|
+
numeral: z4.string().optional().meta({ description: "Reference numeral for this element, e.g. 302." })
|
|
1488
|
+
})).min(1),
|
|
1489
|
+
edges: z4.array(z4.object({
|
|
1490
|
+
from: z4.string(),
|
|
1491
|
+
to: z4.string(),
|
|
1492
|
+
label: z4.string().optional().meta({ description: "Catchword such as YES / NO." }),
|
|
1493
|
+
arrow: z4.enum(["end", "both", "none"]).default("end")
|
|
1494
|
+
})).default([]),
|
|
1495
|
+
numeralSide: z4.enum(["left", "right"]).default("left"),
|
|
1496
|
+
area: z4.object({ x: z4.number(), y: z4.number(), w: z4.number(), h: z4.number() }).optional().meta({ description: "Region to fit the graph in (mm). Defaults to the usable area above the FIG. label." })
|
|
1497
|
+
});
|
|
1498
|
+
async function layoutGraph(session, input, ctx) {
|
|
1499
|
+
const area = input.area ?? usableArea(session.doc);
|
|
1500
|
+
const labels = new Map(input.nodes.map((n2) => [n2.id, n2.label.split("\n")]));
|
|
1501
|
+
const sizes = new Map(input.nodes.map((n2) => [n2.id, nodeSize(n2.shape, labels.get(n2.id))]));
|
|
1502
|
+
const graph = await elk.layout({
|
|
1503
|
+
id: "root",
|
|
1504
|
+
layoutOptions: {
|
|
1505
|
+
"elk.algorithm": "layered",
|
|
1506
|
+
"elk.direction": input.direction,
|
|
1507
|
+
"elk.spacing.nodeNode": "12",
|
|
1508
|
+
"elk.layered.spacing.nodeNodeBetweenLayers": "14",
|
|
1509
|
+
"elk.edgeRouting": "ORTHOGONAL",
|
|
1510
|
+
"elk.layered.nodePlacement.strategy": "BRANDES_KOEPF"
|
|
1511
|
+
},
|
|
1512
|
+
children: input.nodes.map((n2) => ({ id: n2.id, width: sizes.get(n2.id).w, height: sizes.get(n2.id).h })),
|
|
1513
|
+
edges: input.edges.map((e, i) => ({ id: `e${i}`, sources: [e.from], targets: [e.to] }))
|
|
1514
|
+
});
|
|
1515
|
+
const g = graph;
|
|
1516
|
+
const gw = g.width ?? 1, gh = g.height ?? 1;
|
|
1517
|
+
const gutter = input.nodes.some((n2) => n2.numeral) ? 16 : 0;
|
|
1518
|
+
const s = Math.min(1, (area.w - gutter) / gw, area.h / gh);
|
|
1519
|
+
const ox = area.x + (input.numeralSide === "left" ? gutter : 0) + Math.max(0, (area.w - gutter - gw * s) / 2);
|
|
1520
|
+
const oy = area.y;
|
|
1521
|
+
const shapes = [], texts = [], flow = [], anns = [];
|
|
1522
|
+
const boxes = {};
|
|
1523
|
+
for (const c of g.children ?? []) {
|
|
1524
|
+
const node = input.nodes.find((n2) => n2.id === c.id);
|
|
1525
|
+
const x = r12(ox + (c.x ?? 0) * s), y = r12(oy + (c.y ?? 0) * s), w = r12((c.width ?? 0) * s), h = r12((c.height ?? 0) * s);
|
|
1526
|
+
boxes[node.id] = { x, y, w, h };
|
|
1527
|
+
shapes.push(...shapeItems(node.id, node.label.replace(/\n/g, " "), node.shape, x, y, w, h));
|
|
1528
|
+
const lines = labels.get(node.id);
|
|
1529
|
+
const firstBaseline = y + h / 2 - (lines.length - 1) * LINE_H / 2 + CAP / 2;
|
|
1530
|
+
texts.push({ id: `${node.id}-t`, type: "text", x: r12(x + w / 2), y: r12(firstBaseline), text: lines.join("\n"), size: CAP, anchor: "middle", ...base3 });
|
|
1531
|
+
if (node.numeral) {
|
|
1532
|
+
const left = input.numeralSide === "left";
|
|
1533
|
+
const edgeX = node.shape === "decision" ? x + (left ? w * 0.18 : w * 0.82) : left ? x : x + w;
|
|
1534
|
+
const target = [r12(edgeX), r12(y + h * (node.shape === "decision" ? 0.32 : 0.35))];
|
|
1535
|
+
const at = [r12(left ? x - 9 : x + w + 9), r12(y - 2)];
|
|
1536
|
+
anns.push({ id: `n${node.numeral}-${node.id}`, type: "numeral", n: node.numeral, at, target, leader: "curved", underline: false, size: CAP, ...base3 });
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
const down = input.direction === "DOWN";
|
|
1540
|
+
const fwd = down ? "bottom" : "right", back = down ? "top" : "left";
|
|
1541
|
+
const sideways = (from, to) => {
|
|
1542
|
+
const a = boxes[from], b = boxes[to];
|
|
1543
|
+
return down ? b.x + b.w / 2 >= a.x + a.w / 2 ? "right" : "left" : b.y + b.h / 2 >= a.y + a.h / 2 ? "bottom" : "top";
|
|
1544
|
+
};
|
|
1545
|
+
const shapeOf = new Map(input.nodes.map((n2) => [n2.id, n2.shape]));
|
|
1546
|
+
const outCount = /* @__PURE__ */ new Map();
|
|
1547
|
+
input.edges.forEach((e, i) => {
|
|
1548
|
+
const a = boxes[e.from], b = boxes[e.to];
|
|
1549
|
+
if (!a || !b) return;
|
|
1550
|
+
const k = outCount.get(e.from) ?? 0;
|
|
1551
|
+
outCount.set(e.from, k + 1);
|
|
1552
|
+
const sides = {};
|
|
1553
|
+
const backwards = down ? b.y + b.h <= a.y : b.x + b.w <= a.x;
|
|
1554
|
+
if (backwards) {
|
|
1555
|
+
sides.fromSide = down ? "right" : "bottom";
|
|
1556
|
+
sides.toSide = sides.fromSide;
|
|
1557
|
+
} else if (shapeOf.get(e.from) === "decision") {
|
|
1558
|
+
if (k === 0) {
|
|
1559
|
+
sides.fromSide = fwd;
|
|
1560
|
+
sides.toSide = back;
|
|
1561
|
+
} else {
|
|
1562
|
+
sides.fromSide = sideways(e.from, e.to);
|
|
1563
|
+
sides.toSide = back;
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
flow.push({
|
|
1567
|
+
id: `${e.from}-${e.to}-${i}`,
|
|
1568
|
+
type: "connector",
|
|
1569
|
+
from: { itemId: e.from },
|
|
1570
|
+
to: { itemId: e.to },
|
|
1571
|
+
routing: "orthogonal",
|
|
1572
|
+
arrow: e.arrow,
|
|
1573
|
+
arrowStyle: "filled",
|
|
1574
|
+
stroke: stroke2(),
|
|
1575
|
+
...base3,
|
|
1576
|
+
...sides,
|
|
1577
|
+
...e.label ? { label: e.label } : {}
|
|
1578
|
+
});
|
|
1579
|
+
});
|
|
1580
|
+
const L = input.layers;
|
|
1581
|
+
const patches = [
|
|
1582
|
+
...ensureLayers(session.doc, [
|
|
1583
|
+
{ id: L.shapes, name: "Shapes" },
|
|
1584
|
+
{ id: L.labels, name: "Labels" },
|
|
1585
|
+
{ id: L.flow, name: "Flow" },
|
|
1586
|
+
{ id: L.annotations, name: "Annotations" }
|
|
1587
|
+
]),
|
|
1588
|
+
...addItemsPatches(L.shapes, shapes),
|
|
1589
|
+
...addItemsPatches(L.labels, texts),
|
|
1590
|
+
...addItemsPatches(L.flow, flow),
|
|
1591
|
+
...addItemsPatches(L.annotations, anns)
|
|
1592
|
+
];
|
|
1593
|
+
const emit = emitOf(ctx);
|
|
1594
|
+
session.status(emit, "drawing", "Laying out the diagram");
|
|
1595
|
+
const r = session.applyMany(patches, emit);
|
|
1596
|
+
const numerals = input.nodes.filter((n2) => n2.numeral).map((n2) => n2.numeral);
|
|
1597
|
+
return {
|
|
1598
|
+
ok: r.errors.length === 0,
|
|
1599
|
+
scale: r12(s),
|
|
1600
|
+
nodes: boxes,
|
|
1601
|
+
...s < 0.999 ? { note: "Graph was scaled down to fit; check that labels still fit their shapes." } : {},
|
|
1602
|
+
...numerals.length ? { reminder: `Describe numerals ${numerals.join(", ")} with set_numerals if not already in the registry.` } : {},
|
|
1603
|
+
...r.errors.length ? { errors: r.errors } : {}
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
var diagramSkill = {
|
|
1607
|
+
types: ["flowchart", "blockDiagram"],
|
|
1608
|
+
title: "Flowcharts and block diagrams",
|
|
1609
|
+
instructions: `
|
|
1610
|
+
Use layout_graph to draw flowcharts and block/system diagrams. Do not place boxes by hand unless adjusting afterwards.
|
|
1611
|
+
|
|
1612
|
+
Flowcharts (method claims):
|
|
1613
|
+
- One node per claimed step, in claim order. Shapes: terminal (START/END, optional), process (step), decision (branch), io (data in/out).
|
|
1614
|
+
- START and END terminals get NO reference numeral; only steps, decisions and data elements are numbered.
|
|
1615
|
+
- Step numerals follow the figure series: FIG. 3 uses 302, 304, 306... (even numbers, step 2). Reuse registry numerals for the same steps.
|
|
1616
|
+
- Labels are short imperative phrases ("Receive sensor data"), 2-4 words. Long claim language belongs in the description, not the figure.
|
|
1617
|
+
- Decisions have exactly two labelled exits: YES and NO. Loops go back to an earlier node.
|
|
1618
|
+
- Direction DOWN. Numerals on the left.
|
|
1619
|
+
|
|
1620
|
+
Block / system diagrams (apparatus claims):
|
|
1621
|
+
- One node per component; nest is not supported, so draw the system boundary afterwards as a dashed rect around the blocks and give it the underlined system numeral (e.g. 100) with underline: true.
|
|
1622
|
+
- Shapes: block for components, database for data stores, io for interfaces. Labels are UPPERCASE nouns ("SERVER", "NETWORK").
|
|
1623
|
+
- Edges between communicating components; use arrow "both" for bidirectional links.
|
|
1624
|
+
- Direction DOWN for hierarchies, RIGHT for pipelines.
|
|
1625
|
+
|
|
1626
|
+
After layout_graph: set_numerals for every numeral used, check the FIG. label sits centred below the drawing (move fig-label with update_items if needed), run check_compliance, then review_drawing.
|
|
1627
|
+
`.trim(),
|
|
1628
|
+
tools: (session) => [
|
|
1629
|
+
toolDefinition({
|
|
1630
|
+
name: "layout_graph",
|
|
1631
|
+
description: "Auto-layout a flowchart or block diagram (ELK layered layout) and add it to the drawing: shapes, centred labels, attached orthogonal connectors and reference numerals. Returns each node's box in mm.",
|
|
1632
|
+
inputSchema: LayoutInput
|
|
1633
|
+
}).server(async (raw, ctx) => layoutGraph(session, LayoutInput.parse(raw), ctx))
|
|
1634
|
+
]
|
|
1635
|
+
};
|
|
1636
|
+
|
|
1637
|
+
// ../../src/patent-render/server/skills/mechanical.ts
|
|
1638
|
+
import { toolDefinition as toolDefinition2 } from "@tanstack/ai";
|
|
1639
|
+
import { z as z5 } from "zod";
|
|
1640
|
+
var mechanicalSkill = {
|
|
1641
|
+
types: ["mechanical2d"],
|
|
1642
|
+
title: "Mechanical 2D views (orthographic, section, exploded)",
|
|
1643
|
+
instructions: `
|
|
1644
|
+
Draw mechanical parts as clean black line art built from rect, ellipse, arc, polyline and path items.
|
|
1645
|
+
|
|
1646
|
+
Views
|
|
1647
|
+
- Choose the view that shows the claimed features: front/side/top orthographic, sectional ("taken along line A-A"), or exploded.
|
|
1648
|
+
- One figure = one view. Make the object large: it should fill 60-80% of the usable area. Keep proportions believable.
|
|
1649
|
+
- Sectional view: draw the cut faces with hatch items (45\xB0, spacing 1.5-2 mm). Adjacent parts get opposite angles (45\xB0 / 135\xB0) so they read as separate parts. Do not hatch shafts, bolts or pins cut along their axis.
|
|
1650
|
+
- Mark the cutting plane on the view it is taken from with a sectionLine (label "A"), and say "Section A-A" only in the description, not on the figure.
|
|
1651
|
+
- Exploded view: draw the parts ASSEMBLED (composite) on their own layers, then call set_exploded_view with view "exploded" and auto "y" (or "x"), or explicit per-layer offsets. Alignment lines are drawn automatically. The same model then serves both the assembled and the exploded figure.
|
|
1652
|
+
|
|
1653
|
+
Line conventions (stroke.style)
|
|
1654
|
+
- solid 0.35-0.5 mm: visible edges (outlines 0.5, details 0.35).
|
|
1655
|
+
- dashed 0.3 mm: hidden edges, used sparingly.
|
|
1656
|
+
- centre 0.25 mm: axes of symmetry and hole centres; extend 3-4 mm past the part.
|
|
1657
|
+
- phantom: alternate positions or adjacent parts shown for context.
|
|
1658
|
+
- No shading, no grey, no colour. Solid black fill only for very thin cut sections (e.g. gaskets).
|
|
1659
|
+
|
|
1660
|
+
Layers and numerals
|
|
1661
|
+
- One layer per component, named with its numeral ("Housing 202"). Keep numerals and the FIG. label on the "annotations" layer.
|
|
1662
|
+
- Numerals sit outside the part, 8-15 mm away, with curved leaders that touch the part they name and never cross each other. Spread them around the figure; do not stack them on one side.
|
|
1663
|
+
- The same part shown twice uses the same numeral. Sub-parts can use letter suffixes (208a, 208b).
|
|
1664
|
+
- A numeral for a whole assembly is underlined (underline: true) with a leader ending at the assembly's edge.
|
|
1665
|
+
|
|
1666
|
+
Workflow: plan components \u2192 add layers \u2192 outlines \u2192 interior detail \u2192 hatching \u2192 centre lines \u2192 numerals \u2192 set_numerals \u2192 check_compliance \u2192 review_drawing. Use mirror_items for symmetric halves.
|
|
1667
|
+
`.trim(),
|
|
1668
|
+
tools: (session) => [
|
|
1669
|
+
toolDefinition2({
|
|
1670
|
+
name: "mirror_items",
|
|
1671
|
+
description: "Create mirrored copies of items across a vertical line x=\u2026 or horizontal line y=\u2026 (for symmetric parts). New ids get the given suffix.",
|
|
1672
|
+
inputSchema: z5.object({
|
|
1673
|
+
ids: z5.array(z5.string()).min(1),
|
|
1674
|
+
axis: z5.union([z5.object({ x: z5.number() }), z5.object({ y: z5.number() })]),
|
|
1675
|
+
suffix: z5.string().default("-m"),
|
|
1676
|
+
layerId: z5.string().optional().meta({ description: "Target layer; defaults to each item's own layer." })
|
|
1677
|
+
})
|
|
1678
|
+
}).server(async ({ ids, axis, suffix = "-m", layerId }, ctx) => {
|
|
1679
|
+
const patches = [];
|
|
1680
|
+
const created = [];
|
|
1681
|
+
for (const id of ids) {
|
|
1682
|
+
const loc = findItem(session.doc, id);
|
|
1683
|
+
if (!loc) continue;
|
|
1684
|
+
const origin = "x" in axis ? [axis.x, 0] : [0, axis.y];
|
|
1685
|
+
const sx = "x" in axis ? -1 : 1, sy = "y" in axis ? -1 : 1;
|
|
1686
|
+
const copy = { ...loc.item, ...scaleChanges(loc.item, origin, sx, sy), id: `${id}${suffix}` };
|
|
1687
|
+
if (copy.type === "arc" && loc.item.type === "arc") {
|
|
1688
|
+
const a = loc.item;
|
|
1689
|
+
Object.assign(copy, "x" in axis ? { start: 180 - a.end, end: 180 - a.start } : { start: -a.end, end: -a.start });
|
|
1690
|
+
}
|
|
1691
|
+
if (copy.rotation) copy.rotation = (360 - copy.rotation) % 360;
|
|
1692
|
+
patches.push({ op: "addItem", layerId: layerId ?? session.doc.layers[loc.layerIndex].id, item: copy, index: void 0 });
|
|
1693
|
+
created.push(copy.id);
|
|
1694
|
+
}
|
|
1695
|
+
const r = session.applyMany(patches, emitOf(ctx));
|
|
1696
|
+
return { ok: r.errors.length === 0, created, ...r.errors.length ? { errors: r.errors } : {} };
|
|
1697
|
+
})
|
|
1698
|
+
]
|
|
1699
|
+
};
|
|
1700
|
+
|
|
1701
|
+
// ../../src/patent-render/server/skills/ui-screen.ts
|
|
1702
|
+
import { toolDefinition as toolDefinition3 } from "@tanstack/ai";
|
|
1703
|
+
import { z as z6 } from "zod";
|
|
1704
|
+
var FRAMES = {
|
|
1705
|
+
phone: { aspect: 2.05, radius: 7, bezel: 3.5, statusBar: 6 },
|
|
1706
|
+
tablet: { aspect: 1.38, radius: 6, bezel: 5, statusBar: 5 },
|
|
1707
|
+
desktop: { aspect: 0.66, radius: 2, bezel: 2.5, statusBar: 0 },
|
|
1708
|
+
browser: { aspect: 0.66, radius: 2, bezel: 0, statusBar: 9 }
|
|
1709
|
+
};
|
|
1710
|
+
var uiScreenSkill = {
|
|
1711
|
+
types: ["uiScreen"],
|
|
1712
|
+
title: "User-interface screens",
|
|
1713
|
+
instructions: `
|
|
1714
|
+
GUI figures show a screen as line art. Start with device_frame, then draw inside the returned screen box.
|
|
1715
|
+
|
|
1716
|
+
- Represent UI elements with simple outlines: rect (buttons, fields, cards, radius 1-2 mm), ellipse (avatars, radio buttons), lines (dividers, text placeholders).
|
|
1717
|
+
- Text in UI figures: only short, meaningful labels that the claims rely on (e.g. "PAY", "Settings"). Replace body copy with 2-3 horizontal placeholder lines (0.35 mm). Text height at least 3.5 mm even if real UI text is smaller.
|
|
1718
|
+
- No colour, no screenshots, no gradients, no icons with fills. Icons become simple outline glyphs or a labelled box.
|
|
1719
|
+
- Numerals point at the UI elements the claims mention (e.g. 402 = payment button), placed outside the device frame with leaders entering the screen.
|
|
1720
|
+
- One layer for the frame, one per screen region (header, content, footer), annotations on top.
|
|
1721
|
+
- For a sequence of screens, draw one screen per figure (FIG. 4A, 4B), not several on one sheet.
|
|
1722
|
+
`.trim(),
|
|
1723
|
+
tools: (session) => [
|
|
1724
|
+
toolDefinition3({
|
|
1725
|
+
name: "device_frame",
|
|
1726
|
+
description: "Draw a device outline (phone, tablet, desktop monitor, browser window) and return the inner screen box (mm) to draw the UI into.",
|
|
1727
|
+
inputSchema: z6.object({
|
|
1728
|
+
kind: z6.enum(["phone", "tablet", "desktop", "browser"]),
|
|
1729
|
+
layerId: z6.string().default("frame"),
|
|
1730
|
+
width: z6.number().optional().meta({ description: "Outer width in mm; defaults to fit the usable area." }),
|
|
1731
|
+
x: z6.number().optional(),
|
|
1732
|
+
y: z6.number().optional()
|
|
1733
|
+
})
|
|
1734
|
+
}).server(async ({ kind, layerId: lid, width, x, y }, ctx) => {
|
|
1735
|
+
const layerId = lid ?? "frame";
|
|
1736
|
+
const f = FRAMES[kind];
|
|
1737
|
+
const area = usableArea(session.doc);
|
|
1738
|
+
const w = width ?? Math.min(area.w * (kind === "phone" ? 0.55 : 0.9), area.h / f.aspect);
|
|
1739
|
+
const h = w * f.aspect;
|
|
1740
|
+
const ox = x ?? area.x + (area.w - w) / 2, oy = y ?? area.y;
|
|
1741
|
+
const items = [{ id: `${layerId}-outer`, name: `${kind} frame`, type: "rect", x: r12(ox), y: r12(oy), w: r12(w), h: r12(h), radius: f.radius, fill: "none", stroke: stroke2(0.5), ...base3 }];
|
|
1742
|
+
let screen = { x: ox + f.bezel, y: oy + f.bezel, w: w - 2 * f.bezel, h: h - 2 * f.bezel };
|
|
1743
|
+
if (kind === "phone" || kind === "tablet") {
|
|
1744
|
+
screen = { x: ox + f.bezel, y: oy + f.bezel * 2.4, w: w - 2 * f.bezel, h: h - f.bezel * 4.8 };
|
|
1745
|
+
items.push({ id: `${layerId}-screen`, name: "Screen", type: "rect", ...rnd(screen), radius: 1, fill: "none", stroke: stroke2(0.35), ...base3 });
|
|
1746
|
+
}
|
|
1747
|
+
if (kind === "desktop") {
|
|
1748
|
+
items.push(
|
|
1749
|
+
{ id: `${layerId}-screen`, name: "Screen", type: "rect", ...rnd(screen), radius: 0, fill: "none", stroke: stroke2(0.35), ...base3 },
|
|
1750
|
+
{
|
|
1751
|
+
id: `${layerId}-stand`,
|
|
1752
|
+
name: "Stand",
|
|
1753
|
+
type: "polyline",
|
|
1754
|
+
closed: true,
|
|
1755
|
+
fill: "none",
|
|
1756
|
+
stroke: stroke2(0.5),
|
|
1757
|
+
...base3,
|
|
1758
|
+
points: [[r12(ox + w * 0.42), r12(oy + h)], [r12(ox + w * 0.58), r12(oy + h)], [r12(ox + w * 0.62), r12(oy + h + 10)], [r12(ox + w * 0.38), r12(oy + h + 10)]]
|
|
1759
|
+
}
|
|
1760
|
+
);
|
|
1761
|
+
}
|
|
1762
|
+
if (kind === "browser") {
|
|
1763
|
+
items.push({ id: `${layerId}-bar`, name: "Address bar", type: "line", a: [r12(ox), r12(oy + f.statusBar)], b: [r12(ox + w), r12(oy + f.statusBar)], stroke: stroke2(0.35), ...base3 });
|
|
1764
|
+
screen = { x: ox, y: oy + f.statusBar, w, h: h - f.statusBar };
|
|
1765
|
+
}
|
|
1766
|
+
const r = session.applyMany([...ensureLayers(session.doc, [{ id: layerId, name: "Device" }]), ...addItemsPatches(layerId, items)], emitOf(ctx));
|
|
1767
|
+
return { ok: r.errors.length === 0, screen: rnd(screen), ...r.errors.length ? { errors: r.errors } : {} };
|
|
1768
|
+
})
|
|
1769
|
+
]
|
|
1770
|
+
};
|
|
1771
|
+
function rnd(b) {
|
|
1772
|
+
return { x: r12(b.x), y: r12(b.y), w: r12(b.w), h: r12(b.h) };
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
// ../../src/patent-render/server/skills/perspective.ts
|
|
1776
|
+
import { toolDefinition as toolDefinition4 } from "@tanstack/ai";
|
|
1777
|
+
import { z as z7 } from "zod";
|
|
1778
|
+
var C30 = Math.cos(Math.PI / 6);
|
|
1779
|
+
var iso = ([x, y, z13]) => [(x - y) * C30, (x + y) * 0.5 - z13];
|
|
1780
|
+
var depth = ([x, y, z13]) => x + y + z13;
|
|
1781
|
+
var Solid = z7.discriminatedUnion("kind", [
|
|
1782
|
+
z7.object({
|
|
1783
|
+
kind: z7.literal("box"),
|
|
1784
|
+
id: z7.string(),
|
|
1785
|
+
name: z7.string().optional(),
|
|
1786
|
+
position: vec(3).meta({ description: "Min corner [x, y, z] in model units." }),
|
|
1787
|
+
size: vec(3).meta({ description: "[width x, depth y, height z]" })
|
|
1788
|
+
}),
|
|
1789
|
+
z7.object({
|
|
1790
|
+
kind: z7.literal("cylinder"),
|
|
1791
|
+
id: z7.string(),
|
|
1792
|
+
name: z7.string().optional(),
|
|
1793
|
+
base: vec(3).meta({ description: "Centre of the base circle." }),
|
|
1794
|
+
radius: z7.number().positive(),
|
|
1795
|
+
length: z7.number().positive(),
|
|
1796
|
+
axis: z7.enum(["x", "y", "z"]).default("z")
|
|
1797
|
+
})
|
|
1798
|
+
]);
|
|
1799
|
+
function circle(c, r, axis, n2 = 48) {
|
|
1800
|
+
const out = [];
|
|
1801
|
+
for (let i = 0; i < n2; i++) {
|
|
1802
|
+
const t = i / n2 * Math.PI * 2, a = Math.cos(t) * r, b = Math.sin(t) * r;
|
|
1803
|
+
out.push(axis === "z" ? [c[0] + a, c[1] + b, c[2]] : axis === "x" ? [c[0], c[1] + a, c[2] + b] : [c[0] + a, c[1], c[2] + b]);
|
|
1804
|
+
}
|
|
1805
|
+
return out;
|
|
1806
|
+
}
|
|
1807
|
+
function hull(pts2) {
|
|
1808
|
+
const p = [...pts2].sort((a, b) => a[0] - b[0] || a[1] - b[1]);
|
|
1809
|
+
const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
|
|
1810
|
+
const lo = [], up = [];
|
|
1811
|
+
for (const q of p) {
|
|
1812
|
+
while (lo.length >= 2 && cross(lo[lo.length - 2], lo[lo.length - 1], q) <= 0) lo.pop();
|
|
1813
|
+
lo.push(q);
|
|
1814
|
+
}
|
|
1815
|
+
for (const q of p.reverse()) {
|
|
1816
|
+
while (up.length >= 2 && cross(up[up.length - 2], up[up.length - 1], q) <= 0) up.pop();
|
|
1817
|
+
up.push(q);
|
|
1818
|
+
}
|
|
1819
|
+
return [...lo.slice(0, -1), ...up.slice(0, -1)];
|
|
1820
|
+
}
|
|
1821
|
+
function toShape(s) {
|
|
1822
|
+
if (s.kind === "box") {
|
|
1823
|
+
const [x, y, z13] = s.position, [w, d, h] = s.size;
|
|
1824
|
+
const X = x + w, Y = y + d, Z = z13 + h;
|
|
1825
|
+
const top = [[x, y, Z], [X, y, Z], [X, Y, Z], [x, Y, Z]];
|
|
1826
|
+
const px = [[X, y, z13], [X, Y, z13], [X, Y, Z], [X, y, Z]];
|
|
1827
|
+
const py = [[x, Y, z13], [X, Y, z13], [X, Y, Z], [x, Y, Z]];
|
|
1828
|
+
return { id: s.id, name: s.name, depth: depth([x + w / 2, y + d / 2, z13 + h / 2]), polys: [top, px, py] };
|
|
1829
|
+
}
|
|
1830
|
+
const { base: b, radius: r, length: L, axis } = s;
|
|
1831
|
+
const end = axis === "z" ? [b[0], b[1], b[2] + L] : axis === "x" ? [b[0] + L, b[1], b[2]] : [b[0], b[1] + L, b[2]];
|
|
1832
|
+
const c0 = circle(b, r, axis), c1 = circle(end, r, axis);
|
|
1833
|
+
const nearCap = depth(end) >= depth(b) ? c1 : c0;
|
|
1834
|
+
const mid = [(b[0] + end[0]) / 2, (b[1] + end[1]) / 2, (b[2] + end[2]) / 2];
|
|
1835
|
+
return { id: s.id, name: s.name, depth: depth(mid), polys: [], outline: [...c0, ...c1], extra: [nearCap] };
|
|
1836
|
+
}
|
|
1837
|
+
var perspectiveSkill = {
|
|
1838
|
+
types: ["perspective3d"],
|
|
1839
|
+
title: "Perspective / isometric views",
|
|
1840
|
+
instructions: `
|
|
1841
|
+
Perspective figures give an overall impression of a device. Build them from simple solids with project_solids, then add details.
|
|
1842
|
+
|
|
1843
|
+
- Model the object in your own units (e.g. millimetres of the real device) as boxes and cylinders (axis x, y or z). Keep solids from interpenetrating: occlusion is resolved by drawing nearer solids over farther ones.
|
|
1844
|
+
- project_solids projects isometrically, fits everything into the usable area (or a given region), and returns the screen position of each solid's anchors (top-face centre, front faces) for placing numerals and extra detail.
|
|
1845
|
+
- Add features (buttons, slots, holes, edges) as extra lines/ellipses on top, using the returned anchors and bounding boxes. Holes on a top face are ellipses with rx \u2248 1.73 \xD7 ry.
|
|
1846
|
+
- Surface shading is allowed only as a few parallel lines on curved surfaces (optional). No fills, no grey.
|
|
1847
|
+
- Numerals: leaders end on the visible face of the part.
|
|
1848
|
+
`.trim(),
|
|
1849
|
+
tools: (session) => [
|
|
1850
|
+
toolDefinition4({
|
|
1851
|
+
name: "project_solids",
|
|
1852
|
+
description: "Draw an isometric line-art view of boxes and cylinders with hidden surfaces removed (painter's algorithm, white-filled faces). Fits into the usable area. Returns per-solid screen boxes and anchor points in mm.",
|
|
1853
|
+
inputSchema: z7.object({
|
|
1854
|
+
layerId: z7.string().default("body"),
|
|
1855
|
+
layerName: z7.string().default("Body"),
|
|
1856
|
+
solids: z7.array(Solid).min(1),
|
|
1857
|
+
area: z7.object({ x: z7.number(), y: z7.number(), w: z7.number(), h: z7.number() }).optional(),
|
|
1858
|
+
fill: z7.number().min(0.2).max(1).default(0.75).meta({ description: "Fraction of the area to fill." })
|
|
1859
|
+
})
|
|
1860
|
+
}).server(async ({ layerId: lid, layerName: lname, solids: rawSolids, area, fill = 0.75 }, ctx) => {
|
|
1861
|
+
const layerId = lid ?? "body", layerName = lname ?? "Body";
|
|
1862
|
+
const solids = rawSolids.map((s) => Solid.parse(s));
|
|
1863
|
+
const shapes = solids.map(toShape).sort((a, b) => a.depth - b.depth);
|
|
1864
|
+
const all = shapes.flatMap((s) => [...s.polys.flat(), ...s.outline ?? []].map(iso));
|
|
1865
|
+
const xs = all.map((p) => p[0]), ys = all.map((p) => p[1]);
|
|
1866
|
+
const minX = Math.min(...xs), maxX = Math.max(...xs), minY = Math.min(...ys), maxY = Math.max(...ys);
|
|
1867
|
+
const A = area ?? usableArea(session.doc);
|
|
1868
|
+
const k = Math.min(A.w * fill / (maxX - minX || 1), A.h * fill / (maxY - minY || 1));
|
|
1869
|
+
const ox = A.x + (A.w - (maxX - minX) * k) / 2 - minX * k;
|
|
1870
|
+
const oy = A.y + (A.h - (maxY - minY) * k) / 2 - minY * k;
|
|
1871
|
+
const P = (v) => {
|
|
1872
|
+
const [sx, sy] = iso(v);
|
|
1873
|
+
return [r12(ox + sx * k), r12(oy + sy * k)];
|
|
1874
|
+
};
|
|
1875
|
+
const items = [];
|
|
1876
|
+
const anchors = {};
|
|
1877
|
+
for (const s of shapes) {
|
|
1878
|
+
const solid = solids.find((x) => x.id === s.id);
|
|
1879
|
+
const a = {};
|
|
1880
|
+
if (s.polys.length) {
|
|
1881
|
+
const names = ["top", "right", "front"];
|
|
1882
|
+
s.polys.forEach((poly2, i) => {
|
|
1883
|
+
const pts3 = poly2.map(P);
|
|
1884
|
+
items.push({ id: `${s.id}-${names[i]}`, name: `${s.name ?? s.id} ${names[i]}`, type: "polyline", closed: true, fill: "white", points: pts3, stroke: stroke2(0.4), ...base3 });
|
|
1885
|
+
a[names[i]] = [r12(pts3.reduce((t, p) => t + p[0], 0) / pts3.length), r12(pts3.reduce((t, p) => t + p[1], 0) / pts3.length)];
|
|
1886
|
+
});
|
|
1887
|
+
} else if (s.outline) {
|
|
1888
|
+
const sil = hull(s.outline.map(P));
|
|
1889
|
+
items.push({ id: `${s.id}-body`, name: s.name ?? s.id, type: "polyline", closed: true, fill: "white", points: sil, stroke: stroke2(0.4), ...base3 });
|
|
1890
|
+
for (const [i, cap] of (s.extra ?? []).entries()) {
|
|
1891
|
+
const pts3 = cap.map(P);
|
|
1892
|
+
items.push({ id: `${s.id}-cap${i}`, name: `${s.name ?? s.id} end`, type: "polyline", closed: true, fill: "white", points: pts3, stroke: stroke2(0.4), ...base3 });
|
|
1893
|
+
a.cap = [r12(pts3.reduce((t, p) => t + p[0], 0) / pts3.length), r12(pts3.reduce((t, p) => t + p[1], 0) / pts3.length)];
|
|
1894
|
+
}
|
|
1895
|
+
const sp = sil;
|
|
1896
|
+
a.side = [r12(sp.reduce((t, p) => t + p[0], 0) / sp.length), r12(sp.reduce((t, p) => t + p[1], 0) / sp.length)];
|
|
1897
|
+
}
|
|
1898
|
+
const pts2 = items.filter((it) => it.id.startsWith(`${s.id}-`)).flatMap((it) => it.type === "polyline" ? it.points : []);
|
|
1899
|
+
const bx = Math.min(...pts2.map((p) => p[0])), by = Math.min(...pts2.map((p) => p[1]));
|
|
1900
|
+
a.bbox = { x: r12(bx), y: r12(by), w: r12(Math.max(...pts2.map((p) => p[0])) - bx), h: r12(Math.max(...pts2.map((p) => p[1])) - by) };
|
|
1901
|
+
anchors[solid.id] = a;
|
|
1902
|
+
}
|
|
1903
|
+
const r = session.applyMany([...ensureLayers(session.doc, [{ id: layerId, name: layerName }]), ...addItemsPatches(layerId, items)], emitOf(ctx));
|
|
1904
|
+
return { ok: r.errors.length === 0, scale: r12(k), anchors, ...r.errors.length ? { errors: r.errors } : {} };
|
|
1905
|
+
})
|
|
1906
|
+
]
|
|
1907
|
+
};
|
|
1908
|
+
|
|
1909
|
+
// ../../src/patent-render/server/skills/circuit.ts
|
|
1910
|
+
import { toolDefinition as toolDefinition5 } from "@tanstack/ai";
|
|
1911
|
+
import { z as z8 } from "zod";
|
|
1912
|
+
var Kind = z8.enum([
|
|
1913
|
+
"resistor",
|
|
1914
|
+
"capacitor",
|
|
1915
|
+
"inductor",
|
|
1916
|
+
"diode",
|
|
1917
|
+
"led",
|
|
1918
|
+
"battery",
|
|
1919
|
+
"voltage_source",
|
|
1920
|
+
"switch",
|
|
1921
|
+
"ground",
|
|
1922
|
+
"transistor_npn",
|
|
1923
|
+
"transistor_pnp",
|
|
1924
|
+
"op_amp",
|
|
1925
|
+
"ic",
|
|
1926
|
+
"junction"
|
|
1927
|
+
]);
|
|
1928
|
+
function symbol(kind, pinsPerSide = 4) {
|
|
1929
|
+
switch (kind) {
|
|
1930
|
+
case "resistor": {
|
|
1931
|
+
const pts2 = [[0, 0], [3.5, 0]];
|
|
1932
|
+
for (let i = 0; i < 6; i++) pts2.push([4 + i * 1.33, i % 2 ? 2 : -2]);
|
|
1933
|
+
pts2.push([11.5, 0], [15, 0]);
|
|
1934
|
+
return { prims: [{ k: "pl", pts: pts2 }], pins: { a: [0, 0], b: [15, 0] } };
|
|
1935
|
+
}
|
|
1936
|
+
case "capacitor":
|
|
1937
|
+
return { prims: [{ k: "pl", pts: [[0, 0], [6.5, 0]] }, { k: "pl", pts: [[6.5, -3.5], [6.5, 3.5]] }, { k: "pl", pts: [[8.5, -3.5], [8.5, 3.5]] }, { k: "pl", pts: [[8.5, 0], [15, 0]] }], pins: { a: [0, 0], b: [15, 0] } };
|
|
1938
|
+
case "inductor":
|
|
1939
|
+
return { prims: [{ k: "pl", pts: [[0, 0], [2.5, 0]] }, { k: "arcs", from: [2.5, 0], humps: 4, r: 1.25 }, { k: "pl", pts: [[12.5, 0], [15, 0]] }], pins: { a: [0, 0], b: [15, 0] } };
|
|
1940
|
+
case "diode":
|
|
1941
|
+
case "led": {
|
|
1942
|
+
const prims = [
|
|
1943
|
+
{ k: "pl", pts: [[0, 0], [5, 0]] },
|
|
1944
|
+
{ k: "pl", pts: [[5, -3], [5, 3], [10, 0]], closed: true },
|
|
1945
|
+
{ k: "pl", pts: [[10, -3], [10, 3]] },
|
|
1946
|
+
{ k: "pl", pts: [[10, 0], [15, 0]] }
|
|
1947
|
+
];
|
|
1948
|
+
if (kind === "led") {
|
|
1949
|
+
for (const dx of [0, 2.5]) {
|
|
1950
|
+
prims.push({ k: "pl", pts: [[7 + dx, -4], [9.5 + dx, -6.5]] }, { k: "pl", pts: [[8.3 + dx, -6.6], [9.5 + dx, -6.5], [9.4 + dx, -5.3]] });
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
return { prims, pins: { anode: [0, 0], cathode: [15, 0] } };
|
|
1954
|
+
}
|
|
1955
|
+
case "battery":
|
|
1956
|
+
return { prims: [{ k: "pl", pts: [[0, 0], [6.5, 0]] }, { k: "pl", pts: [[6.5, -4], [6.5, 4]] }, { k: "pl", pts: [[8.5, -2], [8.5, 2]] }, { k: "pl", pts: [[8.5, 0], [15, 0]] }], pins: { positive: [0, 0], negative: [15, 0] } };
|
|
1957
|
+
case "voltage_source":
|
|
1958
|
+
return {
|
|
1959
|
+
prims: [
|
|
1960
|
+
{ k: "pl", pts: [[0, 0], [3.5, 0]] },
|
|
1961
|
+
{ k: "circle", c: [7.5, 0], r: 4 },
|
|
1962
|
+
{ k: "pl", pts: [[11.5, 0], [15, 0]] },
|
|
1963
|
+
{ k: "pl", pts: [[4.8, -1], [4.8, 1]] },
|
|
1964
|
+
{ k: "pl", pts: [[3.8, 0], [5.8, 0]] },
|
|
1965
|
+
{ k: "pl", pts: [[9.5, 0], [10.7, 0]] }
|
|
1966
|
+
],
|
|
1967
|
+
pins: { positive: [0, 0], negative: [15, 0] }
|
|
1968
|
+
};
|
|
1969
|
+
case "switch":
|
|
1970
|
+
return { prims: [{ k: "pl", pts: [[0, 0], [5, 0]] }, { k: "circle", c: [5, 0], r: 0.6, fill: "white" }, { k: "pl", pts: [[5, 0], [10, -3.5]] }, { k: "circle", c: [10, 0], r: 0.6, fill: "white" }, { k: "pl", pts: [[10, 0], [15, 0]] }], pins: { a: [0, 0], b: [15, 0] } };
|
|
1971
|
+
case "ground":
|
|
1972
|
+
return { prims: [{ k: "pl", pts: [[0, 0], [0, 4]] }, { k: "pl", pts: [[-3, 4], [3, 4]] }, { k: "pl", pts: [[-2, 5.2], [2, 5.2]] }, { k: "pl", pts: [[-1, 6.4], [1, 6.4]] }], pins: { a: [0, 0] } };
|
|
1973
|
+
case "junction":
|
|
1974
|
+
return { prims: [{ k: "circle", c: [0, 0], r: 0.6, fill: "black" }], pins: { a: [0, 0] } };
|
|
1975
|
+
case "transistor_npn":
|
|
1976
|
+
case "transistor_pnp": {
|
|
1977
|
+
const npn = kind === "transistor_npn";
|
|
1978
|
+
const tip = npn ? [1.6, 4.4] : [-1.6, 2.4];
|
|
1979
|
+
const arrow = { k: "pl", pts: npn ? [tip, [-0.2, 4.2], [0.9, 2.7]] : [tip, [0.2, 2.6], [-0.9, 4.1]], closed: true, fill: "black" };
|
|
1980
|
+
return {
|
|
1981
|
+
prims: [
|
|
1982
|
+
{ k: "circle", c: [0, 0], r: 6 },
|
|
1983
|
+
{ k: "pl", pts: [[-10, 0], [-3, 0]] },
|
|
1984
|
+
{ k: "pl", pts: [[-3, -3.5], [-3, 3.5]] },
|
|
1985
|
+
{ k: "pl", pts: [[-3, -1.5], [2.5, -5], [2.5, -10]] },
|
|
1986
|
+
{ k: "pl", pts: [[-3, 1.5], [2.5, 5], [2.5, 10]] },
|
|
1987
|
+
arrow
|
|
1988
|
+
],
|
|
1989
|
+
pins: { base: [-10, 0], collector: [2.5, -10], emitter: [2.5, 10] }
|
|
1990
|
+
};
|
|
1991
|
+
}
|
|
1992
|
+
case "op_amp":
|
|
1993
|
+
return {
|
|
1994
|
+
prims: [
|
|
1995
|
+
{ k: "pl", pts: [[-8, -9], [-8, 9], [10, 0]], closed: true },
|
|
1996
|
+
{ k: "pl", pts: [[-12, -4], [-8, -4]] },
|
|
1997
|
+
{ k: "pl", pts: [[-12, 4], [-8, 4]] },
|
|
1998
|
+
{ k: "pl", pts: [[10, 0], [14, 0]] },
|
|
1999
|
+
{ k: "pl", pts: [[-6.6, -4], [-4.6, -4]] },
|
|
2000
|
+
{ k: "pl", pts: [[-6.6, 4], [-4.6, 4]] },
|
|
2001
|
+
{ k: "pl", pts: [[-5.6, 3], [-5.6, 5]] }
|
|
2002
|
+
],
|
|
2003
|
+
pins: { inverting: [-12, -4], non_inverting: [-12, 4], output: [14, 0] }
|
|
2004
|
+
};
|
|
2005
|
+
case "ic": {
|
|
2006
|
+
const pitch = 5, h = pinsPerSide * pitch + 2, w = 16;
|
|
2007
|
+
const prims = [{ k: "pl", pts: [[0, 0], [w, 0], [w, h], [0, h]], closed: true }];
|
|
2008
|
+
const pins = {};
|
|
2009
|
+
for (let i = 0; i < pinsPerSide; i++) {
|
|
2010
|
+
const y = 3.5 + i * pitch;
|
|
2011
|
+
prims.push({ k: "pl", pts: [[-4, y], [0, y]] }, { k: "pl", pts: [[w, y], [w + 4, y]] });
|
|
2012
|
+
pins[`p${i + 1}`] = [-4, y];
|
|
2013
|
+
pins[`p${pinsPerSide * 2 - i}`] = [w + 4, y];
|
|
2014
|
+
}
|
|
2015
|
+
return { prims, pins };
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
}
|
|
2019
|
+
function rot(p, deg) {
|
|
2020
|
+
const r = (deg % 360 + 360) % 360;
|
|
2021
|
+
const [x, y] = p;
|
|
2022
|
+
return r === 90 ? [-y, x] : r === 180 ? [-x, -y] : r === 270 ? [y, -x] : [x, y];
|
|
2023
|
+
}
|
|
2024
|
+
var PlaceInput = z8.object({
|
|
2025
|
+
layerId: z8.string().default("components"),
|
|
2026
|
+
components: z8.array(z8.object({
|
|
2027
|
+
id: z8.string(),
|
|
2028
|
+
kind: Kind,
|
|
2029
|
+
x: z8.number().meta({ description: "Position of the symbol origin (first pin for two-terminal parts)." }),
|
|
2030
|
+
y: z8.number(),
|
|
2031
|
+
rotation: z8.union([z8.literal(0), z8.literal(90), z8.literal(180), z8.literal(270)]).default(0),
|
|
2032
|
+
pinsPerSide: z8.number().int().min(1).max(12).optional().meta({ description: "For ic only." }),
|
|
2033
|
+
label: z8.string().optional().meta({ description: "Optional short label drawn next to the symbol (e.g. MCU for an ic)." })
|
|
2034
|
+
})).min(1)
|
|
2035
|
+
});
|
|
2036
|
+
var circuitSkill = {
|
|
2037
|
+
types: ["circuit"],
|
|
2038
|
+
title: "Circuit schematics",
|
|
2039
|
+
instructions: `
|
|
2040
|
+
Draw schematics with place_component for each symbol, then wire pins with polyline items (orthogonal runs only, 0.35 mm).
|
|
2041
|
+
|
|
2042
|
+
- Lay out signal flow left to right, supply rails at the top, ground at the bottom. Keep 10+ mm between components.
|
|
2043
|
+
- place_component returns each pin's coordinates; route wires between those exact points with horizontal/vertical polylines. Add a junction (kind "junction") where three or more wires meet; never use a junction where wires merely cross.
|
|
2044
|
+
- Rotation is 0/90/180/270 degrees. Resistors in vertical branches use rotation 90.
|
|
2045
|
+
- Component values ("10 k\u03A9") are text matter: omit them unless the claims require them. Identify components by reference numerals (502, 504...), not by designators like R1, unless the spec uses them.
|
|
2046
|
+
- Functional blocks that aren't standard symbols: use kind "ic" (labelled rectangle) or a plain rect with a short UPPERCASE label.
|
|
2047
|
+
- One layer for components, one for wiring, annotations on top.
|
|
2048
|
+
`.trim(),
|
|
2049
|
+
tools: (session) => [
|
|
2050
|
+
toolDefinition5({
|
|
2051
|
+
name: "place_component",
|
|
2052
|
+
description: "Place a schematic symbol (resistor, capacitor, inductor, diode, led, battery, voltage_source, switch, ground, transistor_npn/pnp, op_amp, ic, junction). Returns pin coordinates in mm for wiring.",
|
|
2053
|
+
inputSchema: PlaceInput
|
|
2054
|
+
}).server(async (raw, ctx) => {
|
|
2055
|
+
const { layerId, components } = PlaceInput.parse(raw);
|
|
2056
|
+
const items = [];
|
|
2057
|
+
const pins = {};
|
|
2058
|
+
for (const c of components) {
|
|
2059
|
+
const sym = symbol(c.kind, c.pinsPerSide);
|
|
2060
|
+
const T = (p) => {
|
|
2061
|
+
const q = rot(p, c.rotation);
|
|
2062
|
+
return [r12(c.x + q[0]), r12(c.y + q[1])];
|
|
2063
|
+
};
|
|
2064
|
+
sym.prims.forEach((pr, i) => {
|
|
2065
|
+
const id = `${c.id}-${i}`;
|
|
2066
|
+
if (pr.k === "pl") items.push({ id, type: "polyline", points: pr.pts.map(T), closed: !!pr.closed, fill: pr.fill ?? "none", stroke: stroke2(0.35), ...base3, ...i === 0 ? { name: c.id } : {} });
|
|
2067
|
+
if (pr.k === "circle") {
|
|
2068
|
+
const [cx, cy] = T(pr.c);
|
|
2069
|
+
items.push({ id, type: "ellipse", cx, cy, rx: pr.r, ry: pr.r, fill: pr.fill ?? "none", stroke: stroke2(0.35), ...base3 });
|
|
2070
|
+
}
|
|
2071
|
+
if (pr.k === "arcs") {
|
|
2072
|
+
let d = "";
|
|
2073
|
+
for (let h = 0; h < pr.humps; h++) {
|
|
2074
|
+
const a = T([pr.from[0] + h * pr.r * 2, pr.from[1]]), b = T([pr.from[0] + (h + 1) * pr.r * 2, pr.from[1]]);
|
|
2075
|
+
d += `${h === 0 ? `M ${a[0]} ${a[1]} ` : ""}A ${pr.r} ${pr.r} 0 0 1 ${b[0]} ${b[1]} `;
|
|
2076
|
+
}
|
|
2077
|
+
items.push({ id, type: "path", d: d.trim(), fill: "none", stroke: stroke2(0.35), ...base3 });
|
|
2078
|
+
}
|
|
2079
|
+
});
|
|
2080
|
+
if (c.label) {
|
|
2081
|
+
const xs = items.filter((it) => it.id.startsWith(`${c.id}-`) && it.type === "polyline").flatMap((it) => it.type === "polyline" ? it.points : []);
|
|
2082
|
+
const top = Math.min(...xs.map((p) => p[1]));
|
|
2083
|
+
const cx = (Math.min(...xs.map((p) => p[0])) + Math.max(...xs.map((p) => p[0]))) / 2;
|
|
2084
|
+
items.push({ id: `${c.id}-label`, type: "text", x: r12(cx), y: r12(top - 2), text: c.label, size: 3.5, anchor: "middle", ...base3 });
|
|
2085
|
+
}
|
|
2086
|
+
pins[c.id] = Object.fromEntries(Object.entries(sym.pins).map(([k, p]) => [k, T(p)]));
|
|
2087
|
+
}
|
|
2088
|
+
const r = session.applyMany([...ensureLayers(session.doc, [{ id: layerId, name: "Components" }]), ...addItemsPatches(layerId, items)], emitOf(ctx));
|
|
2089
|
+
return { ok: r.errors.length === 0, pins, ...r.errors.length ? { errors: r.errors } : {} };
|
|
2090
|
+
})
|
|
2091
|
+
]
|
|
2092
|
+
};
|
|
2093
|
+
|
|
2094
|
+
// ../../src/patent-render/server/skills/chemical.ts
|
|
2095
|
+
import { toolDefinition as toolDefinition6 } from "@tanstack/ai";
|
|
2096
|
+
import { z as z9 } from "zod";
|
|
2097
|
+
import { Molecule } from "openchemlib";
|
|
2098
|
+
var BOND_MM = 16;
|
|
2099
|
+
var LABEL_GAP = 2.4;
|
|
2100
|
+
function atomLabel(mol, a) {
|
|
2101
|
+
const sym = mol.getAtomLabel(a);
|
|
2102
|
+
const charge = mol.getAtomCharge(a);
|
|
2103
|
+
const hs = mol.getAllHydrogens(a);
|
|
2104
|
+
if (sym === "C" && charge === 0) return null;
|
|
2105
|
+
const h = sym === "C" ? "" : hs === 0 ? "" : hs === 1 ? "H" : `H${hs}`;
|
|
2106
|
+
const q = charge === 0 ? "" : charge > 0 ? charge === 1 ? "+" : `${charge}+` : charge === -1 ? "\u2212" : `${-charge}\u2212`;
|
|
2107
|
+
return `${sym}${h}${q}`;
|
|
2108
|
+
}
|
|
2109
|
+
function ringSide(mol, pos, a1, a2, p, ux, uy) {
|
|
2110
|
+
let sx = 0, sy = 0, n2 = 0;
|
|
2111
|
+
for (const a of [a1, a2]) {
|
|
2112
|
+
for (let i = 0; i < mol.getConnAtoms(a); i++) {
|
|
2113
|
+
const c = mol.getConnAtom(a, i);
|
|
2114
|
+
if (c === a1 || c === a2 || !mol.isRingAtom(c) || !pos.has(c)) continue;
|
|
2115
|
+
const q = pos.get(c);
|
|
2116
|
+
sx += q[0];
|
|
2117
|
+
sy += q[1];
|
|
2118
|
+
n2++;
|
|
2119
|
+
}
|
|
2120
|
+
}
|
|
2121
|
+
if (!n2) return 1;
|
|
2122
|
+
const dx = sx / n2 - p[0], dy = sy / n2 - p[1];
|
|
2123
|
+
return -uy * dx + ux * dy >= 0 ? 1 : -1;
|
|
2124
|
+
}
|
|
2125
|
+
function moleculeItems(smiles, id, centre2, maxW, maxH) {
|
|
2126
|
+
const mol = Molecule.fromSmiles(smiles);
|
|
2127
|
+
mol.inventCoordinates();
|
|
2128
|
+
const n2 = mol.getAllAtoms();
|
|
2129
|
+
const heavy = [...Array(n2).keys()].filter((a) => mol.getAtomicNo(a) !== 1);
|
|
2130
|
+
const avg = mol.getAverageBondLength(true) || 1;
|
|
2131
|
+
const raw = heavy.map((a) => [mol.getAtomX(a) / avg, -mol.getAtomY(a) / avg]);
|
|
2132
|
+
const minX = Math.min(...raw.map((p) => p[0])), maxX = Math.max(...raw.map((p) => p[0]));
|
|
2133
|
+
const minY = Math.min(...raw.map((p) => p[1])), maxY = Math.max(...raw.map((p) => p[1]));
|
|
2134
|
+
const s = Math.min(BOND_MM, maxW / Math.max(0.1, maxX - minX), maxH / Math.max(0.1, maxY - minY));
|
|
2135
|
+
const cx = (minX + maxX) / 2, cy = (minY + maxY) / 2;
|
|
2136
|
+
const pos = /* @__PURE__ */ new Map();
|
|
2137
|
+
heavy.forEach((a, i) => pos.set(a, [r12(centre2[0] + (raw[i][0] - cx) * s), r12(centre2[1] + (raw[i][1] - cy) * s)]));
|
|
2138
|
+
const labels = /* @__PURE__ */ new Map();
|
|
2139
|
+
for (const a of heavy) {
|
|
2140
|
+
const l = atomLabel(mol, a);
|
|
2141
|
+
if (l) labels.set(a, l);
|
|
2142
|
+
}
|
|
2143
|
+
const items = [];
|
|
2144
|
+
for (let b = 0; b < mol.getAllBonds(); b++) {
|
|
2145
|
+
const a1 = mol.getBondAtom(0, b), a2 = mol.getBondAtom(1, b);
|
|
2146
|
+
if (!pos.has(a1) || !pos.has(a2)) continue;
|
|
2147
|
+
let p = pos.get(a1), q = pos.get(a2);
|
|
2148
|
+
const dx = q[0] - p[0], dy = q[1] - p[1], len = Math.hypot(dx, dy) || 1;
|
|
2149
|
+
const ux = dx / len, uy = dy / len;
|
|
2150
|
+
if (labels.has(a1)) p = [p[0] + ux * LABEL_GAP, p[1] + uy * LABEL_GAP];
|
|
2151
|
+
if (labels.has(a2)) q = [q[0] - ux * LABEL_GAP, q[1] - uy * LABEL_GAP];
|
|
2152
|
+
const order = mol.getBondOrder(b);
|
|
2153
|
+
const line = (k, o, trim = 0) => {
|
|
2154
|
+
const nx = -uy * o, ny = ux * o, tx = ux * trim, ty = uy * trim;
|
|
2155
|
+
items.push({ id: `${id}-b${b}-${k}`, type: "line", a: [r12(p[0] + nx + tx), r12(p[1] + ny + ty)], b: [r12(q[0] + nx - tx), r12(q[1] + ny - ty)], stroke: stroke2(0.35), ...base3 });
|
|
2156
|
+
};
|
|
2157
|
+
if (order === 2 && mol.isRingBond(b)) {
|
|
2158
|
+
const side = ringSide(mol, pos, a1, a2, p, ux, uy);
|
|
2159
|
+
line(0, 0);
|
|
2160
|
+
line(1, side * 1.1, len * 0.15);
|
|
2161
|
+
} else {
|
|
2162
|
+
const offs = order === 1 ? [0] : order === 2 ? [-0.55, 0.55] : [-0.9, 0, 0.9];
|
|
2163
|
+
offs.forEach((o, k) => line(k, o));
|
|
2164
|
+
}
|
|
2165
|
+
}
|
|
2166
|
+
for (const [a, text] of labels) {
|
|
2167
|
+
const [x, y] = pos.get(a);
|
|
2168
|
+
items.push({ id: `${id}-a${a}`, type: "text", x, y: r12(y + 1.75), text, size: 3.5, anchor: "middle", ...base3 });
|
|
2169
|
+
}
|
|
2170
|
+
const pts2 = [...pos.values()];
|
|
2171
|
+
const bx = Math.min(...pts2.map((p) => p[0])), by = Math.min(...pts2.map((p) => p[1]));
|
|
2172
|
+
return { items, bbox: { x: r12(bx), y: r12(by), w: r12(Math.max(...pts2.map((p) => p[0])) - bx), h: r12(Math.max(...pts2.map((p) => p[1])) - by) }, atoms: heavy.length };
|
|
2173
|
+
}
|
|
2174
|
+
var chemicalSkill = {
|
|
2175
|
+
types: ["chemical"],
|
|
2176
|
+
title: "Chemical structures",
|
|
2177
|
+
instructions: `
|
|
2178
|
+
Draw chemical structures with draw_molecule from a SMILES string; do not hand-place atoms.
|
|
2179
|
+
|
|
2180
|
+
- Carbon atoms are implicit (skeletal formula); heteroatoms and charged atoms are labelled with attached hydrogens (OH, NH2).
|
|
2181
|
+
- Use one draw_molecule call per compound. For reaction schemes, place reactants left to right and add arrows with connector items (point-to-point, arrow end) and "+" signs as text between compounds.
|
|
2182
|
+
- Generic substituents (R1, R2, X) are allowed as text labels at the attachment point; draw the core with a placeholder atom ([*]) or add the label manually afterwards.
|
|
2183
|
+
- Compounds in a figure are identified by roman numerals or compound numbers as text below each structure (e.g. "(I)"), unless the spec uses reference numerals.
|
|
2184
|
+
`.trim(),
|
|
2185
|
+
tools: (session) => [
|
|
2186
|
+
toolDefinition6({
|
|
2187
|
+
name: "draw_molecule",
|
|
2188
|
+
description: "Draw a chemical structure from SMILES (skeletal formula, 2D coordinates from OpenChemLib). Returns the structure's bounding box in mm.",
|
|
2189
|
+
inputSchema: z9.object({
|
|
2190
|
+
id: z9.string(),
|
|
2191
|
+
smiles: z9.string(),
|
|
2192
|
+
layerId: z9.string().default("structures"),
|
|
2193
|
+
centre: vec(2).optional().meta({ description: "Centre point in mm; defaults to the middle of the usable area." }),
|
|
2194
|
+
maxWidth: z9.number().default(120),
|
|
2195
|
+
maxHeight: z9.number().default(110),
|
|
2196
|
+
caption: z9.string().optional().meta({ description: "Short identifier drawn below, e.g. (I)." })
|
|
2197
|
+
})
|
|
2198
|
+
}).server(async ({ id, smiles, layerId: layerIdIn, centre: centre2, maxWidth = 120, maxHeight = 110, caption }, ctx) => {
|
|
2199
|
+
const layerId = layerIdIn ?? "structures";
|
|
2200
|
+
let mol;
|
|
2201
|
+
try {
|
|
2202
|
+
const area = usableArea(session.doc);
|
|
2203
|
+
mol = moleculeItems(smiles, id, centre2 ?? [area.x + area.w / 2, area.y + area.h / 2], maxWidth, maxHeight);
|
|
2204
|
+
} catch (e) {
|
|
2205
|
+
return { ok: false, error: `Could not parse SMILES: ${e instanceof Error ? e.message : String(e)}` };
|
|
2206
|
+
}
|
|
2207
|
+
if (caption) {
|
|
2208
|
+
mol.items.push({ id: `${id}-caption`, type: "text", x: r12(mol.bbox.x + mol.bbox.w / 2), y: r12(mol.bbox.y + mol.bbox.h + 9), text: caption, size: 3.5, anchor: "middle", ...base3 });
|
|
2209
|
+
}
|
|
2210
|
+
const r = session.applyMany([...ensureLayers(session.doc, [{ id: layerId, name: "Structures" }]), ...addItemsPatches(layerId, mol.items)], emitOf(ctx));
|
|
2211
|
+
return { ok: r.errors.length === 0, bbox: mol.bbox, heavyAtoms: mol.atoms, ...r.errors.length ? { errors: r.errors } : {} };
|
|
2212
|
+
})
|
|
2213
|
+
]
|
|
2214
|
+
};
|
|
2215
|
+
|
|
2216
|
+
// ../../src/patent-render/server/skills/detail.ts
|
|
2217
|
+
import { toolDefinition as toolDefinition7 } from "@tanstack/ai";
|
|
2218
|
+
import { z as z10 } from "zod";
|
|
2219
|
+
|
|
2220
|
+
// ../../src/patent-render/geometry/bezier.ts
|
|
2221
|
+
var r3 = (n2) => Math.round(n2 * 1e3) / 1e3;
|
|
2222
|
+
var pt2 = (p) => `${r3(p[0])} ${r3(p[1])}`;
|
|
2223
|
+
var same = (a, b) => Math.abs(a[0] - b[0]) < 1e-6 && Math.abs(a[1] - b[1]) < 1e-6;
|
|
2224
|
+
function segment(a, b) {
|
|
2225
|
+
if (!a.out && !b.in) return `L ${pt2(b.p)}`;
|
|
2226
|
+
return `C ${pt2(a.out ?? a.p)} ${pt2(b.in ?? b.p)} ${pt2(b.p)}`;
|
|
2227
|
+
}
|
|
2228
|
+
function nodesToD(subs) {
|
|
2229
|
+
return subs.filter((s) => s.nodes.length > 0).map((s) => {
|
|
2230
|
+
const n2 = s.nodes;
|
|
2231
|
+
let d = `M ${pt2(n2[0].p)}`;
|
|
2232
|
+
for (let i = 1; i < n2.length; i++) d += ` ${segment(n2[i - 1], n2[i])}`;
|
|
2233
|
+
if (s.closed && n2.length > 1) {
|
|
2234
|
+
const last = n2[n2.length - 1], first = n2[0];
|
|
2235
|
+
if (last.out || first.in) d += ` ${segment(last, first)}`;
|
|
2236
|
+
d += " Z";
|
|
2237
|
+
}
|
|
2238
|
+
return d;
|
|
2239
|
+
}).join(" ");
|
|
2240
|
+
}
|
|
2241
|
+
function dToNodes(d) {
|
|
2242
|
+
const subs = [];
|
|
2243
|
+
let cur = null;
|
|
2244
|
+
let x = 0, y = 0;
|
|
2245
|
+
let lastC2 = null;
|
|
2246
|
+
let lastQ = null;
|
|
2247
|
+
const cmds = parsePath(d);
|
|
2248
|
+
for (let i = 0; i < cmds.length; i++) {
|
|
2249
|
+
const { c, v } = cmds[i];
|
|
2250
|
+
const rel = c === c.toLowerCase() && !(i === 0 && c === "m");
|
|
2251
|
+
const ox = rel ? x : 0, oy = rel ? y : 0;
|
|
2252
|
+
const C = c.toUpperCase();
|
|
2253
|
+
const prevC2 = lastC2, prevQ = lastQ;
|
|
2254
|
+
lastC2 = null;
|
|
2255
|
+
lastQ = null;
|
|
2256
|
+
const lastNode = () => cur.nodes[cur.nodes.length - 1];
|
|
2257
|
+
switch (C) {
|
|
2258
|
+
case "M":
|
|
2259
|
+
x = ox + v[0];
|
|
2260
|
+
y = oy + v[1];
|
|
2261
|
+
cur = { nodes: [{ p: [x, y] }], closed: false };
|
|
2262
|
+
subs.push(cur);
|
|
2263
|
+
break;
|
|
2264
|
+
case "L":
|
|
2265
|
+
case "H":
|
|
2266
|
+
case "V": {
|
|
2267
|
+
if (!cur) return null;
|
|
2268
|
+
if (C === "L") {
|
|
2269
|
+
x = ox + v[0];
|
|
2270
|
+
y = oy + v[1];
|
|
2271
|
+
} else if (C === "H") x = (rel ? x : 0) + v[0];
|
|
2272
|
+
else y = (rel ? y : 0) + v[0];
|
|
2273
|
+
cur.nodes.push({ p: [x, y] });
|
|
2274
|
+
break;
|
|
2275
|
+
}
|
|
2276
|
+
case "C":
|
|
2277
|
+
case "S": {
|
|
2278
|
+
if (!cur) return null;
|
|
2279
|
+
const c1 = C === "C" ? [ox + v[0], oy + v[1]] : prevC2 ? [2 * x - prevC2[0], 2 * y - prevC2[1]] : [x, y];
|
|
2280
|
+
const off2 = C === "C" ? 2 : 0;
|
|
2281
|
+
const c2 = [ox + v[off2], oy + v[off2 + 1]];
|
|
2282
|
+
const p = [ox + v[off2 + 2], oy + v[off2 + 3]];
|
|
2283
|
+
lastNode().out = c1;
|
|
2284
|
+
cur.nodes.push({ p, in: c2 });
|
|
2285
|
+
x = p[0];
|
|
2286
|
+
y = p[1];
|
|
2287
|
+
lastC2 = c2;
|
|
2288
|
+
break;
|
|
2289
|
+
}
|
|
2290
|
+
case "Q":
|
|
2291
|
+
case "T": {
|
|
2292
|
+
if (!cur) return null;
|
|
2293
|
+
const q = C === "Q" ? [ox + v[0], oy + v[1]] : prevQ ? [2 * x - prevQ[0], 2 * y - prevQ[1]] : [x, y];
|
|
2294
|
+
const p = C === "Q" ? [ox + v[2], oy + v[3]] : [ox + v[0], oy + v[1]];
|
|
2295
|
+
lastNode().out = [x + 2 / 3 * (q[0] - x), y + 2 / 3 * (q[1] - y)];
|
|
2296
|
+
cur.nodes.push({ p, in: [p[0] + 2 / 3 * (q[0] - p[0]), p[1] + 2 / 3 * (q[1] - p[1])] });
|
|
2297
|
+
x = p[0];
|
|
2298
|
+
y = p[1];
|
|
2299
|
+
lastQ = q;
|
|
2300
|
+
break;
|
|
2301
|
+
}
|
|
2302
|
+
case "Z": {
|
|
2303
|
+
if (!cur) return null;
|
|
2304
|
+
cur.closed = true;
|
|
2305
|
+
const n2 = cur.nodes;
|
|
2306
|
+
if (n2.length > 1 && same(n2[n2.length - 1].p, n2[0].p)) {
|
|
2307
|
+
const end = n2.pop();
|
|
2308
|
+
if (end.in) n2[0].in = end.in;
|
|
2309
|
+
}
|
|
2310
|
+
x = n2[0].p[0];
|
|
2311
|
+
y = n2[0].p[1];
|
|
2312
|
+
break;
|
|
2313
|
+
}
|
|
2314
|
+
default:
|
|
2315
|
+
return null;
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
return subs;
|
|
2319
|
+
}
|
|
2320
|
+
|
|
2321
|
+
// ../../src/patent-render/server/skills/detail.ts
|
|
2322
|
+
function mapItem(item, f, angleDeg = 0) {
|
|
2323
|
+
const fp = (p) => {
|
|
2324
|
+
const q = f(p);
|
|
2325
|
+
return [r12(q[0]), r12(q[1])];
|
|
2326
|
+
};
|
|
2327
|
+
switch (item.type) {
|
|
2328
|
+
case "line":
|
|
2329
|
+
case "sectionLine":
|
|
2330
|
+
return { ...item, a: fp(item.a), b: fp(item.b) };
|
|
2331
|
+
case "polyline":
|
|
2332
|
+
case "hatch":
|
|
2333
|
+
return { ...item, points: item.points.map(fp) };
|
|
2334
|
+
case "rect": {
|
|
2335
|
+
const pts2 = [[item.x, item.y], [item.x + item.w, item.y], [item.x + item.w, item.y + item.h], [item.x, item.y + item.h]];
|
|
2336
|
+
return { id: item.id, name: item.name, type: "polyline", closed: true, fill: item.fill, stroke: item.stroke, rotation: 0, locked: item.locked, hidden: item.hidden, points: pts2.map(fp) };
|
|
2337
|
+
}
|
|
2338
|
+
case "path": {
|
|
2339
|
+
const subs = dToNodes(item.d);
|
|
2340
|
+
if (!subs) return null;
|
|
2341
|
+
return { ...item, d: nodesToD(subs.map((s) => ({ closed: s.closed, nodes: s.nodes.map((n2) => ({ p: fp(n2.p), in: n2.in && fp(n2.in), out: n2.out && fp(n2.out) })) }))) };
|
|
2342
|
+
}
|
|
2343
|
+
case "ellipse": {
|
|
2344
|
+
const [cx, cy] = fp([item.cx, item.cy]);
|
|
2345
|
+
return { ...item, cx, cy, rotation: (item.rotation + angleDeg) % 360 };
|
|
2346
|
+
}
|
|
2347
|
+
case "text": {
|
|
2348
|
+
const [x, y] = fp([item.x, item.y]);
|
|
2349
|
+
return { ...item, x, y };
|
|
2350
|
+
}
|
|
2351
|
+
default:
|
|
2352
|
+
return null;
|
|
2353
|
+
}
|
|
2354
|
+
}
|
|
2355
|
+
var Region = z10.object({ x: z10.number(), y: z10.number(), w: z10.number().positive(), h: z10.number().positive() });
|
|
2356
|
+
var RENDERING_GUIDE = `
|
|
2357
|
+
Rendering detail for perspective and product drawings (the look of formal US design/utility figures):
|
|
2358
|
+
- Surface shading: a few thin (0.25 mm) parallel strokes, never fills or grey. Cylinders get vertical strokes bunched toward the shadow edge (shade kind "cylinder"). Glass and polished faces get 2-3 short parallel diagonal glare strokes (shade kind "glare"). Flat faces in shadow get sparse parallel strokes (kind "flat").
|
|
2359
|
+
- Graduations, scale marks, teeth and serrations: use graduations (on a circle, foreshortened with squash for perspective ellipses) or array_items (linear/polar repeat of one drawn element) instead of drawing each mark.
|
|
2360
|
+
- Knurling (e.g. a watch crown): short parallel lines across the band via array_items linear.
|
|
2361
|
+
- Stitching and seams: dashed polylines (stroke.style "dashed", 0.25 mm) running parallel to the edge, 1-1.5 mm inside it.
|
|
2362
|
+
- Cut ends and sections in a perspective view: hatch items on the exposed faces.
|
|
2363
|
+
- Lines: outer silhouettes 0.5 mm, internal edges 0.35 mm, shading/detail 0.25 mm. This line-weight hierarchy is what makes figures read clearly after reduction.
|
|
2364
|
+
- Leaders: smooth curves ending exactly on the surface they identify; numerals evenly distributed around the figure, never crossing.
|
|
2365
|
+
`.trim();
|
|
2366
|
+
var detailSkill = {
|
|
2367
|
+
types: [],
|
|
2368
|
+
title: "Rendering detail",
|
|
2369
|
+
instructions: RENDERING_GUIDE,
|
|
2370
|
+
tools: (session) => [
|
|
2371
|
+
toolDefinition7({
|
|
2372
|
+
name: "array_items",
|
|
2373
|
+
description: "Repeat existing items: linear (step dx, dy) or polar (rotate about a centre; squash < 1 foreshortens the circle into a perspective ellipse). Copies get ids <id>-1, <id>-2, ... Use for ticks, knurling, holes, teeth, buttons, stitching dots.",
|
|
2374
|
+
inputSchema: z10.object({
|
|
2375
|
+
ids: z10.array(z10.string()).min(1),
|
|
2376
|
+
count: z10.number().int().min(1).max(120).meta({ description: "Number of copies (excluding the original)." }),
|
|
2377
|
+
mode: z10.enum(["linear", "polar"]),
|
|
2378
|
+
dx: z10.number().optional(),
|
|
2379
|
+
dy: z10.number().optional(),
|
|
2380
|
+
centre: z10.array(z10.number()).length(2).optional().meta({ description: "Polar centre [x, y] in mm." }),
|
|
2381
|
+
stepDeg: z10.number().optional().meta({ description: "Polar angle between copies (default 360/(count+1))." }),
|
|
2382
|
+
squash: z10.number().min(0.1).max(1).optional().meta({ description: "Polar only: vertical scale of the circle (ry/rx) for perspective." })
|
|
2383
|
+
})
|
|
2384
|
+
}).server(async ({ ids, count, mode, dx = 0, dy = 0, centre: centre2, stepDeg, squash = 1 }, ctx) => {
|
|
2385
|
+
const patches = [];
|
|
2386
|
+
const skipped = [];
|
|
2387
|
+
for (const id of ids) {
|
|
2388
|
+
const loc = findItem(session.doc, id);
|
|
2389
|
+
if (!loc) {
|
|
2390
|
+
skipped.push(id);
|
|
2391
|
+
continue;
|
|
2392
|
+
}
|
|
2393
|
+
const layerId = session.doc.layers[loc.layerIndex].id;
|
|
2394
|
+
for (let k = 1; k <= count; k++) {
|
|
2395
|
+
let f, angle = 0;
|
|
2396
|
+
if (mode === "linear") f = ([x, y]) => [x + dx * k, y + dy * k];
|
|
2397
|
+
else {
|
|
2398
|
+
const [cx, cy] = centre2 ?? [0, 0];
|
|
2399
|
+
angle = (stepDeg ?? 360 / (count + 1)) * k;
|
|
2400
|
+
const t = angle * Math.PI / 180, c = Math.cos(t), s = Math.sin(t);
|
|
2401
|
+
f = ([x, y]) => {
|
|
2402
|
+
const ux = x - cx, uy = (y - cy) / squash;
|
|
2403
|
+
return [cx + ux * c - uy * s, cy + (ux * s + uy * c) * squash];
|
|
2404
|
+
};
|
|
2405
|
+
}
|
|
2406
|
+
const copy = mapItem(loc.item, f, angle);
|
|
2407
|
+
if (!copy) {
|
|
2408
|
+
skipped.push(id);
|
|
2409
|
+
break;
|
|
2410
|
+
}
|
|
2411
|
+
patches.push({ op: "addItem", layerId, item: { ...copy, id: `${id}-${k}` } });
|
|
2412
|
+
}
|
|
2413
|
+
}
|
|
2414
|
+
const r = session.applyMany(patches, emitOf(ctx));
|
|
2415
|
+
return { ok: r.errors.length === 0, added: r.accepted, ...skipped.length ? { skipped: `${skipped.join(", ")} (unsupported type or arcs)` } : {}, ...r.errors.length ? { errors: r.errors.slice(0, 5) } : {} };
|
|
2416
|
+
}),
|
|
2417
|
+
toolDefinition7({
|
|
2418
|
+
name: "graduations",
|
|
2419
|
+
description: "Draw tick marks around a circle or perspective ellipse (bezels, dials, scales): radial ticks with longer major ticks, optional index triangle at 12 o'clock.",
|
|
2420
|
+
inputSchema: z10.object({
|
|
2421
|
+
id: z10.string(),
|
|
2422
|
+
layerId: z10.string(),
|
|
2423
|
+
centre: z10.array(z10.number()).length(2),
|
|
2424
|
+
radius: z10.number().positive().meta({ description: "Outer radius (horizontal, mm)." }),
|
|
2425
|
+
squash: z10.number().min(0.1).max(1).default(1).meta({ description: "ry/rx for a perspective ellipse." }),
|
|
2426
|
+
count: z10.number().int().min(4).max(240).default(60),
|
|
2427
|
+
length: z10.number().positive().default(1.2),
|
|
2428
|
+
majorEvery: z10.number().int().min(0).default(5),
|
|
2429
|
+
majorLength: z10.number().positive().default(2.2),
|
|
2430
|
+
indexTriangle: z10.boolean().default(false)
|
|
2431
|
+
})
|
|
2432
|
+
}).server(async (raw, ctx) => {
|
|
2433
|
+
const { id, layerId, centre: centre2, radius, squash = 1, count = 60, length = 1.2, majorEvery = 5, majorLength = 2.2, indexTriangle = false } = raw;
|
|
2434
|
+
const [cx, cy] = centre2;
|
|
2435
|
+
const items = [];
|
|
2436
|
+
for (let k = 0; k < count; k++) {
|
|
2437
|
+
const t = k / count * Math.PI * 2 - Math.PI / 2;
|
|
2438
|
+
const major = majorEvery > 0 && k % majorEvery === 0;
|
|
2439
|
+
const L = major ? majorLength : length;
|
|
2440
|
+
const p = (r2) => [r12(cx + Math.cos(t) * r2), r12(cy + Math.sin(t) * r2 * squash)];
|
|
2441
|
+
if (indexTriangle && k === 0) continue;
|
|
2442
|
+
items.push({ id: `${id}-${k}`, type: "line", a: p(radius), b: p(radius - L), stroke: stroke2(major ? 0.3 : 0.2), ...base3 });
|
|
2443
|
+
}
|
|
2444
|
+
if (indexTriangle) {
|
|
2445
|
+
const s = majorLength;
|
|
2446
|
+
items.push({
|
|
2447
|
+
id: `${id}-index`,
|
|
2448
|
+
type: "polyline",
|
|
2449
|
+
closed: true,
|
|
2450
|
+
fill: "black",
|
|
2451
|
+
stroke: stroke2(0.2),
|
|
2452
|
+
...base3,
|
|
2453
|
+
points: [[r12(cx - s * 0.6), r12(cy - radius * squash)], [r12(cx + s * 0.6), r12(cy - radius * squash)], [r12(cx), r12(cy - (radius - s) * squash)]]
|
|
2454
|
+
});
|
|
2455
|
+
}
|
|
2456
|
+
const r = session.applyMany([...ensureLayers(session.doc, [{ id: layerId, name: "Detail" }]), ...items.map((item) => ({ op: "addItem", layerId, item }))], emitOf(ctx));
|
|
2457
|
+
return { ok: r.errors.length === 0, added: r.accepted, ...r.errors.length ? { errors: r.errors.slice(0, 5) } : {} };
|
|
2458
|
+
}),
|
|
2459
|
+
toolDefinition7({
|
|
2460
|
+
name: "shade",
|
|
2461
|
+
description: "Add surface shading strokes in a region: 'cylinder' (vertical strokes bunched toward one side), 'glare' (2-3 short diagonal strokes for glass), 'flat' (sparse parallel strokes).",
|
|
2462
|
+
inputSchema: z10.object({
|
|
2463
|
+
id: z10.string(),
|
|
2464
|
+
layerId: z10.string(),
|
|
2465
|
+
kind: z10.enum(["cylinder", "glare", "flat"]),
|
|
2466
|
+
region: Region,
|
|
2467
|
+
side: z10.enum(["left", "right"]).default("right").meta({ description: "Shadow side for cylinder/flat." }),
|
|
2468
|
+
count: z10.number().int().min(1).max(12).default(3),
|
|
2469
|
+
angle: z10.number().default(45).meta({ description: "Stroke angle for glare/flat, degrees." })
|
|
2470
|
+
})
|
|
2471
|
+
}).server(async (raw, ctx) => {
|
|
2472
|
+
const { id, layerId, kind, region: b, side = "right", count = 3, angle = 45 } = raw;
|
|
2473
|
+
const items = [];
|
|
2474
|
+
const line = (k, a, c) => items.push({ id: `${id}-${k}`, type: "line", a: [r12(a[0]), r12(a[1])], b: [r12(c[0]), r12(c[1])], stroke: stroke2(0.25), ...base3 });
|
|
2475
|
+
if (kind === "cylinder") {
|
|
2476
|
+
for (let k = 0; k < count; k++) {
|
|
2477
|
+
const f = 0.05 + 0.3 * ((k + 1) / count) ** 2;
|
|
2478
|
+
const x = side === "right" ? b.x + b.w * (1 - f) : b.x + b.w * f;
|
|
2479
|
+
const inset = b.h * (0.08 + 0.04 * k);
|
|
2480
|
+
line(k, [x, b.y + inset], [x, b.y + b.h - inset]);
|
|
2481
|
+
}
|
|
2482
|
+
} else if (kind === "glare") {
|
|
2483
|
+
const t = angle * Math.PI / 180, m = Math.min(b.w, b.h);
|
|
2484
|
+
const lens = [0.32, 0.42, 0.24].slice(0, Math.max(1, Math.min(3, count)));
|
|
2485
|
+
lens.forEach((L, k) => {
|
|
2486
|
+
const sx = b.x + b.w * (0.2 + 0.07 * k), sy = b.y + b.h * (0.35 + 0.07 * k);
|
|
2487
|
+
line(k, [sx, sy], [sx + Math.cos(t) * m * L, sy - Math.sin(t) * m * L]);
|
|
2488
|
+
});
|
|
2489
|
+
} else {
|
|
2490
|
+
const t = angle * Math.PI / 180, dir = [Math.cos(t), -Math.sin(t)];
|
|
2491
|
+
for (let k = 0; k < count; k++) {
|
|
2492
|
+
const f = (k + 1) / (count + 1);
|
|
2493
|
+
const cx = side === "right" ? b.x + b.w * (0.55 + 0.4 * f) : b.x + b.w * (0.45 - 0.4 * f);
|
|
2494
|
+
const cy = b.y + b.h / 2, half = Math.min(b.w, b.h) * 0.3;
|
|
2495
|
+
line(k, [cx - dir[0] * half, cy - dir[1] * half], [cx + dir[0] * half, cy + dir[1] * half]);
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
const r = session.applyMany([...ensureLayers(session.doc, [{ id: layerId, name: "Shading" }]), ...items.map((item) => ({ op: "addItem", layerId, item }))], emitOf(ctx));
|
|
2499
|
+
return { ok: r.errors.length === 0, added: r.accepted, ...r.errors.length ? { errors: r.errors.slice(0, 5) } : {} };
|
|
2500
|
+
})
|
|
2501
|
+
]
|
|
2502
|
+
};
|
|
2503
|
+
|
|
2504
|
+
// ../../src/patent-render/server/skills/index.ts
|
|
2505
|
+
var SKILLS = [diagramSkill, mechanicalSkill, uiScreenSkill, perspectiveSkill, circuitSkill, chemicalSkill, detailSkill];
|
|
2506
|
+
var WITH_DETAIL = /* @__PURE__ */ new Set(["mechanical2d", "perspective3d", "uiScreen"]);
|
|
2507
|
+
function skillFor(type) {
|
|
2508
|
+
const s = SKILLS.find((x) => x.types.includes(type)) ?? diagramSkill;
|
|
2509
|
+
return WITH_DETAIL.has(type) ? { ...s, instructions: `${s.instructions}
|
|
2510
|
+
|
|
2511
|
+
${RENDERING_GUIDE}` } : s;
|
|
2512
|
+
}
|
|
2513
|
+
|
|
2514
|
+
// ../../src/patent-render/server/tools.ts
|
|
2515
|
+
var emitOf2 = (ctx) => ctx?.emitCustomEvent.bind(ctx);
|
|
2516
|
+
var ITEM_FIELDS_HELP = "All coordinates in mm on the sheet. Points are [x, y]. Strokes {width, style: solid|dashed|centre|phantom}. Fill none|white|black. Text/numeral `size` is cap height in mm (use 3.5).";
|
|
2517
|
+
function result(session, touched, extra = {}) {
|
|
2518
|
+
const issues = summariseIssues(session.issuesFor(touched));
|
|
2519
|
+
return { ok: true, ...extra, ...issues.length ? { issues } : {} };
|
|
2520
|
+
}
|
|
2521
|
+
function createDrawingTools(session, deps) {
|
|
2522
|
+
const getDrawing = toolDefinition8({
|
|
2523
|
+
name: "get_drawing",
|
|
2524
|
+
description: "Return the current drawing: layers, items (id, type, bbox, key fields), numeral registry and selection. Call before editing an existing figure if unsure of ids or positions.",
|
|
2525
|
+
inputSchema: z11.object({})
|
|
2526
|
+
}).server(async () => ({ drawing: describeDocument(session.doc, session.selection) }));
|
|
2527
|
+
const planFigure = toolDefinition8({
|
|
2528
|
+
name: "plan_figure",
|
|
2529
|
+
description: "Plan a NEW figure before drawing it. Runs the prompt enhancer, which expands the user's request into a figure plan: figure type, view, components with reference numerals (reusing the application's registry), and the layer breakdown. Call once at the start of a new figure, not for small edits.",
|
|
2530
|
+
inputSchema: z11.object({ request: z11.string().meta({ description: "The user's request, plus anything relevant you know from the conversation." }) })
|
|
2531
|
+
}).server(async ({ request }, ctx) => {
|
|
2532
|
+
const emit = emitOf2(ctx);
|
|
2533
|
+
session.status(emit, "enhancing", "Planning the figure");
|
|
2534
|
+
const plan = await deps.plan(request);
|
|
2535
|
+
session.plan = plan;
|
|
2536
|
+
emit?.(EVENTS.plan, { plan });
|
|
2537
|
+
session.status(emit, "drawing", "Drawing");
|
|
2538
|
+
const skill = skillFor(plan.figureType);
|
|
2539
|
+
return { plan, nextStep: session.prefs?.style === "detailed" ? `Call load_skill with figureType "${plan.figureType}" (${skill.title}); the user wants a DETAILED rendering, so use the rendering-detail tools (shade, graduations, array_items).` : `Call load_skill with figureType "${plan.figureType}" (${skill.title}) before drawing.` };
|
|
2540
|
+
});
|
|
2541
|
+
const loadSkill = toolDefinition8({
|
|
2542
|
+
name: "load_skill",
|
|
2543
|
+
description: `Load drawing conventions and specialist tool guidance for a figure type. Types: ${SKILLS.filter((s) => s.types.length).map((s) => `${s.types.join("/")} (${s.title})`).join("; ")}.`,
|
|
2544
|
+
inputSchema: z11.object({ figureType: FigureType })
|
|
2545
|
+
}).server(async ({ figureType }) => {
|
|
2546
|
+
const s = skillFor(figureType);
|
|
2547
|
+
return { skill: s.title, instructions: s.instructions };
|
|
2548
|
+
});
|
|
2549
|
+
const addLayer = toolDefinition8({
|
|
2550
|
+
name: "add_layer",
|
|
2551
|
+
description: "Create a layer. Layers group a component and its parts (e.g. 'Housing 202'). Later layers draw on top. Use stable, readable ids.",
|
|
2552
|
+
inputSchema: z11.object({
|
|
2553
|
+
id: z11.string(),
|
|
2554
|
+
name: z11.string(),
|
|
2555
|
+
index: z11.number().int().optional().meta({ description: "Z position; omit to put it on top." })
|
|
2556
|
+
})
|
|
2557
|
+
}).server(async ({ id, name, index }, ctx) => {
|
|
2558
|
+
const layer = { id, name, visible: true, locked: false, items: [] };
|
|
2559
|
+
const annIdx = session.doc.layers.findIndex((l) => l.id === "annotations");
|
|
2560
|
+
const at = index ?? (annIdx >= 0 ? annIdx : void 0);
|
|
2561
|
+
const err = session.apply({ op: "addLayer", layer, index: at }, emitOf2(ctx));
|
|
2562
|
+
return err ? { ok: false, error: err } : { ok: true, id };
|
|
2563
|
+
});
|
|
2564
|
+
const updateLayer = toolDefinition8({
|
|
2565
|
+
name: "update_layer",
|
|
2566
|
+
description: "Rename, hide/show or lock/unlock a layer.",
|
|
2567
|
+
inputSchema: z11.object({ id: z11.string(), name: z11.string().optional(), visible: z11.boolean().optional(), locked: z11.boolean().optional() })
|
|
2568
|
+
}).server(async ({ id, ...changes }, ctx) => {
|
|
2569
|
+
const err = session.apply({ op: "updateLayer", id, changes }, emitOf2(ctx));
|
|
2570
|
+
return err ? { ok: false, error: err } : { ok: true };
|
|
2571
|
+
});
|
|
2572
|
+
const removeLayer = toolDefinition8({
|
|
2573
|
+
name: "remove_layer",
|
|
2574
|
+
description: "Delete a layer and everything on it.",
|
|
2575
|
+
inputSchema: z11.object({ id: z11.string() })
|
|
2576
|
+
}).server(async ({ id }, ctx) => {
|
|
2577
|
+
const err = session.apply({ op: "removeLayer", id }, emitOf2(ctx));
|
|
2578
|
+
return err ? { ok: false, error: err } : { ok: true };
|
|
2579
|
+
});
|
|
2580
|
+
const addItems = toolDefinition8({
|
|
2581
|
+
name: "add_items",
|
|
2582
|
+
description: `Add drawing items to a layer. Give every item a unique, readable id (e.g. "housing-outer", "n102"). ${ITEM_FIELDS_HELP} Types: line{a,b} polyline{points,closed,fill} path{d,fill} rect{x,y,w,h,radius,fill} ellipse{cx,cy,rx,ry,fill} arc{cx,cy,r,start,end} text{x,y(baseline),text,size,anchor} numeral{n,at(label centre),target(point on the part),leader:curved|straight|none,underline} figLabel{x,y,size} connector{from:{itemId}|{point},to,routing:orthogonal|straight,arrow:end|start|both|none,label} hatch{points(closed outline),angle,spacing} sectionLine{a,b,label}.`,
|
|
2583
|
+
inputSchema: z11.object({ layerId: z11.string(), items: z11.array(Item).min(1) })
|
|
2584
|
+
}).server(async ({ layerId, items: raw }, ctx) => {
|
|
2585
|
+
const emit = emitOf2(ctx);
|
|
2586
|
+
const items = raw.map((i) => Item.parse(i));
|
|
2587
|
+
const layer = session.doc.layers.find((l) => l.id === layerId);
|
|
2588
|
+
if (layer) session.status(emit, "drawing", `Drawing ${layer.name}`);
|
|
2589
|
+
const r = session.applyMany(items.map((item) => ({ op: "addItem", layerId, item })), emit);
|
|
2590
|
+
return { ...result(session, items.map((i) => i.id), { added: r.accepted }), ...r.errors.length ? { errors: r.errors } : {} };
|
|
2591
|
+
});
|
|
2592
|
+
const updateItems = toolDefinition8({
|
|
2593
|
+
name: "update_items",
|
|
2594
|
+
description: `Change fields of existing items by id (partial updates; type and id cannot change). ${ITEM_FIELDS_HELP}`,
|
|
2595
|
+
inputSchema: z11.object({
|
|
2596
|
+
updates: z11.array(z11.object({ id: z11.string(), changes: z11.record(z11.string(), z11.unknown()) })).min(1)
|
|
2597
|
+
})
|
|
2598
|
+
}).server(async ({ updates }, ctx) => {
|
|
2599
|
+
const r = session.applyMany(updates.map((u) => ({ op: "updateItem", id: u.id, changes: u.changes })), emitOf2(ctx));
|
|
2600
|
+
return { ...result(session, updates.map((u) => u.id), { updated: r.accepted }), ...r.errors.length ? { errors: r.errors } : {} };
|
|
2601
|
+
});
|
|
2602
|
+
const removeItems = toolDefinition8({
|
|
2603
|
+
name: "remove_items",
|
|
2604
|
+
description: "Delete items by id.",
|
|
2605
|
+
inputSchema: z11.object({ ids: z11.array(z11.string()).min(1) })
|
|
2606
|
+
}).server(async ({ ids }, ctx) => {
|
|
2607
|
+
const r = session.applyMany(ids.map((id) => ({ op: "removeItem", id })), emitOf2(ctx));
|
|
2608
|
+
return { ok: r.errors.length === 0, removed: r.accepted, ...r.errors.length ? { errors: r.errors } : {} };
|
|
2609
|
+
});
|
|
2610
|
+
const moveItems = toolDefinition8({
|
|
2611
|
+
name: "move_items",
|
|
2612
|
+
description: "Move items to another layer (or reorder within a layer with toIndex).",
|
|
2613
|
+
inputSchema: z11.object({ ids: z11.array(z11.string()).min(1), toLayerId: z11.string(), toIndex: z11.number().int().optional() })
|
|
2614
|
+
}).server(async ({ ids, toLayerId, toIndex }, ctx) => {
|
|
2615
|
+
const r = session.applyMany(ids.map((id) => ({ op: "moveItem", id, toLayerId, toIndex })), emitOf2(ctx));
|
|
2616
|
+
return { ok: r.errors.length === 0, moved: r.accepted, ...r.errors.length ? { errors: r.errors } : {} };
|
|
2617
|
+
});
|
|
2618
|
+
const setNumerals = toolDefinition8({
|
|
2619
|
+
name: "set_numerals",
|
|
2620
|
+
description: "Add or update reference numeral descriptions in the registry (shared with the specification). Use null to remove. Every numeral drawn must be described.",
|
|
2621
|
+
inputSchema: z11.object({ entries: z11.array(z11.object({ n: z11.string(), label: z11.string().nullable() })).min(1) })
|
|
2622
|
+
}).server(async ({ entries }, ctx) => {
|
|
2623
|
+
const r = session.applyMany(entries.map((e) => ({ op: "setNumeral", n: e.n, label: e.label })), emitOf2(ctx));
|
|
2624
|
+
return { ok: true, updated: r.accepted };
|
|
2625
|
+
});
|
|
2626
|
+
const setSheet = toolDefinition8({
|
|
2627
|
+
name: "set_sheet",
|
|
2628
|
+
description: "Change sheet size or orientation. Prefer portrait; use landscape only for wide figures.",
|
|
2629
|
+
inputSchema: z11.object({ size: z11.enum(["a4", "letter"]).optional(), orientation: z11.enum(["portrait", "landscape"]).optional() })
|
|
2630
|
+
}).server(async ({ size, orientation }, ctx) => {
|
|
2631
|
+
const sheet = { ...session.doc.sheet, ...size ? { size } : {}, ...orientation ? { orientation } : {} };
|
|
2632
|
+
const err = session.apply({ op: "setSheet", sheet }, emitOf2(ctx));
|
|
2633
|
+
return err ? { ok: false, error: err } : { ok: true, drawing: describeDocument(session.doc).split("\n").slice(0, 2).join("\n") };
|
|
2634
|
+
});
|
|
2635
|
+
const checkCompliance = toolDefinition8({
|
|
2636
|
+
name: "check_compliance",
|
|
2637
|
+
description: "Run the deterministic patent-office rule check on the whole figure. Errors must be fixed before you finish; warnings should be fixed when reasonable.",
|
|
2638
|
+
inputSchema: z11.object({})
|
|
2639
|
+
}).server(async () => {
|
|
2640
|
+
const r = session.report();
|
|
2641
|
+
return { ok: r.ok, errors: summariseIssues(r.errors), warnings: summariseIssues(r.warnings) };
|
|
2642
|
+
});
|
|
2643
|
+
const reviewDrawing = toolDefinition8({
|
|
2644
|
+
name: "review_drawing",
|
|
2645
|
+
description: "Render the figure and have a reviewer look at it for visual problems (overlaps, crossing leaders, cramped or unbalanced layout, missing parts from the plan). Use after the initial drawing is complete and compliance is clean; not needed for small edits.",
|
|
2646
|
+
inputSchema: z11.object({ focus: z11.string().optional().meta({ description: "Optional area to scrutinise." }) })
|
|
2647
|
+
}).server(async ({ focus }, ctx) => {
|
|
2648
|
+
if (session.reviews >= deps.maxReviews) {
|
|
2649
|
+
return { ok: true, verdict: "ok", findings: [], note: "Review budget used. Finish now." };
|
|
2650
|
+
}
|
|
2651
|
+
const emit = emitOf2(ctx);
|
|
2652
|
+
session.reviews += 1;
|
|
2653
|
+
session.status(emit, "critiquing", session.reviews === 1 ? "Reviewing the drawing" : `Review pass ${session.reviews}`);
|
|
2654
|
+
const r = await deps.review(focus);
|
|
2655
|
+
emit?.(EVENTS.review, { round: session.reviews, verdict: r.verdict, findings: r.findings });
|
|
2656
|
+
session.status(emit, "drawing", r.verdict === "ok" ? "Finishing" : "Applying review fixes");
|
|
2657
|
+
return { ok: true, ...r, reviewsLeft: deps.maxReviews - session.reviews };
|
|
2658
|
+
});
|
|
2659
|
+
const setExplodedView = toolDefinition8({
|
|
2660
|
+
name: "set_exploded_view",
|
|
2661
|
+
description: "Switch between the composite (assembled) and exploded view of the same model. Each component layer has an explode offset; numerals follow the part their leader touches and dash-dot alignment lines are drawn. Use auto with an axis to spread parts automatically, or give explicit offsets (mm) per layer.",
|
|
2662
|
+
inputSchema: z11.object({
|
|
2663
|
+
view: z11.enum(["composite", "exploded"]),
|
|
2664
|
+
auto: z11.enum(["x", "y"]).optional().meta({ description: "Spread component layers along this axis." }),
|
|
2665
|
+
offsets: z11.array(z11.object({ layerId: z11.string(), dx: z11.number(), dy: z11.number() })).optional(),
|
|
2666
|
+
alignmentLines: z11.boolean().optional()
|
|
2667
|
+
})
|
|
2668
|
+
}).server(async ({ view, auto, offsets, alignmentLines }, ctx) => {
|
|
2669
|
+
const patches = [];
|
|
2670
|
+
if (auto) patches.push(autoExplodePatch(session.doc, auto));
|
|
2671
|
+
for (const o of offsets ?? []) patches.push({ op: "updateLayer", id: o.layerId, changes: { explode: { dx: o.dx, dy: o.dy } } });
|
|
2672
|
+
patches.push({ op: "setView", view, ...alignmentLines === void 0 ? {} : { explodeLines: alignmentLines } });
|
|
2673
|
+
const r = session.applyMany(patches, emitOf2(ctx));
|
|
2674
|
+
return {
|
|
2675
|
+
ok: r.errors.length === 0,
|
|
2676
|
+
offsets: session.doc.layers.filter((l) => l.explode).map((l) => ({ layerId: l.id, ...l.explode })),
|
|
2677
|
+
...r.errors.length ? { errors: r.errors } : {},
|
|
2678
|
+
issues: summariseIssues([...session.report().errors, ...session.report().warnings]).slice(0, 8)
|
|
2679
|
+
};
|
|
2680
|
+
});
|
|
2681
|
+
const skillTools = SKILLS.flatMap((s) => s.tools?.(session) ?? []);
|
|
2682
|
+
return [
|
|
2683
|
+
getDrawing,
|
|
2684
|
+
planFigure,
|
|
2685
|
+
loadSkill,
|
|
2686
|
+
addLayer,
|
|
2687
|
+
updateLayer,
|
|
2688
|
+
removeLayer,
|
|
2689
|
+
addItems,
|
|
2690
|
+
updateItems,
|
|
2691
|
+
removeItems,
|
|
2692
|
+
moveItems,
|
|
2693
|
+
setNumerals,
|
|
2694
|
+
setSheet,
|
|
2695
|
+
checkCompliance,
|
|
2696
|
+
reviewDrawing,
|
|
2697
|
+
setExplodedView,
|
|
2698
|
+
...skillTools
|
|
2699
|
+
];
|
|
2700
|
+
}
|
|
2701
|
+
|
|
2702
|
+
// ../../src/patent-render/server/prompts.ts
|
|
2703
|
+
function contextBlock(ctx) {
|
|
2704
|
+
if (!ctx) return "No application context was provided.";
|
|
2705
|
+
const parts = [];
|
|
2706
|
+
if (ctx.title) parts.push(`Title: ${ctx.title}`);
|
|
2707
|
+
if (ctx.claims) parts.push(`Claims:
|
|
2708
|
+
${ctx.claims.slice(0, 12e3)}`);
|
|
2709
|
+
if (ctx.specExcerpt) parts.push(`Specification excerpt:
|
|
2710
|
+
${ctx.specExcerpt.slice(0, 12e3)}`);
|
|
2711
|
+
const reg = Object.entries(ctx.numeralRegistry ?? {});
|
|
2712
|
+
if (reg.length) parts.push(`Reference numerals already used in the application: ${reg.map(([k, v]) => `${k} ${v}`).join("; ")}`);
|
|
2713
|
+
return parts.join("\n\n") || "No application context was provided.";
|
|
2714
|
+
}
|
|
2715
|
+
function drawerSystemPrompt(doc, selection, ctx, prefs) {
|
|
2716
|
+
const p = PROFILES[doc.jurisdiction];
|
|
2717
|
+
const isEmpty = doc.layers.every((l) => l.items.every((i) => i.type === "figLabel"));
|
|
2718
|
+
return `
|
|
2719
|
+
You are a patent draftsperson. You produce formal patent drawings as editable vector line art by calling tools. Everything you draw appears live on the user's canvas, layer by layer.
|
|
2720
|
+
|
|
2721
|
+
# The figure
|
|
2722
|
+
${describeDocument(doc, selection)}
|
|
2723
|
+
|
|
2724
|
+
# The application
|
|
2725
|
+
${contextBlock(ctx)}
|
|
2726
|
+
|
|
2727
|
+
# User preferences
|
|
2728
|
+
${preferencesBlock(prefs)}
|
|
2729
|
+
|
|
2730
|
+
# How to work
|
|
2731
|
+
${isEmpty ? `This is a NEW figure.
|
|
2732
|
+
1. Call plan_figure with the user's request (include relevant claim language). The plan fixes the figure type, view, components and numerals, and its "spec" is your blueprint: follow its proportions, counts and placements exactly.
|
|
2733
|
+
2. Call load_skill for the plan's figure type and follow its conventions.
|
|
2734
|
+
3. Draw: create the plan's layers, then the geometry, then reference numerals and set_numerals for every numeral.
|
|
2735
|
+
4. Call check_compliance and fix every error (and warnings where reasonable).
|
|
2736
|
+
5. Call review_drawing once; apply its fixes; review a second time only if the first review found real problems.
|
|
2737
|
+
6. Finish with a short plain-text message (at most 3 sentences, no markdown, no lists) saying what the figure shows and anything the user should check.` : `This figure already has content, possibly edited by hand. Treat the request as an EDIT.
|
|
2738
|
+
- Make targeted changes with update_items / add_items / remove_items / move_items. Never redraw the figure from scratch unless explicitly asked.
|
|
2739
|
+
- Preserve manual edits: do not move or restyle items the request does not concern.
|
|
2740
|
+
- If the user has a selection, "this", "these" and "it" refer to the selected items.
|
|
2741
|
+
- Call get_drawing if you need fresh positions after several edits. Call load_skill if you need conventions for an unfamiliar figure type.
|
|
2742
|
+
- Run check_compliance after edits; review_drawing is optional for small edits.
|
|
2743
|
+
- Finish with one plain-text sentence describing the change (no markdown).`}
|
|
2744
|
+
|
|
2745
|
+
# Drawing rules (${p.name}, ${p.citation})
|
|
2746
|
+
- Black line art only. No colour, no grey, no shading except hatching for cut sections. Fill is none, white (to occlude) or black (very thin parts only).
|
|
2747
|
+
- Coordinates are millimetres on the sheet. Keep everything inside the usable area; leave the bottom ~20 mm for "FIG. ${doc.figureNumber}" (item id fig-label, keep exactly one; move it with update_items, centred under the drawing).
|
|
2748
|
+
- The figure should fill most of the usable area. Do not draw tiny figures in a corner.
|
|
2749
|
+
- Reference numerals: cap height >= ${p.minCapHeight} mm (use 3.5), placed outside the parts, with leaders that touch the part and do not cross other leaders or numerals. Same part = same numeral across the application; reuse the application's numerals.
|
|
2750
|
+
- Text matter: ${p.text.mode === "strict" ? "only when indispensable (single words, flowchart catchwords)" : "short legends only"}; max ${p.text.maxWordsPerText} words per text item, ${p.text.maxWordsPerCatchword} per connector label. Descriptions belong in the specification.
|
|
2751
|
+
- Give items readable, stable ids (e.g. "housing-outer", "n202") and names for important parts. Put each component on its own layer named with its numeral.
|
|
2752
|
+
- Batch work: add many items per add_items call. Avoid one call per item.
|
|
2753
|
+
|
|
2754
|
+
# Tone
|
|
2755
|
+
Be brief in chat. The drawing is the answer. Do not narrate each tool call.
|
|
2756
|
+
`.trim();
|
|
2757
|
+
}
|
|
2758
|
+
var STYLE_GUIDE = {
|
|
2759
|
+
standard: "Standard patent line art: clean outlines, the features the claims need, a few key details. No decorative shading.",
|
|
2760
|
+
detailed: "Detailed rendering in the style of formal US product figures: line-weight hierarchy (0.5 mm silhouettes, 0.35 mm edges, 0.25 mm detail), surface shading strokes on curved faces, glare strokes on glass or glossy faces, textures such as knurling, vents, grips and seams, small hardware such as screws, LEDs and labels as outlines.",
|
|
2761
|
+
minimal: "Minimal outline: only the outlines needed to identify each claimed component. No shading, no textures, the fewest lines possible."
|
|
2762
|
+
};
|
|
2763
|
+
function preferencesBlock(prefs) {
|
|
2764
|
+
const lines = [];
|
|
2765
|
+
if (prefs?.figureType) lines.push(`Figure type REQUIRED by the user: ${prefs.figureType} (${FIGURE_TYPE_LABEL[prefs.figureType]}). Use it.`);
|
|
2766
|
+
lines.push(`Drawing style: ${STYLE_LABEL[prefs?.style ?? "standard"].label}. ${STYLE_GUIDE[prefs?.style ?? "standard"]}`);
|
|
2767
|
+
return lines.join("\n");
|
|
2768
|
+
}
|
|
2769
|
+
function plannerSystemPrompt(doc, ctx, prefs) {
|
|
2770
|
+
const p = PROFILES[doc.jurisdiction];
|
|
2771
|
+
return `
|
|
2772
|
+
You are a senior patent agent and industrial designer planning ONE patent drawing (FIG. ${doc.figureNumber}) before a draftsperson draws it.
|
|
2773
|
+
Expand the user's request, however short, into a precise, complete plan that can be drawn without guessing.
|
|
2774
|
+
|
|
2775
|
+
# Application
|
|
2776
|
+
${contextBlock(ctx)}
|
|
2777
|
+
|
|
2778
|
+
# User preferences
|
|
2779
|
+
${preferencesBlock(prefs)}
|
|
2780
|
+
|
|
2781
|
+
# Planning rules
|
|
2782
|
+
- figureType: one of ${Object.entries(FIGURE_TYPE_LABEL).map(([k, v]) => `${k} (${v})`).join(", ")}. If the user fixed a type above, use it. Otherwise: method claims \u2192 flowchart; interacting system components \u2192 blockDiagram; a physical product \u2192 perspective3d for an overall view or mechanical2d for orthographic, section or exploded views; GUI \u2192 uiScreen; electronics \u2192 circuit; compounds \u2192 chemical.
|
|
2783
|
+
- view: the formal caption as in the brief description of drawings (e.g. "Perspective view of a USB-C hub according to an embodiment").
|
|
2784
|
+
- spec: the FULL generation spec, 120-300 words. This matters most when the request is short (e.g. "USB-C hub with 2 USB-A ports, HDMI, SD card slot and a short cable"): invent a realistic, coherent product and state:
|
|
2785
|
+
* overall form and proportions in mm (e.g. body 110 x 45 x 15 mm, corner radius 6 mm), the viewing angle, and which faces are visible;
|
|
2786
|
+
* every component's shape, count, size, position and orientation relative to the body (e.g. two USB-A ports side by side on the right long face, 13 x 6 mm openings, 4 mm apart);
|
|
2787
|
+
* connections, such as the cable exit point, cable length and bend, and the connector at its end;
|
|
2788
|
+
* surface details for the chosen style (seams, vents, LEDs, logos as plain outlines, grips) and what to leave out;
|
|
2789
|
+
* placement on the sheet: the figure should fill about 70% of the usable area, with numerals spread around it.
|
|
2790
|
+
With claims available, keep the spec faithful to them and do not add unclaimed features that would confuse the reader.
|
|
2791
|
+
- components: every element the figure must show, each with a reference numeral. Reuse numerals from the application registry for the same elements (reused: true). New numerals use the FIG. ${doc.figureNumber} series (${doc.figureNumber}02, ${doc.figureNumber}04, ... even numbers) and must not collide with existing ones. The whole product gets an underlined assembly numeral when useful (e.g. ${doc.figureNumber}00).
|
|
2792
|
+
- name: the element's name as used in the claims or spec (lower case, e.g. "HDMI port").
|
|
2793
|
+
- layers: one layer per major component or group, plus "annotations" last. Use readable ids.
|
|
2794
|
+
- notes: concrete drawing guidance, such as line conventions, what to emphasise and what to omit.
|
|
2795
|
+
- Respect ${p.name} rules: black line art, minimal text (${p.text.mode}).
|
|
2796
|
+
- If the user attached a sketch or image, follow its layout and content (or its style, if they say so), cleaned up into formal line art.
|
|
2797
|
+
`.trim();
|
|
2798
|
+
}
|
|
2799
|
+
function criticSystemPrompt(doc) {
|
|
2800
|
+
const p = PROFILES[doc.jurisdiction];
|
|
2801
|
+
return `
|
|
2802
|
+
You review a rendered patent drawing (FIG. ${doc.figureNumber}, ${p.name}) for visual quality before filing.
|
|
2803
|
+
Judge only what you can see. Report concrete, actionable problems, each tied to item ids from the drawing listing when possible:
|
|
2804
|
+
- overlapping or touching elements that should be separate; text overlapping lines
|
|
2805
|
+
- leaders that cross each other, cross other numerals, or end in empty space instead of on the part
|
|
2806
|
+
- numerals crowded on one side or too close to the drawing (< 5 mm)
|
|
2807
|
+
- cramped, lopsided or tiny layout (figure should fill most of the sheet's usable area); FIG. label not centred below
|
|
2808
|
+
- missing components from the plan, or parts that don't read as what they are
|
|
2809
|
+
- anything that looks unlike formal patent line art
|
|
2810
|
+
Return verdict "ok" when nothing important needs fixing (minor nitpicks don't count). Keep findings to the 6 most important.
|
|
2811
|
+
`.trim();
|
|
2812
|
+
}
|
|
2813
|
+
|
|
2814
|
+
// ../../src/patent-render/server/agents.ts
|
|
2815
|
+
import { chat } from "@tanstack/ai";
|
|
2816
|
+
import { z as z12 } from "zod";
|
|
2817
|
+
|
|
2818
|
+
// ../../src/patent-render/server/png.ts
|
|
2819
|
+
import { Resvg } from "@resvg/resvg-js";
|
|
2820
|
+
|
|
2821
|
+
// ../../src/patent-render/render/nodes.ts
|
|
2822
|
+
var INK = "#000";
|
|
2823
|
+
var FONT_FAMILY = "Arial, Helvetica, sans-serif";
|
|
2824
|
+
var SERIF_FAMILY = "'Times New Roman', Times, Georgia, serif";
|
|
2825
|
+
var ARROW_MARKER_ID = "pr-arrow";
|
|
2826
|
+
var ARROW_START_MARKER_ID = "pr-arrow-start";
|
|
2827
|
+
var OPEN = "-open";
|
|
2828
|
+
var DASH = {
|
|
2829
|
+
solid: null,
|
|
2830
|
+
dashed: "3 1.5",
|
|
2831
|
+
centre: "8 1.5 1.5 1.5",
|
|
2832
|
+
phantom: "8 1.5 1.5 1.5 1.5 1.5"
|
|
2833
|
+
};
|
|
2834
|
+
var r32 = (n2) => Math.round(n2 * 1e3) / 1e3;
|
|
2835
|
+
var pts = (p) => p.map(([x, y]) => `${r32(x)},${r32(y)}`).join(" ");
|
|
2836
|
+
function strokeAttrs(s) {
|
|
2837
|
+
const a = {
|
|
2838
|
+
stroke: INK,
|
|
2839
|
+
"stroke-width": s.width,
|
|
2840
|
+
"stroke-linecap": "round",
|
|
2841
|
+
"stroke-linejoin": "round"
|
|
2842
|
+
};
|
|
2843
|
+
const dash = DASH[s.style];
|
|
2844
|
+
if (dash) a["stroke-dasharray"] = dash;
|
|
2845
|
+
return a;
|
|
2846
|
+
}
|
|
2847
|
+
var fillAttr = (f) => f === "black" ? INK : f === "white" ? "#fff" : "none";
|
|
2848
|
+
function textNode(x, y, text, cap, anchor, extra = {}) {
|
|
2849
|
+
return {
|
|
2850
|
+
tag: "text",
|
|
2851
|
+
attrs: {
|
|
2852
|
+
x: r32(x),
|
|
2853
|
+
y: r32(y),
|
|
2854
|
+
"font-size": r32(fontSize(cap)),
|
|
2855
|
+
"font-family": FONT_FAMILY,
|
|
2856
|
+
"text-anchor": anchor,
|
|
2857
|
+
fill: INK,
|
|
2858
|
+
...extra
|
|
2859
|
+
},
|
|
2860
|
+
text
|
|
2861
|
+
};
|
|
2862
|
+
}
|
|
2863
|
+
function arcPath(cx, cy, r, start, end) {
|
|
2864
|
+
const rad = (d) => d * Math.PI / 180;
|
|
2865
|
+
const sweep = ((end - start) % 360 + 360) % 360 || 360;
|
|
2866
|
+
if (sweep >= 359.999) {
|
|
2867
|
+
return `M ${r32(cx - r)} ${r32(cy)} a ${r32(r)} ${r32(r)} 0 1 1 ${r32(2 * r)} 0 a ${r32(r)} ${r32(r)} 0 1 1 ${r32(-2 * r)} 0`;
|
|
2868
|
+
}
|
|
2869
|
+
const p0 = [cx + r * Math.cos(rad(start)), cy + r * Math.sin(rad(start))];
|
|
2870
|
+
const p1 = [cx + r * Math.cos(rad(start + sweep)), cy + r * Math.sin(rad(start + sweep))];
|
|
2871
|
+
return `M ${r32(p0[0])} ${r32(p0[1])} A ${r32(r)} ${r32(r)} 0 ${sweep > 180 ? 1 : 0} 1 ${r32(p1[0])} ${r32(p1[1])}`;
|
|
2872
|
+
}
|
|
2873
|
+
function hatchLines(points, angle, spacing) {
|
|
2874
|
+
const b = boxFromPoints(points);
|
|
2875
|
+
const [cx, cy] = centre(b);
|
|
2876
|
+
const half = Math.hypot(b.w, b.h) / 2 + spacing;
|
|
2877
|
+
const t = angle * Math.PI / 180;
|
|
2878
|
+
const dir = [Math.cos(t), Math.sin(t)];
|
|
2879
|
+
const nrm = [-dir[1], dir[0]];
|
|
2880
|
+
const segs = [];
|
|
2881
|
+
for (let o = -half; o <= half; o += spacing) {
|
|
2882
|
+
const px = cx + nrm[0] * o, py = cy + nrm[1] * o;
|
|
2883
|
+
segs.push(`M ${r32(px - dir[0] * half)} ${r32(py - dir[1] * half)} L ${r32(px + dir[0] * half)} ${r32(py + dir[1] * half)}`);
|
|
2884
|
+
}
|
|
2885
|
+
return segs.join(" ");
|
|
2886
|
+
}
|
|
2887
|
+
function numeralNodes(item, bold) {
|
|
2888
|
+
const label = numeralLabelBox(item.at, item.n, item.size);
|
|
2889
|
+
const baseline = item.at[1] + item.size / 2;
|
|
2890
|
+
const out = [textNode(item.at[0], baseline, item.n, item.size, "middle", bold ? { "font-weight": "bold" } : {})];
|
|
2891
|
+
if (item.underline) {
|
|
2892
|
+
out.push({
|
|
2893
|
+
tag: "line",
|
|
2894
|
+
attrs: { x1: r32(label.x), y1: r32(baseline + 0.8), x2: r32(label.x + label.w), y2: r32(baseline + 0.8), ...strokeAttrs({ width: 0.25, style: "solid" }) }
|
|
2895
|
+
});
|
|
2896
|
+
}
|
|
2897
|
+
if (item.leader !== "none") {
|
|
2898
|
+
const padded = { x: label.x - 0.8, y: label.y - 0.8, w: label.w + 1.6, h: label.h + 1.6 };
|
|
2899
|
+
const s = boxExitPoint(padded, item.target);
|
|
2900
|
+
const t = item.target;
|
|
2901
|
+
let d;
|
|
2902
|
+
if (item.leader === "curved") {
|
|
2903
|
+
const mx = (s[0] + t[0]) / 2, my = (s[1] + t[1]) / 2;
|
|
2904
|
+
const dx = t[0] - s[0], dy = t[1] - s[1];
|
|
2905
|
+
const k = 0.2;
|
|
2906
|
+
d = `M ${r32(s[0])} ${r32(s[1])} Q ${r32(mx - dy * k)} ${r32(my + dx * k)} ${r32(t[0])} ${r32(t[1])}`;
|
|
2907
|
+
} else {
|
|
2908
|
+
d = `M ${r32(s[0])} ${r32(s[1])} L ${r32(t[0])} ${r32(t[1])}`;
|
|
2909
|
+
}
|
|
2910
|
+
out.push({ tag: "path", attrs: { d, fill: "none", ...strokeAttrs({ width: 0.25, style: "solid" }) } });
|
|
2911
|
+
}
|
|
2912
|
+
return out;
|
|
2913
|
+
}
|
|
2914
|
+
function curveControls(cg) {
|
|
2915
|
+
const { a, b } = cg;
|
|
2916
|
+
const k = Math.max(8, Math.hypot(b[0] - a[0], b[1] - a[1]) / 2.5);
|
|
2917
|
+
const dir = (side, from, to) => {
|
|
2918
|
+
if (side === "top") return [0, -1];
|
|
2919
|
+
if (side === "bottom") return [0, 1];
|
|
2920
|
+
if (side === "left") return [-1, 0];
|
|
2921
|
+
if (side === "right") return [1, 0];
|
|
2922
|
+
const d = Math.hypot(to[0] - from[0], to[1] - from[1]) || 1;
|
|
2923
|
+
return [(to[0] - from[0]) / d, (to[1] - from[1]) / d];
|
|
2924
|
+
};
|
|
2925
|
+
const da = dir(cg.sideA, a, b), db = dir(cg.sideB, b, a);
|
|
2926
|
+
return [a, [a[0] + da[0] * k, a[1] + da[1] * k], [b[0] + db[0] * k, b[1] + db[1] * k], b];
|
|
2927
|
+
}
|
|
2928
|
+
function itemNode(doc, item) {
|
|
2929
|
+
const transform = {};
|
|
2930
|
+
if (item.rotation) {
|
|
2931
|
+
const [cx, cy] = centre(itemBox(doc, item));
|
|
2932
|
+
transform.transform = `rotate(${r32(item.rotation)} ${r32(cx)} ${r32(cy)})`;
|
|
2933
|
+
}
|
|
2934
|
+
const g = (children) => ({ tag: "g", attrs: { ...transform }, children });
|
|
2935
|
+
switch (item.type) {
|
|
2936
|
+
case "line":
|
|
2937
|
+
return g([{ tag: "line", attrs: { x1: item.a[0], y1: item.a[1], x2: item.b[0], y2: item.b[1], ...strokeAttrs(item.stroke) } }]);
|
|
2938
|
+
case "polyline":
|
|
2939
|
+
return g([{
|
|
2940
|
+
tag: item.closed ? "polygon" : "polyline",
|
|
2941
|
+
attrs: { points: pts(item.points), fill: fillAttr(item.fill), ...strokeAttrs(item.stroke) }
|
|
2942
|
+
}]);
|
|
2943
|
+
case "path":
|
|
2944
|
+
return g([{ tag: "path", attrs: { d: item.d, fill: fillAttr(item.fill), ...strokeAttrs(item.stroke) } }]);
|
|
2945
|
+
case "rect":
|
|
2946
|
+
return g([{
|
|
2947
|
+
tag: "rect",
|
|
2948
|
+
attrs: { x: item.x, y: item.y, width: item.w, height: item.h, rx: item.radius, fill: fillAttr(item.fill), ...strokeAttrs(item.stroke) }
|
|
2949
|
+
}]);
|
|
2950
|
+
case "ellipse":
|
|
2951
|
+
return g([{
|
|
2952
|
+
tag: "ellipse",
|
|
2953
|
+
attrs: { cx: item.cx, cy: item.cy, rx: item.rx, ry: item.ry, fill: fillAttr(item.fill), ...strokeAttrs(item.stroke) }
|
|
2954
|
+
}]);
|
|
2955
|
+
case "arc":
|
|
2956
|
+
return g([{ tag: "path", attrs: { d: arcPath(item.cx, item.cy, item.r, item.start, item.end), fill: "none", ...strokeAttrs(item.stroke) } }]);
|
|
2957
|
+
case "text": {
|
|
2958
|
+
const lines = item.text.split("\n");
|
|
2959
|
+
const lh = fontSize(item.size) * 1.2;
|
|
2960
|
+
return g(lines.map((ln, i) => textNode(item.x, item.y + i * lh, ln, item.size, item.anchor)));
|
|
2961
|
+
}
|
|
2962
|
+
case "figLabel":
|
|
2963
|
+
return g([textNode(
|
|
2964
|
+
item.x,
|
|
2965
|
+
item.y,
|
|
2966
|
+
figLabelText(doc),
|
|
2967
|
+
item.size,
|
|
2968
|
+
"middle",
|
|
2969
|
+
doc.lettering?.figLabel === "serif-italic" ? { "font-weight": "bold", "font-style": "italic", "font-family": SERIF_FAMILY } : { "font-weight": "bold" }
|
|
2970
|
+
)]);
|
|
2971
|
+
case "numeral":
|
|
2972
|
+
return g(numeralNodes(item, doc.lettering?.numeralWeight === "bold"));
|
|
2973
|
+
case "connector": {
|
|
2974
|
+
const cg = connectorGeometry(doc, item);
|
|
2975
|
+
const curved = item.routing === "curved";
|
|
2976
|
+
const route = item.routing === "orthogonal" ? orthogonalRoute(cg.a, cg.b, cg.sideA, cg.sideB) : curved ? curveControls(cg) : [cg.a, cg.b];
|
|
2977
|
+
const attrs = curved ? { d: `M ${r32(route[0][0])} ${r32(route[0][1])} C ${route.slice(1).map(([x, y]) => `${r32(x)} ${r32(y)}`).join(" ")}`, fill: "none", ...strokeAttrs(item.stroke) } : { points: pts(route), fill: "none", ...strokeAttrs(item.stroke) };
|
|
2978
|
+
const style = item.arrowStyle === "open" ? OPEN : "";
|
|
2979
|
+
if (item.arrow === "end" || item.arrow === "both") attrs["marker-end"] = `url(#${ARROW_MARKER_ID}${style})`;
|
|
2980
|
+
if (item.arrow === "start" || item.arrow === "both") attrs["marker-start"] = `url(#${ARROW_START_MARKER_ID}${style})`;
|
|
2981
|
+
const children = [{ tag: curved ? "path" : "polyline", attrs }];
|
|
2982
|
+
if (item.label) {
|
|
2983
|
+
const [p0, p1] = route;
|
|
2984
|
+
const vertical = Math.abs(p1[0] - p0[0]) < Math.abs(p1[1] - p0[1]);
|
|
2985
|
+
const dir = vertical ? Math.sign(p1[1] - p0[1]) || 1 : Math.sign(p1[0] - p0[0]) || 1;
|
|
2986
|
+
const along = Math.min(5, Math.hypot(p1[0] - p0[0], p1[1] - p0[1]) / 2);
|
|
2987
|
+
if (vertical) children.push(textNode(p0[0] + 1.5, p0[1] + dir * along + 1.6, item.label, 3.2, "start"));
|
|
2988
|
+
else children.push(textNode(p0[0] + dir * along, p0[1] - 1.5, item.label, 3.2, dir > 0 ? "start" : "end"));
|
|
2989
|
+
}
|
|
2990
|
+
return g(children);
|
|
2991
|
+
}
|
|
2992
|
+
case "hatch": {
|
|
2993
|
+
const clipId = `pr-clip-${item.id}`;
|
|
2994
|
+
return g([
|
|
2995
|
+
{ tag: "clipPath", attrs: { id: clipId }, children: [{ tag: "polygon", attrs: { points: pts(item.points) } }] },
|
|
2996
|
+
{
|
|
2997
|
+
tag: "path",
|
|
2998
|
+
attrs: { d: hatchLines(item.points, item.angle, item.spacing), "clip-path": `url(#${clipId})`, fill: "none", ...strokeAttrs({ width: item.lineWidth, style: "solid" }) }
|
|
2999
|
+
}
|
|
3000
|
+
]);
|
|
3001
|
+
}
|
|
3002
|
+
case "sectionLine": {
|
|
3003
|
+
const children = [
|
|
3004
|
+
{ tag: "line", attrs: { x1: item.a[0], y1: item.a[1], x2: item.b[0], y2: item.b[1], ...strokeAttrs({ ...item.stroke, style: "centre" }) } }
|
|
3005
|
+
];
|
|
3006
|
+
for (const p of [item.a, item.b]) {
|
|
3007
|
+
children.push(textNode(p[0], p[1] - 2, item.label, 3.5, "middle"));
|
|
3008
|
+
}
|
|
3009
|
+
return g(children);
|
|
3010
|
+
}
|
|
3011
|
+
}
|
|
3012
|
+
}
|
|
3013
|
+
function defsNode() {
|
|
3014
|
+
return {
|
|
3015
|
+
tag: "defs",
|
|
3016
|
+
attrs: {},
|
|
3017
|
+
// Fixed 3.2 mm arrowheads, independent of line weight (legible after reduction).
|
|
3018
|
+
// Start arrows use their own reversed marker: resvg ignores orient="auto-start-reverse".
|
|
3019
|
+
children: [
|
|
3020
|
+
{
|
|
3021
|
+
tag: "marker",
|
|
3022
|
+
attrs: { id: ARROW_MARKER_ID, viewBox: "0 0 10 10", refX: 9, refY: 5, markerWidth: 3.2, markerHeight: 3.2, markerUnits: "userSpaceOnUse", orient: "auto" },
|
|
3023
|
+
children: [{ tag: "path", attrs: { d: "M 0 0 L 10 5 L 0 10 z", fill: INK } }]
|
|
3024
|
+
},
|
|
3025
|
+
{
|
|
3026
|
+
tag: "marker",
|
|
3027
|
+
attrs: { id: ARROW_START_MARKER_ID, viewBox: "0 0 10 10", refX: 1, refY: 5, markerWidth: 3.2, markerHeight: 3.2, markerUnits: "userSpaceOnUse", orient: "auto" },
|
|
3028
|
+
children: [{ tag: "path", attrs: { d: "M 10 0 L 0 5 L 10 10 z", fill: INK } }]
|
|
3029
|
+
},
|
|
3030
|
+
// Open (line) arrowheads.
|
|
3031
|
+
{
|
|
3032
|
+
tag: "marker",
|
|
3033
|
+
attrs: { id: `${ARROW_MARKER_ID}${OPEN}`, viewBox: "0 0 10 10", refX: 9.5, refY: 5, markerWidth: 3.2, markerHeight: 3.2, markerUnits: "userSpaceOnUse", orient: "auto" },
|
|
3034
|
+
children: [{ tag: "path", attrs: { d: "M 0 0.5 L 9.5 5 L 0 9.5", fill: "none", stroke: INK, "stroke-width": 1.1, "stroke-linejoin": "miter" } }]
|
|
3035
|
+
},
|
|
3036
|
+
{
|
|
3037
|
+
tag: "marker",
|
|
3038
|
+
attrs: { id: `${ARROW_START_MARKER_ID}${OPEN}`, viewBox: "0 0 10 10", refX: 0.5, refY: 5, markerWidth: 3.2, markerHeight: 3.2, markerUnits: "userSpaceOnUse", orient: "auto" },
|
|
3039
|
+
children: [{ tag: "path", attrs: { d: "M 10 0.5 L 0.5 5 L 10 9.5", fill: "none", stroke: INK, "stroke-width": 1.1, "stroke-linejoin": "miter" } }]
|
|
3040
|
+
}
|
|
3041
|
+
]
|
|
3042
|
+
};
|
|
3043
|
+
}
|
|
3044
|
+
function layerNodes(doc, opts = {}) {
|
|
3045
|
+
return doc.layers.filter((l) => opts.includeHidden || l.visible).map((layer) => ({
|
|
3046
|
+
tag: "g",
|
|
3047
|
+
attrs: opts.editorAttrs ? { "data-layer-id": layer.id } : {},
|
|
3048
|
+
children: layer.items.filter((it) => opts.includeHidden || !it.hidden).map((it) => {
|
|
3049
|
+
const n2 = itemNode(doc, it);
|
|
3050
|
+
if (opts.editorAttrs) n2.attrs["data-item-id"] = it.id;
|
|
3051
|
+
return n2;
|
|
3052
|
+
})
|
|
3053
|
+
}));
|
|
3054
|
+
}
|
|
3055
|
+
function sheetLabelNodes(doc) {
|
|
3056
|
+
if (!doc.sheetLabel) return [];
|
|
3057
|
+
const { w } = sheetDims(doc.sheet);
|
|
3058
|
+
const p = PROFILES[doc.jurisdiction];
|
|
3059
|
+
const m = effectiveMargins(p, doc.sheet.orientation);
|
|
3060
|
+
return [textNode(m.left + (w - m.left - m.right) / 2, m.top + 5, doc.sheetLabel, 3.5, "middle")];
|
|
3061
|
+
}
|
|
3062
|
+
function documentNode(model, opts = {}) {
|
|
3063
|
+
const doc = viewDocument(model);
|
|
3064
|
+
const { w, h } = sheetDims(doc.sheet);
|
|
3065
|
+
return {
|
|
3066
|
+
tag: "svg",
|
|
3067
|
+
attrs: {
|
|
3068
|
+
xmlns: "http://www.w3.org/2000/svg",
|
|
3069
|
+
width: `${w}mm`,
|
|
3070
|
+
height: `${h}mm`,
|
|
3071
|
+
viewBox: `0 0 ${w} ${h}`
|
|
3072
|
+
},
|
|
3073
|
+
children: [
|
|
3074
|
+
defsNode(),
|
|
3075
|
+
{ tag: "rect", attrs: { x: 0, y: 0, width: w, height: h, fill: "#fff" } },
|
|
3076
|
+
...sheetLabelNodes(doc),
|
|
3077
|
+
...layerNodes(doc, opts)
|
|
3078
|
+
]
|
|
3079
|
+
};
|
|
3080
|
+
}
|
|
3081
|
+
|
|
3082
|
+
// ../../src/patent-render/render/serialize.ts
|
|
3083
|
+
var esc = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
3084
|
+
function serializeNode(n2) {
|
|
3085
|
+
const attrs = Object.entries(n2.attrs).map(([k, v]) => ` ${k}="${esc(String(v))}"`).join("");
|
|
3086
|
+
const inner = (n2.text !== void 0 ? esc(n2.text) : "") + (n2.children ?? []).map(serializeNode).join("");
|
|
3087
|
+
return inner ? `<${n2.tag}${attrs}>${inner}</${n2.tag}>` : `<${n2.tag}${attrs}/>`;
|
|
3088
|
+
}
|
|
3089
|
+
function renderSvg(doc, opts = {}) {
|
|
3090
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
3091
|
+
${serializeNode(documentNode(doc, { ...opts, editorAttrs: false }))}`;
|
|
3092
|
+
}
|
|
3093
|
+
|
|
3094
|
+
// ../../src/patent-render/server/png.ts
|
|
3095
|
+
function renderPng(doc, opts = {}) {
|
|
3096
|
+
const dpi = opts.dpi ?? 300;
|
|
3097
|
+
const { w } = sheetDims(doc.sheet);
|
|
3098
|
+
const widthPx = Math.round(w / 25.4 * dpi);
|
|
3099
|
+
const resvg = new Resvg(renderSvg(doc), {
|
|
3100
|
+
fitTo: { mode: "width", value: widthPx },
|
|
3101
|
+
background: "#ffffff",
|
|
3102
|
+
font: {
|
|
3103
|
+
loadSystemFonts: true,
|
|
3104
|
+
defaultFontFamily: "Arial",
|
|
3105
|
+
sansSerifFamily: "Arial",
|
|
3106
|
+
...opts.fontFiles ? { fontFiles: opts.fontFiles } : {}
|
|
3107
|
+
}
|
|
3108
|
+
});
|
|
3109
|
+
return resvg.render().asPng();
|
|
3110
|
+
}
|
|
3111
|
+
|
|
3112
|
+
// ../../src/patent-render/server/agents.ts
|
|
3113
|
+
var Review = z12.object({
|
|
3114
|
+
verdict: z12.enum(["ok", "revise"]),
|
|
3115
|
+
findings: z12.array(z12.object({
|
|
3116
|
+
issue: z12.string(),
|
|
3117
|
+
itemIds: z12.array(z12.string()).default([]),
|
|
3118
|
+
fix: z12.string().meta({ description: "Concrete instruction, e.g. 'move n204 label to (186, 80)'." })
|
|
3119
|
+
})).max(8)
|
|
3120
|
+
});
|
|
3121
|
+
async function runPlanner(adapter, session, request, o) {
|
|
3122
|
+
const content = [{ type: "text", content: request }, ...session.attachments];
|
|
3123
|
+
const plan = await chat({
|
|
3124
|
+
adapter,
|
|
3125
|
+
threadId: `${o.threadId}:plan`,
|
|
3126
|
+
systemPrompts: [plannerSystemPrompt(session.doc, session.context, session.prefs)],
|
|
3127
|
+
messages: [{ role: "user", content }],
|
|
3128
|
+
outputSchema: FigurePlan,
|
|
3129
|
+
abortController: o.abortController,
|
|
3130
|
+
middleware: o.middleware
|
|
3131
|
+
});
|
|
3132
|
+
return FigurePlan.parse(plan);
|
|
3133
|
+
}
|
|
3134
|
+
async function runCritic(adapter, session, focus, o) {
|
|
3135
|
+
const png = renderPng(session.doc, { dpi: 110, fontFiles: o.fontFiles }).toString("base64");
|
|
3136
|
+
const text = [
|
|
3137
|
+
session.plan ? `Figure plan:
|
|
3138
|
+
${JSON.stringify(session.plan, null, 1)}` : "No plan (edit request).",
|
|
3139
|
+
`Drawing listing (ids, bboxes in mm):
|
|
3140
|
+
${describeDocument(session.doc)}`,
|
|
3141
|
+
focus ? `Pay particular attention to: ${focus}` : ""
|
|
3142
|
+
].filter(Boolean).join("\n\n");
|
|
3143
|
+
const r = await chat({
|
|
3144
|
+
adapter,
|
|
3145
|
+
threadId: `${o.threadId}:review`,
|
|
3146
|
+
systemPrompts: [criticSystemPrompt(session.doc)],
|
|
3147
|
+
messages: [{ role: "user", content: [{ type: "text", content: text }, { type: "image", source: { type: "data", value: png, mimeType: "image/png" } }] }],
|
|
3148
|
+
outputSchema: Review,
|
|
3149
|
+
abortController: o.abortController,
|
|
3150
|
+
middleware: o.middleware
|
|
3151
|
+
});
|
|
3152
|
+
const parsed = Review.parse(r);
|
|
3153
|
+
return {
|
|
3154
|
+
verdict: parsed.verdict,
|
|
3155
|
+
findings: parsed.findings.map((f) => `${f.issue}${f.itemIds.length ? ` [${f.itemIds.join(", ")}]` : ""} \u2192 ${f.fix}`)
|
|
3156
|
+
};
|
|
3157
|
+
}
|
|
3158
|
+
|
|
3159
|
+
// ../../src/patent-render/server/handler.ts
|
|
3160
|
+
var resolveModel = (m) => typeof m === "function" ? m() : m;
|
|
3161
|
+
function latestAttachments(messages) {
|
|
3162
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
3163
|
+
const m = messages[i];
|
|
3164
|
+
if (m?.role !== "user") continue;
|
|
3165
|
+
const parts = Array.isArray(m.parts) ? m.parts : Array.isArray(m.content) ? m.content : [];
|
|
3166
|
+
return parts.filter((p) => p?.type === "image");
|
|
3167
|
+
}
|
|
3168
|
+
return [];
|
|
3169
|
+
}
|
|
3170
|
+
function createPatentRenderHandler(config = {}) {
|
|
3171
|
+
const envModels = llmModels({ provider: "anthropic" });
|
|
3172
|
+
const drawer = () => resolveModel(config.models?.drawer ?? envModels.drawer);
|
|
3173
|
+
const planner = () => resolveModel(config.models?.planner ?? envModels.planner);
|
|
3174
|
+
const critic = () => resolveModel(config.models?.critic ?? envModels.critic);
|
|
3175
|
+
const usageMw = (phase) => config.onUsage ? [{ name: `patent-render-usage-${phase}`, onUsage: (_ctx, usage) => config.onUsage({ phase, usage }) }] : [];
|
|
3176
|
+
return async function POST(request) {
|
|
3177
|
+
let params;
|
|
3178
|
+
try {
|
|
3179
|
+
params = await chatParamsFromRequest(request);
|
|
3180
|
+
} catch {
|
|
3181
|
+
return Response.json({ error: "Invalid chat request" }, { status: 400 });
|
|
3182
|
+
}
|
|
3183
|
+
const body = params.forwardedProps;
|
|
3184
|
+
const parsed = PatentDocument.safeParse(body.document);
|
|
3185
|
+
if (!parsed.success) {
|
|
3186
|
+
return Response.json({ error: "Missing or invalid document in forwardedProps" }, { status: 400 });
|
|
3187
|
+
}
|
|
3188
|
+
const session = new DrawingSession({
|
|
3189
|
+
doc: parsed.data,
|
|
3190
|
+
selection: Array.isArray(body.selection) ? body.selection.filter((s) => typeof s === "string") : [],
|
|
3191
|
+
context: body.context,
|
|
3192
|
+
attachments: latestAttachments(params.messages),
|
|
3193
|
+
prefs: GenerationPrefs.safeParse(body.preferences ?? {}).data
|
|
3194
|
+
});
|
|
3195
|
+
let models;
|
|
3196
|
+
try {
|
|
3197
|
+
models = { drawer: drawer(), planner: planner(), critic: critic() };
|
|
3198
|
+
} catch (e) {
|
|
3199
|
+
console.error("[patent-render] model configuration error:", e instanceof Error ? e.message : e);
|
|
3200
|
+
return Response.json({ error: "PatentRender model is not configured on the server." }, { status: 503 });
|
|
3201
|
+
}
|
|
3202
|
+
const abortController = new AbortController();
|
|
3203
|
+
request.signal?.addEventListener("abort", () => abortController.abort());
|
|
3204
|
+
const sub = { threadId: params.threadId, abortController };
|
|
3205
|
+
const tools = createDrawingTools(session, {
|
|
3206
|
+
maxReviews: config.maxReviews ?? 2,
|
|
3207
|
+
plan: (req) => runPlanner(models.planner, session, req, { ...sub, middleware: usageMw("planner") }),
|
|
3208
|
+
review: (focus) => runCritic(models.critic, session, focus, { ...sub, middleware: usageMw("critic"), fontFiles: config.fontFiles })
|
|
3209
|
+
});
|
|
3210
|
+
const stream = chat2({
|
|
3211
|
+
adapter: models.drawer,
|
|
3212
|
+
messages: params.messages,
|
|
3213
|
+
threadId: params.threadId,
|
|
3214
|
+
systemPrompts: [drawerSystemPrompt(session.doc, session.selection, session.context, session.prefs)],
|
|
3215
|
+
tools,
|
|
3216
|
+
agentLoopStrategy: maxIterations(config.maxTurns ?? 40),
|
|
3217
|
+
abortController,
|
|
3218
|
+
middleware: usageMw("drawer")
|
|
3219
|
+
});
|
|
3220
|
+
return toServerSentEventsResponse(stream, { abortController });
|
|
3221
|
+
};
|
|
3222
|
+
}
|
|
3223
|
+
|
|
3224
|
+
// ../../src/patent-render/server/actions.ts
|
|
3225
|
+
async function exportPatentPng(document, dpi = 300) {
|
|
3226
|
+
const doc = PatentDocument.parse(document);
|
|
3227
|
+
const png = renderPng(doc, { dpi: Math.min(600, Math.max(72, dpi)) });
|
|
3228
|
+
return { dataUrl: `data:image/png;base64,${png.toString("base64")}`, report: validate(doc) };
|
|
3229
|
+
}
|
|
3230
|
+
export {
|
|
3231
|
+
DEFAULT_MODELS,
|
|
3232
|
+
LLM_KEY_ENV,
|
|
3233
|
+
createPatentRenderHandler,
|
|
3234
|
+
exportPatentPng,
|
|
3235
|
+
llmModels,
|
|
3236
|
+
renderPng
|
|
3237
|
+
};
|
|
3238
|
+
//# sourceMappingURL=server.js.map
|