codeassembly-agent-logic 0.0.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (169) hide show
  1. package/.meta/changelog.json +105 -0
  2. package/CHANGELOG.md +38 -0
  3. package/LICENSE +7 -0
  4. package/README.md +77 -1
  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 +14 -0
  53. package/dist/esm/index.js +13 -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/corpus.md +19 -0
  167. package/docs/extraction-rules.md +123 -0
  168. package/package.json +108 -2
  169. package/schema/agent-logic.schema.json +475 -0
@@ -0,0 +1,75 @@
1
+ import { useCallback, useRef } from 'react';
2
+ import { describeConfig } from "../../layout/describe-config.js";
3
+ import { describeAgentSelection } from "./describe-agent-selection.js";
4
+ import { describeLoadedByAgent } from "./describe-load-outcome.js";
5
+ import { findExampleInSearch } from "./example-location.js";
6
+ import { useAgentBridge } from "./useAgentBridge.js";
7
+ export function useAgentSync(client, page) {
8
+ const isApplying = useRef(false);
9
+ const bridge = useAgentBridge(client, {
10
+ onConnect: (state) => {
11
+ const pageChart = page.readChart();
12
+ if (pageChart !== undefined) {
13
+ bridge.publishChart(toLabel(pageChart), pageChart.config);
14
+ return;
15
+ }
16
+ const { chart } = state;
17
+ if (chart === undefined || findExampleInSearch(globalThis.location.search) !== undefined)
18
+ return;
19
+ applying(() => page.showChart(toLabel(chart), chart.config));
20
+ },
21
+ onAgentChange: (action, state) => {
22
+ applying(() => applyAgentChange(page, action, state));
23
+ },
24
+ });
25
+ function applying(change) {
26
+ isApplying.current = true;
27
+ try {
28
+ change();
29
+ }
30
+ finally {
31
+ isApplying.current = false;
32
+ }
33
+ }
34
+ const { isConnected, publishChart: sendChart, publishSelection: sendSelection } = bridge;
35
+ const publishChart = useCallback((label, config) => {
36
+ if (!isApplying.current)
37
+ sendChart(label, config);
38
+ }, [sendChart]);
39
+ const publishSelection = useCallback((path) => {
40
+ if (!isApplying.current)
41
+ sendSelection(path);
42
+ }, [sendSelection]);
43
+ return { isConnected, publishChart, publishSelection };
44
+ }
45
+ function applyAgentChange(page, action, state) {
46
+ switch (action) {
47
+ case 'load_chart':
48
+ case 'show_chart': {
49
+ if (state.chart === undefined)
50
+ return;
51
+ const { config } = state.chart;
52
+ page.showLoadedInput(toLabel(state.chart), config);
53
+ page.announce(describeLoadedByAgent(state.chart.source, config));
54
+ return;
55
+ }
56
+ case 'select_element': {
57
+ const pageChart = page.readChart();
58
+ if (pageChart === undefined)
59
+ return;
60
+ const text = describeAgentSelection(describeConfig(pageChart.config), state.selectedPath);
61
+ if (text === undefined)
62
+ return;
63
+ page.selectElement(state.selectedPath);
64
+ page.announce(text);
65
+ return;
66
+ }
67
+ case 'save_prompt':
68
+ if (state.savedPrompt !== undefined)
69
+ page.announce(`Agent saved ${state.savedPrompt.fileName}.`);
70
+ return;
71
+ }
72
+ }
73
+ function toLabel({ source, downloadName }) {
74
+ return { source, downloadName };
75
+ }
@@ -0,0 +1,25 @@
1
+ import type { FlowElements } from '../../layout/to-flow-elements.js';
2
+ import type { AgentLogicConfig } from '../../schema/agent-logic-schema.js';
3
+ /** A chart's layout, or why it failed, under the key of the load that it belongs to. */
4
+ export type ChartLayout = {
5
+ key: number;
6
+ elements: FlowElements;
7
+ } | {
8
+ key: number;
9
+ error: string;
10
+ };
11
+ /**
12
+ * Lays out the shown chart again whenever it or the preamble setting changes, keeping the previous layout until the
13
+ * new one is ready, and calls `onFail` when a layout fails.
14
+ */
15
+ export declare function useChartLayout({ chart, layout, showAmbient, onFail, }: {
16
+ chart: {
17
+ key: number;
18
+ config: AgentLogicConfig;
19
+ } | undefined;
20
+ layout: (config: AgentLogicConfig, options: {
21
+ showAmbient: boolean;
22
+ }) => Promise<FlowElements>;
23
+ showAmbient: boolean;
24
+ onFail: () => void;
25
+ }): ChartLayout | undefined;
@@ -0,0 +1,29 @@
1
+ import { describeError } from '@williamthorsen/toolbelt.errors';
2
+ import { useEffect, useState } from 'react';
3
+ export function useChartLayout({ chart, layout, showAmbient, onFail, }) {
4
+ const [laidOut, setLaidOut] = useState();
5
+ useEffect(() => {
6
+ if (chart === undefined)
7
+ return;
8
+ const { config, key } = chart;
9
+ let isCurrent = true;
10
+ void runLayout();
11
+ return () => {
12
+ isCurrent = false;
13
+ };
14
+ async function runLayout() {
15
+ try {
16
+ const elements = await layout(config, { showAmbient });
17
+ if (isCurrent)
18
+ setLaidOut({ key, elements });
19
+ }
20
+ catch (error) {
21
+ if (!isCurrent)
22
+ return;
23
+ setLaidOut({ key, error: describeError(error) });
24
+ onFail();
25
+ }
26
+ }
27
+ }, [chart, layout, onFail, showAmbient]);
28
+ return chart !== undefined && laidOut?.key === chart.key ? laidOut : undefined;
29
+ }
@@ -0,0 +1,31 @@
1
+ import type { ConversionRequest } from '../../contract/conversion-job.js';
2
+ import type { Problem } from '../../schema/validate-config.js';
3
+ import type { ConversionClient } from './conversion-client.js';
4
+ /** The time between two reads of a running job. */
5
+ export declare const POLL_INTERVAL_MS = 2000;
6
+ /** The `sessionStorage` key under which the running job's id and name are kept, so that a reload resumes it. */
7
+ export declare const CONVERSION_STORAGE_KEY = "agent-logic.conversion";
8
+ /** What the page does with a conversion's outcome, each call naming the prompt. */
9
+ export interface ConversionHandlers {
10
+ /** Learns that a conversion was cancelled, by the user or on the server. */
11
+ onCancelled: (name: string) => void;
12
+ /** Takes the agent-logic file's text of a conversion that succeeded. */
13
+ onConverted: (name: string, text: string) => void;
14
+ /** Takes the problems of a conversion that did not produce a file, or of a request that failed. */
15
+ onProblems: (name: string, problems: Problem[]) => void;
16
+ /** Learns that a conversion started running, or that the page resumed one after a reload. */
17
+ onRunning: (name: string) => void;
18
+ }
19
+ /** The running conversion, if any, and the functions that start and cancel one. */
20
+ export interface Conversion {
21
+ running: {
22
+ name: string;
23
+ } | undefined;
24
+ cancel: () => void;
25
+ start: (request: ConversionRequest) => void;
26
+ }
27
+ /**
28
+ * Runs one conversion at a time on the conversion server, polling it until it ends. Starting another cancels the
29
+ * current one. The running job's id is kept in `sessionStorage`, and the page resumes it when it loads.
30
+ */
31
+ export declare function useConversion(client: ConversionClient, handlers: ConversionHandlers): Conversion;
@@ -0,0 +1,177 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ export const POLL_INTERVAL_MS = 2000;
3
+ export const CONVERSION_STORAGE_KEY = 'agent-logic.conversion';
4
+ export function useConversion(client, handlers) {
5
+ const [running, setRunning] = useState();
6
+ const clientRef = useRef(client);
7
+ const handlersRef = useRef(handlers);
8
+ useEffect(() => {
9
+ clientRef.current = client;
10
+ handlersRef.current = handlers;
11
+ });
12
+ const runRef = useRef(0);
13
+ const currentRef = useRef(undefined);
14
+ const timerRef = useRef(undefined);
15
+ useEffect(() => {
16
+ const stored = readStoredJob();
17
+ if (stored !== undefined) {
18
+ const run = begin(stored);
19
+ void poll(stored, run, { isResumed: true });
20
+ }
21
+ return () => {
22
+ runRef.current += 1;
23
+ clearTimeout(timerRef.current);
24
+ };
25
+ }, []);
26
+ function begin(job) {
27
+ runRef.current += 1;
28
+ clearTimeout(timerRef.current);
29
+ currentRef.current = job;
30
+ setRunning({ name: job.name });
31
+ return runRef.current;
32
+ }
33
+ function end() {
34
+ runRef.current += 1;
35
+ clearTimeout(timerRef.current);
36
+ currentRef.current = undefined;
37
+ setRunning(undefined);
38
+ writeStoredJob(undefined);
39
+ }
40
+ function follow(job, name, run, { isResumed }) {
41
+ if (job.status === 'running') {
42
+ const isNew = currentRef.current?.id !== job.id || isResumed;
43
+ currentRef.current = { id: job.id, name };
44
+ writeStoredJob({ id: job.id, name });
45
+ if (isNew)
46
+ handlersRef.current.onRunning(name);
47
+ timerRef.current = setTimeout(() => {
48
+ void poll({ id: job.id, name }, run, { isResumed: false });
49
+ }, POLL_INTERVAL_MS);
50
+ return;
51
+ }
52
+ end();
53
+ settle(job, name);
54
+ }
55
+ async function poll(job, run, options) {
56
+ const result = await clientRef.current.read(job.id);
57
+ if (run !== runRef.current)
58
+ return;
59
+ if (result.ok) {
60
+ follow(result.job, job.name, run, options);
61
+ return;
62
+ }
63
+ end();
64
+ if (options.isResumed && result.reason === 'not-found')
65
+ return;
66
+ report(job.name, result);
67
+ }
68
+ function report(name, result) {
69
+ handlersRef.current.onProblems(name, result.reason === 'not-found'
70
+ ? [
71
+ {
72
+ path: '',
73
+ message: 'The conversion server no longer has the conversion, as after a restart. Convert the prompt again.',
74
+ },
75
+ ]
76
+ : result.problems);
77
+ }
78
+ function settle(job, name) {
79
+ const { onCancelled, onConverted, onProblems } = handlersRef.current;
80
+ if (job.status === 'cancelled')
81
+ onCancelled(name);
82
+ else if (job.status === 'done' && job.result?.ok === true)
83
+ onConverted(name, job.result.text);
84
+ else if (job.status === 'done' && job.result !== undefined && 'outOfScope' in job.result)
85
+ onProblems(name, [{ path: '', message: `Out of scope: ${job.result.outOfScope.reason}` }]);
86
+ else if (job.status === 'done' && job.result !== undefined && 'problems' in job.result)
87
+ onProblems(name, job.result.problems);
88
+ else
89
+ onProblems(name, [{ path: '', message: describeEnd(job) }]);
90
+ }
91
+ async function start(request) {
92
+ const previous = currentRef.current;
93
+ if (previous?.id !== undefined)
94
+ void clientRef.current.cancel(previous.id);
95
+ const run = begin({ name: request.name });
96
+ const result = await clientRef.current.start(request);
97
+ if (run !== runRef.current) {
98
+ if (result.ok)
99
+ void clientRef.current.cancel(result.job.id);
100
+ return;
101
+ }
102
+ if (result.ok) {
103
+ follow(result.job, request.name, run, { isResumed: false });
104
+ return;
105
+ }
106
+ end();
107
+ report(request.name, result);
108
+ }
109
+ async function cancel() {
110
+ const current = currentRef.current;
111
+ if (current === undefined)
112
+ return;
113
+ end();
114
+ if (current.id === undefined) {
115
+ handlersRef.current.onCancelled(current.name);
116
+ return;
117
+ }
118
+ const result = await clientRef.current.cancel(current.id);
119
+ if (result.ok) {
120
+ settle(result.job, current.name);
121
+ return;
122
+ }
123
+ if (result.reason !== 'finished') {
124
+ report(current.name, result);
125
+ return;
126
+ }
127
+ const read = await clientRef.current.read(current.id);
128
+ if (read.ok)
129
+ settle(read.job, current.name);
130
+ else
131
+ report(current.name, read);
132
+ }
133
+ const handleCancel = useCallback(() => void cancel(), []);
134
+ const handleStart = useCallback((request) => void start(request), []);
135
+ return { running, cancel: handleCancel, start: handleStart };
136
+ }
137
+ function describeEnd(job) {
138
+ if (job.status === 'failed')
139
+ return job.error ?? 'The conversion failed.';
140
+ return 'The conversion ended without a result.';
141
+ }
142
+ function readStoredJob() {
143
+ let raw;
144
+ try {
145
+ raw = globalThis.sessionStorage.getItem(CONVERSION_STORAGE_KEY);
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ if (raw === null)
151
+ return undefined;
152
+ let value;
153
+ try {
154
+ value = JSON.parse(raw);
155
+ }
156
+ catch {
157
+ return undefined;
158
+ }
159
+ return typeof value === 'object' &&
160
+ value !== null &&
161
+ 'id' in value &&
162
+ typeof value.id === 'string' &&
163
+ 'name' in value &&
164
+ typeof value.name === 'string'
165
+ ? { id: value.id, name: value.name }
166
+ : undefined;
167
+ }
168
+ function writeStoredJob(job) {
169
+ try {
170
+ if (job === undefined)
171
+ globalThis.sessionStorage.removeItem(CONVERSION_STORAGE_KEY);
172
+ else
173
+ globalThis.sessionStorage.setItem(CONVERSION_STORAGE_KEY, JSON.stringify(job));
174
+ }
175
+ catch {
176
+ }
177
+ }
@@ -0,0 +1,18 @@
1
+ /** The convert dialog's starting name and prompt; `key` changes with each opening, so that the dialog starts afresh. */
2
+ export interface ConvertDraft {
3
+ key: number;
4
+ name: string;
5
+ prompt: string;
6
+ }
7
+ /** The open convert dialog's draft, with functions that open the dialog afresh and close it. */
8
+ export interface ConvertDraftControls {
9
+ draft: ConvertDraft | undefined;
10
+ /** Opens the dialog, starting with the name and the prompt given, if any. */
11
+ open: (initial?: {
12
+ name: string;
13
+ prompt: string;
14
+ }) => void;
15
+ close: () => void;
16
+ }
17
+ /** Holds the convert dialog's open state, so that the header and the saved-files list can both open it. */
18
+ export declare function useConvertDraft(): ConvertDraftControls;
@@ -0,0 +1,11 @@
1
+ import { useCallback, useRef, useState } from 'react';
2
+ export function useConvertDraft() {
3
+ const [draft, setDraft] = useState();
4
+ const openCount = useRef(0);
5
+ const open = useCallback((initial) => {
6
+ openCount.current += 1;
7
+ setDraft({ key: openCount.current, name: initial?.name ?? '', prompt: initial?.prompt ?? '' });
8
+ }, []);
9
+ const close = useCallback(() => setDraft(undefined), []);
10
+ return { draft, open, close };
11
+ }
@@ -0,0 +1,2 @@
1
+ /** Names the shown chart's source in the document title, so that tabs and history entries can be told apart. */
2
+ export declare function useDocumentTitle(source: string | undefined): void;
@@ -0,0 +1,7 @@
1
+ import { useEffect } from 'react';
2
+ const PAGE_TITLE = 'Agent logic';
3
+ export function useDocumentTitle(source) {
4
+ useEffect(() => {
5
+ document.title = source === undefined ? PAGE_TITLE : `${source} – ${PAGE_TITLE}`;
6
+ }, [source]);
7
+ }
@@ -0,0 +1,2 @@
1
+ /** Calls `clear` when Escape is pressed, except where an open dialog takes the key to close itself. */
2
+ export declare function useEscapeToClear(clear: () => void): void;
@@ -0,0 +1,16 @@
1
+ import { useEffect } from 'react';
2
+ export function useEscapeToClear(clear) {
3
+ useEffect(() => {
4
+ function handleKeyDown(event) {
5
+ if (event.key !== 'Escape' || event.defaultPrevented)
6
+ return;
7
+ if (event.target instanceof Element && event.target.closest('[role="dialog"]') !== null)
8
+ return;
9
+ clear();
10
+ }
11
+ document.addEventListener('keydown', handleKeyDown);
12
+ return () => {
13
+ document.removeEventListener('keydown', handleKeyDown);
14
+ };
15
+ }, [clear]);
16
+ }
@@ -0,0 +1,26 @@
1
+ import type { HarnessList } from '@williamthorsen/telefactor/client';
2
+ import type { Problem } from '../../schema/validate-config.js';
3
+ import type { ConversionClient } from './conversion-client.js';
4
+ /** The harnesses that the server offers, without the problems that a malformed config file reports instead. */
5
+ export type HarnessOffer = Extract<HarnessList, {
6
+ harnesses: unknown;
7
+ }>;
8
+ /**
9
+ * The harness listing: `loading` until the server answers, `ready` with the harnesses, `malformed` with the problems of
10
+ * a config file that the server cannot use, or `unreachable` with the problems that kept the page from reading it.
11
+ */
12
+ export type HarnessListing = {
13
+ state: 'loading';
14
+ } | {
15
+ state: 'ready';
16
+ list: HarnessOffer;
17
+ } | {
18
+ state: 'malformed';
19
+ configPath: string;
20
+ problems: Problem[];
21
+ } | {
22
+ state: 'unreachable';
23
+ problems: Problem[];
24
+ };
25
+ /** Reads the server's harnesses once, when the component mounts. */
26
+ export declare function useHarnessList(client: ConversionClient): HarnessListing;
@@ -0,0 +1,24 @@
1
+ import { useEffect, useState } from 'react';
2
+ export function useHarnessList(client) {
3
+ const [listing, setListing] = useState({ state: 'loading' });
4
+ useEffect(() => {
5
+ let isCurrent = true;
6
+ async function load() {
7
+ const outcome = await client.listHarnesses();
8
+ if (!isCurrent)
9
+ return;
10
+ if (!outcome.ok)
11
+ setListing({ state: 'unreachable', problems: outcome.problems });
12
+ else if ('problems' in outcome.list) {
13
+ setListing({ state: 'malformed', configPath: outcome.list.configPath, problems: outcome.list.problems });
14
+ }
15
+ else
16
+ setListing({ state: 'ready', list: outcome.list });
17
+ }
18
+ void load();
19
+ return () => {
20
+ isCurrent = false;
21
+ };
22
+ }, [client]);
23
+ return listing;
24
+ }
@@ -0,0 +1,27 @@
1
+ import type { PromptEntry } from '../../server/prompt-directory-schemas.js';
2
+ import type { ConversionClient } from './conversion-client.js';
3
+ /**
4
+ * The prompts directory as the page shows it: `hidden` until the server first answers and whenever it does not serve
5
+ * the directory or cannot be reached, `ready` with its entries, `missing` when the directory does not exist, and
6
+ * `malformed` when the config file that names it cannot be used.
7
+ */
8
+ export type PromptDirectoryState = {
9
+ state: 'hidden';
10
+ } | {
11
+ state: 'ready';
12
+ directory: string;
13
+ configPath: string;
14
+ entries: PromptEntry[];
15
+ } | {
16
+ state: 'missing';
17
+ directory: string;
18
+ configPath: string;
19
+ } | {
20
+ state: 'malformed';
21
+ };
22
+ /**
23
+ * Polls the prompts directory every `POLL_INTERVAL_MS`, so that a file saved there appears without a reload. A server
24
+ * that does not serve the directory stops the polling; one that cannot be reached does not, so that a restarted dev
25
+ * server shows the directory again.
26
+ */
27
+ export declare function usePromptDirectory(client: ConversionClient): PromptDirectoryState;
@@ -0,0 +1,34 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { POLL_INTERVAL_MS } from "./useConversion.js";
3
+ export function usePromptDirectory(client) {
4
+ const [directory, setDirectory] = useState({ state: 'hidden' });
5
+ useEffect(() => {
6
+ let isCurrent = true;
7
+ let timer;
8
+ void poll();
9
+ return () => {
10
+ isCurrent = false;
11
+ clearTimeout(timer);
12
+ };
13
+ async function poll() {
14
+ const outcome = await client.listPrompts();
15
+ if (!isCurrent)
16
+ return;
17
+ if (outcome.ok) {
18
+ const { list } = outcome;
19
+ const { directory, configPath } = list;
20
+ if ('entries' in list)
21
+ setDirectory({ state: 'ready', directory, configPath, entries: list.entries });
22
+ else
23
+ setDirectory({ state: 'missing', directory, configPath });
24
+ }
25
+ else {
26
+ setDirectory({ state: outcome.reason === 'malformed' ? 'malformed' : 'hidden' });
27
+ if (outcome.reason === 'absent')
28
+ return;
29
+ }
30
+ timer = setTimeout(() => void poll(), POLL_INTERVAL_MS);
31
+ }
32
+ }, [client]);
33
+ return directory;
34
+ }
@@ -0,0 +1,17 @@
1
+ import type { Span } from '../../schema/agent-logic-schema.js';
2
+ /** The element selected and the passages shown, of which the page marks one at a time, and the calls that set them. */
3
+ export interface Selection {
4
+ selectedPath: string | undefined;
5
+ shownPassages: Span[];
6
+ /** Selects an element, or clears the selection, and clears the passages shown. */
7
+ select: (path: string | undefined) => void;
8
+ /** Shows passages, such as an unconverted one or a finding's, and clears the selection. */
9
+ showPassages: (passages: Span[]) => void;
10
+ /** Clears both without publishing, for a new chart, whose load clears the agent's selection itself. */
11
+ reset: () => void;
12
+ }
13
+ /**
14
+ * Holds the page's one set of marked passages: a selected element's, or those that a message shows. Each change of the
15
+ * selection goes to `publish`, so that the agent's session state follows it.
16
+ */
17
+ export declare function useSelection(publish: (path: string | undefined) => void): Selection;
@@ -0,0 +1,21 @@
1
+ import { useCallback, useState } from 'react';
2
+ export function useSelection(publish) {
3
+ const [selectedPath, setSelectedPath] = useState();
4
+ const [shownPassages, setShownPassages] = useState(NO_PASSAGES);
5
+ const select = useCallback((path) => {
6
+ setShownPassages(NO_PASSAGES);
7
+ setSelectedPath(path);
8
+ publish(path);
9
+ }, [publish]);
10
+ const showPassages = useCallback((passages) => {
11
+ setSelectedPath(undefined);
12
+ publish(undefined);
13
+ setShownPassages(passages);
14
+ }, [publish]);
15
+ const reset = useCallback(() => {
16
+ setSelectedPath(undefined);
17
+ setShownPassages(NO_PASSAGES);
18
+ }, []);
19
+ return { selectedPath, shownPassages, select, showPassages, reset };
20
+ }
21
+ const NO_PASSAGES = [];
@@ -0,0 +1,7 @@
1
+ /** The `localStorage` key under which the viewer remembers whether flows show their preambles. */
2
+ export declare const SHOW_AMBIENT_KEY = "agent-logic.show-ambient";
3
+ /**
4
+ * Holds whether flows show their preambles of ambient instructions, remembered across loads and reloads; shown when
5
+ * nothing is remembered or storage is unavailable.
6
+ */
7
+ export declare function useShowAmbient(): [boolean, (isShown: boolean) => void];
@@ -0,0 +1,22 @@
1
+ import { useCallback, useState } from 'react';
2
+ export const SHOW_AMBIENT_KEY = 'agent-logic.show-ambient';
3
+ export function useShowAmbient() {
4
+ const [isShown, setIsShown] = useState(readShowAmbient);
5
+ const setShowAmbient = useCallback((next) => {
6
+ setIsShown(next);
7
+ try {
8
+ globalThis.localStorage.setItem(SHOW_AMBIENT_KEY, String(next));
9
+ }
10
+ catch {
11
+ }
12
+ }, []);
13
+ return [isShown, setShowAmbient];
14
+ }
15
+ function readShowAmbient() {
16
+ try {
17
+ return globalThis.localStorage.getItem(SHOW_AMBIENT_KEY) !== 'false';
18
+ }
19
+ catch {
20
+ return true;
21
+ }
22
+ }
@@ -0,0 +1,7 @@
1
+ /** The `example` value of the URL when it names no bundled example, and the function that clears it after a load. */
2
+ export interface UnknownExample {
3
+ unknownExample: string | undefined;
4
+ clearUnknownExample: () => void;
5
+ }
6
+ /** Tracks an unknown `example` value in the URL, announcing it on the first load and after each move through history. */
7
+ export declare function useUnknownExample(announce: (text: string) => void): UnknownExample;
@@ -0,0 +1,26 @@
1
+ import { useCallback, useEffect, useState } from 'react';
2
+ import { describeUnknownExample } from "./describe-load-outcome.js";
3
+ import { findUnknownExampleInSearch } from "./example-location.js";
4
+ export function useUnknownExample(announce) {
5
+ const [unknownExample, setUnknownExample] = useState(() => findUnknownExampleInSearch(globalThis.location.search));
6
+ useEffect(() => {
7
+ announceIfUnknown(findUnknownExampleInSearch(globalThis.location.search));
8
+ globalThis.addEventListener('popstate', handlePopState);
9
+ return () => {
10
+ globalThis.removeEventListener('popstate', handlePopState);
11
+ };
12
+ function handlePopState() {
13
+ const value = findUnknownExampleInSearch(globalThis.location.search);
14
+ setUnknownExample(value);
15
+ announceIfUnknown(value);
16
+ }
17
+ function announceIfUnknown(value) {
18
+ if (value !== undefined)
19
+ announce(describeUnknownExample(value));
20
+ }
21
+ }, [announce]);
22
+ const clearUnknownExample = useCallback(() => {
23
+ setUnknownExample(undefined);
24
+ }, []);
25
+ return { unknownExample, clearUnknownExample };
26
+ }
@@ -0,0 +1,24 @@
1
+ /** `./react` entry: the statechart canvas, the data of its key, and the hooks of a page that presents a chart. */
2
+ export * from './canvas/canvas-key-entries.js';
3
+ export * from './canvas/list-chart-marks.js';
4
+ export * from './canvas/marks.js';
5
+ export * from './canvas/StatechartCanvas.js';
6
+ export * from './hooks/conversion-client.js';
7
+ export * from './hooks/describe-agent-selection.js';
8
+ export * from './hooks/describe-load-outcome.js';
9
+ export * from './hooks/download-config.js';
10
+ export * from './hooks/example-location.js';
11
+ export * from './hooks/label-source.js';
12
+ export * from './hooks/parse-config-text.js';
13
+ export * from './hooks/useAgentBridge.js';
14
+ export * from './hooks/useAgentSync.js';
15
+ export * from './hooks/useChartLayout.js';
16
+ export * from './hooks/useConversion.js';
17
+ export * from './hooks/useConvertDraft.js';
18
+ export * from './hooks/useDocumentTitle.js';
19
+ export * from './hooks/useEscapeToClear.js';
20
+ export * from './hooks/useHarnessList.js';
21
+ export * from './hooks/usePromptDirectory.js';
22
+ export * from './hooks/useSelection.js';
23
+ export * from './hooks/useShowAmbient.js';
24
+ export * from './hooks/useUnknownExample.js';