insightcrm 0.1.11 → 0.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,6 +22,7 @@ crm skill # 打印给 agent 的使用说明;在 age
22
22
 
23
23
  - `--json` 时 stdout 只有一个 JSON 对象,过程信息走 stderr。
24
24
  - 退出码:`0` 成功 · `1` 出错 · `2` 用法或输入不合法 · `3` 认证 · `4` 限流 · `5` 冲突。
25
+ - 限流按人计(Web 和 CLI 共用一份配额):读 300 次/分钟、写 240 次/分钟。撞到时按响应里的 `Retry-After` 等几秒再继续。
25
26
  - 环境变量:`CRM_API_URL`、`CRM_TOKEN`、`CRM_SERVER`、`CRM_JSON=1`、`CRM_LANG`。
26
27
  - 可自定义的 prompt 模板(抽取规则、起草消息等):`crm prompts list`。
27
28
 
package/SKILL.md CHANGED
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: insightcrm
3
- description: Record and look up customers in InsightCRM with the `crm` CLI. Use when the user pastes a chat log, WeChat Moments / social screenshots, a business card or meeting notes and wants the person filed as a customer profile; asks to update an existing customer; asks who to follow up with today; or wants to reuse phrasings ("hooks") that worked on other customers.
3
+ description: Record and look up customers in InsightCRM with the `crm` CLI. Use when the user pastes a chat log, WeChat Moments / social screenshots, a business card or meeting notes and wants the person filed as a customer profile; asks to update an existing customer; asks who to follow up with today; asks when a customer's status or potential changed; or wants to reuse phrasings ("hooks") that worked on other customers.
4
4
  ---
5
5
 
6
6
  # 用 crm 管理客户档案
@@ -29,10 +29,13 @@ crm login https://<服务器地址>
29
29
  echo '{"name":"王小明","company":"ACME","conversionPotential":"High", ...}' | crm add - --json
30
30
  ```
31
31
  5. **复述结果**:把写入的 `id`、姓名和关键字段告诉用户,让他核对。
32
+ 6. **被问到「什么时候变的」**:用 `crm history <id> --json`(见下面「变更历史」)。这是唯一能给出时间线的入口,不要靠 `capturedAt` 或 `relationships` 的数组顺序猜。
32
33
 
33
34
  所有命令加 `--json` 后,stdout 只有**一个** JSON 对象,过程信息在 stderr。失败时是 `{"error":{"code","message"}}`。
34
35
 
35
- 退出码:`0` 成功 · `1` 出错 · `2` 用法或输入不合法 · `3` 认证(没登录、邮箱未验证) · `4` 被限流 · `5` 冲突或被拒绝。
36
+ 退出码:`0` 成功 · `1` 出错 · `2` 用法或输入不合法 · `3` 认证或被拒(没登录、邮箱未验证、权限不足——服务端回 403 就是这个) · `4` 被限流 · `5` 冲突。
37
+
38
+ **退出码 4(被限流)**:服务端按人限速——读 300 次/分钟、写 240 次/分钟,Web 和 CLI 共用同一份配额。批量录入几百条时容易撞到:按响应里的 `Retry-After` 等几秒再继续,**不要并发轰**。**已经写成功的不用重写**:先用 `crm search` 查一下哪些已经进去了,重跑会造出重复档案。
36
39
 
37
40
  ## 怎么从材料里抽取
38
41
 
@@ -61,7 +64,7 @@ crm login https://<服务器地址>
61
64
  - 常见路径:潜客 → 意向学员 → 学员 → 校友 → 意向甲方 → 甲方。
62
65
  - **微信标签里写明的身份最硬**(「AI编程 N23 期学员」就是学员)。注意区分:职位(产品经理、老师)不是关系,别混进 `title` 和 `relationships`。
63
66
  - 转化了**追加**新关系,别删旧的——学员变甲方,两个都留着,路径才追得回。
64
- - 没有依据就留空,不要编。命令行写法:`--relationship 学员 甲方`。
67
+ - 没有依据就留空,不要编。命令行写法:`--relationship 学员 甲方`(加引号写成 `--relationship "学员 甲方"` 也一样,CLI 会拆开)。
65
68
 
66
69
  **单位 `orgs`**:这个人挂着的**所有**机构——公司、学校、协会、平台、实验室。
67
70
  - 元素形如 `{"org":"同济大学建筑与城市规划学院","role":"在职教师","status":"current"}`。`role` 是在这个机构里的身份 / 职位(自由文本);`status` 是受控词表。
@@ -72,14 +75,15 @@ crm login https://<服务器地址>
72
75
  - 材料里没出现就整条省略,**不要编造**。命令行写法:`--org "同济大学:在职教师:在职" "浙江理工大学:博士在读:在读"`(机构名:身份:状态,身份可省略)。
73
76
 
74
77
  **相关人物 `relatedPeople`**:这个人牵连到的**其他人**——人与人之间的关系。
75
- - 元素形如 `{"name":"李雅婷","relation":"转介绍人","note":"07-15 发了她的名片说「这位同事推荐的」"}`。`name` 必填;`id` 和 `note` 选填。
78
+ - 元素形如 `{"name":"李雅婷","wechatId":"TwinkleAurora","relation":"转介绍人","note":"07-15 发了她的名片说「这位同事推荐的」"}`。`name` 必填;`wechatId` / `id` / `note` 选填。
76
79
  - **跟 `relationships` 不是一回事**:`relationships` 是「这个人在我这里是什么身份」(对我),`relatedPeople` 是「人与人之间」(对内)。别把两者混着填。
77
80
  - `relation` 是**自由文本**,不是受控词表。推荐写法:转介绍人 / 被转介绍人 / 对接协调方 / 拍板决策人 / 同场协作 / 同场竞争 / 同事 / 同学 / 导师 / 师傅 / 联合创始人 / 团队成员 / 投资人 / 介绍人。材料里没有的关系**不要编**。
78
- - `id` 可以省略:省略后服务端会按**同一用户名下唯一同名**自动补上。**库外的人**(导师、师傅、联合创始人、团队成员……)只留名字就行,照样要记。
79
- - **名字要照抄材料里的写法**,不要合并全名和简称。同名多人时服务端宁可不补 id,也不要指错人——所以靠 id 或全名才可靠,靠字符串匹配会误命中(库里有「谢」和另一个叫「谢扬」的人)。
81
+ - `id` 可以省略:省略后服务端按 **id > 微信号 > 唯一同名** 的顺序自动补上。**库外的人**(导师、师傅、联合创始人、团队成员……)只留名字就行,照样要记。
82
+ - **`wechatId` 优先填**:微信号是这条链上唯一干净的标识。客户档案的 `name` 常带注释(「李雅婷 猫屿meow」),相关人物写的又是短名(「李雅婷」),两边语义不对齐,姓名精确匹配几乎打不中;同名多人时只有微信号能分出是哪一位。**材料里出现了对方的微信号就填上**——同一个账号下微信号唯一,填错会被服务端拒。服务端**写了微信号但对不上就留空,不退回按姓名猜**。
83
+ - **名字要照抄材料里的写法**,不要合并全名和简称。同名多人时服务端宁可不补 id,也不要指错人——所以靠微信号或 id 才可靠,靠字符串匹配会误命中(库里有「谢」和另一个叫「谢扬」的人)。
80
84
  - **按人筛是包含匹配**:`crm list --related 谢` 会把「老谢」「谢扬」这些不同的人一起带出来。要精确指某一个人,用全名或看档案里的 `relatedPeople.id`。
81
85
  - **典型要记的场景**:谁把谁介绍来的、谁在中间做推进、谁跟谁一起做过事、谁跟谁在抢同一批名额。
82
- - 材料里没出现就整条省略,**不要编造**。命令行写法:`--related "李雅婷:转介绍人" "柴老师:导师"`(姓名:关系,关系必填,说明可省略)。
86
+ - 材料里没出现就整条省略,**不要编造**。命令行写法:`--related "李雅婷:转介绍人" "柴老师:导师"`(姓名:关系,关系必填,说明可省略);带微信号写 `--related "李雅婷:转介绍人:wx=TwinkleAurora"`(第 3 段以 `wx=` 开头就是微信号,第 4 段起是说明)。
83
87
 
84
88
  **日程 `upcomingEvents`**:`{title, date, type}` 的数组,`date` 是 `YYYY-MM-DD`,`type` 是 `meeting` / `follow_up` / `deadline` / `other`。
85
89
  - 今天是几号要自己确认,相对日期(「下周三」)按今天换算成具体日期。
@@ -154,6 +158,21 @@ crm list --related 李雅婷 --json # 和李雅婷有关系的人
154
158
  crm get <id> --json
155
159
  ```
