@wirecat/cli-core 0.606.0 → 0.608.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 (209) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/dist/calendar/index.d.ts +1 -0
  3. package/dist/calendar/index.js +1 -0
  4. package/dist/calendar/reads.js +5 -0
  5. package/dist/cli/app-mcp-command.d.ts +6 -2
  6. package/dist/cli/app-mcp-command.js +11 -2
  7. package/dist/cli/csv.d.ts +10 -0
  8. package/dist/cli/csv.js +22 -0
  9. package/dist/cli/early-refusal.d.ts +10 -0
  10. package/dist/cli/early-refusal.js +19 -0
  11. package/dist/cli/index.d.ts +3 -0
  12. package/dist/cli/index.js +3 -0
  13. package/dist/cli/profile-token.d.ts +29 -0
  14. package/dist/cli/profile-token.js +65 -0
  15. package/dist/cli/program.js +4 -2
  16. package/dist/crm/cli/csv.d.ts +23 -0
  17. package/dist/crm/cli/csv.js +135 -0
  18. package/dist/crm/cli/index.d.ts +1 -1
  19. package/dist/crm/cli/index.js +33 -21
  20. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  21. package/dist/crm/cli/pipeline-view.js +36 -0
  22. package/dist/crm/writes.d.ts +6 -4
  23. package/dist/crm/writes.js +17 -13
  24. package/dist/documents.d.ts +2 -0
  25. package/dist/documents.js +2 -0
  26. package/dist/domain/business.d.ts +79 -0
  27. package/dist/domain/business.js +42 -0
  28. package/dist/domain/finance.d.ts +2 -0
  29. package/dist/domain/finance.js +2 -2
  30. package/dist/domain/google-documents.d.ts +2 -0
  31. package/dist/domain/google-documents.js +3 -1
  32. package/dist/domain/money.d.ts +2 -0
  33. package/dist/domain/money.js +11 -3
  34. package/dist/domain/providers.d.ts +36 -1
  35. package/dist/domain/providers.js +69 -7
  36. package/dist/domain/record-fields.d.ts +42 -0
  37. package/dist/domain/record-fields.js +122 -0
  38. package/dist/domain/record-types.d.ts +489 -16
  39. package/dist/domain/record-types.js +374 -7
  40. package/dist/domain/records.d.ts +96 -5
  41. package/dist/domain/records.js +178 -32
  42. package/dist/domain/ref-summaries.js +5 -0
  43. package/dist/domain/references.d.ts +1 -1
  44. package/dist/domain/references.js +5 -0
  45. package/dist/domain/vcard.d.ts +25 -0
  46. package/dist/domain/vcard.js +267 -0
  47. package/dist/entities/deal.d.ts +14 -0
  48. package/dist/entities/deal.js +3 -0
  49. package/dist/entities/index.d.ts +12 -0
  50. package/dist/errors/reasons.js +63 -4
  51. package/dist/fetch/addresses.d.ts +5 -0
  52. package/dist/fetch/addresses.js +76 -0
  53. package/dist/fetch/page.d.ts +64 -0
  54. package/dist/fetch/page.js +256 -0
  55. package/dist/index.d.ts +5 -3
  56. package/dist/index.js +5 -3
  57. package/dist/meetings/calendar-text.d.ts +1 -1
  58. package/dist/meetings/calendar-text.js +4 -0
  59. package/dist/meetings/event-store.d.ts +2 -2
  60. package/dist/search/account-list.d.ts +4 -0
  61. package/dist/search/account-list.js +19 -8
  62. package/dist/search/query.js +2 -2
  63. package/dist/services/events-search.js +2 -2
  64. package/dist/services/index.d.ts +1 -1
  65. package/dist/services/index.js +1 -1
  66. package/dist/services/ingest.d.ts +56 -8
  67. package/dist/services/ingest.js +95 -61
  68. package/dist/services/messages-search.js +3 -2
  69. package/dist/services/metadata.d.ts +1 -1
  70. package/dist/services/notes-search.js +1 -0
  71. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  72. package/dist/services/proposals/kinds/contracts.js +9 -0
  73. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  74. package/dist/services/proposals/kinds/finance.js +14 -35
  75. package/dist/services/proposals/kinds/orders.js +7 -30
  76. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  77. package/dist/services/proposals/kinds/shared.js +34 -0
  78. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  79. package/dist/services/proposals/kinds/source-review.js +45 -0
  80. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  81. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  82. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  83. package/dist/services/proposals/kinds/transactions.js +10 -0
  84. package/dist/services/proposals/registry.js +9 -0
  85. package/dist/services/search-all-meetings.js +2 -2
  86. package/dist/services/search-all.js +4 -3
  87. package/dist/services/search-kind.js +3 -3
  88. package/dist/store/decisions.js +5 -1
  89. package/dist/store/index.d.ts +14 -3
  90. package/dist/store/index.js +3 -0
  91. package/dist/store/people.js +1 -1
  92. package/dist/store/source-review.d.ts +64 -0
  93. package/dist/store/source-review.js +7 -0
  94. package/dist/store/sqlite/accounts.d.ts +1 -1
  95. package/dist/store/sqlite/accounts.js +24 -1
  96. package/dist/store/sqlite/added-sources.d.ts +82 -0
  97. package/dist/store/sqlite/added-sources.js +237 -0
  98. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  99. package/dist/store/sqlite/business-contracts.js +182 -0
  100. package/dist/store/sqlite/calendar-events.js +7 -3
  101. package/dist/store/sqlite/calendar-forget.js +3 -0
  102. package/dist/store/sqlite/calendar.d.ts +21 -1
  103. package/dist/store/sqlite/calendar.js +27 -7
  104. package/dist/store/sqlite/chat-rekey.js +7 -0
  105. package/dist/store/sqlite/chats.d.ts +3 -1
  106. package/dist/store/sqlite/chats.js +15 -1
  107. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  108. package/dist/store/sqlite/crm-rows.js +195 -0
  109. package/dist/store/sqlite/crm.d.ts +2 -11
  110. package/dist/store/sqlite/crm.js +11 -166
  111. package/dist/store/sqlite/deals.d.ts +4 -8
  112. package/dist/store/sqlite/deals.js +5 -3
  113. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  114. package/dist/store/sqlite/emails.js +2 -0
  115. package/dist/store/sqlite/entity-types.d.ts +14 -9
  116. package/dist/store/sqlite/entity-types.js +4 -10
  117. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  118. package/dist/store/sqlite/evidence-signature.js +349 -0
  119. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  120. package/dist/store/sqlite/evidence-sources.js +7 -3
  121. package/dist/store/sqlite/facts.d.ts +7 -2
  122. package/dist/store/sqlite/facts.js +21 -5
  123. package/dist/store/sqlite/finance.d.ts +18 -105
  124. package/dist/store/sqlite/finance.js +100 -219
  125. package/dist/store/sqlite/knowledge.d.ts +8 -2
  126. package/dist/store/sqlite/knowledge.js +65 -71
  127. package/dist/store/sqlite/labelled.d.ts +3 -0
  128. package/dist/store/sqlite/labelled.js +11 -0
  129. package/dist/store/sqlite/link-kinds.d.ts +2 -0
  130. package/dist/store/sqlite/link-kinds.js +2 -0
  131. package/dist/store/sqlite/manifest.js +2 -0
  132. package/dist/store/sqlite/memories.d.ts +23 -9
  133. package/dist/store/sqlite/memories.js +41 -13
  134. package/dist/store/sqlite/messages.js +2 -0
  135. package/dist/store/sqlite/migrations.generated.js +103 -0
  136. package/dist/store/sqlite/money-lines.d.ts +48 -0
  137. package/dist/store/sqlite/money-lines.js +76 -0
  138. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  139. package/dist/store/sqlite/money-transactions.js +295 -0
  140. package/dist/store/sqlite/notes.d.ts +11 -2
  141. package/dist/store/sqlite/notes.js +20 -25
  142. package/dist/store/sqlite/orders.d.ts +36 -6
  143. package/dist/store/sqlite/orders.js +126 -46
  144. package/dist/store/sqlite/payment-facts.js +1 -1
  145. package/dist/store/sqlite/private-people.js +2 -0
  146. package/dist/store/sqlite/products.d.ts +78 -0
  147. package/dist/store/sqlite/products.js +131 -0
  148. package/dist/store/sqlite/project-transfer/records.js +26 -1
  149. package/dist/store/sqlite/project-transfer/snapshot.js +5 -3
  150. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  151. package/dist/store/sqlite/proposed-actions.js +24 -7
  152. package/dist/store/sqlite/providers.d.ts +0 -4
  153. package/dist/store/sqlite/providers.js +20 -2
  154. package/dist/store/sqlite/record-matching.d.ts +80 -0
  155. package/dist/store/sqlite/record-matching.js +264 -0
  156. package/dist/store/sqlite/record-projection.d.ts +89 -0
  157. package/dist/store/sqlite/record-projection.js +50 -0
  158. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  159. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  160. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  161. package/dist/store/sqlite/record-projectors-money.js +214 -0
  162. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  163. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  164. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  165. package/dist/store/sqlite/record-projectors.js +7 -67
  166. package/dist/store/sqlite/record-relations.d.ts +24 -0
  167. package/dist/store/sqlite/record-relations.js +92 -0
  168. package/dist/store/sqlite/record-remap.d.ts +12 -0
  169. package/dist/store/sqlite/record-remap.js +92 -0
  170. package/dist/store/sqlite/record-run.d.ts +71 -0
  171. package/dist/store/sqlite/record-run.js +179 -0
  172. package/dist/store/sqlite/record-settling.d.ts +9 -0
  173. package/dist/store/sqlite/record-settling.js +74 -0
  174. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  175. package/dist/store/sqlite/record-stamps.js +30 -0
  176. package/dist/store/sqlite/record-writes.d.ts +43 -0
  177. package/dist/store/sqlite/record-writes.js +307 -0
  178. package/dist/store/sqlite/records.d.ts +52 -42
  179. package/dist/store/sqlite/records.js +123 -353
  180. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  181. package/dist/store/sqlite/ref-summaries.js +60 -8
  182. package/dist/store/sqlite/refunds.d.ts +31 -0
  183. package/dist/store/sqlite/refunds.js +112 -0
  184. package/dist/store/sqlite/reviewed.d.ts +109 -0
  185. package/dist/store/sqlite/reviewed.js +173 -0
  186. package/dist/store/sqlite/schema.d.ts +2840 -83
  187. package/dist/store/sqlite/schema.js +256 -1
  188. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  189. package/dist/store/sqlite/source-review-marks.js +143 -0
  190. package/dist/store/sqlite/source-review.d.ts +54 -0
  191. package/dist/store/sqlite/source-review.js +221 -0
  192. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  193. package/dist/store/sqlite/stage-amounts.js +23 -0
  194. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  195. package/dist/store/sqlite/subscriptions.js +294 -0
  196. package/dist/store/sqlite/text-input.d.ts +3 -0
  197. package/dist/store/sqlite/text-input.js +13 -0
  198. package/dist/store/sqlite/things.js +2 -9
  199. package/dist/store/sqlite/transaction.d.ts +15 -0
  200. package/dist/store/sqlite/transaction.js +57 -0
  201. package/dist/store/sqlite/wallets.d.ts +88 -0
  202. package/dist/store/sqlite/wallets.js +143 -0
  203. package/dist/store/store-errors.d.ts +1 -0
  204. package/dist/store/store-errors.js +45 -0
  205. package/dist/store/store.d.ts +16 -1
  206. package/dist/store/store.js +30 -6
  207. package/package.json +5 -2
  208. package/schemas/examples/records-business.jsonl +11 -0
  209. package/schemas/records-envelope.v1.schema.json +1160 -5
