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, 03:37 UTC
| 1 | import { errorDisplayMessage } from "./errors/translatable.ts"; |
| 2 | import { |
| 3 | SecretReference, |
| 4 | secretRequestPageUrl, |
| 5 | type OrchestrationV2TurnItem, |
| 6 | type SecretProviderId, |
| 7 | type SecretRequestAnswerInput, |
| 8 | type ServerConfig, |
| 9 | type ServerSettings, |
| 10 | } from "@t3tools/contracts"; |
| 11 | import { builtInSecretProviderDefinitions } from "@t3tools/secret-provider-definitions/registry"; |
| 12 | import * as Option from "effect/Option"; |
| 13 | import * as Schema from "effect/Schema"; |
| 14 | import { mFallback, msg } from "gt-i18n"; |
| 15 | import type { MFunctionType } from "gt-i18n/types"; |
| 16 | |
| 17 | export type SecretRequestItem = Extract< |
| 18 | OrchestrationV2TurnItem, |
| 19 | { readonly type: "secret_request" } |
| 20 | >; |
| 21 | |
| 22 | /** A `file` request lets the agent's commands read the value, so its card must not promise more. */ |
| 23 | export const secretRequestPrivacyNote = ( |
| 24 | item: Pick<SecretRequestItem, "delivery" | "fields">, |
| 25 | resolve: MFunctionType = mFallback, |
| 26 | ) => |
| 27 | item.delivery !== "file" |
| 28 | ? resolve(msg("Stored securely, never shown to the agent")) |
| 29 | : item.fields === undefined |
| 30 | ? resolve( |
| 31 | msg("Kept out of chat, in a private file this agent's commands can read for 24 hours"), |
| 32 | ) |
| 33 | : resolve( |
| 34 | msg("Kept out of chat, in private files this agent's commands can read for 24 hours"), |
| 35 | ); |
| 36 | const SECRET_REQUEST_DEFAULT_PLACEHOLDER = msg("Paste the secret"); |
| 37 | |
| 38 | export interface SecretRequestInput { |
| 39 | /** Key in the card's values: the field name, or "" for a request without fields. */ |
| 40 | readonly key: string; |
| 41 | readonly label: string; |
| 42 | readonly placeholder: string; |
| 43 | /** Masked, with a toggle to show it. */ |
| 44 | readonly secret: boolean; |
| 45 | } |
| 46 | |
| 47 | export function secretRequestInputs( |
| 48 | item: Pick<SecretRequestItem, "label" | "placeholder" | "fields">, |
| 49 | resolve: MFunctionType = mFallback, |
| 50 | ): ReadonlyArray<SecretRequestInput> { |
| 51 | if (item.fields === undefined) { |
| 52 | return [ |
| 53 | { |
| 54 | key: "", |
| 55 | label: item.label, |
| 56 | placeholder: item.placeholder ?? resolve(SECRET_REQUEST_DEFAULT_PLACEHOLDER), |
| 57 | secret: true, |
| 58 | }, |
| 59 | ]; |
| 60 | } |
| 61 | return item.fields.map((field) => ({ |
| 62 | key: field.name, |
| 63 | label: field.label, |
| 64 | placeholder: field.placeholder ?? "", |
| 65 | secret: field.secret !== false, |
| 66 | })); |
| 67 | } |
| 68 | |
| 69 | // Backticks, <angle brackets> and markdown link targets (balanced parentheses allowed) keep their |
| 70 | // exact text; a bare link drops trailing sentence punctuation. |
| 71 | const REASON_LINK = |
| 72 | /`(https?:\/\/[^`\s]+)`|<(https?:\/\/[^>\s]+)>|\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))+)\)|(https?:\/\/[^\s<>"'`[\]]+)/giu; |
| 73 | /** Drops trailing sentence punctuation; a `)` stays when the link opened a matching `(`. */ |
| 74 | function trimPunctuation(link: string): string { |
| 75 | let end = link.length; |
| 76 | while (end > 0 && ".,;:!?)".includes(link[end - 1]!)) { |
| 77 | const kept = link.slice(0, end); |
| 78 | if (link[end - 1] === ")" && kept.split("(").length > kept.split(")").length - 1) break; |
| 79 | end -= 1; |
| 80 | } |
| 81 | return link.slice(0, end); |
| 82 | } |
| 83 | |
| 84 | /** Drops a closing `*` or `_` run only when the same run opened emphasis before the link and is still open. */ |
| 85 | function trimEmphasis(link: string, before: string) { |
| 86 | const run = /(\*{1,3}|_{1,3})$/u.exec(link)?.[1]; |
| 87 | if (run === undefined) return link; |
| 88 | const escaped = run.replaceAll("*", "\\*"); |
| 89 | // Nested emphasis (`**_url_**`) opens one run right after another. |
| 90 | const opener = [...before.matchAll(new RegExp(`(?:^|[\\s(*_])${escaped}(?=\\S|$)`, "gu"))].at(-1); |
| 91 | if (opener === undefined) return link; |
| 92 | const closed = new RegExp(`\\S${escaped}(?:[\\s.,;:!?)]|$)`, "u").test( |
| 93 | before.slice(opener.index + opener[0].length), |
| 94 | ); |
| 95 | return closed ? link : trimPunctuation(link.slice(0, -run.length)); |
| 96 | } |
| 97 | |
| 98 | /** The one distinct http(s) link in `reason`, for agents that put it there instead of in `url`. */ |
| 99 | function reasonLink(reason: string): string | undefined { |
| 100 | const raw = Array.from(reason.matchAll(REASON_LINK), (match) => { |
| 101 | const [, ticked, angled, target, bare] = match; |
| 102 | if (bare === undefined) return ticked ?? angled ?? target ?? ""; |
| 103 | const before = reason.slice(0, match.index); |
| 104 | let link = trimPunctuation(bare); |
| 105 | for (let next = trimEmphasis(link, before); next !== link; next = trimEmphasis(link, before)) { |
| 106 | link = next; |
| 107 | } |
| 108 | return link; |
| 109 | }); |
| 110 | // Two spellings of one page (`https://a.dev` and `https://a.dev/`) count once. |
| 111 | const links = new Set(raw.map((link) => secretRequestPageUrl(link)?.href ?? link)); |
| 112 | return links.size === 1 ? [...links][0] : undefined; |
| 113 | } |
| 114 | |
| 115 | /** Only http(s), so an agent cannot make the card open another scheme. */ |
| 116 | export function secretRequestLink(item: Pick<SecretRequestItem, "url" | "reason">) { |
| 117 | const raw = item.url ?? reasonLink(item.reason); |
| 118 | const url = raw === undefined ? null : secretRequestPageUrl(raw); |
| 119 | return url === null ? null : { href: url.href, host: url.host }; |
| 120 | } |
| 121 | |
| 122 | export type SecretRequestDisplay = |
| 123 | | { readonly kind: "pending" } |
| 124 | | { readonly kind: "pending-elsewhere"; readonly label: string } |
| 125 | | { |
| 126 | readonly kind: "answered"; |
| 127 | readonly outcome: "saved" | "declined" | "ended"; |
| 128 | readonly label: string; |
| 129 | }; |
| 130 | |
| 131 | const PENDING_DISPLAY: SecretRequestDisplay = { kind: "pending" }; |
| 132 | |
| 133 | /** |
| 134 | * `visibility` is the projected row's: a request inherited from another |
| 135 | * thread (a fork) can only be answered where it was asked. |
| 136 | */ |
| 137 | export function secretRequestDisplay( |
| 138 | item: Pick<SecretRequestItem, "secretStatus">, |
| 139 | visibility: "local" | "inherited" | "synthetic", |
| 140 | resolve: MFunctionType = mFallback, |
| 141 | ): SecretRequestDisplay { |
| 142 | switch (item.secretStatus) { |
| 143 | case "pending": |
| 144 | return visibility === "local" |
| 145 | ? PENDING_DISPLAY |
| 146 | : { |
| 147 | kind: "pending-elsewhere", |
| 148 | label: resolve(msg("Waiting for an answer in the original thread")), |
| 149 | }; |
| 150 | case "saved": |
| 151 | return { |
| 152 | kind: "answered", |
| 153 | outcome: "saved", |
| 154 | label: resolve(msg("Saved securely and kept private")), |
| 155 | }; |
| 156 | case "declined": |
| 157 | return { kind: "answered", outcome: "declined", label: resolve(msg("Declined")) }; |
| 158 | case "cancelled": |
| 159 | return { kind: "answered", outcome: "ended", label: resolve(msg("Request ended")) }; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | /** A configured secret provider a pending card can read its answer from. */ |
| 164 | export interface SecretRequestSource { |
| 165 | readonly id: SecretProviderId; |
| 166 | readonly label: string; |
| 167 | readonly isReference: (reference: string) => boolean; |
| 168 | readonly referencePlaceholder: string; |
| 169 | readonly invalidReferenceMessage: string; |
| 170 | } |
| 171 | |
| 172 | const NO_SOURCES: ReadonlyArray<SecretRequestSource> = []; |
| 173 | |
| 174 | // Secret provider packages author this text in English; the same English, translatable here. |
| 175 | const INVALID_REFERENCE_MESSAGES: ReadonlyMap<string, string> = new Map([ |
| 176 | [ |
| 177 | "Use a 1Password reference like op://vault/item/field.", |
| 178 | msg("Use a 1Password reference like {example}.", { example: "op://vault/item/field" }), |
| 179 | ], |
| 180 | ]); |
| 181 | |
| 182 | /** A secret provider's `invalidReferenceMessage` in the UI language when it is a known one. */ |
| 183 | export function invalidSecretReferenceText( |
| 184 | message: string, |
| 185 | resolve: MFunctionType = mFallback, |
| 186 | ): string { |
| 187 | const translated = INVALID_REFERENCE_MESSAGES.get(message); |
| 188 | return translated === undefined ? message : resolve(translated); |
| 189 | } |
| 190 | const decodeConfigByKind = new Map( |
| 191 | builtInSecretProviderDefinitions.definitions.map((definition) => [ |
| 192 | definition.kind, |
| 193 | Schema.decodeUnknownOption(definition.configSchema), |
| 194 | ]), |
| 195 | ); |
| 196 | |
| 197 | /** Empty unless the server accepts reference answers; providers this build cannot read are left out. */ |
| 198 | export function secretRequestSources( |
| 199 | config: Pick<ServerConfig, "secretRequestReferences"> | null | undefined, |
| 200 | providers: ServerSettings["secretProviders"], |
| 201 | resolve: MFunctionType = mFallback, |
| 202 | ): ReadonlyArray<SecretRequestSource> { |
| 203 | if (config?.secretRequestReferences !== true) return NO_SOURCES; |
| 204 | return configuredSecretSources(providers, resolve); |
| 205 | } |
| 206 | |
| 207 | export function configuredSecretSources( |
| 208 | providers: ServerSettings["secretProviders"], |
| 209 | resolve: MFunctionType = mFallback, |
| 210 | ): ReadonlyArray<SecretRequestSource> { |
| 211 | return (Object.keys(providers) as Array<SecretProviderId>).flatMap((id) => { |
| 212 | const provider = providers[id]; |
| 213 | const definition = |
| 214 | provider === undefined ? undefined : builtInSecretProviderDefinitions.find(provider.kind); |
| 215 | if ( |
| 216 | provider === undefined || |
| 217 | definition === undefined || |
| 218 | decodeConfigByKind.get(definition.kind)?.(provider.config)._tag !== "Some" |
| 219 | ) { |
| 220 | return []; |
| 221 | } |
| 222 | return [ |
| 223 | { |
| 224 | id, |
| 225 | label: provider.label, |
| 226 | isReference: definition.isReference, |
| 227 | referencePlaceholder: definition.referencePlaceholder, |
| 228 | invalidReferenceMessage: invalidSecretReferenceText( |
| 229 | definition.invalidReferenceMessage, |
| 230 | resolve, |
| 231 | ), |
| 232 | }, |
| 233 | ]; |
| 234 | }); |
| 235 | } |
| 236 | |
| 237 | const decodeSecretReference = Schema.decodeUnknownOption(SecretReference); |
| 238 | |
| 239 | /** The reference `text` names, or undefined when it is not `source`'s syntax. */ |
| 240 | export function secretRequestReference( |
| 241 | source: SecretRequestSource, |
| 242 | text: string, |
| 243 | ): SecretReference | undefined { |
| 244 | const decoded = decodeSecretReference({ provider: source.id, reference: text.trim() }); |
| 245 | return Option.isSome(decoded) && source.isReference(decoded.value.reference) |
| 246 | ? decoded.value |
| 247 | : undefined; |
| 248 | } |
| 249 | |
| 250 | /** A card value by input key. Own keys only: a field may be named `constructor`. */ |
| 251 | export const secretRequestValue = (values: Readonly<Record<string, string>>, key: string) => |
| 252 | Object.hasOwn(values, key) ? (values[key] ?? "") : ""; |
| 253 | |
| 254 | export type SecretRequestReply = |
| 255 | /** Keyed by `SecretRequestInput.key`. */ |
| 256 | | { readonly type: "save"; readonly values: Readonly<Record<string, string>> } |
| 257 | /** Single-value cards only: the server reads it through `source`. */ |
| 258 | | { readonly type: "reference"; readonly source: SecretRequestSource; readonly reference: string } |
| 259 | | { readonly type: "decline" }; |
| 260 | |
| 261 | /** Null until every input has a value, or while a reference is not `source`'s syntax. */ |
| 262 | export function secretRequestAnswerInput( |
| 263 | item: Pick<SecretRequestItem, "id" | "threadId" | "label" | "placeholder" | "fields">, |
| 264 | answer: SecretRequestReply, |
| 265 | ): SecretRequestAnswerInput | null { |
| 266 | const base = { threadId: item.threadId, turnItemId: item.id }; |
| 267 | if (answer.type === "decline") return { ...base, answer: { type: "decline" } }; |
| 268 | if (answer.type === "reference") { |
| 269 | const reference = |
| 270 | item.fields === undefined |
| 271 | ? secretRequestReference(answer.source, answer.reference) |
| 272 | : undefined; |
| 273 | return reference === undefined ? null : { ...base, answer: { type: "reference", reference } }; |
| 274 | } |
| 275 | const entries = secretRequestInputs(item).map( |
| 276 | (input) => [input.key, secretRequestValue(answer.values, input.key).trim()] as const, |
| 277 | ); |
| 278 | if (entries.some(([, value]) => value.length === 0)) return null; |
| 279 | if (item.fields === undefined) { |
| 280 | return { ...base, answer: { type: "save", secret: entries[0]?.[1] ?? "" } }; |
| 281 | } |
| 282 | |
| 283 | return { ...base, answer: { type: "save", values: Object.fromEntries(entries) } }; |
| 284 | } |
| 285 | |
| 286 | const USER_FACING_FAILURE_TAGS = new Set(["SecretRequestError", "EnvironmentAuthorizationError"]); |
| 287 | |
| 288 | /** |
| 289 | * Only known server errors pass their message through: anything else (transport or encoding |
| 290 | * failures) gets the generic copy, so the typed value can never surface in the UI. |
| 291 | */ |
| 292 | export function secretRequestFailureMessage( |
| 293 | failure: unknown, |
| 294 | resolve: MFunctionType = mFallback, |
| 295 | ): string { |
| 296 | if ( |
| 297 | typeof failure === "object" && |
| 298 | failure !== null && |
| 299 | "_tag" in failure && |
| 300 | typeof failure._tag === "string" && |
| 301 | USER_FACING_FAILURE_TAGS.has(failure._tag) && |
| 302 | "message" in failure && |
| 303 | typeof failure.message === "string" && |
| 304 | failure.message.trim().length > 0 |
| 305 | ) { |
| 306 | return errorDisplayMessage(failure, resolve) ?? failure.message; |
| 307 | } |
| 308 | return resolve(msg("Could not answer the request. Try again.")); |
| 309 | } |