Skip to content

Commit a36e948

Browse files
authored
Merge pull request #273 from taras/feat/webform-elicitation
✨ Answer elicitations with a browser form, and enforce WebForm's fingerprint
2 parents 3d00dcb + 436295b commit a36e948

15 files changed

Lines changed: 497 additions & 91 deletions

‎packages/cli/src/cli.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ import { env as readEnv } from "@executablemd/runtime";
5252
import { createAcpxProvider, DEFAULT_AGENT_NAME } from "@executablemd/acp";
5353
import { installTestingComponents, TestFailureError, useTesting } from "@executablemd/testing";
5454
import { installTestAgentComponents, runTestAgentWorker } from "@executablemd/test-agent";
55-
import { installWebComponents } from "@executablemd/web";
55+
import { installWebComponents, installWebElicitation } from "@executablemd/web";
5656
import { resolveAgentConfig } from "./agent-config.ts";
5757
import type { AgentFlags } from "./agent-config.ts";
5858
import { FileStream } from "./file-stream.ts";
@@ -392,6 +392,17 @@ function* runDocument(config: DocumentConfig, mode: DocumentMode): Operation<Res
392392
// repository's own WebForm.md or WebForm.ts still wins.
393393
yield* installWebComponents();
394394

395+
// `<Elicit>` reaches a person through the same form — but only for `xmd run`.
396+
// Under `xmd test` a document that elicits without supplying an answer would
397+
// open a browser and wait for somebody who is not coming, which is a hang
398+
// rather than a test result. Leaving the provider out makes that document
399+
// fail immediately with "no elicitation provider configured", and the two
400+
// deterministic answers — an `<Answers>` region, or scripted middleware —
401+
// stay the way a test says what the answer is.
402+
if (!mode.testing) {
403+
yield* installWebElicitation();
404+
}
405+
395406
// Agent flags are exclusive to `xmd run` — `xmd test` drives agents
396407
// through the deterministic TestAgent stack instead.
397408
if (mode.agent) {

‎packages/core/src/elicitation-api.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,8 @@ export const Elicitation: Api<ElicitationApi> = createApi<ElicitationApi>("Elici
6464
throw new ElicitationProviderError(
6565
"no elicitation provider configured — a host installs one with " +
6666
'yield* Elicitation.around({ *elicit([request], next) { ... } }, { at: "min" }). ' +
67-
"Tests install scripted responses with scriptElicitations().",
67+
"`xmd run` installs the WebForm provider; under `xmd test`, supply the answer " +
68+
"with an <Answers> region.",
6869
);
6970
},
7071
});

‎packages/web/mod.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@
33
* Schema-backed local web form input for executable.md documents.
44
*
55
* `installWebComponents()` makes `<WebForm>` resolvable for the installing scope
6-
* and its descendants. `liveForm()` is the same browser interaction without the
7-
* component around it, for #197's `<Elicit>` and anything else that needs a
8-
* person's answer rather than a form element.
6+
* and its descendants. `installWebElicitation()` answers that scope's
7+
* elicitations with the same form, which is how `<Elicit>` reaches a person
8+
* under the CLI. `liveForm()` is the browser interaction on its own, for a host
9+
* that wants an answer without either component.
910
*/
1011

1112
export { installWebComponents } from "./src/components.ts";
13+
export { installWebElicitation } from "./src/elicitation.ts";
1214
export { liveForm } from "./src/live-form.ts";
1315
export type { LiveFormInput } from "./src/live-form.ts";

‎packages/web/src/WebForm.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ import type { Operation } from "effection";
3232

3333
import { parseDeclaration } from "./declaration.ts";
3434
import type { Json } from "./json.ts";
35-
import { fingerprint, persistResponse } from "./journal.ts";
35+
import { fingerprint, persistResponse, refuseChangedQuestion } from "./journal.ts";
3636
import { prepareForm, runPreparedForm } from "./live-form.ts";
3737
import { renderBody } from "./markdown.ts";
3838

