@things-factory/figure-service 10.1.283 → 10.1.287

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.
@@ -0,0 +1,11 @@
1
+ import type { FigureAITrace } from './figure-propose-steps.js';
2
+ /**
3
+ * Where each AI request's course is kept (ADR-0206): one JSON line per request, one file a day -- what the model was
4
+ * told (the guide's version), what it answered, what was refused and observed, what it decided and noted. Read to find
5
+ * where the guide or the observations fail the model; never read back by the application.
6
+ *
7
+ * FIGURE_AI_TRACE_DIR or config `figure/aiTraceDir` names the folder; `off` writes nothing. Default: logs/figure-ai
8
+ * under the server's working folder.
9
+ */
10
+ export declare function figureAITraceDir(): string | undefined;
11
+ export declare function writeFigureAITrace(record: FigureAITrace, dir?: string | undefined): void;
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.figureAITraceDir = figureAITraceDir;
4
+ exports.writeFigureAITrace = writeFigureAITrace;
5
+ const fs_1 = require("fs");
6
+ const path_1 = require("path");
7
+ const env_1 = require("@things-factory/env");
8
+ /**
9
+ * Where each AI request's course is kept (ADR-0206): one JSON line per request, one file a day -- what the model was
10
+ * told (the guide's version), what it answered, what was refused and observed, what it decided and noted. Read to find
11
+ * where the guide or the observations fail the model; never read back by the application.
12
+ *
13
+ * FIGURE_AI_TRACE_DIR or config `figure/aiTraceDir` names the folder; `off` writes nothing. Default: logs/figure-ai
14
+ * under the server's working folder.
15
+ */
16
+ function figureAITraceDir() {
17
+ const dir = process.env.FIGURE_AI_TRACE_DIR || env_1.config.get('figure/aiTraceDir', '') || (0, path_1.join)(process.cwd(), 'logs', 'figure-ai');
18
+ return dir === 'off' ? undefined : dir;
19
+ }
20
+ function writeFigureAITrace(record, dir = figureAITraceDir()) {
21
+ if (!dir)
22
+ return;
23
+ (0, fs_1.mkdirSync)(dir, { recursive: true });
24
+ (0, fs_1.appendFileSync)((0, path_1.join)(dir, `${record.at.slice(0, 10)}.jsonl`), JSON.stringify(record) + '\n');
25
+ }
26
+ //# sourceMappingURL=figure-ai-trace.js.map
@@ -20,6 +20,7 @@ const figure_namespace_js_1 = require("./figure-namespace.js");
20
20
  const figure_categories_js_1 = require("./figure-categories.js");
21
21
  const figure_format_js_2 = require("./figure-format.js");
22
22
  const figure_propose_steps_js_1 = require("./figure-propose-steps.js");
23
+ const figure_ai_trace_js_1 = require("./figure-ai-trace.js");
23
24
  const figure_write_js_1 = require("./figure-write.js");
24
25
  const figure_mesh_store_js_1 = require("./figure-mesh-store.js");
25
26
  const figure_glb_js_1 = require("./figure-glb.js");
@@ -481,6 +482,7 @@ let FigureMutation = class FigureMutation {
481
482
  }
