Repository navigation
Expand file tree
/
Copy pathapprovalFormatter.ts
More file actions
197 lines (163 loc) · 6.36 KB
/
Copy pathapprovalFormatter.ts
File metadata and controls
197 lines (163 loc) · 6.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import { logger, type AdminForthResource, type IAdminForth } from "adminforth";
import { getErrorMessage } from "../shared/errors.js";
/** One tool call awaiting approval, normalized out of the provider interrupt payload. */
export type ApprovalRequest = {
toolName: string;
args: Record<string, unknown>;
};
/** One value on the approval card; `from` is the stored value an update replaces. */
export type ApprovalField = {
label: string;
from?: string;
to: string;
};
/** A tool call awaiting approval, described for the approval card. */
export type ApprovalDescription = {
/** What the call does and to which record, e.g. `Update record with id:10 in Cars`. */
summary: string;
/** The values the call writes, in the resource's own wording. */
fields: ApprovalField[];
};
/** Argument keys that address the call itself rather than the data being changed. */
const NON_FIELD_KEYS = new Set(["resourceId", "recordId", "primaryKey", "requiredColumnsToSkip", "meta", "extra"]);
const MAX_VALUE_LENGTH = 80;
function truncate(text: string, limit = MAX_VALUE_LENGTH): string {
return text.length > limit ? `${text.slice(0, limit - 1)}…` : text;
}
function findResource(adminforth: IAdminForth, resourceId?: unknown): AdminForthResource | undefined {
return typeof resourceId === "string"
? (adminforth.config?.resources ?? []).find((resource) => resource.resourceId === resourceId)
: undefined;
}
function resourceLabel(resource: AdminForthResource | undefined, args: Record<string, unknown>): string {
return resource?.label ?? (typeof args.resourceId === "string" ? args.resourceId : "resource");
}
/** `first_name` / `firstName` -> `First name`, for keys the resource does not declare. */
function humanize(name: string): string {
const spaced = name.replace(/[_-]+/g, " ").replace(/([a-z\d])([A-Z])/g, "$1 $2").trim();
return spaced ? `${spaced[0].toUpperCase()}${spaced.slice(1).toLowerCase()}` : name;
}
function formatValue(value: unknown, column?: any): string {
if (value === undefined || value === null || value === "") {
return "empty";
}
if (column?.masked || column?.backendOnly) {
return "••••••";
}
if (typeof value === "boolean") {
return value ? "Yes" : "No";
}
const enumLabel = Array.isArray(column?.enum)
? column.enum.find((item: any) => item.value === value)?.label
: undefined;
if (enumLabel) {
return truncate(String(enumLabel));
}
if (Array.isArray(value)) {
return truncate(value.map((item) => formatValue(item)).join(", "));
}
if (typeof value === "object") {
return truncate(JSON.stringify(value));
}
return truncate(String(value));
}
/**
* The record payload as labelled values in the resource's own wording. Every field is
* listed: the admin approves exactly what will be written. With `oldRecord` each value is
* paired with the one it replaces.
*/
function describeFields(
record: unknown,
resource: AdminForthResource | undefined,
oldRecord?: Record<string, unknown>,
): ApprovalField[] {
if (record === null || typeof record !== "object" || Array.isArray(record)) {
return [];
}
const columnsByName = new Map((resource?.columns ?? []).map((column) => [column.name, column]));
return Object.entries(record as Record<string, unknown>)
.filter(([key]) => !NON_FIELD_KEYS.has(key))
.map(([name, value]) => {
const column = columnsByName.get(name);
return {
label: column?.label || humanize(name),
from: oldRecord ? formatValue(oldRecord[name], column) : undefined,
to: formatValue(value, column),
};
});
}
/**
* The stored record an update would change, read the same way the update endpoint reads it.
* The preview must never block the approval prompt, so a failed read only drops the old values.
*/
async function loadRecord(
adminforth: IAdminForth,
resource: AdminForthResource | undefined,
recordId: unknown,
): Promise<Record<string, unknown> | undefined> {
if (!resource) {
return undefined;
}
try {
return await adminforth.connectors[resource.dataSource].getRecordByPrimaryKey(resource, String(recordId)) ?? undefined;
} catch (error) {
logger.warn(`Approval preview: failed to read record ${String(recordId)} of "${resource.resourceId}": ${getErrorMessage(error)}`);
return undefined;
}
}
function actionLabel(resource: AdminForthResource | undefined, actionId: unknown): string {
if (typeof actionId !== "string" || !actionId) {
return "action";
}
const action = (resource?.options?.actions ?? []).find((candidate: any) => candidate.id === actionId);
return `"${action?.name || humanize(actionId)}"`;
}
/**
* Describe a tool call awaiting approval so an admin (not a developer) can act on it —
* resource and column labels instead of ids, values instead of raw JSON, and for an
* update the current value next to each new one. Tool calls it does not recognize are
* shown as their arguments.
*/
export async function formatApprovalRequest(
adminforth: IAdminForth,
request: ApprovalRequest,
): Promise<ApprovalDescription> {
const { args, toolName } = request;
const resource = findResource(adminforth, args.resourceId);
const label = resourceLabel(resource, args);
switch (toolName) {
case "create_record":
return {
summary: `Create a new record in ${label}`,
fields: describeFields(args.record, resource),
};
case "update_record":
return {
summary: `Update record with id:${formatValue(args.recordId)} in ${label}`,
fields: describeFields(args.record, resource, await loadRecord(adminforth, resource, args.recordId)),
};
case "delete_record":
return {
summary: `Delete record with id:${formatValue(args.primaryKey)} from ${label} — this cannot be undone`,
fields: [],
};
case "start_custom_action":
return {
summary: `Run ${actionLabel(resource, args.actionId)} on record ${formatValue(args.recordId)} in ${label}`,
fields: [],
};
case "start_custom_bulk_action":
case "start_bulk_action": {
const count = Array.isArray(args.recordIds) ? args.recordIds.length : 0;
return {
summary: `Run ${actionLabel(resource, args.actionId)} on ${count} record(s) in ${label}`,
fields: [],
};
}
default:
return {
summary: humanize(toolName),
fields: describeFields(args, resource),
};
}
}