The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import type { |
| 2 | OrchestrationV2UserInputQuestion, |
| 3 | ProviderUserInputAnswers, |
| 4 | } from "@t3tools/contracts"; |
| 5 | import type * as EffectAcpSchema from "effect-acp/compat"; |
| 6 | |
| 7 | import { unknownRecord } from "./clientPolicy.ts"; |
| 8 | |
| 9 | type Field = |
| 10 | | { readonly kind: "text" } |
| 11 | | { readonly kind: "number"; readonly integer: boolean } |
| 12 | | { readonly kind: "boolean" } |
| 13 | | { readonly kind: "choice"; readonly values: ReadonlySet<string> } |
| 14 | | { |
| 15 | readonly kind: "multiChoice"; |
| 16 | readonly values: ReadonlySet<string>; |
| 17 | readonly minItems: number; |
| 18 | readonly maxItems: number; |
| 19 | }; |
| 20 | |
| 21 | type Option = OrchestrationV2UserInputQuestion["options"][number]; |
| 22 | |
| 23 | export interface ElicitationForm { |
| 24 | readonly questions: ReadonlyArray<OrchestrationV2UserInputQuestion>; |
| 25 | /** |
| 26 | * Types answers as the schema declares them. Unknown keys and options are |
| 27 | * dropped, as is an answer that does not fit its field. Returns undefined |
| 28 | * when a required field is left without a valid answer. |
| 29 | */ |
| 30 | readonly content: ( |
| 31 | answers: ProviderUserInputAnswers, |
| 32 | ) => Record<string, EffectAcpSchema.ElicitationContentValue> | undefined; |
| 33 | } |
| 34 | |
| 35 | function text(value: unknown): string | undefined { |
| 36 | return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined; |
| 37 | } |
| 38 | |
| 39 | /** All of `entries` as options, or undefined when any entry cannot be one. */ |
| 40 | function choiceOptions( |
| 41 | entries: unknown, |
| 42 | toOption: (entry: unknown) => Option | undefined, |
| 43 | ): Option[] | undefined { |
| 44 | if (!Array.isArray(entries) || entries.length === 0) return undefined; |
| 45 | const options = entries.map(toOption); |
| 46 | return options.every((option) => option !== undefined) ? options : undefined; |
| 47 | } |
| 48 | |
| 49 | function enumOptions(entries: unknown): Option[] | undefined { |
| 50 | if ( |
| 51 | !Array.isArray(entries) || |
| 52 | entries.length === 0 || |
| 53 | !entries.every((value): value is string => typeof value === "string") |
| 54 | ) |
| 55 | return undefined; |
| 56 | const counts = new Map<string, number>(); |
| 57 | for (const value of entries) counts.set(value.trim(), (counts.get(value.trim()) ?? 0) + 1); |
| 58 | const options = entries.map((value) => { |
| 59 | const plain = value.trim(); |
| 60 | const label = plain !== "" && counts.get(plain) === 1 ? plain : JSON.stringify(value); |
| 61 | return { label, description: label, value }; |
| 62 | }); |
| 63 | // A quoted fallback can collide with a literal label; quote every value in that case. |
| 64 | return new Set(options.map((option) => option.label)).size === options.length |
| 65 | ? options |
| 66 | : options.map((option) => { |
| 67 | const label = JSON.stringify(option.value); |
| 68 | return { ...option, label, description: label }; |
| 69 | }); |
| 70 | } |
| 71 | |
| 72 | /** Titled entries (`oneOf` on strings, `anyOf` on array items) carry a title for their `const`. */ |
| 73 | function titledOption(entry: unknown): Option | undefined { |
| 74 | const option = unknownRecord(entry); |
| 75 | const label = text(option?.title) ?? text(option?.const); |
| 76 | return typeof option?.const === "string" && label !== undefined |
| 77 | ? { label, description: text(option.description) ?? label, value: option.const } |
| 78 | : undefined; |
| 79 | } |
| 80 | |
| 81 | function parseField( |
| 82 | property: Readonly<Record<string, unknown>>, |
| 83 | ): { readonly field: Field; readonly options: Option[] } | undefined { |
| 84 | switch (property.type) { |
| 85 | case "string": { |
| 86 | // ACP treats a null `enum` or `oneOf` like an omitted one. |
| 87 | if ((property.enum ?? property.oneOf ?? undefined) === undefined) { |
| 88 | return { field: { kind: "text" }, options: [] }; |
| 89 | } |
| 90 | const options = Array.isArray(property.oneOf) |
| 91 | ? choiceOptions(property.oneOf, titledOption) |
| 92 | : enumOptions(property.enum); |
| 93 | return options === undefined |
| 94 | ? undefined |
| 95 | : { |
| 96 | field: { kind: "choice", values: new Set(options.map(optionValue)) }, |
| 97 | options, |
| 98 | }; |
| 99 | } |
| 100 | case "array": { |
| 101 | // String items list plain values in `enum`; titled items list `{ const, title }` in `anyOf`. |
| 102 | const items = unknownRecord(property.items); |
| 103 | const options = |
| 104 | items?.type === "string" |
| 105 | ? enumOptions(items.enum) |
| 106 | : items !== undefined && items.type === undefined |
| 107 | ? choiceOptions(items.anyOf, titledOption) |
| 108 | : undefined; |
| 109 | if (options === undefined) return undefined; |
| 110 | // The schema decode already limits counts to non-negative integers. |
| 111 | const values = new Set(options.map(optionValue)); |
| 112 | const minItems = typeof property.minItems === "number" ? property.minItems : 0; |
| 113 | const maxItems = typeof property.maxItems === "number" ? property.maxItems : Infinity; |
| 114 | // Clients require a selection, so empty-only questions cannot be answered. |
| 115 | if (maxItems === 0 || minItems > maxItems || minItems > values.size) return undefined; |
| 116 | return { field: { kind: "multiChoice", values, minItems, maxItems }, options }; |
| 117 | } |
| 118 | case "boolean": |
| 119 | return { |
| 120 | field: { kind: "boolean" }, |
| 121 | options: [ |
| 122 | { label: "true", description: "Yes", value: "true" }, |
| 123 | { label: "false", description: "No", value: "false" }, |
| 124 | ], |
| 125 | }; |
| 126 | case "number": |
| 127 | case "integer": |
| 128 | return { field: { kind: "number", integer: property.type === "integer" }, options: [] }; |
| 129 | default: |
| 130 | return undefined; |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | function optionValue(option: Option): string { |
| 135 | return option.value ?? option.label; |
| 136 | } |
| 137 | |
| 138 | function typedAnswer( |
| 139 | field: Field, |
| 140 | answer: unknown, |
| 141 | ): EffectAcpSchema.ElicitationContentValue | undefined { |
| 142 | switch (field.kind) { |
| 143 | case "text": |
| 144 | return typeof answer === "string" ? answer : undefined; |
| 145 | case "boolean": |
| 146 | if (typeof answer === "boolean") return answer; |
| 147 | return answer === "true" ? true : answer === "false" ? false : undefined; |
| 148 | case "number": { |
| 149 | const parsed = |
| 150 | typeof answer === "number" |
| 151 | ? answer |
| 152 | : typeof answer === "string" && answer.trim().length > 0 |
| 153 | ? Number(answer.trim()) |
| 154 | : Number.NaN; |
| 155 | if (!Number.isFinite(parsed)) return undefined; |
| 156 | return field.integer && !Number.isInteger(parsed) ? undefined : parsed; |
| 157 | } |
| 158 | case "choice": |
| 159 | return typeof answer === "string" && field.values.has(answer) ? answer : undefined; |
| 160 | case "multiChoice": { |
| 161 | if (!Array.isArray(answer)) return undefined; |
| 162 | const selected = [ |
| 163 | ...new Set( |
| 164 | answer.filter( |
| 165 | (entry): entry is string => typeof entry === "string" && field.values.has(entry), |
| 166 | ), |
| 167 | ), |
| 168 | ]; |
| 169 | // `[]` is an explicit empty selection, but a selection of only unknown |
| 170 | // options is not one. |
| 171 | if (selected.length === 0 && answer.length > 0) return undefined; |
| 172 | return selected.length >= field.minItems && selected.length <= field.maxItems |
| 173 | ? selected |
| 174 | : undefined; |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // Decline unaskable forms; validate types and selection counts, leaving other constraints to the agent. |
| 180 | // `allowOther` lets single choices take typed text, sent as the field's value. |
| 181 | export function parseElicitationForm( |
| 182 | requestedSchema: unknown, |
| 183 | message: string, |
| 184 | { allowOther = false }: { readonly allowOther?: boolean } = {}, |
| 185 | ): ElicitationForm | undefined { |
| 186 | const schema = unknownRecord(requestedSchema); |
| 187 | const required = new Set( |
| 188 | Array.isArray(schema?.required) |
| 189 | ? schema.required.filter((key): key is string => typeof key === "string") |
| 190 | : [], |
| 191 | ); |
| 192 | const fields = new Map<string, Field>(); |
| 193 | const parsedFields: Array<{ |
| 194 | readonly id: string; |
| 195 | readonly property: Readonly<Record<string, unknown>>; |
| 196 | readonly options: Option[]; |
| 197 | }> = []; |
| 198 | for (const [id, value] of Object.entries(unknownRecord(schema?.properties) ?? {})) { |
| 199 | const property = unknownRecord(value); |
| 200 | const parsed = property === undefined ? undefined : parseField(property); |
| 201 | // Question ids must survive the contract's trim to round-trip answers. |
| 202 | if (property === undefined || parsed === undefined || text(id) !== id) return undefined; |
| 203 | fields.set(id, parsed.field); |
| 204 | parsedFields.push({ id, property, options: parsed.options }); |
| 205 | } |
| 206 | // An optional `<id>__other` text field (OMP's ask dialog) is the free-text answer to |
| 207 | // optional single choice `<id>`: ask them as one question and send custom text to the |
| 208 | // companion. Multi-select keeps both fields, since it can answer with options and text. |
| 209 | const companions = new Map<string, string>(); |
| 210 | for (const [id, field] of fields) { |
| 211 | const companionId = `${id}__other`; |
| 212 | if ( |
| 213 | field.kind === "choice" && |
| 214 | fields.get(companionId)?.kind === "text" && |
| 215 | !required.has(id) && |
| 216 | !required.has(companionId) |
| 217 | ) { |
| 218 | companions.set(id, companionId); |
| 219 | } |
| 220 | } |
| 221 | const folded = new Set(companions.values()); |
| 222 | const questions: OrchestrationV2UserInputQuestion[] = []; |
| 223 | for (const { id, property, options } of parsedFields) { |
| 224 | if (folded.has(id)) continue; |
| 225 | const kind = fields.get(id)?.kind; |
| 226 | questions.push({ |
| 227 | id, |
| 228 | header: text(property.title) ?? `Question ${questions.length + 1}`, |
| 229 | question: text(property.description) ?? message, |
| 230 | options, |
| 231 | ...(kind === "text" || |
| 232 | kind === "number" || |
| 233 | companions.has(id) || |
| 234 | (allowOther && kind === "choice") |
| 235 | ? {} |
| 236 | : { allowCustomAnswer: false }), |
| 237 | ...(kind === "multiChoice" ? { multiSelect: true } : {}), |
| 238 | ...(kind === "text" && !required.has(id) ? { required: false } : {}), |
| 239 | }); |
| 240 | } |
| 241 | return { |
| 242 | questions, |
| 243 | content: (answers) => { |
| 244 | const entries: Array<[string, EffectAcpSchema.ElicitationContentValue]> = []; |
| 245 | for (const [id, field] of fields) { |
| 246 | if (folded.has(id)) continue; |
| 247 | const answer = Object.hasOwn(answers, id) ? answers[id] : undefined; |
| 248 | const typed = answer === undefined ? undefined : typedAnswer(field, answer); |
| 249 | const companionId = companions.get(id); |
| 250 | if (typed !== undefined) entries.push([id, typed]); |
| 251 | else if ( |
| 252 | allowOther && |
| 253 | field.kind === "choice" && |
| 254 | typeof answer === "string" && |
| 255 | answer.trim() !== "" |
| 256 | ) { |
| 257 | entries.push([id, answer]); |
| 258 | } else if (companionId !== undefined && typeof answer === "string") { |
| 259 | entries.push([companionId, answer]); |
| 260 | } else if (required.has(id)) return undefined; |
| 261 | } |
| 262 | // Own properties for every field, `__proto__` included; assigning to |
| 263 | // `{}` would hit its inherited setter instead. |
| 264 | return Object.fromEntries(entries); |
| 265 | }, |
| 266 | }; |
| 267 | } |