@open-dy/interest-card-cli 0.1.0-beta.28 → 0.1.0-beta.30

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.
@@ -50,6 +50,14 @@ async function postAuth(route, body, headers = {}) {
50
50
  }
51
51
  return { response, envelope, xTtLogid: response.headers.get('x-tt-logid') || undefined };
52
52
  }
53
+ /**
54
+ * The account id of a token answer. Only a string of digits is taken: a number would already have
55
+ * lost digits in JSON.parse, and anything else is not an id.
56
+ */
57
+ export function tokenUserId(value) {
58
+ const id = typeof value === 'string' ? value.trim() : '';
59
+ return /^[1-9]\d{0,31}$/.test(id) ? id : undefined;
60
+ }
53
61
  function tokenConfigFrom(base, envelope, now = Date.now()) {
54
62
  const data = envelope?.data;
55
63
  if (Number(envelope?.error ?? 0) !== 0 || !data) {
@@ -70,6 +78,10 @@ function tokenConfigFrom(base, envelope, now = Date.now()) {
70
78
  scopes: null,
71
79
  user: { ...base.user },
72
80
  };
81
+ const userId = tokenUserId(data.user_id);
82
+ if (userId) {
83
+ config.creator_uid = userId;
84
+ }
73
85
  if (!isBearerCredentialConfig(config)) {
74
86
  return undefined;
75
87
  }
@@ -1,3 +1,4 @@
1
+ import { noteTelemetryProject } from '../telemetry-project.js';
1
2
  import { getString } from '../cli-helpers.js';
2
3
  import { printText } from '../output.js';
3
4
  import { buildWorkspaceHeaders } from '../platform.js';
@@ -46,6 +47,8 @@ export async function handleCardCreate(parsed) {
46
47
  tenant,
47
48
  name: requestedName,
48
49
  });
50
+ // Noted at once: the project exists from here on, whatever happens to the first message.
51
+ noteTelemetryProject({ projectId, conversationId });
49
52
  const projectUrl = buildProjectPageUrl(projectId);
50
53
  const target = { config, headers, conversationId, projectId };
51
54
  const messageId = await sendCardMessage(target, blank
@@ -1,3 +1,4 @@
1
+ import { noteTelemetryProject } from '../telemetry-project.js';
1
2
  import { getString } from '../cli-helpers.js';
2
3
  import { applyRuntimeConfigOverrides, hasExplicitPlatform, loadCommandConfig, } from '../command-context.js';
3
4
  import { cardAuthFor } from './card-token.js';
@@ -65,6 +66,8 @@ export async function resolveCardProject(config, projectId, tenant) {
65
66
  productTypes: (app.conversationList || []).map(item => item.productType || item.sourceType),
66
67
  });
67
68
  }
