@wirecat/cli-core 0.658.0 → 0.660.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 (50) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/dist/cli/ask-before-write.d.ts +8 -0
  3. package/dist/cli/ask-before-write.js +28 -0
  4. package/dist/cli/config-command.js +2 -9
  5. package/dist/cli/config-issues.js +1 -1
  6. package/dist/cli/index.d.ts +1 -0
  7. package/dist/cli/index.js +1 -0
  8. package/dist/cli/messenger/messages-delete-command.d.ts +2 -1
  9. package/dist/cli/messenger/messages-delete-command.js +2 -1
  10. package/dist/{cli → domain}/config-repair.d.ts +7 -0
  11. package/dist/{cli → domain}/config-repair.js +53 -0
  12. package/dist/domain/providers.js +1 -1
  13. package/dist/entities/index.d.ts +33 -93
  14. package/dist/errors/reasons.js +12 -0
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/kit/sync-after-install.js +5 -0
  18. package/dist/meetings/answers.d.ts +35 -27
  19. package/dist/meetings/answers.js +3 -2
  20. package/dist/meetings/cli/index.d.ts +13 -0
  21. package/dist/meetings/cli/index.js +61 -16
  22. package/dist/meetings/cli/management.d.ts +16 -0
  23. package/dist/meetings/cli/management.js +90 -0
  24. package/dist/meetings/index.d.ts +5 -3
  25. package/dist/meetings/index.js +4 -2
  26. package/dist/meetings/item.d.ts +33 -19
  27. package/dist/meetings/item.js +29 -4
  28. package/dist/meetings/pull.d.ts +27 -2
  29. package/dist/meetings/pull.js +103 -78
  30. package/dist/meetings/read-through.d.ts +74 -0
  31. package/dist/meetings/read-through.js +330 -0
  32. package/dist/meetings/reads.d.ts +1 -0
  33. package/dist/meetings/reads.js +4 -2
  34. package/dist/meetings/result-items.d.ts +31 -0
  35. package/dist/meetings/result-items.js +31 -0
  36. package/dist/meetings/source.d.ts +47 -0
  37. package/dist/meetings/store.d.ts +7 -0
  38. package/dist/meetings/testing/memory.js +8 -1
  39. package/dist/replies/rules.d.ts +1 -1
  40. package/dist/replies/rules.js +1 -1
  41. package/dist/search/service-query.d.ts +63 -0
  42. package/dist/search/service-query.js +57 -0
  43. package/dist/sends/permissions.js +9 -4
  44. package/dist/services/messages-search.js +3 -4
  45. package/dist/services/server-search.d.ts +2 -1
  46. package/dist/services/server-search.js +36 -32
  47. package/dist/store/shared-config.d.ts +2 -0
  48. package/dist/store/shared-config.js +38 -8
  49. package/dist/store/sqlite/meetings.js +15 -1
  50. package/package.json +1 -1
@@ -123,7 +123,38 @@ const repair = v.strictObject({
123
123
  transcripts: count,
124
124
  languages: v.array(v.strictObject({ language: nullableText, transcripts: count })),
125
125
  });
