@vite-hub/presets 0.1.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.
@@ -1,4 +1,4 @@
1
- import { AgentDefinition, AgentInvocationContextValues, AgentInvokerProfile, AgentRuntimeConfig, ConfiguredAgentDefinition } from "@vite-hub/agent";
1
+ import { AgentDefinition, AgentInvocationContextValues, AgentInvoker, AgentRuntimeConfig, AgentRuntimeContext, ConfiguredAgentDefinition } from "@vite-hub/agent";
2
2
  import { GmailClient, GmailLabelSettings } from "@vite-hub/agent/channels";
3
3
  //#region src/labeller.d.ts
4
4
  export interface LabellerLabel extends GmailLabelSettings {}
@@ -24,13 +24,31 @@ export interface LabellerAction {
24
24
  star?: boolean;
25
25
  trash?: boolean;
26
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
+ }
27
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. */
28
36
  labels: Readonly<Record<string, LabellerLabel>>;
29
37
  rules: Readonly<Record<string, LabellerRule>>;
30
38
  actions: Readonly<Record<string, LabellerAction>>;
39
+ cleanup: Readonly<Record<string, LabellerCleanupRule>>;
31
40
  bodyLimit: number;
32
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;
33
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;
34
52
  trashEnabled: boolean;
35
53
  client?: GmailClient;
36
54
  }
@@ -46,8 +64,30 @@ type LabellerResult = {
46
64
  };
47
65
  rule?: string;
48
66
  };
49
- type LabellerDefinition = AgentDefinition<AgentRuntimeConfig, unknown, AgentInvokerProfile, AgentInvocationContextValues, LabellerResult | LabellerDecision>;
67
+ type LabellerDefinition = AgentDefinition<AgentRuntimeConfig, unknown, AgentInvoker, AgentInvocationContextValues, LabellerResult | LabellerDecision>;
50
68
  export type LabellerAgent = ConfiguredAgentDefinition<LabellerOptions, LabellerDefinition>;
51
69
  /** Gmail labelling preset: ordered rules first, then a constrained Jev choice. */
52
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>;
53
93
  //#endregion
package/dist/labeller.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { i as isRuntimeRecord, t as presetsErrorDiagnostics } from "./error-diagnostics-BTBW9sZx.js";
1
2
  import { defineAgent } from "@vite-hub/agent";
2
3
  import { hasRuntimeType, isRuntimeObject } from "@vite-hub/runtime/internal/runtime-type";
3
- import { channelMessageContextKey, gmail } from "@vite-hub/agent/channels";
4
+ import * as v from "valibot";
5
+ import { channelMessageContextKey, gmail, gmailClient } from "@vite-hub/agent/channels";
4
6
  import { ask } from "@vite-hub/gateways";
5
7
  //#region src/labeller.ts
6
8
  const maxBodyLimit = 1e5;
@@ -24,34 +26,34 @@ const reservedLabels = /* @__PURE__ */ new Set([
24
26
  "CATEGORY_FORUMS"
25
27
  ]);
26
28
  function validateLabels(labels) {
27
- if (!isRuntimeObject(labels) || Array.isArray(labels)) throw new TypeError("[vitehub] Labeller labels must be an object.");
29
+ if (!isRuntimeObject(labels) || Array.isArray(labels)) throw presetsErrorDiagnostics.PRESETS_LABELLER_LABELS_INVALID();
28
30
  for (const [name, value] of Object.entries(labels)) {
29
- if (!name.trim() || name.length > 225 || /\p{Cc}/u.test(name) || reservedLabels.has(name.toUpperCase())) throw new TypeError(`[vitehub] Labeller label "${name}" is reserved or invalid.`);
30
- if (!isRuntimeObject(value) || Array.isArray(value)) throw new TypeError(`[vitehub] Labeller label "${name}" must be an object.`);
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 });
31
33
  }
32
34
  }
33
35
  function patternList(value) {
34
36
  if (value === void 0) return;
35
37
  const values = Array.isArray(value) ? value : [value];
36
- if (!values.length || values.some((item) => !hasRuntimeType(item, "string") || item.length === 0 || item.length > maxPatternLength)) throw new TypeError(`[vitehub] Labeller patterns must be non-empty strings of at most ${maxPatternLength} characters.`);
38
+ if (!values.length || values.some((item) => !hasRuntimeType(item, "string") || item.length === 0 || item.length > maxPatternLength)) throw presetsErrorDiagnostics.PRESETS_LABELLER_PATTERN_INVALID({ max: maxPatternLength });
37
39
  return values;
38
40
  }
