1688-cli 0.1.40 → 0.1.42

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 (110) hide show
  1. package/AGENTS.md +112 -318
  2. package/ARCHITECTURE.md +106 -0
  3. package/CHANGELOG.md +107 -0
  4. package/README.md +100 -10
  5. package/dist/cli.js +165 -2
  6. package/dist/cli.js.map +1 -1
  7. package/dist/commands/cart-add.js +15 -11
  8. package/dist/commands/cart-add.js.map +1 -1
  9. package/dist/commands/cart-list.js +13 -11
  10. package/dist/commands/cart-list.js.map +1 -1
  11. package/dist/commands/compare.js +107 -0
  12. package/dist/commands/compare.js.map +1 -0
  13. package/dist/commands/debug.js +101 -0
  14. package/dist/commands/debug.js.map +1 -0
  15. package/dist/commands/doctor.js +107 -4
  16. package/dist/commands/doctor.js.map +1 -1
  17. package/dist/commands/image-search.js +2 -6
  18. package/dist/commands/image-search.js.map +1 -1
  19. package/dist/commands/inbox.js +16 -32
  20. package/dist/commands/inbox.js.map +1 -1
  21. package/dist/commands/offer.js +7 -5
  22. package/dist/commands/offer.js.map +1 -1
  23. package/dist/commands/order-list.js +4 -2
  24. package/dist/commands/order-list.js.map +1 -1
  25. package/dist/commands/order-logistics.js +4 -2
  26. package/dist/commands/order-logistics.js.map +1 -1
  27. package/dist/commands/profile.js +84 -0
  28. package/dist/commands/profile.js.map +1 -0
  29. package/dist/commands/research.js +142 -0
  30. package/dist/commands/research.js.map +1 -0
  31. package/dist/commands/search.js +157 -111
  32. package/dist/commands/search.js.map +1 -1
  33. package/dist/commands/seller-messages.js +7 -4
  34. package/dist/commands/seller-messages.js.map +1 -1
  35. package/dist/commands/similar.js +2 -6
  36. package/dist/commands/similar.js.map +1 -1
  37. package/dist/commands/sourcing-utils.js +438 -0
  38. package/dist/commands/sourcing-utils.js.map +1 -0
  39. package/dist/commands/supplier-inspect.js +559 -0
  40. package/dist/commands/supplier-inspect.js.map +1 -0
  41. package/dist/commands/supplier-search.js +522 -0
  42. package/dist/commands/supplier-search.js.map +1 -0
  43. package/dist/daemon/client.js +2 -2
  44. package/dist/daemon/client.js.map +1 -1
  45. package/dist/daemon/protocol.js +2 -1
  46. package/dist/daemon/protocol.js.map +1 -1
  47. package/dist/io/output.js +31 -2
  48. package/dist/io/output.js.map +1 -1
  49. package/dist/session/config.js +82 -0
  50. package/dist/session/config.js.map +1 -0
  51. package/dist/session/dispatch.js +26 -3
  52. package/dist/session/dispatch.js.map +1 -1
  53. package/dist/session/events.js +151 -0
  54. package/dist/session/events.js.map +1 -0
  55. package/dist/session/im-cards.js +183 -0
  56. package/dist/session/im-cards.js.map +1 -0
  57. package/dist/session/im-ws.js +8 -5
  58. package/dist/session/im-ws.js.map +1 -1
  59. package/dist/session/navigation-guard.js +65 -0
  60. package/dist/session/navigation-guard.js.map +1 -0
  61. package/dist/session/paths.js +23 -4
  62. package/dist/session/paths.js.map +1 -1
  63. package/dist/session/search-capture.js +56 -6
  64. package/dist/session/search-capture.js.map +1 -1
  65. package/dist/session/search-mtop.js +53 -0
  66. package/dist/session/search-mtop.js.map +1 -1
  67. package/dist/session/supplier-search.js +403 -0
  68. package/dist/session/supplier-search.js.map +1 -0
  69. package/dist/util/encoding.js +8 -0
  70. package/dist/util/encoding.js.map +1 -0
  71. package/dist/util/temp.js +6 -0
  72. package/dist/util/temp.js.map +1 -0
  73. package/docs/AGENT_MAPS_PLAN.md +171 -0
  74. package/docs/AGENT_WORKING_PRINCIPLES.md +143 -0
  75. package/docs/COMMANDS.md +199 -0
  76. package/docs/FEATURES.md +45 -0
  77. package/docs/JSON_CONTRACTS.md +390 -0
  78. package/docs/QUALITY_SCORE.md +60 -0
  79. package/docs/README.md +35 -0
  80. package/docs/RELIABILITY.md +61 -0
  81. package/docs/SAFETY.md +100 -0
  82. package/docs/WORKFLOW.md +82 -0
  83. package/docs/exec-plans/README.md +9 -0
  84. package/docs/exec-plans/active/README.md +4 -0
  85. package/docs/exec-plans/completed/2026-05-28-sourcing-research-v1.md +125 -0
  86. package/docs/exec-plans/completed/2026-05-31-supplier-inspect-v1.md +113 -0
  87. package/docs/exec-plans/completed/2026-06-04-supplier-search-v1.md +81 -0
  88. package/docs/exec-plans/completed/2026-06-07-windows-cli-compatibility.md +138 -0
  89. package/docs/exec-plans/completed/README.md +4 -0
  90. package/docs/exec-plans/tech-debt-tracker.md +5 -0
  91. package/docs/generated/command-index.md +54 -0
  92. package/docs/generated/json-shapes.md +111 -0
  93. package/docs/generated/module-map.md +13 -0
  94. package/docs/generated/test-index.md +34 -0
  95. package/docs/playbooks/add-command.md +15 -0
  96. package/docs/playbooks/add-mtop-capture.md +13 -0
  97. package/docs/playbooks/change-json-output.md +11 -0
  98. package/docs/playbooks/debug-risk-control.md +12 -0
  99. package/docs/playbooks/update-cli-release.md +11 -0
  100. package/docs/specs/checkout-and-orders.md +30 -0
  101. package/docs/specs/seller-im.md +28 -0
  102. package/docs/specs/sourcing-research.md +186 -0
  103. package/docs/specs/supplier-inspect.md +144 -0
  104. package/docs/specs/supplier-search.md +179 -0
  105. package/docs/specs/windows-cli-compatibility.md +123 -0
  106. package/package.json +12 -2
  107. package/scripts/check_agent_map.mjs +86 -0
  108. package/scripts/fix_bin_mode.mjs +18 -0
  109. package/scripts/generate_agent_context.mjs +253 -0
  110. package/scripts/postinstall.mjs +12 -4