126
+ const kind = v.picklist(["instant", "scheduled"]);
127
+ /** What `meetings create|update|cancel` did on the service, or would do under `--dry-run` (`applied: false`). */
128
+ const managedChange = v.strictObject({
129
+ action: v.picklist(["create", "update", "cancel"]),
130
+ provider: text,
131
+ account: text,
132
+ id: v.optional(identifier),
133
+ occurrence_id: v.optional(identifier),
134
+ change: v.optional(v.strictObject({
135
+ title: v.optional(text),
136
+ kind: v.optional(kind),
137
+ start_time: v.optional(text),
138
+ duration_minutes: v.optional(count),
139
+ timezone: v.optional(text),
140
+ agenda: v.optional(text),
141
+ })),
142
+ applied: flag,
143
+ meeting: v.optional(v.strictObject({
144
+ id: identifier,
145
+ title: nullableText,
146
+ kind: v.nullable(kind),
147
+ start_time: nullableText,
148
+ duration_minutes: v.nullable(count),
149
+ timezone: nullableText,
150
+ agenda: nullableText,
151
+ join_url: nullableText,
152
+ })),
153
+ });
154
+ const invitation = v.strictObject({ id: identifier, invitation: text, untrusted: v.optional(v.array(text)) });
126
155
  export const MEETING_RESULT_ENTITIES = {
156
+ meeting_change: managedChange,
157
+ meeting_invitation: invitation,
127
158
  meeting_ingestion: run,
128
159
  meeting_export: exported,
129
160
  meeting_association: meetingChange,
@@ -1,3 +1,5 @@
1
+ import type { Predicate } from "@wirecat/cli-base/query";
2
+ import type { ServiceOperator } from "../search/service-query.js";
1
3
  import type { Metadata, SourceChatLine, SourceMeeting, SummaryContent, TranscriptLine } from "./model.js";
2
4
  import type { MeetingDocumentInput, MeetingSave } from "./store.js";
3
5
  export interface SourceParticipant {
@@ -17,6 +19,42 @@ export interface SourceParticipant {
17
19
  sessions: import("./model.js").JsonValue;
18
20
  metadata: Metadata;
19
21
  }
22
+ /** When the meetings `find` asks for started, epoch milliseconds, both ends inclusive; an open end is the source's. */
23
+ export interface MeetingWindow {
24
+ from?: number;
25
+ to?: number;
26
+ }
27
+ /** A `meetings list` term `find` declared it reads, besides `started_at`; `negated` only for a negatable field. */
28
+ export interface MeetingTerm {
29
+ predicate: Predicate;
30
+ negated: boolean;
31
+ }
32
+ /** A meeting the service returned, with its participants when the same answer carries them. */
33
+ export interface FoundMeeting {
34
+ meeting: SourceMeeting;
35
+ participants?: SourceParticipant[] | null;
36
+ }
37
+ export interface FoundMeetings {
38
+ meetings: FoundMeeting[];
39
+ /** The next page's cursor; `null` on the last page. */
40
+ next: string | null;
41
+ }
42
+ /** One meeting with what `meetings show` keeps of it: its people, transcript and Drive documents. */
43
+ export interface FullMeeting extends FoundMeeting {
44
+ transcript?: TranscriptLine[] | null;
45
+ documents?: MeetingDocumentInput[] | null;
46
+ }
47
+ /**
48
+ * What `find` filters besides `started_at`, which every `find` takes as its window: `meetings list` fields and the
49
+ * operators the service reads on each (`provider_id: ["term"]`). The store decides the rest of the query.
50
+ */
51
+ export interface MeetingFinds {
52
+ fields: Readonly<Record<string, readonly ServiceOperator[]>>;
53
+ /** The fields whose NOT the service can send. */
54
+ negatable?: readonly string[];
55
+ /** False for a service that lists no meeting before it starts (Meet: scheduling is Google Calendar's). */
56
+ upcoming?: boolean;
57
+ }
20
58
  /** Null means unavailable; it never requests deletion of previously saved data. */
21
59
  export interface MeetingSource {
22
60
  readonly provider: string;
@@ -40,4 +78,13 @@ export interface MeetingSource {
40
78
  files(occurrenceId: string): Promise<NonNullable<MeetingSave["attachments"]> | null>;
41
79
  /** The Drive files the service saved for the occurrence: its transcript, recording and notes documents. */
42
80
  documents?(occurrenceId: string): Promise<MeetingDocumentInput[] | null>;
81
+ /** What `find` reads of a `meetings list` query; required with `find`. */
82
+ readonly finds?: MeetingFinds;
83
+ /**
84
+ * The meetings that may match, for `meetings list`: one page from `cursor` (`null` first). Each meeting's
85
+ * `occurrence.id` is the one `meetings()` gives, so the row it is kept as is the row `sync` writes.
86
+ */
87
+ find?(window: MeetingWindow, terms: readonly MeetingTerm[], cursor: string | null): Promise<FoundMeetings>;
88
+ /** One meeting by the service's id, for `meetings show`; `null` when the service has none. */
89
+ get?(id: string): Promise<FullMeeting | null>;
43
90
  }
@@ -98,6 +98,11 @@ export interface MeetingFilter {
98
98
  accountId?: number;
99
99
  /** A validated `meetings list` query over `MEETING_QUERY`'s fields. */
100
100
  query?: QueryAst;
101
+ /** The zone and the instant the query's dates are read in; UTC and the current time without them. */
102
+ timezone?: string;
103
+ now?: number;
104
+ /** Only these stored meetings, by their store id. */
105
+ ids?: readonly number[];
101
106
  eventId?: number;
102
107
  meetingSeriesId?: number;
103
108
  since?: number;
@@ -158,6 +163,8 @@ export interface MeetingStore {
158
163
  /** The provider and account a meeting account id stands for; `null` when the store has no such account. */
159
164
  account(id: number): Promise<MeetingOwner | null>;
160
165
  meeting(id: number): Promise<MeetingDetails | null>;
166
+ /** The account's meeting the provider knows by `externalId` (the occurrence id), deleted or not; `null` when none. */
167
+ meetingByExternalId?(accountId: number, externalId: string): Promise<MeetingDetails | null>;
161
168
  participants(query: string, accountId?: number): Promise<Participant[]>;
162
169
  search(query: string, filter?: MeetingFilter): Promise<ListResult<SearchHit>>;
163
170
  events(): Promise<Event[]>;
@@ -19,8 +19,12 @@ const filterMeetings = (rows, filter = {}) => {
19
19
  (filter.meetingSeriesId === undefined || m.meetingSeriesId === filter.meetingSeriesId) &&
20
20
  (filter.since === undefined || (m.startedAt !== null && m.startedAt >= filter.since)) &&
21
21
  (filter.until === undefined || (m.startedAt !== null && m.startedAt <= filter.until)) &&
22
+ (filter.ids === undefined || filter.ids.includes(m.id)) &&
22
23
  (filter.query === undefined ||
23
- evaluate(filter.query, MEETING_QUERY.fields, meetingItem(m, MEMORY_OWNER(m.accountId)))))
24
+ evaluate(filter.query, MEETING_QUERY.fields, meetingItem(m, MEMORY_OWNER(m.accountId)), {
25
+ zone: filter.timezone ?? "UTC",
26
+ ...(filter.now === undefined ? {} : { now: filter.now }),
27
+ })))
24
28
  .sort((a, b) => (b.meeting.startedAt ?? 0) - (a.meeting.startedAt ?? 0) || a.meeting.id - b.meeting.id)
25
29
  .slice(filter.offset ?? 0, filter.limit === undefined ? undefined : (filter.offset ?? 0) + filter.limit);
26
30
  };
@@ -93,6 +97,9 @@ export const memoryMeetingStore = () => {
93
97
  async meeting(id) {
94
98
  return structuredClone(state.meetings.find((d) => d.meeting.id === id) ?? null);
95
99
  },
100
+ async meetingByExternalId(accountId, externalId) {
101
+ return structuredClone(state.meetings.find((d) => d.meeting.accountId === accountId && d.meeting.externalId === externalId) ?? null);
102
+ },
96
103
  async participants(query, accountId) {
97
104
  const term = query.toLocaleLowerCase();
98
105
  return structuredClone(state.meetings
@@ -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"));
@@ -0,0 +1,63 @@
1
+ import { type DateRange, type Occur, type Predicate, type Span } from "@wirecat/cli-base/query";
2
+ /**
3
+ * Where a read looks, the one vocabulary of messages, mail, calendar and meetings: the store (`archive`), the
4
+ * service's own search (`server`), or both, with what the service returns kept in the store.
5
+ */
6
+ export declare const BACKENDS: readonly ["archive", "server", "both"];
7
+ export type Backend = (typeof BACKENDS)[number];
8
+ /** The operators a service's own search may read; patterns and regexes always stay with the store. */
9
+ export type ServiceOperator = "term" | "phrase" | "range";
10
+ /** A parsed query whose leaves may carry what resolving them found, as messages' `ResolvedNode` does. */
11
+ export type QueryTree<P extends Predicate = Predicate> = P | {
12
+ kind: "boolean";
13
+ clauses: {
14
+ occur: Occur;
15
+ node: QueryTree<P>;
16
+ }[];
17
+ span: Span;
18
+ };
19
+ /**
20
+ * What a service's search can filter, and how its call is built. `B` is one call's criteria in the caller's terms. The
21
+ * store answers the whole query afterwards, so a part the service cannot read is left out: that only widens a call.
22
+ */
23
+ export interface ServiceCapability<P extends Predicate, B> {
24
+ /** The fields the service filters, each with the operators it reads. */
25
+ fields: Readonly<Record<string, readonly ServiceOperator[]>>;
26
+ /** The fields whose NOT the service can send; every other NOT is the store's. */
27
+ negatable?: readonly string[];
28
+ /** At most this many calls; the branches beyond it are not asked and the answer is not complete. */
29
+ maxCalls: number;
30
+ /** Criteria that match everything: where every call starts, and what a part left out becomes. */
31
+ all: B;
32
+ /**
33
+ * One readable leaf as criteria. `undefined` drops the branch it is in: no call can match it (another account's
34
+ * chat). A leaf with nothing to send but that may match returns `all` itself.
35
+ */
36
+ leaf(predicate: P, negated: boolean): B | undefined;
37
+ /** Both criteria at once; `undefined` when they cannot both hold, so the branch is never asked. */
38
+ both(one: B, other: B): B | undefined;
39
+ /** A service that can OR joins every branch into its one call; without it each OR branch is a call of its own. */
40
+ either?(branches: B[]): B;
41
+ /** Whether a branch is worth a call: messages asks only with words. A branch left out does not count as a call. */
42
+ sends?(branch: B): boolean;
43
+ }
44
+ export interface ServiceCalls<B> {
45
+ calls: B[];
46
+ /** False when the cap left a branch unasked. */
47
+ complete: boolean;
48
+ /** Branches `sends` refused. */
49
+ unsent: number;
50
+ }
51
+ /**
52
+ * Splits a parsed query into the calls a service's search can take: the parts it can read kept, the rest left out,
53
+ * which only widens a call and never loses a hit, since the store answers the whole query after. Each OR branch is a
54
+ * call of its own, up to `maxCalls`, unless the service can OR. `scope` holds in every call (`--chat`).
55
+ */
56
+ export declare const serviceCallsOf: <P extends Predicate, B>(root: QueryTree<P>, capability: ServiceCapability<P, B>, scope?: B) => ServiceCalls<B>;
57
+ /** A time leaf (`date:`, `started_at:`) as the range it names, in `zone`, at `now`. */
58
+ export declare const rangeOf: (node: Predicate, zone: string, now?: number) => DateRange;
59
+ /** Inclusive bounds in milliseconds, as a service's window takes them; an open side is left out. */
60
+ export declare const windowOf: ({ lower, upper, lower_inclusive, upper_inclusive, }: DateRange) => {
61
+ from?: number;
62
+ to?: number;
63
+ };
@@ -0,0 +1,57 @@
1
+ import { dateRange } from "@wirecat/cli-base/query";
2
+ /**
3
+ * Where a read looks, the one vocabulary of messages, mail, calendar and meetings: the store (`archive`), the
4
+ * service's own search (`server`), or both, with what the service returns kept in the store.
5
+ */
6
+ export const BACKENDS = ["archive", "server", "both"];
7
+ /** Past this many branches an AND of ORs is not multiplied further: the clause is left to the store. */
8
+ const MAX_BRANCHES = 64;
9
+ // Criteria may be arrays themselves, so a missing one is an empty list and a present one is wrapped.
10
+ const some = (value) => (value === undefined ? [] : [value]);
11
+ const readable = (node, capability) => capability.fields[node.field]?.includes(node.operator) === true;
12
+ const branchesOf = (node, capability, cut) => {
13
+ if (node.kind === "predicate")
14
+ return readable(node, capability) ? some(capability.leaf(node, false)) : [capability.all];
15
+ const must = node.clauses.filter(({ occur }) => occur === "must");
16
+ const not = node.clauses.flatMap(({ occur, node }) => occur === "must_not" &&
17
+ node.kind === "predicate" &&
18
+ capability.negatable?.includes(node.field) &&
19
+ readable(node, capability)
20
+ ? some(capability.leaf(node, true))
21
+ : []);
22
+ const should = node.clauses.filter(({ occur }) => occur === "should");
23
+ // Lucene: beside a required clause an optional one only ranks, so only the required ones narrow.
24
+ const base = must.length || !should.length
25
+ ? must.reduce((product, { node }) => {
26
+ const next = product.flatMap((one) => branchesOf(node, capability, cut).flatMap((other) => some(capability.both(one, other))));
27
+ // Leaving a required clause out only widens the calls: nothing is lost.
28
+ return next.length > MAX_BRANCHES ? product : next;
29
+ }, [capability.all])
30
+ : should.flatMap(({ node }) => branchesOf(node, capability, cut));
31
+ if (base.length > MAX_BRANCHES)
32
+ cut.branches = true;
33
+ return not.reduce((branches, negated) => branches.flatMap((one) => some(capability.both(one, negated))), base.slice(0, MAX_BRANCHES));
34
+ };
35
+ /**
36
+ * Splits a parsed query into the calls a service's search can take: the parts it can read kept, the rest left out,
37
+ * which only widens a call and never loses a hit, since the store answers the whole query after. Each OR branch is a
38
+ * call of its own, up to `maxCalls`, unless the service can OR. `scope` holds in every call (`--chat`).
39
+ */
40
+ export const serviceCallsOf = (root, capability, scope) => {
41
+ const cut = { branches: false };
42
+ const all = branchesOf(root, capability, cut).flatMap((branch) => scope === undefined ? [branch] : some(capability.both(scope, branch)));
43
+ const sent = capability.sends ? all.filter((branch) => capability.sends?.(branch)) : all;
44
+ const unique = [...new Map(sent.map((branch) => [JSON.stringify(branch), branch])).values()];
45
+ const unsent = all.length - sent.length;
46
+ if (capability.either && unique.length)
47
+ return { calls: [capability.either(unique)], complete: !cut.branches, unsent };
48
+ const max = Math.max(1, capability.maxCalls);
49
+ return { calls: unique.slice(0, max), complete: !cut.branches && unique.length <= max, unsent };
50
+ };
51
+ /** A time leaf (`date:`, `started_at:`) as the range it names, in `zone`, at `now`. */
52
+ export const rangeOf = (node, zone, now) => dateRange(node.value, node.operator === "range" ? (node.upper ?? "*") : node.value, node.operator === "range" ? node.lower_inclusive === true : true, node.operator === "range" ? node.upper_inclusive === true : true, zone, node.span, now);
53
+ /** Inclusive bounds in milliseconds, as a service's window takes them; an open side is left out. */
54
+ export const windowOf = ({ lower, upper, lower_inclusive, upper_inclusive, }) => ({
55
+ ...(lower === undefined ? {} : { from: lower_inclusive ? lower : lower + 1 }),
56
+ ...(upper === undefined ? {} : { to: upper_inclusive ? upper : upper - 1 }),
57
+ });
@@ -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.
@@ -41,6 +42,10 @@ export const DEFAULT_PERMISSIONS = {
41
42
  "schedule.run": "ask",
42
43
  "schedule.exec": "ask",
43
44
  "doctor.reports.create": "ask",
45
+ // A meeting changed on the service reaches its invitees: asked first, as zoom's `remote-meetings` was.
46
+ "meetings.create": "ask",
47
+ "meetings.update": "ask",
48
+ "meetings.cancel": "ask",
44
49
  };
45
50
  /** Commands under a housekeeping word, or store maintenance, that still have a key of their own: their path. */
46
51
  export const KEYED_UNDER_HOUSEKEEPING = new Set(Object.keys(DEFAULT_PERMISSIONS).filter((key) => /^(store|server|models|images|schedule|doctor)\./.test(key)));
@@ -15,8 +15,9 @@ import { chatAmong, chatsMatchingIn, senderAmong, sendersMatching } from "./mess
15
15
  import { accountsOfKind, listedAccounts, MAIL } from "./search-kind.js";
16
16
  const PERSON_FIELDS = new Set(["from", "to", "cc", "bcc"]);
17
17
  const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is", "list"]);
18
- import { dateRange, parseLucene, timezoneOf, walkQuery, } from "@wirecat/cli-base/query";
18
+ import { parseLucene, timezoneOf, walkQuery, } from "@wirecat/cli-base/query";
19
19
  import { MESSAGE_PARSING, searchError } from "../search/lucene/types.js";
20
+ import { rangeOf } from "../search/service-query.js";
20
21
  const positiveSources = (node) => node.kind === "predicate"
21
22
  ? node.field === "in"
22
23
  ? [node.value.toLowerCase()]
@@ -118,9 +119,7 @@ export const prepareLucene = async (store, account, request, messenger) => {
118
119
  if (node.field === "date")
119
120
  return {
120
121
  ...node,
121
- resolution: {
122
- date: dateRange(node.value, node.operator === "range" ? (node.upper ?? "*") : node.value, node.operator === "range" ? node.lower_inclusive === true : true, node.operator === "range" ? node.upper_inclusive === true : true, timezone, node.span),
123
- },
122
+ resolution: { date: rangeOf(node, timezone) },
124
123
  };
125
124
  return node;
126
125
  };
@@ -1,4 +1,5 @@
1
1
  import type { Id } from "../domain/models.js";
2
+ import { type Backend } from "../search/service-query.js";
2
3
  import type { ServiceDeps } from "./deps.js";
3
4
  import type { SearchQuery } from "./messages.js";
4
5
  export declare const SERVER_SEARCH_KEY = "messages.server-search";
@@ -13,7 +14,7 @@ export declare const SERVER_BOUNDS: {
13
14
  textBytes: number;
14
15
  };
15
16
  export declare const DEFAULT_BACKEND = "both";
16
- export type Backend = "archive" | "server" | "both";
17
+ export type { Backend };
17
18
  export interface ServerOptions {
18
19
  timeMs?: number;
19
20
  }
@@ -1,5 +1,6 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { capability } from "../ports/messenger.js";
3
+ import { serviceCallsOf, windowOf } from "../search/service-query.js";
3
4
  import { prepareLucene } from "./messages-search.js";
4
5
  export const SERVER_SEARCH_KEY = "messages.server-search";
5
6
  /**
@@ -27,33 +28,40 @@ const merge = (one, other) => {
27
28
  };
28
29
  };
29
30
  const sameAccount = (one, other) => one.provider === other.provider && one.account === other.account;
30
- // Each branch is one server call that narrows the candidates; the strict local query decides. A
31
- // part the server cannot read is left out, which only widens a branch, never drops a hit.
32
- const branchesOf = (node, account) => {
33
- if (node.kind === "predicate") {
34
- if ((node.field === "text" || node.field === "exact") && (node.operator === "term" || node.operator === "phrase"))
35
- return node.value === "" ? [{ words: [] }] : [{ words: [node.value] }];
31
+ // The server reads words, one chat, one sender and a date range; the strict local query decides the rest.
32
+ const serverReads = (account) => ({
33
+ fields: {
34
+ text: ["term", "phrase"],
35
+ exact: ["term", "phrase"],
36
+ chat: ["term", "phrase"],
37
+ from: ["term", "phrase"],
38
+ date: ["term", "range"],
39
+ },
40
+ maxCalls: SERVER_BOUNDS.maxCalls,
41
+ all: { words: [] },
42
+ leaf: (node) => {
43
+ if (node.field === "text" || node.field === "exact")
44
+ return { words: node.value === "" ? [] : [node.value] };
36
45
  const { chat, sender, date } = node.resolution ?? {};
46
+ // Another account's chat holds nothing this account's server can return.
37
47
  if (chat)
38
- return sameAccount(chat.account, account) ? [{ words: [], chat: chat.chatId }] : [];
48
+ return sameAccount(chat.account, account) ? { words: [], chat: chat.chatId } : undefined;
39
49
  if (sender?.provider === account.provider)
40
- return [{ words: [], from: sender.id }];
41
- if (date)
42
- return [
43
- {
44
- words: [],
45
- ...(date.lower === undefined ? {} : { minDate: date.lower_inclusive ? date.lower : date.lower + 1 }),
46
- ...(date.upper === undefined ? {} : { maxDate: date.upper_inclusive ? date.upper : date.upper - 1 }),
47
- },
48
- ];
49
- return [{ words: [] }];
50
- }
51
- const must = node.clauses.filter(({ occur }) => occur === "must");
52
- if (must.length)
53
- return must.reduce((product, { node }) => product.flatMap((one) => branchesOf(node, account).flatMap((other) => merge(one, other) ?? [])), [{ words: [] }]);
54
- const should = node.clauses.filter(({ occur }) => occur === "should");
55
- return should.length ? should.flatMap(({ node }) => branchesOf(node, account)) : [{ words: [] }];
56
- };
50
+ return { words: [], from: sender.id };
51
+ if (date) {
52
+ const { from, to } = windowOf(date);
53
+ return {
54
+ words: [],
55
+ ...(from === undefined ? {} : { minDate: from }),
56
+ ...(to === undefined ? {} : { maxDate: to }),
57
+ };
58
+ }
59
+ // `from:me` and the like: nothing the server filters, so the call is not narrowed.
60
+ return { words: [] };
61
+ },
62
+ both: merge,
63
+ sends: ({ words }) => words.length > 0,
64
+ });
57
65
  const asQuery = ({ words, from, ...rest }) => ({
58
66
  text: words.join(" "),
59
67
  ...rest,
@@ -123,15 +131,12 @@ export const searchServer = async (deps, request) => {
123
131
  : { words: [] };
124
132
  if (!scoped)
125
133
  return skip("other_accounts");
126
- const all = branchesOf(execution.root, account).flatMap((branch) => merge(scoped, branch) ?? []);
127
- const unique = [
128
- ...new Map(all.filter(({ words }) => words.length).map((branch) => [JSON.stringify(branch), branch])).values(),
129
- ];
130
- if (!unique.length)
134
+ const { calls, complete } = serviceCallsOf(execution.root, serverReads(account), scoped);
135
+ if (!calls.length)
131
136
  return skip("no_words");
132
- if (deps.messenger.serverSearch === "chat" && unique.some(({ chat }) => chat === undefined))
137
+ if (deps.messenger.serverSearch === "chat" && calls.some(({ chat }) => chat === undefined))
133
138
  return skip("needs_chat");
134
- if (unique.length > SERVER_BOUNDS.maxCalls)
139
+ if (!complete)
135
140
  report.complete = false;
136
141
  const controller = new AbortController();
137
142
  const timer = setTimeout(() => controller.abort(), timeMs);
@@ -141,7 +146,6 @@ export const searchServer = async (deps, request) => {
141
146
  resolve(BOUND);
142
147
  stop.addEventListener("abort", () => resolve(BOUND), { once: true });
143
148
  });
144
- const calls = unique.slice(0, SERVER_BOUNDS.maxCalls);
145
149
  const pending = new Set(calls);
146
150
  const found = [];
147
151
  let open = true;
@@ -6,6 +6,8 @@ export type TaskCategoryEdits = Record<string, string | null>;
6
6
  * A store moved by `MESSAGING_STORE` (tests, `bin/tg`) reads the one beside it, so it never reads the owner's.
7
7
  */
8
8
  export declare const sharedConfigPath: (store: string, env?: NodeJS.ProcessEnv) => string;
9
+ /** Beside the file, so the owner finds it; a second repair in the same millisecond never replaces the first. */
10
+ export declare const backupPathFor: (file: string) => string;
9
11
  /** The `task_categories` section, or `undefined` when the file or the section is missing. */
10
12
  export declare const readTaskCategoryEdits: (path: string) => TaskCategoryEdits | undefined;
11
13
  /** `base` with the edits applied: a text sets the category (a new one goes before `other`), `null` drops it. */
@@ -1,6 +1,7 @@
1
- import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join, resolve } from "node:path";
3
- import { CliError, resolvePaths } from "@wirecat/cli-base";
3
+ import { CliError, resolvePaths, writeSecurely } from "@wirecat/cli-base";
4
+ import { explainBrokenJson, repairConfigText, SAFE_REPAIRS } from "../domain/config-repair.js";
4
5
  import { DEFAULT_TASK_CATEGORIES, FALLBACK_CATEGORY, taskCategoryValue, withTaskCategory, } from "../domain/task-categories.js";
5
6
  import { storePath } from "./path.js";
6
7
  const SECTION = "task_categories";
@@ -16,10 +17,40 @@ export const sharedConfigPath = (store, env = process.env) => {
16
17
  ? join(paths.config, "config.json")
17
18
  : join(dirname(store), "config.json");
18
19
  };
20
+ /** Beside the file, so the owner finds it; a second repair in the same millisecond never replaces the first. */
21
+ export const backupPathFor = (file) => {
22
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
23
+ let path = `${file}.bak-${stamp}`;
24
+ for (let n = 2; existsSync(path); n++)
25
+ path = `${file}.bak-${stamp}-${n}`;
26
+ return path;
27
+ };
28
+ /**
29
+ * A slip with one reading (a byte-order mark, a comment, a trailing or a missing comma between lines) is mended in
30
+ * the file, the old one kept beside it (owner, 2026-11-14); anything else is refused with its line and likely fix.
31
+ */
32
+ const mended = (path, bytes) => {
33
+ const text = bytes.toString("utf8");
34
+ const result = repairConfigText(text);
35
+ if (result.state === "repaired" && result.fixes.every((one) => SAFE_REPAIRS.has(one.kind))) {
36
+ try {
37
+ writeSecurely(backupPathFor(path), bytes, statSync(path).mode & 0o777);
38
+ writeSecurely(path, result.text, 0o600);
39
+ }
40
+ catch {
41
+ // A file this run cannot write is still read as mended; the next run that can write mends it.
42
+ }
43
+ return JSON.parse(result.text);
44
+ }
45
+ throw new CliError("configuration_error", `${path} is not valid JSON, ${explainBrokenJson(text, result)}`, {
46
+ reason: "config.invalid_json",
47
+ file: path,
48
+ });
49
+ };
19
50
  const readJson = (path) => {
20
- let text;
51
+ let bytes;
21
52
  try {
22
- text = readFileSync(path, "utf8");
53
+ bytes = readFileSync(path);
23
54
  }
24
55
  catch (error) {
25
56
  if (error.code === "ENOENT")
@@ -28,11 +59,10 @@ const readJson = (path) => {
28
59
  }
29
60
  let parsed;
30
61
  try {
31
- // Windows editors save JSON with a byte-order mark, which JSON.parse refuses.
32
- parsed = JSON.parse(text.replace(/^\uFEFF/u, ""));
62
+ parsed = JSON.parse(bytes.toString("utf8"));
33
63
  }
34
- catch (error) {
35
- throw new CliError("configuration_error", `${path} is not valid JSON: ${error.message}`);
64
+ catch {
65
+ parsed = mended(path, bytes);
36
66
  }
37
67
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
38
68
  throw new CliError("configuration_error", `${path} must hold a JSON object`);
@@ -430,6 +430,7 @@ const MEETING_COLUMNS = {
430
430
  ended_at: { type: "time", sql: "ended_at" },
431
431
  duration_ms: { type: "num", sql: "duration_ms" },
432
432
  participants_count: { type: "num", sql: "participants_count" },
433
+ provider_id: { type: "kw", sql: "external_id" },
433
434
  created_at: { type: "time", sql: "created_at" },
434
435
  updated_at: { type: "time", sql: "updated_at" },
435
436
  };
@@ -452,8 +453,15 @@ const filtered = (filter = {}) => {
452
453
  add("started_at >= ?", filter.since);
453
454
  if (filter.until !== undefined)
454
455
  add("started_at <= ?", filter.until);
456
+ // One bound list: an OR of ids per meeting grows past SQLite's expression depth at about a thousand.
457
+ if (filter.ids !== undefined)
458
+ add("id IN (SELECT value FROM json_each(?))", JSON.stringify(filter.ids));
455
459
  if (filter.query !== undefined) {
456
- const compiled = queryFilter(filter.query, MEETING_COLUMNS, { command: "meetings list" });
460
+ const compiled = queryFilter(filter.query, MEETING_COLUMNS, {
461
+ command: "meetings list",
462
+ ...(filter.timezone === undefined ? {} : { zone: filter.timezone }),
463
+ ...(filter.now === undefined ? {} : { now: filter.now }),
464
+ });
457
465
  where.push(`(${compiled.sql})`);
458
466
  params.push(...compiled.params);
459
467
  }
@@ -659,6 +667,12 @@ export const meetingStoreOver = (context) => {
659
667
  async meeting(id) {
660
668
  return details(database, id);
661
669
  },
670
+ async meetingByExternalId(accountId, externalId) {
671
+ const row = database
672
+ .prepare("SELECT id FROM meetings WHERE account_id = ? AND external_id = ?")
673
+ .get(accountId, externalId);
674
+ return row ? details(database, Number(row.id)) : null;
675
+ },
662
676
  async participants(query, accountId) {
663
677
  return participants(database, query, accountId);
664
678
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.658.0",
3
+ "version": "0.660.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",