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, type Msg } from "gt-i18n";
15import type { M } from "gt-i18n";
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" | "fields">,
25 resolve: M = 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 );
36const SECRET_REQUEST_DEFAULT_PLACEHOLDER = msg("Paste the secret");
37
38export 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
47export function secretRequestInputs(
48 item: Pick<SecretRequestItem, "label" | "placeholder" | "fields">,
49 resolve: M = 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.
71const REASON_LINK =
72 /`(https?:\/\/[^`\s]+)`|<(https?:\/\/[^>\s]+)>|\]\((https?:\/\/(?:[^()\s]|\([^()\s]*\))+)\)|(https?:\/\/(?:[^\s<>"'`[\]]|\[[^\s<>"'`[\]]*\])+)/giu;
73/** Drops trailing sentence punctuation; a `)` stays when the link opened a matching `(`. */
74function 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. */
85function 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`. */
99function 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. */
116export 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
122export 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
131const 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 */
137export function secretRequestDisplay(
138 item: Pick<SecretRequestItem, "secretStatus">,
139 visibility: "local" | "inherited" | "synthetic",
140 resolve: M = 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. */
164export 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
172const NO_SOURCES: ReadonlyArray<SecretRequestSource> = [];
173
174// Secret provider packages author this text in English; the same English, translatable here.
175const INVALID_REFERENCE_MESSAGES: ReadonlyMap<string, string | Msg> = new Map([
176 [
177 "Use a 1Password reference like op://vault/item/field.",
178 msg`Use a 1Password reference like ${{ example: "op://vault/item/field" }}.`,
179 ],
180]);
181
182/** A secret provider's `invalidReferenceMessage` in the UI language when it is a known one. */
183export function invalidSecretReferenceText(message: string, resolve: M = mFallback): string {
184 const translated = INVALID_REFERENCE_MESSAGES.get(message);
185 return translated === undefined ? message : resolve(translated);
186}
187const decodeConfigByKind = new Map(
188 builtInSecretProviderDefinitions.definitions.map((definition) => [
189 definition.kind,
190 Schema.decodeUnknownOption(definition.configSchema),
191 ]),
192);
193
194/** Empty unless the server accepts reference answers; providers this build cannot read are left out. */
195export function secretRequestSources(
196 config: Pick<ServerConfig, "secretRequestReferences"> | null | undefined,
197 providers: ServerSettings["secretProviders"],
198 resolve: M = mFallback,
199): ReadonlyArray<SecretRequestSource> {
200 if (config?.secretRequestReferences !== true) return NO_SOURCES;
201 return configuredSecretSources(providers, resolve);
202}
203
204export function configuredSecretSources(
205 providers: ServerSettings["secretProviders"],
206 resolve: M = mFallback,
207): ReadonlyArray<SecretRequestSource> {
208 return (Object.keys(providers) as Array<SecretProviderId>).flatMap((id) => {
209 const provider = providers[id];
210 const definition =
211 provider === undefined ? undefined : builtInSecretProviderDefinitions.find(provider.kind);
212 if (
213 provider === undefined ||
214 definition === undefined ||
215 decodeConfigByKind.get(definition.kind)?.(provider.config)._tag !== "Some"
216 ) {
217 return [];
218 }
219 return [
220 {
221 id,
222 label: provider.label,
223 isReference: definition.isReference,
224 referencePlaceholder: definition.referencePlaceholder,
225 invalidReferenceMessage: invalidSecretReferenceText(
226 definition.invalidReferenceMessage,
227 resolve,
228 ),
229 },
230 ];
231 });
232}
233
234const decodeSecretReference = Schema.decodeUnknownOption(SecretReference);
235
236/** The reference `text` names, or undefined when it is not `source`'s syntax. */
237export function secretRequestReference(
238 source: SecretRequestSource,
239 text: string,
240): SecretReference | undefined {
241 const decoded = decodeSecretReference({ provider: source.id, reference: text.trim() });
242 return Option.isSome(decoded) && source.isReference(decoded.value.reference)
243 ? decoded.value
244 : undefined;
245}
246
247/** A card value by input key. Own keys only: a field may be named `constructor`. */
248export const secretRequestValue = (values: Readonly<Record<string, string>>, key: string) =>
249 Object.hasOwn(values, key) ? (values[key] ?? "") : "";
250
251export type SecretRequestReply =
252 /** Keyed by `SecretRequestInput.key`. */
253 | { readonly type: "save"; readonly values: Readonly<Record<string, string>> }
254 /** Single-value cards only: the server reads it through `source`. */
255 | { readonly type: "reference"; readonly source: SecretRequestSource; readonly reference: string }
256 | { readonly type: "decline" };
257
258/** Null until every input has a value, or while a reference is not `source`'s syntax. */
259export function secretRequestAnswerInput(
260 item: Pick<SecretRequestItem, "id" | "threadId" | "label" | "placeholder" | "fields">,
261 answer: SecretRequestReply,
262): SecretRequestAnswerInput | null {
263 const base = { threadId: item.threadId, turnItemId: item.id };
264 if (answer.type === "decline") return { ...base, answer: { type: "decline" } };
265 if (answer.type === "reference") {
266 const reference =
267 item.fields === undefined
268 ? secretRequestReference(answer.source, answer.reference)
269 : undefined;
270 return reference === undefined ? null : { ...base, answer: { type: "reference", reference } };
271 }
272 const entries = secretRequestInputs(item).map(
273 (input) => [input.key, secretRequestValue(answer.values, input.key).trim()] as const,
274 );
275 if (entries.some(([, value]) => value.length === 0)) return null;
276 if (item.fields === undefined) {
277 return { ...base, answer: { type: "save", secret: entries[0]?.[1] ?? "" } };
278 }
279
280 return { ...base, answer: { type: "save", values: Object.fromEntries(entries) } };
281}
282
283const USER_FACING_FAILURE_TAGS = new Set(["SecretRequestError", "EnvironmentAuthorizationError"]);
284
285/**
286 * Only known server errors pass their message through: anything else (transport or encoding
287 * failures) gets the generic copy, so the typed value can never surface in the UI.
288 */
289export function secretRequestFailureMessage(failure: unknown, resolve: M = mFallback): string {
290 if (
291 typeof failure === "object" &&
292 failure !== null &&
293 "_tag" in failure &&
294 typeof failure._tag === "string" &&
295 USER_FACING_FAILURE_TAGS.has(failure._tag) &&
296 "message" in failure &&
297 typeof failure.message === "string" &&
298 failure.message.trim().length > 0
299 ) {
300 return errorDisplayMessage(failure, resolve) ?? failure.message;
301 }
302 return resolve(msg("Could not answer the request. Try again."));
303}