156
160
 
161
+ ## 变更历史(这个客户什么时候被改过)
162
+
163
+ 服务端记录每次改动**改了哪些字段、旧值和新值**。用它回答「这个人什么时候从潜客变成学员」「潜力是什么时候升上去的」「哪一次改动把机构加上的」。
164
+
165
+ ```bash
166
+ crm history <id> --json # 某个客户的变更时间线(按时间正序)
167
+ crm history --all --json # 全局身份迁移:谁的主身份从什么变成了什么,凭哪条审计记录
168
+ ```
169
+
170
+ 每条记录带 `id`(就是审计记录的 id,可据此回溯)、`action`、`source`、`createdAt`、`fields`,以及 `diff`——**只含真正变了的字段**,每个是 `{before, after}`。长文本(备注、摘要、下一步动作)会截断到 500 字并标 `truncated`,这时 `before`/`after` 不是完整原文。
171
+
172
+ 只记**真正变了**的字段:归一化后等价的写法(写「甲方」vs 写 `client`)判定为没变,不进 diff;没传的字段也不进。
173
+
174
+ **记录只从启用变更留痕之后开始。** 起点之前发生过什么查不出来——**「没有记录」不等于「没有变过」**。`crm history --all` 会给出 `recordStart`(最早一条记录的时间),引用这个结论时必须一起说明。
175
+
157
176
  ## 体检(`crm lint`)
158
177
 
159
178
  写入路径对拿不准的值是**刻意宽松**的:认不出来的 `orgs.status`、清单外的城市、过期日期都原样保留、不报错,