package/CHANGELOG.md CHANGED
@@ -7,6 +7,202 @@ shape of this file.
7
7
 
8
8
  ## Unreleased
9
9
 
10
+ ## 0.608.0 — 08.11.2026
11
+
12
+ ### Fixed
13
+
14
+ - **Two pairs of reasons no longer share one message**, so the command audit (`same-error-reason`) passes in a CLI
15
+ that lists cli-core's reasons, such as b24 and beeline. `oauth.missing` says the profile is not signed in to the
16
+ provider and `session.missing` that it has no API token saved; `finance.line-amount` names an invoice line and
17
+ `order.line-amount` an order line. The reason ids and codes are unchanged.
18
+
19
+ ## 0.607.0 — 08.11.2026
20
+
21
+ ### Added
22
+
23
+ - **Phone data in the records envelope.** A `message` of kind `sms` becomes a chat and message, and an `event` of kind
24
+ `call` an event of the `calls` calendar (`event_type: call`, never busy), both in the one account the import names,
25
+ so `search all`, `events list event_type:call`, an account group and a person's context read them. The other side is
26
+ the `counterpart` person record, matched by phone or made; `events list person:` finds a call through it.
27
+ `envelopeOfVcard(text, { provider, account, batchId, region })` and `isVcard` turn a `.vcf` (2.1, 3.0, 4.0) into
28
+ persons and their organizations, and `ingestVcard` (`./services`) imports it. A number without a country code is
29
+ read only with `region`.
30
+ - **A provider may hold several kinds.** A provider entry takes `kinds` beside `kind` (its first), and search lanes
31
+ pick the accounts whose provider holds their kind (`holdsKind`, `kindsIn`). The seeded `phone` holds `messages` and
32
+ `events`. An entry with `kind` alone means what it meant; an older build reads the first kind only.
33
+ Entries of one name join their kinds, so registering an older shape never drops another build's. `imported`
34
+ marks a provider no sync writes; SMS and calls are taken only there (`record.provider-not-imported`), never into a
35
+ chat whose membership is not `imported` (`record.chat`), and an SMS moved to another thread is refused
36
+ (`record.moved`). A deleted SMS or call record tombstones its message or event, and
37
+ sending it again brings them back.
38
+ - **`deals list --format csv` and `leads list --format csv`: a page of deals or leads as a table for a spreadsheet.**
39
+ stdout carries the CSV (RFC 4180, CRLF) and nothing else; the way to the next page goes to stderr. The columns are
40
+ the built-in fields, `amount` and `currency` apart, then every CRM field by its label as `fields list` shows it — a
41
+ money field as `<label> amount` and `<label> currency`, a label two fields share told apart by its code.
42
+ `--json=a,b` beside it picks the columns, a CRM field as `provider_metadata.<code>`. A cell that would start a
43
+ formula (`=`, `+`, `-`, `@`, tab, CR) gets a leading `'`, a plain number excepted. `--jsonl`, a bare `--json`,
44
+ `--compact` and an agent's run are refused with `output.conflict`. `csvCell`, `csvRecords` and `writeCsv` are
45
+ exported from `@wirecat/cli-core/cli` for a CLI's own lists.
46
+
47
+ - **`pipelines show` in a CRM CLI is the pipeline's board.** Each stage now gives `items`, the deals or leads standing
48
+ in it, and `amounts`, their sum per currency with how many carry it. Nothing is converted, and an item with no amount
49
+ is counted but adds no sum. At a terminal it prints a table of the stages, then the open stages' sum and the won,
50
+ lost and win rate. The pipeline may be left out when the CRM account has only one; with several, the command lists
51
+ them as `name (pipeline:<id>)` and in `allowed` (`crm.pipeline-required`). `store.deals.pipeline` gives the same two
52
+ fields, counted from the rows its `since` keeps.
53
+
54
+ - **`appMcpCommand`'s `signedIn` hook gets the run's keyring** as a third argument, so `mcp check` reads a test's
55
+ `memoryKeyring()` and the CLI no longer captures it in a `preAction` hook of its own. A hook that throws, such as
56
+ on a locked keyring, counts as not signed in. A two-argument hook still works.
57
+ - **`ProfileTokenStore` in `@wirecat/cli-core/cli`: one API token per profile for a CLI that is not a messenger**,
58
+ so b24, beeline and cli-template drop their copies of `src/token.ts`. `<PREFIX>_TOKEN`, then the keyring entry
59
+ `token:<profile>` under the app's service, then a 0600 file; a moved run writes only a temporary
60
+ `<app>:<config folder>` entry. `write(profile, token, "file")` also forgets the keyring copy. `need(profile)`
61
+ throws the new reason `session.missing` (`authentication_error`, naming `session start`), the one "not signed in"
62
+ every token CLI gives; `signedIn(profile)` is `appMcpCommand`'s hook.
63
+ - **Evidence can carry the quote a memory or fact rests on, and every evidence link records what its source looked
64
+ like.** `store.memories.add` and `store.facts.add` take each piece of evidence as a reference, as before, or as
65
+ `{ ref, quote }` with up to 500 characters (`evidence.quote-length` otherwise); a quote the source's text does not
66
+ hold is refused (`evidence.quote-not-found`). The link's `metadata` keeps `{ v: 1, sig, rev, cited_rev, quote?,
67
+ checked_at }`, read from the source's columns and never its text, deletion included, so a later check can tell that
68
+ a cited source changed or went. Reads still return evidence as references. A project snapshot leaves the signature
69
+ behind and the restore signs each evidence link against the target store; a quote does not travel.
70
+ - **Memories and facts follow their sources.** `store.knowledge.checkSources({ limit })` walks the evidence links of
71
+ memories and facts, 500 a run by default, going on from where the last run stopped, and opens one
72
+ `memory_source_review` proposal per memory or fact whose source changed (`changed`), was deleted (`deleted`), or
73
+ cites a fact or memory that no longer holds (`outdated`, naming its replacement). A changed source that still says
74
+ the quoted words raises nothing. A source deleted for good, or a message tombstoned, opens a `deleted` review at once.
75
+ `store.knowledge.challenge(ref, { evidence, reason, by, suggestion? })` raises one as `contradicted`. The check
76
+ answers `{ checked, baselined, raised, refreshed, closed }` and never changes a status. Memory and fact reads carry
77
+ `sourceReview: { id, cause } | null`. The review is the owner's alone: `knowledge.decideSourceReview` or the
78
+ registry confirms it (still true; a memory is verified now) or rejects it (dismissed), and both sign its sources
79
+ again. Superseding, invalidating, reversing or rejecting the memory or fact closes its review as executed; removing
80
+ it erases its reviews. When a cited source is erased, every review naming it loses that reference and the words of
81
+ each challenge and suggestion that cited it.
82
+ - **`fetchPage(url)` in `@wirecat/cli-core/documents` reads one web page** for a link the owner adds by hand: `http`
83
+ or `https` only, 50 MiB, 30 s, at most 5 redirects followed by hand, no cookies or credentials. Every hop's name must
84
+ resolve to public addresses only, and the connection goes to the address that was checked, so a link cannot reach
85
+ this computer, the local network or a cloud metadata address, even by DNS rebinding or an IPv4-mapped form. The
86
+ reader is chosen by content type. Refusals carry `source.url-refused`, `source.url-status`, `source.url-timeout`,
87
+ `source.url-redirects`, `source.url-unreachable`, `source.too-large`, `source.unsupported`, `source.no-text`,
88
+ `source.unreadable` and `source.engine-missing`; a private Google document is `source.needs-sign-in`.
89
+ `isPublicAddress` is exported too. A redirect from `https` to `http` is refused, the reader is stopped at the same
90
+ 30 s, and the answer gives `requestedUrl` (the address to keep) beside `finalUrl` (never to be stored).
91
+ - **`store.notes.saveAddedSource` keeps a source the owner adds by hand**: pasted text, a file, or a page read from a
92
+ link, in the new `added` account. It is a document like a folder's, found by notes search, by `search all` and by
93
+ meaning. A repeat of the same file or text is the same document (`created: false`); a live folder or Drive document
94
+ with the same content is answered as `duplicateOf`, and only the new subjects are linked to it. `by` names who
95
+ adds it: an agent's subjects are linked unconfirmed. Only the text is kept unless the caller passes `keepCopy` with
96
+ the path of its copy (`kept: "text" | "copy"`). The account is no folder, so `saveFileNote` and `deleteFileNotes`
97
+ refuse it, and a folder file of the same content never joins an added source. `store.notes.addedAccount()` names
98
+ the account; `ADDED_PROVIDER` and `ADDED_ACCOUNT` are exported.
99
+ - **`store.notes.findAddedSource` and `addedSourceKeyOf` say what saving would find, writing nothing**, so a caller
100
+ that keeps a copy of a file writes it only when the source is new. **`store.notes.removeAddedSource(ref, "owner")`**
101
+ removes an added source the way a folder file's removal does and answers the path of its copy, if any.
102
+ - **Store version 57: business tables.** `store.products` (`product:<id>`, written directly, a line copies its
103
+ price), `store.contracts` (`contract:<id>`: an agent's or an import's is proposed only when it carries a value, and
104
+ only the owner changes the value of a confirmed one; the notice deadline is computed), `store.subscriptions`
105
+ (`subscription:<id>`, every price a row and a proposal of its own, `subscription_price:<id>`, never overwritten;
106
+ `currentPrice` is the confirmed one in force today), `store.wallets` (`wallet:<id>`, one currency each, the balance
107
+ computed from confirmed, booked transactions after the opening day, pending ones beside it; only the owner sets the
108
+ opening balance) and `store.transactions` (`transaction:<id>`, splits by category within the amount, a payment linked
109
+ only of the same currency, direction and amount, once). `minCompatible` stays 56, as version 56 set it.
110
+ - **Orders take lines, a direction, a contract and a deal.** With lines an order totals their sum (`order.total`);
111
+ `orders.addLine` and `orders.removeLine` change them, the owner on any order, an agent only on its own proposed one.
112
+ A `sale` makes the owner its supplier. `orders.add` and `orders.get` answer `OrderDetail` with `lines`.
113
+ - **Refunds.** `finance.addPayment({ refundOf })` writes a payment the other way that takes money back
114
+ (`finance.refund`, `finance.over-refund`, `finance.refunded`): it is confirmed only after its payment, goes back only
115
+ to an invoice its payment paid, never more than that payment gave it, and a refunded payment is not rejected.
116
+ Invoices and payments take a `contract` and a `subscription`; an invoice line may name a `product`.
117
+ - **Review kinds `contract`, `subscription`, `subscription_price` and `transaction`**, decided by the owner only, as
118
+ invoices are. Confirming a subscription confirms the prices proposed with it; a later price is its own proposal
119
+ (`subscription_price:<id>`). A bot changes only its own still-proposed rows; a confirmed one is the owner's.
120
+ - **`InvoiceLine.product`** names the product a line was priced from, and `OrderInput.supplierName` may be left out
121
+ of a sale. `signedMinorUnits` and a `formatDecimal` that prints negative amounts are exported.
122
+ - **New reasons:** `finance.refund`, `finance.over-refund`, `finance.refunded`; `order.total`, `order.line` (an order
123
+ keeps its last line), `order.no-line`, `order.lines`, `order.line-amount`, `order.currency`, `order.owner-only`;
124
+ `product.field`, `product.duplicate`, `product.ref`; `contract.field`, `contract.ref`; `subscription.field`,
125
+ `subscription.interval`, `subscription.price`, `subscription.no-price`, `subscription.ref`; `wallet.field`,
126
+ `wallet.number`, `wallet.ref`; `transaction.field`, `transaction.payment`, `transaction.ref`, `transaction.split`,
127
+ `transaction.no-split`.
128
+ - **The records envelope takes every business type.** Beside v1's five, `deal`, `lead`, `pipeline`, `order` (with
129
+ `lines`), `contract`, `subscription` (with `prices`), `product`, `wallet` and `transaction` (with `splits`), each with
130
+ typed `fields` and roles in `RECORD_TYPES`; `pnpm schema:envelope` writes the shipped JSON Schema from it. A relation
131
+ names a store entity by `ref` (`organization:12`), a relationship role carries `as` (`decision-maker`), `payment`
132
+ takes `refund_of`, a line names its `product` or `product_ref`, and `options.lines: "products"` reads an invoice
133
+ line's product. Money types are proposals of the bot `import`; deals and leads land on the row CRM sync writes for
134
+ the same account. A changed record re-proposes the import's own proposal while nobody else touched it, and is
135
+ flagged once the owner edited or decided it. See
136
+ [`docs/storage/records-envelope.md`](docs/storage/records-envelope.md).
137
+ - **Streaming JSONL.** `ingestLines(store, jsonlLines(stream), { account, dryRun, chunk, onIssue })` (`./services`)
138
+ writes per chunk as lines arrive; the receipt's lists keep 1000 entries and set `truncated`, the counts stay exact,
139
+ and `onIssue` (also on `ingest`) gets every refusal. A dry run is one transaction rolled back at the end: it holds
140
+ the write lock, and any other statement on the store handle meanwhile is refused (`store.dry-run`). A leading
141
+ byte-order mark is skipped; `envelopeOfText(text)` reads a file's text as JSON or JSONL.
142
+ - **Receipt `unmatched[{key, pointer, reason, candidates}]`** and a flagged entry's `reason` and `candidates`,
143
+ `store.records.match({ provider, account })`, `store.records.list({ unmatched })`, `SourceRecord.createdEntity` and
144
+ a relation's `ref` and `as`. The owner's `store.records.map` moves a record whose entity the import made, with the
145
+ account's records linked to it, and answers the old one as `unused`, beside the records it completed.
146
+ - **`options.phone_region`**: a person's phone without `+` is an identifier only when the envelope names this country
147
+ and the number is valid there; the `phone_countries` setting never decides it. Without it the number stays data and
148
+ the receipt lists it under `ignored` (`record.phone-region`).
149
+ - **An envelope deal's and lead's people stay as record relations** (with `as`) until imports report relationships to
150
+ the store; they no longer write the deal's person links.
151
+ - **`orders.revise(order, input)`** replaces an order's columns and lines: the owner on any order, a bot on its own
152
+ proposed one. New reasons `record.identifier`, `record.ambiguous`, `record.separated`, `record.phone-region` and
153
+ `store.dry-run`.
154
+ - **An example import, one synthetic customer end to end**, ships as
155
+ `@wirecat/cli-core/schemas/examples/records-business.jsonl`.
156
+
157
+ ### Changed — may break callers
158
+
159
+ - **`EntryEventType` has `call`**, and `events list event_type:` takes it. A switch over the kinds needs a branch.
160
+ - **`kindIn` and `ListedAccount.kind` name a provider's first kind only.** A provider may hold several (`kindsIn`,
161
+ `ListedAccount.kinds`, `holdsKind`); code that tests `kindIn(provider) === kind` misses the others.
162
+ - **`calendarAccounts`, `inSource(..., "events")` and `events list person:` now return phone accounts and calls**:
163
+ a phone account holds events, and a call's other side is found by its `related-to` link.
164
+ - **`run()` refuses `--offline` for a command annotated `offline: false`, or under a group that is**, before its
165
+ action and before the first-run questions: `permission_error`, reason `offline.refused`. A command's own
166
+ `--dry-run` still runs. cli-core's own such commands answered `validation_error` (`upgrade`, `topics`,
167
+ `chats inspect`, `chats send-as`) or `busy.offline` (`calendars busy`); they now all answer `offline.refused`, exit
168
+ code 5 instead of 2. `refuseOffline(command, service)` in `@wirecat/cli-core/cli` is the same refusal for a command
169
+ whose need depends on a flag, such as `session status --check`, so b24, beeline, gcal and cli-template drop theirs.
170
+ - **A cited source deleted for good leaves the citing evidence in place.** Removing a fact, memory, note, document,
171
+ calendar event, chat or account kept rows whose ids a later row could take, or deleted the links that cited them, so
172
+ a memory could lose a source without a trace or rest on someone else's text. Now each evidence link to the removed
173
+ row stays with no pointer and no quote, marked `gone`, and `sources` shows it `missing`; `memories.remove` and
174
+ `facts.remove` no longer count it among the links they removed. A message's tombstone drops quotes of it too. A
175
+ purged account or chat forgets evidence to every row it took, chats included, and a chat merge re-signs the
176
+ evidence it moves onto the kept chat and messages.
177
+ - **An agent can no longer retire what the owner stands behind**, even with `agent_decisions` on:
178
+ `memories.markStale` of a confirmed memory, and `facts.accept` of a correction that supersedes an accepted fact,
179
+ refuse an agent with `proposal.owner-only`. An agent that finds such a memory or fact wrong calls
180
+ `knowledge.challenge` with what contradicts it, and the owner decides the review. An agent allowed to decide may
181
+ still turn down another agent's proposed memory, and accept a correction of a fact that is only proposed.
182
+ - **An invoice's paid amount is net of confirmed refunds.** `paid`, `open`, the status, `openTotals` and the void check
183
+ read one figure, the confirmed allocations of payments less those of their refunds: an invoice refunded in full is
184
+ `issued` again and may be voided. An older memo computes paid gross; update memo before writing refunds.
185
+ - **A person, organization or project record is matched or made on import**, in every file, v1 files included. One
186
+ exact e-mail, E.164 phone, organization identifier or project key links it; none makes the entity (marked
187
+ `createdEntity`) with the record's identifiers; two or more leave it `unmatched` (`record.ambiguous`). A record
188
+ that waited for the owner's `records.map` is matched or made on its next import, so dry-run an old file before
189
+ importing it again. An organization's `email` identifier is kept under the provider `org-email`.
190
+ - **`store.records.write` is `store.records.run`**, taking an iterable of `{ index, record, errors? }` and answering
191
+ counts and capped lists instead of one outcome per record; `RecordOutcome` and `RecordsWritten` are gone. A
192
+ `SourceRecord` relation's `externalId` is `null` when it names a `ref`. `ingest` checks a record's fields against
193
+ its type's schema first, so a broken v1 invoice or payment field is refused with `record.invalid` at the field's
194
+ pointer.
195
+ - **A CRM contact identity escapes a `/` or `%`** in its account or id (`%2F`, `%25`), so two accounts never share
196
+ one; ids without them, every CRM's so far, keep their identity.
197
+
198
+ ### Fixed
199
+
200
+ - **A CRM field lookup's refusal names the option the name came from.** `fieldNamed`, `unknownField` and `optionOf`
201
+ take that option as a last argument, `--field` when left out. They always answered `param: "--field"`, so a CRM
202
+ CLI that looked up a field named in `--query` or `--json` pointed the caller at the wrong option.
203
+ - **`store.accounts.purge` deletes the account's documents too**, with their files, pieces, words and the links to
204
+ them; a notes folder, Drive or added account with documents no longer stops at them.
205
+
10
206
  ## 0.606.0 — 08.11.2026
11
207
 
12
208
  ### Added
@@ -2,6 +2,7 @@ export type { CalendarAccessRole, CalendarInput, EntryAttachment, EntryAttachmen
2
2
  export { expandSeries, localMoment, unexpandable } from "./expand.js";
3
3
  export { type CalendarFeeds, FEED_LIMITS, FEED_PREFIX, type FeedLimits, type FeedRecord, type FeedRegistry, type FeedSyncStats, type FeedsSyncReport, feedAddress, fetchFeed, icsFeeds, isFeedCalendar, readFeed, syncWithFeeds, } from "./feeds.js";
4
4
  export { type IcsEvent, type IcsOverride, type IcsRead, type IcsSkip, readIcs, writeIcs } from "./ics.js";
5
+ export { accountsMeta } from "./reads.js";
5
6
  export { repeatRule } from "./recurrence.js";
6
7
  export type { BusyTimes, CalendarExpander, CalendarSource, CalendarSourceTraits, ChangePage, ChangeResult, FreeBusyRequest, SearchPage, SyncWindow, } from "./source.js";
7
8
  export { type CalendarCursor, type CalendarSyncOptions, type CalendarSyncReport, type CalendarSyncResult, calendarStatus, calendarSyncWindow, type PendingRound, parseCalendarCursor, syncCalendars, } from "./sync.js";
@@ -1,6 +1,7 @@
1
1
  export { expandSeries, localMoment, unexpandable } from "./expand.js";
2
2
  export { FEED_LIMITS, FEED_PREFIX, feedAddress, fetchFeed, icsFeeds, isFeedCalendar, readFeed, syncWithFeeds, } from "./feeds.js";
3
3
  export { readIcs, writeIcs } from "./ics.js";
4
+ export { accountsMeta } from "./reads.js";
4
5
  export { repeatRule } from "./recurrence.js";
5
6
  export { calendarStatus, calendarSyncWindow, parseCalendarCursor, syncCalendars, } from "./sync.js";
6
7
  export { CALENDAR_WRITE_DEFAULTS, CALENDAR_WRITE_KEYS, calendarConflict, EVENTS_DELETE_SERIES_KEY, EVENTS_NOTIFY_KEY, EVENTS_REMIND_HOOK_KEY, } from "./writer.js";
@@ -1,6 +1,7 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { dateRange, dayBoundary, queryError, queryFieldsOf, } from "@wirecat/cli-base/query";
3
3
  import { LIST_QUERY_GUIDE, listQuery, nativeTermLists, negatableOf, typedQuery, } from "../cli/list-query.js";
4
+ import { isImportedProvider } from "../domain/providers.js";
4
5
  import { event, eventChange, eventItem, listed, } from "../meetings/index.js";
5
6
  import { entriesOfList, fitting } from "../search/account-list.js";
6
7
  import { listContextOf } from "../services/search-kind.js";
@@ -78,6 +79,7 @@ export const EVENT_TYPES = [
78
79
  "working-location",
79
80
  "birthday",
80
81
  "from-mail",
82
+ "call",
81
83
  ];
82
84
  const oneSided = (field, example) => (node) => {
83
85
  if (node.operator !== "range" || node.upper !== "*")
@@ -481,6 +483,9 @@ export const sourceAccounts = async (messages, running, source, command) => {
481
483
  export const accountsMeta = async (store, accounts, skipped, now) => {
482
484
  const issues = [...skipped];
483
485
  for (const { id, key } of accounts) {
486
+ // An import's calls are all it has: no sync could be behind on them.
487
+ if (isImportedProvider(key.provider))
488
+ continue;
484
489
  const { items } = await calendarStatus(store, id, { profile: nameOf(key), now });
485
490
  if (items.length === 0)
486
491
  issues.push({ code: "not_found", reason: "calendar.unsynced", source: nameOf(key) });
@@ -1,3 +1,4 @@
1
+ import type { KeyringStore } from "@wirecat/cli-base";
1
2
  import type { Command } from "commander";
2
3
  import type { AppServerOptions } from "../mcp/app-server.js";
3
4
  import type { AppIdentity } from "../ports/app.js";
@@ -12,8 +13,11 @@ export interface AppMcpOptions {
12
13
  skill?: URL;
13
14
  /** What the CLI alone knows stops a command for a profile, such as an OAuth grant without the scope. */
14
15
  availability?: AppServerOptions["availability"];
15
- /** Whether the profile can reach the service, read from disk; left out, `mcp check` does not say. */
16
- signedIn?: (profile: string, env: NodeJS.ProcessEnv) => boolean;
16
+ /**
17
+ * Whether the profile can reach the service, read from disk with the run's keyring (a test's `memoryKeyring()`);
18
+ * left out, `mcp check` does not say. A throw, such as a locked keyring, counts as not signed in.
19
+ */
20
+ signedIn?: (profile: string, env: NodeJS.ProcessEnv, keyring: KeyringStore | undefined) => boolean;
17
21
  }
18
22
  /**
19
23
  * `mcp serve | revoke | server | config | add | check` for a CLI that is not a messenger — the same commands, flags
@@ -1,4 +1,4 @@
1
- import { baseContext } from "./context.js";
1
+ import { baseContext, environmentOf } from "./context.js";
2
2
  import { mcpGroup } from "./messenger/mcp-command.js";
3
3
  import { refuseUnknownPermissionKeys } from "./permission-keys.js";
4
4
  /**
@@ -43,7 +43,16 @@ export const appMcpCommand = (app, configuration, options) => {
43
43
  untrusted: options.untrusted,
44
44
  });
45
45
  },
46
- signedIn: (_self, profile, env) => options.signedIn?.(profile, env),
46
+ signedIn: (self, profile, env) => {
47
+ if (!options.signedIn)
48
+ return undefined;
49
+ try {
50
+ return options.signedIn(profile, env, environmentOf(self).keyring);
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ },
47
56
  };
48
57
  return mcpGroup(host);
49
58
  };
@@ -0,0 +1,10 @@
1
+ import type { Streams } from "@wirecat/cli-base";
2
+ /**
3
+ * One cell as RFC 4180 writes it, safe to open in a spreadsheet: text that would start a formula gets a leading `'`,
4
+ * since every cell may be what someone else typed into the CRM.
5
+ */
6
+ export declare const csvCell: (value: unknown) => string;
7
+ /** A header and its rows as RFC 4180 records, without line ends; the header is guarded like any cell. */
8
+ export declare const csvRecords: (header: readonly string[], rows: readonly (readonly unknown[])[]) => string[];
9
+ /** The table on stdout and nothing else, every record ending in CRLF. */
10
+ export declare const writeCsv: (streams: Pick<Streams, "data">, header: readonly string[], rows: readonly (readonly unknown[])[]) => void;
@@ -0,0 +1,22 @@
1
+ /** A number a spreadsheet reads as a number; it cannot be a formula, so a leading minus stays. */
2
+ const NUMBER = /^-?\d+(\.\d+)?$/;
3
+ /** What a spreadsheet reads as the start of a formula (OWASP's CSV injection list). */
4
+ const FORMULA = /^[=+\-@\t\r]/;
5
+ /**
6
+ * One cell as RFC 4180 writes it, safe to open in a spreadsheet: text that would start a formula gets a leading `'`,
7
+ * since every cell may be what someone else typed into the CRM.
8
+ */
9
+ export const csvCell = (value) => {
10
+ if (value === null || value === undefined)
11
+ return "";
12
+ const text = String(value);
13
+ const safe = FORMULA.test(text) && !NUMBER.test(text) ? `'${text}` : text;
14
+ return /[",\r\n]/.test(safe) ? `"${safe.replaceAll('"', '""')}"` : safe;
15
+ };
16
+ /** A header and its rows as RFC 4180 records, without line ends; the header is guarded like any cell. */
17
+ export const csvRecords = (header, rows) => [header, ...rows].map((row) => row.map(csvCell).join(","));
18
+ /** The table on stdout and nothing else, every record ending in CRLF. */
19
+ export const writeCsv = (streams, header, rows) => {
20
+ // `data` adds the "\n" itself, so the last record's CRLF needs only its "\r".
21
+ streams.data(`${csvRecords(header, rows).join("\r\n")}\r`);
22
+ };
@@ -1,6 +1,16 @@
1
1
  import type { Command } from "commander";
2
2
  import { type AppIdentity } from "../ports/app.js";
3
3
  import { type CommandPermissions } from "./permission-keys.js";
4
+ /**
5
+ * Refuses `--offline` for a command that needs the service: call it where the need depends on a flag, such as
6
+ * `session status --check`. A command that always needs it is annotated `offline: false`, and `run()` refuses it.
7
+ */
8
+ export declare const refuseOffline: (command: Command, service: string) => void;
9
+ /**
10
+ * Refuses `--offline` before anything runs when the command, or a group above it, is annotated `offline: false`. A
11
+ * command's own `--dry-run` passes: it answers without the service.
12
+ */
13
+ export declare const refuseOfflineCommand: (action: Command, app: AppIdentity, offline: boolean, preview: boolean) => void;
4
14
  type Resolve = (flags: object, options: {
5
15
  env: NodeJS.ProcessEnv;
6
16
  needsProfile: false;
@@ -11,6 +11,25 @@ import { withAgentLevels } from "./context.js";
11
11
  import { changesMessenger } from "./effects.js";
12
12
  import { refuseUnknownPermissionKeys } from "./permission-keys.js";
13
13
  import { NONE_NAMED, settingsFor } from "./settings.js";
14
+ /**
15
+ * Refuses `--offline` for a command that needs the service: call it where the need depends on a flag, such as
16
+ * `session status --check`. A command that always needs it is annotated `offline: false`, and `run()` refuses it.
17
+ */
18
+ export const refuseOffline = (command, service) => {
19
+ if (command.optsWithGlobals().offline)
20
+ throw new CliError("permission_error", `this needs ${service}; leave out --offline`, { reason: "offline.refused" });
21
+ };
22
+ /**
23
+ * Refuses `--offline` before anything runs when the command, or a group above it, is annotated `offline: false`. A
24
+ * command's own `--dry-run` passes: it answers without the service.
25
+ */
26
+ export const refuseOfflineCommand = (action, app, offline, preview) => {
27
+ if (!offline || preview)
28
+ return;
29
+ for (let command = action; command; command = command.parent)
30
+ if (metaOf(command).offline === false)
31
+ throw new CliError("permission_error", `\`${[app.command, ...commandPathOf(action)].join(" ")}\` needs the service, not the local copy; leave out --offline`, { reason: "offline.refused" });
32
+ };
14
33
  /**
15
34
  * Refuses a change on the messenger the read-only lock or the profile's level stops, before anything connects
16
35
  * (SEC-62). The send guard would refuse it too, but only after the command connected and found its chat. The journal
@@ -69,9 +69,11 @@ export { loadSnakeCaseConfig } from "./config-keys.js";
69
69
  export { type AgentRun, type BaseContext, type BaseEnvironment, baseContext, environmentOf, inCommandRun, outputFor, provide, runBudgetOf, secretInputOf, withAgentLevels, } from "./context.js";
70
70
  export { addContractInfo, type ContractEvidenceOptions, contractEvidence } from "./contract-evidence.js";
71
71
  export { sharedCommandTemplate } from "./contract-templates.js";
72
+ export { csvCell, csvRecords, writeCsv } from "./csv.js";
72
73
  export { type Closeable, withDeadline } from "./deadline.js";
73
74
  export { DEFAULT_CONFIG, ensureDefaultConfig } from "./default-config.js";
74
75
  export { DISCOVERY_DESCRIPTIONS } from "./discovery-descriptions.js";
76
+ export { refuseOffline } from "./early-refusal.js";
75
77
  export { admittedUnderLock, changesAuthority, changesAuthorityAt, changesAuthorityNow, destroysNothing, FETCH, fetchesOnly, fetchesOnlyAt, grantsAuthority, isLogin, isOtherServiceCall, isProposal, isStoreChange, judgedEffects, judgedTargets, LOCAL_READ, LOCAL_WRITE, LOCKED_AUTHORITY_COMMANDS, logsInOrOut, NO_EFFECTS, narrowsUnderLock, ownerOnlyOption, PROPOSE_COMMANDS, previewFlag, proposesOnly, REMOTE_READ, REMOTE_WRITE, reachesOtherService, readsOverMcp, readsOverMcpAt, refuseUnderReadOnly, storeChangeRefusal, writesFileOnlyWith, writesNewFileOnlyWith, } from "./effects.js";
76
78
  export { type CliEntry, type EntryContext, type EntryIo, openBrowser, startCli } from "./entry.js";
77
79
  export { type AnswerOutput, answerSchema, type Body, type ItemBody, isBody, itemAnswer, itemOf, jsonlRecords, judgedAnswer, type ListBody, type ListInput, listOf, metaNow, printItem, renderAnswer, sealed, snakeKeys, snakeKeysKeeping, } from "./envelope.js";
@@ -119,6 +121,7 @@ export { writeNewFile } from "./new-file.js";
119
121
  export { positiveCount, window, withPaging } from "./paging.js";
120
122
  export { type CommandPermissions, type ConditionalKey, commandPathKey, commandPermissions, knownBeside, knownPermissionKeys, type PermissionKeyOf, type PermissionKeySource, refuseUnknownPermissionKeys, unknownPermissionIssues, unknownPermissionKeys, } from "./permission-keys.js";
121
123
  export { asFirstWord, commandWords, liftProfile, profileFree, refuseCommandName, rootOf, takesProfile, usableProfileName, } from "./profile.js";
124
+ export { ProfileTokenStore, type ProfileTokenStoreOptions, type TokenStorage } from "./profile-token.js";
122
125
  export { createProgram, type ProgramDefinition, type ProgramOptions, type RunOptions, run } from "./program.js";
123
126
  export { type ProjectTextHints, projectAnswerParts, projectCutoffTime, projectEvidenceText, projectWindowOf, withSyncCommands, } from "./project-evidence.js";
124
127
  export { type ProjectStatusHints, type ProjectStatusItem, projectStatusAnswer, projectStatusRow, projectStatusSchema, projectStatusText, } from "./project-status.js";
package/dist/cli/index.js CHANGED
@@ -61,9 +61,11 @@ export { loadSnakeCaseConfig } from "./config-keys.js";
61
61
  export { baseContext, environmentOf, inCommandRun, outputFor, provide, runBudgetOf, secretInputOf, withAgentLevels, } from "./context.js";
62
62
  export { addContractInfo, contractEvidence } from "./contract-evidence.js";
63
63
  export { sharedCommandTemplate } from "./contract-templates.js";
64
+ export { csvCell, csvRecords, writeCsv } from "./csv.js";
64
65
  export { withDeadline } from "./deadline.js";
65
66
  export { DEFAULT_CONFIG, ensureDefaultConfig } from "./default-config.js";
66
67
  export { DISCOVERY_DESCRIPTIONS } from "./discovery-descriptions.js";
68
+ export { refuseOffline } from "./early-refusal.js";
67
69
  export { admittedUnderLock, changesAuthority, changesAuthorityAt, changesAuthorityNow, destroysNothing, FETCH, fetchesOnly, fetchesOnlyAt, grantsAuthority, isLogin, isOtherServiceCall, isProposal, isStoreChange, judgedEffects, judgedTargets, LOCAL_READ, LOCAL_WRITE, LOCKED_AUTHORITY_COMMANDS, logsInOrOut, NO_EFFECTS, narrowsUnderLock, ownerOnlyOption, PROPOSE_COMMANDS, previewFlag, proposesOnly, REMOTE_READ, REMOTE_WRITE, reachesOtherService, readsOverMcp, readsOverMcpAt, refuseUnderReadOnly, storeChangeRefusal, writesFileOnlyWith, writesNewFileOnlyWith, } from "./effects.js";
68
70
  export { openBrowser, startCli } from "./entry.js";
69
71
  export { answerSchema, isBody, itemAnswer, itemOf, jsonlRecords, judgedAnswer, listOf, metaNow, printItem, renderAnswer, sealed, snakeKeys, snakeKeysKeeping, } from "./envelope.js";
@@ -109,6 +111,7 @@ export { writeNewFile } from "./new-file.js";
109
111
  export { positiveCount, window, withPaging } from "./paging.js";
110
112
  export { commandPathKey, commandPermissions, knownBeside, knownPermissionKeys, refuseUnknownPermissionKeys, unknownPermissionIssues, unknownPermissionKeys, } from "./permission-keys.js";
111
113
  export { asFirstWord, commandWords, liftProfile, profileFree, refuseCommandName, rootOf, takesProfile, usableProfileName, } from "./profile.js";
114
+ export { ProfileTokenStore } from "./profile-token.js";
112
115
  export { createProgram, run } from "./program.js";
113
116
  export { projectAnswerParts, projectCutoffTime, projectEvidenceText, projectWindowOf, withSyncCommands, } from "./project-evidence.js";
114
117
  export { projectStatusAnswer, projectStatusRow, projectStatusSchema, projectStatusText, } from "./project-status.js";
@@ -0,0 +1,29 @@
1
+ import { type CredentialSource, type KeyringStore, type StoredCredential } from "@wirecat/cli-base";
2
+ import { type AppIdentity } from "../ports/app.js";
3
+ export type TokenStorage = "keyring" | "file";
4
+ export interface ProfileTokenStoreOptions {
5
+ app: AppIdentity;
6
+ env?: NodeJS.ProcessEnv;
7
+ keyring?: KeyringStore;
8
+ /** Where the one warning about an unreachable keyring goes; stderr when left out. */
9
+ warn?: (message: string) => void;
10
+ }
11
+ /**
12
+ * One API token per profile for a CLI that is not a messenger: `<PREFIX>_TOKEN`, then the keyring entry
13
+ * `token:<profile>` under the app's own service, then a 0600 file (WC-SECR-4). A run with moved folders reads the
14
+ * owner's entry and never replaces or deletes it: it writes a temporary `<app>:<config folder>` entry instead
15
+ * (WC-SECR-24, cli-base `Credentials`).
16
+ */
17
+ export declare class ProfileTokenStore {
18
+ #private;
19
+ readonly variable: string;
20
+ constructor({ app, env, keyring, warn }: ProfileTokenStoreOptions);
21
+ read(profile: string): StoredCredential | undefined;
22
+ /** `file` also forgets the keyring copy, so a later read cannot find the token the owner asked to keep elsewhere. */
23
+ write(profile: string, token: string, storage?: TokenStorage): CredentialSource;
24
+ remove(profile: string): CredentialSource[];
25
+ /** The profile's token, or the one "not signed in" refusal every token CLI gives, naming the command to fix it. */
26
+ need(profile: string): string;
27
+ /** For `appMcpCommand`'s `signedIn`: a keyring that cannot be read counts as not signed in. */
28
+ signedIn(profile: string): boolean;
29
+ }
@@ -0,0 +1,65 @@
1
+ import { CliError, Credentials, isMovedRun, resolvePaths, } from "@wirecat/cli-base";
2
+ import { envName } from "../ports/app.js";
3
+ /**
4
+ * One API token per profile for a CLI that is not a messenger: `<PREFIX>_TOKEN`, then the keyring entry
5
+ * `token:<profile>` under the app's own service, then a 0600 file (WC-SECR-4). A run with moved folders reads the
6
+ * owner's entry and never replaces or deletes it: it writes a temporary `<app>:<config folder>` entry instead
7
+ * (WC-SECR-24, cli-base `Credentials`).
8
+ */
9
+ export class ProfileTokenStore {
10
+ variable;
11
+ #app;
12
+ #options;
13
+ #credentials;
14
+ constructor({ app, env = process.env, keyring, warn }) {
15
+ const where = { appName: app.appName, prefix: app.envPrefix, env };
16
+ this.#app = app;
17
+ this.variable = envName(app, "TOKEN");
18
+ this.#options = {
19
+ configDir: resolvePaths(where).config,
20
+ service: app.appName,
21
+ envVar: this.variable,
22
+ isolated: isMovedRun(where),
23
+ env,
24
+ ...(keyring ? { keyring } : {}),
25
+ warn: warn ?? ((message) => process.stderr.write(`${message}\n`)),
26
+ };
27
+ this.#credentials = new Credentials(this.#options);
28
+ }
29
+ read(profile) {
30
+ return this.#credentials.read(accountOf(profile));
31
+ }
32
+ /** `file` also forgets the keyring copy, so a later read cannot find the token the owner asked to keep elsewhere. */
33
+ write(profile, token, storage = "keyring") {
34
+ if (storage === "keyring")
35
+ return this.#credentials.write(accountOf(profile), token, { signIn: true });
36
+ const kept = new Credentials({ ...this.#options, storage: "file" }).write(accountOf(profile), token);
37
+ try {
38
+ new Credentials({ ...this.#options, storage: "keyring" }).remove(accountOf(profile));
39
+ }
40
+ catch {
41
+ // No keyring on this computer: there is no copy to forget.
42
+ }
43
+ return kept;
44
+ }
45
+ remove(profile) {
46
+ return this.#credentials.remove(accountOf(profile));
47
+ }
48
+ /** The profile's token, or the one "not signed in" refusal every token CLI gives, naming the command to fix it. */
49
+ need(profile) {
50
+ const stored = this.read(profile);
51
+ if (stored)
52
+ return stored.secret;
53
+ throw new CliError("authentication_error", `profile ${profile} is not signed in — run \`${this.#app.command} ${profile} session start\``, { reason: "session.missing" });
54
+ }
55
+ /** For `appMcpCommand`'s `signedIn`: a keyring that cannot be read counts as not signed in. */
56
+ signedIn(profile) {
57
+ try {
58
+ return this.read(profile) !== undefined;
59
+ }
60
+ catch {
61
+ return false;
62
+ }
63
+ }
64
+ }
65
+ const accountOf = (profile) => `token:${profile}`;
@@ -20,7 +20,7 @@ import { commandAvailability } from "./command-availability.js";
20
20
  import { commandPathOf } from "./command-contract.js";
21
21
  import { entityRows } from "./compact.js";
22
22
  import { outputFor, provide } from "./context.js";
23
- import { refuseByCommandPermissions, refuseWriteBeforeConnecting } from "./early-refusal.js";
23
+ import { refuseByCommandPermissions, refuseOfflineCommand, refuseWriteBeforeConnecting } from "./early-refusal.js";
24
24
  import { admittedUnderLock, changesAuthorityAt, changesAuthorityNow, isLogin, isStoreChange, judgedEffects, judgedTargets, storeChangeRefusal, } from "./effects.js";
25
25
  import { itemOf, renderAnswer, snakeKeys } from "./envelope.js";
26
26
  import { byteCount, DEFAULT_AGENT_COOPERATIVE_MS, DEFAULT_COMMAND_MS, DEFAULT_COOPERATIVE_MS, DEFAULT_OUTPUT_BYTES, DEFAULT_SYNC_MS, execution, } from "./execution.js";
@@ -287,7 +287,8 @@ const runOnce = async (argv, definition, options) => {
287
287
  const headless = machine || flags.input === false || Boolean(commandEnv.CI) || (options.tty ?? process.stdout.isTTY) !== true;
288
288
  checkJson(action, requested, !flags.jsonl && (options.tty ?? process.stdout.isTTY) === true);
289
289
  control.configure({
290
- ...(flags.fields === undefined ? {} : { fields: flags.fields }),
290
+ // Beside `--format csv`, `--json=a,b` names the table's columns: a CSV is no JSON to pick fields from.
291
+ ...(flags.fields === undefined || action.getOptionValue("format") === "csv" ? {} : { fields: flags.fields }),
291
292
  maxOutputBytes: flags.maxOutputBytes === undefined
292
293
  ? machine || (options.tty ?? process.stdout.isTTY) !== true
293
294
  ? DEFAULT_OUTPUT_BYTES
@@ -304,6 +305,7 @@ const runOnce = async (argv, definition, options) => {
304
305
  const localPreview = action.options.some((option) => option.long === "--dry-run");
305
306
  if (flags.dryRun && localPreview)
306
307
  action.setOptionValue("dryRun", true);
308
+ refuseOfflineCommand(action, definition.app, flags.offline === true, flags.dryRun === true && localPreview);
307
309
  const path = commandPathOf(action);
308
310
  const lock = readOnlyLockOf(definition.app, commandEnv);
309
311
  const input = options.stdin ?? process.stdin;
@@ -0,0 +1,23 @@
1
+ import { type Command, Option } from "commander";
2
+ import type { CrmField } from "../../domain/crm.js";
3
+ /**
4
+ * `--format csv`: `--format` is the vocabulary's output choice, so no CLI's command lint needs a new word. Off MCP: a
5
+ * table carries no `untrusted` marker for an agent.
6
+ */
7
+ export declare const csvFormatOption: () => Option;
8
+ /** What a page of deals or leads gives the table: its rows as `--json` answers them, and the CRM's own fields. */
9
+ export interface CsvPage {
10
+ items: Record<string, unknown>[];
11
+ fields: CrmField[];
12
+ page: number;
13
+ hasMore: boolean;
14
+ }
15
+ /**
16
+ * Reads a page in the profile's run, closes it, then prints the table: stdout carries the CSV and nothing else, and
17
+ * the way to the next page goes to stderr.
18
+ */
19
+ export declare const renderCsv: <R extends {
20
+ close?: () => Promise<void>;
21
+ }>(command: Command, open: (command: Command, access: {
22
+ readOnly: boolean;
23
+ }) => Promise<R>, read: (run: R) => Promise<CsvPage>) => Promise<void>;