@wirecat/cli-core 0.609.0 → 0.611.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 (52) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/dist/cli/messenger/search-answers.js +12 -0
  3. package/dist/cli/search-left-out.d.ts +1 -0
  4. package/dist/cli/search-left-out.js +2 -0
  5. package/dist/domain/business.d.ts +3 -0
  6. package/dist/domain/business.js +2 -0
  7. package/dist/entities/hit.d.ts +13 -2
  8. package/dist/entities/hit.js +10 -2
  9. package/dist/entities/index.d.ts +7 -1
  10. package/dist/errors/reasons.js +4 -0
  11. package/dist/meetings/mcp/index.d.ts +15 -15
  12. package/dist/search/account-list.d.ts +3 -2
  13. package/dist/search/account-list.js +5 -4
  14. package/dist/services/link-scorers/chat-senders.d.ts +2 -1
  15. package/dist/services/link-scorers/chat-senders.js +13 -4
  16. package/dist/services/link-scorers/types.d.ts +1 -1
  17. package/dist/services/metadata.d.ts +1 -1
  18. package/dist/services/proposals/kinds/relationship.js +1 -0
  19. package/dist/services/proposals/registry.js +3 -1
  20. package/dist/services/proposals/types.d.ts +2 -0
  21. package/dist/services/search-all-business.d.ts +18 -0
  22. package/dist/services/search-all-business.js +38 -0
  23. package/dist/services/search-all-meetings.d.ts +1 -1
  24. package/dist/services/search-all-meetings.js +7 -2
  25. package/dist/services/search-all.d.ts +10 -6
  26. package/dist/services/search-all.js +26 -10
  27. package/dist/store/exports.d.ts +2 -0
  28. package/dist/store/exports.js +2 -0
  29. package/dist/store/index.d.ts +4 -1
  30. package/dist/store/index.js +2 -0
  31. package/dist/store/sqlite/business-search.d.ts +44 -0
  32. package/dist/store/sqlite/business-search.js +141 -0
  33. package/dist/store/sqlite/finance.d.ts +12 -0
  34. package/dist/store/sqlite/finance.js +38 -2
  35. package/dist/store/sqlite/involvement-queue.d.ts +2 -7
  36. package/dist/store/sqlite/involvement-queue.js +11 -14
  37. package/dist/store/sqlite/money-lines.d.ts +12 -1
  38. package/dist/store/sqlite/money-lines.js +50 -4
  39. package/dist/store/sqlite/orders.js +5 -25
  40. package/dist/store/sqlite/proposed-actions.d.ts +2 -0
  41. package/dist/store/sqlite/proposed-actions.js +4 -3
  42. package/dist/store/sqlite/records.d.ts +21 -0
  43. package/dist/store/sqlite/records.js +74 -13
  44. package/dist/store/sqlite/ref-summaries.d.ts +3 -1
  45. package/dist/store/sqlite/ref-summaries.js +4 -1
  46. package/dist/store/sqlite/reported-relations.d.ts +1 -0
  47. package/dist/store/sqlite/reported-relations.js +1 -1
  48. package/dist/store/store.d.ts +2 -0
  49. package/dist/store/store.js +4 -4
  50. package/dist/terminal/prompt.d.ts +4 -0
  51. package/dist/terminal/prompt.js +21 -2
  52. package/package.json +3 -3
@@ -25,17 +25,24 @@ export interface PricedLine {
25
25
  amount: number;
26
26
  productId: number | null;
27
27
  }
28
- /** Where each parent keeps its lines, and the prefix of the reasons its line errors carry. */
28
+ export declare const MAX_LINES = 500;
29
+ /** Where each parent keeps its lines, and the reasons its line errors carry. */
29
30
  declare const PARENTS: {
30
31
  readonly invoice: {
32
+ readonly parents: "invoices";
31
33
  readonly table: "invoice_lines";
32
34
  readonly column: "invoice_id";
33
35
  readonly reasons: "finance";
36
+ readonly full: "finance.lines";
37
+ readonly instead: "reject or void the invoice instead";
34
38
  };
35
39
  readonly order: {
40
+ readonly parents: "orders";
36
41
  readonly table: "order_lines";
37
42
  readonly column: "order_id";
38
43
  readonly reasons: "order";
44
+ readonly full: "order.field";
45
+ readonly instead: "reject or cancel the order instead";
39
46
  };
40
47
  };
41
48
  export type LineParent = keyof typeof PARENTS;
