@vite-hub/presets 0.1.0 → 0.4.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,5 +1,5 @@
1
- import { AgentDefinition, AgentInvocationContextValues, AgentInvokerProfile, AgentRuntimeConfig, ConfiguredAgentDefinition } from "@vite-hub/agent";
2
- import { GmailClient, GmailLabelSettings } from "@vite-hub/agent/channels";
1
+ import { AgentDefinition, AgentInvocationContextValues, AgentInvoker, AgentRuntimeConfig, AgentRuntimeContext, ConfiguredAgentDefinition } from "@vite-hub/agent";
2
+ import { GmailChannel, GmailClient, GmailLabelSettings } from "@vite-hub/agent/channels";
3
3
  //#region src/labeller.d.ts
4
4
  export interface LabellerLabel extends GmailLabelSettings {}
5
5
  export type LabellerPattern = string | readonly string[];
@@ -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,34 @@ 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> & {
68
+ readonly channels: {
69
+ readonly gmail: GmailChannel;
70
+ };
71
+ };
50
72
  export type LabellerAgent = ConfiguredAgentDefinition<LabellerOptions, LabellerDefinition>;
51
73
  /** Gmail labelling preset: ordered rules first, then a constrained Jev choice. */
52
74
  export declare const labeller: LabellerAgent;
75
+ export interface CleanupLabellerOptions {
76
+ /** Move the matches to Trash. Without it, or while the Agent has `dryRun: true` or `trashEnabled: false`, the function only lists them. */
77
+ apply?: boolean;
78
+ /** Runtime Context for Server Env and Cloudflare bindings. Omit it outside a host request. */
79
+ runtime?: AgentRuntimeContext;
80
+ }
81
+ export interface LabellerCleanupRuleResult {
82
+ /** IDs of the matching messages, at most 500 per rule. */
83
+ messageIds: string[];
84
+ /** Gmail search query of the rule. */
85
+ query: string;
86
+ rule: string;
87
+ }
88
+ export interface CleanupLabellerResult {
89
+ applied: boolean;
90
+ rules: LabellerCleanupRuleResult[];
91
+ }
92
+ /**
93
+ * Runs the Labeller's `cleanup` rules on its Gmail Channel, at most 500 messages per rule.
94
+ * Call it from a daily Schedule: each run continues with the matches that remain.
95
+ */
96
+ export declare function cleanupLabeller(agent: LabellerAgent, options?: CleanupLabellerOptions): Promise<CleanupLabellerResult>;
53
97
  //#endregion
package/dist/labeller.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { i as isRuntimeRecord, t as presetsErrorDiagnostics } from "./error-diagnostics-o3pHscWs.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
  },
@@ -158,18 +178,21 @@ const labeller = defineAgent({
158
178
  if (materializingTemplate) {
159
179
  materializingTemplate = false;
160
180
  return defineAgent({
181
+ channels: { gmail: gmail({ dryRun: true }) },
161
182
  driver: { run: () => {
162
- throw new TypeError("[vitehub] Labeller labels must contain between 1 and 254 labels.");
183
+ throw presetsErrorDiagnostics.PRESETS_LABELLER_LABEL_COUNT_INVALID();
163
184
  } },
164
185
  intercept: () => void 0
165
186
  });
166
187
  }
167
188
  validateOptions(options);
168
- const { labels, rules, actions, bodyLimit, minConfidence, trashEnabled, client } = options;
189
+ const { labels, rules, actions, bodyLimit, hideUnmanagedLabels, maxAttempts, minConfidence, relabel, trashEnabled, client } = options;
169
190
  const channelOptions = {
170
191
  labels,
171
192
  bodyLimit,
172
- client
193
+ client,
194
+ hideUnmanagedLabels,
195
+ ...maxAttempts === void 0 ? {} : { maxAttempts }
173
196
  };
174
197
  if (options.dryRun) channelOptions.dryRun = true;
175
198
  const channel = gmail(channelOptions);
@@ -182,20 +205,28 @@ const labeller = defineAgent({
182
205
  return selected ? selected : void 0;
183
206
  },
184
207
  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])),