@@ -166,7 +185,10 @@ crm lint --kind company-prose --json # 只看某一类
166
185
  ```
167
186
 
168
187
  报告的类别:`notes-over-limit`(会被服务端拒)、`notes-long`、`unknown-status`(状态不在受控词表里,按状态聚合会漏)、
169
- `expired-event`(过期日程)、`dangling-related-id`(相关人物指向库里没有的人)、`duplicate-wechat`、
188
+ `expired-event`(过期日程)、`dangling-related-id`(相关人物指向库里没有的人)、
189
+ `related-ambiguous`(相关人物没写 id 也没写微信号,而它的名字在库里有 ≥2 个同名客户——指哪一位说不准)、
190
+ `related-wechat-unmatched`(相关人物写了微信号,但库里查不到这个号——可能拼错了,也可能对方还没入库)、
191
+ `duplicate-wechat`、`name-annotated`(姓名栏塞了注释性括号)、
170
192
  `company-prose`(company 写成了说明文而不是简称)、`company-without-orgs`、`orgs-without-company`、
171
193
  `no-relationship`(不知道这个人是谁)、`city-off-list`、`half-width-punctuation`。
172
194
 
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import { readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
11
11
  import { hostname as hostname3, platform } from "os";
12
12
  import { fileURLToPath } from "url";
13
13
  import { createInterface } from "readline/promises";
14
- import { Command, Option } from "commander";
14
+ import { Command, CommanderError, Option } from "commander";
15
15
 
16
16
  // ../shared/src/constants.ts
17
17
  var CONVERSION_POTENTIALS = ["High", "Medium", "Low"];
@@ -185,6 +185,7 @@ var ORG_STATUSES = [
185
185
  "unknown"
186
186
  // 未明示:只知道有这么个机构,关系待确认
187
187
  ];
188
+ var AUDIT_SOURCES = ["web", "cli", "mcp"];
188
189
  var EXIT = {
189
190
  ok: 0,
190
191
  error: 1,
@@ -195,10 +196,6 @@ var EXIT = {
195
196
  };
196
197
  var VERIFY_LINK_TTL_MS = 72 * 60 * 60 * 1e3;
197
198
  var RESET_LINK_TTL_MS = 24 * 60 * 60 * 1e3;
198
- var CLI_AUTH = {
199
- ttlMs: 10 * 60 * 1e3,
200
- pollIntervalSec: 3
201
- };
202
199
 
203
200
  // ../shared/src/city.ts
204
201
  var CITY_ALIASES = {
@@ -541,6 +538,7 @@ function normalizeRelationship(input2) {
541
538
  if (!cleaned) return "";
542
539
  return LOOKUP3.get(cleaned.toLowerCase()) ?? cleaned;
543
540
  }
541
+ var isKnownRelationship = (input2) => RELATIONSHIPS.includes(normalizeRelationship(input2));
544
542
  var RELATIONSHIP_LABELS = {
545
543
  lead: { zh: "\u6F5C\u5BA2", en: "Lead" },
546
544
  student_intent: { zh: "\u610F\u5411\u5B66\u5458", en: "Prospective student" },
@@ -643,6 +641,11 @@ function normalizeRelatedRelation(input2) {
643
641
  return input2.replace(/[ \s]+/g, " ").trim();
644
642
  }
645
643
 
644
+ // ../shared/src/wechat.ts
645
+ function wechatKey(input2) {
646
+ return (input2 ?? "").replace(/\s+/g, "").trim().toLowerCase();
647
+ }
648
+
646
649
  // ../shared/src/profile.ts
647
650
  var NOTES_MAX = 1e4;
648
651
  var NOTES_LONG = 6e3;
@@ -656,6 +659,12 @@ function nameProblem(name) {
656
659
  if (/[((][^))]*(微信|昵称|显示名|备注|手机|邮箱|真名|未知)/.test(n)) return `name \u91CC\u5E26\u4E86\u6CE8\u91CA\u6027\u62EC\u53F7\u3002${hint}`;
657
660
  return null;
658
661
  }
662
+ function stripNameAnnotation(name) {
663
+ const n = (name ?? "").trim();
664
+ if (!n) return "";
665
+ const at = n.search(/[((]/);
666
+ return (at === -1 ? n : n.slice(0, at)).trim();
667
+ }
659
668
  var CJK = /[一-鿿]/g;
660
669
  function isProseCompany(company) {
661
670
  const c = (company ?? "").trim();
@@ -20405,6 +20414,11 @@ var orgLink = external_exports.object({
20405
20414
  var relatedPerson = external_exports.object({
20406
20415
  name: external_exports.string().trim().min(1).max(100).transform(normalizeRelatedName),
20407
20416
  id: external_exports.string().trim().max(64).nullable().optional(),
20417
+ /**
20418
+ * 对方微信号。这条链上唯一可靠的标识:同一个账号下微信号不重复,
20419
+ * 同名不同人时靠它分出是哪一位。对方不在库里也可以记——将来入库能自动对上。
20420
+ */
20421
+ wechatId: external_exports.string().trim().min(1).max(100).nullable().optional(),
20408
20422
  relation: external_exports.string().trim().min(1).max(100).transform(normalizeRelatedRelation),
20409
20423
  note: external_exports.string().trim().max(500).nullable().optional()
20410
20424
  });
@@ -20466,7 +20480,7 @@ var recommendationCreate = external_exports.object({
20466
20480
  isEnabled: external_exports.boolean().optional()
20467
20481
  });
20468
20482
  var recommendationPatch = recommendationCreate.partial();
20469
- var ENTITIES = ["customer", "hook", "rec"];
20483
+ var ENTITIES = ["customer", "hook", "rec", "history"];
20470
20484
  var eventFields = [
20471
20485
  { name: "title", type: "string", required: true, guide: "\u4E8B\u4EF6\u540D\uFF0C\u5982\u300C\u4EA7\u54C1\u6F14\u793A\u300D\u300C\u62A5\u4EF7\u622A\u6B62\u300D" },
20472
20486
  { name: "date", type: "date", required: true, guide: "YYYY-MM-DD\u3002\u53EA\u5199\u5BF9\u8BDD\u91CC\u660E\u786E\u51FA\u73B0\u6216\u80FD\u786E\u5B9A\u7684\u65E5\u671F\uFF0C\u4E0D\u8981\u731C" },
@@ -20500,7 +20514,8 @@ var orgFields = [
20500
20514
  ];
20501
20515
  var relatedFields = [
20502
20516
  { name: "name", type: "string", required: true, guide: "\u5BF9\u65B9\u59D3\u540D\u3002\u6750\u6599\u91CC\u51FA\u73B0\u7684\u4EBA\u540D\u7167\u6284\uFF0C\u4E0D\u8981\u6539\u5199\u6210\u5173\u7CFB\u79F0\u8C13" },
20503
- { name: "id", type: "string", nullable: true, guide: "\u5BF9\u65B9\u5728 CRM \u91CC\u7684\u5BA2\u6237 id\u3002\u5BF9\u65B9\u4E0D\u5728\u5E93\u91CC\u5C31\u7701\u7565\uFF1B\u7559\u7A7A\u4E14\u5E93\u91CC\u6709\u552F\u4E00\u540C\u540D\u7684\u5BA2\u6237\u65F6\u670D\u52A1\u7AEF\u4F1A\u81EA\u52A8\u8865\u4E0A" },
20517
+ { name: "wechatId", type: "string", nullable: true, guide: "\u5BF9\u65B9\u5FAE\u4FE1\u53F7\u3002\u8FD9\u6761\u94FE\u4E0A\u552F\u4E00\u53EF\u9760\u7684\u6807\u8BC6\uFF1A\u540C\u4E00\u4E2A\u8D26\u53F7\u4E0B\u5FAE\u4FE1\u53F7\u4E0D\u91CD\u590D\uFF0C\u540C\u540D\u4E0D\u540C\u4EBA\u65F6\u9760\u5B83\u5206\u51FA\u662F\u54EA\u4E00\u4F4D\u3002\u6750\u6599\u91CC\u51FA\u73B0\u4E86\u5BF9\u65B9\u7684\u5FAE\u4FE1\u53F7\u5C31\u586B\u4E0A\u2014\u2014\u6CA1\u6709\u5B83\uFF0C\u670D\u52A1\u7AEF\u53EA\u80FD\u6309\u59D3\u540D\u731C\uFF0C\u731C\u4E0D\u4E2D\u5C31\u7559\u7A7A" },
20518
+ { name: "id", type: "string", nullable: true, guide: "\u5BF9\u65B9\u5728 CRM \u91CC\u7684\u5BA2\u6237 id\u3002\u5BF9\u65B9\u4E0D\u5728\u5E93\u91CC\u5C31\u7701\u7565\uFF1B\u7559\u7A7A\u65F6\u670D\u52A1\u7AEF\u6309\u300C\u5FAE\u4FE1\u53F7 \u2192 \u552F\u4E00\u540C\u540D\u300D\u7684\u987A\u5E8F\u81EA\u52A8\u8865\u4E0A\uFF0C\u4E24\u4E2A\u90FD\u5BF9\u4E0D\u4E0A\u624D\u7559\u7A7A" },
20504
20519
  { name: "relation", type: "string", required: true, guide: "\u4ECE\u672C\u6761\u89C6\u89D2\u770B\u7684\u5173\u7CFB\uFF0C\u81EA\u7531\u6587\u672C\u3002\u63A8\u8350\u5199\u6CD5\uFF1A\u8F6C\u4ECB\u7ECD\u4EBA / \u88AB\u8F6C\u4ECB\u7ECD\u4EBA / \u5BF9\u63A5\u534F\u8C03\u65B9 / \u62CD\u677F\u51B3\u7B56\u4EBA / \u540C\u573A\u534F\u4F5C / \u540C\u573A\u7ADE\u4E89 / \u540C\u4E8B / \u540C\u5B66 / \u5BFC\u5E08 / \u5E08\u5085 / \u8054\u5408\u521B\u59CB\u4EBA / \u56E2\u961F\u6210\u5458 / \u6295\u8D44\u4EBA" },
20505
20520
  { name: "note", type: "string", nullable: true, guide: "\u4E00\u53E5\u8BDD\u8BF4\u660E\u8FD9\u6761\u5173\u7CFB\u7684\u6765\u9F99\u53BB\u8109\uFF0C\u5982\u300C07-15 \u53D1\u5979\u7684\u540D\u7247\u8BF4\u300E\u8FD9\u4F4D\u540C\u4E8B\u63A8\u8350\u7684\u300F\u300D" }
20506
20521
  ];
@@ -20535,7 +20550,7 @@ var SCHEMA = {
20535
20550
  name: "relatedPeople",
20536
20551
  type: "object[]",
20537
20552
  fields: relatedFields,
20538
- guide: "\u76F8\u5173\u4EBA\u7269\uFF1A\u8FD9\u4E2A\u4EBA\u7275\u8FDE\u5230\u7684\u5176\u4ED6\u4EBA\u3002\u8DDF relationships\uFF08\u8FD9\u4E2A\u4EBA\u5728\u6211\u8FD9\u91CC\u662F\u4EC0\u4E48\u8EAB\u4EFD\uFF09\u4E0D\u662F\u4E00\u56DE\u4E8B\u2014\u2014\u90A3\u662F\u300C\u5BF9\u7528\u6237\u300D\u7684\u5173\u7CFB\uFF0C\u8FD9\u662F\u300C\u4EBA\u4E0E\u4EBA\u4E4B\u95F4\u300D\u7684\u5173\u7CFB\u3002\u5143\u7D20\u5F62\u5982 {name:'\u674E\u96C5\u5A77', relation:'\u8F6C\u4ECB\u7ECD\u4EBA', note:'07-15 \u53D1\u5979\u7684\u540D\u7247\u8BF4\u300C\u8FD9\u4F4D\u540C\u4E8B\u63A8\u8350\u7684\u300D'}\u3002\u8981\u8BB0\u7684\u5178\u578B\u573A\u666F\uFF1A\u8C01\u628A\u8C01\u4ECB\u7ECD\u6765\u7684\u3001\u8C01\u5728\u4E2D\u95F4\u505A\u63A8\u8FDB\u3001\u8C01\u8DDF\u8C01\u4E00\u8D77\u505A\u8FC7\u4E8B\u3001\u8C01\u8DDF\u8C01\u5728\u62A2\u540C\u4E00\u6279\u540D\u989D\u3002\u5BFC\u5E08\u3001\u5E08\u5085\u3001\u8054\u5408\u521B\u59CB\u4EBA\u3001\u56E2\u961F\u6210\u5458\u8FD9\u4E9B\u4E0D\u5728 CRM \u91CC\u7684\u4EBA\u4E5F\u8981\u8BB0\uFF0C\u53EA\u7559\u540D\u5B57\u5373\u53EF\u3002relation \u662F\u81EA\u7531\u6587\u672C\uFF0C\u4E0D\u8981\u7F16\u9020\u6750\u6599\u91CC\u6CA1\u6709\u7684\u5173\u7CFB\u3002\u66F4\u65B0\u65F6\u4F20\u5165\u5B8C\u6574\u5217\u8868\u4F1A\u6574\u4F53\u66FF\u6362\u65E7\u5217\u8868\uFF1B\u4E0D\u4F20\u5219\u4E0D\u52A8\u3002"
20553
+ guide: "\u76F8\u5173\u4EBA\u7269\uFF1A\u8FD9\u4E2A\u4EBA\u7275\u8FDE\u5230\u7684\u5176\u4ED6\u4EBA\u3002\u8DDF relationships\uFF08\u8FD9\u4E2A\u4EBA\u5728\u6211\u8FD9\u91CC\u662F\u4EC0\u4E48\u8EAB\u4EFD\uFF09\u4E0D\u662F\u4E00\u56DE\u4E8B\u2014\u2014\u90A3\u662F\u300C\u5BF9\u7528\u6237\u300D\u7684\u5173\u7CFB\uFF0C\u8FD9\u662F\u300C\u4EBA\u4E0E\u4EBA\u4E4B\u95F4\u300D\u7684\u5173\u7CFB\u3002\u5143\u7D20\u5F62\u5982 {name:'\u674E\u96C5\u5A77', wechatId:'TwinkleAurora', relation:'\u8F6C\u4ECB\u7ECD\u4EBA', note:'07-15 \u53D1\u5979\u7684\u540D\u7247\u8BF4\u300C\u8FD9\u4F4D\u540C\u4E8B\u63A8\u8350\u7684\u300D'}\u3002\u8981\u8BB0\u7684\u5178\u578B\u573A\u666F\uFF1A\u8C01\u628A\u8C01\u4ECB\u7ECD\u6765\u7684\u3001\u8C01\u5728\u4E2D\u95F4\u505A\u63A8\u8FDB\u3001\u8C01\u8DDF\u8C01\u4E00\u8D77\u505A\u8FC7\u4E8B\u3001\u8C01\u8DDF\u8C01\u5728\u62A2\u540C\u4E00\u6279\u540D\u989D\u3002\u5BFC\u5E08\u3001\u5E08\u5085\u3001\u8054\u5408\u521B\u59CB\u4EBA\u3001\u56E2\u961F\u6210\u5458\u8FD9\u4E9B\u4E0D\u5728 CRM \u91CC\u7684\u4EBA\u4E5F\u8981\u8BB0\uFF0C\u53EA\u7559\u540D\u5B57\u5373\u53EF\u3002relation \u662F\u81EA\u7531\u6587\u672C\uFF0C\u4E0D\u8981\u7F16\u9020\u6750\u6599\u91CC\u6CA1\u6709\u7684\u5173\u7CFB\u3002**\u6750\u6599\u91CC\u51FA\u73B0\u4E86\u5BF9\u65B9\u7684\u5FAE\u4FE1\u53F7\u5C31\u586B wechatId**\uFF1A\u59D3\u540D\u662F\u5F31\u6807\u8BC6\uFF08\u540C\u540D\u4E0D\u540C\u4EBA\u5206\u4E0D\u51FA\u6765\u3001\u5BA2\u6237\u6863\u6848\u91CC\u7684\u540D\u5B57\u5E38\u5E26\u6CE8\u91CA\uFF09\uFF0C\u5FAE\u4FE1\u53F7\u624D\u662F\u8FD9\u6761\u94FE\u4E0A\u552F\u4E00\u53EF\u9760\u7684\u6807\u8BC6\uFF1B\u670D\u52A1\u7AEF\u9760\u5B83\u628A\u76F8\u5173\u4EBA\u7269\u548C\u5BA2\u6237\u6863\u6848\u5BF9\u4E0A\uFF0C\u5BF9\u4E0D\u4E0A\u5C31\u5B81\u53EF\u7559\u7A7A\u3002\u66F4\u65B0\u65F6\u4F20\u5165\u5B8C\u6574\u5217\u8868\u4F1A\u6574\u4F53\u66FF\u6362\u65E7\u5217\u8868\uFF1B\u4E0D\u4F20\u5219\u4E0D\u52A8\u3002"
20539
20554
  },
20540
20555
  { name: "summary", type: "string", guide: "\u4E00\u6BB5\u8BDD\u6982\u62EC\u8FD9\u4E2A\u5BA2\u6237\u662F\u8C01\u3001\u5F53\u524D\u5904\u4E8E\u4EC0\u4E48\u9636\u6BB5" },
20541
20556
  { name: "painPoints", type: "string[]", guide: "\u75DB\u70B9\u6807\u7B7E\uFF0C\u6BCF\u6761\u7B80\u77ED\uFF08\u51E0\u4E2A\u5B57\u5230\u4E00\u53E5\u8BDD\uFF09\u3002\u540C\u4E00\u4E2A\u75DB\u70B9\u590D\u7528\u5DF2\u6709\u6807\u7B7E\u7684\u5199\u6CD5\uFF0C\u4FBF\u4E8E\u6309\u6807\u7B7E\u805A\u5408" },
@@ -20566,6 +20581,21 @@ var SCHEMA = {
20566
20581
  { name: "link", type: "string", nullable: true, guide: "\u7528\u6237\u7ED9\u7684\u94FE\u63A5\uFF1B\u6CA1\u6709\u5C31\u7701\u7565\uFF0C\u4E0D\u8981\u731C" },
20567
20582
  { name: "isEnabled", type: "boolean", guide: "\u662F\u5426\u542F\u7528\uFF08\u53C2\u4E0E\u63A8\u8350\uFF09\uFF0C\u9ED8\u8BA4 true" }
20568
20583
  ]
20584
+ },
20585
+ history: {
20586
+ description: "\u5BA2\u6237\u53D8\u66F4\u5386\u53F2\uFF08\u53EA\u8BFB\uFF0C\u4E0D\u80FD\u5199\uFF09\u3002\u4E00\u6761\u8BB0\u5F55 = \u4E00\u6B21\u6539\u52A8\uFF0C\u542B\u6539\u4E86\u54EA\u4E9B\u5B57\u6BB5\u4EE5\u53CA\u6BCF\u4E2A\u5B57\u6BB5\u7684\u65E7\u503C\u548C\u65B0\u503C\u3002\u7528\u5B83\u56DE\u7B54\u300C\u8FD9\u4E2A\u4EBA\u4EC0\u4E48\u65F6\u5019\u4ECE\u6F5C\u5BA2\u53D8\u6210\u5B66\u5458\u300D\u300C\u6F5C\u529B\u662F\u4EC0\u4E48\u65F6\u5019\u5347\u4E0A\u53BB\u7684\u300D\u3002\u8BB0\u5F55\u53EA\u4ECE\u542F\u7528\u53D8\u66F4\u7559\u75D5\u4E4B\u540E\u5F00\u59CB\uFF0C\u8D77\u70B9\u4E4B\u524D\u53D1\u751F\u8FC7\u4EC0\u4E48\u67E5\u4E0D\u51FA\u6765\u2014\u2014\u6CA1\u6709\u8BB0\u5F55\u4E0D\u7B49\u4E8E\u6CA1\u6709\u53D8\u8FC7\u3002",
20587
+ fields: [
20588
+ { name: "id", type: "uuid", required: true, guide: "\u8FD9\u6761\u53D8\u66F4\u7684\u5BA1\u8BA1\u8BB0\u5F55 id\uFF0C\u53EF\u636E\u6B64\u56DE\u6EAF\u5230\u5177\u4F53\u90A3\u4E00\u6761" },
20589
+ { name: "action", type: "string", required: true, guide: "customer.create=\u65B0\u5EFA\uFF0Ccustomer.update=\u6539\u8FC7\uFF0Ccustomer.delete=\u5220\u9664" },
20590
+ { name: "source", type: "enum", required: true, values: AUDIT_SOURCES, guide: "\u6539\u52A8\u6765\u81EA\u54EA\u4E2A\u5165\u53E3\uFF1Aweb=\u7F51\u9875\uFF0Ccli=\u547D\u4EE4\u884C\uFF0Cmcp=agent" },
20591
+ { name: "createdAt", type: "datetime", required: true, guide: "\u6539\u52A8\u53D1\u751F\u7684\u65F6\u523B\uFF08ISO 8601\uFF09" },
20592
+ { name: "fields", type: "string[]", required: true, guide: "\u8FD9\u6B21\u52A8\u8FC7\u7684\u5B57\u6BB5\u540D\u5217\u8868\uFF08\u6309\u5199\u5165\u65B9\u58F0\u660E\uFF0C\u53EF\u80FD\u542B\u5B9E\u9645\u6CA1\u53D8\u7684\u5B57\u6BB5\uFF09" },
20593
+ {
20594
+ name: "diff",
20595
+ type: "object",
20596
+ guide: "\u53EA\u542B\u771F\u6B63\u53D8\u4E86\u7684\u5B57\u6BB5\uFF0C\u6BCF\u4E2A\u662F {before, after}\uFF1B\u957F\u6587\u672C\u88AB\u622A\u65AD\u65F6\u5E26 truncated=true\uFF0C\u6B64\u65F6 before/after \u4E0D\u662F\u5B8C\u6574\u539F\u6587\u3002\u6CA1\u6709 diff \u7684\u8BB0\u5F55\u8868\u793A\u6539\u52A8\u53D1\u751F\u5728\u7559\u75D5\u4E4B\u524D\u3002"
20597
+ }
20598
+ ]
20569
20599
  }
20570
20600
  };
20571
20601
 
@@ -20630,7 +20660,7 @@ function renderPrompt(text, customer) {
20630
20660
  // package.json
20631
20661
  var package_default = {
20632
20662
  name: "insightcrm",
20633
- version: "0.1.11",
20663
+ version: "0.1.12",
20634
20664
  description: "Command line and agent skill for InsightCRM: file customers from chats and screenshots with your own AI agent. Non-interactive, --json output, stable exit codes.",
20635
20665
  license: "MIT",
20636
20666
  type: "module",
@@ -20690,7 +20720,7 @@ var CliError = class extends Error {
20690
20720
  exitCode;
20691
20721
  status;
20692
20722
  };
20693
- var exitFor = (status, code) => status === 401 || ["email_unverified", "banned", "access_denied", "expired_token", "forbidden", "bad_origin"].includes(code) ? EXIT.auth : status === 429 || code === "rate_limited" ? EXIT.quota : status === 400 ? EXIT.usage : status === 409 ? EXIT.failed : EXIT.error;
20723
+ var exitFor = (status, code) => status === 401 || status === 403 ? EXIT.auth : ["email_unverified", "banned", "access_denied", "expired_token", "forbidden", "bad_origin"].includes(code) ? EXIT.auth : status === 429 || code === "rate_limited" ? EXIT.quota : status === 400 ? EXIT.usage : status === 409 ? EXIT.failed : EXIT.error;
20694
20724
  function createClient(apiUrl, token) {
20695
20725
  async function call(method, p, body) {
20696
20726
  const headers = { "user-agent": `insightcrm-cli/${package_default.version}` };
@@ -20725,11 +20755,22 @@ function createClient(apiUrl, token) {
20725
20755
  deviceStart: (clientName) => call("POST", "/cli/device", { clientName }),
20726
20756
  deviceToken: (deviceCode) => call("POST", "/cli/device/token", { deviceCode }),
20727
20757
  schema: (entity) => call("GET", `/schema${qs({ entity })}`),
20728
- listCustomers: (f) => call("GET", `/customers${qs(f)}`),
20758
+ listCustomers: (f, p) => call(
20759
+ "GET",
20760
+ `/customers${qs({
20761
+ ...f,
20762
+ limit: p?.limit === void 0 ? void 0 : String(p.limit),
20763
+ offset: p?.offset === void 0 ? void 0 : String(p.offset)
20764
+ })}`
20765
+ ),
20729
20766
  getCustomer: (id) => call("GET", `/customers/${enc(id)}`),
20730
20767
  addCustomer: (body) => call("POST", "/customers", body),
20731
20768
  updateCustomer: (id, body) => call("PATCH", `/customers/${enc(id)}`, body),
20732
20769
  removeCustomer: (id) => call("DELETE", `/customers/${enc(id)}`),
20770
+ /** 变更历史:这个客户什么时候被改过、哪些字段变了 */
20771
+ customerHistory: (id) => call("GET", `/customers/${enc(id)}/history`),
20772
+ /** 身份迁移图的数据源:谁的主身份从什么变成了什么,凭哪条审计记录 */
20773
+ identityMigrations: () => call("GET", "/customers/migrations"),
20733
20774
  listHooks: (customerId) => call("GET", `/hooks${qs({ customerId })}`),
20734
20775
  addHook: (body) => call("POST", "/hooks", body),
20735
20776
  removeHook: (id) => call("DELETE", `/hooks/${enc(id)}`),
@@ -20749,11 +20790,19 @@ function lintCustomers(customers, today2) {
20749
20790
  const push = (c, kind, severity, detail2) => issues.push({ id: c.id, name: c.name, kind, severity, detail: detail2 });
20750
20791
  const byWechat = /* @__PURE__ */ new Map();
20751
20792
  for (const c of customers) {
20752
- const w = (c.wechatId ?? "").trim();
20753
- if (!w) continue;
20754
- const arr = byWechat.get(w);
20793
+ const k = wechatKey(c.wechatId);
20794
+ if (!k) continue;
20795
+ const arr = byWechat.get(k);
20796
+ if (arr) arr.push(c);
20797
+ else byWechat.set(k, [c]);
20798
+ }
20799
+ const byBaseName = /* @__PURE__ */ new Map();
20800
+ for (const c of customers) {
20801
+ const base = stripNameAnnotation(c.name).toLowerCase();
20802
+ if (!base) continue;
20803
+ const arr = byBaseName.get(base);
20755
20804
  if (arr) arr.push(c);
20756
- else byWechat.set(w, [c]);
20805
+ else byBaseName.set(base, [c]);
20757
20806
  }
20758
20807
  for (const c of customers) {
20759
20808
  const notesLen = (c.notes ?? "").length;
@@ -20779,10 +20828,20 @@ function lintCustomers(customers, today2) {
20779
20828
  }
20780
20829
  for (const p of c.relatedPeople ?? []) {
20781
20830
  if (p.id && !ids.has(p.id)) push(c, "dangling-related-id", "error", `relatedPeople[${p.name}].id=${p.id} \u6307\u5411\u5E93\u91CC\u4E0D\u5B58\u5728\u7684\u5BA2\u6237`);
20831
+ const wx = wechatKey(p.wechatId);
20832
+ if (!p.id && !wx) {
20833
+ const hits = byBaseName.get(p.name.trim().toLowerCase()) ?? [];
20834
+ if (hits.length >= 2) {
20835
+ push(c, "related-ambiguous", "warn", `relatedPeople[${p.name}] \u5E93\u91CC\u6709 ${hits.length} \u4E2A\u540C\u540D\u5BA2\u6237\uFF0C\u6307\u54EA\u4E00\u4F4D\u8BF4\u4E0D\u51C6\uFF1B\u8865\u4E0A\u5FAE\u4FE1\u53F7\uFF08wx=\u2026\uFF09\u5C31\u80FD\u5B9A\u4E0B\u6765`);
20836
+ }
20837
+ }
20838
+ if (wx && !byWechat.get(wx)?.length) {
20839
+ push(c, "related-wechat-unmatched", "info", `relatedPeople[${p.name}] \u7684\u5FAE\u4FE1\u53F7 ${p.wechatId} \u5728\u5E93\u91CC\u67E5\u4E0D\u5230`);
20840
+ }
20782
20841
  }
20783
20842
  const w = (c.wechatId ?? "").trim();
20784
- if (w && (byWechat.get(w)?.length ?? 0) > 1) {
20785
- push(c, "duplicate-wechat", "warn", `wechatId=${w} \u5728 ${byWechat.get(w).length} \u6761\u8BB0\u5F55\u4E0A\u91CD\u590D`);
20843
+ if (w && (byWechat.get(wechatKey(w))?.length ?? 0) > 1) {
20844
+ push(c, "duplicate-wechat", "warn", `wechatId=${w} \u5728 ${byWechat.get(wechatKey(w)).length} \u6761\u8BB0\u5F55\u4E0A\u91CD\u590D`);
20786
20845
  }
20787
20846
  const texts = [
20788
20847
  ["summary", c.summary ?? ""],
@@ -20855,10 +20914,43 @@ function parseRelated(s) {
20855
20914
  if (!name) throw new CliError("usage", `Can't read related person "${s}". Use name:relation, e.g. \u674E\u96C5\u5A77:\u8F6C\u4ECB\u7ECD\u4EBA`, EXIT.usage);
