@graview/tools 0.1.65 → 0.1.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/ai.d.ts +63 -1
  2. package/dist/ai.d.ts.map +1 -1
  3. package/dist/ai.js.map +1 -1
  4. package/dist/cli.d.ts.map +1 -1
  5. package/dist/cli.js +2 -1
  6. package/dist/cli.js.map +1 -1
  7. package/dist/design-agent.d.ts +190 -0
  8. package/dist/design-agent.d.ts.map +1 -0
  9. package/dist/design-agent.js +434 -0
  10. package/dist/design-agent.js.map +1 -0
  11. package/dist/dev-ai.js +61 -0
  12. package/dist/dev-ai.js.map +1 -1
  13. package/dist/draft-check.d.ts +166 -0
  14. package/dist/draft-check.d.ts.map +1 -0
  15. package/dist/draft-check.js +443 -0
  16. package/dist/draft-check.js.map +1 -0
  17. package/dist/frame.d.ts +1 -1
  18. package/dist/frame.d.ts.map +1 -1
  19. package/dist/index.d.ts +2 -1
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/inline-ai.d.ts.map +1 -1
  23. package/dist/inline-ai.js +28 -1
  24. package/dist/inline-ai.js.map +1 -1
  25. package/dist/page-better.d.ts +240 -0
  26. package/dist/page-better.d.ts.map +1 -0
  27. package/dist/page-better.js +383 -0
  28. package/dist/page-better.js.map +1 -0
  29. package/dist/providers/structure.d.ts.map +1 -1
  30. package/dist/providers/structure.js +2 -2
  31. package/dist/providers/structure.js.map +1 -1
  32. package/dist/reshape.d.ts +15 -0
  33. package/dist/reshape.d.ts.map +1 -1
  34. package/dist/reshape.js.map +1 -1
  35. package/dist/section.d.ts +30 -4
  36. package/dist/section.d.ts.map +1 -1
  37. package/dist/section.js +58 -30
  38. package/dist/section.js.map +1 -1
  39. package/dist/tidy/blocking.d.ts +1 -1
  40. package/dist/tidy/blocking.d.ts.map +1 -1
  41. package/dist/tidy/blocking.js +21 -14
  42. package/dist/tidy/blocking.js.map +1 -1
  43. package/dist/tidy/dream.d.ts.map +1 -1
  44. package/dist/tidy/dream.js +5 -1
  45. package/dist/tidy/dream.js.map +1 -1
  46. package/dist/tidy/judges.d.ts +19 -0
  47. package/dist/tidy/judges.d.ts.map +1 -1
  48. package/dist/tidy/judges.js +46 -8
  49. package/dist/tidy/judges.js.map +1 -1
  50. package/dist/tidy/judging.d.ts.map +1 -1
  51. package/dist/tidy/judging.js +15 -24
  52. package/dist/tidy/judging.js.map +1 -1
  53. package/dist/workflows/far.d.ts +17 -0
  54. package/dist/workflows/far.d.ts.map +1 -0
  55. package/dist/workflows/far.js +63 -0
  56. package/dist/workflows/far.js.map +1 -0
  57. package/dist/workflows/run-act.d.ts.map +1 -1
  58. package/dist/workflows/run-act.js +35 -1
  59. package/dist/workflows/run-act.js.map +1 -1
  60. package/dist/workflows/run-agent.d.ts.map +1 -1
  61. package/dist/workflows/run-agent.js +80 -14
  62. package/dist/workflows/run-agent.js.map +1 -1
  63. package/dist/workflows/run-classify.js +4 -4
  64. package/dist/workflows/run-classify.js.map +1 -1
  65. package/dist/workflows/run.d.ts.map +1 -1
  66. package/dist/workflows/run.js +85 -2
  67. package/dist/workflows/run.js.map +1 -1
  68. package/dist/workflows/seat.d.ts +3 -1
  69. package/dist/workflows/seat.d.ts.map +1 -1
  70. package/dist/workflows/seat.js +1 -0
  71. package/dist/workflows/seat.js.map +1 -1
  72. package/dist/workflows/types.d.ts +126 -2
  73. package/dist/workflows/types.d.ts.map +1 -1
  74. package/dist/workflows.d.ts +2 -1
  75. package/dist/workflows.d.ts.map +1 -1
  76. package/dist/workflows.js +1 -0
  77. package/dist/workflows.js.map +1 -1
  78. package/package.json +3 -3