package/AGENTS.md CHANGED
@@ -1,318 +1,112 @@
1
- # 1688 — 1688 CLI for agents
2
-
3
- When the user asks anything about 1688 sourcing, products, orders, or
4
- logistics, use the `1688` CLI. It outputs JSON automatically when stdout
5
- is piped, so `1688 <cmd> | jq` works.
6
-
7
- ## Current commands
8
-
9
- Organized by buyer journey: sourcing → inquiry → cart → checkout → tracking → post-sale.
10
-
11
- ```
12
- # Sourcing
13
- 1688 search <keyword> Keyword search; --max N to limit.
14
- 1688 search --headed Open window once if a slider verification appears.
15
- 1688 similar <offerId> "找同款" similar offers from other suppliers, sorted by price.
16
- 1688 image-search <pathOrUrl> Search by image (local .jpg/.png/.webp file or http(s) URL).
17
- 1688 offer <offerId> Full product detail: title, priceTiers, SKUs, attributes,
18
- packageInfo, supplier (loginId/memberId/province/city).
19
-
20
- # Pre-sale inquiry (seller IM, scoped by offerId)
21
- 1688 seller inquire <offerId> <message> Send product link + question to the supplier.
22
- 1688 seller messages --offer <offerId> Read replies in this offer's conversation.
23
- 1688 seller messages --offer <offerId> --watch [--interval N]
24
- Live-tail new replies (line-delimited JSON when piped).
25
- Long-running; min interval 10 s, default 30 s.
26
-
27
- # Cart
28
- 1688 cart list List items in 1688 cart (采购车).
29
- 1688 cart add <offerId> --sku <skuId> --qty N
30
- Add SKU to cart (~6 s, mtop hijack). Returns
31
- {added: CartItem, isNewRow, addedQuantity}.
32
- 1688 cart remove <cartId> Remove one cart row (~12 s, UI replay).
33
-
34
- # Checkout
35
- 1688 checkout prepare <cartId>... Preview total/address/items (NO order placement).
36
- 1688 checkout confirm <cartId>... PLACE order — TTY+prompt by default.
37
- 1688 checkout confirm <cartId>... --agent Agent mode: no prompt; use only after explicit approval.
38
- MUST be preceded by `prepare` shown to the user AND
39
- explicit user authorization in the current turn.
40
-
41
- # Order tracking
42
- 1688 order list List buyer orders; --status, --page, --page-size flags.
43
- Each order has actions[] (buyer ops + URLs), services[]
44
- (insurance/refund), badges[].
45
- 1688 order list --status waitbuyerreceive Filter to "awaiting delivery".
46
- 1688 order get <orderId> One order by ID (--max-scan-pages N, --status hint).
47
- 1688 order logistics <orderId> Tracking number + trace (mailNo, carrier, remark).
48
- 1688 shipped <orderId> Order detail + logistics merged into one call.
49
- 1688 stuck [--days N] Paid but not shipped > N days (default 3).
50
- 1688 fake-shipped [--days N] [--debug] Marked shipped but courier never collected (虚假发货).
51
- 1688 seller-history <sellerName> All orders from a seller + avg ship days + on-time rate.
52
-
53
- # Post-sale chat (seller IM, scoped by orderId)
54
- 1688 seller chat <orderId|loginId> <message>
55
- Send to seller. With orderId, auto-attaches the order card.
56
- 1688 seller chat <orderId> <message> --no-card
57
- Follow-up reply, no card.
58
- 1688 seller messages <orderId> Read replies in this order's conversation.
59
- 1688 seller messages <orderId> --watch Live-tail (same as the --offer form above).
60
-
61
- # Account & daemon
62
- 1688 login Show QR code; user scans with phone.
63
- 1688 login --headed Use a real browser window instead (fallback).
64
- 1688 login --force Re-login even if a session exists.
65
- 1688 logout [--yes] Log out (prompts unless --yes).
66
- 1688 whoami [--verify] Print current account; exit 3 if not logged in.
67
- 1688 doctor [--no-launch] Diagnose environment + session state.
68
- 1688 daemon start | stop | status | reload Manage the background daemon.
69
- 1688 serve Run the daemon in the foreground.
70
- ```
71
-
72
- ## Daemon (recommended for agent use)
73
-
74
- When the daemon is running, commands route through it and share a single
75
- Chromium context. Benefits:
76
- - ~2-3 seconds saved per command (no Chrome cold start)
77
- - One continuous logged-in session across commands
78
- - Built-in inter-command jitter (1.2-3 s)
79
-
80
- The agent should call `1688 daemon start` once at the beginning of a session
81
- that involves multiple 1688 commands. The daemon auto-stops after 30 minutes
82
- of inactivity. Run `1688 daemon reload` after the package updates to pick up
83
- new code.
84
-
85
- `login`, `logout`, `doctor` stay inline; they need interactive UI or browser
86
- windows. If the daemon is running and you need to `login --force`, stop the
87
- daemon first.
88
-
89
- ## Watch mode (long-running streams)
90
-
91
- `1688 seller messages ... --watch` is a long-running command. It:
92
- - Prints `Baseline: <conversation> — N messages in history` to stderr on start
93
- - Emits one line of JSON to stdout per **newly-arrived** message (history is
94
- not re-emitted)
95
- - Dedup is by server-side `messageId`
96
- - Default interval 30 s, minimum 10 s, override with `--interval <seconds>`
97
- - Exits cleanly on SIGINT (Ctrl+C)
98
-
99
- For agent loops, pipe stdout into a `while read line` and parse each line as
100
- its own JSON object. Do not assume the process will exit — it is meant to
101
- stay alive.
102
-
103
- ## Exit codes
104
-
105
- | Code | Meaning |
106
- |------|---------|
107
- | 0 | Success |
108
- | 2 | Bad invocation (missing flag, etc.) |
109
- | 3 | Not logged in / session expired |
110
- | 5 | Another 1688 command is running (lock busy) |
111
- | 6 | Chromium not installed |
112
- | 7 | Login wait timeout |
113
- | 4 | Aliyun risk control (slider verification) — retry with `--headed` |
114
- | 8 | Login finished but cookies missing |
115
- | 9 | Network error |
116
- | 130 | User canceled |
117
-
118
- ## Status filter values (for `order list --status`)
119
-
120
- | value | meaning |
121
- |---|---|
122
- | `all` | All orders |
123
- | `waitbuyerpay` | 待付款 |
124
- | `waitsellersend` | 待发货 |
125
- | `waitbuyerreceive` | 待收货 |
126
- | `success` | 已完成 |
127
- | `cancel` | 已取消 |
128
-
129
- ## Rules for the agent
130
-
131
- - `1688 login` opens a window the user must interact with. Only run it
132
- yourself if the user explicitly asks you to log in.
133
- - `1688 logout` requires `--yes` in non-interactive mode. Do not pass
134
- `--yes` without explicit user confirmation in the current turn.
135
- - If a command returns exit 3, tell the user to run `1688 login`.
136
- Do not loop or retry on your own.
137
- - If a command returns exit 4 (risk control), tell the user to run the
138
- same command once with `--headed` (they will need to drag a slider).
139
- Do not retry the same command silently.
140
- - **`1688 checkout confirm` requires a TTY by default**, OR `--agent` flag.
141
- It places real orders (no payment yet, but commits to seller).
142
-
143
- **Agent protocol for placing orders:**
144
- 1. Run `1688 checkout prepare <cartIds>` first
145
- 2. SHOW the user the full preview (total, items, address, seller)
146
- 3. WAIT for the user's explicit "yes, place it" / "下单吧" in the current turn
147
- 4. Only then run `1688 checkout confirm <cartIds> --agent`
148
- 5. Report the final orderId / URL back to the user
149
-
150
- NEVER run `--agent` without the prepare+approval cycle. NEVER infer authorization
151
- from older messages — it must be explicit in the CURRENT turn.
152
- - JSON output of `whoami`:
153
- ```json
154
- {"loggedIn": true, "memberId": "...", "nick": "...", "lastVerifiedAt": "..."}
155
- {"loggedIn": false}
156
- ```
157
-
158
- ## Key JSON shapes
159
-
160
- ### `seller messages` result
161
-
162
- ```ts
163
- {
164
- conversation: string,
165
- total: number,
166
- messages: Array<{
167
- sender: string,
168
- time: string | null, // "YYYY-MM-DD HH:MM:SS" in +08:00
169
- isMine: boolean,
170
- content: string,
171
- read: boolean,
172
- kind: "text" | "offerCard" | "orderCard" | "autoReply"
173
- | "assessment" | "image" | "other",
174
- card?: { title: string|null, price: string|null,
175
- image: string|null, url: string|null },
176
- messageId?: string, // present when sourced from WS
177
- }>,
178
- }
179
- ```
180
-
181
- `--watch` mode emits per-message instead:
182
- ```ts
183
- { conversation: string, message: <one item from messages[] above> }
184
- ```
185
-
186
- ### `cart add` result
187
-
188
- ```ts
189
- {
190
- ok: boolean,
191
- added: CartItem, // see `cart list` JSON for full shape
192
- isNewRow: boolean, // true=new cartId, false=merged into existing row
193
- addedQuantity: number, // delta this call added (== args.quantity for new row)
194
- }
195
- ```
196
-
197
- To get the cartId reliably in a pipeline:
198
- ```bash
199
- id=$(1688 cart add <offerId> --sku <skuId> --qty 1 | jq -r '.added.cartId')
200
- ```
201
-
202
- ## Output flags (every command)
203
-
204
- In addition to `BB1688_JSON=1`, every command accepts:
205
-
206
- ```
207
- --json Force JSON output even in a TTY.
208
- --pretty Indent JSON by 2 spaces.
209
- --get <path> Print one field by dot-path. Scalar → raw line,
210
- object/array → JSON. Wildcards stream one element per line.
211
- Syntax: field.sub, arr[N].field, arr[*].field
212
- --pick <paths> Comma-separated dot-paths → emit a JSON object with each
213
- path as a key. Useful for trimming output for downstream agents.
214
- ```
215
-
216
- Examples:
217
- ```bash
218
- 1688 offer X --get supplier.name # 深圳... (raw)
219
- 1688 offer X --get supplier # {"name":"...","loginId":"..."}
220
- 1688 offer X --get 'skus[*].price' # 49 \n 68 \n 98.75 ...
221
- 1688 offer X --pick price,supplier.name # {"price":1.25,"supplier.name":"..."}
222
- 1688 offer X --json --pretty # full payload, indented
223
- ```
224
-
225
- When `--get`/`--pick` is given, the human renderer is skipped; the resolved
226
- value(s) go to stdout. The full payload still flows through when neither
227
- flag is set, so existing `| jq` pipelines keep working.
228
-
229
- ## Login in non-interactive sessions (Codex / Claude Code / scripted)
230
-
231
- `1688 login` displays a QR code on stderr. ASCII rendering only works on
232
- a real TTY — when invoked from an agent, stderr is usually piped and the
233
- ASCII art either does not render or appears garbled.
234
-
235
- The login command always **also** saves the QR as a PNG to
236
- `~/.1688/login-qr.png` (`%USERPROFILE%\.1688\login-qr.png` on Windows)
237
- and writes `QR saved as PNG: <path>` on stderr. The agent should:
238
-
239
- 1. Watch stderr for the `QR saved as PNG:` line.
240
- 2. Surface that file to the user (display the image inline, or tell the
241
- user the exact path so they can open it).
242
- 3. Wait for the command to exit naturally — the user must scan the QR
243
- with their 1688 mobile app within the timeout (default 300 s).
244
-
245
- Do not attempt to "open" the raw QR URL in a browser — it is a token URL
246
- that only the 1688 app can consume, not a human-readable page.
247
-
248
- ## Feedback / bug reports
249
-
250
- ```
251
- 1688 feedback "<message>" Open a pre-filled GitHub issue (TTY browser).
252
- 1688 feedback --bug "<details>" Tag the issue as a bug.
253
- 1688 feedback --no-open "<msg>" Just print the URL — useful for agents to
254
- show the user without opening a browser
255
- on the agent's machine.
256
- 1688 feedback "<msg>" --submit Post the issue DIRECTLY via the `gh` CLI
257
- (requires `gh auth login`). Skips the
258
- "Submit new issue" click in the browser.
259
- ```
260
-
261
- **Agent rule for `--submit`**: do NOT add `--submit` on the agent's own
262
- initiative. Always run without `--submit` first, show the user the
263
- generated URL, and only re-run with `--submit` if the user explicitly
264
- asks ("submit it" / "直接发吧" / "post the issue"). Posting an issue is
265
- a public write action.
266
-
267
- The CLI auto-attaches anonymized environment info (version, Node, OS) and
268
- the last error from `daemon.log` if present. Nothing about the user's
269
- 1688 account is sent. The actual submission still requires the user to
270
- click "Submit new issue" in the browser — the CLI only prepares the URL.
271
-
272
- ## Update awareness
273
-
274
- At the start of a session that runs multiple 1688 commands, run
275
- `1688 doctor`. Its JSON output includes a `version` block:
276
-
277
- ```json
278
- {
279
- "version": {
280
- "current": "0.1.27",
281
- "latest": "0.1.29",
282
- "updateAvailable": true,
283
- "updateCommand": "npm i -g 1688-cli@latest",
284
- "error": null
285
- }
286
- }
287
- ```
288
-
289
- You can also detect updates from any command: in JSON mode (piped / `--json`
290
- / `BB1688_JSON=1`), a single line of structured JSON appears on stderr
291
- when a newer version is cached:
292
-
293
- ```
294
- {"_notice":"updateAvailable","current":"0.1.27","latest":"0.1.29","updateCommand":"npm i -g 1688-cli@latest"}
295
- ```
296
-
297
- ### Rules for upgrades
298
-
299
- - **Interactive session** (TTY, the user is watching the conversation):
300
- ask the user once whether to upgrade now. Show the current → latest
301
- versions and the install command. If the user agrees, run
302
- `updateCommand`, then `1688 daemon reload` to pick up the new code.
303
-
304
- - **Non-interactive** (CI, cron, scripted agent loop with no human in
305
- the loop): do NOT upgrade on your own. Log the notice to stderr and
306
- continue. Pinning is intentional in those contexts.
307
-
308
- - Never run the install command without explicit user authorization in
309
- the CURRENT turn. The CLI version is part of the user's global
310
- environment; treat it the same way you treat any `sudo` or
311
- "modify global state" action.
312
-
313
- - Ask at most once per session. If the user declines or postpones,
314
- don't ask again in the same session.
315
-
316
- ## Discovery
317
-
318
- Run `1688 --help` and `1688 <command> --help` for the latest flags.
1
+ # Agent Map
2
+
3
+ This file is the short entry point for coding agents. Treat it as a map, not
4
+ as the full manual. Load deeper context from `ARCHITECTURE.md` and `docs/`
5
+ only when the task needs it.
6
+
7
+ ## First Read
8
+
9
+ - Agent working principles: `docs/AGENT_WORKING_PRINCIPLES.md`
10
+ - System architecture: `ARCHITECTURE.md`
11
+ - Documentation map: `docs/README.md`
12
+ - Default workflow: `docs/WORKFLOW.md`
13
+ - Command catalog: `docs/COMMANDS.md`
14
+ - JSON contracts: `docs/JSON_CONTRACTS.md`
15
+ - Safety and approval rules: `docs/SAFETY.md`
16
+ - Reliability and browser/session behavior: `docs/RELIABILITY.md`
17
+ - Quality score and known gaps: `docs/QUALITY_SCORE.md`
18
+
19
+ ## Project Shape
20
+
21
+ - `src/cli.ts`: Commander CLI surface and command routing.
22
+ - `src/commands`: command executors and human renderers.
23
+ - `src/session`: Playwright browser/session helpers, mtop capture, locators,
24
+ recovery, lock, state, and artifacts.
25
+ - `src/daemon`: background daemon client/server/protocol/throttle.
26
+ - `src/io`: JSON/text output, prompts, and structured errors.
27
+ - `src/auth`: login/session verification and cookie helpers.
28
+ - `src/util`: small shared utilities.
29
+ - `tests`: deterministic Vitest coverage and fixtures.
30
+ - `scripts`: probes, postinstall, and agent-map utilities.
31
+ - `docs`: canonical agent-readable knowledge base.
32
+
33
+ ## Common Commands
34
+
35
+ - Install deps: `pnpm install`
36
+ - Typecheck: `pnpm typecheck`
37
+ - Deterministic tests: `pnpm test:unit`
38
+ - Full test run, including live doctor checks: `pnpm test`
39
+ - Build CLI: `pnpm build`
40
+ - Generate agent indexes: `pnpm agent-context`
41
+ - Check generated indexes: `pnpm docs-check`
42
+ - Check map structure: `pnpm agent-map-check`
43
+ - Default agent gate: `pnpm agent-verify`
44
+
45
+ `pnpm agent-verify` is the default green gate. If it fails, report the exact
46
+ failure instead of hiding it.
47
+
48
+ ## Task Routing
49
+
50
+ - New or changed CLI command: read `docs/playbooks/add-command.md`,
51
+ `docs/COMMANDS.md`, and the relevant `src/commands/*` file.
52
+ - JSON output change: read `docs/playbooks/change-json-output.md` and
53
+ `docs/JSON_CONTRACTS.md`; preserve compatibility unless the user approved a
54
+ breaking change.
55
+ - Browser risk-control / slider / login issue: read
56
+ `docs/playbooks/debug-risk-control.md`, `docs/SAFETY.md`, and
57
+ `docs/RELIABILITY.md`.
58
+ - New mtop or response capture: read `docs/playbooks/add-mtop-capture.md` and
59
+ existing helpers in `src/session/*capture*.ts`.
60
+ - Release/update behavior: read `docs/playbooks/update-cli-release.md`.
61
+ - Sourcing research features: read `docs/specs/sourcing-research.md`
62
+ and `docs/FEATURES.md`.
63
+ - Supplier search/research work: read `docs/specs/supplier-search.md`.
64
+ - Seller IM work: read `docs/specs/seller-im.md`.
65
+ - Checkout/order work: read `docs/specs/checkout-and-orders.md` and
66
+ `docs/SAFETY.md`.
67
+ - Complex feature/refactor: create or update an ExecPlan under
68
+ `docs/exec-plans/active/`.
69
+
70
+ ## 1688 Runtime Rules
71
+
72
+ - For 1688 sourcing, products, orders, or logistics, use the `1688` CLI.
73
+ - It outputs JSON automatically when stdout is piped, so
74
+ `1688 <cmd> | jq` works.
75
+ - At the start of a multi-command 1688 session, run
76
+ `1688 doctor --no-launch --json` and start the daemon when useful with
77
+ `1688 daemon start`.
78
+ - If a command returns exit `3`, tell the user to run `1688 login`; do not
79
+ retry in a loop.
80
+ - If a command returns exit `4`, tell the user to run the same command once
81
+ with `--headed` and solve the slider manually; do not silently retry.
82
+ - `1688 login` opens a user-interactive QR/browser flow. Run it only when the
83
+ user explicitly asks to log in.
84
+ - `1688 logout --yes` requires explicit current-turn confirmation.
85
+ - Seller messages `--watch` is long-running and emits one JSON object per new
86
+ message.
87
+
88
+ ## Write-Action Boundaries
89
+
90
+ These commands contact sellers, modify buyer state, or place orders. Use the
91
+ protocols in `docs/SAFETY.md`.
92
+
93
+ - `1688 seller inquire <offerId> <message>`
94
+ - `1688 seller chat <orderId|loginId> <message>`
95
+ - `1688 cart add <offerId> --sku <skuId> --qty N`
96
+ - `1688 cart remove <cartId>`
97
+ - `1688 checkout confirm <cartIds...>`
98
+ - `1688 feedback "<message>" --submit`
99
+ - `1688 logout --yes`
100
+
101
+ Hard rule: never run `1688 checkout confirm ... --agent` unless
102
+ `1688 checkout prepare <cartIds...>` was shown to the user and the user gave
103
+ explicit current-turn approval to place the order.
104
+
105
+ ## Done Criteria
106
+
107
+ - Relevant docs/playbooks/specs were read and updated if behavior changed.
108
+ - `pnpm agent-context` was run after command, JSON contract, source layout, or
109
+ test layout changes.
110
+ - `pnpm agent-verify` was run, or the exact blocker is recorded.
111
+ - For complex work, active ExecPlans contain progress, decisions, and latest
112
+ verification.
@@ -0,0 +1,106 @@
1
+ # Architecture
2
+
3
+ `1688-cli` is a TypeScript command-line tool for Alibaba 1688 buyer workflows:
4
+ sourcing, seller IM, cart, checkout, order tracking, and logistics follow-up.
5
+ It uses Playwright with a persistent browser profile, a daemon for warm
6
+ sessions, and stable JSON output for agents.
7
+
8
+ ## Layer Map
9
+
10
+ ```text
11
+ src/cli.ts
12
+ -> src/commands
13
+ -> src/session
14
+ -> src/daemon
15
+ -> src/io
16
+ -> src/auth
17
+ -> src/util
18
+ tests -> src/*
19
+ docs/generated -> scripts/generate_agent_context.mjs
20
+ ```
21
+
22
+ ## Layer Responsibilities
23
+
24
+ `src/cli.ts` owns the public command surface: command names, options,
25
+ arguments, and lazy imports.
26
+
27
+ `src/commands` owns user-visible behavior for each command. A command usually
28
+ contains:
29
+
30
+ - option parsing / validation
31
+ - `execute(ctx, args)` for daemon-dispatched work
32
+ - `run(opts)` for CLI invocation
33
+ - human rendering through `emit({ human, data })`
34
+
35
+ `src/session` owns browser automation primitives: Playwright context setup,
36
+ mtop/response capture, locators, recovery, locking, page-state detection,
37
+ navigation guards, artifacts, and timing helpers.
38
+
39
+ `src/daemon` owns the long-lived background process, request protocol,
40
+ client/server dispatch, and inter-command throttling.
41
+
42
+ `src/io` owns output compatibility, JSON flags, prompts, and structured
43
+ `CliError` behavior.
44
+
45
+ `src/auth` owns login/session verification and cookie handling.
46
+
47
+ `src/util` owns small shared helpers.
48
+
49
+ `tests` owns deterministic Vitest coverage. Live/browser flows should be
50
+ guarded or documented when they cannot be deterministic.
51
+
52
+ `docs` owns durable agent-readable knowledge. `docs/generated/*` is generated
53
+ by `scripts/generate_agent_context.mjs`.
54
+
55
+ ## Dependency Rules
56
+
57
+ - CLI routing may import commands lazily, but command modules should not import
58
+ `src/cli.ts`.
59
+ - Command modules may use `src/session`, `src/daemon/dispatch` indirectly,
60
+ `src/io`, `src/auth`, and `src/util`.
61
+ - `src/session` should not depend on command modules, except shared types only
62
+ when there is no cleaner local session type.
63
+ - `src/io` should stay browser-free and command-agnostic.
64
+ - `src/daemon` should depend on command executors through explicit dispatch
65
+ wiring, not dynamic ad-hoc imports from arbitrary modules.
66
+ - JSON-facing result interfaces should live near the owning command and be
67
+ documented in `docs/JSON_CONTRACTS.md` when stable for agents.
68
+
69
+ ## Major Domains
70
+
71
+ - Sourcing: `search`, `similar`, `image-search`, `offer`.
72
+ - Pre-sale seller IM: `seller inquire`, `seller messages --offer`.
73
+ - Cart: `cart list`, `cart add`, `cart remove`.
74
+ - Checkout: `checkout prepare`, `checkout confirm`.
75
+ - Order tracking: `order list`, `order get`, `order logistics`, `shipped`,
76
+ `stuck`, `fake-shipped`, `seller-history`.
77
+ - Post-sale seller IM: `seller chat`, `seller messages <orderId|loginId>`.
78
+ - Account/session: `login`, `logout`, `whoami`, `doctor`, `daemon`, `serve`.
79
+
80
+ ## Browser And Session Model
81
+
82
+ - The tool uses a persistent browser profile under `~/.1688`.
83
+ - The daemon reuses one browser context and adds jitter between commands.
84
+ - Commands should handle login redirects, risk-control pages, and browser
85
+ closure through structured exit codes.
86
+ - `--headed` is the manual escape hatch for slider verification.
87
+ - Browser probes under `scripts/probe-*.mjs` are exploratory tools, not stable
88
+ verification gates.
89
+
90
+ ## Generated Context
91
+
92
+ - Run `pnpm agent-context` after changing commands, source layout, tests, or
93
+ exported JSON result interfaces.
94
+ - Generated files live under `docs/generated`.
95
+ - Do not hand-edit generated files; change
96
+ `scripts/generate_agent_context.mjs` instead.
97
+
98
+ ## Verification Surfaces
99
+
100
+ - Type safety: `pnpm typecheck`
101
+ - Deterministic tests: `pnpm test:unit`
102
+ - Full test suite including live doctor checks: `pnpm test`
103
+ - Agent indexes: `pnpm agent-context`
104
+ - Generated docs freshness: `pnpm docs-check`
105
+ - Agent map structure: `pnpm agent-map-check`
106
+ - Default gate: `pnpm agent-verify`
package/CHANGELOG.md CHANGED
@@ -3,6 +3,113 @@
3
3
  All notable changes to this project are documented here.
