@vite-hub/presets 0.0.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,93 @@
1
+ import { AgentDefinition, AgentInvocationContextValues, AgentInvoker, AgentRuntimeConfig, AgentRuntimeContext, ConfiguredAgentDefinition } from "@vite-hub/agent";
2
+ import { GmailClient, GmailLabelSettings } from "@vite-hub/agent/channels";
3
+ //#region src/labeller.d.ts
4
+ export interface LabellerLabel extends GmailLabelSettings {}
5
+ export type LabellerPattern = string | readonly string[];
6
+ export interface LabellerRule {
7
+ from?: LabellerPattern;
8
+ to?: LabellerPattern;
9
+ subject?: LabellerPattern;
10
+ body?: LabellerPattern;
11
+ listId?: LabellerPattern;
12
+ hasLabel?: LabellerPattern;
13
+ header?: Readonly<Record<string, LabellerPattern>>;
14
+ not?: LabellerRule;
15
+ label?: string;
16
+ archive?: boolean;
17
+ read?: boolean;
18
+ star?: boolean;
19
+ trash?: boolean;
20
+ }
21
+ export interface LabellerAction {
22
+ archive?: boolean;
23
+ read?: boolean;
24
+ star?: boolean;
25
+ trash?: boolean;
26
+ }
27
+ /** Moves mail with a declared `label` that is older than `olderThan` days to Trash. Starred mail stays. */
28
+ export interface LabellerCleanupRule {
29
+ /** Gmail label name. Nested labels use `Parent/Child`. */
30
+ label: string;
31
+ /** Age in whole days. */
32
+ olderThan: number;
33
+ }
34
+ export interface LabellerOptions {
35
+ /** Labels the Agent may set. Jev chooses only among labels with a `description`; a label without one is set only by rules. */
36
+ labels: Readonly<Record<string, LabellerLabel>>;
37
+ rules: Readonly<Record<string, LabellerRule>>;
38
+ actions: Readonly<Record<string, LabellerAction>>;
39
+ cleanup: Readonly<Record<string, LabellerCleanupRule>>;
40
+ bodyLimit: number;
41
+ dryRun: boolean;
42
+ /** Hide Gmail labels that `labels` does not declare from Gmail's label list when `vitehub channels sync` applies. */
43
+ hideUnmanagedLabels: boolean;
44
+ /** Syncs that try one failing message before the Gmail Channel skips it. Defaults to the Channel's 5. */
45
+ maxAttempts?: number;
46
+ minConfidence: number;
47
+ /**
48
+ * Remove the other declared labels when a message gets its label, and every declared label when no label fits.
49
+ * Use it to correct earlier labels with a replay. Defaults to `false`, which only adds a label.
50
+ */
51
+ relabel: boolean;
52
+ trashEnabled: boolean;
53
+ client?: GmailClient;
54
+ }
55
+ export interface LabellerDecision {
56
+ label: string;
57
+ rule?: string;
58
+ }
59
+ type LabellerResult = {
60
+ label: string | {
61
+ choice?: unknown;
62
+ confidence?: unknown;
63
+ probabilities?: Record<string, unknown>;
64
+ };
65
+ rule?: string;
66
+ };
67
+ type LabellerDefinition = AgentDefinition<AgentRuntimeConfig, unknown, AgentInvoker, AgentInvocationContextValues, LabellerResult | LabellerDecision>;
68
+ export type LabellerAgent = ConfiguredAgentDefinition<LabellerOptions, LabellerDefinition>;
69
+ /** Gmail labelling preset: ordered rules first, then a constrained Jev choice. */
70
+ export declare const labeller: LabellerAgent;
71
+ export interface CleanupLabellerOptions {
72
+ /** Move the matches to Trash. Without it, or while the Agent has `dryRun: true` or `trashEnabled: false`, the function only lists them. */
73
+ apply?: boolean;
74
+ /** Runtime Context for Server Env and Cloudflare bindings. Omit it outside a host request. */
75
+ runtime?: AgentRuntimeContext;
76
+ }
77
+ export interface LabellerCleanupRuleResult {
78
+ /** IDs of the matching messages, at most 500 per rule. */
79
+ messageIds: string[];
80
+ /** Gmail search query of the rule. */
81
+ query: string;
82
+ rule: string;
83
+ }
84
+ export interface CleanupLabellerResult {
85
+ applied: boolean;
86
+ rules: LabellerCleanupRuleResult[];
87
+ }
88
+ /**
89
+ * Runs the Labeller's `cleanup` rules on its Gmail Channel, at most 500 messages per rule.
90
+ * Call it from a daily Schedule: each run continues with the matches that remain.
91
+ */
92
+ export declare function cleanupLabeller(agent: LabellerAgent, options?: CleanupLabellerOptions): Promise<CleanupLabellerResult>;
93
+ //#endregion
@@ -0,0 +1,289 @@
1
+ import { i as isRuntimeRecord, t as presetsErrorDiagnostics } from "./error-diagnostics-BTBW9sZx.js";
2
+ import { defineAgent } from "@vite-hub/agent";
3
+ import { hasRuntimeType, isRuntimeObject } from "@vite-hub/runtime/internal/runtime-type";
4
+ import * as v from "valibot";
5
+ import { channelMessageContextKey, gmail, gmailClient } from "@vite-hub/agent/channels";
6
+ import { ask } from "@vite-hub/gateways";
7
+ //#region src/labeller.ts
8
+ const maxBodyLimit = 1e5;
9
+ const maxPatternLength = 256;
10
+ const maxHeaderValueLength = 1e3;
11
+ const reservedLabels = /* @__PURE__ */ new Set([
12
+ "NONE",
13
+ "INBOX",
14
+ "TRASH",
15
+ "SPAM",
16
+ "UNREAD",
17
+ "STARRED",
18
+ "IMPORTANT",
19
+ "SENT",
20
+ "DRAFT",
21
+ "ALL",
22
+ "CATEGORY_PERSONAL",
23
+ "CATEGORY_SOCIAL",
24
+ "CATEGORY_PROMOTIONS",
25
+ "CATEGORY_UPDATES",
26
+ "CATEGORY_FORUMS"
27
+ ]);
28
+ function validateLabels(labels) {
29
+ if (!isRuntimeObject(labels) || Array.isArray(labels)) throw presetsErrorDiagnostics.PRESETS_LABELLER_LABELS_INVALID();
30
+ for (const [name, value] of Object.entries(labels)) {
31
+ if (!name.trim() || name.length > 225 || /\p{Cc}/u.test(name) || reservedLabels.has(name.toUpperCase())) throw presetsErrorDiagnostics.PRESETS_LABELLER_LABEL_NAME_INVALID({ name });
32
+ if (!isRuntimeObject(value) || Array.isArray(value)) throw presetsErrorDiagnostics.PRESETS_LABELLER_LABEL_SETTINGS_INVALID({ name });
33
+ }
34
+ }
35
+ function patternList(value) {
36
+ if (value === void 0) return;
37
+ const values = Array.isArray(value) ? value : [value];
38
+ if (!values.length || values.some((item) => !hasRuntimeType(item, "string") || item.length === 0 || item.length > maxPatternLength)) throw presetsErrorDiagnostics.PRESETS_LABELLER_PATTERN_INVALID({ max: maxPatternLength });
39
+ return values;
40
+ }
41
+ function compilePattern(value) {
42
+ const regex = /^\/(.*)\/([a-z]*)$/.exec(value);
43
+ if (!regex) return;
44
+ if (regex[1].length > maxPatternLength || /[^imsu]/.test(regex[2])) throw presetsErrorDiagnostics.PRESETS_LABELLER_REGEX_FLAGS_INVALID();
45
+ const source = regex[1];
46
+ for (let index = 0; index < source.length; index++) {
47
+ const character = source[index];
48
+ if (character === "\\") {
49
+ const escaped = source[++index];
50
+ if (!escaped || !"\\^$.*+?()[]{}|/".includes(escaped)) throw presetsErrorDiagnostics.PRESETS_LABELLER_REGEX_ESCAPE_INVALID();
51
+ } else if ("()[]{}*+?".includes(character)) throw presetsErrorDiagnostics.PRESETS_LABELLER_REGEX_SYNTAX_UNSUPPORTED();
52
+ }
53
+ try {
54
+ return new RegExp(source, regex[2]);
55
+ } catch {
56
+ throw presetsErrorDiagnostics.PRESETS_LABELLER_REGEX_INVALID();
57
+ }
58
+ }
59
+ function matchesText(value, pattern) {
60
+ const patterns = patternList(pattern);
61
+ if (!patterns) return true;
62
+ return (Array.isArray(value) ? value : [value]).some((item) => patterns.some((candidate) => {
63
+ try {
64
+ const regex = compilePattern(candidate);
65
+ return regex ? regex.test(item) : item.toLowerCase().includes(candidate.toLowerCase());
66
+ } catch {
67
+ return false;
68
+ }
69
+ }));
70
+ }
71
+ function matches(message, rule) {
72
+ return matchesText(message.from, rule.from) && matchesText(message.to, rule.to) && matchesText(message.subject, rule.subject) && matchesText(message.body || message.snippet, rule.body) && matchesText(message.headers["list-id"] || "", rule.listId) && matchesText(message.labelIds, rule.hasLabel) && Object.entries(rule.header || {}).every(([name, value]) => matchesText(message.headers[name.toLowerCase()] || "", value)) && (!rule.not || !matches(message, rule.not));
73
+ }
74
+ function explicitAction(rule) {
75
+ if (!rule) return {};
76
+ const action = {};
77
+ for (const key of [
78
+ "archive",
79
+ "read",
80
+ "star",
81
+ "trash"
82
+ ]) if (rule[key] !== void 0) action[key] = rule[key];
83
+ return action;
84
+ }
85
+ function selectedLabel(result) {
86
+ const label = result?.label;
87
+ if (hasRuntimeType(label, "string")) return label;
88
+ const choice = label?.choice;
89
+ return hasRuntimeType(choice, "string") ? choice : void 0;
90
+ }
91
+ function selectedConfidence(result) {
92
+ if (hasRuntimeType(result.label, "string")) return 1;
93
+ const confidence = result.label.confidence;
94
+ return hasRuntimeType(confidence, "number") && Number.isFinite(confidence) && confidence >= 0 && confidence <= 1 ? confidence : void 0;
95
+ }
96
+ function validateAction(name, action) {
97
+ for (const key of [
98
+ "archive",
99
+ "read",
100
+ "star",
101
+ "trash"
102
+ ]) if (action[key] !== void 0 && !hasRuntimeType(action[key], "boolean")) throw presetsErrorDiagnostics.PRESETS_LABELLER_ACTION_FLAG_INVALID({
103
+ name,
104
+ key
105
+ });
106
+ }
107
+ function validateRule(name, rule, labels, depth = 0) {
108
+ if (depth > 8) throw presetsErrorDiagnostics.PRESETS_LABELLER_RULE_NESTING_TOO_DEEP();
109
+ if (!isRuntimeObject(rule)) throw presetsErrorDiagnostics.PRESETS_LABELLER_RULE_INVALID({ name });
110
+ validateAction(`rule "${name}"`, rule);
111
+ for (const field of [
112
+ rule.from,
113
+ rule.to,
114
+ rule.subject,
115
+ rule.body,
116
+ rule.listId,
117
+ rule.hasLabel
118
+ ]) for (const pattern of patternList(field) || []) compilePattern(pattern);
119
+ for (const [header, value] of Object.entries(rule.header || {})) {
120
+ if (!header.trim() || header.length > maxHeaderValueLength) throw presetsErrorDiagnostics.PRESETS_LABELLER_RULE_HEADER_INVALID({ name });
121
+ for (const pattern of patternList(value) || []) compilePattern(pattern);
122
+ }
123
+ if (rule.label !== void 0 && (!Object.hasOwn(labels, rule.label) || !rule.label.trim())) throw presetsErrorDiagnostics.PRESETS_LABELLER_RULE_LABEL_UNDECLARED({ name });
124
+ if (rule.label === void 0 && (rule.archive === true || rule.read === true || rule.star === true || rule.trash === true)) throw presetsErrorDiagnostics.PRESETS_LABELLER_RULE_LABEL_MISSING({ name });
125
+ if (rule.not) validateRule(`${name}.not`, rule.not, labels, depth + 1);
126
+ }
127
+ function validateOptions(options) {
128
+ for (const key of [
129
+ "dryRun",
130
+ "hideUnmanagedLabels",
131
+ "relabel",
132
+ "trashEnabled"
133
+ ]) if (!hasRuntimeType(options[key], "boolean")) throw presetsErrorDiagnostics.PRESETS_LABELLER_OPTION_NOT_BOOLEAN({ key });
134
+ validateLabels(options.labels);
135
+ const labelCount = Object.keys(options.labels).length;
136
+ if (labelCount < 1 || labelCount > 254) throw presetsErrorDiagnostics.PRESETS_LABELLER_LABEL_COUNT_INVALID();
137
+ if (!Number.isSafeInteger(options.bodyLimit) || options.bodyLimit < 1 || options.bodyLimit > maxBodyLimit) throw presetsErrorDiagnostics.PRESETS_LABELLER_BODY_LIMIT_INVALID({ max: maxBodyLimit });
138
+ if (!Number.isFinite(options.minConfidence) || options.minConfidence < 0 || options.minConfidence > 1) throw presetsErrorDiagnostics.PRESETS_LABELLER_MIN_CONFIDENCE_INVALID();
139
+ if (!isRuntimeObject(options.rules) || Array.isArray(options.rules)) throw presetsErrorDiagnostics.PRESETS_LABELLER_RULES_INVALID();
140
+ for (const [name, rule] of Object.entries(options.rules || {})) validateRule(name, rule, options.labels);
141
+ if (!isRuntimeObject(options.actions) || Array.isArray(options.actions)) throw presetsErrorDiagnostics.PRESETS_LABELLER_ACTIONS_INVALID();
142
+ for (const [label, action] of Object.entries(options.actions || {})) {
143
+ if (!Object.hasOwn(options.labels, label)) throw presetsErrorDiagnostics.PRESETS_LABELLER_ACTION_LABEL_UNDECLARED({ label });
144
+ if (!isRuntimeObject(action) || Array.isArray(action)) throw presetsErrorDiagnostics.PRESETS_LABELLER_ACTION_INVALID({ label });
145
+ validateAction(`action "${label}"`, action);
146
+ }
147
+ if (!isRuntimeObject(options.cleanup) || Array.isArray(options.cleanup)) throw presetsErrorDiagnostics.PRESETS_LABELLER_CLEANUP_INVALID();
148
+ for (const [name, rule] of Object.entries(options.cleanup)) {
149
+ if (!isRuntimeObject(rule) || !hasRuntimeType(rule.label, "string") || !Object.hasOwn(options.labels, rule.label)) throw presetsErrorDiagnostics.PRESETS_LABELLER_CLEANUP_LABEL_UNDECLARED({ name });
150
+ if (/["\\\p{Cc}]/u.test(rule.label)) throw presetsErrorDiagnostics.PRESETS_LABELLER_CLEANUP_LABEL_NAME_INVALID({ name });
151
+ if (!Number.isSafeInteger(rule.olderThan) || rule.olderThan < 1) throw presetsErrorDiagnostics.PRESETS_LABELLER_CLEANUP_OLDER_THAN_INVALID({ name });
152
+ }
153
+ }
154
+ function decision(message, rules) {
155
+ for (const [name, rule] of Object.entries(rules || {})) if (matches(message, rule)) return {
156
+ label: rule.label || "none",
157
+ rule: name
158
+ };
159
+ }
160
+ let materializingTemplate = true;
161
+ /** Gmail labelling preset: ordered rules first, then a constrained Jev choice. */
162
+ const labeller = defineAgent({
163
+ options: {
164
+ labels: {},
165
+ rules: {},
166
+ actions: {},
167
+ cleanup: {},
168
+ bodyLimit: 1e4,
169
+ dryRun: true,
170
+ hideUnmanagedLabels: false,
171
+ maxAttempts: void 0,
172
+ minConfidence: .6,
173
+ relabel: false,
174
+ trashEnabled: false,
175
+ client: void 0
176
+ },
177
+ configure: (options) => {
178
+ if (materializingTemplate) {
179
+ materializingTemplate = false;
180
+ return defineAgent({
181
+ driver: { run: () => {
182
+ throw presetsErrorDiagnostics.PRESETS_LABELLER_LABEL_COUNT_INVALID();
183
+ } },
184
+ intercept: () => void 0
185
+ });
186
+ }
187
+ validateOptions(options);
188
+ const { labels, rules, actions, bodyLimit, hideUnmanagedLabels, maxAttempts, minConfidence, relabel, trashEnabled, client } = options;
189
+ const channelOptions = {
190
+ labels,
191
+ bodyLimit,
192
+ client,
193
+ hideUnmanagedLabels,
194
+ ...maxAttempts === void 0 ? {} : { maxAttempts }
195
+ };
196
+ if (options.dryRun) channelOptions.dryRun = true;
197
+ const channel = gmail(channelOptions);
198
+ return defineAgent({
199
+ description: "Label Gmail messages with ordered rules, then a constrained Jev choice.",
200
+ channels: { gmail: channel },
201
+ intercept: ({ context }) => {
202
+ const message = context.get(channelMessageContextKey);
203
+ const selected = message ? decision(message, rules) : void 0;
204
+ return selected ? selected : void 0;
205
+ },
206
+ driver: { ask: { label: ask.choice("Choose the Gmail label that best fits this email. Choose none when no declared label clearly fits.", {
207
+ ...Object.fromEntries(Object.entries(labels).flatMap(([name, value]) => value.description ? [[name, value.description]] : [])),
208
+ none: "No declared label clearly fits this email."
209
+ }) } },
210
+ hooks: { async "agent:finish"({ message, result }) {
211
+ if (message?.channel !== "gmail" || !result) return;
212
+ const output = result;
213
+ const candidate = selectedLabel(output);
214
+ const declared = candidate && candidate !== "none" && Object.hasOwn(labels, candidate) ? candidate : void 0;
215
+ const confidence = declared ? selectedConfidence(output) : void 0;
216
+ const label = confidence !== void 0 && confidence >= minConfidence ? declared : void 0;
217
+ if (relabel) {
218
+ const removeLabels = Object.keys(labels).filter((name) => name !== label);
219
+ await message.modify({
220
+ addLabels: label ? [label] : [],
221
+ removeLabels
222
+ });
223
+ }
224
+ if (!label) return;
225
+ const rule = output.rule ? rules[output.rule] : void 0;
226
+ const selectedAction = { ...actions[label] };
227
+ if (rule?.label === label) Object.assign(selectedAction, explicitAction(rule));
228
+ if (!relabel) await message.label(label);
229
+ if (selectedAction.archive) await message.archive();
230
+ if (selectedAction.read) await message.markRead();
231
+ if (selectedAction.star) await message.star();
232
+ if (selectedAction.trash && trashEnabled) await message.trash();
233
+ } }
234
+ });
235
+ }
236
+ });
237
+ /** Gmail's largest search page. A later run finds the rest. */
238
+ const cleanupLimit = 500;
239
+ const trashConcurrency = 5;
240
+ const messageList = v.object({ messages: v.optional(v.array(v.object({ id: v.string() }))) });
241
+ /**
242
+ * Runs the Labeller's `cleanup` rules on its Gmail Channel, at most 500 messages per rule.
243
+ * Call it from a daily Schedule: each run continues with the matches that remain.
244
+ */
245
+ async function cleanupLabeller(agent, options = {}) {
246
+ const channel = agent.channels?.gmail;
247
+ if (!channel) throw presetsErrorDiagnostics.PRESETS_LABELLER_CLEANUP_AGENT_INVALID();
248
+ const apply = options.apply === true && agent.options.dryRun === false && agent.options.trashEnabled === true;
249
+ const rules = Object.entries(agent.options.cleanup);
250
+ if (!rules.length) return {
251
+ applied: apply,
252
+ rules: []
253
+ };
254
+ const client = await gmailClient(channel, options.runtime ? { runtime: options.runtime } : {});
255
+ const results = [];
256
+ for (const [rule, { label, olderThan }] of rules) {
257
+ const query = `label:"${label}" older_than:${olderThan}d -is:starred -in:trash`;
258
+ const messageIds = (v.parse(messageList, await client({
259
+ method: "GET",
260
+ path: "messages",
261
+ query: {
262
+ includeSpamTrash: true,
263
+ maxResults: cleanupLimit,
264
+ q: query
265
+ }
266
+ })).messages ?? []).map((message) => message.id);
267
+ for (let start = 0; apply && start < messageIds.length; start += trashConcurrency) await Promise.all(messageIds.slice(start, start + trashConcurrency).map(async (id) => {
268
+ try {
269
+ await client({
270
+ method: "POST",
271
+ path: `messages/${encodeURIComponent(id)}/trash`
272
+ });
273
+ } catch (error) {
274
+ if (!isRuntimeRecord(error) || error.status !== 404) throw error;
275
+ }
276
+ }));
277
+ results.push({
278
+ messageIds,
279
+ query,
280
+ rule
281
+ });
282
+ }
283
+ return {
284
+ applied: apply,
285
+ rules: results
286
+ };
287
+ }
288
+ //#endregion
289
+ export { cleanupLabeller, labeller };