39
41
  function compilePattern(value) {
40
42
  const regex = /^\/(.*)\/([a-z]*)$/.exec(value);
41
43
  if (!regex) return;
42
- if (regex[1].length > maxPatternLength || /[^imsu]/.test(regex[2])) throw new TypeError("[vitehub] Labeller regex patterns use only bounded syntax and the i, m, s, and u flags.");
44
+ if (regex[1].length > maxPatternLength || /[^imsu]/.test(regex[2])) throw presetsErrorDiagnostics.PRESETS_LABELLER_REGEX_FLAGS_INVALID();
43
45
  const source = regex[1];
44
46
  for (let index = 0; index < source.length; index++) {
45
47
  const character = source[index];
46
48
  if (character === "\\") {
47
49
  const escaped = source[++index];
48
- if (!escaped || !"\\^$.*+?()[]{}|/".includes(escaped)) throw new TypeError("[vitehub] Labeller regex patterns may only escape literal regex characters.");
49
- } else if ("()[]{}*+?".includes(character)) throw new TypeError("[vitehub] Labeller regex patterns may not use repetition or grouping.");
50
+ if (!escaped || !"\\^$.*+?()[]{}|/".includes(escaped)) throw presetsErrorDiagnostics.PRESETS_LABELLER_REGEX_ESCAPE_INVALID();
51
+ } else if ("()[]{}*+?".includes(character)) throw presetsErrorDiagnostics.PRESETS_LABELLER_REGEX_SYNTAX_UNSUPPORTED();
50
52
  }
51
53
  try {
52
54
  return new RegExp(source, regex[2]);
53
55
  } catch {
54
- throw new TypeError("[vitehub] Labeller regex pattern is invalid.");
56
+ throw presetsErrorDiagnostics.PRESETS_LABELLER_REGEX_INVALID();
55
57
  }
56
58
  }
57
59
  function matchesText(value, pattern) {
@@ -97,11 +99,14 @@ function validateAction(name, action) {
97
99
  "read",
98
100
  "star",
99
101
  "trash"
100
- ]) if (action[key] !== void 0 && !hasRuntimeType(action[key], "boolean")) throw new TypeError(`[vitehub] Labeller ${name} ${key} must be a boolean.`);
102
+ ]) if (action[key] !== void 0 && !hasRuntimeType(action[key], "boolean")) throw presetsErrorDiagnostics.PRESETS_LABELLER_ACTION_FLAG_INVALID({
103
+ name,
104
+ key
105
+ });
101
106
  }
102
107
  function validateRule(name, rule, labels, depth = 0) {
103
- if (depth > 8) throw new TypeError("[vitehub] Labeller rules may nest at most eight not clauses.");
104
- if (!isRuntimeObject(rule)) throw new TypeError(`[vitehub] Labeller rule "${name}" must be an object.`);
108
+ if (depth > 8) throw presetsErrorDiagnostics.PRESETS_LABELLER_RULE_NESTING_TOO_DEEP();
109
+ if (!isRuntimeObject(rule)) throw presetsErrorDiagnostics.PRESETS_LABELLER_RULE_INVALID({ name });
105
110
  validateAction(`rule "${name}"`, rule);
106
111
  for (const field of [
107
112
  rule.from,
@@ -112,28 +117,39 @@ function validateRule(name, rule, labels, depth = 0) {
112
117
  rule.hasLabel
113
118
  ]) for (const pattern of patternList(field) || []) compilePattern(pattern);
114
119
  for (const [header, value] of Object.entries(rule.header || {})) {
115
- if (!header.trim() || header.length > maxHeaderValueLength) throw new TypeError(`[vitehub] Labeller rule "${name}" has an invalid header name.`);
120
+ if (!header.trim() || header.length > maxHeaderValueLength) throw presetsErrorDiagnostics.PRESETS_LABELLER_RULE_HEADER_INVALID({ name });
116
121
  for (const pattern of patternList(value) || []) compilePattern(pattern);
117
122
  }
118
- if (rule.label !== void 0 && (!Object.hasOwn(labels, rule.label) || !rule.label.trim())) throw new TypeError(`[vitehub] Labeller rule "${name}" refers to an undeclared label.`);
119
- if (rule.label === void 0 && (rule.archive === true || rule.read === true || rule.star === true || rule.trash === true)) throw new TypeError(`[vitehub] Labeller rule "${name}" must declare a label before enabling actions.`);
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 });
120
125
  if (rule.not) validateRule(`${name}.not`, rule.not, labels, depth + 1);
121
126
  }
122
127
  function validateOptions(options) {
123
- for (const key of ["dryRun", "trashEnabled"]) if (!hasRuntimeType(options[key], "boolean")) throw new TypeError(`[vitehub] Labeller ${key} must be a boolean.`);
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 });
124
134
  validateLabels(options.labels);
125
135
  const labelCount = Object.keys(options.labels).length;