@@ -44,5 +51,9 @@ export declare const moneyLinesOver: ({ database }: StoreContext) => {
44
51
  linesOf: (parent: LineParent, lines: MoneyLineInput[], currency: string) => PricedLine[];
45
52
  insertLines: (parent: LineParent, id: number, lines: PricedLine[], from: number, at: number) => void;
46
53
  shownLines: (parent: LineParent, id: number, currency: string) => MoneyLine[];
54
+ appendLine: (parent: LineParent, id: number, line: PricedLine, at: number) => void;
55
+ deleteLine: (parent: LineParent, id: number, position: number) => void;
56
+ sumOf: (parent: LineParent, id: number) => number;
57
+ retotal: (parent: LineParent, id: number, at: number) => void;
47
58
  };
48
59
  export {};
@@ -1,10 +1,26 @@
1
+ import { CliError } from "@wirecat/cli-base";
1
2
  import { formatDecimal, lineUnits, minorUnits, moneyLabel, quantityOf, scaleOf } from "../../domain/money.js";
2
3
  import { requiredThing } from "./notes.js";
3
4
  import { refuse, text } from "./reviewed.js";
4
- /** Where each parent keeps its lines, and the prefix of the reasons its line errors carry. */
5
+ export const MAX_LINES = 500;
6
+ /** Where each parent keeps its lines, and the reasons its line errors carry. */
5
7
  const PARENTS = {
6
- invoice: { table: "invoice_lines", column: "invoice_id", reasons: "finance" },
7
- order: { table: "order_lines", column: "order_id", reasons: "order" },
8
+ invoice: {
9
+ parents: "invoices",
10
+ table: "invoice_lines",
11
+ column: "invoice_id",
12
+ reasons: "finance",
13
+ full: "finance.lines",
14
+ instead: "reject or void the invoice instead",
15
+ },
16
+ order: {
17
+ parents: "orders",
18
+ table: "order_lines",
19
+ column: "order_id",
20
+ reasons: "order",
21
+ full: "order.field",
22
+ instead: "reject or cancel the order instead",
23
+ },
8
24
  };
9
25
  /** Invoice and order lines: quantity × unit price, in the parent's currency, a product's name and price copied. */
10
26
  export const moneyLinesOver = ({ database }) => {
@@ -72,5 +88,35 @@ export const moneyLinesOver = ({ database }) => {
72
88
  product: line.catalog_item_id == null ? null : `product:${line.catalog_item_id}`,
73
89
  }));
74
90
  };
75
- return { linesOf, insertLines, shownLines };
91
+ /** Writes a line after the last one; the caller retotals the parent in the same write. */
92
+ const appendLine = (parent, id, line, at) => {
93
+ const { table, column, full } = PARENTS[parent];
94
+ const last = Number(database.prepare(`SELECT coalesce(max(position), 0) AS n FROM ${table} WHERE ${column} = ?`).get(id)?.n);
95
+ if (last >= MAX_LINES)
96
+ refuse(`an ${parent} has at most ${MAX_LINES} lines`, full);
97
+ insertLines(parent, id, [line], last + 1, at);
98
+ };
99
+ /** Removes one line, never the last; the caller retotals the parent in the same write. */
100
+ const deleteLine = (parent, id, position) => {
101
+ const { table, column, reasons, instead } = PARENTS[parent];
102
+ const lines = Number(database.prepare(`SELECT count(*) AS n FROM ${table} WHERE ${column} = ?`).get(id)?.n);
103
+ const gone = database.prepare(`DELETE FROM ${table} WHERE ${column} = ? AND position = ?`).run(id, position);
104
+ if (gone.changes === 0)
105
+ throw new CliError("not_found", `${parent}:${id} has no line ${position}`, { reason: `${reasons}.no-line` });
106
+ if (lines === 1)
107
+ refuse(`line ${position} is the last of ${parent}:${id}; ${instead}`, `${reasons}.line`);
108
+ };
109
+ const sumOf = (parent, id) => {
110
+ const { table, column } = PARENTS[parent];
111
+ return Number(database.prepare(`SELECT coalesce(sum(amount), 0) AS n FROM ${table} WHERE ${column} = ?`).get(id)?.n);
112
+ };
113
+ /** The parent's total follows its lines: orders' trigger checks the sum when the order changes. */
114
+ const retotal = (parent, id, at) => {
115
+ const { parents, table, column } = PARENTS[parent];
116
+ database
117
+ .prepare(`UPDATE ${parents} SET total = coalesce((SELECT sum(amount) FROM ${table} WHERE ${column} = ?), total), ` +
118
+ "updated_at = ? WHERE id = ?")
119
+ .run(id, at, id);
120
+ };
121
+ return { linesOf, insertLines, shownLines, appendLine, deleteLine, sumOf, retotal };
76
122
  };