69
+ // The project this command works on, for its telemetry event.
70
+ noteTelemetryProject({ projectId: app.id || projectId, conversationId: conversation.conversationId });
68
71
  return {
69
72
  projectId: app.id || projectId,
70
73
  projectName: app.name,
@@ -1,3 +1,4 @@
1
+ import { noteTelemetryProject } from '../telemetry-project.js';
1
2
  import { getString } from '../cli-helpers.js';
2
3
  import { printText } from '../output.js';
3
4
  import { buildWorkspaceHeaders } from '../platform.js';
@@ -54,6 +55,7 @@ export async function handleCardRename(parsed) {
54
55
  if (!projectId) {
55
56
  throw new CliError('No project given. Pass --project <projectUrl|projectId>, or run inside a pulled card directory.', 'CARD_INVALID_ARGS');
56
57
  }
58
+ noteTelemetryProject({ projectId });
57
59
  await updateProjectName(config, headers, projectId, name);
58
60
  if (root) {
59
61
  const binding = await readBinding(root);
@@ -0,0 +1,16 @@
1
+ let noted = {};
2
+ /** Later notes fill in or replace earlier ones. Never throws. */
3
+ export function noteTelemetryProject(project) {
4
+ noted = {
5
+ ...noted,
6
+ ...(project.projectId ? { projectId: project.projectId } : {}),
7
+ ...(project.conversationId ? { conversationId: project.conversationId } : {}),
8
+ };
9
+ }
10
+ export function notedTelemetryProject() {
11
+ return { ...noted };
12
+ }
13
+ /** For tests: one process there runs many commands. */
14
+ export function resetTelemetryProject() {
15
+ noted = {};
16
+ }
@@ -5,11 +5,13 @@ import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { readBinding, findProjectRoot } from './card/binding.js';
8
+ import { CARD_PROJECT_PAGE_URL } from './card/constants.js';
8
9
  import { getString } from './cli-helpers.js';
9
10
  import { resolveCommandConfigPath } from './command-context.js';
10
11
  import { getConfigBaseUrl, resolveConfigPath, tryLoadConfig } from './config.js';
11
12
  import { isCreatorPlatform, isExternalPlatform } from './platform.js';
12
13
  import { laneHeaders } from './request-source.js';
14
+ import { notedTelemetryProject } from './telemetry-project.js';
13
15
  import { CliError, DEFAULT_CONFIG_DIR } from './types.js';
14
16
  import { getCliVersion } from './version.js';
15
17
  /**
@@ -76,6 +78,164 @@ export function telemetryLoginMethod(parsed) {
76
78
  }
77
79
  return parsed.options.qr ? 'qr' : 'link';
78
80
  }
81
+ const ERROR_MESSAGE_MAX_CHARS = 300;
82
+ const ERROR_DETAIL_MAX_CHARS = 200;
83
+ const ERROR_TOTAL_MAX_CHARS = 1000;
84
+ const LOGID_PATTERN = /^[A-Za-z0-9]{8,64}$/;
85
+ /** Applied in order. What is left is for finding the cause, not for reading someone's machine. */
86
+ const ERROR_MESSAGE_REDACTIONS = [
87
+ // Credentials: CLI tokens, bearer headers, cookie pairs, JSON fields, then any other long opaque string.
88
+ [/\bict\.[\w.-]+/g, 'ict.<redacted>'],
89
+ [/\bBearer\s+\S+/gi, 'Bearer <redacted>'],
90
+ [/\b([\w-]*(?:session|sid|token|passport|secret|cookie)[\w-]*)=[^;\s&"']+/gi, '$1=<redacted>'],
91
+ [
92
+ /(["']?[\w-]*(?:session|sid|token|passport|secret|cookie|password)[\w-]*["']?\s*:\s*)(?:"[^"]*"|'[^']*'|[^\s,}]+)/gi,
93
+ '$1<redacted>',
94
+ ],
95
+ [/[A-Za-z0-9+/_-]{40,}={0,2}/g, '<redacted>'],
96
+ [/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/g, '<email>'],
97
+ // A query string can carry anything; the path is enough to tell which request failed.
98
+ [/(https?:\/\/[^\s?#"']+)[?#][^\s"']*/g, '$1'],
99
+ ];
100
+ /**
101
+ * `CliError.details` fields worth reporting, in the order they are written. Only these are read:
102
+ * `hint` is fixed text, `projectId` has its own param, and `data` / `response` / `stdout` can hold
103
+ * whatever the server or a child process answered.
104
+ */
105
+ const ERROR_DETAIL_KEYS = [
106
+ 'status',
107
+ 'code',
108
+ 'error',
109
+ 'errorCode',
110
+ 'rpcCode',
111
+ 'causeCode',
112
+ 'exitCode',
113
+ 'exit',
114
+ 'method',
115
+ 'route',
116
+ 'path',
117
+ 'url',
118
+ 'op',
119
+ 'command',
120
+ 'registry',
121
+ 'contentType',
122
+ 'redirected',
123
+ 'timeoutSeconds',
124
+ 'timeoutMs',
125
+ 'retryAfterSeconds',
126
+ 'reason',
127
+ 'reasons',
128
+ 'message',
129
+ 'msg',
130
+ 'cause',
131
+ 'stderr',
132
+ ];
133
+ /** A failed response's JSON body: only what says why it failed. */
134
+ const ERROR_BODY_KEYS = ['code', 'error', 'error_code', 'err_no', 'status_code', 'message', 'msg', 'err_msg'];
135
+ function cleanErrorText(text, home, maxChars, keepEnd = false) {
136
+ let cleaned = text.replace(/\s+/g, ' ').trim();
137
+ if (home && home !== path.sep) {
138
+ cleaned = cleaned.split(home).join('~');
139
+ }
140
+ cleaned = cleaned.replace(/([A-Za-z]:\\Users\\|\/Users\/|\/home\/)[^\s\\/"']+/g, '$1<user>');
141
+ for (const [pattern, replacement] of ERROR_MESSAGE_REDACTIONS) {
142
+ cleaned = cleaned.replace(pattern, replacement);
143
+ }
144
+ if (cleaned.length <= maxChars) {
145
+ return cleaned;
146
+ }
147
+ // A child's stderr says what went wrong at the end, a message at the start.
148
+ return keepEnd ? `…${cleaned.slice(-maxChars)}` : `${cleaned.slice(0, maxChars)}…`;
149
+ }
150
+ function detailText(value) {
151
+ if (typeof value === 'string') {
152
+ return value;
153
+ }
154
+ if (typeof value === 'number' || typeof value === 'boolean') {
155
+ return String(value);
156
+ }
157
+ if (value instanceof Error) {
158
+ return value.message;
159
+ }
160
+ if (Array.isArray(value)) {
161
+ return value.map(detailText).filter(Boolean).join('; ');
162
+ }
163
+ return '';
164
+ }
165
+ function bodyDetails(body) {
166
+ if (typeof body !== 'string' || !body.trim().startsWith('{')) {
167
+ return [];
168
+ }
169
+ try {
170
+ const parsed = JSON.parse(body);
171
+ return ERROR_BODY_KEYS.map(key => [`body.${key}`, detailText(parsed[key])]);
172
+ }
173
+ catch {
174
+ // Cut or not JSON: nothing in it can be told apart from the rest.
175
+ return [];
176
+ }
177
+ }
178
+ /** Node's own failures: `ENOENT`, `EACCES`, and what `fetch failed` hides in `cause`. */
179
+ function nativeErrorDetails(error) {
180
+ const pairs = [];
181
+ if (!(error instanceof Error)) {
182
+ return pairs;
183
+ }
184
+ if (!(error instanceof CliError)) {
185
+ if (error.name && error.name !== 'Error') {
186
+ pairs.push(['name', error.name]);
187
+ }
188
+ pairs.push(['code', detailText(error.code)]);
189
+ pairs.push(['syscall', detailText(error.syscall)]);
190
+ }
191
+ const { cause } = error;
192
+ if (cause instanceof Error) {
193
+ pairs.push(['cause', cause.message]);
194
+ pairs.push(['causeCode', detailText(cause.code)]);
195
+ }
196
+ else {
197
+ pairs.push(['cause', detailText(cause)]);
198
+ }
199
+ return pairs;
200
+ }
201
+ /**
202
+ * The failed command's message for `err_msg`, with what the error knows about why: HTTP status,
203
+ * server / RPC / exit codes, the request path, the underlying cause, the end of a child's stderr,
204
+ * and the server's log id. One line, without the home directory, credentials or emails, every
205
+ * part cut to a fixed length. Messages are written by the CLI or answered by the server; the
206
+ * creator's prompt is never part of one.
207
+ */
208
+ export function telemetryErrorMessage(error, home = os.homedir()) {
209
+ const message = cleanErrorText(error instanceof Error ? error.message : typeof error === 'string' ? error : '', home, ERROR_MESSAGE_MAX_CHARS);
210
+ const details = error instanceof CliError && typeof error.details === 'object' && error.details !== null
211
+ ? error.details
212
+ : {};
213
+ const pairs = [
214
+ ...ERROR_DETAIL_KEYS.map(key => [key, detailText(details[key])]),
215
+ ...bodyDetails(details.body),
216
+ ...nativeErrorDetails(error),
217
+ ];
218
+ const seen = new Set();
219
+ const parts = [];
220
+ for (const [key, raw] of pairs) {
221
+ const value = cleanErrorText(raw, home, ERROR_DETAIL_MAX_CHARS, key === 'stderr');
222
+ // The message often repeats a detail (the server's `msg`, an exit code): say it once.
223
+ if (!value || seen.has(key) || message.includes(value) && value.length > 3) {
224
+ continue;
225
+ }
226
+ seen.add(key);
227
+ parts.push(`${key}=${value}`);
228
+ }
229
+ const logid = typeof details.xTtLogid === 'string' && LOGID_PATTERN.test(details.xTtLogid)
230
+ ? details.xTtLogid
231
+ : '';
232
+ const tail = logid ? ` [logid=${logid}]` : '';
233
+ let text = [message, parts.join(' ')].filter(Boolean).join(' | ');
234
+ if (text.length > ERROR_TOTAL_MAX_CHARS - tail.length) {
235
+ text = `${text.slice(0, ERROR_TOTAL_MAX_CHARS - tail.length - 1)}…`;
236
+ }
237
+ return `${text}${tail}`.trim();
238
+ }
79
239
  export function telemetryErrorCode(error) {
80
240
  if (error instanceof CliError && ERROR_CODE_PATTERN.test(error.code)) {
81
241
  return error.code;
@@ -90,6 +250,13 @@ export function telemetryPlatform(baseUrl) {
90
250
  return isExternalPlatform(baseUrl) ? 'external' : undefined;
91
251
  }
92
252
  export function telemetryUserId(config) {
253
+ // The server's answer wins: a link login has nothing else, and an older login may carry an email.
254
+ const serverId = config && 'creator_uid' in config && typeof config.creator_uid === 'string'
255
+ ? config.creator_uid.trim()
256
+ : '';
257
+ if (serverId) {
258
+ return serverId;
259
+ }
93
260
  const id = config?.user?.email?.trim() || '';
94
261
  return PLACEHOLDER_USER_IDS.has(id) ? undefined : id;
95
262
  }
@@ -110,12 +277,15 @@ export function buildTelemetryJob(telemetry, identity, options = {}) {
110
277
  result: telemetry.result,
111
278
  duration_ms: Math.max(0, Math.round(telemetry.durationMs)),
112
279
  error_code: telemetry.errorCode || '',
113
- // Raw error messages can hold paths and prompts, so err_msg stays empty.
114
- err_msg: '',
280
+ err_msg: telemetry.errorMessage || '',
115
281
  website: WEBSITE_BY_PLATFORM[identity.platform || 'creator'],
116
282
  app_mode: INTEREST_CARD_APP_MODE,
117
283
  product_type: INTEREST_CARD_PRODUCT_TYPE,
118
284
  conversation_id: telemetry.conversationId || '',
285
+ project_id: telemetry.projectId || '',
286
+ project_url: telemetry.projectId
287
+ ? `${CARD_PROJECT_PAGE_URL}/${encodeURIComponent(telemetry.projectId)}`
288
+ : '',
119
289
  // CLI params.
120
290
  command: telemetry.command,
121
291
  output: telemetry.json ? 'json' : 'text',
@@ -152,17 +322,19 @@ export async function reportCommand(parsed, outcome) {
152
322
  return;
153
323
  }
154
324
  const failed = 'error' in outcome;
155
- const [identity, conversationId] = await Promise.all([
325
+ const [identity, project] = await Promise.all([
156
326
  resolveIdentity(parsed),
157
- resolveConversationId(parsed),
327
+ resolveProject(parsed),
158
328
  ]);
159
329
  const job = buildTelemetryJob({
160
330
  command: telemetryCommandName(parsed),
161
331
  result: outcome.canceled ? 'canceled' : failed ? 'fail' : 'success',
162
332
  errorCode: failed ? telemetryErrorCode(outcome.error) : undefined,
333
+ errorMessage: failed ? telemetryErrorMessage(outcome.error) : undefined,
163
334
  durationMs: Date.now() - outcome.startedAt,
164
335
  json: Boolean(parsed.options.json),
165
- conversationId,
336
+ conversationId: project.conversationId,
337
+ projectId: project.projectId,
166
338
  attemptId: outcome.attemptId,
167
339
  loginMethod: telemetryLoginMethod(parsed),
168
340
  }, identity);
@@ -206,19 +378,33 @@ export function trackCommand(parsed, startedAt = Date.now()) {
206
378
  dispose,
207
379
  };
208
380
  }
209
- /** Card commands run inside a bound project; anything else (or a broken binding) reports none. */
210
- async function resolveConversationId(parsed) {
211
- if (parsed.command !== 'card') {
212
- return undefined;
213
- }
214
- try {
215
- const root = await findProjectRoot(getString(parsed, 'dir') || process.cwd());
216
- const id = (await readBinding(root)).conversationId;
217
- return CONVERSATION_ID_PATTERN.test(id) ? id : undefined;
218
- }
219
- catch {
220
- return undefined;
381
+ /**
382
+ * The project of one event. What the command noted wins: it is the project the command really
383
+ * worked on (`create`, `pull <project>`, `--project`), which may not be the current directory's.
384
+ * The binding fills in what a note of the same project left out, and stands alone when nothing
385
+ * was noted. Ids that do not look like ids are dropped.
386
+ */
387
+ export function telemetryProject(noted, binding) {
388
+ const hasNote = Boolean(noted.projectId || noted.conversationId);
389
+ const sameProject = !noted.projectId || noted.projectId === binding.projectId;
390
+ const merged = !hasNote ? binding : sameProject && !noted.conversationId ? { ...binding, ...noted } : noted;
391
+ const clean = (id) => (id && CONVERSATION_ID_PATTERN.test(id) ? id : undefined);
392
+ return { projectId: clean(merged.projectId), conversationId: clean(merged.conversationId) };
393
+ }
394
+ /** Card commands run inside a bound project; anything else (or a broken binding) has no binding. */
395
+ async function resolveProject(parsed) {
396
+ let binding = {};
397
+ if (parsed.command === 'card') {
398
+ try {
399
+ const root = await findProjectRoot(getString(parsed, 'dir') || process.cwd());
400
+ const read = await readBinding(root);
401
+ binding = { projectId: read.projectId, conversationId: read.conversationId };
402
+ }
403
+ catch {
404
+ binding = {};
405
+ }
221
406
  }
407
+ return telemetryProject(notedTelemetryProject(), binding);
222
408
  }
223
409
  async function resolveIdentity(parsed) {
224
410
  let config;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-dy/interest-card-cli",
3
- "version": "0.1.0-beta.28",
3
+ "version": "0.1.0-beta.30",
4
4
  "description": "Pull, edit and sync Douyin interest card projects locally with any AI agent",
5
5
  "private": false,
6
6
  "type": "module",