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