@@ -7,11 +7,10 @@ import { ORDER_PURPOSES, ORDER_STATUSES, orderTitle } from "../../domain/orders.
7
7
  import { fold } from "../normalize.js";
8
8
  import { ownerPerson, proposedBySql } from "./actors.js";
9
9
  import { projectId } from "./memories.js";
10
- import { moneyLinesOver } from "./money-lines.js";
10
+ import { MAX_LINES, moneyLinesOver } from "./money-lines.js";
11
11
  import { requiredThing } from "./notes.js";
12
12
  import { isoDate, limitOf, oneOf, refuse, reviewedRowsOver, text, } from "./reviewed.js";
13
13
  import { write } from "./transaction.js";
14
- const MAX_LINES = 500;
15
14
  const ORDERS = "SELECT o.*, b.name AS author_name, b.kind AS author_kind FROM orders o " +
16
15
  "LEFT JOIN bots b ON o.author_type = 'bot' AND b.id = o.author_id";
17
16
  export const orderOperationsOver = (context) => {
@@ -57,13 +56,6 @@ export const orderOperationsOver = (context) => {
57
56
  ...orderOf(row),
58
57
  lines: row.currency == null ? [] : moneyLines.shownLines("order", Number(row.id), String(row.currency)),
59
58
  });
60
- /** The order's total follows its lines in the same write: the trigger checks the sum when the order changes. */
61
- const retotal = (orderId) => {
62
- database
63
- .prepare("UPDATE orders SET total = coalesce((SELECT sum(amount) FROM order_lines WHERE order_id = ?), total), " +
64
- "updated_at = ? WHERE id = ?")
65
- .run(orderId, now(), orderId);
66
- };
67
59
  const mayChangeLines = (row, by) => {
68
60
  mayChangeParts(row, by, `only the owner changes the lines of order:${row.id}; a bot changes only an order it proposed that is still proposed`, "order.owner-only");
69
61
  if (row.review === "rejected" || row.deleted_at != null)
@@ -208,13 +200,8 @@ export const orderOperationsOver = (context) => {
208
200
  refuse(`order:${row.id} has no currency; a line needs one`, "order.total");
209
201
  const [priced] = moneyLines.linesOf("order", [line], String(row.currency));
210
202
  write(database, () => {
211
- const last = Number(database
212
- .prepare("SELECT coalesce(max(position), 0) AS n FROM order_lines WHERE order_id = ?")
213
- .get(Number(row.id))?.n);
214
- if (last >= MAX_LINES)
215
- refuse(`an order has at most ${MAX_LINES} lines`, "order.field");
216
- moneyLines.insertLines("order", Number(row.id), [priced], last + 1, now());
217
- retotal(Number(row.id));
203
+ moneyLines.appendLine("order", Number(row.id), priced, now());
204
+ moneyLines.retotal("order", Number(row.id), now());
218
205
  });
219
206
  return detailOf(rowOf(`order:${row.id}`));
220
207
  },
@@ -222,15 +209,8 @@ export const orderOperationsOver = (context) => {
222
209
  const row = rowOf(reference);
223
210
  mayChangeLines(row, by);
224
211
  write(database, () => {
225
- const lines = Number(database.prepare("SELECT count(*) AS n FROM order_lines WHERE order_id = ?").get(Number(row.id))?.n);
226
- const gone = database
227
- .prepare("DELETE FROM order_lines WHERE order_id = ? AND position = ?")
228
- .run(Number(row.id), position);
229
- if (gone.changes === 0)
230
- throw new CliError("not_found", `order:${row.id} has no line ${position}`, { reason: "order.no-line" });
231
- if (lines === 1)
232
- refuse(`line ${position} is the last of order:${row.id}; reject or cancel the order instead`, "order.line");
233
- retotal(Number(row.id));
212
+ moneyLines.deleteLine("order", Number(row.id), position);
213
+ moneyLines.retotal("order", Number(row.id), now());
234
214
  });
235
215
  return detailOf(rowOf(`order:${row.id}`));
236
216
  },
@@ -61,6 +61,8 @@ export interface ProposedActionsStore {
61
61
  proposedBy?: ProposedByFilter;
62
62
  /** A `project:<id>` the action targets or its payload names as `to`, `from` or `project`. */
63
63
  project?: string;
64
+ /** A reference the payload's `evidence` holds. */
65
+ evidence?: string;
64
66
  }): Promise<ProposedAction[]>;