20856
20915
  const relation = parts[1] ?? "";
20857
20916
  if (!relation) throw new CliError("usage", `Can't read related person "${s}". Use name:relation, e.g. \u674E\u96C5\u5A77:\u8F6C\u4ECB\u7ECD\u4EBA`, EXIT.usage);
20858
- const note = parts.length > 2 ? parts.slice(2).join(":").trim() : "";
20859
- return { name, relation, ...note ? { note } : {} };
20917
+ let wechatId;
20918
+ let note = "";
20919
+ if (parts.length > 2) {
20920
+ const third = parts[2] ?? "";
20921
+ if (/^wx=/i.test(third)) {
20922
+ const raw = third.slice(3).trim();
20923
+ if (!raw) {
20924
+ throw new CliError("usage", `Can't read related person "${s}". wx= needs a wechat id, e.g. \u674E\u96C5\u5A77:\u8F6C\u4ECB\u7ECD\u4EBA:wx=TwinkleAurora`, EXIT.usage);
20925
+ }
20926
+ if (raw.length > 100) {
20927
+ throw new CliError("usage", `Wechat id for "${name}" is longer than 100 characters`, EXIT.usage);
20928
+ }
20929
+ wechatId = raw;
20930
+ note = parts.length > 3 ? parts.slice(3).join(":").trim() : "";
20931
+ } else {
20932
+ note = parts.slice(2).join(":").trim();
20933
+ }
20934
+ }
20935
+ return { name, relation, ...wechatId ? { wechatId } : {}, ...note ? { note } : {} };
20860
20936
  }
