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,205 @@
1
+ import { agentLogicConfigSchema, } from "./agent-logic-schema.js";
2
+ import { listStates, listTransitions } from "./config-traversal.js";
3
+ export function formatPath(path) {
4
+ return path
5
+ .map((segment, index) => {
6
+ if (typeof segment === 'number')
7
+ return `[${segment}]`;
8
+ const key = String(segment);
9
+ if (key.includes('.'))
10
+ return `["${key}"]`;
11
+ return index === 0 ? key : `.${key}`;
12
+ })
13
+ .join('');
14
+ }
15
+ export function validateConfig(value) {
16
+ const parsed = agentLogicConfigSchema.safeParse(value);
17
+ if (!parsed.success) {
18
+ return {
19
+ ok: false,
20
+ problems: parsed.error.issues.map((issue) => ({ path: formatPath(issue.path), message: describeIssue(issue) })),
21
+ };
22
+ }
23
+ const problems = findSemanticProblems(parsed.data);
24
+ return problems.length === 0 ? { ok: true, config: parsed.data } : { ok: false, problems };
25
+ }
26
+ function describeIssue(issue) {
27
+ if (issue.code === 'unrecognized_keys') {
28
+ return `Unrecognized ${issue.keys.length === 1 ? 'key' : 'keys'}: ${issue.keys.join(', ')}. Remove ${issue.keys.length === 1 ? 'it' : 'them'}.`;
29
+ }
30
+ return `${issue.message}.`;
31
+ }
32
+ function checkActionSpans(actions, promptLength, path, problems) {
33
+ const entries = (actions ?? []).entries();
34
+ for (const [index, action] of entries) {
35
+ if (action.meta !== undefined)
36
+ checkSpan(action.meta.source, promptLength, [...path, index, 'meta', 'source'], problems);
37
+ }
38
+ }
39
+ function checkAmbient(config, states, problems) {
40
+ const promptLength = config.meta.prompt.length;
41
+ const placed = [];
42
+ for (const { path, state } of states) {
43
+ const ambient = state.meta.ambient;
44
+ if (ambient === undefined)
45
+ continue;
46
+ if (state.states === undefined) {
47
+ problems.push({
48
+ path: formatPath([...path, 'meta', 'ambient']),
49
+ message: 'Ambient instructions belong to the root or to a compound state. Move them to the enclosing flow or the root.',
50
+ });
51
+ continue;
52
+ }
53
+ for (const [index, span] of ambient.entries()) {
54
+ const spanPath = [...path, 'meta', 'ambient', index];
55
+ checkSpan(span, promptLength, spanPath, problems);
56
+ if (placed.some((other) => overlaps(other, span))) {
57
+ problems.push({
58
+ path: formatPath(spanPath),
59
+ message: 'The span overlaps another ambient instruction. Give each passage one ambient entry.',
60
+ });
61
+ }
62
+ else if (config.meta.unconverted.some((other) => overlaps(other, span))) {
63
+ problems.push({
64
+ path: formatPath(spanPath),
65
+ message: 'The span overlaps an unconverted passage. List the passage as ambient or as unconverted, not both.',
66
+ });
67
+ }
68
+ placed.push(span);
69
+ }
70
+ }
71
+ }
72
+ function checkFindings(findings, isElementInferred, promptLength, path, problems) {
73
+ if (findings === undefined)
74
+ return;
75
+ for (const [index, finding] of findings.entries()) {
76
+ const findingPath = [...path, 'meta', 'findings', index];
77
+ for (const [sourceIndex, span] of finding.sources.entries()) {
78
+ checkSpan(span, promptLength, [...findingPath, 'sources', sourceIndex], problems);
79
+ }
80
+ if (finding.kind === 'inferred-resolution' && !isElementInferred) {
81
+ problems.push({
82
+ path: formatPath([...findingPath, 'kind']),
83
+ message: 'An inferred-resolution finding explains an inferred element, and this one is not. Move it to the inferred element that it explains, or change its kind.',
84
+ });
85
+ }
86
+ }
87
+ }
88
+ function checkInitial(path, state, problems) {
89
+ const childKeys = Object.keys(state.states ?? {});
90
+ if (childKeys.length > 0 && state.initial === undefined) {
91
+ problems.push({
92
+ path: formatPath([...path, 'initial']),
93
+ message: `The state has children but no initial state. Set "initial" to one of: ${childKeys.join(', ')}.`,
94
+ });
95
+ }
96
+ else if (state.initial !== undefined && !childKeys.includes(state.initial)) {
97
+ problems.push({
98
+ path: formatPath([...path, 'initial']),
99
+ message: childKeys.length === 0
100
+ ? `"initial" names "${state.initial}", but the state has no children. Remove "initial".`
101
+ : `"initial" names "${state.initial}", which is not a child state. Name one of: ${childKeys.join(', ')}.`,
102
+ });
103
+ }
104
+ }
105
+ function checkSpan(span, promptLength, path, problems) {
106
+ if (span.start > span.end) {
107
+ problems.push({
108
+ path: formatPath(path),
109
+ message: `The span starts at ${span.start}, after its end at ${span.end}. Swap or correct the offsets.`,
110
+ });
111
+ }
112
+ else if (span.end > promptLength) {
113
+ problems.push({
114
+ path: formatPath(path),
115
+ message: `The span ends at ${span.end}, past the prompt's last offset, ${promptLength}. Correct the offsets.`,
116
+ });
117
+ }
118
+ }
119
+ function checkUniqueIds(states, problems) {
120
+ const pathsById = Map.groupBy(states, ({ state }) => state.id);
121
+ for (const [id, entries] of pathsById) {
122
+ const [, duplicate] = entries;
123
+ if (duplicate !== undefined) {
124
+ problems.push({
125
+ path: formatPath([...duplicate.path, 'id']),
126
+ message: `The id "${id}" is used by ${entries.length} states. Give each state its own id.`,
127
+ });
128
+ }
129
+ }
130
+ }
131
+ function findNearestId(missingId, ids) {
132
+ const threshold = Math.max(1, Math.floor(missingId.length / 3));
133
+ let nearest;
134
+ for (const id of ids) {
135
+ const distance = measureEditDistance(missingId, id);
136
+ if (distance > threshold || (nearest !== undefined && distance >= nearest.distance))
137
+ continue;
138
+ nearest = { id, distance };
139
+ }
140
+ return nearest?.id;
141
+ }
142
+ function findSemanticProblems(config) {
143
+ const problems = [];
144
+ const states = listStates(config);
145
+ const ids = new Set(states.map(({ state }) => state.id));
146
+ const promptLength = config.meta.prompt.length;
147
+ checkUniqueIds(states, problems);
148
+ for (const [index, span] of config.meta.unconverted.entries()) {
149
+ checkSpan(span, promptLength, ['meta', 'unconverted', index], problems);
150
+ }
151
+ checkAmbient(config, states, problems);
152
+ for (const { path, state } of states) {
153
+ checkSpan(state.meta.source, promptLength, [...path, 'meta', 'source'], problems);
154
+ checkFindings(state.meta.findings, isInferred(state.meta), promptLength, path, problems);
155
+ checkActionSpans(state.entry, promptLength, [...path, 'entry'], problems);
156
+ checkActionSpans(state.exit, promptLength, [...path, 'exit'], problems);
157
+ checkInitial(path, state, problems);
158
+ if ('gate' in state.meta && state.meta.gate === true) {
159
+ problems.push({
160
+ path: formatPath([...path, 'meta', 'gate']),
161
+ message: 'A state cannot be a gate. Flag the transition into the step, an action of the step, or an ambient instruction.',
162
+ });
163
+ }
164
+ const transitions = listTransitions(state);
165
+ if ('type' in state && state.type === 'final' && (state.states !== undefined || transitions.length > 0)) {
166
+ problems.push({
167
+ path: formatPath([...path, 'type']),
168
+ message: 'A final state cannot have children or transitions. Remove them, or remove "type".',
169
+ });
170
+ }
171
+ for (const { path: transitionPath, transition } of transitions) {
172
+ const fullPath = [...path, ...transitionPath];
173
+ checkSpan(transition.meta.source, promptLength, [...fullPath, 'meta', 'source'], problems);
174
+ checkFindings(transition.meta.findings, isInferred(transition.meta), promptLength, fullPath, problems);
175
+ checkActionSpans(transition.actions, promptLength, [...fullPath, 'actions'], problems);
176
+ if (transition.target === undefined || ids.has(transition.target.slice(1)))
177
+ continue;
178
+ const nearestId = findNearestId(transition.target.slice(1), ids);
179
+ problems.push({
180
+ path: formatPath([...fullPath, 'target']),
181
+ message: nearestId === undefined
182
+ ? `The target "${transition.target}" does not name any state. Use "#" followed by an existing state's id.`
183
+ : `The target "${transition.target}" does not name any state. Use "#${nearestId}" or another existing state's id.`,
184
+ });
185
+ }
186
+ }
187
+ return problems;
188
+ }
189
+ function isInferred(meta) {
190
+ return 'inferred' in meta && meta.inferred === true;
191
+ }
192
+ function overlaps(first, second) {
193
+ return first.start < second.end && second.start < first.end;
194
+ }
195
+ function measureEditDistance(from, to) {
196
+ let previousRow = Array.from({ length: to.length + 1 }, (_, index) => index);
197
+ for (let fromIndex = 0; fromIndex < from.length; fromIndex += 1) {
198
+ const row = [fromIndex + 1];
199
+ for (let toIndex = 0; toIndex < to.length; toIndex += 1) {
200
+ row.push(Math.min((previousRow[toIndex + 1] ?? 0) + 1, (row[toIndex] ?? 0) + 1, (previousRow[toIndex] ?? 0) + (from[fromIndex] === to[toIndex] ? 0 : 1)));
201
+ }
202
+ previousRow = row;
203
+ }
204
+ return previousRow[to.length] ?? 0;
205
+ }
@@ -0,0 +1,4 @@
1
+ /** Location of the committed JSON Schema file. */
2
+ export declare const JSON_SCHEMA_PATH: string;
3
+ /** Renders the agent-logic schema as the text of a JSON Schema file, describing what a producer writes. */
4
+ export declare function renderJsonSchema(): string;
@@ -0,0 +1,12 @@
1
+ import { writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { z } from 'zod';
5
+ import { agentLogicConfigSchema } from "./agent-logic-schema.js";
6
+ export const JSON_SCHEMA_PATH = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../schema/agent-logic.schema.json');
7
+ export function renderJsonSchema() {
8
+ return `${JSON.stringify(z.toJSONSchema(agentLogicConfigSchema, { io: 'input' }), undefined, 2)}\n`;
9
+ }
10
+ if (import.meta.main) {
11
+ writeFileSync(JSON_SCHEMA_PATH, renderJsonSchema());
12
+ }
@@ -0,0 +1,11 @@
1
+ import { type JobImplementation } from '@williamthorsen/telefactor/server';
2
+ import { conversionJob } from '../contract/conversion-job.js';
3
+ /**
4
+ * Implements the conversion job: Each run writes the prompt to a file in a directory of its own under
5
+ * `conversionsDirectory`, expands `{prompt}`, `{output}`, and `{problems}` in the harness command to absolute paths in
6
+ * that directory, and reads back the agent-logic file that the command writes or, when it writes none, the problems or
7
+ * out-of-scope verdict in the problems file.
8
+ */
9
+ export declare function createConversionJobImplementation({ conversionsDirectory, }: {
10
+ conversionsDirectory: string;
11
+ }): JobImplementation<typeof conversionJob>;
@@ -0,0 +1,84 @@
1
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { implementJob } from '@williamthorsen/telefactor/server';
4
+ import { describeError } from '@williamthorsen/toolbelt.errors';
5
+ import { conversionJob, problemsFileSchema } from "../contract/conversion-job.js";
6
+ import { outOfScopeSchema } from "../convert/draft-schema.js";
7
+ import { sanitizeName } from "../convert/sanitize-name.js";
8
+ import { validateConfig } from "../schema/validate-config.js";
9
+ const TAIL_LINES = 20;
10
+ const RELEASED_OUTCOMES = new Set(['cancelled', 'done']);
11
+ export function createConversionJobImplementation({ conversionsDirectory, }) {
12
+ return implementJob(conversionJob, {
13
+ async prepare({ id, harness, prompt, input }) {
14
+ const baseName = sanitizeName(input.name);
15
+ const directory = path.join(conversionsDirectory, id);
16
+ const paths = {
17
+ prompt: path.join(directory, `${baseName}.md`),
18
+ output: path.join(directory, `${baseName}.agent-logic.json`),
19
+ problems: path.join(directory, `${baseName}.problems.json`),
20
+ };
21
+ try {
22
+ await mkdir(directory, { recursive: true });
23
+ await writeFile(paths.prompt, prompt);
24
+ }
25
+ catch (error) {
26
+ await rm(directory, { recursive: true, force: true });
27
+ throw error;
28
+ }
29
+ return {
30
+ placeholders: paths,
31
+ stdin: '',
32
+ async read({ stdout, stderrTail }) {
33
+ const result = (await readOutput(paths.output)) ?? (await readProblems(paths.problems));
34
+ if (result === undefined) {
35
+ const tail = formatOutputTail(stdout, stderrTail);
36
+ throw new Error(`The harness ${harness} exited without writing ${paths.output}.${tail}`);
37
+ }
38
+ return result;
39
+ },
40
+ async release(outcome) {
41
+ if (RELEASED_OUTCOMES.has(outcome))
42
+ await rm(directory, { recursive: true, force: true });
43
+ },
44
+ };
45
+ },
46
+ });
47
+ }
48
+ function formatOutputTail(stdout, stderrTail) {
49
+ const output = [stdout.trim(), stderrTail.trim()].filter((part) => part !== '').join('\n');
50
+ return output === '' ? '' : `\n${output.split('\n').slice(-TAIL_LINES).join('\n')}`;
51
+ }
52
+ async function readOutput(outputPath) {
53
+ let text;
54
+ try {
55
+ text = await readFile(outputPath, 'utf8');
56
+ }
57
+ catch {
58
+ return undefined;
59
+ }
60
+ let value;
61
+ try {
62
+ value = JSON.parse(text);
63
+ }
64
+ catch (error) {
65
+ const reason = describeError(error);
66
+ return { ok: false, problems: [{ path: '', message: `The agent-logic file is not valid JSON: ${reason}.` }] };
67
+ }
68
+ const validated = validateConfig(value);
69
+ return validated.ok ? { ok: true, config: validated.config, text } : validated;
70
+ }
71
+ async function readProblems(problemsPath) {
72
+ let value;
73
+ try {
74
+ value = JSON.parse(await readFile(problemsPath, 'utf8'));
75
+ }
76
+ catch {
77
+ return undefined;
78
+ }
79
+ const verdict = outOfScopeSchema.safeParse(value);
80
+ if (verdict.success)
81
+ return { ok: false, outOfScope: verdict.data.outOfScope };
82
+ const parsed = problemsFileSchema.safeParse(value);
83
+ return parsed.success ? { ok: false, problems: parsed.data.problems } : undefined;
84
+ }
@@ -0,0 +1,26 @@
1
+ import type { HarnessSettingsResult } from '@williamthorsen/telefactor/server';
2
+ import { type Context, type Env, Hono } from 'hono';
3
+ import type { z } from 'zod';
4
+ import type { viewerConfigSchema } from '../contract/built-in-harnesses.js';
5
+ import type { PromptDirectoryListing, PromptFileRead } from './prompt-directory.js';
6
+ /** The harness settings with the viewer's own keys, as `readHarnessSettings` resolves them. */
7
+ export type ViewerSettingsResult = HarnessSettingsResult<z.output<typeof viewerConfigSchema>>;
8
+ interface PromptsAppOptions<E extends Env> {
9
+ /** Resolves the settings; called on each request, so that an edit applies at once. */
10
+ readSettings: () => Promise<ViewerSettingsResult>;
11
+ /** Decides whether a request may reach the routes; a rejected request gets `403`. */
12
+ isAllowed: (context: Context<E>) => boolean;
13
+ listPrompts: (directory: string) => Promise<PromptDirectoryListing>;
14
+ /** Returns the text of a file in the prompts directory, if a listing of the directory names it. */
15
+ readPromptFile: (directory: string, fileName: string) => Promise<PromptFileRead>;
16
+ }
17
+ /**
18
+ * Creates the HTTP app that lists the prompts directory that the settings name at `/` and returns the text of a listed
19
+ * file at `/files/:fileName`.
20
+ */
21
+ export declare function createPromptsApp<E extends Env>({ readSettings, isAllowed, listPrompts, readPromptFile, }: PromptsAppOptions<E>): Hono<E>;
22
+ /** Returns the prompts directory as an absolute path, resolved against the config file's directory. */
23
+ export declare function resolvePromptsDirectory({ configPath, settings }: Extract<ViewerSettingsResult, {
24
+ ok: true;
25
+ }>): string;
26
+ export {};
@@ -0,0 +1,41 @@
1
+ import path from 'node:path';
2
+ import { Hono } from 'hono';
3
+ export function createPromptsApp({ readSettings, isAllowed, listPrompts, readPromptFile, }) {
4
+ const app = new Hono();
5
+ app.use(async (context, next) => {
6
+ if (isAllowed(context)) {
7
+ await next();
8
+ }
9
+ else {
10
+ context.res = context.json({ error: 'The prompts routes accept only local requests.' }, 403);
11
+ }
12
+ });
13
+ app.get('/', async (context) => {
14
+ const resolved = await readSettings();
15
+ if (!resolved.ok)
16
+ return context.json({ problems: resolved.problems }, 400);
17
+ const { configPath } = resolved;
18
+ const directory = resolvePromptsDirectory(resolved);
19
+ const listing = await listPrompts(directory);
20
+ const list = listing.ok
21
+ ? { directory, configPath, entries: listing.entries }
22
+ : { directory, configPath, missing: true };
23
+ return context.json(list);
24
+ });
25
+ app.get('/files/:fileName', async (context) => {
26
+ const resolved = await readSettings();
27
+ if (!resolved.ok)
28
+ return context.json({ problems: resolved.problems }, 400);
29
+ const fileName = context.req.param('fileName');
30
+ const read = await readPromptFile(resolvePromptsDirectory(resolved), fileName);
31
+ if (read.ok)
32
+ return context.json({ text: read.text });
33
+ return read.reason === 'too-large'
34
+ ? context.json({ error: `${fileName} is larger than 1 MiB.` }, 413)
35
+ : context.json({ error: `The prompts directory does not list ${fileName}.` }, 404);
36
+ });
37
+ return app;
38
+ }
39
+ export function resolvePromptsDirectory({ configPath, settings }) {
40
+ return path.resolve(path.dirname(configPath), settings.app.promptsDirectory);
41
+ }
@@ -0,0 +1,15 @@
1
+ import type { Plugin } from 'vite';
2
+ /** The variable whose JSON argv replaces every other harness. */
3
+ export declare const HARNESS_COMMAND_VARIABLE = "AGENT_LOGIC_HARNESS_COMMAND";
4
+ /** The config file, resolved against the Vite root. */
5
+ export declare const HARNESS_CONFIG_FILE = "harness.config.json";
6
+ /** The path under which the prompts routes are mounted. */
7
+ export declare const PROMPTS_BASE_PATH = "/api/prompts";
8
+ /**
9
+ * Creates the dev-server plugins: telefactor's harness, job, terminal, and contract routes under `/api/telefactor`,
10
+ * running the conversion job with a directory of its own for each run under `conversionsDirectory`, and the prompts
11
+ * routes under `/api/prompts`.
12
+ */
13
+ export declare function createViewerServerPlugins({ conversionsDirectory }: {
14
+ conversionsDirectory: string;
15
+ }): Plugin[];
@@ -0,0 +1,76 @@
1
+ import { mkdirSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { getRequestListener } from '@hono/node-server';
4
+ import { isLoopbackRequest, isSameOriginRequest, readHarnessSettings, readRequestHost, } from '@williamthorsen/telefactor/server';
5
+ import { telefactor } from '@williamthorsen/telefactor/vite';
6
+ import { DEFAULT_PROMPTS_DIRECTORY, viewerBuiltInHarnesses, viewerConfigSchema, } from "../contract/built-in-harnesses.js";
7
+ import { createConversionJobImplementation } from "./conversion-job-implementation.js";
8
+ import { createPromptsApp } from "./create-prompts-app.js";
9
+ import { listPromptDirectory, readPromptDirectoryFile } from "./prompt-directory.js";
10
+ import { createViewerContractImplementation } from "./viewer-contract-implementation.js";
11
+ export const HARNESS_COMMAND_VARIABLE = 'AGENT_LOGIC_HARNESS_COMMAND';
12
+ export const HARNESS_CONFIG_FILE = 'harness.config.json';
13
+ export const PROMPTS_BASE_PATH = '/api/prompts';
14
+ export function createViewerServerPlugins({ conversionsDirectory }) {
15
+ let root;
16
+ return [
17
+ {
18
+ name: 'agent-logic-root',
19
+ configResolved(config) {
20
+ root = config.root;
21
+ },
22
+ },
23
+ telefactor({
24
+ builtIn: viewerBuiltInHarnesses,
25
+ commandVariable: HARNESS_COMMAND_VARIABLE,
26
+ config: viewerConfigSchema,
27
+ configPath: HARNESS_CONFIG_FILE,
28
+ contract: createViewerContractImplementation({
29
+ readSettings: () => {
30
+ if (root === undefined)
31
+ throw new Error('The dev server has not resolved its root.');
32
+ return readViewerSettings(root);
33
+ },
34
+ }),
35
+ job: createConversionJobImplementation({ conversionsDirectory }),
36
+ }),
37
+ createPromptsServerPlugin(),
38
+ ];
39
+ }
40
+ function createPromptsServerPlugin() {
41
+ return {
42
+ name: 'agent-logic-prompts',
43
+ apply: 'serve',
44
+ configureServer(server) {
45
+ const { root } = server.config;
46
+ mkdirSync(path.join(root, DEFAULT_PROMPTS_DIRECTORY), { recursive: true });
47
+ const app = createPromptsApp({
48
+ readSettings: () => readViewerSettings(root),
49
+ isAllowed: (context) => isLoopbackRequest({
50
+ host: readRequestHost(context.req.header('host'), context.env.incoming),
51
+ remoteAddress: context.env.incoming.socket.remoteAddress,
52
+ }) &&
53
+ isSameOriginRequest({
54
+ origin: context.req.header('origin'),
55
+ secFetchSite: context.req.header('sec-fetch-site'),
56
+ url: context.req.url,
57
+ }),
58
+ listPrompts: listPromptDirectory,
59
+ readPromptFile: readPromptDirectoryFile,
60
+ });
61
+ const listener = getRequestListener((request, env) => app.fetch(request, env), { overrideGlobalObjects: false });
62
+ server.middlewares.use(PROMPTS_BASE_PATH, (request, response) => {
63
+ void listener(request, response);
64
+ });
65
+ },
66
+ };
67
+ }
68
+ function readViewerSettings(root) {
69
+ return readHarnessSettings({
70
+ env: process.env,
71
+ configPath: path.join(root, HARNESS_CONFIG_FILE),
72
+ builtIn: viewerBuiltInHarnesses,
73
+ commandVariable: HARNESS_COMMAND_VARIABLE,
74
+ config: viewerConfigSchema,
75
+ });
76
+ }
@@ -0,0 +1,7 @@
1
+ /** `./server` entry: the telefactor plugin glue that serves prompts and runs conversions. */
2
+ export * from './conversion-job-implementation.js';
3
+ export * from './create-prompts-app.js';
4
+ export * from './create-viewer-server-plugins.js';
5
+ export * from './prompt-directory.js';
6
+ export * from './prompt-directory-schemas.js';
7
+ export * from './viewer-contract-implementation.js';
@@ -0,0 +1,6 @@
1
+ export * from "./conversion-job-implementation.js";
2
+ export * from "./create-prompts-app.js";
3
+ export * from "./create-viewer-server-plugins.js";
4
+ export * from "./prompt-directory.js";
5
+ export * from "./prompt-directory-schemas.js";
6
+ export * from "./viewer-contract-implementation.js";
@@ -0,0 +1,30 @@
1
+ import { z } from 'zod';
2
+ /** A base name and the prompt and agent-logic files that share it. */
3
+ export declare const promptEntrySchema: z.ZodObject<{
4
+ name: z.ZodString;
5
+ promptFile: z.ZodOptional<z.ZodString>;
6
+ agentLogicFile: z.ZodOptional<z.ZodString>;
7
+ }, z.core.$strip>;
8
+ export type PromptEntry = z.infer<typeof promptEntrySchema>;
9
+ /**
10
+ * The body of a `200` from `GET /prompts`: the absolute directory, the config file that names it, and its entries, or
11
+ * `missing` when the directory does not exist.
12
+ */
13
+ export declare const promptListSchema: z.ZodUnion<readonly [z.ZodObject<{
14
+ directory: z.ZodString;
15
+ configPath: z.ZodString;
16
+ entries: z.ZodArray<z.ZodObject<{
17
+ name: z.ZodString;
18
+ promptFile: z.ZodOptional<z.ZodString>;
19
+ agentLogicFile: z.ZodOptional<z.ZodString>;
20
+ }, z.core.$strip>>;
21
+ }, z.core.$strip>, z.ZodObject<{
22
+ directory: z.ZodString;
23
+ configPath: z.ZodString;
24
+ missing: z.ZodLiteral<true>;
25
+ }, z.core.$strip>]>;
26
+ export type PromptList = z.infer<typeof promptListSchema>;
27
+ /** The body of a `200` from `GET /prompts/files/{fileName}`. */
28
+ export declare const promptFileSchema: z.ZodObject<{
29
+ text: z.ZodString;
30
+ }, z.core.$strip>;
@@ -0,0 +1,11 @@
1
+ import { z } from 'zod';
2
+ export const promptEntrySchema = z.object({
3
+ name: z.string(),
4
+ promptFile: z.string().optional(),
5
+ agentLogicFile: z.string().optional(),
6
+ });
7
+ export const promptListSchema = z.union([
8
+ z.object({ directory: z.string(), configPath: z.string(), entries: z.array(promptEntrySchema) }),
9
+ z.object({ directory: z.string(), configPath: z.string(), missing: z.literal(true) }),
10
+ ]);
11
+ export const promptFileSchema = z.object({ text: z.string() });
@@ -0,0 +1,40 @@
1
+ import type { PromptEntry } from './prompt-directory-schemas.js';
2
+ /** The largest file, in bytes, that the file route returns. */
3
+ export declare const MAX_PROMPT_FILE_BYTES: number;
4
+ /** A directory's entries, sorted by name, or `missing` when the directory does not exist. */
5
+ export type PromptDirectoryListing = {
6
+ ok: true;
7
+ entries: PromptEntry[];
8
+ } | {
9
+ ok: false;
10
+ reason: 'missing';
11
+ };
12
+ /** The text of a listed file, or why it is not returned. */
13
+ export type PromptFileRead = {
14
+ ok: true;
15
+ text: string;
16
+ } | {
17
+ ok: false;
18
+ reason: 'missing' | 'not-listed' | 'too-large';
19
+ };
20
+ /**
21
+ * Lists the prompts and agent-logic files in a directory, grouped by base name. Only regular files are listed, so a
22
+ * subdirectory or a symlink is not; a dotfile and a file with another name are not either.
23
+ */
24
+ export declare function listPromptDirectory(directory: string): Promise<PromptDirectoryListing>;
25
+ /**
26
+ * Returns the text of a file that a fresh listing of the directory names, never joining an unlisted name onto the
27
+ * directory, so that a name cannot reach outside it.
28
+ */
29
+ export declare function readPromptDirectoryFile(directory: string, fileName: string): Promise<PromptFileRead>;
30
+ /**
31
+ * Writes a new file to the directory, refusing a name that already exists so that a write never replaces a file. The
32
+ * name must not contain a path separator.
33
+ */
34
+ export declare function writePromptDirectoryFile(directory: string, fileName: string, text: string): Promise<{
35
+ ok: true;
36
+ path: string;
37
+ } | {
38
+ ok: false;
39
+ reason: 'exists';
40
+ }>;