@pellux/goodvibes-daemon 1.28.0
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.
- package/CHANGELOG.md +383 -0
- package/LICENSE +21 -0
- package/README.md +125 -0
- package/bin/goodvibes-daemon +100 -0
- package/bin/launcher-support.js +226 -0
- package/package.json +96 -0
- package/scripts/check-bun.sh +20 -0
- package/scripts/postinstall.js +244 -0
- package/src/cli/command-catalog.ts +828 -0
- package/src/cli/completion.ts +299 -0
- package/src/cli/help.ts +167 -0
- package/src/cli/index.ts +21 -0
- package/src/cli/parser.ts +55 -0
- package/src/cli/surface-catalog.ts +26 -0
- package/src/cli/types.ts +63 -0
- package/src/cluster/daemon-ws-call.ts +235 -0
- package/src/cluster/raw-reply-route.ts +111 -0
- package/src/config/checkpoint-settings.ts +113 -0
- package/src/config/run-daemon-config-migration.ts +47 -0
- package/src/config/secret-config.ts +175 -0
- package/src/config/secrets.ts +71 -0
- package/src/config/surface.ts +24 -0
- package/src/core/pairing-banner.ts +82 -0
- package/src/daemon/cli.ts +878 -0
- package/src/daemon/config-command.ts +281 -0
- package/src/daemon/handlers/context.ts +29 -0
- package/src/daemon/handlers/contracts.ts +43 -0
- package/src/daemon/handlers/credentials.ts +139 -0
- package/src/daemon/handlers/drafts/draft-store.ts +427 -0
- package/src/daemon/handlers/drafts/index.ts +17 -0
- package/src/daemon/handlers/drafts/register.ts +331 -0
- package/src/daemon/handlers/errors.ts +18 -0
- package/src/daemon/handlers/inbox/aggregator.ts +375 -0
- package/src/daemon/handlers/inbox/cursor-store.ts +512 -0
- package/src/daemon/handlers/inbox/index.ts +221 -0
- package/src/daemon/handlers/inbox/mapping.ts +192 -0
- package/src/daemon/handlers/inbox/poller.ts +239 -0
- package/src/daemon/handlers/inbox/provider-adapter.ts +171 -0
- package/src/daemon/handlers/inbox/providers/discord.ts +276 -0
- package/src/daemon/handlers/inbox/providers/email.ts +176 -0
- package/src/daemon/handlers/inbox/providers/imap-client.ts +300 -0
- package/src/daemon/handlers/inbox/providers/route-util.ts +24 -0
- package/src/daemon/handlers/inbox/providers/slack.ts +287 -0
- package/src/daemon/handlers/index.ts +117 -0
- package/src/daemon/handlers/register.ts +180 -0
- package/src/daemon/handlers/remote/backends/cloud-terminal.ts +143 -0
- package/src/daemon/handlers/remote/backends/docker.ts +79 -0
- package/src/daemon/handlers/remote/backends/index.ts +40 -0
- package/src/daemon/handlers/remote/backends/local-process.ts +113 -0
- package/src/daemon/handlers/remote/backends/process-runner.ts +127 -0
- package/src/daemon/handlers/remote/backends/ssh.ts +126 -0
- package/src/daemon/handlers/remote/backends/types.ts +97 -0
- package/src/daemon/handlers/remote/dispatcher.ts +181 -0
- package/src/daemon/handlers/remote/index.ts +120 -0
- package/src/daemon/handlers/remote/peer-registry.ts +357 -0
- package/src/daemon/handlers/remote/service.ts +191 -0
- package/src/daemon/handlers/routing/inbox-bridge.ts +71 -0
- package/src/daemon/handlers/routing/index.ts +261 -0
- package/src/daemon/handlers/routing/route-store.ts +319 -0
- package/src/daemon/handlers/routing/routing-resolver.ts +75 -0
- package/src/daemon/handlers/sqlite-store.ts +303 -0
- package/src/daemon/handlers/triage/index.ts +57 -0
- package/src/daemon/handlers/triage/integration.ts +213 -0
- package/src/daemon/handlers/triage/pipeline.ts +274 -0
- package/src/daemon/handlers/triage/scorer.ts +287 -0
- package/src/daemon/handlers/triage/tagger/discord.ts +187 -0
- package/src/daemon/handlers/triage/tagger/imap.ts +384 -0
- package/src/daemon/handlers/triage/tagger/index.ts +184 -0
- package/src/daemon/handlers/triage/tagger/shared.ts +70 -0
- package/src/daemon/handlers/triage/tagger/slack.ts +69 -0
- package/src/daemon/handlers/triage/types.ts +50 -0
- package/src/daemon/lifecycle.ts +41 -0
- package/src/daemon/local-daemon-state.ts +233 -0
- package/src/daemon/pair-command.ts +301 -0
- package/src/daemon/provision-wake-model.ts +81 -0
- package/src/daemon/send/channels.ts +200 -0
- package/src/daemon/send/command.ts +333 -0
- package/src/daemon/send/composition.ts +100 -0
- package/src/daemon/send/failure-text.ts +93 -0
- package/src/daemon/send/inert-text.ts +225 -0
- package/src/daemon/send/stdin.ts +24 -0
- package/src/daemon/service-commands.ts +530 -0
- package/src/daemon/sessions-command.ts +209 -0
- package/src/daemon/status-command.ts +481 -0
- package/src/daemon/webui-command.ts +339 -0
- package/src/runtime/boot-tasks.ts +110 -0
- package/src/runtime/cluster-composition.ts +124 -0
- package/src/runtime/cluster-group-composition.ts +284 -0
- package/src/runtime/conversation-rewind-port.ts +171 -0
- package/src/runtime/credential-composition.ts +54 -0
- package/src/runtime/daemon-handler-composition.ts +76 -0
- package/src/runtime/device-posture-composition.ts +115 -0
- package/src/runtime/disposal-wiring.ts +101 -0
- package/src/runtime/fleet-needs-input-push.ts +61 -0
- package/src/runtime/fleet-services.ts +41 -0
- package/src/runtime/hosted-session-composition.ts +128 -0
- package/src/runtime/index.ts +100 -0
- package/src/runtime/knowledge-services.ts +101 -0
- package/src/runtime/legacy-daemon-migration.ts +605 -0
- package/src/runtime/legacy-daemon-reconcile.ts +448 -0
- package/src/runtime/mail-composition.ts +65 -0
- package/src/runtime/notification-dispatch.ts +86 -0
- package/src/runtime/plugin-composition.ts +111 -0
- package/src/runtime/runtime-services-types.ts +268 -0
- package/src/runtime/services.ts +756 -0
- package/src/runtime/trigger-services.ts +62 -0
- package/src/runtime/trust/checkpoint-eligibility.ts +138 -0
- package/src/runtime/trust/trust-gated-approvals.ts +169 -0
- package/src/runtime/update-check.ts +61 -0
- package/src/runtime/workspace-checkpointing.ts +116 -0
- package/src/testing/daemon-fixture.ts +276 -0
- package/src/testing/hosted-session-failures.ts +92 -0
- package/src/version.ts +26 -0
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
/// <reference types="@pellux/goodvibes-sdk/sql-js" />
|
|
2
|
+
// `sql.js` ships no types. The declaration is SDK-owned and reaches here
|
|
3
|
+
// through that reference — there is no local copy to keep in step.
|
|
4
|
+
|
|
5
|
+
import { mkdir, rename, writeFile } from 'node:fs/promises';
|
|
6
|
+
import { readFileSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs';
|
|
7
|
+
import { existsSync } from 'node:fs';
|
|
8
|
+
import { basename, dirname, join } from 'node:path';
|
|
9
|
+
import { logger } from '@pellux/goodvibes-sdk/platform/utils';
|
|
10
|
+
import initSqlJs from 'sql.js';
|
|
11
|
+
import { GOODVIBES_DAEMON_SURFACE_ROOT } from '../../config/surface.ts';
|
|
12
|
+
|
|
13
|
+
type SqlJsStatic = Awaited<ReturnType<typeof initSqlJs>>;
|
|
14
|
+
type SqlDatabase = InstanceType<SqlJsStatic['Database']>;
|
|
15
|
+
|
|
16
|
+
export interface SqliteStoreOptions {
|
|
17
|
+
workingDirectory: string;
|
|
18
|
+
/** e.g. 'channel-routes.sqlite', 'drafts.sqlite', 'inbox-cursors.sqlite' */
|
|
19
|
+
fileName: string;
|
|
20
|
+
/** CREATE TABLE / INDEX statements run once on init (idempotent: IF NOT EXISTS). */
|
|
21
|
+
schema: string[];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The 16 bytes every SQLite file begins with ("SQLite format 3" + NUL). A file
|
|
26
|
+
* that does not start with these is not a database, whatever its extension —
|
|
27
|
+
* which is exactly what a crash mid-create, a zero-fill, or a partially
|
|
28
|
+
* restored backup leaves behind.
|
|
29
|
+
*/
|
|
30
|
+
const SQLITE_HEADER = Buffer.from('SQLite format 3\0', 'latin1');
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* How long a quarantined `.corrupt-<timestamp>` database is kept before it is
|
|
34
|
+
* reclaimed. These files exist so an operator can try to salvage a damaged
|
|
35
|
+
* store by hand; 14 days is long enough for someone to notice a broken daemon
|
|
36
|
+
* and come looking, and short enough that a store that goes bad repeatedly
|
|
37
|
+
* cannot fill the disk with copies of itself. Reaped on the next init.
|
|
38
|
+
*/
|
|
39
|
+
const CORRUPT_QUARANTINE_TTL_MS = 14 * 24 * 60 * 60 * 1000;
|
|
40
|
+
|
|
41
|
+
/** At most this many quarantined copies of one store are kept, newest first. */
|
|
42
|
+
const MAX_CORRUPT_QUARANTINES = 3;
|
|
43
|
+
|
|
44
|
+
let sqlJsStaticPromise: Promise<SqlJsStatic> | null = null;
|
|
45
|
+
|
|
46
|
+
async function loadSqlJs(): Promise<SqlJsStatic> {
|
|
47
|
+
if (!sqlJsStaticPromise) {
|
|
48
|
+
sqlJsStaticPromise = initSqlJs();
|
|
49
|
+
}
|
|
50
|
+
return sqlJsStaticPromise;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Daemon sqlite helper following the project MemoryStore lifecycle
|
|
55
|
+
* (sql.js WASM: init → run/exec → save → close). One file per concern under
|
|
56
|
+
* {workingDirectory}/.goodvibes/tui/operator/{fileName}.
|
|
57
|
+
*/
|
|
58
|
+
export class HandlerSqliteStore {
|
|
59
|
+
/**
|
|
60
|
+
* Makes every temp filename this process writes distinct. Static rather than
|
|
61
|
+
* per-instance because two INSTANCES pointed at one file (two surfaces
|
|
62
|
+
* sharing a store path) would otherwise collide with each other exactly as
|
|
63
|
+
* two saves of one instance did. See save().
|
|
64
|
+
*/
|
|
65
|
+
private static saveSequence = 0;
|
|
66
|
+
|
|
67
|
+
private readonly options: SqliteStoreOptions;
|
|
68
|
+
private readonly resolvedPath: string;
|
|
69
|
+
private db: SqlDatabase | null = null;
|
|
70
|
+
|
|
71
|
+
constructor(options: SqliteStoreOptions) {
|
|
72
|
+
this.options = options;
|
|
73
|
+
this.resolvedPath = join(
|
|
74
|
+
options.workingDirectory,
|
|
75
|
+
'.goodvibes',
|
|
76
|
+
GOODVIBES_DAEMON_SURFACE_ROOT,
|
|
77
|
+
'operator',
|
|
78
|
+
options.fileName,
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
get dbPath(): string {
|
|
83
|
+
return this.resolvedPath;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
private requireDb(): SqlDatabase {
|
|
87
|
+
if (!this.db) {
|
|
88
|
+
throw new Error(`HandlerSqliteStore not initialized: ${this.resolvedPath}`);
|
|
89
|
+
}
|
|
90
|
+
return this.db;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Move a database file that cannot be opened aside instead of deleting it, so
|
|
95
|
+
* an operator still has something to salvage, and return the quarantine path.
|
|
96
|
+
* Returns null when the move itself failed — in which case the caller starts
|
|
97
|
+
* fresh in memory and the bad file is left exactly where it was rather than
|
|
98
|
+
* being overwritten on the next save.
|
|
99
|
+
*/
|
|
100
|
+
private quarantineUnreadable(): string | null {
|
|
101
|
+
const target = `${this.resolvedPath}.corrupt-${Date.now()}`;
|
|
102
|
+
try {
|
|
103
|
+
renameSync(this.resolvedPath, target);
|
|
104
|
+
return target;
|
|
105
|
+
} catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Bound the quarantine directory: drop `.corrupt-*` copies of THIS store that
|
|
112
|
+
* are past the TTL or beyond the keep-newest count. Best-effort and
|
|
113
|
+
* idempotent — a file another process already removed is success, not an
|
|
114
|
+
* error — so two daemons opening the same store at once cannot fight.
|
|
115
|
+
* Returns how many were reclaimed.
|
|
116
|
+
*/
|
|
117
|
+
private reapCorruptQuarantines(nowMs: number): number {
|
|
118
|
+
const dir = dirname(this.resolvedPath);
|
|
119
|
+
const prefix = `${basename(this.resolvedPath)}.corrupt-`;
|
|
120
|
+
let candidates: Array<{ path: string; mtimeMs: number }>;
|
|
121
|
+
try {
|
|
122
|
+
candidates = readdirSync(dir)
|
|
123
|
+
.filter((name) => name.startsWith(prefix))
|
|
124
|
+
.map((name) => join(dir, name))
|
|
125
|
+
.flatMap((path) => {
|
|
126
|
+
try {
|
|
127
|
+
return [{ path, mtimeMs: statSync(path).mtimeMs }];
|
|
128
|
+
} catch {
|
|
129
|
+
return [];
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
} catch {
|
|
133
|
+
return 0;
|
|
134
|
+
}
|
|
135
|
+
if (candidates.length === 0) return 0;
|
|
136
|
+
// Newest first: the newest MAX_CORRUPT_QUARANTINES survive the count cap,
|
|
137
|
+
// and everything past the TTL goes regardless of rank.
|
|
138
|
+
candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
|
|
139
|
+
let reclaimed = 0;
|
|
140
|
+
for (const [index, candidate] of candidates.entries()) {
|
|
141
|
+
const tooOld = nowMs - candidate.mtimeMs > CORRUPT_QUARANTINE_TTL_MS;
|
|
142
|
+
const overCap = index >= MAX_CORRUPT_QUARANTINES;
|
|
143
|
+
if (!tooOld && !overCap) continue;
|
|
144
|
+
try {
|
|
145
|
+
rmSync(candidate.path, { force: true });
|
|
146
|
+
reclaimed += 1;
|
|
147
|
+
} catch {
|
|
148
|
+
// Another process may have taken it first; that is the outcome we wanted.
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return reclaimed;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async init(): Promise<void> {
|
|
155
|
+
if (this.db) return;
|
|
156
|
+
await mkdir(dirname(this.resolvedPath), { recursive: true });
|
|
157
|
+
const SQL = await loadSqlJs();
|
|
158
|
+
|
|
159
|
+
// Validate the file by its CONTENT, not by existsSync. `save()` writes
|
|
160
|
+
// through a pid-and-timestamp temp file and an atomic rename, so it cannot
|
|
161
|
+
// itself leave a half-written database — but a zero-filled file recovered
|
|
162
|
+
// by a filesystem, a truncated restore, or a copy interrupted by something
|
|
163
|
+
// outside this process all produce a path that exists and holds no usable
|
|
164
|
+
// database. Handing those bytes to `new SQL.Database(...)` throws out of
|
|
165
|
+
// init and takes the whole daemon store down with no way back.
|
|
166
|
+
let existing: Buffer | undefined;
|
|
167
|
+
let quarantined: string | null = null;
|
|
168
|
+
let quarantineReason = '';
|
|
169
|
+
if (existsSync(this.resolvedPath)) {
|
|
170
|
+
let raw: Buffer | null = null;
|
|
171
|
+
try {
|
|
172
|
+
raw = readFileSync(this.resolvedPath);
|
|
173
|
+
} catch {
|
|
174
|
+
raw = null;
|
|
175
|
+
}
|
|
176
|
+
if (!raw || raw.length === 0) {
|
|
177
|
+
quarantineReason = raw ? 'zero-byte file (interrupted write)' : 'unreadable file';
|
|
178
|
+
quarantined = this.quarantineUnreadable();
|
|
179
|
+
} else if (raw.length < SQLITE_HEADER.length || !raw.subarray(0, SQLITE_HEADER.length).equals(SQLITE_HEADER)) {
|
|
180
|
+
quarantineReason = 'missing the SQLite file header (not a database)';
|
|
181
|
+
quarantined = this.quarantineUnreadable();
|
|
182
|
+
} else {
|
|
183
|
+
existing = raw;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (existing) {
|
|
188
|
+
// The constructor is NOT where a damaged image surfaces: sql.js accepts
|
|
189
|
+
// the bytes and only reports "database disk image is malformed" when the
|
|
190
|
+
// first statement touches a bad page. So the open is not proved until the
|
|
191
|
+
// schema has actually run against it, and both steps share one catch.
|
|
192
|
+
try {
|
|
193
|
+
const candidate = new SQL.Database(existing);
|
|
194
|
+
try {
|
|
195
|
+
for (const statement of this.options.schema) candidate.run(statement);
|
|
196
|
+
this.db = candidate;
|
|
197
|
+
} catch (error) {
|
|
198
|
+
candidate.close();
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
} catch (error) {
|
|
202
|
+
// Header present but the body does not hold up: a truncated or damaged
|
|
203
|
+
// database. Same treatment — set aside, disclose, start clean.
|
|
204
|
+
quarantineReason = `database would not open: ${error instanceof Error ? error.message : String(error)}`;
|
|
205
|
+
this.db = null;
|
|
206
|
+
quarantined = this.quarantineUnreadable();
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
if (!this.db) {
|
|
211
|
+
this.db = new SQL.Database();
|
|
212
|
+
for (const statement of this.options.schema) this.db.run(statement);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Disclosure: starting a store from scratch is data loss from the user's
|
|
216
|
+
// point of view, so it is never allowed to happen quietly.
|
|
217
|
+
if (quarantineReason) {
|
|
218
|
+
logger.warn('daemon store could not be opened — starting a fresh one', {
|
|
219
|
+
store: this.options.fileName,
|
|
220
|
+
path: this.resolvedPath,
|
|
221
|
+
reason: quarantineReason,
|
|
222
|
+
quarantinedTo: quarantined ?? '(could not be moved aside; left in place)',
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const reclaimed = this.reapCorruptQuarantines(Date.now());
|
|
227
|
+
if (reclaimed > 0) {
|
|
228
|
+
logger.info('daemon store reclaimed quarantined copies', {
|
|
229
|
+
store: this.options.fileName,
|
|
230
|
+
reclaimedFiles: reclaimed,
|
|
231
|
+
ttlDays: Math.round(CORRUPT_QUARANTINE_TTL_MS / (24 * 60 * 60 * 1000)),
|
|
232
|
+
keptNewest: MAX_CORRUPT_QUARANTINES,
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Execute a write (INSERT/UPDATE/DELETE/CREATE). */
|
|
238
|
+
run(sql: string, params?: (string | number | Uint8Array | null)[]): void {
|
|
239
|
+
this.requireDb().run(sql, params);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** SELECT → array of row objects (columns mapped to values). */
|
|
243
|
+
all<T = Record<string, unknown>>(sql: string, params?: (string | number)[]): T[] {
|
|
244
|
+
const result = this.requireDb().exec(sql, params);
|
|
245
|
+
if (result.length === 0) return [];
|
|
246
|
+
const { columns, values } = result[0]!;
|
|
247
|
+
return values.map((row) => {
|
|
248
|
+
const obj: Record<string, unknown> = {};
|
|
249
|
+
for (let i = 0; i < columns.length; i += 1) {
|
|
250
|
+
obj[columns[i]!] = row[i];
|
|
251
|
+
}
|
|
252
|
+
return obj as T;
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** First row or null. */
|
|
257
|
+
get<T = Record<string, unknown>>(sql: string, params?: (string | number)[]): T | null {
|
|
258
|
+
const rows = this.all<T>(sql, params);
|
|
259
|
+
return rows.length > 0 ? rows[0]! : null;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* Serialize and atomically persist to dbPath (tmp + rename).
|
|
264
|
+
*
|
|
265
|
+
* The temp filename carries a per-process counter, not just pid + clock. Two
|
|
266
|
+
* saves of the same store in the SAME millisecond produced the same temp path
|
|
267
|
+
* before it did: both wrote it, the first rename moved it away, and the
|
|
268
|
+
* second failed with ENOENT on a file it had just written. That is not a
|
|
269
|
+
* hypothetical race — the inbox poller flushes once per provider and polls
|
|
270
|
+
* every provider concurrently, so it hit on an ordinary two-provider startup,
|
|
271
|
+
* and the failure surfaced as a provider reporting a filesystem error for its
|
|
272
|
+
* feed. Every store on this base shares the hazard, so the counter lives here.
|
|
273
|
+
*/
|
|
274
|
+
async save(): Promise<void> {
|
|
275
|
+
const db = this.requireDb();
|
|
276
|
+
await mkdir(dirname(this.resolvedPath), { recursive: true });
|
|
277
|
+
const data = db.export();
|
|
278
|
+
HandlerSqliteStore.saveSequence += 1;
|
|
279
|
+
const tmpPath = `${this.resolvedPath}.${process.pid}.${Date.now()}.${HandlerSqliteStore.saveSequence}.tmp`;
|
|
280
|
+
await writeFile(tmpPath, data);
|
|
281
|
+
await rename(tmpPath, this.resolvedPath);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
close(): void {
|
|
285
|
+
if (this.db) {
|
|
286
|
+
this.db.close();
|
|
287
|
+
this.db = null;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** BEGIN/COMMIT around fn; ROLLBACK on throw (synchronous sql.js). */
|
|
292
|
+
transaction(fn: () => void): void {
|
|
293
|
+
const db = this.requireDb();
|
|
294
|
+
db.run('BEGIN');
|
|
295
|
+
try {
|
|
296
|
+
fn();
|
|
297
|
+
db.run('COMMIT');
|
|
298
|
+
} catch (error) {
|
|
299
|
+
db.run('ROLLBACK');
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Public surface for the daemon-internal Email Auto-Tag / Spam Triage handler.
|
|
3
|
+
//
|
|
4
|
+
// `registerTriagedInbox` (from ./integration.ts) is the single entry the
|
|
5
|
+
// runtime composition root calls. It DECORATES the inbox surface's
|
|
6
|
+
// `channels.inbox.list` handler (overlaying persisted triage metadata) and
|
|
7
|
+
// returns the poller-facing pipeline + tagger. inbox.triage.* are NOT published
|
|
8
|
+
// catalog methods — this surface registers no triage method id.
|
|
9
|
+
// ---------------------------------------------------------------------------
|
|
10
|
+
|
|
11
|
+
export {
|
|
12
|
+
scoreInboundItem,
|
|
13
|
+
labelToTag,
|
|
14
|
+
type TriageScore,
|
|
15
|
+
type TriageScorerOptions,
|
|
16
|
+
} from './scorer.ts';
|
|
17
|
+
|
|
18
|
+
export type {
|
|
19
|
+
InboundChannelItem,
|
|
20
|
+
TriageLabel,
|
|
21
|
+
ConversationKind,
|
|
22
|
+
} from './types.ts';
|
|
23
|
+
|
|
24
|
+
export {
|
|
25
|
+
runInboxTriage,
|
|
26
|
+
createTriageStore,
|
|
27
|
+
readTriageMetadata,
|
|
28
|
+
readTriageMetadataBatch,
|
|
29
|
+
enrichItemsWithTriage,
|
|
30
|
+
TRIAGE_STORE_FILE,
|
|
31
|
+
type TriageMetadata,
|
|
32
|
+
type TriagedItem,
|
|
33
|
+
type TriageOverlay,
|
|
34
|
+
type TriageEnrichedItem,
|
|
35
|
+
type RunInboxTriageOptions,
|
|
36
|
+
type RunInboxTriageResult,
|
|
37
|
+
} from './pipeline.ts';
|
|
38
|
+
|
|
39
|
+
export {
|
|
40
|
+
createTriageTagger,
|
|
41
|
+
TRIAGE_AUTOTAG_FLAG,
|
|
42
|
+
type TriageTagger,
|
|
43
|
+
type TriageTaggerOptions,
|
|
44
|
+
type TaggerProviderConfig,
|
|
45
|
+
type ApplyTagsRequest,
|
|
46
|
+
type ApplyTagsResult,
|
|
47
|
+
type ImapStoreArgs,
|
|
48
|
+
type ImapRetryOptions,
|
|
49
|
+
} from './tagger/index.ts';
|
|
50
|
+
|
|
51
|
+
export {
|
|
52
|
+
registerTriagedInbox,
|
|
53
|
+
INBOX_LIST_METHOD_ID,
|
|
54
|
+
type RegisterInbox,
|
|
55
|
+
type RegisterTriagedInboxOptions,
|
|
56
|
+
type TriagedInboxRegistration,
|
|
57
|
+
} from './integration.ts';
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Daemon-internal triage INTEGRATION (the single entry the runtime calls).
|
|
3
|
+
//
|
|
4
|
+
// `registerTriagedInbox(ctx, registerInbox, options)` closes the contract loop:
|
|
5
|
+
//
|
|
6
|
+
// 1. It DECORATES the inbox surface's `channels.inbox.list` handler. The
|
|
7
|
+
// inbox surface (a separate handler module) attaches its handler to the
|
|
8
|
+
// SDK-auto-registered descriptor via `ctx.catalog.register(descriptor,
|
|
9
|
+
// handler, { replace: true })`. We pass the inbox `registerInbox` a
|
|
10
|
+
// catalog PROXY whose `register` intercepts exactly the
|
|
11
|
+
// `channels.inbox.list` id and wraps the handler so every returned item is
|
|
12
|
+
// overlaid with the persisted triageScore/triageTags via
|
|
13
|
+
// enrichItemsWithTriage(). Every other registration passes straight
|
|
14
|
+
// through to the real catalog. The inbox descriptor/schema/id is never
|
|
15
|
+
// re-authored — only its handler is wrapped.
|
|
16
|
+
// 2. It exposes the triage pipeline + tagger (`runInboxTriage`, `tagger`) for
|
|
17
|
+
// the daemon-internal poller, which scores items and persists them to the
|
|
18
|
+
// co-located inbox-triage.sqlite store the decorator reads from.
|
|
19
|
+
// 3. inbox.triage.* are intentionally NOT registered on the catalog (they are
|
|
20
|
+
// a daemon-internal pipeline, not published methods) — so this module
|
|
21
|
+
// makes ZERO catalog.register call for any triage id.
|
|
22
|
+
//
|
|
23
|
+
// Reads in the decorator are best-effort and degrade to the raw item when no
|
|
24
|
+
// triage row exists yet, so the read-only inbox feed never breaks.
|
|
25
|
+
// ---------------------------------------------------------------------------
|
|
26
|
+
|
|
27
|
+
import type { HandlerContext } from '../context.ts';
|
|
28
|
+
import type {
|
|
29
|
+
GatewayMethodCatalog,
|
|
30
|
+
GatewayMethodDescriptor,
|
|
31
|
+
GatewayMethodHandler,
|
|
32
|
+
} from '../contracts.ts';
|
|
33
|
+
import type { Unregister } from '../register.ts';
|
|
34
|
+
import { HandlerSqliteStore } from '../sqlite-store.ts';
|
|
35
|
+
import {
|
|
36
|
+
createTriageStore,
|
|
37
|
+
enrichItemsWithTriage,
|
|
38
|
+
runInboxTriage,
|
|
39
|
+
type RunInboxTriageOptions,
|
|
40
|
+
type RunInboxTriageResult,
|
|
41
|
+
} from './pipeline.ts';
|
|
42
|
+
import type { InboundChannelItem } from './types.ts';
|
|
43
|
+
import {
|
|
44
|
+
createTriageTagger,
|
|
45
|
+
type ApplyTagsRequest,
|
|
46
|
+
type ApplyTagsResult,
|
|
47
|
+
type TriageTagger,
|
|
48
|
+
type TriageTaggerOptions,
|
|
49
|
+
} from './tagger/index.ts';
|
|
50
|
+
import { summarizeError } from '@pellux/goodvibes-sdk/platform/utils';
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Canonical id of the inbox list method whose handler we decorate. This is the
|
|
54
|
+
* SDK's published id — referenced as a plain string for matching during
|
|
55
|
+
* registration; no descriptor or schema is authored here.
|
|
56
|
+
*/
|
|
57
|
+
export const INBOX_LIST_METHOD_ID = 'channels.inbox.list';
|
|
58
|
+
|
|
59
|
+
/** Minimal shape of the inbox.list result the decorator overlays triage onto. */
|
|
60
|
+
interface InboxListResult {
|
|
61
|
+
items?: unknown;
|
|
62
|
+
[key: string]: unknown;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface RegisterTriagedInboxOptions {
|
|
66
|
+
pipeline?: RunInboxTriageOptions;
|
|
67
|
+
tagger?: TriageTaggerOptions;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* The inbox surface provider. The runtime supplies the inbox module's register
|
|
72
|
+
* function; we hand it a decorating catalog proxy so its `channels.inbox.list`
|
|
73
|
+
* handler is wrapped with triage enrichment.
|
|
74
|
+
*/
|
|
75
|
+
export type RegisterInbox = (ctx: HandlerContext) => Unregister;
|
|
76
|
+
|
|
77
|
+
/** Handle returned to the runtime: teardown + the poller-facing pipeline/tagger. */
|
|
78
|
+
export interface TriagedInboxRegistration {
|
|
79
|
+
readonly unregister: Unregister;
|
|
80
|
+
/** Score (+persist) a batch of polled items. Used by the inbox poller. */
|
|
81
|
+
runInboxTriage(
|
|
82
|
+
items: readonly InboundChannelItem[],
|
|
83
|
+
options?: RunInboxTriageOptions,
|
|
84
|
+
): Promise<RunInboxTriageResult>;
|
|
85
|
+
/** Provider-side tagger (IMAP flag / Slack or Discord reaction/tag). */
|
|
86
|
+
readonly tagger: TriageTagger;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
type StoredHandler = GatewayMethodHandler;
|
|
90
|
+
|
|
91
|
+
interface EnrichmentProxy {
|
|
92
|
+
readonly ctx: HandlerContext;
|
|
93
|
+
/** Close the shared triage store handle (if one was ever opened). */
|
|
94
|
+
dispose(): void;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Build a HandlerContext whose catalog decorates `channels.inbox.list`
|
|
99
|
+
* registration. The triage store is opened lazily ONCE on the first list
|
|
100
|
+
* invocation and reused for every subsequent call (hot read path); the caller
|
|
101
|
+
* disposes the handle on teardown.
|
|
102
|
+
*/
|
|
103
|
+
function withInboxEnrichment(ctx: HandlerContext): EnrichmentProxy {
|
|
104
|
+
const original = ctx.catalog;
|
|
105
|
+
|
|
106
|
+
let store: HandlerSqliteStore | null = null;
|
|
107
|
+
let initPromise: Promise<HandlerSqliteStore> | null = null;
|
|
108
|
+
const getStore = async (): Promise<HandlerSqliteStore> => {
|
|
109
|
+
if (store) return store;
|
|
110
|
+
if (!initPromise) {
|
|
111
|
+
const pending = createTriageStore(ctx.workingDirectory);
|
|
112
|
+
initPromise = pending
|
|
113
|
+
.init()
|
|
114
|
+
.then(() => {
|
|
115
|
+
store = pending;
|
|
116
|
+
return pending;
|
|
117
|
+
})
|
|
118
|
+
.catch((error) => {
|
|
119
|
+
initPromise = null; // allow a later call to retry opening the store
|
|
120
|
+
throw error;
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
return initPromise;
|
|
124
|
+
};
|
|
125
|
+
const dispose = (): void => {
|
|
126
|
+
if (store) {
|
|
127
|
+
store.close();
|
|
128
|
+
store = null;
|
|
129
|
+
}
|
|
130
|
+
initPromise = null;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const decoratedRegister: GatewayMethodCatalog['register'] = (
|
|
134
|
+
descriptor: GatewayMethodDescriptor,
|
|
135
|
+
handler?: StoredHandler,
|
|
136
|
+
options?: { replace?: boolean },
|
|
137
|
+
): Unregister => {
|
|
138
|
+
if (descriptor.id !== INBOX_LIST_METHOD_ID || !handler) {
|
|
139
|
+
return original.register(descriptor, handler, options);
|
|
140
|
+
}
|
|
141
|
+
const innerHandler = handler;
|
|
142
|
+
const wrapped: StoredHandler = async (invocation) => {
|
|
143
|
+
const result = (await innerHandler(invocation)) as InboxListResult;
|
|
144
|
+
if (!result || !Array.isArray(result.items) || result.items.length === 0) {
|
|
145
|
+
return result;
|
|
146
|
+
}
|
|
147
|
+
const items = result.items as Array<{ id: string }>;
|
|
148
|
+
try {
|
|
149
|
+
const handle = await getStore();
|
|
150
|
+
return { ...result, items: enrichItemsWithTriage(handle, items) };
|
|
151
|
+
} catch (error) {
|
|
152
|
+
// Triage is best-effort: a missing/locked store must never break the
|
|
153
|
+
// read-only inbox feed. Log and return the un-enriched result.
|
|
154
|
+
ctx.logger.warn('triage: inbox enrichment skipped', {
|
|
155
|
+
message: summarizeError(error),
|
|
156
|
+
});
|
|
157
|
+
return result;
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
return original.register(descriptor, wrapped, options);
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
// Clone the context with only `catalog.register` swapped. Every other catalog
|
|
164
|
+
// method (invoke/list/get/...) keeps pointing at the original instance.
|
|
165
|
+
const proxiedCatalog = new Proxy(original, {
|
|
166
|
+
get(target, prop, receiver) {
|
|
167
|
+
if (prop === 'register') return decoratedRegister;
|
|
168
|
+
return Reflect.get(target, prop, receiver);
|
|
169
|
+
},
|
|
170
|
+
}) as GatewayMethodCatalog;
|
|
171
|
+
|
|
172
|
+
return { ctx: { ...ctx, catalog: proxiedCatalog }, dispose };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Compose the triage pipeline with the inbox surface so channels.inbox.list
|
|
177
|
+
* returns pre-scored items. Returns the teardown plus the poller-facing
|
|
178
|
+
* pipeline/tagger handle. The inbox surface's registration is wrapped; inbox
|
|
179
|
+
* teardown runs first, then the shared store handle is disposed.
|
|
180
|
+
*/
|
|
181
|
+
export function registerTriagedInbox(
|
|
182
|
+
ctx: HandlerContext,
|
|
183
|
+
registerInbox: RegisterInbox,
|
|
184
|
+
options: RegisterTriagedInboxOptions = {},
|
|
185
|
+
): TriagedInboxRegistration {
|
|
186
|
+
const tagger = createTriageTagger(ctx, options.tagger);
|
|
187
|
+
const enriched = withInboxEnrichment(ctx);
|
|
188
|
+
|
|
189
|
+
let unregisterInbox: Unregister;
|
|
190
|
+
try {
|
|
191
|
+
unregisterInbox = registerInbox(enriched.ctx);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
enriched.dispose();
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const unregister: Unregister = () => {
|
|
198
|
+
try {
|
|
199
|
+
unregisterInbox();
|
|
200
|
+
} finally {
|
|
201
|
+
enriched.dispose();
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
return {
|
|
206
|
+
unregister,
|
|
207
|
+
runInboxTriage: (items, runOptions) =>
|
|
208
|
+
runInboxTriage(items, ctx, { ...options.pipeline, ...runOptions }),
|
|
209
|
+
tagger,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export type { ApplyTagsRequest, ApplyTagsResult };
|