20861
20937
  var relatedKey = (p) => JSON.stringify([p.name, p.relation]);
20938
+ function mergeRelated(existing, added) {
20939
+ const out2 = existing.map((e) => ({ ...e }));
20940
+ for (const a of added) {
20941
+ const idx = out2.findIndex((e2) => relatedKey(e2) === relatedKey(a));
20942
+ if (idx === -1) {
20943
+ out2.push({ ...a });
20944
+ continue;
20945
+ }
20946
+ const e = out2[idx];
20947
+ const merged = { ...e };
20948
+ if (!merged.wechatId && a.wechatId) merged.wechatId = a.wechatId;
20949
+ if (!merged.note && a.note) merged.note = a.note;
20950
+ out2[idx] = merged;
20951
+ }
20952
+ return out2;
20953
+ }
20862
20954
 
20863
20955
  // src/prompts.ts
20864
20956
  import { mkdir as mkdir2, readFile as readFile2, writeFile as writeFile2 } from "fs/promises";
@@ -21001,7 +21093,7 @@ async function fetchLatestVersion(opts = {}) {
21001
21093
  }
21002
21094
 
21003
21095
  // src/cli.ts
21004
- var program = new Command().name("crm").description("InsightCRM command line: read and write your customer records. The AI lives in your agent, not here.").version(package_default.version).addOption(new Option("--json", "print one JSON object to stdout (also CRM_JSON=1)").default(process.env.CRM_JSON === "1")).option("-n, --server <name>", "use a saved server for this command (env CRM_SERVER); see `crm servers`").option("--api-url <url>", "server URL, overrides the saved one (env CRM_API_URL)").option("--token <token>", "API token, overrides the saved one (env CRM_TOKEN)").showHelpAfterError().addHelpText(
21096
+ var program = new Command().name("crm").description("InsightCRM command line: read and write your customer records. The AI lives in your agent, not here.").version(package_default.version).addOption(new Option("--json", "print one JSON object to stdout (also CRM_JSON=1)").default(process.env.CRM_JSON === "1")).option("-n, --server <name>", "use a saved server for this command (env CRM_SERVER); see `crm servers`").option("--api-url <url>", "server URL, overrides the saved one (env CRM_API_URL)").option("--token <token>", "API token, overrides the saved one (env CRM_TOKEN)").exitOverride().showHelpAfterError().addHelpText(
21005
21097
  "after",
21006
21098
  `
21007
21099
  Recommended workflow (for agents):
@@ -21011,6 +21103,7 @@ Recommended workflow (for agents):
21011
21103
  Before adding search <name> --json (avoid duplicates; if the customer exists, update instead of add)
21012
21104
  Record a customer add - --json < profile.json (or: add --name ... --potential High)
21013
21105
  Update update <id> --add-pain "budget" --add-event 2026-10-20:follow_up:send quote --json
21106
+ Change history history <id> --json (when this record changed, old value \u2192 new value; history --all for identity migrations)
21014
21107
  Audit the records lint --json (report dirty records; reports only, never writes)
21015
21108
  Reuse what works hook list --json (successful phrasings from other customers)
21016
21109
  Recommend rec list --json (the user's OWN inventory: pick what fits; add items only when the user asks, never from chat)
@@ -21038,6 +21131,11 @@ Examples:
21038
21131
  $ crm export -o backup.json`
21039
21132
  );
21040
21133
  var g = () => program.opts();
21134
+ var jsonRequested = () => g().json === true || process.argv.includes("--json") || process.env.CRM_JSON === "1";
21135
+ function writeJsonError(code, message) {
21136
+ process.stdout.write(`${JSON.stringify({ error: { code, message } })}
21137
+ `);
21138
+ }
21041
21139
  function out(human, data) {
21042
21140
  if (g().json) process.stdout.write(`${JSON.stringify(data)}
21043
21141
  `);
@@ -21060,6 +21158,16 @@ async function client(requireToken = true) {
21060
21158
  }
21061
21159
  return createClient(apiUrl, token);
21062
21160
  }
21161
+ var LIST_PAGE_SIZE = 500;
21162
+ async function fetchAllCustomers(api, f) {
21163
+ const all = [];
21164
+ for (let offset = 0; ; offset += LIST_PAGE_SIZE) {
21165
+ const r = await api.listCustomers(f, { limit: LIST_PAGE_SIZE, offset });
21166
+ all.push(...r.customers);
21167
+ if (r.customers.length < LIST_PAGE_SIZE || all.length >= r.total) break;
21168
+ }
21169
+ return all;
21170
+ }
21063
21171
  var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
21064
21172
  function openBrowser(url2) {
21065
21173
  const [cmd, args] = platform() === "darwin" ? ["open", [url2]] : platform() === "win32" ? ["cmd", ["/c", "start", "", url2]] : ["xdg-open", [url2]];
@@ -21109,10 +21217,14 @@ function parseSocial(s) {
21109
21217
  if (!platform2 || !handle) throw new CliError("usage", `Can't read social "${s}". Use platform:handle, e.g. channels:@san or email:zhang@example.com`, EXIT.usage);
21110
21218
  return { platform: platform2, handle };
21111
21219
  }
21220
+ var splitRelationships = (values) => values.flatMap((v) => {
21221
+ const parts = v.split(/\s+/).filter(Boolean);
21222
+ return parts.length > 1 && parts.every(isKnownRelationship) ? parts : [v];
21223
+ });
21112
21224
  function withCustomerOptions(cmd, forUpdate) {
21113
- cmd.option("--name <s>", "name").option("--company <s>").option("--title <s>", "job title").option("--city <s>").option("--wechat <s>", "WeChat id").option("--summary <s>").option("--current-action <s>").option("--notes <s>").option("--potential <High|Medium|Low>").option("--cycle-days <n>", "predicted conversion window in days").option("--pain <a,b,c>", `pain-point tags, comma separated${forUpdate ? " (replaces the whole list)" : ""}`).option("--goal <s...>", `goals${forUpdate ? " (replaces the whole list)" : ""}`).option("--event <date:type:title...>", `calendar events${forUpdate ? " (replaces the whole calendar; see --add-event)" : ""}`).option("--social <platform:handle...>", `social accounts, e.g. channels:@san xiaohongshu:san${forUpdate ? " (replaces the whole list; see --add-social)" : ""}`).option("--relationship <r...>", `relationship to the user, e.g. \u5B66\u5458 \u7532\u65B9${forUpdate ? " (replaces the whole list; see --add-relationship)" : ""}`).option("--org <name:role:status...>", `organizations, e.g. \u540C\u6D4E\u5927\u5B66:\u5728\u804C\u6559\u5E08:\u5728\u804C\uFF08\u673A\u6784\u540D:\u8EAB\u4EFD:\u72B6\u6001\uFF0C\u8EAB\u4EFD\u53EF\u7701\u7565\uFF09${forUpdate ? " (replaces the whole list; see --add-org)" : ""}`).option("--related <name:relation:note...>", `related people, e.g. \u674E\u96C5\u5A77:\u8F6C\u4ECB\u7ECD\u4EBA\uFF08\u59D3\u540D:\u5173\u7CFB\uFF0C\u8BF4\u660E\u53EF\u7701\u7565\uFF09${forUpdate ? " (replaces the whole list; see --add-related)" : ""}`);
21225
+ cmd.option("--name <s>", "name").option("--company <s>").option("--title <s>", "job title").option("--city <s>").option("--wechat <s>", "WeChat id").option("--summary <s>").option("--current-action <s>").option("--notes <s>").option("--potential <High|Medium|Low>").option("--cycle-days <n>", "predicted conversion window in days").option("--pain <a,b,c>", `pain-point tags, comma separated${forUpdate ? " (replaces the whole list)" : ""}`).option("--goal <s...>", `goals${forUpdate ? " (replaces the whole list)" : ""}`).option("--event <date:type:title...>", `calendar events${forUpdate ? " (replaces the whole calendar; see --add-event)" : ""}`).option("--social <platform:handle...>", `social accounts, e.g. channels:@san xiaohongshu:san${forUpdate ? " (replaces the whole list; see --add-social)" : ""}`).option("--relationship <r...>", `relationship to the user, e.g. \u5B66\u5458 \u7532\u65B9${forUpdate ? " (replaces the whole list; see --add-relationship)" : ""}`).option("--org <name:role:status...>", `organizations, e.g. \u540C\u6D4E\u5927\u5B66:\u5728\u804C\u6559\u5E08:\u5728\u804C\uFF08\u673A\u6784\u540D:\u8EAB\u4EFD:\u72B6\u6001\uFF0C\u8EAB\u4EFD\u53EF\u7701\u7565\uFF09${forUpdate ? " (replaces the whole list; see --add-org)" : ""}`).option("--related <name:relation:note...>", `related people, e.g. \u674E\u96C5\u5A77:\u8F6C\u4ECB\u7ECD\u4EBA\uFF08\u59D3\u540D:\u5173\u7CFB\uFF0C\u8BF4\u660E\u53EF\u7701\u7565\uFF09\uFF1B\u5E26\u5FAE\u4FE1\u53F7\u5199 \u59D3\u540D:\u5173\u7CFB:wx=\u5FAE\u4FE1\u53F7${forUpdate ? " (replaces the whole list; see --add-related)" : ""}`);
21114
21226
  if (forUpdate) {
21115
- cmd.option("--add-pain <s...>", "append pain-point tags, keeping existing ones").option("--add-goal <s...>", "append goals, keeping existing ones").option("--add-event <date:type:title...>", "append calendar events, keeping existing ones").option("--add-social <platform:handle...>", "append social accounts, keeping existing ones").option("--add-relationship <r...>", "append relationships, keeping existing ones").option("--add-org <name:role:status...>", "append organizations, keeping existing ones (\u673A\u6784\u540D:\u8EAB\u4EFD:\u72B6\u6001)").option("--add-related <name:relation:note...>", "append related people, keeping existing ones (\u59D3\u540D:\u5173\u7CFB\uFF0C\u8BF4\u660E\u53EF\u7701\u7565)").option("--remove-event <date:keyword...>", "remove calendar events on that date (YYYY-MM-DD), or with date:keyword only those whose title contains the keyword; other events stay").option("--clear-events", "remove all calendar events");
21227
+ cmd.option("--add-pain <s...>", "append pain-point tags, keeping existing ones").option("--add-goal <s...>", "append goals, keeping existing ones").option("--add-event <date:type:title...>", "append calendar events, keeping existing ones").option("--add-social <platform:handle...>", "append social accounts, keeping existing ones").option("--add-relationship <r...>", "append relationships, keeping existing ones").option("--add-org <name:role:status...>", "append organizations, keeping existing ones (\u673A\u6784\u540D:\u8EAB\u4EFD:\u72B6\u6001)").option("--add-related <name:relation:note...>", "append related people, keeping existing ones (\u59D3\u540D:\u5173\u7CFB\uFF0C\u8BF4\u660E\u53EF\u7701\u7565\uFF1B\u5FAE\u4FE1\u53F7\u5199 \u59D3\u540D:\u5173\u7CFB:wx=\u5FAE\u4FE1\u53F7)").option("--remove-event <date:keyword...>", "remove calendar events on that date (YYYY-MM-DD), or with date:keyword only those whose title contains the keyword; other events stay").option("--clear-events", "remove all calendar events");
21116
21228
  } else {
21117
21229
  cmd.option("--hook-title <s>", "also record a successful hook for this customer (needs --hook-desc)").option("--hook-desc <s>");
21118
21230
  }
@@ -21142,7 +21254,7 @@ function buildCustomerBody(base, o) {
21142
21254
  if (o.event) body.upcomingEvents = o.event.map(parseEvent);
21143
21255
  if (o.clearEvents) body.upcomingEvents = [];
21144
21256
  if (o.social) body.socials = o.social.map(parseSocial);
21145
- if (o.relationship) body.relationships = o.relationship;
21257
+ if (o.relationship) body.relationships = splitRelationships(o.relationship);
21146
21258
  if (o.org) body.orgs = o.org.map(parseOrg);
21147
21259
  if (o.related) body.relatedPeople = o.related.map(parseRelated);
21148
21260
  if (o.hookTitle || o.hookDesc) {
@@ -21191,7 +21303,7 @@ function detail(c) {
21191
21303
  ["socials", c.socials.map((s) => `${s.platform}: ${s.handle}${s.url ? ` (${s.url})` : ""}`).join("; ")],
21192
21304
  ["relationship", c.relationships.map((r) => relationshipLabel(r, "zh")).join(", ")],
21193
21305
  ["orgs", (c.orgs ?? []).map((o) => `${o.org}${o.role ? ` \xB7 ${o.role}` : ""} [${orgStatusLabel(o.status, "zh")}]`).join("; ")],
21194
- ["related", (c.relatedPeople ?? []).map((p) => `${p.name} \xB7 ${p.relation}${p.note ? `\uFF08${p.note}\uFF09` : ""}`).join("; ")],
21306
+ ["related", (c.relatedPeople ?? []).map((p) => `${p.name} \xB7 ${p.relation}${p.wechatId ? ` wx:${p.wechatId}` : ""}${p.note ? `\uFF08${p.note}\uFF09` : ""}`).join("; ")],
21195
21307
  ["potential", c.conversionPotential],
21196
21308
  ["cycle days", String(c.conversionCycleDays)],
21197
21309
  ["pain points", c.painPoints.join(", ")],
@@ -21369,7 +21481,7 @@ withCustomerOptions(
21369
21481
  if (o.addRelated) {
21370
21482
  const added = o.addRelated.map(parseRelated);
21371
21483
  const existing = body.relatedPeople ?? cur.relatedPeople;
21372
- body.relatedPeople = [...existing, ...added.filter((x) => !existing.some((e) => relatedKey(e) === relatedKey(x)))];
21484
+ body.relatedPeople = mergeRelated(existing, added);
21373
21485
  }
21374
21486
  }
21375
21487
  if (!Object.keys(body).length) throw new CliError("usage", "Nothing to change. Pass a JSON input or flags like --summary, --potential, --add-pain", EXIT.usage);
@@ -21389,9 +21501,57 @@ program.command("get").description("Show one customer").argument("<id>").action(
21389
21501
  ].join("\n");
21390
21502
  out(rows, { customer, hooks });
21391
21503
  });
21504
+ var diffValue = (v) => {
21505
+ if (v === null || v === void 0) return "(none)";
21506
+ if (Array.isArray(v)) {
21507
+ if (!v.length) return "(empty)";
21508
+ return v.map((x) => typeof x === "object" && x !== null ? JSON.stringify(x) : String(x)).join(", ");
21509
+ }
21510
+ if (typeof v === "object") return JSON.stringify(v);
21511
+ return String(v);
21512
+ };
21513
+ var diffLabel = (field, v) => {
21514
+ if (field === "relationships" && Array.isArray(v)) {
21515
+ if (!v.length) return diffValue(v);
21516
+ return v.map((r) => relationshipLabel(String(r), "zh")).join(", ");
21517
+ }
21518
+ return diffValue(v);
21519
+ };
21520
+ program.command("history").description(
21521
+ "When a customer's record changed and what changed (old value \u2192 new value). Records only start where change tracking started, so an empty history does NOT mean nothing changed. --all lists identity migrations across every customer instead."
21522
+ ).argument("[id]", "customer id (omit with --all)").option("--all", "list identity migrations across all customers").action(async (id, o) => {
21523
+ if (o.all) {
21524
+ if (id) throw new CliError("usage", "Pass a customer id or --all, not both", EXIT.usage);
21525
+ const api2 = await client();
21526
+ const g2 = await api2.identityMigrations();
21527
+ const start = g2.recordStart ? g2.recordStart.slice(0, 10) : "none";
21528
+ const rows2 = g2.transitions.map(
21529
+ (t) => ` ${t.at} ${t.customerName || t.customerId} ${t.from ? diffLabel("relationships", [t.from]) : "(unrecorded)"} \u2192 ${diffLabel("relationships", [t.to])} (audit ${t.auditId})`
21530
+ );
21531
+ const human2 = [
21532
+ `Identity migrations \xB7 record start ${start} \xB7 ${g2.transitions.length} step${g2.transitions.length === 1 ? "" : "s"}`,
21533
+ g2.recordStart ? "Changes before the record start are not recoverable \u2014 no record does not mean never changed." : "No identity change has been recorded yet.",
21534
+ ...rows2
21535
+ ].join("\n");
21536
+ out(human2, g2);
21537
+ return;
21538
+ }
21539
+ if (!id) throw new CliError("usage", "Pass a customer id, or --all for every customer", EXIT.usage);
21540
+ const api = await client();
21541
+ const { history } = await api.customerHistory(id);
21542
+ const rows = history.map((h) => {
21543
+ const changed = h.diff ? Object.entries(h.diff).map(([f, d]) => ` ${f.padEnd(22)}${diffLabel(f, d.before)} \u2192 ${diffLabel(f, d.after)}${d.truncated ? " (truncated)" : ""}`) : [" (changed before change tracking started \u2014 no old/new values recorded)"];
21544
+ return [` ${h.createdAt} ${h.action} ${h.source}`, ...changed].join("\n");
21545
+ });
21546
+ const human = [
21547
+ `Change history for ${id} \xB7 ${history.length} entr${history.length === 1 ? "y" : "ies"}`,
21548
+ ...history.length ? rows : [" (nothing recorded)"]
21549
+ ].join("\n");
21550
+ out(human, { history, count: history.length });
21551
+ });
21392
21552
  program.command("lint").description("Audit every customer record and report what should be checked or fixed. Reports only \u2014 never writes.").option("--kind <kind>", "only report one kind of issue").option("--severity <level>", "only report this severity: error / warn / info").action(async (o) => {
21393
21553
  const api = await client();
21394
- const { customers } = await api.listCustomers({});
21554
+ const customers = await fetchAllCustomers(api, {});
21395
21555
  const all = lintCustomers(customers, today());
21396
21556
  const issues = all.filter(
21397
21557
  (i) => (!o.kind || i.kind === o.kind) && (!o.severity || i.severity === o.severity)
@@ -21414,7 +21574,7 @@ program.command("lint").description("Audit every customer record and report what
21414
21574
  out(human, { scanned: customers.length, count: issues.length, errors, warns, infos, issues, perCustomer });
21415
21575
  });
21416
21576
  program.command("list").description("List customers (newest update first), optionally filtered").option("--potential <High|Medium|Low>").option("--city <s>", "exact city (case-insensitive)").option("--tag <s>", "has this pain-point tag").option("--social-platform <s>", "has a social account on this platform (e.g. xiaohongshu, channels, email)").option("--relationship <s>", "has this relationship to the user (e.g. \u7532\u65B9 / client, \u5B66\u5458 / student, \u6E20\u9053\u65B9 / channel)").option("--org <s>", "is affiliated with this organization (substring match, e.g. \u540C\u6D4E / \u535A\u4E16)").option("--related <s>", "is connected to this person (substring match on the related-people list; also matches records that point at this customer)").option("--due-today", "has a calendar event today (your local date)").option("--due <YYYY-MM-DD>", "has a calendar event on this date").option("--expired [date]", "has a calendar event before this date (default: today) \u2014 overdue events nobody cleaned up").option("-q, --query <s>", "keyword across name, company, title, city, wechat, social accounts, relationships, organizations, related people, summary, notes, tags, goals").action(async (o) => {
21417
- const { customers } = await (await client()).listCustomers({
21577
+ const customers = await fetchAllCustomers(await client(), {
21418
21578
  potential: o.potential ? potentialOf(o.potential) : void 0,
21419
21579
  city: o.city,
21420
21580
  tag: o.tag,
@@ -21429,7 +21589,7 @@ program.command("list").description("List customers (newest update first), optio
21429
21589
  out(customers.length ? customers.map(line).join("\n") : "No customers match.", { customers, count: customers.length });
21430
21590
  });
21431
21591
  program.command("search").description("Search customers by keyword (same as `list -q`). Run this before `add` to avoid duplicates.").argument("<keyword>").action(async (keyword) => {
21432
- const { customers } = await (await client()).listCustomers({ q: keyword });
21592
+ const customers = await fetchAllCustomers(await client(), { q: keyword });
21433
21593
  out(customers.length ? customers.map(line).join("\n") : "No customers match.", { customers, count: customers.length });
21434
21594
  });
21435
21595
  program.command("rm").description("Delete a customer (their hooks stay in the hook library)").argument("<id>").option("-y, --yes", "skip the confirmation (required when not a TTY)").action(async (id, o) => {
@@ -21552,14 +21712,22 @@ program.command("import").description("Import a backup (from `crm export` or the
21552
21712
  throw new CliError("usage", `Can't read ${src}: ${e.message}`, EXIT.usage);
21553
21713
  }
21554
21714
  const { counts } = await (await client()).importAll(data);
21555
- out(`Imported ${counts.customers} customers, ${counts.hooks} hooks, ${counts.recommendations} recommendations${counts.skipped ? ` (${counts.skipped} invalid entries skipped)` : ""}`, { ok: true, counts });
21715
+ out(`Imported ${counts.customers} customers, ${counts.hooks} hooks, ${counts.recommendations} recommendations${counts.skipped ? ` (${counts.skipped} entries skipped)` : ""}`, { ok: true, counts });
21556
21716
  });
21557
21717
  try {
21558
21718
  await program.parseAsync();
21559
21719
  } catch (e) {
21560
- const err = e instanceof CliError ? e : new CliError("internal", e.message, EXIT.error);
21561
- if (g().json) process.stdout.write(`${JSON.stringify({ error: { code: err.code, message: err.message } })}
21562
- `);
21563
- else console.error(`error: ${err.message}`);
21564
- process.exitCode = err.exitCode;
21720
+ if (e instanceof CommanderError) {
21721
+ if (e.code === "commander.helpDisplayed" || e.code === "commander.version") {
21722
+ process.exitCode = 0;
21723
+ } else {
21724
+ if (jsonRequested()) writeJsonError("usage", e.message.replace(/^error:\s*/, ""));
21725
+ process.exitCode = EXIT.usage;
21726
+ }
21727
+ } else {
21728
+ const err = e instanceof CliError ? e : new CliError("internal", e.message, EXIT.error);
21729
+ if (jsonRequested()) writeJsonError(err.code, err.message);
21730
+ else console.error(`error: ${err.message}`);
21731
+ process.exitCode = err.exitCode;
21732
+ }
21565
21733
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "insightcrm",
3
- "version": "0.1.11",
3
+ "version": "0.1.12",
4
4
  "description": "Command line and agent skill for InsightCRM: file customers from chats and screenshots with your own AI agent. Non-interactive, --json output, stable exit codes.",
5
5
  "license": "MIT",
6
6
  "type": "module",