@wirecat/cli-core 0.657.0 → 0.659.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/index.d.ts +1 -1
  4. package/dist/calendar/index.js +1 -1
  5. package/dist/calendar/mcp/index.d.ts +12 -12
  6. package/dist/calendar/reads.d.ts +1 -0
  7. package/dist/calendar/reads.js +1 -1
  8. package/dist/cli/config-command.js +2 -9
  9. package/dist/cli/config-issues.js +1 -1
  10. package/dist/cli/index.d.ts +2 -0
  11. package/dist/cli/index.js +2 -0
  12. package/dist/cli/listings.d.ts +46 -0
  13. package/dist/cli/listings.js +188 -0
  14. package/dist/cli/messenger/messages-delete-command.d.ts +2 -1
  15. package/dist/cli/messenger/messages-delete-command.js +2 -1
  16. package/dist/cli/messenger/serve-relay.d.ts +1 -1
  17. package/dist/{cli → domain}/config-repair.d.ts +7 -0
  18. package/dist/{cli → domain}/config-repair.js +53 -0
  19. package/dist/entities/listings.d.ts +514 -0
  20. package/dist/entities/listings.js +154 -0
  21. package/dist/errors/reasons.js +4 -0
  22. package/dist/kit/sync-after-install.js +5 -0
  23. package/dist/replies/rules.d.ts +1 -1
  24. package/dist/replies/rules.js +1 -1
  25. package/dist/sends/permissions.js +5 -4
  26. package/dist/services/index.d.ts +1 -0
  27. package/dist/services/index.js +1 -0
  28. package/dist/services/listings.d.ts +74 -0
  29. package/dist/services/listings.js +285 -0
  30. package/dist/services/metadata.d.ts +1 -1
  31. package/dist/store/index.d.ts +2 -0
  32. package/dist/store/index.js +2 -0
  33. package/dist/store/shared-config.d.ts +2 -0
  34. package/dist/store/shared-config.js +38 -8
  35. package/dist/store/sqlite/calendar-events.d.ts +10 -0
  36. package/dist/store/sqlite/calendar-events.js +18 -8
  37. package/dist/store/sqlite/document-listing.d.ts +99 -0
  38. package/dist/store/sqlite/document-listing.js +292 -0
  39. package/dist/store/sqlite/files.d.ts +2 -0
  40. package/dist/store/sqlite/files.js +7 -3
  41. package/dist/store/sqlite/meeting-listing.d.ts +108 -0
  42. package/dist/store/sqlite/meeting-listing.js +431 -0
  43. package/dist/store/store.d.ts +4 -0
  44. package/dist/store/store.js +6 -0
  45. package/package.json +1 -1