@@ -0,0 +1,240 @@
1
+ import type { GraviewDocument } from "@graview/core/document";
2
+ import type { HostAi, ThinkingProvider } from "./ai.js";
3
+ import type { SectionMode, SectionStage } from "./section.js";
4
+ /** The page's part, as the models are told it. */
5
+ export interface PagePartSaid {
6
+ readonly name: string;
7
+ readonly slot: "list" | "group" | "record" | "home" | "place";
8
+ readonly kind?: string;
9
+ readonly group?: string;
10
+ }
11
+ /** Whether words typed in the menu are about how the part looks or about its records, and who said so. */
12
+ export declare function aboutTheLook(ai: HostAi | undefined, words: string, name: string): Promise<{
13
+ readonly about: "look" | "records";
14
+ readonly by: "fast" | "words";
15
+ readonly confidence?: number;
16
+ }>;
17
+ /**
18
+ * SPEC FIRST, UNLESS THE FAST SLOT IS SURE: a page goes to a view of its
19
+ * own only where it says so with at least this confidence. A vague ask
20
+ * ("make this page look better") is tried over the spec, whose model may
21
+ * still answer that the spec cannot say it.
22
+ */
23
+ export declare const OWN_VIEW_WHEN_SURE = 0.6;
24
+ /** Whether the view spec can say what was asked of the page, or it needs a view of its own. */
25
+ export declare function specCanSay(ai: HostAi | undefined, words: string, part: PagePartSaid): Promise<{
26
+ readonly can: boolean;
27
+ readonly by: "fast" | "words";
28
+ readonly confidence?: number;
29
+ }>;
30
+ /** The edit ops a page's look may be changed by: the view spec, and nothing else of the app. */
31
+ export declare const PAGE_SPEC_OPS: readonly ["set-view", "set-glance", "set-page-fields", "arrange-pages", "set-label", "set-format"];
32
+ /** What in these edits is not the view spec's, in sentences: empty when every one is. */
33
+ export declare function notTheSpec(edits: readonly unknown[]): string[];
34
+ export declare const PAGE_SPEC_SYSTEM: string;
35
+ /** What the model is told of the page and its spec. */
36
+ export declare function pageSpecPrompt(ask: {
37
+ readonly part: PagePartSaid;
38
+ readonly document: GraviewDocument;
39
+ readonly mode: SectionMode;
40
+ readonly words?: string;
41
+ readonly highlighted?: readonly string[];
42
+ readonly shows?: string;
43
+ readonly findings?: readonly string[];
44
+ readonly last?: unknown;
45
+ }): string;
46
+ /** The model's answer read: the edits and the sentence, or what it says the spec cannot do; undefined when it is neither. */
47
+ export declare function readPageSpecReply(text: string): {
48
+ readonly edits: readonly unknown[];
49
+ readonly said: string;
50
+ } | {
51
+ readonly cannot: string;
52
+ } | undefined;
53
+ export interface DraftPageSpecOptions {
54
+ readonly ai: HostAi;
55
+ readonly document: GraviewDocument;
56
+ readonly part: PagePartSaid;
57
+ readonly mode: SectionMode;
58
+ readonly words?: string;
59
+ readonly highlighted?: readonly string[];
60
+ readonly shows?: string;
61
+ /** THE HOST'S JUDGMENT of the edits: the checker's refusal and anything else that keeps them from being offered, in sentences; empty when they may be. */
62
+ readonly judge: (edits: readonly unknown[]) => Promise<readonly string[]>;
63
+ /** Told when the first try was refused and is handed back, with what was refused. */
64
+ readonly repairing?: (findings: readonly string[]) => void;
65
+ }
66
+ export type DraftPageSpecResult = {
67
+ readonly ok: true;
68
+ readonly edits: readonly unknown[];
69
+ readonly said: string;
70
+ readonly repaired: boolean;
71
+ readonly stages: readonly SectionStage[];
72
+ } | {
73
+ readonly ok: false;
74
+ readonly cannot?: string;
75
+ readonly refused: string;
76
+ readonly stages: readonly SectionStage[];
77
+ };
78
+ /**
79
+ * THE LEAST EDITS OVER THE VIEW SPEC: the light model first — the full one
80
+ * where its answer cannot be read — held to the spec's ops and judged by
81
+ * the host (its checker); what is refused is handed back once to the full
82
+ * model, and refused in words if it fails again. A model that says the
83
+ * spec cannot do it is answered `cannot`, for the page to offer its own view.
84
+ */
85
+ export declare function draftPageSpec(options: DraftPageSpecOptions): Promise<DraftPageSpecResult>;
86
+ /** A worker view's manifest for the page a part is on: its name, title, what it attaches to and draws. */
87
+ export interface ForkManifest {
88
+ readonly name: string;
89
+ /** None: the view is the page it was made of, not a place of its own beside it. */
90
+ readonly title?: string;
91
+ readonly attach: string;
92
+ readonly cardinality: "one" | "many";
93
+ readonly replaces?: "page";
94
+ readonly reads?: {
95
+ readonly kinds?: readonly string[];
96
+ readonly edges?: readonly string[];
97
+ };
98
+ /** The acts its presses may ask for (`data-act`): the kind's own, so a new design can finish a task as the page did. */
99
+ readonly acts?: readonly string[];
100
+ }
101
+ /**
102
+ * THE VIEW A PAGE BECOMES: a kind's list (a group's too) is a view of many
103
+ * that is the list page, a record's page a view of one that is the whole
104
+ * page, the home the home's body — each reading the kinds and the
105
+ * relations the kind is linked by — untitled, so it is that page and not a
106
+ * place of its own beside it. Undefined for a place, which a lens draws.
107
+ */
108
+ export declare function forkManifest(part: PagePartSaid, links: {
109
+ readonly kinds: readonly string[];
110
+ readonly edges: readonly string[];
111
+ }, acts?: readonly string[]): ForkManifest | undefined;
112
+ export declare const PAGE_VIEW_SYSTEM: string;
113
+ /** What the model is told of the page it rewrites as a view — or, with `current`, of the draft so far that it changes again. */
114
+ export declare function pageViewPrompt(ask: {
115
+ readonly part: PagePartSaid;
116
+ readonly manifest: ForkManifest;
117
+ readonly mode: SectionMode;
118
+ readonly words?: string;
119
+ readonly highlighted?: readonly string[];
120
+ readonly outline: string;
121
+ readonly data: unknown;
122
+ readonly keep?: PageViewKeeps;
123
+ readonly markup?: string;
124
+ readonly current?: string;
125
+ readonly findings?: readonly string[];
126
+ readonly last?: unknown;
127
+ }): string;
128
+ /** THE CHECKLIST a new design must cover, a line per record: what it must show beside its name, and the heading it sits under. */
129
+ export declare function checklistOf(keep: PageViewKeeps): readonly {
130
+ readonly record: string;
131
+ readonly id?: string;
132
+ readonly must_show?: readonly string[];
133
+ readonly under?: string;
134
+ }[];
135
+ /** How the page grouped its records, as a rule the model can write: which link names the heading. */
136
+ export declare function groupingRule(grouping: NonNullable<PageViewKeeps["grouping"]>): string;
137
+ /** The model's view read: the script and its few words; undefined when it is not one. */
138
+ export declare function readPageViewReply(text: string): {
139
+ readonly source: string;
140
+ readonly said: string;
141
+ } | undefined;
142
+ /** What a new design must keep of the page: its title (drawn by the page, never again), its other headings, and the records it showed, by their words. */
143
+ export interface PageViewKeeps {
144
+ readonly title: string;
145
+ readonly headings: readonly string[];
146
+ readonly records: readonly string[];
147
+ /** What each record's row said beside its name (its status, its dates, its counts) and the heading it sat under, by its name — with its id where it is known. */
148
+ readonly says?: Readonly<Record<string, {
149
+ readonly id?: string;
150
+ readonly shows?: readonly string[];
151
+ readonly under?: string;
152
+ }>>;
153
+ /** How the page grouped its records: under the name of the `kind` record each is linked to by an `edge`, the grouped record at the edge's `record` end. */
154
+ readonly grouping?: {
155
+ readonly edge: string;
156
+ readonly kind: string;
157
+ readonly record: "from" | "to";
158
+ };
159
+ }
160
+ export interface DraftPageViewOptions {
161
+ readonly ai: HostAi;
162
+ readonly part: PagePartSaid;
163
+ readonly manifest: ForkManifest;
164
+ readonly mode: SectionMode;
165
+ readonly words?: string;
166
+ readonly highlighted?: readonly string[];
167
+ /** The page as it stands: its headings and the words it shows, a line each. */
168
+ readonly outline: string;
169
+ /** The data it reads: the kind's fields and a few records. */
170
+ readonly data: unknown;
171
+ /** The draft so far, changed again by `words` (a step on the bar). */
172
+ readonly current?: string;
173
+ /** What it must keep of the page, said to the model plainly. */
174
+ readonly keep?: PageViewKeeps;
175
+ /** The page as drawn, its markup, for the draft to start from: what it shows survives by default rather than being made again. */
176
+ readonly markup?: string;
177
+ /** How long the light model's tries may take together, in ms (30 s): past it the draft stops and says what it could not keep. */
178
+ readonly within?: number;
179
+ /** TRY HARDER: the full model once, from the last try and what broke (`from`), as long as it takes — until `signal` cancels it. */
180
+ readonly harder?: boolean;
181
+ readonly from?: {
182
+ readonly source: string;
183
+ readonly findings: readonly string[];
184
+ };
185
+ /** Cancels the drafting at once: the result is `canceled`, and nothing is shown. */
186
+ readonly signal?: AbortSignal;
187
+ /**
188
+ * THE PAGE'S JUDGMENT of a view: drawn where nobody sees it yet, the
189
+ * host's own checks, compared with the page it replaces — the findings
190
+ * that keep it from being shown. What the host would strip from its
191
+ * stylesheets is found before it is drawn at all (`cssFindings`).
192
+ */
193
+ readonly judge: (source: string) => Promise<readonly string[]>;
194
+ /** Told each time a try failed and is handed back, with what broke. */
195
+ readonly repairing?: (findings: readonly string[]) => void;
196
+ }
197
+ /**
198
+ * Who is asked, try by try: the light model, then at most two light
199
+ * repairs with what broke — the full model is never in the loop a person
200
+ * waits on, only behind Try harder (`harder`), once. Where only the full
201
+ * model is lent, it is asked once.
202
+ */
203
+ export declare function repairTries(light: ThinkingProvider | undefined, full: ThinkingProvider | undefined, options?: {
204
+ readonly harder?: boolean;
205
+ }): ThinkingProvider[];
206
+ /** How long a person waits on the light model's tries together before the card says plainly what it could not keep. */
207
+ export declare const DRAFT_WITHIN_MS = 30000;
208
+ /** A model's answer, raced against the time left and a cancel: the answer, "late", or "canceled". */
209
+ export declare function inTime<T>(answer: Promise<T>, ms: number | undefined, signal: AbortSignal | undefined): Promise<{
210
+ readonly value: T;
211
+ } | "late" | "canceled">;
212
+ /** What the card says where no version passed: plain, and never the findings. */
213
+ export declare const COULD_NOT = "I couldn't make a version that looks right.";
214
+ export type DraftPageViewResult = {
215
+ readonly ok: true;
216
+ readonly source: string;
217
+ readonly said: string;
218
+ readonly repaired: boolean;
219
+ readonly tries: number;
220
+ readonly stages: readonly SectionStage[];
221
+ } | {
222
+ readonly ok: false;
223
+ readonly refused: string;
224
+ readonly findings: readonly string[];
225
+ readonly last?: string;
226
+ readonly canceled?: true;
227
+ readonly late?: true;
228
+ readonly stages: readonly SectionStage[];
229
+ };
230
+ /**
231
+ * THE PAGE AS A VIEW OF ITS OWN, revised as asked: the light model first,
232
+ * judged where nobody sees it; what breaks is handed back to the light
233
+ * model at most twice, with what broke, all within `within` (30 s). A
234
+ * version that never passes stops there and says what it could not keep
235
+ * (`couldNotKeep`), with the last try and its findings for Try harder —
236
+ * the full model once, from there (`harder`, `from`), until it answers or
237
+ * is canceled. Nothing that did not pass is shown.
238
+ */
239
+ export declare function draftPageView(options: DraftPageViewOptions): Promise<DraftPageViewResult>;
240
+ //# sourceMappingURL=page-better.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"page-better.d.ts","sourceRoot":"","sources":["../src/page-better.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D,OAAO,KAAK,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAC;AAGxD,OAAO,KAAK,EAAE,WAAW,EAAE,YAAY,EAAE,MA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MAAM,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,GAAG,SAAS,EAAE,MAAM,EAAE,WAAW,GAAG,SAAS,GAAG,OAAO,CAAC;IAAE,QAAQ,CAAC,KAAK,EAAE,CAAC,CAAA;CAAE,GAAG,MAAM,GAAG,UAAU,CAAC,CAYjK;AAED,iFAAiF;AACjF,eAAO,MAAM,SAAS,gDAAgD,CAAC;AAEvE,MAAM,MAAM,mBAAmB,GAC3B;IAAE,QAAQ,CAAC,EAAE,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,CAAA;CAAE,GACnK;IAAE,QAAQ,CAAC,EAAE,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,EAAE,SAAS,MAAM,EAAE,CAAC;IAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,SAAS,YAAY,EAAE,CAAA;CAAE,CAAC;AAE7M;;;;;;;;GAQG;AACH,wBAAsB,aAAa,CAAC,OAAO,EAAE,oBAAoB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CA0C/F"}
@@ -0,0 +1,383 @@
1
+ import { thinkingOf } from "./inline-ai.js";
2
+ import { cssFindings, couldNotKeep } from "./draft-check.js";
3
+ /** The Fast slot the host gave, or its `decide`, where AI is not off. */
4
+ const fastOf = (ai) => (ai === undefined || ai.off ? undefined : (ai.fast ?? (ai.decide ? { model: ai.name ?? "decide", decide: ai.decide } : undefined)));
5
+ /** Words that are about how something looks or is laid out, read without a model where there is no Fast slot. */
6
+ const LOOK = /\b(look|looks|looking|nicer|prettier|cleaner|ugly|layout|laid out|lay it out|design|style|styled|theme|colou?rs?|font|bigger|smaller|larger|wider|narrower|taller|shorter|spacing|space|padding|margin|compact|dense|denser|roomier|columns?|grid|cards?|rows?|show (?:the )?\S+ (?:on|in) (?:each|every|the)|sort(?:ed)? by|order(?:ed)? by|group(?:ed)? by|readable|easier to read|at a glance|icons?|badges?|headings?|bold|highlight)\b/i;
7
+ /** Whether words typed in the menu are about how the part looks or about its records, and who said so. */
8
+ export async function aboutTheLook(ai, words, name) {
9
+ const said = words.trim();
10
+ const fast = fastOf(ai);
11
+ if (fast && said) {
12
+ try {
13
+ const decided = await fast.decide({ typed: said, on: name }, {
14
+ about: {
15
+ type: "choice",
16
+ instructions: `Somebody right-clicked “${name}” in an app and typed “${said}”. Is it about how “${name}” looks or is laid out, or about the records in it?`,
17
+ criteria: {
18
+ look: "How it looks or is laid out: making it look better, its style, size or spacing, what each row, card or page shows, its order or grouping",
19
+ records: "The records themselves: changing, closing, assigning, adding, deleting or moving them, or a question about them",
20
+ },
21
+ },
22
+ });
23
+ ai?.meter?.({ tier: "fast", model: fast.model, inputTokens: decided.usage.inputTokens, outputTokens: decided.usage.outputTokens, interaction: "menu" });
24
+ const answer = decided.answers["about"];
25
+ if (answer?.type === "choice" && (answer.choice === "look" || answer.choice === "records"))
26
+ return { about: answer.choice, by: "fast", confidence: answer.confidence };
27
+ }
28
+ catch {
29
+ // A Fast slot that fails leaves the words to decide.
30
+ }
31
+ }
32
+ return { about: LOOK.test(said) ? "look" : "records", by: "words" };
33
+ }
34
+ /** Words that need drawing the view spec has no word for, read without a model where there is no Fast slot. */
35
+ const DRAWING = /\b(colou?rs?|font|typeface|bigger|smaller|larger|wider|narrower|taller|spacing|padding|margin|border|shadow|rounded|corners?|columns? side by side|side by side|grid|chart|graph|picture of|animation|background|gradient|icons?|css|kanban|calendar)\b/i;
36
+ /**
37
+ * SPEC FIRST, UNLESS THE FAST SLOT IS SURE: a page goes to a view of its
38
+ * own only where it says so with at least this confidence. A vague ask
39
+ * ("make this page look better") is tried over the spec, whose model may
40
+ * still answer that the spec cannot say it.
41
+ */
42
+ export const OWN_VIEW_WHEN_SURE = 0.6;
43
+ /** Whether the view spec can say what was asked of the page, or it needs a view of its own. */
44
+ export async function specCanSay(ai, words, part) {
45
+ const said = words.trim();
46
+ if (!said)
47
+ return { can: true, by: "words" };
48
+ const fast = fastOf(ai);
49
+ if (fast) {
50
+ try {
51
+ const decided = await fast.decide({ asked: said, on: part.name, page: part.slot }, {
52
+ can: {
53
+ type: "choice",
54
+ instructions: `Somebody asked of the page “${part.name}”: “${said}”. Can the app's view settings do it, or does it need drawing of its own?`,
55
+ criteria: {
56
+ spec: "The view settings can do it: which fields a card, a row or a page shows and in what order, a headline, a badge with a tone, a figure, a progress bar, a list of related records, how a list is sorted, grouped or filtered, a field's label or format",
57
+ drawing: "It needs drawing the settings have no word for: colors, fonts, sizes, spacing, borders or shadows, a layout or columns side by side, a chart, a calendar, a board, or markup and styles of its own",
58
+ },
59
+ },
60
+ });
61
+ ai?.meter?.({ tier: "fast", model: fast.model, inputTokens: decided.usage.inputTokens, outputTokens: decided.usage.outputTokens, interaction: "section" });
62
+ const answer = decided.answers["can"];
63
+ if (answer?.type === "choice" && (answer.choice === "spec" || answer.choice === "drawing"))
64
+ return { can: answer.choice === "spec" || answer.confidence < OWN_VIEW_WHEN_SURE, by: "fast", confidence: answer.confidence };
65
+ }
66
+ catch {
67
+ // Read from the words.
68
+ }
69
+ }
70
+ return { can: !DRAWING.test(said), by: "words" };
71
+ }
72
+ /** The edit ops a page's look may be changed by: the view spec, and nothing else of the app. */
73
+ export const PAGE_SPEC_OPS = ["set-view", "set-glance", "set-page-fields", "arrange-pages", "set-label", "set-format"];
74
+ const ARRANGING = new Set(["sort", "group", "filters"]);
75
+ /** What in these edits is not the view spec's, in sentences: empty when every one is. */
76
+ export function notTheSpec(edits) {
77
+ const said = [];
78
+ if (edits.length === 0)
79
+ said.push("It changed nothing.");
80
+ for (const edit of edits) {
81
+ const op = edit?.op;
82
+ if (typeof op !== "string" || !PAGE_SPEC_OPS.includes(op)) {
83
+ said.push(`“${String(op)}” is not a change to how a page reads.`);
84
+ continue;
85
+ }
86
+ if (op === "arrange-pages")
87
+ for (const key of Object.keys(edit))
88
+ if (key !== "op" && !ARRANGING.has(key))
89
+ said.push(`arrange-pages may say only sort, group and filters here, not “${key}”.`);
90
+ if (op === "set-label" && edit.field === undefined)
91
+ said.push("set-label may name only a field's label here, not a kind's.");
92
+ }
93
+ return said;
94
+ }
95
+ export const PAGE_SPEC_SYSTEM = [
96
+ "You change how one page of a Graview app reads, by editing its view spec: data that says what a kind's card, row and page show, and how a list opens. Nothing in it is code: no CSS, no markup, no colors or sizes of your own.",
97
+ "You are told the page (a kind's list, one group of it, a record's page, or the home), what was asked, the kind's fields and relations, and its spec as it stands.",
98
+ 'Answer with one JSON object and nothing else: {"edits": [...], "said": "<one sentence to the person saying what will change>"}. Or, where the spec has no word for it (colors, fonts, sizes, spacing, layout, a chart), answer {"cannot": "<one sentence saying what it would need>"}.',
99
+ "The edits you may use, and no others:",
100
+ '{"op":"set-view","kind":K,"slot":"card"|"row"|"page","blocks":[...]} — a kind\'s card, its row on a list, the blocks over its record page; {"op":"set-view","slot":"home","blocks":[...]} — the home. Blocks: {"title":"{name}"}, {"headline":"{count(out(\'rel\'))} things"}, {"text":"{field}","lines":2}, {"badge":"{field}","tone":"good"|"warn"|"bad"|"neutral"|"accent"}, {"field":"due","as":"date"|"time"|"datetime"|"relative"|"money"|"percent"|"count","label":"Due"}, {"figure":"expr","as":"number"|"money"|"percent","label":"..."}, {"progress":{"value":"done","max":"total"},"label":"..."}, {"list":"out(\'rel\')" or "all(\'kind\')","as":"row"|"card","sort":{"by":"f","direction":"asc"|"desc"},"limit":5,"group":{"by":"f"},"empty":"None yet."}, {"group":[...blocks],"direction":"row"|"column"}, {"when":"rule expression","show":[...blocks]}, {"divider":true}. Templates say {field}; a row always leads with {"title":"{name}"} or the record\'s label field.',
101
+ '{"op":"set-glance","kind":K,"fields":[...]} — the few facts said beside a record\'s name on a list.',
102
+ '{"op":"set-page-fields","kind":K,"fields":[...],"groups":[{"title":"...","fields":[...]}]} — the order and groups of a record page\'s facts.',
103
+ '{"op":"arrange-pages","sort":{K:{"by":"f","direction":"asc"|"desc"}},"group":{K:{"by":"f"}},"filters":{K:["f"]}} — how a kind\'s list opens. A list sorts by one of its kind\'s fields or computed values, and groups only by a choice or a yes-or-no field of its own: grouping by a relation or by the record that holds it is not the spec\'s to say.',
104
+ '{"op":"set-label","kind":K,"field":F,"label":"..."}, {"op":"set-format","kind":K,"field":F,"format":"money"|"percent"|"duration"|null}.',
105
+ "Name only fields and relations the kind has. Change only what the ask needs, on this page's kind. Keep every fact the page shows now unless asked to drop one.",
106
+ "Do what was asked or answer cannot: never something else in its place (grouping by another field than the one asked for, say).",
107
+ ].join("\n");
108
+ /** What the model is told of the page and its spec. */
109
+ export function pageSpecPrompt(ask) {
110
+ const kind = ask.part.kind;
111
+ const doc = ask.document;
112
+ const spec = kind ? doc.kinds[kind] : undefined;
113
+ const asked = ask.mode === "just" ? "Make this page better: easier to read at a glance, the facts a person needs first. Change no data." : (ask.words ?? "").trim();
114
+ return JSON.stringify({
115
+ page: { name: ask.part.name, is: ask.part.slot === "list" ? "a kind's list" : ask.part.slot === "group" ? `one group of a kind's list (“${ask.part.group}”)` : ask.part.slot === "record" ? "a record's page (every record of the kind)" : ask.part.slot === "home" ? "the home" : "a place", ...(kind ? { kind } : {}) },
116
+ asked,
117
+ ...(ask.highlighted?.length ? { pointed_at: ask.highlighted } : {}),
118
+ ...(spec ? { fields: spec["fields"], relations: spec["edges"] ?? spec["relations"], computed: spec["computed"], glance: spec["glance"], pageFields: spec["pageFields"] } : { kinds: Object.keys(doc.kinds) }),
119
+ now: { ...(kind ? { views: doc.views?.[kind] ?? null, list: doc.pages?.lists?.[kind] ?? null } : { home: doc.views?.["home"] ?? null }) },
120
+ ...(ask.shows ? { shows: ask.shows.slice(0, 1500) } : {}),
121
+ ...(ask.findings?.length ? { your_last_answer: ask.last, what_broke: ask.findings, repair: "Your last answer was refused as said in what_broke. Answer again, fixing each one — or, where the spec cannot do what was asked, answer cannot." } : {}),
122
+ });
123
+ }
124
+ /** The first JSON object in a model's answer. */
125
+ function jsonOf(text) {
126
+ const fenced = /```(?:json|js|javascript)?\s*([\s\S]*?)```/.exec(text)?.[1];
127
+ for (const body of fenced ? [fenced, text] : [text]) {
128
+ const start = body.indexOf("{");
129
+ const end = body.lastIndexOf("}");
130
+ if (start < 0 || end <= start)
131
+ continue;
132
+ try {
133
+ const parsed = JSON.parse(body.slice(start, end + 1));
134
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
135
+ return parsed;
136
+ }
137
+ catch {
138
+ // The next.
139
+ }
140
+ }
141
+ return undefined;
142
+ }
143
+ /** The model's answer read: the edits and the sentence, or what it says the spec cannot do; undefined when it is neither. */
144
+ export function readPageSpecReply(text) {
145
+ const parsed = jsonOf(text);
146
+ if (!parsed)
147
+ return undefined;
148
+ if (typeof parsed["cannot"] === "string" && parsed["cannot"].trim())
149
+ return { cannot: parsed["cannot"].trim() };
150
+ if (!Array.isArray(parsed["edits"]))
151
+ return undefined;
152
+ return { edits: parsed["edits"], said: typeof parsed["said"] === "string" && parsed["said"].trim() ? parsed["said"].trim() : "Changed how this page reads." };
153
+ }
154
+ /** Asks a slot, timed, what it spent kept as a stage. */
155
+ function asker(stages) {
156
+ return async (provider, stage, system, prompt) => {
157
+ const began = Date.now();
158
+ try {
159
+ const reply = await provider.think({ system, prompt, state: {}, catalog: { candidates: [] } });
160
+ stages.push({ stage, model: provider.model, ms: Date.now() - began, ...(reply.usage ? { usage: reply.usage } : {}) });
161
+ return reply.text;
162
+ }
163
+ catch {
164
+ stages.push({ stage, model: provider.model, ms: Date.now() - began });
165
+ return undefined;
166
+ }
167
+ };
168
+ }
169
+ /**
170
+ * THE LEAST EDITS OVER THE VIEW SPEC: the light model first — the full one
171
+ * where its answer cannot be read — held to the spec's ops and judged by
172
+ * the host (its checker); what is refused is handed back once to the full
173
+ * model, and refused in words if it fails again. A model that says the
174
+ * spec cannot do it is answered `cannot`, for the page to offer its own view.
175
+ */
176
+ export async function draftPageSpec(options) {
177
+ const stages = [];
178
+ const light = options.ai.off ? undefined : options.ai.light;
179
+ const full = thinkingOf(options.ai);
180
+ const first = light ?? full;
181
+ if (!first)
182
+ return { ok: false, refused: options.ai.withoutModel ?? "Changing a page needs AI, and none is on here.", stages };
183
+ const ask = asker(stages);
184
+ const base = { part: options.part, document: options.document, mode: options.mode, ...(options.words ? { words: options.words } : {}), ...(options.highlighted ? { highlighted: options.highlighted } : {}), ...(options.shows ? { shows: options.shows } : {}) };
185
+ const read = async (provider, stage, prompt) => {
186
+ const text = await ask(provider, stage, PAGE_SPEC_SYSTEM, prompt);
187
+ return text === undefined ? undefined : readPageSpecReply(text);
188
+ };
189
+ let answer = await read(first, light ? "light" : "thinking", pageSpecPrompt(base));
190
+ // Unreadable, the light model is asked once more: the full one is never in a loop a person waits on.
191
+ if (!answer && light)
192
+ answer = await read(light, "light", pageSpecPrompt(base));
193
+ if (!answer)
194
+ return { ok: false, refused: "The model did not answer with a change to this page.", stages };
195
+ if ("cannot" in answer)
196
+ return { ok: false, cannot: answer.cannot, refused: answer.cannot, stages };
197
+ const judged = async (edits) => {
198
+ const own = notTheSpec(edits);
199
+ return own.length > 0 ? own : [...(await options.judge(edits))];
200
+ };
201
+ let findings = await judged(answer.edits);
202
+ if (findings.length === 0)
203
+ return { ok: true, edits: answer.edits, said: answer.said, repaired: false, stages };
204
+ const repairer = first;
205
+ options.repairing?.(findings);
206
+ const again = await read(repairer, repairer === light ? "light" : "thinking", pageSpecPrompt({ ...base, findings, last: answer }));
207
+ if (again && "cannot" in again)
208
+ return { ok: false, cannot: again.cannot, refused: again.cannot, stages };
209
+ if (!again)
210
+ return { ok: false, refused: `It could not be changed so: ${findings.join(" ")}`, stages };
211
+ findings = await judged(again.edits);
212
+ if (findings.length > 0)
213
+ return { ok: false, refused: `It could not be changed so: ${findings.join(" ")}`, stages };
214
+ return { ok: true, edits: again.edits, said: again.said, repaired: true, stages };
215
+ }
216
+ const slug = (words) => words.toLowerCase().normalize("NFKD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "page";
217
+ /**
218
+ * THE VIEW A PAGE BECOMES: a kind's list (a group's too) is a view of many
219
+ * that is the list page, a record's page a view of one that is the whole
220
+ * page, the home the home's body — each reading the kinds and the
221
+ * relations the kind is linked by — untitled, so it is that page and not a
222
+ * place of its own beside it. Undefined for a place, which a lens draws.
223
+ */
224
+ export function forkManifest(part, links, acts = []) {
225
+ const reads = { ...(links.kinds.length ? { kinds: [...links.kinds] } : {}), ...(links.edges.length ? { edges: [...links.edges] } : {}) };
226
+ const read = { ...(Object.keys(reads).length > 0 ? { reads } : {}), ...(acts.length > 0 ? { acts: [...acts] } : {}) };
227
+ if ((part.slot === "list" || part.slot === "group") && part.kind)
228
+ return { name: `${slug(part.kind)}-list`, attach: part.kind, cardinality: "many", replaces: "page", ...read };
229
+ if (part.slot === "record" && part.kind)
230
+ return { name: `${slug(part.kind)}-page`, attach: part.kind, cardinality: "one", replaces: "page", ...read };
231
+ if (part.slot === "home")
232
+ return { name: "home-page", attach: "home", cardinality: "many", ...read };
233
+ return undefined;
234
+ }
235
+ export const PAGE_VIEW_SYSTEM = [
236
+ "You write a Graview worker view: one plain script, no imports and no build, that draws one page of an app through the global `graview`, in place of the page the app drew by itself.",
237
+ "The global: graview.style(css) a stylesheet; graview.onProps((props) => …) on every push of what it is shown; graview.render(graview.html`…`) draws markup, every ${value} escaped; graview.html`` nests: a list is ${items.map((one) => graview.html`<li>…</li>`)}. Never build HTML as a string or with join(): a string is drawn as its words.",
238
+ "props.nodes holds the records a view of many is drawn for and those it reads; props.node the record a view of one is drawn for. A record is plain data: id, kind, label, and each field by name. props.edges are {kind, from, to}. props.choices[kind][field][option] is a choice's label.",
239
+ 'Link to a record with <a data-record="${node.id}">…</a>. Give repeated rows data-key="${node.id}". Name each part a person would name with a heading inside a <section aria-labelledby="x-h"> whose heading has id="x-h"; never aria-label.',
240
+ "The page draws its own title above your view: never draw the page's title again. Draw each other heading the page had, with the same words, and every record the page showed: each record still says what its row said (its status, its dates, its counts, in words) and stays under the heading it was under, unless what was asked changes that.",
241
+ "Say things in words a person reads: a date as the page said it (“Sep 3”), never as stored (2026-09-03). A date kept as YYYY-MM-DD is a day, not an instant: read it as new Date(`${value}T00:00`) — new Date(value) alone is midnight in London and the day before here — then .toLocaleDateString(props.locale, { month: \"short\", day: \"numeric\" }); never show a field's own name (order, done, holds), an id, true, false, null or undefined. Leave out a value the page did not show unless asked for it.",
242
+ "CSS the host keeps: plain rules on your own classes and elements, one level, and @media. Give your outer element a class (class=\"pg\") and style that: never :host, ::slotted or ::part, no url(), @import, @font-face, @keyframes or nesting. Colors, type and corners only through var(--graview-ink), var(--graview-ink-muted), var(--graview-panel), var(--graview-edge), var(--graview-accent), var(--graview-ground), var(--graview-radius). position may be static, relative, absolute or sticky. Set no height; lay it out well at a phone's width and at a desk's.",
243
+ "Never write the words import, export or require, nor <script>, <style>, or on…= attributes.",
244
+ 'Answer with one JSON object and nothing else: {"source": "<the whole script>", "said": "<a few words on what you changed>"}.',
245
+ ].join("\n");
246
+ /** What the model is told of the page it rewrites as a view — or, with `current`, of the draft so far that it changes again. */
247
+ export function pageViewPrompt(ask) {
248
+ const asked = ask.mode === "just" ? "Make this page better: easier to read at a glance, laid out cleanly, in the app's own look. Change no data it shows." : (ask.words ?? "").trim();
249
+ return JSON.stringify({
250
+ page: ask.part.name,
251
+ view: { attach: ask.manifest.attach, cardinality: ask.manifest.cardinality, reads: ask.manifest.reads ?? {} },
252
+ asked,
253
+ ...(ask.highlighted?.length ? { pointed_at: ask.highlighted } : {}),
254
+ as_it_stands: ask.outline.slice(0, 4000),
255
+ ...(ask.keep ? { the_page_draws_its_title: ask.keep.title, keep_these_headings: ask.keep.headings, show_each_of_these_records: ask.keep.records } : {}),
256
+ ...(ask.keep?.says ? { checklist: checklistOf(ask.keep), checklist_rule: CHECKLIST_RULE } : {}),
257
+ ...(ask.keep?.grouping ? { grouping: groupingRule(ask.keep.grouping) } : {}),
258
+ ...(ask.markup ? { the_page_as_html: ask.markup.slice(0, 6000), start_from_it: "Start from this markup: keep every word it shows and the order of its parts; change how it looks as asked. Draw it from props, not as fixed words." } : {}),
259
+ ...(ask.current ? { your_view_so_far: ask.current.slice(0, 8000), change: "Change your view so far as asked; keep everything else of it." } : {}),
260
+ data: ask.data,
261
+ ...(ask.findings?.length ? { your_last_answer: ask.last, what_broke: ask.findings, repair: "Your last answer broke as said in what_broke. Answer again, fixing each one." } : {}),
262
+ });
263
+ }
264
+ /** What the code checks a view for, said to the model as a rule beside the checklist. */
265
+ const CHECKLIST_RULE = "Cover every line of checklist: show each record with each of its must_show words (a date may be said as the page said it, a status in its own words), under its heading where it has one. The code checks every line and refuses a view that misses one.";
266
+ /** THE CHECKLIST a new design must cover, a line per record: what it must show beside its name, and the heading it sits under. */
267
+ export function checklistOf(keep) {
268
+ return keep.records.map((record) => {
269
+ const said = keep.says?.[record];
270
+ return { record, ...(said?.id ? { id: said.id } : {}), ...(said?.shows?.length ? { must_show: said.shows } : {}), ...(said?.under ? { under: said.under } : {}) };
271
+ });
272
+ }
273
+ /** How the page grouped its records, as a rule the model can write: which link names the heading. */
274
+ export function groupingRule(grouping) {
275
+ const [mine, theirs] = grouping.record === "from" ? ["from", "to"] : ["to", "from"];
276
+ return `Group the records as the page did: each record sits under a heading that is the label of the ${grouping.kind} it is linked to — find the edge in props.edges with kind "${grouping.edge}" whose ${mine} is the record's id; the ${grouping.kind} is props.nodes' node whose id is the edge's ${theirs}. Draw the headings in keep_these_headings' order; never guess a record's group from its fields.`;
277
+ }
278
+ /** The model's view read: the script and its few words; undefined when it is not one. */
279
+ export function readPageViewReply(text) {
280
+ const parsed = jsonOf(text);
281
+ const given = parsed?.["source"];
282
+ // A script wrapped as a page would wrap it (`<script>…</script>`, a code fence) is the script inside.
283
+ const source = typeof given === "string" ? given.trim().replace(/^```(?:js|javascript)?\s*/i, "").replace(/\s*```$/, "").replace(/^<script[^>]*>\s*/i, "").replace(/\s*<\/script>\s*$/i, "") : undefined;
284
+ if (typeof source !== "string" || !/graview\.(render|onProps)/.test(source))
285
+ return undefined;
286
+ return { source, said: typeof parsed["said"] === "string" ? parsed["said"].trim() : "" };
287
+ }
288
+ /**
289
+ * Who is asked, try by try: the light model, then at most two light
290
+ * repairs with what broke — the full model is never in the loop a person
291
+ * waits on, only behind Try harder (`harder`), once. Where only the full
292
+ * model is lent, it is asked once.
293
+ */
294
+ export function repairTries(light, full, options = {}) {
295
+ if (options.harder)
296
+ return full ? [full] : light ? [light] : [];
297
+ if (light)
298
+ return [light, light, light];
299
+ return full ? [full] : [];
300
+ }
301
+ /** How long a person waits on the light model's tries together before the card says plainly what it could not keep. */
302
+ export const DRAFT_WITHIN_MS = 30_000;
303
+ /** A model's answer, raced against the time left and a cancel: the answer, "late", or "canceled". */
304
+ export async function inTime(answer, ms, signal) {
305
+ if (signal?.aborted)
306
+ return "canceled";
307
+ let timer;
308
+ let cancel;
309
+ const raced = await Promise.race([
310
+ answer.then((value) => ({ value })),
311
+ ...(ms !== undefined ? [new Promise((done) => (timer = setTimeout(() => done("late"), Math.max(0, ms))))] : []),
312
+ ...(signal ? [new Promise((done) => signal.addEventListener("abort", (cancel = () => done("canceled")), { once: true }))] : []),
313
+ ]);
314
+ if (timer)
315
+ clearTimeout(timer);
316
+ if (cancel)
317
+ signal?.removeEventListener("abort", cancel);
318
+ return raced;
319
+ }
320
+ /** What the card says where no version passed: plain, and never the findings. */
321
+ export const COULD_NOT = "I couldn't make a version that looks right.";
322
+ /**
323
+ * THE PAGE AS A VIEW OF ITS OWN, revised as asked: the light model first,
324
+ * judged where nobody sees it; what breaks is handed back to the light
325
+ * model at most twice, with what broke, all within `within` (30 s). A
326
+ * version that never passes stops there and says what it could not keep
327
+ * (`couldNotKeep`), with the last try and its findings for Try harder —
328
+ * the full model once, from there (`harder`, `from`), until it answers or
329
+ * is canceled. Nothing that did not pass is shown.
330
+ */
331
+ export async function draftPageView(options) {
332
+ const stages = [];
333
+ const light = options.ai.off ? undefined : options.ai.light;
334
+ const full = thinkingOf(options.ai);
335
+ const tries = repairTries(light, full, options.harder ? { harder: true } : {});
336
+ if (tries.length === 0)
337
+ return { ok: false, refused: options.ai.withoutModel ?? "Changing how a page looks needs AI, and none is on here.", findings: [], stages };
338
+ const ask = asker(stages);
339
+ const base = { part: options.part, manifest: options.manifest, mode: options.mode, outline: options.outline, data: options.data, ...(options.words ? { words: options.words } : {}), ...(options.highlighted ? { highlighted: options.highlighted } : {}), ...(options.current ? { current: options.current } : {}), ...(options.keep ? { keep: options.keep } : {}), ...(options.markup ? { markup: options.markup } : {}) };
340
+ /* The light model's tries share one wait (30 s); Try harder has none but the person's Cancel. */
341
+ const began = Date.now();
342
+ const within = options.harder ? undefined : (options.within ?? DRAFT_WITHIN_MS);
343
+ let findings = options.from?.findings ?? [];
344
+ let last = options.from ? { source: options.from.source, said: "" } : undefined;
345
+ const stopped = (extra = {}) => ({ ok: false, refused: couldNotKeep(findings), findings, ...(last ? { last: last.source } : {}), ...extra, stages });
346
+ for (let at = 0; at < tries.length; at++) {
347
+ const provider = tries[at];
348
+ const left = within === undefined ? undefined : within - (Date.now() - began);
349
+ // A repair that could not finish in the time left is not started: the card says what it could not keep now.
350
+ if (left !== undefined && at > 0 && left < 3_000)
351
+ return stopped({ late: true });
352
+ if (at > 0 || options.from)
353
+ options.repairing?.(findings);
354
+ const prompt = pageViewPrompt(findings.length === 0 || !last ? base : { ...base, findings, last: { source: last.source.slice(0, 6000) } });
355
+ const answered = await inTime(ask(provider, provider === light ? "light" : "thinking", PAGE_VIEW_SYSTEM, prompt), left, options.signal);
356
+ if (answered === "canceled")
357
+ return stopped({ canceled: true });
358
+ if (answered === "late")
359
+ return stopped({ late: true });
360
+ const view = answered.value === undefined ? undefined : readPageViewReply(answered.value);
361
+ if (!view) {
362
+ findings = ["The answer was not one JSON object with the whole script in `source`."];
363
+ continue;
364
+ }
365
+ last = view;
366
+ const stripped = cssFindings(view.source);
367
+ if (stripped.length > 0)
368
+ findings = stripped;
369
+ else {
370
+ // Judging draws it where nobody sees it: that, too, is inside the wait.
371
+ const judged = await inTime(options.judge(view.source), within === undefined ? undefined : within - (Date.now() - began), options.signal);
372
+ if (judged === "canceled")
373
+ return stopped({ canceled: true });
374
+ if (judged === "late")
375
+ return stopped({ late: true });
376
+ findings = judged.value;
377
+ }
378
+ if (findings.length === 0)
379
+ return { ok: true, source: view.source, said: view.said, repaired: at > 0 || Boolean(options.from), tries: at + 1, stages };
380
+ }
381
+ return stopped();
382
+ }
383
+ //# sourceMappingURL=page-better.js.map