codeassembly-agent-logic 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/.meta/changelog.json +77 -0
  2. package/CHANGELOG.md +28 -0
  3. package/LICENSE +7 -0
  4. package/README.md +85 -2
  5. package/bin/agent-logic.js +26 -0
  6. package/dist/esm/cli/check-coverage-command.d.ts +3 -0
  7. package/dist/esm/cli/check-coverage-command.js +99 -0
  8. package/dist/esm/cli/convert-command.d.ts +3 -0
  9. package/dist/esm/cli/convert-command.js +116 -0
  10. package/dist/esm/cli/find-package-root.d.ts +7 -0
  11. package/dist/esm/cli/find-package-root.js +31 -0
  12. package/dist/esm/cli/index.d.ts +1 -0
  13. package/dist/esm/cli/index.js +11 -0
  14. package/dist/esm/cli/run.d.ts +8 -0
  15. package/dist/esm/cli/run.js +62 -0
  16. package/dist/esm/contract/built-in-harnesses.d.ts +22 -0
  17. package/dist/esm/contract/built-in-harnesses.js +30 -0
  18. package/dist/esm/contract/conversion-job.d.ts +36 -0
  19. package/dist/esm/contract/conversion-job.js +17 -0
  20. package/dist/esm/contract/index.d.ts +4 -0
  21. package/dist/esm/contract/index.js +3 -0
  22. package/dist/esm/contract/viewer-contract.d.ts +804 -0
  23. package/dist/esm/contract/viewer-contract.js +38 -0
  24. package/dist/esm/convert/convert-prompt.d.ts +21 -0
  25. package/dist/esm/convert/convert-prompt.js +60 -0
  26. package/dist/esm/convert/draft-schema.d.ts +308 -0
  27. package/dist/esm/convert/draft-schema.js +57 -0
  28. package/dist/esm/convert/find-gate-spans.d.ts +6 -0
  29. package/dist/esm/convert/find-gate-spans.js +18 -0
  30. package/dist/esm/convert/format-state-name.d.ts +6 -0
  31. package/dist/esm/convert/format-state-name.js +6 -0
  32. package/dist/esm/convert/normalize-config.d.ts +11 -0
  33. package/dist/esm/convert/normalize-config.js +164 -0
  34. package/dist/esm/convert/resolve-quotes.d.ts +18 -0
  35. package/dist/esm/convert/resolve-quotes.js +169 -0
  36. package/dist/esm/convert/sanitize-name.d.ts +5 -0
  37. package/dist/esm/convert/sanitize-name.js +8 -0
  38. package/dist/esm/coverage-map/check-coverage.d.ts +20 -0
  39. package/dist/esm/coverage-map/check-coverage.js +21 -0
  40. package/dist/esm/coverage-map/coverage-map-schema.d.ts +11 -0
  41. package/dist/esm/coverage-map/coverage-map-schema.js +2 -0
  42. package/dist/esm/coverage-map/find-prompt-blocks.d.ts +15 -0
  43. package/dist/esm/coverage-map/find-prompt-blocks.js +140 -0
  44. package/dist/esm/examples/change-approval.d.ts +2 -0
  45. package/dist/esm/examples/change-approval.js +438 -0
  46. package/dist/esm/examples/examples.d.ts +9 -0
  47. package/dist/esm/examples/examples.js +8 -0
  48. package/dist/esm/examples/password-reset.d.ts +2 -0
  49. package/dist/esm/examples/password-reset.js +235 -0
  50. package/dist/esm/examples/refund-request.d.ts +2 -0
  51. package/dist/esm/examples/refund-request.js +233 -0
  52. package/dist/esm/index.d.ts +13 -0
  53. package/dist/esm/index.js +12 -0
  54. package/dist/esm/layout/build-elk-graph.d.ts +18 -0
  55. package/dist/esm/layout/build-elk-graph.js +96 -0
  56. package/dist/esm/layout/card-limits.d.ts +8 -0
  57. package/dist/esm/layout/card-limits.js +4 -0
  58. package/dist/esm/layout/describe-config.d.ts +118 -0
  59. package/dist/esm/layout/describe-config.js +199 -0
  60. package/dist/esm/layout/layout-config.d.ts +5 -0
  61. package/dist/esm/layout/layout-config.js +73 -0
  62. package/dist/esm/layout/layout-metrics.d.ts +6 -0
  63. package/dist/esm/layout/layout-metrics.js +6 -0
  64. package/dist/esm/layout/pack-preamble.d.ts +20 -0
  65. package/dist/esm/layout/pack-preamble.js +66 -0
  66. package/dist/esm/layout/to-flow-elements.d.ts +46 -0
  67. package/dist/esm/layout/to-flow-elements.js +83 -0
  68. package/dist/esm/react/canvas/AmbientSelectionContext.d.ts +7 -0
  69. package/dist/esm/react/canvas/AmbientSelectionContext.js +5 -0
  70. package/dist/esm/react/canvas/DetailLevelContext.d.ts +3 -0
  71. package/dist/esm/react/canvas/DetailLevelContext.js +2 -0
  72. package/dist/esm/react/canvas/FocusNavigation.d.ts +8 -0
  73. package/dist/esm/react/canvas/FocusNavigation.js +92 -0
  74. package/dist/esm/react/canvas/StateNode.d.ts +5 -0
  75. package/dist/esm/react/canvas/StateNode.js +91 -0
  76. package/dist/esm/react/canvas/StatechartCanvas.d.ts +16 -0
  77. package/dist/esm/react/canvas/StatechartCanvas.js +184 -0
  78. package/dist/esm/react/canvas/TransitionEdge.d.ts +5 -0
  79. package/dist/esm/react/canvas/TransitionEdge.js +22 -0
  80. package/dist/esm/react/canvas/canvas-key-entries.d.ts +14 -0
  81. package/dist/esm/react/canvas/canvas-key-entries.js +51 -0
  82. package/dist/esm/react/canvas/find-element-box.d.ts +8 -0
  83. package/dist/esm/react/canvas/find-element-box.js +25 -0
  84. package/dist/esm/react/canvas/find-view-centre.d.ts +15 -0
  85. package/dist/esm/react/canvas/find-view-centre.js +16 -0
  86. package/dist/esm/react/canvas/list-chart-marks.d.ts +5 -0
  87. package/dist/esm/react/canvas/list-chart-marks.js +37 -0
  88. package/dist/esm/react/canvas/marks.d.ts +19 -0
  89. package/dist/esm/react/canvas/marks.js +24 -0
  90. package/dist/esm/react/canvas/useNewLayout.d.ts +17 -0
  91. package/dist/esm/react/canvas/useNewLayout.js +44 -0
  92. package/dist/esm/react/canvas/zoom-levels.d.ts +28 -0
  93. package/dist/esm/react/canvas/zoom-levels.js +54 -0
  94. package/dist/esm/react/hooks/conversion-client.d.ts +77 -0
  95. package/dist/esm/react/hooks/conversion-client.js +132 -0
  96. package/dist/esm/react/hooks/describe-agent-selection.d.ts +6 -0
  97. package/dist/esm/react/hooks/describe-agent-selection.js +18 -0
  98. package/dist/esm/react/hooks/describe-load-outcome.d.ts +13 -0
  99. package/dist/esm/react/hooks/describe-load-outcome.js +30 -0
  100. package/dist/esm/react/hooks/download-config.d.ts +6 -0
  101. package/dist/esm/react/hooks/download-config.js +11 -0
  102. package/dist/esm/react/hooks/example-location.d.ts +7 -0
  103. package/dist/esm/react/hooks/example-location.js +14 -0
  104. package/dist/esm/react/hooks/label-source.d.ts +21 -0
  105. package/dist/esm/react/hooks/label-source.js +19 -0
  106. package/dist/esm/react/hooks/parse-config-text.d.ts +16 -0
  107. package/dist/esm/react/hooks/parse-config-text.js +38 -0
  108. package/dist/esm/react/hooks/useAgentBridge.d.ts +28 -0
  109. package/dist/esm/react/hooks/useAgentBridge.js +52 -0
  110. package/dist/esm/react/hooks/useAgentSync.d.ts +29 -0
  111. package/dist/esm/react/hooks/useAgentSync.js +75 -0
  112. package/dist/esm/react/hooks/useChartLayout.d.ts +25 -0
  113. package/dist/esm/react/hooks/useChartLayout.js +29 -0
  114. package/dist/esm/react/hooks/useConversion.d.ts +31 -0
  115. package/dist/esm/react/hooks/useConversion.js +177 -0
  116. package/dist/esm/react/hooks/useConvertDraft.d.ts +18 -0
  117. package/dist/esm/react/hooks/useConvertDraft.js +11 -0
  118. package/dist/esm/react/hooks/useDocumentTitle.d.ts +2 -0
  119. package/dist/esm/react/hooks/useDocumentTitle.js +7 -0
  120. package/dist/esm/react/hooks/useEscapeToClear.d.ts +2 -0
  121. package/dist/esm/react/hooks/useEscapeToClear.js +16 -0
  122. package/dist/esm/react/hooks/useHarnessList.d.ts +26 -0
  123. package/dist/esm/react/hooks/useHarnessList.js +24 -0
  124. package/dist/esm/react/hooks/usePromptDirectory.d.ts +27 -0
  125. package/dist/esm/react/hooks/usePromptDirectory.js +34 -0
  126. package/dist/esm/react/hooks/useSelection.d.ts +17 -0
  127. package/dist/esm/react/hooks/useSelection.js +21 -0
  128. package/dist/esm/react/hooks/useShowAmbient.d.ts +7 -0
  129. package/dist/esm/react/hooks/useShowAmbient.js +22 -0
  130. package/dist/esm/react/hooks/useUnknownExample.d.ts +7 -0
  131. package/dist/esm/react/hooks/useUnknownExample.js +26 -0
  132. package/dist/esm/react/index.d.ts +24 -0
  133. package/dist/esm/react/index.js +23 -0
  134. package/dist/esm/react/styles.css +482 -0
  135. package/dist/esm/schema/agent-logic-schema.d.ts +439 -0
  136. package/dist/esm/schema/agent-logic-schema.js +100 -0
  137. package/dist/esm/schema/config-traversal.d.ts +19 -0
  138. package/dist/esm/schema/config-traversal.js +32 -0
  139. package/dist/esm/schema/validate-config.d.ts +17 -0
  140. package/dist/esm/schema/validate-config.js +205 -0
  141. package/dist/esm/schema/write-json-schema.d.ts +4 -0
  142. package/dist/esm/schema/write-json-schema.js +12 -0
  143. package/dist/esm/server/conversion-job-implementation.d.ts +11 -0
  144. package/dist/esm/server/conversion-job-implementation.js +84 -0
  145. package/dist/esm/server/create-prompts-app.d.ts +26 -0
  146. package/dist/esm/server/create-prompts-app.js +41 -0
  147. package/dist/esm/server/create-viewer-server-plugins.d.ts +15 -0
  148. package/dist/esm/server/create-viewer-server-plugins.js +76 -0
  149. package/dist/esm/server/index.d.ts +7 -0
  150. package/dist/esm/server/index.js +6 -0
  151. package/dist/esm/server/prompt-directory-schemas.d.ts +30 -0
  152. package/dist/esm/server/prompt-directory-schemas.js +11 -0
  153. package/dist/esm/server/prompt-directory.d.ts +40 -0
  154. package/dist/esm/server/prompt-directory.js +86 -0
  155. package/dist/esm/server/viewer-contract-implementation.d.ts +12 -0
  156. package/dist/esm/server/viewer-contract-implementation.js +85 -0
  157. package/dist/esm/source/fence.d.ts +16 -0
  158. package/dist/esm/source/fence.js +15 -0
  159. package/dist/esm/source/find-comment-spans.d.ts +6 -0
  160. package/dist/esm/source/find-comment-spans.js +60 -0
  161. package/dist/esm/source/find-occurrences.d.ts +2 -0
  162. package/dist/esm/source/find-occurrences.js +7 -0
  163. package/dist/esm/source/prompt-segments.d.ts +21 -0
  164. package/dist/esm/source/prompt-segments.js +65 -0
  165. package/docs/conversion-agreement.md +37 -0
  166. package/docs/extraction-rules.md +123 -0
  167. package/package.json +105 -3
  168. package/schema/agent-logic.schema.json +475 -0