65
67
  /** `result` records what the approval made, such as the task it became. `by` must be allowed to decide it. */
66
68
  approve(id: string, by: Decider, result?: unknown): Promise<ProposedAction>;
@@ -131,7 +131,7 @@ export const proposalOperationsOver = (context) => {
131
131
  .prepare(`${NAMED} WHERE p.status = 'proposed' ORDER BY p.created_at, p.id LIMIT ?`)
132
132
  .all(Math.min(Math.max(limit, 1), 500))
133
133
  .map(actionOf),
134
- list: ({ status, limit = 100, kinds, except, proposedBy, project } = {}) => {
134
+ list: ({ status, limit = 100, kinds, except, proposedBy, project, evidence } = {}) => {
135
135
  if (status !== undefined && !PROPOSAL_STATUSES.includes(status))
136
136
  throw new CliError("validation_error", `a status is one of ${PROPOSAL_STATUSES.join(", ")}`);
137
137
  const by = proposedBySql("p.proposed_by_type", "p.proposed_by_id", proposedBy);
@@ -139,8 +139,9 @@ export const proposalOperationsOver = (context) => {
139
139
  .prepare(`${NAMED} WHERE (? IS NULL OR ${STATUS} = ?) AND (? IS NULL OR p.kind IN (SELECT value FROM json_each(?))) ` +
140
140
  "AND p.kind NOT IN (SELECT value FROM json_each(?)) AND (? IS NULL OR (p.target_type = 'project' AND " +
141
141
  "'project:' || p.target_id = ?) OR json_extract(p.payload, '$.to') = ? OR json_extract(p.payload, '$.from') = ? " +
142
- `OR json_extract(p.payload, '$.project') = ?) AND ${by.sql} ORDER BY p.created_at DESC, p.id DESC LIMIT ?`)
143
- .all(status ?? null, status ?? null, kinds === undefined ? null : 1, JSON.stringify(kinds ?? []), JSON.stringify(except ?? []), ...Array(5).fill(project ?? null), ...by.params, Math.min(Math.max(limit, 1), 500))
142
+ `OR json_extract(p.payload, '$.project') = ?) AND (? IS NULL OR EXISTS (SELECT 1 FROM json_each(p.payload, '$.evidence') ` +
143
+ `WHERE value = ?)) AND ${by.sql} ORDER BY p.created_at DESC, p.id DESC LIMIT ?`)
144
+ .all(status ?? null, status ?? null, kinds === undefined ? null : 1, JSON.stringify(kinds ?? []), JSON.stringify(except ?? []), ...Array(5).fill(project ?? null), evidence ?? null, evidence ?? null, ...by.params, Math.min(Math.max(limit, 1), 500))
144
145
  .map(actionOf);
145
146
  },
146
147
  approve: (id, result, by) => decide(id, "approved", result, by),
@@ -44,6 +44,13 @@ export interface MappedRecord extends SourceRecord {
44
44
  /** Records that waited on it whose entity was still refused. */
45
45
  errors: IngestError[];
46
46
  }
47
+ export interface IncomingRelation {
48
+ /** The live record whose relation points at the target. */
49
+ record: RecordKey;
50
+ role: string;
51
+ as: string | null;
52
+ amount: string | null;
53
+ }
47
54
  export interface MatchRun {
48
55
  linked: number;
49
56
  created: number;
@@ -74,9 +81,23 @@ export interface RecordStore {
74
81
  /** Only persons, organizations and projects whose identifiers point at more than one entity. */
75
82
  unmatched?: boolean;
76
83
  flagged?: boolean;
84
+ /** A ref such as `person:4`: the records mapped to that entity. */
85
+ entity?: string;
86
+ batch?: string;
87
+ /** `true`: only deleted records; `false`: only live ones; left out, both. */
88
+ deleted?: boolean;
77
89
  /** 1–500, 100 by default. */
78
90
  limit?: number;
79
91
  }): Promise<SourceRecord[]>;
92
+ /**
93
+ * The relations of live records that point at a record of the account, or at an entity: by its ref, or through a
94
+ * record mapped to it. An entity's are read across every account, and each names its own. Oldest relation first.
95
+ */
96
+ incoming(target: RecordKey | {
97
+ entity: string;
98
+ }, options?: {
99
+ limit?: number;
100
+ }): Promise<IncomingRelation[]>;
80
101
  /**
81
102
  * The owner says which entity a record is: `person:4` for a payer a sheet names. Never done by name. Records that
82
103
  * waited for it get their entity, as proposals. A record whose entity the import made moves, with every record of
@@ -11,6 +11,10 @@ import { read, rehearse, write } from "./transaction.js";
11
11
  export { waitingPointer } from "./record-run.js";
12
12
  const LIMIT = 1000;
13
13
  const iso = (value) => new Date(Number(value)).toISOString();
14
+ const checkLimit = (limit) => {
15
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
16
+ throw new CliError("validation_error", "a record list takes 1–500 items");
17
+ };
14
18
  const IDENTITY_SQL = IDENTITY_TYPES.map((type) => `'${type}'`).join(", ");
15
19
  export const recordStoreOver = (context) => {
16
20
  const { database } = context;
@@ -73,21 +77,78 @@ export const recordStoreOver = (context) => {
73
77
  const row = rowOf(key);
74
78
  return row ? sourceRecordOf(row) : undefined;
75
79
  }),
76
- list: async ({ provider, account, type, waiting, unmatched, flagged, limit = 100 }) => {
77
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 500)
78
- throw new CliError("validation_error", "a record list takes 1–500 items");
80
+ list: async ({ provider, account, type, waiting, unmatched, flagged, entity, batch, deleted, limit = 100 }) => {
81
+ checkLimit(limit);
79
82
  return read(database, () => {
80
- if (findAccountPk(context, { provider, account }) === undefined)
83
+ const accountId = findAccountPk(context, { provider, account });
84
+ if (accountId === undefined)
81
85
  return [];
82
- const rows = database
83
- .prepare(`${SELECT}WHERE a.provider = ? AND a.external_id = ? AND (? IS NULL OR r.type = ?) ` +
84
- "AND (? IS NULL OR (r.entity_id IS NULL AND r.deleted_at IS NULL AND r.type NOT LIKE 'custom:%' " +
85
- `AND r.type NOT IN (${IDENTITY_SQL}))) ` +
86
- `AND (? IS NULL OR (r.entity_id IS NULL AND r.deleted_at IS NULL AND r.type IN (${IDENTITY_SQL}))) ` +
87
- "AND (? IS NULL OR (r.entity_id IS NOT NULL AND (r.deleted_at IS NOT NULL " +
88
- "OR r.projected_fingerprint IS NOT r.fingerprint))) ORDER BY r.updated_at DESC, r.id DESC LIMIT ?")
89
- .all(provider, account, type ?? null, type ?? null, waiting ? 1 : null, unmatched ? 1 : null, flagged ? 1 : null, limit);
90
- return rows.map(sourceRecordOf);
86
+ const where = ["r.account_id = ?"];
87
+ const params = [accountId];
88
+ const and = (condition, ...values) => {
89
+ where.push(condition);
90
+ for (const value of values)
91
+ params.push(value);
92
+ };
93
+ if (type !== undefined)
94
+ and("r.type = ?", type);
95
+ if (waiting)
96
+ and("r.entity_id IS NULL AND r.deleted_at IS NULL AND r.type NOT LIKE 'custom:%' " +
97
+ `AND r.type NOT IN (${IDENTITY_SQL})`);
98
+ if (unmatched)
99
+ and(`r.entity_id IS NULL AND r.deleted_at IS NULL AND r.type IN (${IDENTITY_SQL})`);
100
+ if (flagged)
101
+ and("r.entity_id IS NOT NULL AND (r.deleted_at IS NOT NULL OR r.projected_fingerprint IS NOT r.fingerprint)");
102
+ if (entity !== undefined) {
103
+ const thing = requiredThing(database, entity, "the entity");
104
+ and("r.entity_type = ? AND r.entity_id = ?", thing.type, thing.id);
105
+ }
106
+ if (batch !== undefined)
107
+ and("r.batch_id = ?", batch);
108
+ if (deleted !== undefined)
109
+ and(`r.deleted_at IS ${deleted ? "NOT " : ""}NULL`);
110
+ return database
111
+ .prepare(`${SELECT}WHERE ${where.join(" AND ")} ORDER BY r.updated_at DESC, r.id DESC LIMIT ?`)
112
+ .all(...params, limit)
113
+ .map(sourceRecordOf);
114
+ });
115
+ },
116
+ incoming: async (target, { limit = 100 } = {}) => {
117
+ checkLimit(limit);
118
+ return read(database, () => {
119
+ let pointing;
120
+ if ("externalId" in target) {
121
+ const row = rowOf(target);
122
+ if (!row)
123
+ return [];
124
+ pointing = { sql: "SELECT id FROM record_relations WHERE target_id = ?", params: [Number(row.id)] };
125
+ }
126
+ else {
127
+ const thing = requiredThing(database, target.entity, "the entity");
128
+ pointing = {
129
+ sql: "SELECT id FROM record_relations WHERE target_type = ? AND target_external_id = ? UNION " +
130
+ "SELECT rr.id FROM record_relations rr JOIN records t ON t.id = rr.target_id " +
131
+ "WHERE t.entity_type = ? AND t.entity_id = ?",
132
+ params: ["ref", `${thing.type}:${thing.id}`, thing.type, thing.id],
133
+ };
134
+ }
135
+ return database
136
+ .prepare("SELECT rr.role, rr.as_role, rr.amount, r.type, r.external_id, a.provider, a.external_id AS account " +
137
+ "FROM record_relations rr JOIN records r ON r.id = rr.record_id JOIN accounts a ON a.id = r.account_id " +
138
+ `WHERE rr.id IN (${pointing.sql}) AND r.deleted_at IS NULL AND rr.role NOT LIKE 'fields.%' ` +
139
+ "ORDER BY rr.id LIMIT ?")
140
+ .all(...pointing.params, limit)
141
+ .map((row) => ({
142
+ record: {
143
+ provider: String(row.provider),
144
+ account: String(row.account),
145
+ type: String(row.type),
146
+ externalId: String(row.external_id),
147
+ },
148
+ role: String(row.role),
149
+ as: row.as_role == null ? null : String(row.as_role),
150
+ amount: row.amount == null ? null : String(row.amount),
151
+ }));
91
152
  });
92
153
  },
93
154
  map: async (key, entity, by) => {
@@ -1,5 +1,6 @@
1
- import { type RefSummary } from "../../domain/ref-summaries.js";
1
+ import { type RefSummary, type RefsStore } from "../../domain/ref-summaries.js";
2
2
  import type { CacheDatabase } from "../driver.js";
3
+ import type { StoreContext } from "./open.js";
3
4
  /** A summary plus what an evidence reader shows beside it; `summaries` drops the extra fields. */
4
5
  export interface RefRead extends RefSummary {
5
6
  sender: string | null;
@@ -16,3 +17,4 @@ export interface RefReadOptions {
16
17
  }
17
18
  export declare const refReadsOf: (database: CacheDatabase, texts: readonly string[], { excerpt, now }?: RefReadOptions) => Map<string, RefRead>;
18
19
  export declare const refSummariesOf: (database: CacheDatabase, texts: readonly string[], options?: RefReadOptions) => Map<string, RefSummary>;
20
+ export declare const refsStoreOver: (context: StoreContext) => RefsStore;
@@ -3,7 +3,7 @@ import { dealLine } from "../../domain/deals.js";
3
3
  import { invoiceLine, paymentLine } from "../../domain/finance.js";
4
4
  import { orderLine } from "../../domain/orders.js";
5
5
  import { filesAccountSql, providerLabel, providerNamed } from "../../domain/providers.js";
6
- import { oneLine } from "../../domain/ref-summaries.js";
6
+ import { oneLine, } from "../../domain/ref-summaries.js";
7
7
  import { formatReference, parseReference } from "../../domain/references.js";
8
8
  const EXCERPT_CHARS = 280;
9
9
  const TITLE_CHARS = 120;
@@ -485,3 +485,6 @@ export const refReadsOf = (database, texts, { excerpt = false, now = Date.now()
485
485
  };
486
486
  const summaryOf = ({ sender, excerpt, ...summary }, withExcerpt) => withExcerpt ? { ...summary, excerpt } : summary;
487
487
  export const refSummariesOf = (database, texts, options = {}) => new Map([...refReadsOf(database, texts, options)].map(([text, read]) => [text, summaryOf(read, options.excerpt === true)]));
488
+ export const refsStoreOver = (context) => ({
489
+ summaries: async (texts, options) => refSummariesOf(context.database, texts, { ...options, now: context.now() }),
490
+ });
@@ -58,6 +58,7 @@ export interface RelationsStore {
58
58
  */
59
59
  syncReported(key: AccountKey, relationships: ReportedRelation[], scope: ReportedScope, options?: ReportedOptions): Promise<ReportedSync>;
60
60
  }
61
+ export declare const KEYED = "kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL";
61
62
  /** The call, inside a transaction the caller holds: a CRM page saves its rows and their relationships together. */
62
63
  export declare const syncReportedIn: (context: StoreContext, key: AccountKey, relationships: ReportedRelation[], scope: ReportedScope, { source, by }?: ReportedOptions) => ReportedSync;
63
64
  export declare const relationsStoreOver: (context: StoreContext) => RelationsStore;
@@ -9,7 +9,7 @@ import { referenceOfThing, thingOf } from "./things.js";
9
9
  import { write } from "./transaction.js";
10
10
  // links_relationship_key's WHERE, word for word: without it SQLite cannot use that partial index, picks
11
11
  // (to_type, to_id) and reads every link of a busy end, such as a deal owner's, for each relationship (#2623).
12
- const KEYED = "kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL";
12
+ export const KEYED = "kind IN ('member-of', 'related-to', 'reports-to', 'customer-of', 'partner-of') AND to_id IS NOT NULL";
13
13
  const metadataOf = (relation) => relation.metadata && Object.keys(relation.metadata).length ? JSON.stringify(relation.metadata) : null;
14
14
  /** The call, inside a transaction the caller holds: a CRM page saves its rows and their relationships together. */
15
15
  export const syncReportedIn = (context, key, relationships, scope, { source = "import", by = { bot: key.provider, kind: "rule" } } = {}) => {
@@ -22,6 +22,7 @@ import { type SearchesStore } from "./searches.js";
22
22
  import { type AgentActionsStore } from "./sqlite/agent-actions.js";
23
23
  import { type BotUpdateStore } from "./sqlite/bot-updates.js";
24
24
  import { type ContractsStore } from "./sqlite/business-contracts.js";
25
+ import { type BusinessSearchStore } from "./sqlite/business-search.js";
25
26
  import { type CatalogStore } from "./sqlite/catalog.js";
26
27
  import { type CrmCopies } from "./sqlite/crm.js";
27
28
  import { type DealsStore } from "./sqlite/deals.js";
@@ -126,6 +127,7 @@ export interface MessageStore {
126
127
  readonly wallets: WalletsStore;
127
128
  /** What statements say moved on the wallets, split by category; an agent's or an import's wait for the owner. */
128
129
  readonly transactions: TransactionsStore;
130
+ readonly business: BusinessSearchStore;
129
131
  /** A CRM account's pipelines, deals, leads, contacts and companies, written as the CRM has them. */
130
132
  readonly crm: CrmCopies;
131
133
  /** Relationships a source account reports, written as a diff that never overrides the owner's. */
@@ -18,6 +18,7 @@ import { agentActionsStoreOver } from "./sqlite/agent-actions.js";
18
18
  import * as attachmentTexts from "./sqlite/attachment-texts.js";
19
19
  import { botUpdateStoreOver } from "./sqlite/bot-updates.js";
20
20
  import { contractsStoreOver } from "./sqlite/business-contracts.js";
21
+ import { businessSearchOver } from "./sqlite/business-search.js";
21
22
  import { eventStoreOver } from "./sqlite/calendar.js";
22
23
  import { catalogStoreOver } from "./sqlite/catalog.js";
23
24
  import { contextEvidenceOver, contextIndexOver, contextRecordsOver } from "./sqlite/context-evidence.js";
@@ -48,7 +49,7 @@ import { productsStoreOver } from "./sqlite/products.js";
48
49
  import { projectAnnotationStoreOver } from "./sqlite/project-transfer/store.js";
49
50
  import { proposedActionsStoreOver } from "./sqlite/proposed-actions.js";
50
51
  import { recordStoreOver } from "./sqlite/records.js";
51
- import { refSummariesOf } from "./sqlite/ref-summaries.js";
52
+ import { refsStoreOver } from "./sqlite/ref-summaries.js";
52
53
  import { relationsStoreOver } from "./sqlite/reported-relations.js";
53
54
  import * as stems from "./sqlite/stems.js";
54
55
  import { subscriptionsStoreOver } from "./sqlite/subscriptions.js";
@@ -120,9 +121,7 @@ const storeOver = (context) => {
120
121
  const meetingFindings = once(() => meetingFindingsStoreOver(context));
121
122
  const evidenceFindings = once(() => evidenceFindingsStoreOver(context));
122
123
  const mailFindings = once(() => mailFindingsStoreOver(context));
123
- const refs = {
124
- summaries: async (texts, options) => refSummariesOf(context.database, texts, { ...options, now: context.now() }),
125
- };
124
+ const refs = refsStoreOver(context);
126
125
  const facts = once(() => factsStoreOver(context));
127
126
  const finance = once(() => financeStoreOver(context));
128
127
  const orders = once(() => ordersStoreOver(context));
@@ -230,6 +229,7 @@ const storeOver = (context) => {
230
229
  return meetingFindings();
231
230
  },
232
231
  refs,
232
+ business: businessSearchOver(context),
233
233
  get evidenceFindings() {
234
234
  return evidenceFindings();
235
235
  },
@@ -1,3 +1,4 @@
1
+ export declare const pasteHint: (platform?: NodeJS.Platform) => string;
1
2
  export interface SecretInput {
2
3
  input?: NodeJS.ReadableStream & {
3
4
  isTTY?: boolean;
@@ -15,6 +16,9 @@ export interface SecretInput {
15
16
  * second copy nobody remembers to delete. Both are avoided by never letting it land anywhere: it
16
17
  * is typed or piped, goes straight to the keyring, and is never echoed.
17
18
  *
19
+ * An empty hidden answer at a terminal is asked again, up to three times, with a line on how to paste; a piped
20
+ * empty answer still comes back empty at once, so a script never waits.
21
+ *
18
22
  * The prompt goes to **stderr**, not stdout, so that `session start --json` still writes one JSON
19
23
  * value and nothing else.
20
24
  */
@@ -2,6 +2,8 @@ import { createInterface } from "node:readline";
2
2
  import { Writable } from "node:stream";
3
3
  import { CliError } from "@wirecat/cli-base";
4
4
  import { bufferedInput, inputPolicy, MAX_SECRET_INPUT } from "../cli/input-policy.js";
5
+ const EMPTY_TRIES = 3;
6
+ export const pasteHint = (platform = process.platform) => `Nothing arrived. To paste in a terminal, use ${platform === "darwin" ? "Cmd+V" : "Ctrl+Shift+V (or right-click → Paste)"}.`;
5
7
  /**
6
8
  * One line of secret, taken without a file and without argv.
7
9
  *
@@ -9,6 +11,9 @@ import { bufferedInput, inputPolicy, MAX_SECRET_INPUT } from "../cli/input-polic
9
11
  * second copy nobody remembers to delete. Both are avoided by never letting it land anywhere: it
10
12
  * is typed or piped, goes straight to the keyring, and is never echoed.
11
13
  *
14
+ * An empty hidden answer at a terminal is asked again, up to three times, with a line on how to paste; a piped
15
+ * empty answer still comes back empty at once, so a script never waits.
16
+ *
12
17
  * The prompt goes to **stderr**, not stdout, so that `session start --json` still writes one JSON
13
18
  * value and nothing else.
14
19
  */
@@ -66,9 +71,23 @@ export const readSecret = async (prompt, { input = process.stdin, output = proce
66
71
  reader.once("SIGINT", cancel);
67
72
  reader.once("close", cancel);
68
73
  signal?.addEventListener("abort", abort, { once: true });
69
- reader.question(prompt, resolve);
70
- muted = !echo;
74
+ // Hidden input shows nothing, so a paste that never landed (Ctrl+V in a Linux terminal) looks like one that did.
75
+ const ask = (tries) => {
76
+ muted = false;
77
+ reader.question(prompt, (line) => {
78
+ if (echo || line.trim() || tries >= EMPTY_TRIES)
79
+ return resolve(line);
80
+ output.write(`\n${pasteHint()}\n`);
81
+ ask(tries + 1);
82
+ });
83
+ muted = !echo;
84
+ };
85
+ ask(1);
71
86
  });
87
+ if (!echo && !answer.trim())
88
+ throw new CliError("validation_error", `nothing arrived after ${EMPTY_TRIES} tries. ${pasteHint()}`, {
89
+ reason: "input.empty",
90
+ });
72
91
  return answer.trim();
73
92
  }
74
93
  finally {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.609.0",
3
+ "version": "0.611.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",
@@ -278,7 +278,7 @@
278
278
  "@types/node": "^22.20.5",
279
279
  "@types/pngjs": "6.0.5",
280
280
  "@vitest/coverage-v8": "^5.0.5",
281
- "@wirecat/cli-base": "0.82.0",
281
+ "@wirecat/cli-base": "0.85.0",
282
282
  "@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
283
283
  "ajv": "8.17.1",
284
284
  "commander": "15.0.0",
@@ -299,7 +299,7 @@
299
299
  },
300
300
  "peerDependencies": {
301
301
  "@napi-rs/canvas": ">=0.1.69 <2",
302
- "@wirecat/cli-base": ">=0.80.7 <0.83.0",
302
+ "@wirecat/cli-base": ">=0.80.7 <0.86.0",
303
303
  "commander": ">=15"
304
304
  },
305
305
  "bin": {