4
4
  This project follows [Semantic Versioning](https://semver.org/).
5
5
 
6
+ ## [0.1.41] - 2026-05-16
7
+
8
+ ### Added
9
+ - **`1688 inbox` now decodes 1688 IM card messages.** What previously
10
+ rendered as `kind: 'other'` / `preview: '[非文本消息]'` is now broken
11
+ out into structured fields. The decoder reads two parallel sources
12
+ (`content.custom.data` base64-JSON and
13
+ `message.extension.dynamic_msg_content` template JSON), picks the
14
+ best preview text across `productTitle` / `refundTitle` /
15
+ `offerSubTitle` / `title` / `summary`, and emits:
16
+ - `lastMessage.kind` — now `'text' | 'image' | 'card' | 'archived' | 'other'`
17
+ - `lastMessage.cardTemplate` — semantic name when known
18
+ (`'order_followup'`, `'refund'`, `'offer'`, `'order_payment_reminder'`,
19
+ `'address_changed'`, `'evaluation_invite'`, `'coupon'`,
20
+ `'session_ended'`, etc.)
21
+ - `lastMessage.cardCode` — raw 6-digit template code (`170002`, `467001`,
22
+ …) so agents can filter on unmapped templates too
23
+ - `lastMessage.extras` — `{orderId, offerId, refundId, imgUrl, linkUrl,
24
+ amount}`, populated only when at least one field resolved (keeps
25
+ JSON output compact)
26
+ - New `'archived'` kind marks conversations where the server stripped
27
+ `content` entirely (observed on all messages > ~12 months old —
28
+ not a parser failure, just a server retention boundary).
29
+
30
+ Decoder is a pure function in `src/session/im-cards.ts` so it's
31
+ reusable from future commands and easily testable. Live-validated on
32
+ a 2430-conversation account: 421 of 444 cards (95%) get a meaningful
33
+ preview; remaining 23 cards fall back to `'[卡片消息]'` placeholder
34
+ with `cardCode` still surfaced. Tests in `tests/im-cards.test.ts`
35
+ (14 new) and `tests/inbox.test.ts` (updated).
36
+
37
+ - **Opt-in JSON v2 response envelope** (`--envelope v2` / `BB1688_JSON_ENVELOPE=v2`).
38
+ Wraps command output in `{ok, code, data, error, meta}` with a stable
39
+ `meta.requestId` so agents can correlate output with the event log
40
+ (see below) and debug bundles. Default JSON shape is unchanged —
41
+ existing callers keep working bit-for-bit. Implemented in `src/io/output.ts`
42
+ with coverage in `tests/output.test.ts`.
43
+
44
+ - **`1688 profile list` / `1688 profile status`.** A minimal profile
45
+ inventory backed by `~/.1688/profiles/`. `list` enumerates known
46
+ profiles with login state and last-used hints; `status <name>` reports
47
+ state file health, lock holder (if any), and the last few command
48
+ events for that profile. New config loader + validation in
49
+ `src/session/config.ts`; commands in `src/commands/profile.ts`. Tests:
50
+ `tests/config.test.ts`, `tests/profile.test.ts`.
51
+
52
+ - **`1688 doctor --live`.** Extends `1688 doctor` with read-only live
53
+ checks: daemon reachability, event-log writability, artifact directory
54
+ writability, and recent risk-control signals from `~/.1688/runs/`.
55
+ Pure observation — no browser is started, no profile is touched.
56
+ `src/commands/doctor.ts`, `tests/doctor-live.test.ts`.
57
+
58
+ - **`1688 debug list / last / show`.** Read-only post-mortem surface for
59
+ the command event log. `list` paginates recent commands;
60
+ `last` jumps to the most recent run; `show <requestId>` prints the
61
+ start/success/error records plus pointers into the matching
62
+ `~/.1688/runs/<requestId>/` artifact bundle. Powered by the new event
63
+ system (see below). `src/commands/debug.ts`, `tests/debug.test.ts`.
64
+
65
+ - **Command request event log** (`~/.1688/events/`). Dispatched commands
66
+ now record `start`, `success`, and `error` events scoped to a
67
+ per-invocation `requestId`. Captured stdout/stderr aren't modified —
68
+ events are written out-of-band so existing JSON output stays
69
+ bit-for-bit identical. Drives `debug`, `profile status`, and
70
+ `doctor --live`. `src/session/events.ts`, `src/session/dispatch.ts`,
71
+ `src/daemon/client.ts`; `tests/events.test.ts`.
72
+
73
+ - **Navigation-guard classifier (`src/session/navigation-guard.ts`).**
74
+ Tags unexpected page destinations encountered mid-command — login,
75
+ risk-control / verification, payment, or off-host external — so
76
+ commands can decide whether to retry, prompt, or fail with a
77
+ classified diagnostic instead of a raw selector-timeout. Currently
78
+ available as a helper; downstream commands will adopt it
79
+ incrementally. `tests/navigation-guard.test.ts`.
80
+
81
+ ### Changed
82
+ - **`cart-add` / `cart-list` response capture scoped to its triggering
83
+ action.** Listeners are now armed immediately before the action that
84
+ causes the mtop response and disposed in `finally`, so capture
85
+ lifetimes track navigation/click boundaries. Ambiguous add-to-cart
86
+ confirmations now surface capture diagnostics (which event arrived,
87
+ which didn't) instead of generic timeouts.
88
+
89
+ - **`search` capture lifecycle refactor.** Search / image-search /
90
+ similar listeners are now armed immediately before the triggering
91
+ action (initial navigation OR pagination click) and torn down in
92
+ `finally`. Page-close events surface `browser_closed` immediately
93
+ instead of waiting for polling timeouts. Capture also records timing,
94
+ final status, and parser failures so failures produce structured
95
+ diagnostics. Same offer dedup / pagination behavior as 0.1.40 —
96
+ purely a lifecycle and observability change
97
+ (`src/session/search-capture.ts`, `src/commands/search.ts`,
98
+ `image-search.ts`, `similar.ts`).
99
+
100
+ - **Shared deadline-aware polling helper.** The deadline loop in
101
+ `src/session/wait.ts` now backs search capture's blocking waits
102
+ (previously had its own ad-hoc remaining-time math). Behavior
103
+ unchanged, but timeout handling is consistent and unit-tested in one
104
+ place (`tests/wait.test.ts`).
105
+
106
+ ### Tests
107
+ - **Replay fixtures for offline parser coverage.** Sanitized
108
+ `getOfferList` mtop captures, cart `addcargo` success/failure
109
+ responses, and a risk-control page-state HTML now back
110
+ `tests/replay-fixtures.test.ts`. Parser and navigation classification
111
+ changes won't silently drift even if no live env is available.
112
+
6
113
  ## [0.1.40] - 2026-05-15
7
114
 
8
115
  ### Added