@@ -58,7 +58,7 @@ export function* WebForm(props: Record<string, Json>): Operation<Json> {
5858
// First, so a failing body fails here — before a port exists to leak.
5959
const body = yield* content();
6060

61-
const declaration = parseDeclaration(props.schema, props.uiSchema);
61+
const declaration = parseDeclaration("WebForm", props.schema, props.uiSchema);
6262
const sanitized = renderBody(body);
6363

6464
const question = {
@@ -73,10 +73,16 @@ export function* WebForm(props: Record<string, Json>): Operation<Json> {
7373
// operation, where nothing has been read, bound, printed, or recorded.
7474
const prepared = prepareForm(question);
7575

76-
return yield* persistResponse(
77-
{ location: formatLocation(yield* invocation()), fingerprint: fingerprint(question) },
78-
() => runPreparedForm(prepared),
79-
);
76+
const identity = {
77+
location: formatLocation(yield* invocation()),
78+
fingerprint: fingerprint(question),
79+
};
80+
81+
// Before the record is read, so a resumed document cannot bind an answer that
82+
// was given to a different question.
83+
yield* refuseChangedQuestion(identity);
84+
85+
return yield* persistResponse(identity, () => runPreparedForm(prepared));
8086
}
8187

8288
/** `path:line:column`, `line:column`, or `unknown` — the durable identity. */

‎packages/web/src/declaration.ts‎

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -41,19 +41,23 @@ export interface Declaration {
4141
* Normalize and check a declaration.
4242
*
4343
* `schema` is required; `uiSchema` is optional and `undefined` means absent.
44+
*
45+
* `label` names the component the author actually wrote, so a diagnostic from a
46+
* form served for `<Elicit>` does not claim to come from `<WebForm>`. It mirrors
47+
* `compileParseSchema(componentName, …)` in core.
4448
*/
45-
export function parseDeclaration(schema: unknown, uiSchema?: unknown): Declaration {
46-
const normalizedSchema = readObject("schema", schema);
49+
export function parseDeclaration(label: string, schema: unknown, uiSchema?: unknown): Declaration {
50+
const normalizedSchema = readObject(label, "schema", schema);
4751

48-
rejectAsyncSchema(normalizedSchema);
49-
rejectUnsupportedNames(normalizedSchema);
50-
rejectExternalReferences(normalizedSchema);
51-
rejectInvalidDraft07(normalizedSchema);
52+
rejectAsyncSchema(label, normalizedSchema);
53+
rejectUnsupportedNames(label, normalizedSchema);
54+
rejectExternalReferences(label, normalizedSchema);
55+
rejectInvalidDraft07(label, normalizedSchema);
5256

5357
if (uiSchema === undefined) {
5458
return { schema: normalizedSchema };
5559
}
56-
return { schema: normalizedSchema, uiSchema: readObject("uiSchema", uiSchema) };
60+
return { schema: normalizedSchema, uiSchema: readObject(label, "uiSchema", uiSchema) };
5761
}
5862

5963
/**
@@ -64,26 +68,26 @@ export function parseDeclaration(schema: unknown, uiSchema?: unknown): Declarati
6468
* asserted one, and it costs one walk of a value that is about to be walked
6569
* again anyway.
6670
*/
67-
function readObject(name: string, value: unknown): JsonObject {
71+
function readObject(label: string, name: string, value: unknown): JsonObject {
6872
if (typeof value === "string") {
6973
let decoded: unknown;
7074
try {
7175
decoded = JSON.parse(value);
7276
} catch (error) {
73-
throw new DeclarationError(`<WebForm> ${name} text is not JSON: ${messageOf(error)}`);
77+
throw new DeclarationError(`<${label}> ${name} text is not JSON: ${messageOf(error)}`);
7478
}
75-
return asObject(name, decoded);
79+
return asObject(label, name, decoded);
7680
}
77-
return asObject(name, value);
81+
return asObject(label, name, value);
7882
}
7983

80-
function asObject(name: string, value: unknown): JsonObject {
84+
function asObject(label: string, name: string, value: unknown): JsonObject {
8185
try {
8286
return parseJsonObject(value);
8387
} catch (error) {
8488
if (error instanceof JsonParseError) {
8589
throw new DeclarationError(
86-
`<WebForm> ${name} must be a JSON object or JSON text describing one: ${error.message}`,
90+
`<${label}> ${name} must be a JSON object or JSON text describing one: ${error.message}`,
8791
);
8892
}
8993
throw error;
@@ -98,10 +102,10 @@ function asObject(name: string, value: unknown): JsonObject {
98102
* sides, so such a validator would report every submission as valid — a promise
99103
* is truthy. Refusing the declaration is the only place this is cheap to see.
100104
*/
101-
function rejectAsyncSchema(schema: JsonObject): void {
105+
function rejectAsyncSchema(label: string, schema: JsonObject): void {
102106
if (schema["$async"] === true) {
103107
throw new DeclarationError(
104-
"<WebForm> schema must not be asynchronous ($async: true): submission validation is synchronous.",
108+
`<${label}> schema must not be asynchronous ($async: true): submission validation is synchronous.`,
105109
);
106110
}
107111
}
@@ -122,15 +126,15 @@ function rejectAsyncSchema(schema: JsonObject): void {
122126
* not have. The same string as *data* — a `const`, an `enum` member, a title, a
123127
* default — is untouched, because nothing reads it as a key.
124128
*/
125-
function rejectUnsupportedNames(schema: JsonObject): void {
129+
function rejectUnsupportedNames(label: string, schema: JsonObject): void {
126130
walkSchema(schema, {
127131
subschema() {},
128132
declaredName(name: string, kind: NameKind, path: string) {
129133
if (name !== "__proto__") {
130134
return;
131135
}
132136
throw new DeclarationError(
133-
`<WebForm> schema declares "__proto__" as a ${kind} at ${path}, which is not ` +
137+
`<${label}> schema declares "__proto__" as a ${kind} at ${path}, which is not ` +
134138
"supported: the underlying validator loses that name, so the rule would " +
135139
"silently not apply. Rename it, or carry the value under a different key.",
136140
);
@@ -151,15 +155,15 @@ function rejectUnsupportedNames(schema: JsonObject): void {
151155
* a `const` or an `enum` member is a JSON value the author wants matched, not a
152156
* reference, and Ajv never resolves it — so neither does this.
153157
*/
154-
function rejectExternalReferences(schema: JsonObject): void {
158+
function rejectExternalReferences(label: string, schema: JsonObject): void {
155159
walkSchema(schema, {
156160
subschema(subschema: JsonObject, path: string) {
157161
const reference = subschema["$ref"];
158162
if (typeof reference !== "string" || reference.startsWith("#")) {
159163
return;
160164
}
161165
throw new DeclarationError(
162-
`<WebForm> schema references "${reference}" at ${path}, which is outside the ` +
166+
`<${label}> schema references "${reference}" at ${path}, which is outside the ` +
163167
"supplied schema. Only references contained within it resolve; external file " +
164168
"and HTTP(S) references are deferred to #192.",
165169
);
@@ -176,13 +180,13 @@ function rejectExternalReferences(schema: JsonObject): void {
176180
* pointer that does not resolve is not visible here — it surfaces when the
177181
* compiler runs, and is reported there.
178182
*/
179-
function rejectInvalidDraft07(schema: JsonObject): void {
183+
function rejectInvalidDraft07(label: string, schema: JsonObject): void {
180184
const ajv = createServerAjv();
181185
if (ajv.validateSchema(schema)) {
182186
return;
183187
}
184188
throw new DeclarationError(
185-
`<WebForm> schema is not a valid draft-07 JSON Schema: ${ajv.errorsText(ajv.errors)}`,
189+
`<${label}> schema is not a valid draft-07 JSON Schema: ${ajv.errorsText(ajv.errors)}`,
186190
);
187191
}
188192

‎packages/web/src/elicitation.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* Answering an elicitation with a browser form.
3+
*
4+
* `<Elicit>` describes a question without saying how it is asked. This is one
5+
* answer to "how": a host installs it, and every elicitation in that scope opens
6+
* the same loopback form `<WebForm>` serves.
7+
*
8+
* The adapter is deliberately thin, and what it does *not* do is the point. It
9+
* closes over nothing. It never calls `content()`, `invocation()`, or reads a
10+
* binding environment — everything it uses arrives in the request, which carries
11+
* the rendered message and the compiled schema and nothing else. No `as`, no run
12+
* identity, no journal handle crosses this boundary, so the provider cannot
13+
* depend on the component that asked and can be replaced without it noticing.
14+
*
15+
* There is no UI schema. `<Elicit>` has no way to express one, and inventing a
16+
* default here would make the same document render differently depending on
17+
* which provider a host installed. An author who wants RJSF presentation control
18+
* writes `<WebForm>`, which is exactly what it is for.
19+
*
20+
* It lives here rather than in the CLI because the sanitization boundary does.
21+
* `renderBody` is the only supported way to turn a document's markdown into
22+
* page content, and its threat model is documented beside it; exporting it so a
23+
* second package could call it correctly would be worse than keeping the one
24+
* caller here.
25+
*
26+
* `parseDeclaration` re-checks what core already refused — a `__proto__`
27+
* declared name, a reference leaving the schema. Reached through `<Elicit>`
28+
* those are unreachable, because core refuses both before any provider is
29+
* contacted. They stay as defense in depth for a host calling `liveForm`
30+
* directly, and because this module should not depend on which of its callers
31+
* happens to be strict.
32+
*/
33+
34+
import { Elicitation } from "@executablemd/core";
35+
import type { Operation } from "effection";
36+
37+
import { parseDeclaration } from "./declaration.ts";
38+
import type { Json } from "./json.ts";
39+
import { liveForm } from "./live-form.ts";
40+
import { renderBody } from "./markdown.ts";
41+
42+
/**
43+
* Answer elicitations in this scope with a browser form.
44+
*
45+
* Installed at `{ at: "min" }` like any provider: the nearest one answers, so a
46+
* document's own `<Answers>` region still wins inside it and the host's form is
47+
* what everything else falls back to.
48+
*/
49+
export function installWebElicitation(): Operation<void> {
50+
return Elicitation.around(
51+
{
52+
*elicit([request]): Operation<Json> {
53+
const declaration = parseDeclaration("Elicit", request.schema);
54+
return yield* liveForm({
55+
schema: declaration.schema,
56+
content: renderBody(request.message),
57+
});
58+
},
59+
},
60+
{ at: "min" },
61+
);
62+
}

‎packages/web/src/journal.ts‎

Lines changed: 72 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,22 @@
77
* longer exists.
88
*
99
* The description carries a fingerprint of what the person was actually asked:
10-
* the normalized schema, the normalized UI schema, and the sanitized content. A
11-
* document that changes the question changes the fingerprint, and the repository's
12-
* ordinary durability semantics take it from there — nothing here decides what a
13-
* mismatch means.
10+
* the normalized schema, the normalized UI schema, and the sanitized content.
11+
* This module decides what a mismatch means, because nothing else does — only
12+
* `type` and `name` decide whether a journal entry matches, and neither of those
13+
* changes when the question does. A recorded answer whose fingerprint is not
14+
* this run's is refused with a `StaleInputError` rather than bound: binding an
15+
* answer to a question nobody was given is the failure a human-decision
16+
* component must not have. Refusing is as far as it goes; `refuseChangedQuestion`
17+
* below says why.
1418
*/
1519

1620
import { canonicalize } from "@executablemd/core";
17-
import { createDurableOperation } from "@executablemd/durable-streams";
21+
import {
22+
createDurableOperation,
23+
ReplayGuard,
24+
StaleInputError,
25+
} from "@executablemd/durable-streams";
1826
import type { Json as DurableJson, Workflow } from "@executablemd/durable-streams";
1927
import { createHash } from "node:crypto";
2028
import type { Operation } from "effection";
@@ -24,6 +32,17 @@ import { parseJson } from "./json.ts";
2432

2533
const WEB_FORM = "web_form";
2634

35+
/** Where the answer was recorded and what question it answered. */
36+
export interface FormIdentity {
37+
/** `path:line:column` — the durable name. */
38+
location: string;
39+
fingerprint: string;
40+
}
41+
42+
function recordName(location: string): string {
43+
return `webform:${location}`;
44+
}
45+
2746
export interface FormQuestion {
2847
schema: JsonObject;
2948
uiSchema?: JsonObject;
@@ -46,18 +65,64 @@ export function fingerprint(question: FormQuestion): string {
4665
return createHash("sha256").update(canonical, "utf8").digest("hex");
4766
}
4867

68+
/**
69+
* Refuse to replay an answer to a different question.
70+
*
71+
* Only `type` and `name` decide whether a journal entry matches, and this
72+
* effect's name is its source position — so without a guard, a journal that
73+
* describes a different question would still bind its answer here. The
74+
* fingerprint is recorded so that this guard has something to compare; on its
75+
* own it is inert.
76+
*
77+
* Installed by the caller rather than by `persistResponse`, because a `Workflow`
78+
* may yield only durable effects and this is an ordinary one.
79+
*
80+
* A `StaleInputError`, so expansion propagates it rather than rendering it: the
81+
* ambient error policy must not be able to downgrade a durability failure to a
82+
* comment and let later siblings run on an answer that was never given.
83+
*
84+
* This refuses rather than re-asks. Refusing is what the durable protocol
85+
* currently offers — a guard decides between "replay" and "error", and
86+
* re-execution is named in `ReplayOutcome` as a future outcome. Failing where
87+
* the question changed is the safe half of that; #218's re-execution work is
88+
* where the other half belongs.
89+
*/
90+
export function refuseChangedQuestion(identity: FormIdentity): Operation<void> {
91+
const name = recordName(identity.location);
92+
return ReplayGuard.around({
93+
decide([event], next) {
94+
if (event.description.type !== WEB_FORM || event.description.name !== name) {
95+
return next(event);
96+
}
97+
if (event.description.input === identity.fingerprint) {
98+
return next(event);
99+
}
100+
return {
101+
outcome: "error",
102+
error: new StaleInputError(
103+
`the recorded answer for ${name} was given to a different question: the schema, the ` +
104+
"UI schema, or the rendered body has changed since it was recorded. Re-run the " +
105+
"document from the start rather than resuming from a journal that answers " +
106+
"something else.",
107+
{ coroutineId: event.coroutineId, description: event.description },
108+
),
109+
};
110+
},
111+
});
112+
}
113+
49114
/**
50115
* Run a form once and record its answer, or restore the answer already recorded.
51116
*
52117
* On replay `live` is never entered, which is what keeps a resumed document from
53118
* binding a port, printing a URL, or asking anyone anything a second time.
54119
*/
55120
export function* persistResponse(
56-
identity: { location: string; fingerprint: string },
121+
identity: FormIdentity,
57122
live: () => Operation<Json>,
58123
): Workflow<Json> {
59124
const stored = yield createDurableOperation<DurableJson>(
60-
{ type: WEB_FORM, name: `webform:${identity.location}`, input: identity.fingerprint },
125+
{ type: WEB_FORM, name: recordName(identity.location), input: identity.fingerprint },
61126
function* (): Operation<DurableJson> {
62127
return asDurable(yield* live());
63128
},

0 commit comments

Comments
 (0)