126
- if (labelCount < 1 || labelCount > 254) throw new TypeError("[vitehub] Labeller labels must contain between 1 and 254 labels.");
127
- if (!Number.isSafeInteger(options.bodyLimit) || options.bodyLimit < 1 || options.bodyLimit > maxBodyLimit) throw new TypeError(`[vitehub] Labeller bodyLimit must be an integer from 1 to ${maxBodyLimit}.`);
128
- if (!Number.isFinite(options.minConfidence) || options.minConfidence < 0 || options.minConfidence > 1) throw new TypeError("[vitehub] Labeller minConfidence must be between 0 and 1.");
129
- if (!isRuntimeObject(options.rules) || Array.isArray(options.rules)) throw new TypeError("[vitehub] Labeller rules must be an object.");
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();
130
140
  for (const [name, rule] of Object.entries(options.rules || {})) validateRule(name, rule, options.labels);
131
- if (!isRuntimeObject(options.actions) || Array.isArray(options.actions)) throw new TypeError("[vitehub] Labeller actions must be an object.");
141
+ if (!isRuntimeObject(options.actions) || Array.isArray(options.actions)) throw presetsErrorDiagnostics.PRESETS_LABELLER_ACTIONS_INVALID();
132
142
  for (const [label, action] of Object.entries(options.actions || {})) {
133
- if (!Object.hasOwn(options.labels, label)) throw new TypeError(`[vitehub] Labeller action "${label}" refers to an undeclared label.`);
134
- if (!isRuntimeObject(action) || Array.isArray(action)) throw new TypeError(`[vitehub] Labeller action "${label}" must be an object.`);
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 });
135
145
  validateAction(`action "${label}"`, action);
136
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
+ }
137
153
  }
138
154
  function decision(message, rules) {
139
155
  for (const [name, rule] of Object.entries(rules || {})) if (matches(message, rule)) return {
@@ -148,9 +164,13 @@ const labeller = defineAgent({
148
164
  labels: {},
149
165
  rules: {},
150
166
  actions: {},
167
+ cleanup: {},
151
168
  bodyLimit: 1e4,
152
169
  dryRun: true,
170
+ hideUnmanagedLabels: false,
171
+ maxAttempts: void 0,
153
172
  minConfidence: .6,
173
+ relabel: false,
154
174
  trashEnabled: false,
155
175
  client: void 0
156
176
  },
@@ -159,17 +179,19 @@ const labeller = defineAgent({
159
179
  materializingTemplate = false;
160
180
  return defineAgent({
161
181
  driver: { run: () => {
162
- throw new TypeError("[vitehub] Labeller labels must contain between 1 and 254 labels.");
182
+ throw presetsErrorDiagnostics.PRESETS_LABELLER_LABEL_COUNT_INVALID();
163
183
  } },
164
184
  intercept: () => void 0
165
185
  });
166
186
  }
167
187
  validateOptions(options);
168
- const { labels, rules, actions, bodyLimit, minConfidence, trashEnabled, client } = options;
188
+ const { labels, rules, actions, bodyLimit, hideUnmanagedLabels, maxAttempts, minConfidence, relabel, trashEnabled, client } = options;
169
189
  const channelOptions = {
170
190
  labels,
171
191
  bodyLimit,
172
- client
192
+ client,
193
+ hideUnmanagedLabels,
194
+ ...maxAttempts === void 0 ? {} : { maxAttempts }
173
195
  };
174
196
  if (options.dryRun) channelOptions.dryRun = true;
175
197
  const channel = gmail(channelOptions);
@@ -182,20 +204,28 @@ const labeller = defineAgent({
182
204
  return selected ? selected : void 0;
183
205
  },
184
206
  driver: { ask: { label: ask.choice("Choose the Gmail label that best fits this email. Choose none when no declared label clearly fits.", {
185
- ...Object.fromEntries(Object.entries(labels).map(([name, value]) => [name, value.description || name])),
207
+ ...Object.fromEntries(Object.entries(labels).flatMap(([name, value]) => value.description ? [[name, value.description]] : [])),
186
208
  none: "No declared label clearly fits this email."
187
209
  }) } },
188
210
  hooks: { async "agent:finish"({ message, result }) {
189
211
  if (message?.channel !== "gmail" || !result) return;
190
212
  const output = result;
191
- const label = selectedLabel(output);
192
- if (!label || label === "none" || !Object.hasOwn(labels, label)) return;
193
- const confidence = selectedConfidence(output);
194
- if (confidence === void 0 || confidence < minConfidence) return;
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;
195
225
  const rule = output.rule ? rules[output.rule] : void 0;
196
226
  const selectedAction = { ...actions[label] };
197
227
  if (rule?.label === label) Object.assign(selectedAction, explicitAction(rule));
198
- await message.label(label);
228
+ if (!relabel) await message.label(label);
199
229
  if (selectedAction.archive) await message.archive();
200
230
  if (selectedAction.read) await message.markRead();
201
231
  if (selectedAction.star) await message.star();
@@ -204,5 +234,56 @@ const labeller = defineAgent({
204
234
  });
205
235
  }
206
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
+ }
207
288
  //#endregion
208
- export { labeller };
289
+ export { cleanupLabeller, labeller };