@@ -0,0 +1,154 @@
1
+ import * as v from "valibot";
2
+ import { DOCUMENT_KINDS } from "../store/sqlite/document-listing.js";
3
+ import { MEETING_ROW_KINDS } from "../store/sqlite/meeting-listing.js";
4
+ import { count, id, reference, text, time, untrusted } from "./fields.js";
5
+ /** The account a document or a meeting came from, as `provider:account` names it and as a person reads it. */
6
+ const source = v.strictObject({
7
+ provider: text,
8
+ account: text,
9
+ /** `provider:account`: what a list's `source:` term takes. */
10
+ source: text,
11
+ label: text,
12
+ });
13
+ const person = v.strictObject({ ref: reference, name: v.nullable(text), kind: text });
14
+ /** One document of any account: a Drive file, a notes folder's file, an added source, an import's document. */
15
+ export const documentEntry = v.strictObject({
16
+ ref: reference,
17
+ id,
18
+ title: v.nullable(text),
19
+ file_name: v.nullable(text),
20
+ kind: v.picklist(DOCUMENT_KINDS),
21
+ mime: v.nullable(text),
22
+ size: v.nullable(count),
23
+ source,
24
+ /** The folder it is in, inside its account; `null` at the top or where the source keeps no folders. */
25
+ folder: v.nullable(text),
26
+ path: v.nullable(text),
27
+ /** Where it opens: its page at the source. */
28
+ url: v.nullable(text),
29
+ /** Where it opens on this computer: a notes folder's file or the copy kept of an added file. */
30
+ local_path: v.nullable(text),
31
+ /** When its source last changed it. */
32
+ source_modified_at: v.nullable(time),
33
+ /** When the store last wrote its copy. */
34
+ stored_at: time,
35
+ has_text: v.boolean(),
36
+ untrusted,
37
+ });
38
+ const linked = v.strictObject({ ref: reference, title: v.nullable(text), at: v.nullable(time), role: v.nullable(text) });
39
+ /** One document with a part of its text, its tags, the people it names and the meetings it belongs to. */
40
+ export const documentEntryDetails = v.strictObject({
41
+ ...documentEntry.entries,
42
+ text: v.nullable(text),
43
+ /** Where `text` starts in the whole text, in characters. */
44
+ text_offset: count,
45
+ /** The whole text's length, in characters. */
46
+ text_length: count,
47
+ /** More text follows `text`: read it with a larger offset. */
48
+ has_more: v.boolean(),
49
+ extraction: v.nullable(text),
50
+ extraction_error: v.nullable(text),
51
+ language: v.nullable(text),
52
+ tags: v.array(text),
53
+ people: v.array(person),
54
+ meetings: v.array(linked),
55
+ events: v.array(linked),
56
+ });
57
+ /** One account holding documents, with its folders and how many documents each holds. */
58
+ export const documentSource = v.strictObject({
59
+ ...source.entries,
60
+ name: v.nullable(text),
61
+ count,
62
+ /** Documents at the top of the account, in no folder. */
63
+ loose: count,
64
+ /** Every folder down to the depth asked, parents before children; `count` takes in the folders under it. */
65
+ folders: v.array(v.strictObject({ path: text, name: text, depth: count, count })),
66
+ });
67
+ /** The person the store links a name or address to, as `meetings participants` gives it. */
68
+ const personLink = v.strictObject({ ref: reference, name: v.nullable(text) });
69
+ const participant = v.strictObject({
70
+ name: v.nullable(text),
71
+ email: v.nullable(text),
72
+ person: v.nullable(personLink),
73
+ organizer: v.boolean(),
74
+ });
75
+ /** One real meeting, call or calendar event: a calendar's event and its Zoom or Meet record are one row. */
76
+ export const meetingEntry = v.strictObject({
77
+ /** `event:<id>` when a calendar or a meeting service's record made an event of it, else `meeting:<account>/<id>`. */
78
+ ref: reference,
79
+ kind: v.picklist(MEETING_ROW_KINDS),
80
+ title: v.nullable(text),
81
+ started_at: v.nullable(time),
82
+ ended_at: v.nullable(time),
83
+ duration_ms: v.nullable(count),
84
+ all_day: v.boolean(),
85
+ /** The zone its calendar or meeting service gave it, which may differ from the computer's. */
86
+ timezone: v.nullable(text),
87
+ status: v.nullable(text),
88
+ /** The link that joins it: a calendar copy's, else its first meeting's. */
89
+ url: v.nullable(text),
90
+ /** Every distinct join link, with the source that gave it, so each opens in its own app. */
91
+ links: v.array(v.strictObject({ source: text, url: text })),
92
+ sources: v.array(v.strictObject({
93
+ ...source.entries,
94
+ via: v.picklist(["calendar", "meeting"]),
95
+ calendar: v.nullable(text),
96
+ ref: reference,
97
+ })),
98
+ /** The meeting records on this row, `meeting:<account>/<id>`. */
99
+ meetings: v.array(reference),
100
+ participants: v.array(participant),
101
+ participants_count: count,
102
+ has_recording: v.boolean(),
103
+ has_transcript: v.boolean(),
104
+ has_summary: v.boolean(),
105
+ documents: v.array(v.strictObject({ ref: reference, title: v.nullable(text), role: v.nullable(text) })),
106
+ /** Findings waiting for the owner (`meetings actions`) that cite one of its meetings. */
107
+ pending_findings: count,
108
+ untrusted,
109
+ });
110
+ /** One meeting row with its transcript lines, summaries, findings batches and the calendar's text. */
111
+ export const meetingEntryDetails = v.strictObject({
112
+ ...meetingEntry.entries,
113
+ description: v.nullable(text),
114
+ location: v.nullable(text),
115
+ summaries: v.array(v.strictObject({
116
+ meeting: reference,
117
+ source: text,
118
+ title: v.nullable(text),
119
+ overview: v.nullable(text),
120
+ sections: v.array(v.strictObject({ label: text, text })),
121
+ next_steps: v.array(text),
122
+ url: v.nullable(text),
123
+ })),
124
+ transcript: v.nullable(v.strictObject({
125
+ meeting: reference,
126
+ source: text,
127
+ language: v.nullable(text),
128
+ /** Lines from this position, as `--offset` asked. */
129
+ offset: count,
130
+ total: count,
131
+ has_more: v.boolean(),
132
+ lines: v.array(v.strictObject({
133
+ position: count,
134
+ offset_ms: count,
135
+ end_ms: count,
136
+ speaker: v.nullable(text),
137
+ person: v.nullable(personLink),
138
+ text,
139
+ })),
140
+ })),
141
+ /** `findings` cite the row's meetings; `pending` of them wait for the owner's decision. */
142
+ findings: v.array(v.strictObject({ id, status: v.picklist(["proposed", "reviewed"]), findings: count, pending: count })),
143
+ });
144
+ /**
145
+ * The listings' answers by entity name. Not in `ENTITIES`: that registry's inferred type is at the compiler's size
146
+ * limit, so a CLI registers these as its own (memo's `entityFields`).
147
+ */
148
+ export const LISTING_ENTITIES = {
149
+ document_entry: documentEntry,
150
+ document_entry_details: documentEntryDetails,
151
+ document_source: documentSource,
152
+ meeting_entry: meetingEntry,
153
+ meeting_entry_details: meetingEntryDetails,
154
+ };
@@ -154,6 +154,10 @@ const OTHERS = [
154
154
  validation("agent.cost-unknown", "the agent reports no cost, so a cost cap cannot stop it"),
155
155
  validation("document.changed", "the document changed while it was read; nothing was saved"),
156
156
  ["document.not-imported", "not_found", "the document is not imported in this source account"],
157
+ ["document.not-found", "not_found", "no listed document has that reference"],
158
+ ["meeting.not-found", "not_found", "no meeting row has that event or meeting reference"],
159
+ ["listing.source-not-found", "not_found", "a source: term names no account holding what is listed"],
160
+ validation("query.empty-window", "the time window ends before it starts, so no row can fall in it"),
157
161
  ["extraction.invalid-proposals", "invalid_response", "the model's memory proposals could not be used"],
158
162
  validation("extraction.text-too-long", "the text is too long for memory extraction"),
159
163
  validation("file.locked", "another process holds the file's lock"),
@@ -5,6 +5,7 @@ import { join } from "node:path";
5
5
  /**
6
6
  * The shared config (`~/.config/WireCat/config.json`) as a fresh or damaged machine has it. Only an explicit
7
7
  * "read only" answer limits a tool, and even then a sync runs: it only reads the service (owner ruling, 2026-11-13).
8
+ * A slip with one reading is mended in place (2026-11-14), so only `broken` states may fail a step.
8
9
  */
9
10
  const SHARED_CONFIGS = [
10
11
  { state: "no shared config, as on a fresh install" },
@@ -17,6 +18,10 @@ const SHARED_CONFIGS = [
17
18
  state: "a shared config with a byte-order mark",
18
19
  write: (dir) => writeFileSync(join(dir, "config.json"), '{"setup":{"permissions":"allow"}}'),
19
20
  },
21
+ {
22
+ state: "a shared config with a missing comma between two lines",
23
+ write: (dir) => writeFileSync(join(dir, "config.json"), '{\n "setup": {"permissions": "allow"}\n "theme": "dark"\n}\n'),
24
+ },
20
25
  {
21
26
  state: "a folder where the shared config should be",
22
27
  write: (dir) => mkdirSync(join(dir, "config.json")),
@@ -157,7 +157,7 @@ export type ReplyRuleFile = v.InferInput<typeof rule>;
157
157
  /**
158
158
  * Who may get an answer at all, whatever a rule says: everyone, or only those listed in `allow`; and
159
159
  * never anyone in `deny`, which wins when an id is in both. Tasks are not limited by it. A file that
160
- * does not say answers everyone a rule matches; `replies.send` is what keeps a new file silent.
160
+ * does not say answers everyone a rule matches; a new rule starts off, which keeps a new file silent.
161
161
  */
162
162
  declare const audienceShape: v.OptionalSchema<v.StrictObjectSchema<{
163
163
  readonly reply: v.OptionalSchema<v.PicklistSchema<["all", "listed"], undefined>, "all">;
@@ -76,7 +76,7 @@ const side = v.optional(v.strictObject({ people: v.optional(ids, []), chats: v.o
76
76
  /**
77
77
  * Who may get an answer at all, whatever a rule says: everyone, or only those listed in `allow`; and
78
78
  * never anyone in `deny`, which wins when an id is in both. Tasks are not limited by it. A file that
79
- * does not say answers everyone a rule matches; `replies.send` is what keeps a new file silent.
79
+ * does not say answers everyone a rule matches; a new rule starts off, which keeps a new file silent.
80
80
  */
81
81
  const audienceShape = v.optional(v.strictObject({ reply: v.optional(v.picklist(["all", "listed"]), "all"), allow: side, deny: side }), { reply: "all", allow: { people: [], chats: [] }, deny: { people: [], chats: [] } });
82
82
  const file = v.pipe(v.strictObject({ audience: audienceShape, rules: v.array(rule) }), v.check(({ rules }) => new Set(rules.map((one) => one.id)).size === rules.length, "two rules share an id; each needs its own"));
@@ -7,15 +7,16 @@ const DANGEROUS = new Set(["messages.delete", "bot.messages.delete", "topics.del
7
7
  export const skipFlagFor = (key) => DANGEROUS.has(key) ? "--allow-dangerous" : "--yes";
8
8
  /** Only what cannot be undone asks; the tool is meant to work without questions (owner, NEED-460). */
9
9
  export const DEFAULT_PERMISSIONS = {
10
- "messages.delete": "ask",
10
+ // Owner, 2026-11-14: deleting a message does not ask; a profile that wants the question sets `ask`.
11
+ "messages.delete": "allow",
11
12
  "account.sessions.end": "ask",
12
- "bot.messages.delete": "ask",
13
+ "bot.messages.delete": "allow",
13
14
  "topics.enable": "ask",
14
15
  "topics.delete": "ask",
15
16
  "chats.delete": "ask",
16
17
  "chats.clear": "ask",
17
- // NEED-568: a rule writes to people with nobody typing a command; it waits for the owner's own allow.
18
- "replies.send": "deny",
18
+ // Owner, 2026-11-14 (replaces NEED-568): a rule the owner enabled may send; `deny` stops every automatic reply.
19
+ "replies.send": "allow",
19
20
  // NEED-1662: an agent that changes settings, schedules or recipients could lift its own limits; the owner opts in.
20
21
  "mcp.authority": "deny",
21
22
  // NEED-1663: writes no level stopped before, so MCP could not offer them; over MCP `ask` goes ahead.
@@ -184,6 +184,7 @@ export { type DocumentTarget, openPictureEmbedderFor, type PictureOptions, remov
184
184
  export type { ModelChoice } from "./embeddings.js";
185
185
  export { calendarAccounts, type EventsFound, type EventsQuery, type FoundEvent, foundEvent, searchEvents, } from "./events-search.js";
186
186
  export { type GroupGuard, groupGuardOf, lockedRegistry } from "./group-guard.js";
187
+ export { DOCUMENT_TEXT_CANDIDATES, type DocumentEntry, type DocumentEntryDetails, type DocumentListRequest, type DocumentSourceEntry, type Listed, listDocumentSources, listDocuments, listMeetingEntries, type MeetingEntry, type MeetingEntryDetails, type MeetingListRequest, showDocument, showMeetingEntry, } from "./listings.js";
187
188
  export { createMeetingBatchReader } from "./meeting-batch.js";
188
189
  export { type MeetingCombinedHit, type MeetingCombinedRequest, searchMeetingsCombined, } from "./meeting-combined.js";
189
190
  export type { MeetingCommunicationCoverage, MeetingCommunicationExcerpt, MeetingCommunications, MeetingCommunicationsPort, MeetingCommunicationsRequest, } from "./meeting-communications-types.js";
@@ -140,6 +140,7 @@ export { countersService } from "./counters.js";
140
140
  export { openPictureEmbedderFor, removePicture, savePicture, } from "./document-pictures.js";
141
141
  export { calendarAccounts, foundEvent, searchEvents, } from "./events-search.js";
142
142
  export { groupGuardOf, lockedRegistry } from "./group-guard.js";
143
+ export { DOCUMENT_TEXT_CANDIDATES, listDocumentSources, listDocuments, listMeetingEntries, showDocument, showMeetingEntry, } from "./listings.js";
143
144
  export { createMeetingBatchReader } from "./meeting-batch.js";
144
145
  export { searchMeetingsCombined, } from "./meeting-combined.js";
145
146
  export { createMeetingContextService, } from "./meeting-context.js";
@@ -0,0 +1,74 @@
1
+ import type { QueryAst } from "@wirecat/cli-base/query";
2
+ import type * as v from "valibot";
3
+ import type { documentEntry, documentEntryDetails, documentSource, meetingEntry, meetingEntryDetails } from "../entities/listings.js";
4
+ import { type SearchTotal } from "../search/total.js";
5
+ import type { ListedAccount, MeetingRowKind, MessageStore } from "../store/index.js";
6
+ export type DocumentEntry = v.InferOutput<typeof documentEntry>;
7
+ export type DocumentEntryDetails = v.InferOutput<typeof documentEntryDetails>;
8
+ export type DocumentSourceEntry = v.InferOutput<typeof documentSource>;
9
+ export type MeetingEntry = v.InferOutput<typeof meetingEntry>;
10
+ export type MeetingEntryDetails = v.InferOutput<typeof meetingEntryDetails>;
11
+ /** How many documents a text term may match before the list counts them as "at least". */
12
+ export declare const DOCUMENT_TEXT_CANDIDATES = 2000;
13
+ export interface DocumentListRequest {
14
+ /** `source:` terms; every account holding documents when none. */
15
+ sources?: readonly string[];
16
+ /** Words searched as `search notes` searches them, in the document text and titles. */
17
+ text?: string;
18
+ /** The other terms, over the store's document fields (`kind`, `folder`, `source_modified_at`, `tag`, `person`). */
19
+ query?: QueryAst;
20
+ zone?: string;
21
+ now?: number;
22
+ limit: number;
23
+ offset: number;
24
+ }
25
+ export interface Listed<T> {
26
+ items: T[];
27
+ total: SearchTotal;
28
+ /** Every account read, `provider:account`. */
29
+ accounts: string[];
30
+ }
31
+ /** Every document of every account, or of the `source:` accounts, newest change first; a text term ranks nothing. */
32
+ export declare const listDocuments: (store: MessageStore, request: DocumentListRequest) => Promise<Listed<DocumentEntry>>;
33
+ /** The accounts holding documents, each with its folders flattened parents first, for a page's left panel. */
34
+ export declare const listDocumentSources: (store: MessageStore, { sources, depth }: {
35
+ sources?: readonly string[];
36
+ depth: number;
37
+ }) => Promise<DocumentSourceEntry[]>;
38
+ /** One document with `limit` characters of its text from `offset`, its tags, people, meetings and events. */
39
+ export declare const showDocument: (store: MessageStore, reference: string, text: {
40
+ offset: number;
41
+ limit: number;
42
+ }) => Promise<DocumentEntryDetails>;
43
+ export interface MeetingListRequest {
44
+ sources?: readonly string[];
45
+ kinds?: readonly MeetingRowKind[];
46
+ /** `person:<id>`. */
47
+ person?: string;
48
+ hasTranscript?: boolean;
49
+ titleWords?: readonly string[];
50
+ /** Rows that end after this instant; `fromDate` is the same bound as a local day, for all-day events. */
51
+ from?: number;
52
+ to?: number;
53
+ fromDate?: string;
54
+ toDate?: string;
55
+ newest?: boolean;
56
+ limit: number;
57
+ offset: number;
58
+ }
59
+ /**
60
+ * Meetings, calls and calendar events of every account (or the `source:` ones) as one row per real meeting, in a
61
+ * time window. A calendar event and its Zoom or Meet record share a row when the store linked them or their rooms
62
+ * (`join_key`) are the same and their times overlap.
63
+ */
64
+ export declare const listMeetingEntries: (store: MessageStore, request: MeetingListRequest) => Promise<Listed<MeetingEntry> & {
65
+ read: readonly ListedAccount[];
66
+ }>;
67
+ /**
68
+ * One row as `listMeetingEntries` shows it, with the calendar's text, every meeting's summaries, the findings citing
69
+ * them and `limit` transcript lines from `offset` of its first meeting with a transcript.
70
+ */
71
+ export declare const showMeetingEntry: (store: MessageStore, reference: string, lines: {
72
+ offset: number;
73
+ limit: number;
74
+ }) => Promise<MeetingEntryDetails>;
@@ -0,0 +1,285 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { eventIdOf } from "../calendar/index.js";
3
+ import { providerLabel } from "../domain/providers.js";
4
+ import { formatMeetingReference, parseMeetingReference } from "../meetings/index.js";
5
+ import { TOTAL_CAP } from "../search/total.js";
6
+ import { storeQuery } from "./notes-search.js";
7
+ /** How many documents a text term may match before the list counts them as "at least". */
8
+ export const DOCUMENT_TEXT_CANDIDATES = 2_000;
9
+ const iso = (ms) => (ms === null ? null : new Date(ms).toISOString());
10
+ const sourceName = ({ provider, account }) => `${provider}:${account}`;
11
+ const sourceOf = (account) => ({
12
+ provider: account.provider,
13
+ account: account.account,
14
+ source: sourceName(account),
15
+ label: `${providerLabel(account.provider)} · ${account.name ?? account.account}`,
16
+ });
17
+ /**
18
+ * The accounts `source:` terms name, among those holding what is listed: `provider:account`, or every account of a
19
+ * provider. One that names none is refused with the choices, never dropped.
20
+ */
21
+ const chosenAccounts = (held, sources, what) => {
22
+ if (!sources?.length)
23
+ return held;
24
+ const chosen = new Map();
25
+ for (const wanted of sources) {
26
+ const found = held.filter((account) => sourceName(account) === wanted || account.provider === wanted);
27
+ if (found.length === 0)
28
+ throw new CliError("not_found", `source:${wanted} names no account holding ${what} — the store holds ${held.map(sourceName).join(", ") || "none"}`, { reason: "listing.source-not-found" });
29
+ for (const account of found)
30
+ chosen.set(account.id, account);
31
+ }
32
+ return [...chosen.values()];
33
+ };
34
+ const documentItem = (row, accounts) => ({
35
+ ref: `document:${row.id}`,
36
+ id: String(row.id),
37
+ title: row.title,
38
+ file_name: row.fileName,
39
+ kind: row.kind,
40
+ mime: row.mime,
41
+ size: row.size,
42
+ source: sourceOf(accounts.get(row.accountId) ?? { provider: row.provider, account: row.account, name: row.accountName }),
43
+ folder: row.folder,
44
+ path: row.path,
45
+ url: row.url,
46
+ local_path: row.localPath,
47
+ source_modified_at: iso(row.modifiedAt),
48
+ stored_at: new Date(row.storedAt).toISOString(),
49
+ has_text: row.hasText,
50
+ untrusted: ["title", "file_name", "folder", "path"],
51
+ });
52
+ /** Every document of every account, or of the `source:` accounts, newest change first; a text term ranks nothing. */
53
+ export const listDocuments = async (store, request) => {
54
+ const held = await store.listings.documentAccounts();
55
+ const accounts = chosenAccounts(held, request.sources, "documents");
56
+ const narrowed = request.sources?.length ? accounts.map(({ id }) => id) : undefined;
57
+ let ids;
58
+ let capped = false;
59
+ if (request.text?.trim()) {
60
+ const { root, stemmer } = await storeQuery(store, request.text, request.zone ? { timezone: request.zone } : {});
61
+ const found = await store.notes.matchingRefs({
62
+ root,
63
+ limit: DOCUMENT_TEXT_CANDIDATES,
64
+ source: "file",
65
+ ...(narrowed ? { folderIds: narrowed.map(String) } : {}),
66
+ ...(stemmer ? { stemmer } : {}),
67
+ });
68
+ ids = found.refs.flatMap((ref) => (ref.startsWith("document:") ? [Number(ref.slice(9))] : []));
69
+ capped = found.hasMore;
70
+ }
71
+ const page = await store.listings.documents({
72
+ ...(narrowed ? { accountIds: narrowed } : {}),
73
+ ...(request.query ? { query: request.query } : {}),
74
+ ...(ids ? { ids } : {}),
75
+ ...(request.zone ? { zone: request.zone } : {}),
76
+ ...(request.now ? { now: request.now } : {}),
77
+ limit: request.limit,
78
+ offset: request.offset,
79
+ });
80
+ const byId = new Map(held.map((account) => [account.id, account]));
81
+ return {
82
+ items: page.items.map((row) => documentItem(row, byId)),
83
+ total: page.total > TOTAL_CAP || capped
84
+ ? { value: Math.min(page.total, TOTAL_CAP), relation: "gte" }
85
+ : { value: page.total, relation: "eq" },
86
+ accounts: accounts.map(sourceName),
87
+ };
88
+ };
89
+ /** The accounts holding documents, each with its folders flattened parents first, for a page's left panel. */
90
+ export const listDocumentSources = async (store, { sources, depth }) => {
91
+ const held = await store.listings.documentAccounts();
92
+ const accounts = chosenAccounts(held, sources, "documents");
93
+ const tree = await store.listings.documentSources({
94
+ ...(sources?.length ? { accountIds: accounts.map(({ id }) => id) } : {}),
95
+ depth,
96
+ });
97
+ const flat = (nodes, level) => nodes.flatMap((node) => [
98
+ { path: node.path, name: node.name, depth: level, count: node.count },
99
+ ...flat(node.folders, level + 1),
100
+ ]);
101
+ return tree.map((account) => ({
102
+ ...sourceOf(account),
103
+ name: account.name,
104
+ count: account.count,
105
+ loose: account.loose,
106
+ folders: flat(account.folders, 1),
107
+ }));
108
+ };
109
+ const documentId = (reference) => {
110
+ const match = /^document:([1-9]\d*)$/u.exec(reference.trim());
111
+ if (!match)
112
+ throw new CliError("validation_error", `${reference} is not a document; give its document:<id>`);
113
+ return Number(match[1]);
114
+ };
115
+ /** One document with `limit` characters of its text from `offset`, its tags, people, meetings and events. */
116
+ export const showDocument = async (store, reference, text) => {
117
+ const found = await store.listings.document(documentId(reference), text);
118
+ if (!found)
119
+ throw new CliError("not_found", `no document ${reference} in the store`, { reason: "document.not-found" });
120
+ const accounts = new Map((await store.listings.documentAccounts()).map((account) => [account.id, account]));
121
+ return {
122
+ ...documentItem(found, accounts),
123
+ text: found.text,
124
+ text_offset: Math.min(text.offset, found.textLength),
125
+ text_length: found.textLength,
126
+ has_more: found.text !== null && text.offset + found.text.length < found.textLength,
127
+ extraction: found.extraction,
128
+ extraction_error: found.extractionError,
129
+ language: found.language,
130
+ tags: found.tags,
131
+ people: found.people,
132
+ meetings: found.meetings.map(({ ref, title, at, role }) => ({ ref, title, at: iso(at), role })),
133
+ events: found.events.map(({ ref, title, at, role }) => ({ ref, title, at: iso(at), role })),
134
+ untrusted: ["title", "file_name", "folder", "path", "text", "meetings.title", "events.title"],
135
+ };
136
+ };
137
+ const ref = ({ id, accountId }) => formatMeetingReference({ type: "meeting", accountId, meetingId: id });
138
+ const meetingItem = (row, accounts) => {
139
+ const meetings = row.meetings.map(({ id, accountId }) => ref({ id, accountId }));
140
+ const named = (provider, account) => accounts.get(`${provider}:${account}`) ?? { provider, account, name: null };
141
+ return {
142
+ ref: row.type === "event" ? `event:${row.id}` : meetings[0],
143
+ kind: row.kind,
144
+ title: row.title,
145
+ started_at: iso(row.startsAt),
146
+ ended_at: iso(row.endsAt),
147
+ duration_ms: row.startsAt !== null && row.endsAt !== null && row.endsAt >= row.startsAt ? row.endsAt - row.startsAt : null,
148
+ all_day: row.allDay,
149
+ timezone: row.timezone,
150
+ status: row.status,
151
+ url: row.url,
152
+ links: row.links,
153
+ sources: row.sources.map((source) => ({
154
+ ...sourceOf(named(source.provider, source.account)),
155
+ via: source.via,
156
+ calendar: source.calendar,
157
+ ref: source.ref,
158
+ })),
159
+ meetings,
160
+ participants: row.participants,
161
+ participants_count: row.participants.length,
162
+ has_recording: row.hasRecording,
163
+ has_transcript: row.hasTranscript,
164
+ has_summary: row.hasSummary,
165
+ documents: row.documents,
166
+ pending_findings: row.pendingFindings,
167
+ untrusted: ["title", "participants.name", "sources.calendar", "documents.title"],
168
+ };
169
+ };
170
+ const personIdOf = (value) => {
171
+ const match = /^(?:person:)?([1-9]\d*)$/u.exec(value.trim());
172
+ if (!match)
173
+ throw new CliError("validation_error", `person:${value} is not a person; give person:<id>`);
174
+ return Number(match[1]);
175
+ };
176
+ /**
177
+ * Meetings, calls and calendar events of every account (or the `source:` ones) as one row per real meeting, in a
178
+ * time window. A calendar event and its Zoom or Meet record share a row when the store linked them or their rooms
179
+ * (`join_key`) are the same and their times overlap.
180
+ */
181
+ export const listMeetingEntries = async (store, request) => {
182
+ const held = await store.listings.meetingAccounts();
183
+ const accounts = chosenAccounts(held, request.sources, "calendars or meetings");
184
+ const page = await store.listings.meetingRows({
185
+ ...(request.sources?.length ? { accountIds: accounts.map(({ id }) => id) } : {}),
186
+ ...(request.kinds?.length ? { kinds: request.kinds } : {}),
187
+ ...(request.person === undefined ? {} : { personId: personIdOf(request.person) }),
188
+ ...(request.hasTranscript === undefined ? {} : { hasTranscript: request.hasTranscript }),
189
+ ...(request.titleWords?.length ? { titleWords: request.titleWords } : {}),
190
+ ...(request.from === undefined ? {} : { from: request.from }),
191
+ ...(request.to === undefined ? {} : { to: request.to }),
192
+ ...(request.fromDate === undefined ? {} : { fromDate: request.fromDate }),
193
+ ...(request.toDate === undefined ? {} : { toDate: request.toDate }),
194
+ ...(request.newest === undefined ? {} : { newest: request.newest }),
195
+ limit: request.limit,
196
+ offset: request.offset,
197
+ });
198
+ const byName = new Map(held.map((account) => [sourceName(account), account]));
199
+ return {
200
+ items: page.items.map((row) => meetingItem(row, byName)),
201
+ total: { value: page.total, relation: "eq" },
202
+ accounts: accounts.map(sourceName),
203
+ read: accounts,
204
+ };
205
+ };
206
+ const targetOf = (reference) => {
207
+ const text = reference.trim();
208
+ if (text.startsWith("event:"))
209
+ return { event: eventIdOf(text) };
210
+ if (text.startsWith("meeting:") && text.split("/").length === 2)
211
+ return parseMeetingReference(text);
212
+ throw new CliError("validation_error", `${reference} is not a meeting; give its event:<id> or meeting:<account>/<id>`);
213
+ };
214
+ /**
215
+ * One row as `listMeetingEntries` shows it, with the calendar's text, every meeting's summaries, the findings citing
216
+ * them and `limit` transcript lines from `offset` of its first meeting with a transcript.
217
+ */
218
+ export const showMeetingEntry = async (store, reference, lines) => {
219
+ const target = targetOf(reference);
220
+ const row = await store.listings.meetingRow("event" in target ? target : { meeting: target.meetingId });
221
+ const asked = (one) => "meetingId" in target && one.id === target.meetingId && one.accountId === target.accountId;
222
+ if (!row || ("meetingId" in target && !row.meetings.some(asked)))
223
+ throw new CliError("not_found", `no meeting ${reference} in the store`, { reason: "meeting.not-found" });
224
+ const byName = new Map((await store.listings.meetingAccounts()).map((account) => [sourceName(account), account]));
225
+ const event = row.type === "event" ? await store.calendar.event(row.id) : null;
226
+ const details = [];
227
+ for (const { id } of row.meetings) {
228
+ const one = await store.meetings.meeting(id);
229
+ if (one)
230
+ details.push(one);
231
+ }
232
+ const live = event?.entries.find(({ deletedAt }) => deletedAt === null) ?? event?.entries[0];
233
+ const first = details[0]?.meeting;
234
+ const spoken = details.flatMap((one) => one.transcripts
235
+ .filter(({ transcript }) => transcript.deletedAt === null && transcript.supersededAt === null)
236
+ .map((transcript) => ({ meeting: one, ...transcript })))[0];
237
+ const people = new Map((spoken?.meeting.participants ?? []).map((participant) => [participant.id, participant.person ?? null]));
238
+ return {
239
+ ...meetingItem(row, byName),
240
+ description: live?.description ?? event?.event.description ?? first?.description ?? null,
241
+ location: live?.location ?? event?.event.location ?? first?.location ?? null,
242
+ summaries: details.flatMap((one) => one.summaries.map((summary) => ({
243
+ meeting: ref(one.meeting),
244
+ source: summary.source,
245
+ title: summary.title,
246
+ overview: summary.overview,
247
+ sections: summary.sections,
248
+ next_steps: summary.nextSteps,
249
+ url: summary.docUrl,
250
+ }))),
251
+ transcript: spoken
252
+ ? {
253
+ meeting: ref(spoken.meeting.meeting),
254
+ source: spoken.transcript.source,
255
+ language: spoken.transcript.language,
256
+ offset: lines.offset,
257
+ total: spoken.rows.length,
258
+ has_more: lines.offset + lines.limit < spoken.rows.length,
259
+ lines: spoken.rows.slice(lines.offset, lines.offset + lines.limit).map((line) => {
260
+ const person = line.speakerParticipantId === null ? null : (people.get(line.speakerParticipantId) ?? null);
261
+ return {
262
+ position: line.position,
263
+ offset_ms: line.startMs,
264
+ end_ms: line.endMs,
265
+ speaker: line.speakerName,
266
+ person: person === null ? null : { ref: `person:${person.uid}`, name: person.name ?? null },
267
+ text: line.text,
268
+ };
269
+ }),
270
+ }
271
+ : null,
272
+ findings: row.findings,
273
+ untrusted: [
274
+ "title",
275
+ "description",
276
+ "location",
277
+ "participants.name",
278
+ "sources.calendar",
279
+ "documents.title",
280
+ "summaries",
281
+ "transcript.lines.speaker",
282
+ "transcript.lines.text",
283
+ ],
284
+ };
285
+ };
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -54,6 +54,7 @@ export { type CrmContactsRemoved, type CrmCopies, type CrmRelationIssue, type Cr
54
54
  export { COMPANY_TYPE_MEANINGS, type CompanyTypeMeaning, CRM_LINK_MODES, type CrmLinkMode, type CrmStageMove, type CrmStageTasks, crmSettingKey, type StageTaskRule, } from "./sqlite/crm-settings.js";
55
55
  export type { Deal, DealFilter, DealInput, DealPerson, DealScope, DealsStore, FunnelStage, Pipeline, PipelineInput, PipelineReport, PipelineStage, StageChange, } from "./sqlite/deals.js";
56
56
  export type { DecisionMessage, DecisionPress, DecisionRefusal, DecisionRequest, DecisionRequestInput, DecisionRequestStore, TakeResult, } from "./sqlite/decision-requests.js";
57
+ export { DOCUMENT_KINDS, type DocumentDetail, type DocumentFolderNode, type DocumentKind, type DocumentLink, type DocumentListFilter, type DocumentListing, type DocumentListRow, type DocumentSourceNode, } from "./sqlite/document-listing.js";
57
58
  export type { Email, EmailAddress, EmailAttachment, EmailFacts, EmailFilter, EmailInput, EmailInThread, EmailLocationInput, EmailRecipient, EmailRef, EmailThread, EmailVectorHit, FolderEmail, Mailbox, MailboxInput, MailFilter, MailStore, PartialEmail, SenderScore, ThreadDetails, ThreadSave, } from "./sqlite/emails.js";
58
59
  export { EVENT_FIELDS, type EventChunkToEmbed, type EventHit, type EventQuery, type EventSearch, type NearestEvent, } from "./sqlite/event-search.js";
59
60
  export type { EvidenceInput, EvidenceMetadata } from "./sqlite/evidence-signature.js";
@@ -67,6 +68,7 @@ export type { Involvement, InvolvementStore } from "./sqlite/involvements.js";
67
68
  export type { Annotation, KnowledgeRelation, KnowledgeStore, KnowledgeTarget, LabelledType, Organization, Project, Reminder, } from "./sqlite/knowledge.js";
68
69
  export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js";
69
70
  export type { MailRule, MailRuleCount, MailRuleInput, MailRulesStore } from "./sqlite/mail-rules.js";
71
+ export { type ListedAccount, MEETING_ROW_KINDS, type MeetingListFilter, type MeetingListing, type MeetingRow, type MeetingRowDocument, type MeetingRowKind, type MeetingRowParticipant, type MeetingRowSource, } from "./sqlite/meeting-listing.js";
70
72
  export type { MeetingProjectLink, MeetingProjectsStore } from "./sqlite/meeting-projects.js";
71
73
  export type { MeetingContextReadCapabilities, MeetingReadCapabilities, MeetingReadScope, TranscriptContextInput, TranscriptContextPage, TranscriptPage, TranscriptReadScope, TranscriptRowPage, } from "./sqlite/meeting-reads.js";
72
74
  export type { MeetingVectorHit, MeetingVectors } from "./sqlite/meeting-vectors.js";
@@ -35,10 +35,12 @@ export { BUSINESS_FIND_MAX } from "./sqlite/business-search.js";
35
35
  export { CATALOG_QUERY } from "./sqlite/catalog.js";
36
36
  export { crmIdentityId, } from "./sqlite/crm.js";
37
37
  export { COMPANY_TYPE_MEANINGS, CRM_LINK_MODES, crmSettingKey, } from "./sqlite/crm-settings.js";
38
+ export { DOCUMENT_KINDS, } from "./sqlite/document-listing.js";
38
39
  export { EVENT_FIELDS, } from "./sqlite/event-search.js";
39
40
  export { QUOTE_LIMIT, quoteKept } from "./sqlite/evidence-signature.js";
40
41
  export { IMPORTED_DOCUMENT_QUERY } from "./sqlite/imported-documents.js";
41
42
  export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES } from "./sqlite/knowledge.js";
43
+ export { MEETING_ROW_KINDS, } from "./sqlite/meeting-listing.js";
42
44
  export { NOTE_FIELDS, } from "./sqlite/note-search.js";
43
45
  export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
44
46
  export { PEOPLE_SORTS, } from "./sqlite/people-list.js";