208
+ ...Object.fromEntries(Object.entries(labels).flatMap(([name, value]) => value.description ? [[name, value.description]] : [])),
186
209
  none: "No declared label clearly fits this email."
187
210
  }) } },
188
211
  hooks: { async "agent:finish"({ message, result }) {
189
212
  if (message?.channel !== "gmail" || !result) return;
190
213
  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;
214
+ const candidate = selectedLabel(output);
215
+ const declared = candidate && candidate !== "none" && Object.hasOwn(labels, candidate) ? candidate : void 0;
216
+ const confidence = declared ? selectedConfidence(output) : void 0;
217
+ const label = confidence !== void 0 && confidence >= minConfidence ? declared : void 0;
218
+ if (relabel) {
219
+ const removeLabels = Object.keys(labels).filter((name) => name !== label);
220
+ await message.modify({
221
+ addLabels: label ? [label] : [],
222
+ removeLabels
223
+ });
224
+ }
225
+ if (!label) return;
195
226
  const rule = output.rule ? rules[output.rule] : void 0;
196
227
  const selectedAction = { ...actions[label] };
197
228
  if (rule?.label === label) Object.assign(selectedAction, explicitAction(rule));
198
- await message.label(label);
229
+ if (!relabel) await message.label(label);
199
230
  if (selectedAction.archive) await message.archive();
200
231
  if (selectedAction.read) await message.markRead();
201
232
  if (selectedAction.star) await message.star();
@@ -204,5 +235,56 @@ const labeller = defineAgent({
204
235
  });
205
236
  }
206
237
  });
238
+ /** Gmail's largest search page. A later run finds the rest. */
239
+ const cleanupLimit = 500;
240
+ const trashConcurrency = 5;
241
+ const messageList = v.object({ messages: v.optional(v.array(v.object({ id: v.string() }))) });
242
+ /**
243
+ * Runs the Labeller's `cleanup` rules on its Gmail Channel, at most 500 messages per rule.
244
+ * Call it from a daily Schedule: each run continues with the matches that remain.
245
+ */
246
+ async function cleanupLabeller(agent, options = {}) {
247
+ const channel = agent.channels?.gmail;
248
+ if (!channel) throw presetsErrorDiagnostics.PRESETS_LABELLER_CLEANUP_AGENT_INVALID();
249
+ const apply = options.apply === true && agent.options.dryRun === false && agent.options.trashEnabled === true;
250
+ const rules = Object.entries(agent.options.cleanup);
251
+ if (!rules.length) return {
252
+ applied: apply,
253
+ rules: []
254
+ };
255
+ const client = await gmailClient(channel, options.runtime ? { runtime: options.runtime } : {});
256
+ const results = [];
257
+ for (const [rule, { label, olderThan }] of rules) {
258
+ const query = `label:"${label}" older_than:${olderThan}d -is:starred -in:trash`;
259
+ const messageIds = (v.parse(messageList, await client({
260
+ method: "GET",
261
+ path: "messages",
262
+ query: {
263
+ includeSpamTrash: true,
264
+ maxResults: cleanupLimit,
265
+ q: query
266
+ }
267
+ })).messages ?? []).map((message) => message.id);
268
+ for (let start = 0; apply && start < messageIds.length; start += trashConcurrency) await Promise.all(messageIds.slice(start, start + trashConcurrency).map(async (id) => {
269
+ try {
270
+ await client({
271
+ method: "POST",
272
+ path: `messages/${encodeURIComponent(id)}/trash`
273
+ });
274
+ } catch (error) {
275
+ if (!isRuntimeRecord(error) || error.status !== 404) throw error;
276
+ }
277
+ }));
278
+ results.push({
279
+ messageIds,
280
+ query,
281
+ rule
282
+ });
283
+ }
284
+ return {
285
+ applied: apply,
286
+ rules: results
287
+ };
288
+ }
207
289
  //#endregion
208
- export { labeller };
290
+ export { cleanupLabeller, labeller };