@@ -0,0 +1,28 @@
1
+ import { type FitViewOptions, type Rect } from '@xyflow/react';
2
+ import type { FlowNameSite } from '../../layout/to-flow-elements.js';
3
+ /** How much of the canvas's text is drawn at a zoom: all of it, only the 14px text, or none, leaving shapes. */
4
+ export type DetailLevel = 'all-text' | 'large-text' | 'shapes';
5
+ export declare const LARGE_TEXT_MIN_ZOOM: number;
6
+ export declare const SMALL_TEXT_MIN_ZOOM: number;
7
+ /** The zoom at which a state shown as a box is centred when clicked. */
8
+ export declare const READING_ZOOM = 1;
9
+ export declare const FIT_PADDING: NonNullable<FitViewOptions['padding']>;
10
+ /** Returns the detail level at a zoom. */
11
+ export declare function findDetailLevel(zoom: number): DetailLevel;
12
+ /** The screen height of a flow's name, its padding included, which `styles.css` holds at every zoom. */
13
+ export declare const FLOW_NAME_HEIGHT = 24;
14
+ /** Estimates the screen width of a flow's name. */
15
+ export declare function estimateFlowNameWidth(name: string): number;
16
+ /** Where a flow's name sits at a zoom: how far, in canvas units, it moves right, and whether it is shown at all. */
17
+ export interface FlowNamePlacement {
18
+ shift: number;
19
+ isShown: boolean;
20
+ }
21
+ /**
22
+ * Returns where each flow's name sits at a zoom. Each name sits above its flow's top edge at a fixed screen size and,
23
+ * taking the flows in order, moves past every name already placed that it would overlap. A name that would then start
24
+ * at or past its flow's right edge would name nothing, so it is hidden, and later names do not move past it.
25
+ */
26
+ export declare function placeFlowNames(sites: readonly FlowNameSite[], zoom: number): Map<string, FlowNamePlacement>;
27
+ /** Returns the zoom that fits the bounds in a canvas of the given size, capped at the reading zoom. */
28
+ export declare function findFitZoom(bounds: Rect, width: number, height: number): number;
@@ -0,0 +1,54 @@
1
+ import { getViewportForBounds } from '@xyflow/react';
2
+ export const LARGE_TEXT_MIN_ZOOM = 9 / 14;
3
+ export const SMALL_TEXT_MIN_ZOOM = 9 / 12;
4
+ export const READING_ZOOM = 1;
5
+ export const FIT_PADDING = {
6
+ top: '40px',
7
+ right: '16px',
8
+ bottom: '16px',
9
+ left: '16px',
10
+ };
11
+ export function findDetailLevel(zoom) {
12
+ if (zoom >= SMALL_TEXT_MIN_ZOOM)
13
+ return 'all-text';
14
+ if (zoom >= LARGE_TEXT_MIN_ZOOM)
15
+ return 'large-text';
16
+ return 'shapes';
17
+ }
18
+ export const FLOW_NAME_HEIGHT = 24;
19
+ const FLOW_NAME_CHARACTER_WIDTH = 7.5;
20
+ const FLOW_NAME_MAX_WIDTH = 360;
21
+ const FLOW_NAME_GAP = 12;
22
+ export function estimateFlowNameWidth(name) {
23
+ return Math.min(FLOW_NAME_MAX_WIDTH, Math.ceil(name.length * FLOW_NAME_CHARACTER_WIDTH));
24
+ }
25
+ export function placeFlowNames(sites, zoom) {
26
+ const placed = [];
27
+ const placements = new Map();
28
+ for (const { id, name, x, y, width: flowWidth } of sites) {
29
+ const width = estimateFlowNameWidth(name);
30
+ const top = y * zoom - FLOW_NAME_HEIGHT;
31
+ let left = x * zoom;
32
+ let blocker = findBlocker(placed, left, left + width, top);
33
+ while (blocker !== undefined) {
34
+ left = blocker.right + FLOW_NAME_GAP;
35
+ blocker = findBlocker(placed, left, left + width, top);
36
+ }
37
+ const isShown = left < (x + flowWidth) * zoom;
38
+ if (isShown)
39
+ placed.push({ left, right: left + width, top });
40
+ placements.set(id, { shift: isShown ? (left - x * zoom) / zoom : 0, isShown });
41
+ }
42
+ return placements;
43
+ }
44
+ export function findFitZoom(bounds, width, height) {
45
+ if (width <= 0 || height <= 0 || bounds.width <= 0 || bounds.height <= 0)
46
+ return READING_ZOOM;
47
+ return getViewportForBounds(bounds, width, height, Number.MIN_VALUE, READING_ZOOM, FIT_PADDING).zoom;
48
+ }
49
+ function findBlocker(placed, left, right, top) {
50
+ return placed.find((other) => left < other.right + FLOW_NAME_GAP &&
51
+ other.left < right + FLOW_NAME_GAP &&
52
+ top < other.top + FLOW_NAME_HEIGHT &&
53
+ other.top < top + FLOW_NAME_HEIGHT);
54
+ }
@@ -0,0 +1,77 @@
1
+ import { type HarnessList, type HarnessTestResult } from '@williamthorsen/telefactor/client';
2
+ import { type ConversionJob, type ConversionRequest } from '../../contract/conversion-job.js';
3
+ import type { Problem } from '../../schema/validate-config.js';
4
+ import { type PromptList } from '../../server/prompt-directory-schemas.js';
5
+ /**
6
+ * A request's outcome. `not-found` is a `404`, which the page reads as the server no longer having the job, and
7
+ * `finished` is a cancel that came after the job ended; `failed` covers every other failure, the problems naming why.
8
+ */
9
+ export type ClientResult = {
10
+ ok: true;
11
+ job: ConversionJob;
12
+ } | {
13
+ ok: false;
14
+ reason: 'failed' | 'finished' | 'not-found';
15
+ problems: Problem[];
16
+ };
17
+ /** The harnesses that the server offers, or the problems that kept the page from reading them. */
18
+ export type HarnessListOutcome = {
19
+ ok: true;
20
+ list: HarnessList;
21
+ } | {
22
+ ok: false;
23
+ problems: Problem[];
24
+ };
25
+ /** A harness test's result, or the problems that kept it from running; `cancelled` marks a test that the page aborted. */
26
+ export type HarnessTestOutcome = {
27
+ ok: true;
28
+ result: HarnessTestResult;
29
+ } | {
30
+ ok: false;
31
+ cancelled: boolean;
32
+ problems: Problem[];
33
+ };
34
+ /**
35
+ * The prompts directory's listing, or why the page has none: `absent` when the server does not serve the directory,
36
+ * `malformed` with the problems of a config file that the server cannot use, and `failed` for every other failure.
37
+ */
38
+ export type PromptListOutcome = {
39
+ ok: true;
40
+ list: PromptList;
41
+ } | {
42
+ ok: false;
43
+ reason: 'absent' | 'failed' | 'malformed';
44
+ problems: Problem[];
45
+ };
46
+ /** The text of a file in the prompts directory, or the problems that kept the page from reading it. */
47
+ export type PromptFileOutcome = {
48
+ ok: true;
49
+ text: string;
50
+ } | {
51
+ ok: false;
52
+ problems: Problem[];
53
+ };
54
+ /**
55
+ * Starts, reads, and cancels conversions on the conversion server, lists and tests its harnesses, and lists and reads
56
+ * its prompts directory.
57
+ */
58
+ export interface ConversionClient {
59
+ cancel(id: string): Promise<ClientResult>;
60
+ listHarnesses(): Promise<HarnessListOutcome>;
61
+ listPrompts(): Promise<PromptListOutcome>;
62
+ read(id: string): Promise<ClientResult>;
63
+ readPromptFile(fileName: string): Promise<PromptFileOutcome>;
64
+ start(request: ConversionRequest): Promise<ClientResult>;
65
+ testHarness(name: string, signal: AbortSignal): Promise<HarnessTestOutcome>;
66
+ }
67
+ interface ConversionClientOptions {
68
+ /** The server's origin, under which telefactor's routes are served at `/api/telefactor` and the prompts at `/api/prompts`. */
69
+ baseUrl: string;
70
+ fetch?: typeof globalThis.fetch;
71
+ }
72
+ /**
73
+ * Creates a client for the conversion server: telefactor's client for the job and harness routes, and requests of its
74
+ * own for the prompts routes.
75
+ */
76
+ export declare function createConversionClient({ baseUrl, fetch, }: ConversionClientOptions): ConversionClient;
77
+ export {};
@@ -0,0 +1,132 @@
1
+ import { createTelefactorClient, TelefactorRequestError, } from '@williamthorsen/telefactor/client';
2
+ import { describeError } from '@williamthorsen/toolbelt.errors';
3
+ import { z } from 'zod';
4
+ import { conversionJob } from "../../contract/conversion-job.js";
5
+ import { promptFileSchema, promptListSchema } from "../../server/prompt-directory-schemas.js";
6
+ export function createConversionClient({ baseUrl, fetch = globalThis.fetch.bind(globalThis), }) {
7
+ const apiRoot = `${baseUrl.replace(/\/+$/, '')}/api`;
8
+ const telefactorClient = createTelefactorClient({ basePath: `${apiRoot}/telefactor`, fetch, job: conversionJob });
9
+ async function receive(url) {
10
+ let response;
11
+ try {
12
+ response = await fetch(url, { method: 'GET' });
13
+ }
14
+ catch (error) {
15
+ return { ok: false, notJsonStatus: undefined, problems: toProblems(describeUnreachable(error)) };
16
+ }
17
+ try {
18
+ return { ok: true, status: response.status, body: await response.json() };
19
+ }
20
+ catch {
21
+ const message = `The conversion server answered ${response.status} with a body that is not JSON.`;
22
+ return { ok: false, notJsonStatus: response.status, problems: toProblems(message) };
23
+ }
24
+ }
25
+ return {
26
+ cancel(id) {
27
+ return sendJobRequest(() => telefactorClient.cancelJob(id));
28
+ },
29
+ async listHarnesses() {
30
+ try {
31
+ return { ok: true, list: await telefactorClient.listHarnesses() };
32
+ }
33
+ catch (error) {
34
+ return { ok: false, problems: describeFailure(error) };
35
+ }
36
+ },
37
+ async listPrompts() {
38
+ const received = await receive(`${apiRoot}/prompts`);
39
+ if (!received.ok)
40
+ return failPromptList(isPageInPlaceOfApi(received.notJsonStatus) ? 'absent' : 'failed', received.problems);
41
+ const { status, body } = received;
42
+ if (status === 200) {
43
+ const failed = failPromptListRead;
44
+ return readBody({ schema: promptListSchema, body, status, failed }, (list) => ({ ok: true, list }));
45
+ }
46
+ if (status === 400) {
47
+ const failed = failMalformedPromptList;
48
+ return readBody({ schema: problemsBodySchema, body, status, failed }, ({ problems }) => failed(problems));
49
+ }
50
+ const reason = status === 404 ? 'absent' : 'failed';
51
+ return failPromptList(reason, toProblems(`The conversion server answered ${status}.`));
52
+ },
53
+ read(id) {
54
+ return sendJobRequest(() => telefactorClient.getJob(id));
55
+ },
56
+ async readPromptFile(fileName) {
57
+ const received = await receive(`${apiRoot}/prompts/files/${encodeURIComponent(fileName)}`);
58
+ if (!received.ok)
59
+ return { ok: false, problems: received.problems };
60
+ const { status, body } = received;
61
+ const failed = failPromptFile;
62
+ if (status === 200) {
63
+ return readBody({ schema: promptFileSchema, body, status, failed }, ({ text }) => ({ ok: true, text }));
64
+ }
65
+ if (status === 400) {
66
+ return readBody({ schema: problemsBodySchema, body, status, failed }, ({ problems }) => failed(problems));
67
+ }
68
+ return readBody({ schema: errorBodySchema, body, status, failed }, ({ error }) => failed(toProblems(error)));
69
+ },
70
+ start(request) {
71
+ return sendJobRequest(() => telefactorClient.startJob(request));
72
+ },
73
+ async testHarness(name, signal) {
74
+ try {
75
+ return { ok: true, result: await telefactorClient.testHarness(name, { signal }) };
76
+ }
77
+ catch (error) {
78
+ if (signal.aborted)
79
+ return { ok: false, cancelled: true, problems: toProblems('The request was cancelled.') };
80
+ return { ok: false, cancelled: false, problems: describeFailure(error) };
81
+ }
82
+ },
83
+ };
84
+ }
85
+ const JOB_REASONS = { 404: 'not-found', 409: 'finished' };
86
+ const problemSchema = z.object({ path: z.string(), message: z.string() });
87
+ const problemsBodySchema = z.object({ problems: z.array(problemSchema) });
88
+ const errorBodySchema = z.object({ error: z.string() });
89
+ function describeFailure(error) {
90
+ if (error instanceof TelefactorRequestError) {
91
+ return error.problems.length > 0 ? error.problems : toProblems(error.message);
92
+ }
93
+ if (error instanceof z.ZodError)
94
+ return toProblems('The conversion server answered with a body of an unexpected shape.');
95
+ return toProblems(describeUnreachable(error));
96
+ }
97
+ function describeUnreachable(error) {
98
+ return `The conversion server could not be reached (${describeError(error)}).`;
99
+ }
100
+ function failMalformedPromptList(problems) {
101
+ return failPromptList('malformed', problems);
102
+ }
103
+ function failPromptFile(problems) {
104
+ return { ok: false, problems };
105
+ }
106
+ function failPromptList(reason, problems) {
107
+ return { ok: false, reason, problems };
108
+ }
109
+ function failPromptListRead(problems) {
110
+ return failPromptList('failed', problems);
111
+ }
112
+ function isPageInPlaceOfApi(notJsonStatus) {
113
+ return notJsonStatus !== undefined && notJsonStatus < 500;
114
+ }
115
+ function readBody({ schema, body, status, failed, }, toResult) {
116
+ const parsed = schema.safeParse(body);
117
+ return parsed.success
118
+ ? toResult(parsed.data)
119
+ : failed(toProblems(`The conversion server answered ${status} with a body of an unexpected shape.`));
120
+ }
121
+ async function sendJobRequest(request) {
122
+ try {
123
+ return { ok: true, job: await request() };
124
+ }
125
+ catch (error) {
126
+ const reason = error instanceof TelefactorRequestError ? (JOB_REASONS[error.status] ?? 'failed') : 'failed';
127
+ return { ok: false, reason, problems: describeFailure(error) };
128
+ }
129
+ }
130
+ function toProblems(message) {
131
+ return [{ path: '', message }];
132
+ }
@@ -0,0 +1,6 @@
1
+ import { type ConfigDescription } from '../../layout/describe-config.js';
2
+ /**
3
+ * Returns the announcement of a selection that the agent made, naming the element as the page shows it, or `undefined`
4
+ * when the chart does not contain the path.
5
+ */
6
+ export declare function describeAgentSelection(description: ConfigDescription, path: string | undefined): string | undefined;
@@ -0,0 +1,18 @@
1
+ import { buildTransitionLabel } from "../../layout/describe-config.js";
2
+ export function describeAgentSelection(description, path) {
3
+ if (path === undefined)
4
+ return 'Agent cleared the selection.';
5
+ const state = description.states.find((candidate) => candidate.path === path);
6
+ if (state !== undefined)
7
+ return `Agent selected ${state.name}.`;
8
+ const transition = description.transitions.find((candidate) => candidate.path === path);
9
+ if (transition !== undefined) {
10
+ const { trigger } = buildTransitionLabel(transition);
11
+ const route = `${transition.sourceName} to ${transition.targetName}`;
12
+ return `Agent selected the transition from ${route}${trigger === undefined ? '' : ` on ${trigger}`}.`;
13
+ }
14
+ const ambient = description.ambient.find((candidate) => candidate.path === path);
15
+ if (ambient !== undefined)
16
+ return `Agent selected an ambient instruction of ${ambient.containerName}.`;
17
+ return undefined;
18
+ }
@@ -0,0 +1,13 @@
1
+ import type { AgentLogicConfig } from '../../schema/agent-logic-schema.js';
2
+ import type { Problem } from '../../schema/validate-config.js';
3
+ /**
4
+ * Returns the announcement of a chart that loaded, with the counts of its unconverted passages, its gaps, and its
5
+ * findings.
6
+ */
7
+ export declare function describeLoaded(source: string, config: AgentLogicConfig): string;
8
+ /** Returns the announcement of a chart that the agent loaded, with the same counts as `describeLoaded`. */
9
+ export declare function describeLoadedByAgent(source: string, config: AgentLogicConfig): string;
10
+ /** Returns the announcement of a failed load: its problem, or the count of its problems. */
11
+ export declare function describeNotLoaded(source: string, problems: Problem[]): string;
12
+ /** Returns the message for a URL that names an example that does not exist, with the names of those that do. */
13
+ export declare function describeUnknownExample(value: string): string;
@@ -0,0 +1,30 @@
1
+ import { examples } from "../../examples/examples.js";
2
+ import { describeConfig, listGaps } from "../../layout/describe-config.js";
3
+ export function describeLoaded(source, config) {
4
+ return [`${source} loaded.`, ...countListed(config)].join(' ');
5
+ }
6
+ export function describeLoadedByAgent(source, config) {
7
+ return [`Agent loaded ${source}.`, ...countListed(config)].join(' ');
8
+ }
9
+ export function describeNotLoaded(source, problems) {
10
+ const [first, second] = problems;
11
+ if (first !== undefined && second === undefined)
12
+ return `${source} not loaded. ${first.message}`;
13
+ return `${source} not loaded. ${problems.length} problems listed.`;
14
+ }
15
+ export function describeUnknownExample(value) {
16
+ const names = new Intl.ListFormat('en', { type: 'conjunction' }).format(examples.map(({ name }) => name));
17
+ const problem = value === '' ? 'The URL names an empty example.' : `No example is named “${value}”.`;
18
+ return `${problem} The examples are ${names}.`;
19
+ }
20
+ function countListed(config) {
21
+ const { length } = config.meta.unconverted;
22
+ const description = describeConfig(config);
23
+ const gapCount = listGaps(description).length;
24
+ const findingCount = description.findings.length;
25
+ return [
26
+ ...(length === 0 ? [] : [`${length} unconverted ${length === 1 ? 'passage' : 'passages'} listed.`]),
27
+ ...(gapCount === 0 ? [] : [`${gapCount} ${gapCount === 1 ? 'gap' : 'gaps'} listed.`]),
28
+ ...(findingCount === 0 ? [] : [`${findingCount} ${findingCount === 1 ? 'finding' : 'findings'} listed.`]),
29
+ ];
30
+ }
@@ -0,0 +1,6 @@
1
+ import type { AgentLogicConfig } from '../../schema/agent-logic-schema.js';
2
+ /**
3
+ * Has the browser save the config under the given name as the `convert` script writes it, through a Blob URL and an
4
+ * anchor's click.
5
+ */
6
+ export declare function downloadConfig(fileName: string, config: AgentLogicConfig): void;
@@ -0,0 +1,11 @@
1
+ export function downloadConfig(fileName, config) {
2
+ const text = `${JSON.stringify(config, undefined, 2)}\n`;
3
+ const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
4
+ const anchor = document.createElement('a');
5
+ anchor.href = url;
6
+ anchor.download = fileName;
7
+ anchor.click();
8
+ setTimeout(() => {
9
+ URL.revokeObjectURL(url);
10
+ }, 0);
11
+ }
@@ -0,0 +1,7 @@
1
+ import { type Example } from '../../examples/examples.js';
2
+ /** Returns the URL search string that names the example, so that a link to it can be shared. */
3
+ export declare function buildExampleSearch(example: Example): string;
4
+ /** Returns the bundled example that a URL search string names, or `undefined` when it names none that exists. */
5
+ export declare function findExampleInSearch(search: string): Example | undefined;
6
+ /** Returns the `example` value of a URL search string when it names no bundled example, or `undefined` otherwise. */
7
+ export declare function findUnknownExampleInSearch(search: string): string | undefined;
@@ -0,0 +1,14 @@
1
+ import { examples } from "../../examples/examples.js";
2
+ export function buildExampleSearch(example) {
3
+ return `?${new URLSearchParams({ example: example.slug }).toString()}`;
4
+ }
5
+ export function findExampleInSearch(search) {
6
+ const slug = new URLSearchParams(search).get('example');
7
+ return examples.find((example) => example.slug === slug);
8
+ }
9
+ export function findUnknownExampleInSearch(search) {
10
+ const slug = new URLSearchParams(search).get('example');
11
+ if (slug === null || examples.some((example) => example.slug === slug))
12
+ return undefined;
13
+ return slug;
14
+ }
@@ -0,0 +1,21 @@
1
+ /** Where a chart came from. */
2
+ export type LoadOrigin = {
3
+ kind: 'example';
4
+ name: string;
5
+ slug: string;
6
+ } | {
7
+ kind: 'file';
8
+ fileName: string;
9
+ } | {
10
+ kind: 'paste';
11
+ } | {
12
+ kind: 'prompt';
13
+ name: string;
14
+ };
15
+ /** The line that names a chart's source on the page, and the name of the agent-logic file that saves the chart. */
16
+ export interface SourceLabel {
17
+ source: string;
18
+ downloadName: string;
19
+ }
20
+ /** Returns the source line and the saved file's name, `{base}.agent-logic.json`, of a chart from the origin given. */
21
+ export declare function labelSource(origin: LoadOrigin): SourceLabel;
@@ -0,0 +1,19 @@
1
+ import { sanitizeName } from "../../convert/sanitize-name.js";
2
+ export function labelSource(origin) {
3
+ const [source, base] = describe(origin);
4
+ return { source, downloadName: `${base}.agent-logic.json` };
5
+ }
6
+ function describe(origin) {
7
+ switch (origin.kind) {
8
+ case 'example':
9
+ return [`Example: ${origin.name}`, origin.slug];
10
+ case 'file': {
11
+ const base = origin.fileName.replace(/(?:\.agent-logic)?\.[^.]*$/, '');
12
+ return [`File: ${origin.fileName}`, base === '' ? 'agent-logic' : base];
13
+ }
14
+ case 'paste':
15
+ return ['Pasted JSON', 'pasted'];
16
+ case 'prompt':
17
+ return [`Prompt: ${origin.name}`, sanitizeName(origin.name)];
18
+ }
19
+ }
@@ -0,0 +1,16 @@
1
+ import type { Problem } from '../../schema/validate-config.js';
2
+ export type ParseResult = {
3
+ ok: true;
4
+ value: unknown;
5
+ } | {
6
+ ok: false;
7
+ isNotJson: boolean;
8
+ problems: Problem[];
9
+ };
10
+ /** Where the text came from, which decides how a problem names it and what it asks the user to do again. */
11
+ export type TextOrigin = 'conversion' | 'file' | 'paste';
12
+ /**
13
+ * Parses an agent-logic file's text as JSON, removing a Markdown code fence that encloses all of it. Text that begins
14
+ * like JSON and does not parse is reported as a syntax error; any other unparseable text, as text that is not JSON.
15
+ */
16
+ export declare function parseConfigText(text: string, origin: TextOrigin): ParseResult;
@@ -0,0 +1,38 @@
1
+ import { describeError } from '@williamthorsen/toolbelt.errors';
2
+ export function parseConfigText(text, origin) {
3
+ const json = removeEnclosingFence(text);
4
+ try {
5
+ const value = JSON.parse(json);
6
+ return { ok: true, value };
7
+ }
8
+ catch (error) {
9
+ const { subject, retry } = DESCRIPTIONS[origin];
10
+ if (!/^\s*[[{]/.test(json)) {
11
+ return {
12
+ ok: false,
13
+ isNotJson: true,
14
+ problems: [
15
+ {
16
+ path: '',
17
+ message: `${subject} is not JSON, so it is not an agent-logic file. To chart a prompt, convert it first.`,
18
+ },
19
+ ],
20
+ };
21
+ }
22
+ const detail = describeError(error);
23
+ return {
24
+ ok: false,
25
+ isNotJson: false,
26
+ problems: [{ path: '', message: `${subject} is not valid JSON (${detail}). Fix the syntax and ${retry}.` }],
27
+ };
28
+ }
29
+ }
30
+ const DESCRIPTIONS = {
31
+ conversion: { subject: 'The converted file', retry: 'convert the prompt again' },
32
+ file: { subject: 'The file', retry: 'open it again' },
33
+ paste: { subject: 'The pasted text', retry: 'load it again' },
34
+ };
35
+ const ENCLOSING_FENCE = /^```(?!`)[^\n`]*\r?\n([\s\S]*?)\r?\n```[ \t]*$/;
36
+ function removeEnclosingFence(text) {
37
+ return ENCLOSING_FENCE.exec(text.trim())?.[1] ?? text;
38
+ }
@@ -0,0 +1,28 @@
1
+ import type { ContractClient } from '@williamthorsen/telefactor/client';
2
+ import type { ContractState } from '@williamthorsen/telefactor/contract';
3
+ import type { viewerContract } from '../../contract/viewer-contract.js';
4
+ import type { AgentLogicConfig } from '../../schema/agent-logic-schema.js';
5
+ import type { SourceLabel } from './label-source.js';
6
+ export type ViewerContract = typeof viewerContract;
7
+ export type ViewerContractClient = ContractClient<ViewerContract>;
8
+ export type ViewerState = ContractState<ViewerContract>;
9
+ interface AgentBridgeHandlers {
10
+ /** Receives the session state once the dev server first answers. */
11
+ onConnect: (state: ViewerState) => void;
12
+ /** Receives each commit that the agent makes, with the name of the action that made it. */
13
+ onAgentChange: (action: string, state: ViewerState) => void;
14
+ }
15
+ /** The page's link to the session state that it shares with an agent. */
16
+ export interface AgentBridge {
17
+ /** Whether the dev server serves the contract; a built page never connects. */
18
+ isConnected: boolean;
19
+ publishChart: (label: SourceLabel, config: AgentLogicConfig) => void;
20
+ publishSelection: (path: string | undefined) => void;
21
+ }
22
+ /**
23
+ * Subscribes to the viewer's session state, reports the agent's commits, and publishes the page's loads and selections
24
+ * in the order in which the page makes them. A stream that fails before its first snapshot ends the subscription, as
25
+ * under `vite build` or `vite preview`, which do not serve the contract.
26
+ */
27
+ export declare function useAgentBridge(client: ViewerContractClient | undefined, handlers: AgentBridgeHandlers): AgentBridge;
28
+ export {};
@@ -0,0 +1,52 @@
1
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
2
+ export function useAgentBridge(client, handlers) {
3
+ const [isConnected, setIsConnected] = useState(false);
4
+ const handlersRef = useRef(handlers);
5
+ useLayoutEffect(() => {
6
+ handlersRef.current = handlers;
7
+ });
8
+ const isConnectedRef = useRef(false);
9
+ const queue = useRef(Promise.resolve());
10
+ useEffect(() => {
11
+ if (client === undefined)
12
+ return;
13
+ let hasSnapshot = false;
14
+ const unsubscribe = client.subscribe((snapshot) => {
15
+ if (!hasSnapshot) {
16
+ hasSnapshot = true;
17
+ isConnectedRef.current = true;
18
+ setIsConnected(true);
19
+ handlersRef.current.onConnect(snapshot.state);
20
+ return;
21
+ }
22
+ if (snapshot.change?.origin === 'agent')
23
+ handlersRef.current.onAgentChange(snapshot.change.action, snapshot.state);
24
+ }, {
25
+ onError: () => {
26
+ if (!hasSnapshot)
27
+ unsubscribe();
28
+ },
29
+ });
30
+ return unsubscribe;
31
+ }, [client]);
32
+ const send = useCallback((call) => {
33
+ if (client === undefined || !isConnectedRef.current)
34
+ return;
35
+ const previous = queue.current;
36
+ queue.current = (async () => {
37
+ await previous;
38
+ try {
39
+ await call(client);
40
+ }
41
+ catch {
42
+ }
43
+ })();
44
+ }, [client]);
45
+ const publishChart = useCallback((label, config) => {
46
+ send((connected) => connected.call('show_chart', { ...label, config }));
47
+ }, [send]);
48
+ const publishSelection = useCallback((path) => {
49
+ send((connected) => connected.call('select_element', path === undefined ? {} : { path }));
50
+ }, [send]);
51
+ return { isConnected, publishChart, publishSelection };
52
+ }
@@ -0,0 +1,29 @@
1
+ import type { AgentLogicConfig } from '../../schema/agent-logic-schema.js';
2
+ import type { SourceLabel } from './label-source.js';
3
+ import { type ViewerContractClient } from './useAgentBridge.js';
4
+ /** The page's operations that apply the agent's commits; the hook reads them when a commit arrives. */
5
+ export interface AgentSyncPage {
6
+ announce: (text: string) => void;
7
+ /** Returns the chart that the page shows, if any. */
8
+ readChart: () => (SourceLabel & {
9
+ config: AgentLogicConfig;
10
+ }) | undefined;
11
+ /** Shows a chart without a history entry. */
12
+ showChart: (label: SourceLabel, config: AgentLogicConfig) => void;
13
+ /** Shows a chart with a history entry of its own, as a conversion does. */
14
+ showLoadedInput: (label: SourceLabel, config: AgentLogicConfig) => void;
15
+ /** Selects an element, or clears the selection, and clears any passages shown. */
16
+ selectElement: (path: string | undefined) => void;
17
+ }
18
+ /** The page's link to the agent: whether it is connected, and the publishers that skip a commit being applied. */
19
+ export interface AgentSync {
20
+ isConnected: boolean;
21
+ publishChart: (label: SourceLabel, config: AgentLogicConfig) => void;
22
+ publishSelection: (path: string | undefined) => void;
23
+ }
24
+ /**
25
+ * Keeps the page and the session state that it shares with an agent in step: applies and announces the agent's
26
+ * commits through the page's operations, and on connect adopts the session's chart when the page shows none, else
27
+ * publishes the page's chart, which wins. A change made while a commit is applied is not published back.
28
+ */
29
+ export declare function useAgentSync(client: ViewerContractClient | undefined, page: AgentSyncPage): AgentSync;