482
483
  try {
483
484
  const result = await (0, figure_propose_steps_js_1.proposeFigureSteps)({
485
+ trace: figure_ai_trace_js_1.writeFigureAITrace,
484
486
  client: await (0, ai_client_base_1.aiClientFor)({ domain: context.state.domain, user: context.state.user }),
485
487
  prompt: request.prompt,
486
488
  base: request.base ? (0, figure_model_1.parseFigureAsset)(request.base) : undefined,
@@ -0,0 +1,12 @@
1
+ import type { FigureRelationCheck } from './figure-relation-checks.js';
2
+ /**
3
+ * Requests that need figure-model's principles applied, each with the relations that show whether they were
4
+ * (ADR-0206). A request is in a person's words and names the parts it is judged by; nothing in it says how to write
5
+ * the figure. A task is not a design to copy: it is a different case from any example the guide shows.
6
+ */
7
+ export interface FigurePrincipleTask {
8
+ id: string;
9
+ prompt: string;
10
+ checks: FigureRelationCheck[];
11
+ }
12
+ export declare const FIGURE_PRINCIPLE_TASKS: FigurePrincipleTask[];
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FIGURE_PRINCIPLE_TASKS = void 0;
4
+ /* The request says the cabinet is resized: a size change is applied where the cabinet's measure changes. */
5
+ const resized = [
6
+ { kind: 'size', axis: 'y', times: 0.6, resizes: 'cabinet' },
7
+ { kind: 'size', axis: 'y', times: 1.6, resizes: 'cabinet' },
8
+ { kind: 'size', axis: 'x', times: 1.5, resizes: 'cabinet' }
9
+ ];
10
+ const cabinetRelations = [
11
+ { says: 'the panel is on the front face', relation: { kind: 'distance', a: { part: 'panel', axis: 'z', side: 'min' }, b: { part: 'cabinet', axis: 'z', side: 'max' }, mm: 0 } },
12
+ { says: "the panel's top edge is 100 mm below the cabinet's top", relation: { kind: 'distance', a: { part: 'cabinet', axis: 'y', side: 'max' }, b: { part: 'panel', axis: 'y', side: 'max' }, mm: 100, within: 3 } },
13
+ { says: 'the panel is centred across', relation: { kind: 'distance', a: { part: 'panel', axis: 'x', side: 'centre' }, b: { part: 'cabinet', axis: 'x', side: 'centre' }, mm: 0, within: 3 } },
14
+ { says: 'the beacon stands on the top', relation: { kind: 'distance', a: { part: 'beacon', axis: 'y', side: 'min' }, b: { part: 'cabinet', axis: 'y', side: 'max' }, mm: 0 } },
15
+ { says: 'the beacon is over the top', relation: { kind: 'over', part: 'beacon', on: 'cabinet' } }
16
+ ];
17
+ exports.FIGURE_PRINCIPLE_TASKS = [
18
+ {
19
+ id: 'resize-keeps-relations',
20
+ prompt: "A cabinet that a board places at different sizes: the figure resizes where it is placed. Name its parts cabinet, panel and beacon. The cabinet is 600 mm wide, 1200 mm tall and 400 mm deep, standing on the floor. A control panel 300 x 200 x 20 mm is on its front face, centred across, with its top edge 100 mm below the top of the cabinet. A beacon, a cylinder 60 mm across and 120 mm tall, stands on the top of the cabinet. When the cabinet is resized, the panel stays on the front face with its top edge 100 mm below the cabinet's top, and the beacon stays standing on the top.",
21
+ checks: [
22
+ ...cabinetRelations.map(c => ({ ...c, principle: 'relation', under: [{ kind: 'as-made' }] })),
23
+ { principle: 'values', says: 'the cabinet grows with the figure', relation: { kind: 'grows-with-size', part: 'cabinet', axis: 'y' }, under: [...resized].filter(r => r.axis === 'y') },
24
+ { principle: 'values', says: 'the cabinet widens with the figure', relation: { kind: 'grows-with-size', part: 'cabinet', axis: 'x' }, under: [...resized].filter(r => r.axis === 'x') },
25
+ ...cabinetRelations.map(c => ({ ...c, says: `${c.says}, at every size`, principle: 'relation', under: [...resized], after: c.says }))
26
+ ]
27
+ },
28
+ {
29
+ id: 'motion-keeps-relations',
30
+ prompt: "A post 80 mm across and 1000 mm tall standing on the floor. On the top of the post, an arm 600 mm long, 60 mm wide and 40 mm thick, one end over the post, swings around the post's vertical axis from -90 to 90 degrees. A lamp 100 x 60 x 100 mm hangs under the far end of the arm, 30 mm below it. Name the parts post, arm and lamp. As the arm swings, the lamp stays under the far end of the arm, 30 mm below it.",
31
+ checks: [
32
+ { principle: 'state', says: "a control swings the arm 180 degrees about the post's axis", relation: { kind: 'turns-about', part: 'arm', pivot: 'post', degrees: 180, within: 10 }, under: [{ kind: 'controls' }] },
33
+ { principle: 'relation', says: 'the lamp hangs 30 mm below the arm, as it swings', relation: { kind: 'distance', a: { part: 'arm', axis: 'y', side: 'min' }, b: { part: 'lamp', axis: 'y', side: 'max' }, mm: 30, within: 3 }, under: [{ kind: 'controls' }] },
34
+ { principle: 'frames', says: "the arm swings about the post's axis with one end over it, the lamp under its far end", relation: { kind: 'at-far-end', part: 'lamp', end: 'arm', pivot: 'post', within: 120 }, under: [{ kind: 'controls' }] }
35
+ ]
36
+ }
37
+ ];
38
+ //# sourceMappingURL=figure-principle-tasks.js.map
@@ -1,7 +1,8 @@
1
1
  import { figureCostOf, figureScoreOf } from '@hatiolab/figure-model';
2
- import type { FigureAsset, FigureProposalStep } from '@hatiolab/figure-model';
2
+ import type { FigureAsset, FigureProposalFinding, FigureProposalStep } from '@hatiolab/figure-model';
3
3
  import { type AIClient } from '@things-factory/ai-client-base';
4
- import type { AIImageMediaType } from '@things-factory/ai-client-base';
4
+ import type { AIImageMediaType, AIMessage } from '@things-factory/ai-client-base';
5
+ import { type FigureRelationCheck, type FigureRelationVerdict } from './figure-relation-checks.js';
5
6
  import { type FigureReadRequest, type FigureView } from './figure-context.js';
6
7
  export interface ProposeFigureInput {
7
8
  /** The domain's AI agent that answers (aiClientFor). */
@@ -36,6 +37,93 @@ export interface ProposeFigureInput {
36
37
  * outline, may be changed.
37
38
  */
38
39
  read?: FigureReadRequest;
40
+ /** Handed the request's course once it ends, made or not: what was asked, answered, refused, observed and decided. */
41
+ trace?: (record: FigureAITrace) => void;
42
+ /**
43
+ * The relations the request asks for, written from it beforehand (figure-relation-checks.ts). When given, the figure is
44
+ * judged against them, and a relation it breaks is said back with the observations: what was asked, what it gives.
45
+ */
46
+ relations?: FigureRelationCheck[];
47
+ }
48
+ /** What the model decided on the observations it was shown. */
49
+ export interface FigureRefinement {
50
+ /** Whether observations were shown: none when the figure measured clean. */
51
+ asked: boolean;
52
+ decision?: 'kept' | 'revised' | 'revision-refused' | 'no-answer';
53
+ /** The model's reason, as it gave it. */
54
+ why?: string;
55
+ /** Where the guide or the observations were wrong, missing or misleading for this figure, as the model said it. */
56
+ note?: string;
57
+ /** Why a second answer was not taken, as the kernel and the gate said it. */
58
+ reasons?: string[];
59
+ /** Relations the request asks for that the first figure kept and the revised one broke. */
60
+ broke?: string[];
61
+ /** The revision taken was asked again after the kernel refused it once. */
62
+ recovered?: boolean;
63
+ /**
64
+ * How the request's relations ended, when it had any: met (kept without a revision), improved (a revision taken keeps
65
+ * them all), unresolved (one is broken or could not be judged on the figure returned), refused (the revision was refused
66
+ * and the figure before it returned). A kept answer never makes an unmet relation met.
67
+ */
68
+ outcome?: 'met' | 'improved' | 'unresolved' | 'refused';
69
+ /** The request's relations the figure returned does not keep: broken, or not confirmed (said with what could not be judged) -- never counted as met. */
70
+ unresolved?: string[];
71
+ }
72
+ /** One request's course, for finding where the guide or the observations fail the model. */
73
+ export interface FigureAITrace {
74
+ at: string;
75
+ /** The guide and grammar sent, by the first 12 hex digits of their SHA-1: which version the model read. */
76
+ guide: string;
77
+ /** The figure-model release whose guide, grammar, kernel and measures were used. */
78
+ figureModel: string;
79
+ prompt: string;
80
+ revising: boolean;
81
+ /** The draft revised, as its source: what the request started from, to make the course again. */
82
+ base?: string;
83
+ /** Every request to the model, the observations' one included. */
84
+ calls: number;
85
+ /** What each request used, in order, as the provider reported it: what a request costs, and which call cost it. */
86
+ usage: {
87
+ model: string;
88
+ input?: number;
89
+ cached?: number;
90
+ output?: number;
91
+ }[];
92
+ /**
93
+ * What each request was sent, in order, as it was passed to the model: the system prompt it was given, by the same
94
+ * hash as guide, and its messages -- the count, and those added since the request before. The messages of request n
95
+ * are the added of requests 1 to n, in order.
96
+ */
97
+ sent: {
98
+ system: string;
99
+ count: number;
100
+ added: AIMessage[];
101
+ }[];
102
+ attempts: {
103
+ answer: unknown;
104
+ reasons: string[];
105
+ }[];
106
+ observations: {
107
+ code: string;
108
+ severity: string;
109
+ at: string[];
110
+ message: string;
111
+ }[];
112
+ /** The request's relations judged on the first figure taken, when the request had them. */
113
+ relations?: FigureRelationVerdict[];
114
+ refinement: FigureRefinement;
115
+ /** The steps returned and what was measured on the figure they make, or why none were made. */
116
+ made?: {
117
+ steps: FigureProposalStep[];
118
+ observations: {
119
+ code: string;
120
+ severity: string;
121
+ at: string[];
122
+ message: string;
123
+ }[];
124
+ relations?: FigureRelationVerdict[];
125
+ };
126
+ failed?: string[];
39
127
  }
40
128
  export interface ProposeFigureResult {
41
129
  /** What the modeller applies, as one step of its history. */
@@ -44,7 +132,15 @@ export interface ProposeFigureResult {
44
132
  source: FigureAsset;
45
133
  score: ReturnType<typeof figureScoreOf>;
46
134
  cost: ReturnType<typeof figureCostOf>;
135
+ /** Answers asked for until one was taken (a refusal or broken JSON asks again), the observations' request not counted. */
47
136
  attempts: number;
137
+ /** Every request to the model, the observations' one included. */
138
+ calls?: number;
139
+ /** What was measured on the figure returned: observations, the model having seen them when `refinement.asked`. */
140
+ observations?: FigureProposalFinding[];
141
+ /** The request's relations judged on the figure returned, when the request had them. */
142
+ relations?: FigureRelationVerdict[];
143
+ refinement?: FigureRefinement;
48
144
  }
49
145
  /** Could not make it. Never an empty or half-made candidate. */
50
146
  export declare class ProposeFigureFailure extends Error {
@@ -66,14 +162,15 @@ export declare class ProposeFigureFailure extends Error {
66
162
  */
67
163
  export declare function proposalFailureForPerson(failure: ProposeFigureFailure, t: (key: string, params?: Record<string, unknown>) => string): string;
68
164
  /**
69
- * One whole answer the kernel and the gate take: a roller conveyor on two end supports. Three walks on :3300
70
- * (2026-10-16) stopped at three fastening rules in turn, each refusal saying what to do and none put right; one answer
71
- * shows them together -- the plane taken without facing, a part fastened under another, a row made once. Held to the
72
- * kernel by its test, on the path an answer takes.
165
+ * What the model is told before the task: the answer's form, then figure-model's own guide and grammar, both made from
166
+ * the kernel and held to it by its tests. Nothing here designs a thing for it.
73
167
  */
74
- export declare const WORKED_EXAMPLE: FigureProposalStep[];
75
- /** The rules and the words, all from figure-model's constants. */
76
168
  export declare function rulesPromptFigure(): string;
169
+ /**
170
+ * The observations on a figure the kernel and the gate took, said to the model once: what was measured, how, and that
171
+ * the model judges them -- keep, or answer again -- and may say where the guide or these observations failed it.
172
+ */
173
+ export declare function observationsPromptFigure(findings: readonly FigureProposalFinding[], source?: FigureAsset, relationsSaid?: string, broken?: boolean): string;
77
174
  /**
78
175
  * The request, and the open draft's source when revising -- or, too large for that, its outline and the parts read.
79
176
  * Of the draft, only what the view holds is written: the view was measured against the budget, and nothing of the
@@ -1,22 +1,30 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WORKED_EXAMPLE = exports.ProposeFigureFailure = void 0;
3
+ exports.ProposeFigureFailure = void 0;
4
4
  exports.proposalFailureForPerson = proposalFailureForPerson;
5
5
  exports.rulesPromptFigure = rulesPromptFigure;
6
+ exports.observationsPromptFigure = observationsPromptFigure;
6
7
  exports.taskPromptFigure = taskPromptFigure;
7
8
  exports.judgeFigureAnswer = judgeFigureAnswer;
8
9
  exports.proposeFigureSteps = proposeFigureSteps;
10
+ const crypto_1 = require("crypto");
9
11
  const figure_model_1 = require("@hatiolab/figure-model");
10
12
  const ai_client_base_1 = require("@things-factory/ai-client-base");
13
+ const figure_relation_checks_js_1 = require("./figure-relation-checks.js");
11
14
  const figure_context_js_1 = require("./figure-context.js");
12
15
  /**
13
16
  * An AI proposal for a figure is a list of the modeller's own commands (ADR-0094).
14
17
  *
15
- * The model is told the command grammar (figure-model's `FIGURE_PROPOSAL_GRAMMAR`, made from the kernel's constants) and
16
- * the open draft's source, and answers with steps. The steps are applied on a copy with `applyFigureProposal`; the
17
- * first step the kernel refuses, and any gate finding the steps brought in, go back to the model as reasons. After
18
- * three attempts the proposer says it could not make it. Nothing half made is returned, and nothing is saved: the
19
- * modeller applies the same steps through its session as one step of its history.
18
+ * The model is told how a figure is modelled (figure-model's `FIGURE_MODELLING_GUIDE`) and the command grammar
19
+ * (`FIGURE_PROPOSAL_GRAMMAR`), both made from the kernel, and the open draft's source; what the thing is and how it is
20
+ * built is its own knowledge. It answers with steps. The steps are applied on a copy with `applyFigureProposal`; the
21
+ * first step the kernel refuses, and any gate finding the steps brought in, go back to the model as reasons, three
22
+ * attempts at most.
23
+ *
24
+ * A list the kernel and the gate take is then measured (`figureProposalFindings`), and what was measured goes back to
25
+ * the model once as observations, not orders: it keeps the figure, or answers it again. A second answer that is not
26
+ * taken loses nothing -- the first one is returned. Nothing half made is returned, and nothing is saved: the modeller
27
+ * applies the same steps through its session as one step of its history. Each request's course is handed to `trace`.
20
28
  */
21
29
  /** How many times the model is asked. More rarely helps: it tends to stop at the same place. */
22
30
  const MAX_ATTEMPTS = 3;
@@ -46,52 +54,77 @@ function proposalFailureForPerson(failure, t) {
46
54
  return [t('error.figure-proposal-failed', { defaultValue: failure.message }), ...failure.reasons].join('\n');
47
55
  }
48
56
  /**
49
- * One whole answer the kernel and the gate take: a roller conveyor on two end supports. Three walks on :3300
50
- * (2026-10-16) stopped at three fastening rules in turn, each refusal saying what to do and none put right; one answer
51
- * shows them together -- the plane taken without facing, a part fastened under another, a row made once. Held to the
52
- * kernel by its test, on the path an answer takes.
57
+ * What the model is told before the task: the answer's form, then figure-model's own guide and grammar, both made from
58
+ * the kernel and held to it by its tests. Nothing here designs a thing for it.
53
59
  */
54
- exports.WORKED_EXAMPLE = [
55
- { kind: 'add-part', part: { id: 'frame', kind: 'box', dimensions: { width: 2000, height: 100, depth: 600 } } },
56
- { kind: 'attach', part: 'frame', to: { plane: 'mounting-plane' }, gap: 700 },
57
- { kind: 'add-part', part: { id: 'support', kind: 'box', dimensions: { width: 80, height: 700, depth: 560 } } },
58
- { kind: 'attach', part: 'support', to: { part: 'frame', face: 'bottom' }, align: { x: 'min' } },
59
- { kind: 'make-repeat', part: 'support', axis: 'x', pitch: 1920, count: 2 },
60
- { kind: 'add-part', part: { id: 'roller', kind: 'box', dimensions: { width: 60, height: 60, depth: 560 } } },
61
- { kind: 'attach', part: 'roller', to: { part: 'frame', face: 'top' } },
62
- { kind: 'make-repeat', part: 'roller', axis: 'x', pitch: 160 },
63
- { kind: 'set-material', target: 'frame', material: { token: 'palette.frame' }, palette: { 'palette.frame': '#5b6770' } }
64
- ];
65
- /** The rules and the words, all from figure-model's constants. */
66
60
  function rulesPromptFigure() {
67
61
  return [
68
62
  'You author a 3D figure for a factory digital twin by writing the commands a person gives in the figure modeller.',
63
+ 'What the thing is, how it looks and how it moves is your own knowledge; how it is said in this modeller is below.',
69
64
  'Answer with ONE JSON object only: { "steps": [ ...commands in order... ] }. No prose, no code fences.',
70
- '',
71
- 'Space: millimetres; Y is up; the figure stands on its mounting plane. Angles are degrees.',
72
- 'A part is made at the origin and placed by fastening one of its faces to a face of another part or to the mounting',
73
- 'plane. Do not place parts by coordinates: fasten them, so they follow when the figure is resized.',
74
- 'Fasten each part once, and fasten only to the mounting plane or to a part an earlier step added; to move a part',
75
- 'already fastened, attach it again with replace: true.',
76
- 'Several of the same part in a row (rollers, legs, slats) are one part and make-repeat, not a part added and fastened',
77
- 'for each: the row follows the figure when it is resized, and the answer stays short.',
78
- 'A part is named by its id; use lowercase words joined by hyphens. Name only parts that exist or that an earlier step adds.',
79
- 'A colour is a palette token. A token the figure does not have yet is given with its colour on the same command:',
80
- '{ kind: "set-material", target, material: { token }, palette: { [token]: "#rrggbb" } }.',
81
- 'When the request says a measure is the same as, matches or follows another part or the figure, write link-dimension:',
82
- 'a copied number stays the same when the other one is resized.',
83
- 'Declare the sizes the figure may be placed at before any measure follows the figure.',
84
65
  'When revising, write only the commands the request needs. Everything not touched stays as it is.',
85
66
  '',
86
- 'The commands (shape, then what it means):',
87
- ...figure_model_1.FIGURE_PROPOSAL_GRAMMAR.map(word => `- ${word.shape}\n ${word.means}`),
67
+ figure_model_1.FIGURE_MODELLING_GUIDE,
88
68
  '',
89
- 'One whole answer the modeller takes, for a new roller conveyor -- an example of the form, not of the figure asked for:',
90
- 'the frame stands 700 mm up on the mounting plane, a support is fastened under it at one end and repeated to two, a',
91
- 'roller is fastened on top and repeated along it.',
92
- JSON.stringify({ steps: exports.WORKED_EXAMPLE })
69
+ 'THE COMMANDS (shape, then what it means):',
70
+ ...figure_model_1.FIGURE_PROPOSAL_GRAMMAR.map(word => `- ${word.shape}\n ${word.means}`)
93
71
  ].join('\n');
94
72
  }
73
+ /**
74
+ * The observations on a figure the kernel and the gate took, said to the model once: what was measured, how, and that
75
+ * the model judges them -- keep, or answer again -- and may say where the guide or these observations failed it.
76
+ */
77
+ function observationsPromptFigure(findings, source, relationsSaid, broken = false) {
78
+ /* The fastening that made what was measured, beside each part it names: what to look at again is the relation. */
79
+ const joints = (source?.joints ?? []);
80
+ const fastening = (part) => {
81
+ const j = joints.find(x => x?.body1?.part === part && x?.body0);
82
+ if (!j)
83
+ return undefined;
84
+ const o = j.origin ?? {};
85
+ const on = j.body0.plane ? 'the mounting plane' : `${j.body0.part}'s ${j.body0.face ?? 'curved side'}`;
86
+ const terms = [o.align ? `align ${JSON.stringify(o.align)}` : undefined, o.facing ? `facing ${o.facing}` : undefined, o.gap ? `gap ${o.gap} mm` : undefined, j.motion?.length ? 'moving by a joint' : undefined].filter(Boolean);
87
+ return `${part} is fastened to ${on}${terms.length ? ` (${terms.join(', ')})` : ''}`;
88
+ };
89
+ const relations = (f) => [...new Set(f.at.map(fastening).filter((x) => !!x))];
90
+ return [
91
+ ...(relationsSaid ? [relationsSaid, ''] : []),
92
+ ...(findings.length ? ['The kernel took these steps. The figure they make was then measured on boxes along the figure\'s axes, at rest and across each control\'s range. The measures are approximate and do not know what you meant. Observed:'] : []),
93
+ ...findings.map(f => {
94
+ const by = relations(f);
95
+ return `- ${f.code} at ${f.at.join(', ')} (${f.severity === 'fix' ? 'measured as likely wrong' : 'may well be meant'}): ${f.message}${by.length ? `. As fastened: ${by.join('; ')}.` : ''}`;
96
+ }),
97
+ ...(findings.length ? ['These are observations, not orders. Each comes from the relations it names: look again at those, against the request and what you meant. Where one suggests a fix, that is one way, not the only one.'] : []),
98
+ /*
99
+ keep is for a figure that breaks none of the request's relations: a relation the request states is met or it is
100
+ not, whatever was meant. The observations alone may be kept against what was meant.
101
+ */
102
+ ...(broken
103
+ ? [
104
+ 'keep is only for a figure that breaks no relation the request states. One above is broken, so answer { "steps": [ ... ], "why": "..." } with the whole list of steps from the start, as before. If you cannot meet it, say why in "why".'
105
+ ]
106
+ : [
107
+ 'If the figure is as you meant it, answer { "keep": true, "why": "..." }.',
108
+ 'If it should change, answer { "steps": [ ... ], "why": "..." } with the whole list of steps from the start, as before.'
109
+ ]),
110
+ 'Either way you may add "note": anything in the guide or in these observations that was wrong, missing or misleading for this figure.'
111
+ ].join('\n');
112
+ }
113
+ /** What a refused answer is told, before its reasons: the same for a first answer and for a revision. */
114
+ const REFUSED_SAY = 'That was rejected; nothing of it was kept. Fix these and answer again with the whole list of steps:';
115
+ /** A revision refused is asked again this many times at most; the figure taken before it is kept meanwhile. */
116
+ const MAX_REVISION_RECOVERIES = 1;
117
+ /** The figure-model release in use, read from its own package: the guide, grammar and measures are its. */
118
+ const FIGURE_MODEL_VERSION = (() => {
119
+ try {
120
+ return require('@hatiolab/figure-model/package.json').version;
121
+ }
122
+ catch {
123
+ return 'unknown';
124
+ }
125
+ })();
126
+ const findingLine = (f) => ({ code: f.code, severity: f.severity, at: [...f.at], message: f.message });
127
+ const text = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
95
128
  /** What of the draft being revised the writer is shown: whole when it fits, else its outline and the parts read. */
96
129
  function viewFor(input) {
97
130
  if (!input.base)
@@ -247,10 +280,37 @@ async function proposeFigureSteps(input) {
247
280
  const { client } = input;
248
281
  const base = input.base ?? (0, figure_model_1.createFigureAsset)(input.name ?? 'Figure');
249
282
  const view = viewFor(input);
250
- /* Parts asked for and not shown: said before the writer is asked, so the asker reads fewer or names them right. */
251
- if (view?.notRead?.length)
252
- throw new ProposeFigureFailure('What was asked for cannot be shown.', view.notRead.map(one => one.reason), 0);
253
283
  const system = rulesPromptFigure();
284
+ const hashOf = (said) => (0, crypto_1.createHash)('sha1').update(said).digest('hex').slice(0, 12);
285
+ const record = {
286
+ at: new Date().toISOString(),
287
+ guide: hashOf(system),
288
+ figureModel: FIGURE_MODEL_VERSION,
289
+ prompt: input.prompt,
290
+ revising: !!input.base,
291
+ ...(input.base ? { base: (0, figure_model_1.serializeFigureAsset)(input.base) } : {}),
292
+ calls: 0,
293
+ usage: [],
294
+ sent: [],
295
+ attempts: [],
296
+ observations: [],
297
+ refinement: { asked: false }
298
+ };
299
+ const metered = { systemPrompt: system, maxTokens: GENERATE_MAX_TOKENS, onUsage: (used) => record.usage.push({ model: used.model, input: used.inputTokens, cached: used.cacheReadTokens, output: used.outputTokens }) };
300
+ const told = (r) => {
301
+ try {
302
+ input.trace?.(r);
303
+ }
304
+ catch {
305
+ /* A record that cannot be written does not cost the person the figure. */
306
+ }
307
+ };
308
+ /* Parts asked for and not shown: said before the writer is asked, so the asker reads fewer or names them right. */
309
+ if (view?.notRead?.length) {
310
+ const failure = new ProposeFigureFailure('What was asked for cannot be shown.', view.notRead.map(one => one.reason), 0);
311
+ told({ ...record, failed: failure.reasons });
312
+ throw failure;
313
+ }
254
314
  const task = taskPromptFigure(input, view);
255
315
  const messages = [
256
316
  {
@@ -263,12 +323,36 @@ async function proposeFigureSteps(input) {
263
323
  : task
264
324
  }
265
325
  ];
326
+ /* Every request to the model goes here: what is passed is what is recorded, at the moment it is passed. */
327
+ let recordedUpTo = 0;
328
+ const ask = () => {
329
+ record.calls++;
330
+ record.sent.push({ system: hashOf(metered.systemPrompt), count: messages.length, added: structuredClone(messages.slice(recordedUpTo)) });
331
+ recordedUpTo = messages.length;
332
+ return client.generateJSON(messages, metered);
333
+ };
334
+ /* The figure returned, measured; the course handed to trace. */
335
+ const done = (made, attempts, refinement) => {
336
+ const observations = (0, figure_model_1.figureProposalFindings)(input.base, made.source);
337
+ const relations = input.relations ? (0, figure_relation_checks_js_1.figureRelationVerdicts)(made.source, input.relations) : undefined;
338
+ const broke = refinement.decision === 'revised' && record.relations && relations ? (0, figure_relation_checks_js_1.figureRelationsBrokenBy)(record.relations, relations) : [];
339
+ if (broke.length)
340
+ refinement = { ...refinement, broke };
341
+ if (relations) {
342
+ /* Broken, or not confirmed with what could not be judged: either way not met, and said which. */
343
+ const unresolved = relations.filter(v => v.verdict !== 'kept').map(v => (v.verdict === 'cannot' ? `${v.says} (not confirmed: ${v.because})` : v.says));
344
+ const outcome = refinement.decision === 'revision-refused' ? 'refused' : unresolved.length ? 'unresolved' : refinement.decision === 'revised' ? 'improved' : 'met';
345
+ refinement = { ...refinement, outcome, ...(unresolved.length ? { unresolved } : {}) };
346
+ }
347
+ told({ ...record, refinement, made: { steps: made.steps, observations: observations.map(findingLine), ...(relations ? { relations } : {}) } });
348
+ return { steps: made.steps, source: made.source, score: (0, figure_model_1.figureScoreOf)(made.source), cost: (0, figure_model_1.figureCostOf)(made.source), attempts, calls: record.calls, observations, ...(relations ? { relations } : {}), refinement };
349
+ };
266
350
  let reasons = [];
267
351
  let refused;
268
352
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
269
353
  let answer;
270
354
  try {
271
- answer = await client.generateJSON(messages, { systemPrompt: system, maxTokens: GENERATE_MAX_TOKENS });
355
+ answer = await ask();
272
356
  }
273
357
  catch (e) {
274
358
  /*
@@ -276,29 +360,78 @@ async function proposeFigureSteps(input) {
276
360
  key, a rate limit, a dropped connection -- goes up as it failed: asked again it fails again, and said as "not
277
361
  valid JSON" it names a cause it did not have.
278
362
  */
279
- if (!(e instanceof ai_client_base_1.AIAnswerNotJSON))
363
+ if (!(e instanceof ai_client_base_1.AIAnswerNotJSON)) {
364
+ told({ ...record, failed: [String(e?.message ?? e)] });
280
365
  throw e;
366
+ }
281
367
  reasons = [
282
368
  e.cutShort
283
369
  ? `The answer was cut off at the output limit (${GENERATE_MAX_TOKENS} tokens) before the JSON ended. Write fewer commands: repeat a part with make-repeat instead of adding each copy, and write only what the request needs.`
284
370
  : `The answer was not valid JSON: ${e.message}`
285
371
  ];
372
+ record.attempts.push({ answer: undefined, reasons });
286
373
  messages.push({ role: 'user', content: ['That was rejected. Answer with the JSON object only:', ...reasons].join('\n') });
287
374
  continue;
288
375
  }
289
376
  const judged = judgeFigureAnswer(base, answer, !!input.base, view);
377
+ record.attempts.push({ answer, reasons: judged.reasons });
290
378
  if (judged.source) {
291
- return { steps: judged.steps, source: judged.source, score: (0, figure_model_1.figureScoreOf)(judged.source), cost: (0, figure_model_1.figureCostOf)(judged.source), attempts: attempt };
379
+ const candidate = { steps: judged.steps, source: judged.source };
380
+ const findings = (0, figure_model_1.figureProposalFindings)(input.base, candidate.source);
381
+ const relationVerdicts = input.relations ? (0, figure_relation_checks_js_1.figureRelationVerdicts)(candidate.source, input.relations) : undefined;
382
+ if (relationVerdicts)
383
+ record.relations = relationVerdicts;
384
+ const relationsSaid = relationVerdicts ? (0, figure_relation_checks_js_1.figureRelationFeedback)(relationVerdicts) : undefined;
385
+ /*
386
+ A revision is asked for a request relation broken, or for observations. A relation only not judged is no reason to
387
+ change the figure: it is returned unresolved, with what could not be judged.
388
+ */
389
+ const broken = !!relationVerdicts?.some(v => v.verdict === 'broken');
390
+ if (!findings.length && !broken)
391
+ return done(candidate, attempt, { asked: false });
392
+ /* Once: the model sees what was measured and keeps the figure or answers again. A second answer not taken loses nothing. */
393
+ record.observations = findings.map(findingLine);
394
+ messages.push({ role: 'assistant', content: JSON.stringify(answer) });
395
+ messages.push({ role: 'user', content: observationsPromptFigure(findings, candidate.source, relationsSaid, broken) });
396
+ let reply;
397
+ try {
398
+ reply = await ask();
399
+ }
400
+ catch (e) {
401
+ return done(candidate, attempt, { asked: true, decision: 'no-answer', reasons: [String(e?.message ?? e)] });
402
+ }
403
+ /*
404
+ A revision the kernel refuses goes back with its reasons, as a first answer refused does -- once more at most. The
405
+ figure taken stays the candidate until a revision is taken.
406
+ */
407
+ for (let recovery = 0;; recovery++) {
408
+ const why = text(reply?.why);
409
+ const note = text(reply?.note);
410
+ if (reply?.keep === true)
411
+ return done(candidate, attempt, { asked: true, decision: 'kept', why, note });
412
+ const again = judgeFigureAnswer(base, reply, !!input.base, view);
413
+ record.attempts.push({ answer: reply, reasons: again.reasons });
414
+ if (again.source)
415
+ return done({ steps: again.steps, source: again.source }, attempt, { asked: true, decision: 'revised', why, note, ...(recovery ? { recovered: true } : {}) });
416
+ if (recovery >= MAX_REVISION_RECOVERIES)
417
+ return done(candidate, attempt, { asked: true, decision: 'revision-refused', why, note, reasons: again.reasons });
418
+ messages.push({ role: 'assistant', content: JSON.stringify(reply) });
419
+ messages.push({ role: 'user', content: [REFUSED_SAY, ...again.reasons].join('\n') });
420
+ try {
421
+ reply = await ask();
422
+ }
423
+ catch (e) {
424
+ return done(candidate, attempt, { asked: true, decision: 'no-answer', reasons: [String(e?.message ?? e)] });
425
+ }
426
+ }
292
427
  }
293
428
  reasons = judged.reasons;
294
429
  refused = answer;
295
430
  // The reasons go back as they were said; a summary would not tell the model which step to change.
296
431
  messages.push({ role: 'assistant', content: JSON.stringify(answer) });
297
- messages.push({
298
- role: 'user',
299
- content: ['That was rejected; nothing of it was kept. Fix these and answer again with the whole list of steps:', ...reasons].join('\n')
300
- });
432
+ messages.push({ role: 'user', content: [REFUSED_SAY, ...reasons].join('\n') });
301
433
  }
434
+ told({ ...record, failed: reasons });
302
435
  throw new ProposeFigureFailure('The figure could not be made.', reasons, MAX_ATTEMPTS, refused);
303
436
  }
304
437
  //# sourceMappingURL=figure-propose-steps.js.map
@@ -0,0 +1,158 @@
1
+ import type { FigureAsset } from '@hatiolab/figure-model';
2
+ /**
3
+ * Whether a figure keeps the relations a request asks for (ADR-0206).
4
+ *
5
+ * The relations are written from the request before any answer is seen: the parts, the relation expected, how close is
6
+ * close enough, and the changes it must hold under -- the figure's size, a control across its range -- and nothing the
7
+ * request does not ask. The principle a relation exercises is a label for reading the results, not a verdict on the
8
+ * model's understanding. The figure is evaluated under each change and every relation is
9
+ * measured there. A number right only at the size the figure was made at does not pass a relation that must hold as the
10
+ * size changes. How the figure was written -- which commands, in which order -- is never judged: any definition the
11
+ * kernel takes and that keeps the relations passes.
12
+ *
13
+ * The same verdicts can be said to the model that made the figure: which relation broke, under which change.
14
+ */
15
+ export type FigurePrinciple = 'relation' | 'frames' | 'values' | 'state' | 'composition';
16
+ type Axis = 'x' | 'y' | 'z';
17
+ type Side = 'min' | 'max' | 'centre';
18
+ /** A coordinate of a part's box: its min or max edge, or its centre, along an axis of the figure. */
19
+ export interface FigureEdge {
20
+ part: string;
21
+ axis: Axis;
22
+ side: Side;
23
+ }
24
+ export type FigureRelation =
25
+ /** a − b, in mm, is `mm` (within `within`). */
26
+ {
27
+ kind: 'distance';
28
+ a: FigureEdge;
29
+ b: FigureEdge;
30
+ mm: number;
31
+ within?: number;
32
+ }
33
+ /** The part's centre lies over the other part's footprint, across X and Z. */
34
+ | {
35
+ kind: 'over';
36
+ part: string;
37
+ on: string;
38
+ }
39
+ /** The part hangs near the end of `end` farthest from `pivot`'s vertical axis, and in the direction `end` points from it. */
40
+ | {
41
+ kind: 'at-far-end';
42
+ part: string;
43
+ end: string;
44
+ pivot: string;
45
+ within: number;
46
+ }
47
+ /**
48
+ * One control turns the part about the pivot's vertical axis through at least `degrees` across its range, the part's
49
+ * reach from that axis staying the same: the part itself moves, about that axis.
50
+ */
51
+ | {
52
+ kind: 'turns-about';
53
+ part: string;
54
+ pivot: string;
55
+ degrees: number;
56
+ within: number;
57
+ }
58
+ /** The part's extent along the axis grows and shrinks with the figure's size along it, from what it was as made. */
59
+ | {
60
+ kind: 'grows-with-size';
61
+ part: string;
62
+ axis: Axis;
63
+ };
64
+ /** What the figure is changed by before the relations are measured. */
65
+ export type FigureChange = {
66
+ kind: 'as-made';
67
+ }
68
+ /**
69
+ * The figure's size along an axis, times this. Needs a figure that resizes where it is placed. resizes: the part the
70
+ * request says is resized -- the change is applied where that part's measure along the axis changes; without it,
71
+ * where anything in the figure changes.
72
+ */
73
+ | {
74
+ kind: 'size';
75
+ axis: Axis;
76
+ times: number;
77
+ resizes?: string;
78
+ }
79
+ /** Every control with a range, at 0, 25, 50, 75 and 100 % of it. Needs a control. */
80
+ | {
81
+ kind: 'controls';
82
+ };
83
+ export interface FigureRelationCheck {
84
+ /** The principle this relation exercises: a label for reading results, never a verdict on the model. */
85
+ principle: FigurePrinciple;
86
+ /** What is asked, in the request's terms. */
87
+ says: string;
88
+ relation: FigureRelation;
89
+ under: FigureChange[];
90
+ /** Another check (by its says) this one is judged only after: while that one is not kept, this one cannot be judged. */
91
+ after?: string;
92
+ }
93
+ export interface FigureRelationVerdict {
94
+ principle: FigurePrinciple;
95
+ says: string;
96
+ /** kept: held under every change. broken: did not hold under one. cannot: could not be judged -- the change could not be made or was not applied, a part is missing, or a check it comes after is not kept. */
97
+ verdict: 'kept' | 'broken' | 'cannot';
98
+ /** Where it broke or why it could not be judged, said with the change. */
99
+ because?: string;
100
+ /** For a broken relation: what was asked, what was measured, and under which change -- the difference, no remedy. */
101
+ measured?: {
102
+ change: string;
103
+ asked: string;
104
+ got: string;
105
+ between?: string;
106
+ };
107
+ /** The definitions of the parts named, as fastened: evidence to read, not a cause. */
108
+ definition?: string[];
109
+ /** A cause the definition gives grounds for, said as a candidate. */
110
+ cause?: string;
111
+ /** For a turn: the axis asked, the axis the figure turns about, and the joint origin it is measured from, in one frame. */
112
+ axis?: FigureAxisReport;
113
+ /** For a kept relation: what it measures now -- the value a change made for another relation must keep. */
114
+ now?: string;
115
+ }
116
+ type Vec = [number, number, number];
117
+ /** The one frame an axis report is said in: the figure's own. */
118
+ export declare const FIGURE_FRAME = "the figure frame: origin at the figure's origin on its mounting plane, X right, Y up, Z front";
119
+ /**
120
+ * Where a part was asked to turn about, where it turns about, and the joint origin its joint is written from -- all in the
121
+ * figure frame, each line as a direction and the point on it nearest the joint origin. What cannot be read from the
122
+ * figure is left out and named in `unknown`, never guessed.
123
+ */
124
+ export interface FigureAxisReport {
125
+ frame: string;
126
+ asked: {
127
+ direction: Vec;
128
+ through: Vec;
129
+ says: string;
130
+ };
131
+ actual?: {
132
+ direction: Vec;
133
+ through: Vec;
134
+ control: string;
135
+ };
136
+ jointOrigin?: {
137
+ joint: string;
138
+ at: Vec;
139
+ axes: {
140
+ x: Vec;
141
+ y: Vec;
142
+ z: Vec;
143
+ };
144
+ };
145
+ unknown?: string[];
146
+ }
147
+ /** Every check, its verdict. A check that cannot be evaluated under a change, or comes after one not kept, is `cannot`, said why. */
148
+ export declare function figureRelationVerdicts(asset: FigureAsset, checks: readonly FigureRelationCheck[]): FigureRelationVerdict[];
149
+ /**
150
+ * The broken relations said to the model: what was asked, what the figure gives, under which change, and the relation to
151
+ * look at again. No remedy is named: how to keep the relation is the model's to decide.
152
+ */
153
+ export declare function figureRelationFeedback(verdicts: readonly FigureRelationVerdict[]): string | undefined;
154
+ /** The relations a revision broke: kept on the figure before it, broken on the figure after. */
155
+ export declare function figureRelationsBrokenBy(before: readonly FigureRelationVerdict[], after: readonly FigureRelationVerdict[]): string[];
156
+ /** The verdicts by principle: a principle is kept when every one of its checks is. */
157
+ export declare function figurePrincipleVerdicts(verdicts: readonly FigureRelationVerdict[]): Partial<Record<FigurePrinciple, 'kept' | 'broken' | 'cannot'>>;
158
+ export {};
@@ -0,0 +1,374 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FIGURE_FRAME = void 0;
4
+ exports.figureRelationVerdicts = figureRelationVerdicts;
5
+ exports.figureRelationFeedback = figureRelationFeedback;
6
+ exports.figureRelationsBrokenBy = figureRelationsBrokenBy;
7
+ exports.figurePrincipleVerdicts = figurePrincipleVerdicts;
8
+ const figure_model_1 = require("@hatiolab/figure-model");
9
+ /** The one frame an axis report is said in: the figure's own. */
10
+ exports.FIGURE_FRAME = "the figure frame: origin at the figure's origin on its mounting plane, X right, Y up, Z front";
11
+ const edge = (b, axis, side) => (side === 'centre' ? b.centre[axis] : b.centre[axis] + (side === 'max' ? 1 : -1) * (b.extent[axis] / 2));
12
+ const round = (n) => Math.round(n * 10) / 10;
13
+ function boxesUnder(asset, design, state) {
14
+ const sized = { ...asset, designInputs: { ...asset.designInputs, ...design } };
15
+ const geometry = (0, figure_model_1.compileFigureAsset)(sized).evaluate(state).geometry;
16
+ return new Map((0, figure_model_1.figureOccupiedBoxesOf)(geometry, (0, figure_model_1.figureWritersOf)(sized)).map(b => [b.part, b]));
17
+ }
18
+ /**
19
+ * Why a size change was not applied, or undefined when it was: the part the request says is resized keeps its measure
20
+ * along the axis, or, with none named, every part is where and as large as it was as made (to half a millimetre).
21
+ */
22
+ function notApplied(change, boxes, asMade) {
23
+ const same = (b, m, axes, where) => !!b && !!m && axes.every(k => Math.abs(b.extent[k] - m.extent[k]) <= 0.5 && (!where || Math.abs(b.centre[k] - m.centre[k]) <= 0.5));
24
+ if (change.resizes) {
25
+ const [b, m] = [boxes.get(change.resizes), asMade.get(change.resizes)];
26
+ return same(b, m, [change.axis], false) ? `${change.resizes} is ${round(b.extent[change.axis])} mm along ${change.axis}, as made: the size change is not applied` : undefined;
27
+ }
28
+ return [...asMade].every(([part, m]) => same(boxes.get(part), m, ['x', 'y', 'z'], true)) ? 'nothing in the figure changes: the size change is not applied' : undefined;
29
+ }
30
+ /** Each concrete case a change stands for, labelled as it is said back. */
31
+ function casesOf(asset, change) {
32
+ if (change.kind === 'as-made')
33
+ return [{ label: 'as made', design: {}, state: {}, scale: 1 }];
34
+ if (change.kind === 'size') {
35
+ const key = `size.${change.axis}`;
36
+ const now = asset.designInputs?.[key];
37
+ if (typeof now !== 'number')
38
+ return 'the figure does not resize where it is placed';
39
+ return [{ label: `size ${change.axis} x${change.times}`, design: { [key]: now * change.times }, state: {}, scale: change.times }];
40
+ }
41
+ const controls = asset.document.model.inputs.filter(i => i.role === 'state' && Number.isFinite(i.min) && Number.isFinite(i.max) && i.max > i.min);
42
+ if (!controls.length)
43
+ return 'no control with a range';
44
+ return controls.flatMap(c => [0, 0.25, 0.5, 0.75, 1].map(f => {
45
+ const v = c.min + (c.max - c.min) * f;
46
+ return { label: `${c.id} = ${round(v)}`, design: {}, state: { [c.id]: v }, scale: 1 };
47
+ }));
48
+ }
49
+ /** The relation measured on one evaluation: undefined when it holds, else what is off. */
50
+ function offBy(boxes, relation, asMade, scale) {
51
+ const get = (part) => boxes.get(part);
52
+ if (relation.kind === 'grows-with-size') {
53
+ const [now, then] = [get(relation.part), asMade.get(relation.part)];
54
+ if (!now || !then)
55
+ return `no part ${relation.part}`;
56
+ const want = then.extent[relation.axis] * scale;
57
+ return Math.abs(now.extent[relation.axis] - want) <= 1 ? undefined : `${relation.part} is ${round(now.extent[relation.axis])} mm along ${relation.axis}, ${round(want)} if it grew with the figure`;
58
+ }
59
+ if (relation.kind === 'distance') {
60
+ const [a, b] = [get(relation.a.part), get(relation.b.part)];
61
+ if (!a || !b)
62
+ return `no part ${!a ? relation.a.part : relation.b.part}`;
63
+ const d = edge(a, relation.a.axis, relation.a.side) - edge(b, relation.b.axis, relation.b.side);
64
+ return Math.abs(d - relation.mm) <= (relation.within ?? 2) ? undefined : `${round(d)} mm, ${relation.mm} mm asked`;
65
+ }
66
+ if (relation.kind === 'over') {
67
+ const [p, on] = [get(relation.part), get(relation.on)];
68
+ if (!p || !on)
69
+ return `no part ${!p ? relation.part : relation.on}`;
70
+ const inside = ['x', 'z'].every(k => p.centre[k] >= edge(on, k, 'min') - 0.5 && p.centre[k] <= edge(on, k, 'max') + 0.5);
71
+ return inside ? undefined : `${relation.part} is not over ${relation.on}`;
72
+ }
73
+ if (relation.kind === 'turns-about')
74
+ return undefined;
75
+ const [p, end, pivot] = [get(relation.part), get(relation.end), get(relation.pivot)];
76
+ if (!p || !end || !pivot)
77
+ return `no part ${[relation.part, relation.end, relation.pivot].find(n => !get(n))}`;
78
+ const corners = [['min', 'min'], ['min', 'max'], ['max', 'min'], ['max', 'max']].map(([sx, sz]) => [edge(end, 'x', sx) - pivot.centre.x, edge(end, 'z', sz) - pivot.centre.z]);
79
+ const far = corners.reduce((a, c) => (Math.hypot(c[0], c[1]) > Math.hypot(a[0], a[1]) ? c : a));
80
+ const reach = Math.hypot(far[0], far[1]);
81
+ const [ex, ez] = [end.centre.x - pivot.centre.x, end.centre.z - pivot.centre.z];
82
+ const [px, pz] = [p.centre.x - pivot.centre.x, p.centre.z - pivot.centre.z];
83
+ if (Math.hypot(ex, ez) < 0.25 * reach)
84
+ return `${relation.end} is centred over ${relation.pivot}, not one end over it`;
85
+ const out = Math.hypot(px, pz);
86
+ if (out < reach - relation.within)
87
+ return `${relation.part} is ${round(out)} mm out from ${relation.pivot}; ${relation.end} reaches ${round(reach)}`;
88
+ if (out > reach + relation.within)
89
+ return `${relation.part} is ${round(out)} mm out from ${relation.pivot}, beyond the end of ${relation.end} at ${round(reach)}`;
90
+ const angle = (Math.abs(Math.atan2(ex * pz - ez * px, ex * px + ez * pz)) * 180) / Math.PI;
91
+ return angle > 10 ? `${relation.part} is ${round(angle)} degrees off the way ${relation.end} points` : undefined;
92
+ }
93
+ /** A distance as it is measured: each edge where it is in the figure's frame, the one less the other. */
94
+ function betweenOf(boxes, r) {
95
+ const [a, b] = [boxes.get(r.a.part), boxes.get(r.b.part)];
96
+ if (!a || !b)
97
+ return undefined;
98
+ const name = (e) => `${e.part}'s ${e.axis} ${e.side}`;
99
+ return `${name(r.a)} at ${round(edge(a, r.a.axis, r.a.side))} less ${name(r.b)} at ${round(edge(b, r.b.axis, r.b.side))}, in the figure's frame`;
100
+ }
101
+ /** How each part named is fastened, as written: what a reader looks at to find why a relation moved. */
102
+ function definitionsOf(asset, parts) {
103
+ const joints = (asset.joints ?? []);
104
+ return parts.flatMap(part => {
105
+ const j = joints.find(x => x?.body1?.part === part && x?.body0);
106
+ if (!j)
107
+ return [`${part}: no fastening record`];
108
+ const o = j.origin ?? {};
109
+ const on = j.body0.plane ? 'the mounting plane' : `${j.body0.part}'s ${j.body0.face ?? 'curved side'}`;
110
+ return [`${part} is fastened to ${on}${o.align ? `, align ${JSON.stringify(o.align)}` : ''}${o.facing ? `, facing ${o.facing}` : ''}${o.gap ? `, gap ${JSON.stringify(o.gap)}` : ''}${j.motion?.length ? ', moving by a joint' : ''}`];
111
+ });
112
+ }
113
+ const partsOf = (r) => r.kind === 'distance' ? [...new Set([r.a.part, r.b.part])] : r.kind === 'over' ? [r.part, r.on] : r.kind === 'at-far-end' ? [r.part, r.end, r.pivot] : r.kind === 'turns-about' ? [r.part, r.pivot] : [r.part];
114
+ /** A cause the definition grounds: a relation that holds as made and moves with the size, where a fastening term is a plain number. */
115
+ function causeOf(check, change, definition) {
116
+ if (!change.startsWith('size'))
117
+ return undefined;
118
+ const fixed = definition.filter(d => /align \{[^}]*"(x|y|z)":\{"mm":-?\d/.test(d) || /gap -?\d/.test(d));
119
+ return fixed.length ? `a fastening term written as a number stays that number as the size changes: ${fixed.join('; ')}` : undefined;
120
+ }
121
+ /** Every check, its verdict. A check that cannot be evaluated under a change, or comes after one not kept, is `cannot`, said why. */
122
+ function figureRelationVerdicts(asset, checks) {
123
+ let asMade;
124
+ try {
125
+ asMade = boxesUnder(asset, {}, {});
126
+ }
127
+ catch (e) {
128
+ return checks.map(check => ({ principle: check.principle, says: check.says, verdict: 'cannot', because: `not made (${String(e?.message ?? e).slice(0, 120)})` }));
129
+ }
130
+ const out = [];
131
+ for (const check of checks) {
132
+ const before = check.after && out.find(v => v.says === check.after);
133
+ if (before && before.verdict !== 'kept') {
134
+ out.push({ principle: check.principle, says: check.says, verdict: 'cannot', because: `it comes after "${check.after}", which is not kept` });
135
+ continue;
136
+ }
137
+ out.push(judgeOne(asset, check, asMade));
138
+ }
139
+ return out;
140
+ }
141
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
142
+ const matMul = (A, B) => A.map(r => [0, 1, 2].map(j => r[0] * B[0][j] + r[1] * B[1][j] + r[2] * B[2][j]));
143
+ const transpose = (A) => [0, 1, 2].map(j => A.map(r => r[j]));
144
+ const det3 = (m) => m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
145
+ const vecOf = (c) => [c.x, c.y, c.z];
146
+ /** The line a part turned about between two of its poses: its direction and a point on it. None when it did not turn. */
147
+ function turnedAbout(b0, b1) {
148
+ const R0 = b0.rotation, R1 = b1.rotation;
149
+ const D = matMul(R1, transpose(R0));
150
+ const w = [D[2][1] - D[1][2], D[0][2] - D[2][0], D[1][0] - D[0][1]];
151
+ const n = Math.hypot(...w);
152
+ if (n < 1e-3)
153
+ return undefined;
154
+ const u = w.map(x => x / n);
155
+ const c0 = vecOf(b0.centre), c1 = vecOf(b1.centre);
156
+ /* The point p with c1 − p = D (c0 − p), pinned along u level with c0: (I − D + u uᵀ) p = c1 − D c0 + u (u·c0). */
157
+ const M = [0, 1, 2].map(i => [0, 1, 2].map(j => (i === j ? 1 : 0) - D[i][j] + u[i] * u[j]));
158
+ const b = [0, 1, 2].map(i => c1[i] - dot(D[i], c0) + u[i] * dot(u, c0));
159
+ const d = det3(M);
160
+ const point = [0, 1, 2].map(c => det3(M.map((r, i) => r.map((v, j) => (j === c ? b[i] : v)))) / d);
161
+ /* A direction is said pointing up, right or front, so a line turned either way reads the same. */
162
+ const sign = Math.sign(u[1] || u[0] || u[2]) || 1;
163
+ return { direction: u.map(x => x * sign), point };
164
+ }
165
+ /** The point on a line nearest another point. */
166
+ const nearest = (line, to) => {
167
+ const k = dot([to[0] - line.point[0], to[1] - line.point[1], to[2] - line.point[2]], line.direction);
168
+ return [0, 1, 2].map(i => line.point[i] + k * line.direction[i]);
169
+ };
170
+ /** The joint a part moves on, its origin and axes in the figure frame, as the kernel reads them (figureJointFrameOf). */
171
+ function jointFrameOf(asset, part) {
172
+ const frame = (0, figure_model_1.figureJointFrameOf)(asset, part);
173
+ return frame ? { joint: frame.joint, at: frame.origin, axes: frame.axes } : `${part} has no joint of its own`;
174
+ }
175
+ /** The part's heading about the vertical axis, read from its own turn: where its local X points, in degrees. */
176
+ const headingOf = (b) => {
177
+ const r = b.rotation;
178
+ return (Math.atan2(r[2][0], r[0][0]) * 180) / Math.PI;
179
+ };
180
+ /**
181
+ * Some control turns the part through the degrees asked, and about the pivot's vertical axis: its centre, seen from that
182
+ * axis, turns with it (or stays on the axis). Said for every control when none does.
183
+ */
184
+ function turnsAbout(asset, relation) {
185
+ const controls = asset.document.model.inputs.filter(i => i.role === 'state' && Number.isFinite(i.min) && Number.isFinite(i.max) && i.max > i.min);
186
+ if (!controls.length)
187
+ return { off: 'no control with a range' };
188
+ const said = [];
189
+ let widest;
190
+ for (const c of controls) {
191
+ const seen = [];
192
+ const poses = [];
193
+ let pivotBox;
194
+ for (const f of [0, 0.25, 0.5, 0.75, 1]) {
195
+ const boxes = boxesUnder(asset, {}, { [c.id]: c.min + (c.max - c.min) * f });
196
+ const [p, pivot] = [boxes.get(relation.part), boxes.get(relation.pivot)];
197
+ if (!p || !pivot)
198
+ return { off: `no part ${!p ? relation.part : relation.pivot}` };
199
+ poses.push(p);
200
+ pivotBox = pivot;
201
+ seen.push({ heading: headingOf(p), x: p.centre.x - pivot.centre.x, z: p.centre.z - pivot.centre.z });
202
+ }
203
+ let swept = 0;
204
+ for (let i = 1; i < seen.length; i++)
205
+ swept += ((seen[i].heading - seen[i - 1].heading + 540) % 360) - 180;
206
+ /* About the pivot: the centre at each sample is the first centre turned by the heading turned since, in the same sense as the heading is read (atan2 of z over x). */
207
+ const first = seen[0];
208
+ const off = Math.max(...seen.map(s => {
209
+ const t = (((s.heading - first.heading) * Math.PI) / 180);
210
+ const [x, z] = [first.x * Math.cos(t) - first.z * Math.sin(t), first.x * Math.sin(t) + first.z * Math.cos(t)];
211
+ return Math.hypot(s.x - x, s.z - z);
212
+ }));
213
+ const about = off <= relation.within;
214
+ /* Kept: the axis it turns about now is said too, for a change elsewhere to keep. */
215
+ if (Math.abs(swept) >= relation.degrees - 5 && about)
216
+ return { axis: axisReport(asset, relation, { control: c.id, poses, pivot: pivotBox }) };
217
+ if (!widest || Math.abs(swept) > Math.abs(widest.swept))
218
+ widest = { control: c.id, swept, poses, pivot: pivotBox };
219
+ said.push(`${c.id} turns ${relation.part} ${round(Math.abs(swept))} degrees${about ? '' : `, not about ${relation.pivot}'s axis (its centre strays ${round(off)} mm from that turn)`}`);
220
+ }
221
+ return { off: `${said.join('; ')}; ${relation.degrees} degrees about ${relation.pivot}'s axis asked`, axis: widest && axisReport(asset, relation, widest) };
222
+ }
223
+ /** The axis asked -- the pivot's vertical axis, from the relation -- against the axis the widest-turning control turns the part about. */
224
+ function axisReport(asset, relation, widest) {
225
+ const unknown = [];
226
+ const frame = jointFrameOf(asset, relation.part);
227
+ if (typeof frame === 'string')
228
+ unknown.push(frame);
229
+ const jointOrigin = typeof frame === 'string' ? undefined : frame;
230
+ const asked = { direction: [0, 1, 0], point: vecOf(widest.pivot.centre) };
231
+ let line;
232
+ for (let i = 1; i < widest.poses.length && !line; i++)
233
+ line = turnedAbout(widest.poses[i - 1], widest.poses[i]);
234
+ if (!line)
235
+ unknown.push(`${widest.control} does not turn ${relation.part}`);
236
+ /* Each line said by its point nearest the joint origin; without one, nearest the pivot's centre. */
237
+ const near = jointOrigin?.at ?? asked.point;
238
+ return {
239
+ frame: exports.FIGURE_FRAME,
240
+ asked: { direction: asked.direction, through: nearest(asked, near), says: `${relation.pivot}'s vertical axis` },
241
+ ...(line ? { actual: { direction: line.direction, through: nearest(line, near), control: widest.control } } : {}),
242
+ ...(jointOrigin ? { jointOrigin } : {}),
243
+ ...(unknown.length ? { unknown } : {})
244
+ };
245
+ }
246
+ function judgeOne(asset, check, asMade) {
247
+ const said = { principle: check.principle, says: check.says };
248
+ if (check.relation.kind === 'turns-about') {
249
+ let turned;
250
+ try {
251
+ turned = turnsAbout(asset, check.relation);
252
+ }
253
+ catch (e) {
254
+ return { ...said, verdict: 'cannot', because: `not made (${String(e?.message ?? e).slice(0, 120)})` };
255
+ }
256
+ const { off, axis } = turned;
257
+ if (!off)
258
+ return { ...said, verdict: 'kept', ...(axis ? { axis, now: axisNow(axis) } : {}) };
259
+ if (off === 'no control with a range' || off.startsWith('no part'))
260
+ return { ...said, verdict: 'cannot', because: off };
261
+ return { ...said, verdict: 'broken', because: off, measured: { change: 'each control across its range', asked: '', got: off }, definition: definitionsOf(asset, partsOf(check.relation)), ...(axis ? { axis } : {}) };
262
+ }
263
+ /* A case the figure cannot be made at is not judged, and does not hide a case that breaks: every case is evaluated. */
264
+ let unmade;
265
+ for (const change of check.under) {
266
+ const cases = casesOf(asset, change);
267
+ if (typeof cases === 'string')
268
+ return { ...said, verdict: 'cannot', because: cases };
269
+ for (const c of cases) {
270
+ let boxes;
271
+ try {
272
+ boxes = boxesUnder(asset, c.design, c.state);
273
+ }
274
+ catch (e) {
275
+ unmade ??= `${c.label}: not made (${String(e?.message ?? e).slice(0, 120)})`;
276
+ continue;
277
+ }
278
+ /*
279
+ * A size change not applied tests no relation kept under it: not judged there. Applied, the relation is judged
280
+ * whether or not its own parts move -- what it keeps may be that they stay put.
281
+ */
282
+ const skipped = change.kind === 'size' && check.relation.kind !== 'grows-with-size' ? notApplied(change, boxes, asMade) : undefined;
283
+ if (skipped) {
284
+ unmade ??= `${c.label}: ${skipped}`;
285
+ continue;
286
+ }
287
+ const off = offBy(boxes, check.relation, asMade, c.scale);
288
+ if (!off)
289
+ continue;
290
+ if (off.startsWith('no part'))
291
+ return { ...said, verdict: 'cannot', because: `${c.label}: ${off}` };
292
+ const definition = definitionsOf(asset, partsOf(check.relation));
293
+ const [got, asked] = off.includes(', ') && off.endsWith('asked') ? [off.split(', ')[0], off.split(', ')[1].replace(/ asked$/, '')] : [off, ''];
294
+ const cause = causeOf(check, c.label, definition);
295
+ const between = check.relation.kind === 'distance' ? betweenOf(boxes, check.relation) : undefined;
296
+ return { ...said, verdict: 'broken', because: `${c.label}: ${off}`, measured: { change: c.label, asked, got, ...(between ? { between } : {}) }, definition, ...(cause ? { cause } : {}) };
297
+ }
298
+ }
299
+ if (unmade)
300
+ return { ...said, verdict: 'cannot', because: unmade };
301
+ /* Kept: a distance says what it measures as made, the value to keep. */
302
+ const r = check.relation;
303
+ if (r.kind === 'distance') {
304
+ const [a, b] = [asMade.get(r.a.part), asMade.get(r.b.part)];
305
+ if (a && b)
306
+ return { ...said, verdict: 'kept', now: `${round(edge(a, r.a.axis, r.a.side) - edge(b, r.b.axis, r.b.side))} mm` };
307
+ }
308
+ return { ...said, verdict: 'kept' };
309
+ }
310
+ /**
311
+ * The broken relations said to the model: what was asked, what the figure gives, under which change, and the relation to
312
+ * look at again. No remedy is named: how to keep the relation is the model's to decide.
313
+ */
314
+ function figureRelationFeedback(verdicts) {
315
+ const broken = verdicts.filter(v => v.verdict === 'broken');
316
+ const unjudged = verdicts.filter(v => v.verdict === 'cannot');
317
+ if (!broken.length && !unjudged.length)
318
+ return undefined;
319
+ const kept = verdicts.filter(v => v.verdict === 'kept');
320
+ return [
321
+ ...(broken.length ? ['The request states these relations and the figure breaks them. They are conditions the figure must meet, not observations to weigh against what you meant. Evaluated as the request says it changes:'] : []),
322
+ ...broken.map(v => {
323
+ const m = v.measured;
324
+ const diff = m.asked ? `Asked: ${m.asked}. ${m.change === 'as made' ? 'As made' : `With ${m.change}`}, the figure gives ${m.got}${m.between ? ` (${m.between})` : ''}.` : `${m.change === 'as made' ? 'As made' : `With ${m.change}`}: ${m.got}.`;
325
+ return `- ${v.says}. ${diff}${v.axis ? `\n${axisLines(v.axis)}` : ''}${v.definition?.length ? `${v.axis ? '\n ' : ''} As defined: ${v.definition.join('; ')}.` : ''} Look again at the relation you defined for it.`;
326
+ }),
327
+ /* Not judged is not met: said apart, with why it could not be judged. */
328
+ /* Not judged is not broken: whether it is met is not confirmed, and what could not be judged is said. */
329
+ ...(unjudged.length ? ['The request states these too. Whether the figure meets them is not confirmed -- they could not be judged:', ...unjudged.map(v => `- ${v.says}: ${v.because}.`)] : []),
330
+ /* What holds now is said too: a change made for one relation must not undo another. */
331
+ ...(kept.length
332
+ ? ['The request also asks for these, and the figure keeps them now. Keep what they measure now while you change it; they are measured again on your answer:', ...kept.map(v => `- ${v.says}.${v.now ? ` Now: ${v.now}` : ''}`)]
333
+ : [])
334
+ ].join('\n');
335
+ }
336
+ /** The relations a revision broke: kept on the figure before it, broken on the figure after. */
337
+ function figureRelationsBrokenBy(before, after) {
338
+ const was = new Map(before.map(v => [v.says, v.verdict]));
339
+ return after.filter(v => v.verdict === 'broken' && was.get(v.says) === 'kept').map(v => v.says);
340
+ }
341
+ const mm = (v) => `(x ${Math.round(v[0])}, y ${Math.round(v[1])}, z ${Math.round(v[2])})`;
342
+ const way = (v) => `(${v.map(x => Math.round(x * 100) / 100 + 0).join(', ')})`;
343
+ /** A kept turn's axis as one line, in the frame named: where it is and which way it points, and the joint origin it is written from. */
344
+ function axisNow(a) {
345
+ if (!a.actual)
346
+ return `not known (${(a.unknown ?? []).join('; ')}).`;
347
+ return [
348
+ `in ${a.frame}, it turns about direction ${way(a.actual.direction)} through ${mm(a.actual.through)} -- keep this axis there, pointing this way`,
349
+ a.jointOrigin ? `; the joint origin of joint ${a.jointOrigin.joint} is ${mm(a.jointOrigin.at)}, its joint frame axes x ${way(a.jointOrigin.axes.x)}, y ${way(a.jointOrigin.axes.y)}, z ${way(a.jointOrigin.axes.z)}.` : '.'
350
+ ].join('');
351
+ }
352
+ /** An axis report as lines: the frame named once, then the axis asked, the axis turned about, and the joint origin. */
353
+ function axisLines(a) {
354
+ const same = a.actual ? Math.abs(dot(a.actual.direction, a.asked.direction)) > 0.999 : undefined;
355
+ return [
356
+ ` Axes in ${a.frame}:`,
357
+ ` asked: ${a.asked.says}, direction ${way(a.asked.direction)}, through ${mm(a.asked.through)}.`,
358
+ ...(a.actual ? [` turned about (${a.actual.control}): direction ${way(a.actual.direction)}${same ? ', the same as asked' : ', not the direction asked'}, through ${mm(a.actual.through)}.`] : []),
359
+ ...(a.jointOrigin
360
+ ? [` joint origin of joint ${a.jointOrigin.joint}: ${mm(a.jointOrigin.at)}; its joint frame axes x ${way(a.jointOrigin.axes.x)}, y ${way(a.jointOrigin.axes.y)}, z ${way(a.jointOrigin.axes.z)}.`]
361
+ : []),
362
+ ...(a.unknown?.length ? [` not known: ${a.unknown.join('; ')}.`] : [])
363
+ ].join('\n');
364
+ }
365
+ /** The verdicts by principle: a principle is kept when every one of its checks is. */
366
+ function figurePrincipleVerdicts(verdicts) {
367
+ const out = {};
368
+ for (const v of verdicts) {
369
+ const was = out[v.principle];
370
+ out[v.principle] = was === 'broken' || v.verdict === 'broken' ? 'broken' : was === 'cannot' || v.verdict === 'cannot' ? 'cannot' : 'kept';
371
+ }
372
+ return out;
373
+ }
374
+ //# sourceMappingURL=figure-relation-checks.js.map
@@ -43,6 +43,7 @@ const typeorm_1 = require("typeorm");
43
43
  const ai_client_base_1 = require("@things-factory/ai-client-base");
44
44
  const figure_context_js_1 = require("./figure-context.js");
45
45
  const figure_mcp_agent_js_1 = require("./figure-mcp-agent.js");
46
+ const figure_ai_trace_js_1 = require("./figure-ai-trace.js");
46
47
  /**
47
48
  * The person asking, for the agent's tools that reach the application: the tools their privileges open -- asked of the
48
49
  * conversation's own tool gate -- and a token of theirs that lives as long as the agent may run. None when no tool
@@ -525,6 +526,8 @@ function figureToolSpecs() {
525
526
  }
526
527
  else
527
528
  result = await proposeFigureSteps({
529
+ /* Each request's course is kept, to find where the guide or the observations fail the model (ADR-0206). */
530
+ trace: figure_ai_trace_js_1.writeFigureAITrace,
528
531
  /* The agent of this conversation's turn - the one the person picked, or the domain default. */
529
532
  client: await (0, ai_client_base_1.aiClientFor)({
530
533
  domain: ctx?.state?.domain,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@things-factory/figure-service",
3
- "version": "10.1.283",
3
+ "version": "10.1.287",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "@things-factory:registry": "https://registry.npmjs.org"
@@ -41,7 +41,7 @@
41
41
  "test:templates": "node --test scripts/templates.test.mts"
42
42
  },
43
43
  "dependencies": {
44
- "@hatiolab/figure-model": "^0.12.11",
44
+ "@hatiolab/figure-model": "^0.12.13",
45
45
  "@operato/typeorm-history": "^10.0.0",
46
46
  "@things-factory/ai-client-base": "^10.1.283",
47
47
  "@things-factory/attachment-base": "^10.1.283",
@@ -54,5 +54,5 @@
54
54
  "jszip": "^3.10.1",
55
55
  "koa-router": "^7.4.0"
56
56
  },
57
- "gitHead": "912e4835a175273005bba4a98da160906caa2b40"
57
+ "gitHead": "cc547a35fc3f0cda7ae5bc8337a5bb342db4efdc"
58
58
  }