@dayzehq/cli 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +305 -2
  3. package/dist/add.d.ts +6 -0
  4. package/dist/add.js +72 -0
  5. package/dist/admin.d.ts +110 -0
  6. package/dist/admin.js +408 -0
  7. package/dist/agent-bridge.d.ts +50 -0
  8. package/dist/agent-bridge.js +146 -0
  9. package/dist/agent-mcp.d.ts +4 -0
  10. package/dist/agent-mcp.js +36 -0
  11. package/dist/ai-consent.d.ts +18 -0
  12. package/dist/ai-consent.js +93 -0
  13. package/dist/args.d.ts +5 -0
  14. package/dist/args.js +127 -0
  15. package/dist/auth.d.ts +20 -0
  16. package/dist/auth.js +198 -0
  17. package/dist/channel.d.ts +55 -0
  18. package/dist/channel.js +250 -0
  19. package/dist/chat.d.ts +67 -0
  20. package/dist/chat.js +170 -0
  21. package/dist/cli-errors.d.ts +13 -0
  22. package/dist/cli-errors.js +30 -0
  23. package/dist/coding-context.d.ts +12 -0
  24. package/dist/coding-context.js +130 -0
  25. package/dist/coding.d.ts +35 -0
  26. package/dist/coding.js +283 -0
  27. package/dist/config.d.ts +36 -0
  28. package/dist/config.js +149 -0
  29. package/dist/day.d.ts +22 -0
  30. package/dist/day.js +54 -0
  31. package/dist/dayze-cli-runtime +0 -0
  32. package/dist/dayze-days.d.ts +56 -0
  33. package/dist/dayze-days.js +276 -0
  34. package/dist/doctor.d.ts +32 -0
  35. package/dist/doctor.js +225 -0
  36. package/dist/focus.d.ts +9 -0
  37. package/dist/focus.js +163 -0
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +675 -0
  40. package/dist/inventory.d.ts +73 -0
  41. package/dist/inventory.js +1272 -0
  42. package/dist/life.d.ts +48 -0
  43. package/dist/life.js +146 -0
  44. package/dist/me.d.ts +94 -0
  45. package/dist/me.js +789 -0
  46. package/dist/people.d.ts +232 -0
  47. package/dist/people.js +2034 -0
  48. package/dist/projects.d.ts +21 -0
  49. package/dist/projects.js +132 -0
  50. package/dist/request-deadline.d.ts +11 -0
  51. package/dist/request-deadline.js +34 -0
  52. package/dist/runtime-build.json +1 -0
  53. package/dist/ui.d.ts +37 -0
  54. package/dist/ui.js +219 -0
  55. package/dist/version.d.ts +4 -0
  56. package/dist/version.js +16 -0
  57. package/package.json +54 -4
package/dist/people.js ADDED
@@ -0,0 +1,2034 @@
1
+ /**
2
+ * Industry-standard contact directory for Dayze CLI.
3
+ *
4
+ * Patterns borrowed from khard / abook / fzf:
5
+ * - Load full address book once (typical CRM size is fine in memory)
6
+ * - Live type-ahead filter (no modal search)
7
+ * - Vim keys + arrows, letter sections, detail pane on Enter
8
+ * - Plain `list` / `show` for scripts and piping
9
+ */
10
+ import readline from 'node:readline/promises';
11
+ import { stdin as input, stdout as output } from 'node:process';
12
+ import { authHeader } from './config.js';
13
+ import { askAgent } from './chat.js';
14
+ import { printJson } from './cli-errors.js';
15
+ import { fetchJsonWithDeadline } from './request-deadline.js';
16
+ import * as ui from './ui.js';
17
+ import { CLI_USER_AGENT } from './version.js';
18
+ import { PEOPLE_ADD_FIELDS, parseAddArgs, postAdd } from './add.js';
19
+ import { dayNumberFromBirthday, daysToNextBirthday, formatBirthdayDisplay, formatDayNumber, formatDayNumberForPrecision, formatDaysToBday, formatTimeAlive, normalizeBirthdayInput, normalizeBirthTimeInput, resolveBirthdayPrecision, timeAliveFromBirth, } from './dayze-days.js';
20
+ const EDITABLE_FIELDS = [
21
+ { key: 'notes', label: 'Notes' },
22
+ { key: 'relationship', label: 'Relationship' },
23
+ { key: 'occupation', label: 'Occupation' },
24
+ { key: 'company', label: 'Company' },
25
+ { key: 'phone', label: 'Phone' },
26
+ { key: 'email', label: 'Email' },
27
+ { key: 'address', label: 'Location' },
28
+ { key: 'first_met', label: 'First met' },
29
+ { key: 'first_met_location', label: 'Met at' },
30
+ { key: 'birthday', label: 'Birthday' },
31
+ { key: 'birth_time', label: 'Birth time' },
32
+ { key: 'instagram', label: 'Instagram' },
33
+ { key: 'linkedin', label: 'LinkedIn' },
34
+ { key: 'twitter', label: 'Twitter/X' },
35
+ { key: 'website', label: 'Website' },
36
+ { key: 'tier', label: 'Tier' },
37
+ { key: 'pronouns', label: 'Pronouns' },
38
+ { key: 'gender', label: 'Gender' },
39
+ ];
40
+ async function promptLine(question) {
41
+ process.stdout.write('\x1b[?25h');
42
+ const rl = readline.createInterface({ input, output, terminal: true });
43
+ try {
44
+ return (await rl.question(question)).trim();
45
+ }
46
+ finally {
47
+ rl.close();
48
+ }
49
+ }
50
+ export const PEOPLE_SORT_CYCLE = [
51
+ 'name',
52
+ 'day-desc',
53
+ 'day-asc',
54
+ 'birthday',
55
+ 'last',
56
+ ];
57
+ export function parsePeopleSort(raw) {
58
+ if (!raw)
59
+ return null;
60
+ const s = raw.trim().toLowerCase();
61
+ if (s === 'name' || s === 'alpha' || s === 'a-z')
62
+ return 'name';
63
+ if (s === 'day' || s === 'day-desc' || s === 'days' || s === 'dayage' || s === 'age')
64
+ return 'day-desc';
65
+ if (s === 'day-asc' || s === 'youngest')
66
+ return 'day-asc';
67
+ if (s === 'birthday' || s === 'bday' || s === '→bday' || s === 'bday-asc')
68
+ return 'birthday';
69
+ if (s === 'last' || s === 'recent' || s === 'contacted')
70
+ return 'last';
71
+ return null;
72
+ }
73
+ export function peopleSortLabel(sort) {
74
+ switch (sort) {
75
+ case 'name':
76
+ return 'name';
77
+ case 'day-desc':
78
+ return 'day↓';
79
+ case 'day-asc':
80
+ return 'day↑';
81
+ case 'birthday':
82
+ return '→bday';
83
+ case 'last':
84
+ return 'last';
85
+ }
86
+ }
87
+ export function sortPeople(people, sort) {
88
+ const byName = (a, b) => (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' });
89
+ const list = [...people];
90
+ switch (sort) {
91
+ case 'name':
92
+ return list.sort(byName);
93
+ case 'day-desc':
94
+ return list.sort((a, b) => {
95
+ const da = dayNumberFromBirthday(a.birthday ?? null);
96
+ const db = dayNumberFromBirthday(b.birthday ?? null);
97
+ if (da == null && db == null)
98
+ return byName(a, b);
99
+ if (da == null)
100
+ return 1;
101
+ if (db == null)
102
+ return -1;
103
+ return db - da;
104
+ });
105
+ case 'day-asc':
106
+ return list.sort((a, b) => {
107
+ const da = dayNumberFromBirthday(a.birthday ?? null);
108
+ const db = dayNumberFromBirthday(b.birthday ?? null);
109
+ if (da == null && db == null)
110
+ return byName(a, b);
111
+ if (da == null)
112
+ return 1;
113
+ if (db == null)
114
+ return -1;
115
+ return da - db;
116
+ });
117
+ case 'birthday':
118
+ return list.sort((a, b) => {
119
+ const da = daysToNextBirthday(a.birthday ?? null, new Date(), a.birthday_precision);
120
+ const db = daysToNextBirthday(b.birthday ?? null, new Date(), b.birthday_precision);
121
+ if (da == null && db == null)
122
+ return byName(a, b);
123
+ if (da == null)
124
+ return 1;
125
+ if (db == null)
126
+ return -1;
127
+ return da - db;
128
+ });
129
+ case 'last':
130
+ return list.sort((a, b) => {
131
+ const ta = a.last_interaction_at ? new Date(a.last_interaction_at).getTime() : 0;
132
+ const tb = b.last_interaction_at ? new Date(b.last_interaction_at).getTime() : 0;
133
+ if (!ta && !tb)
134
+ return byName(a, b);
135
+ if (!ta)
136
+ return 1;
137
+ if (!tb)
138
+ return -1;
139
+ return tb - ta;
140
+ });
141
+ }
142
+ }
143
+ const LABEL_W = 16;
144
+ function kv(label, value) {
145
+ console.log(` ${ui.c.dim(label.padEnd(LABEL_W))} ${value}`);
146
+ }
147
+ function section(title) {
148
+ console.log('');
149
+ console.log(ui.c.bold(` ${title}`));
150
+ }
151
+ function formatDateLabel(iso) {
152
+ if (!iso)
153
+ return null;
154
+ const d = String(iso).trim().slice(0, 10);
155
+ if (!/^\d{4}-\d{2}-\d{2}/.test(d))
156
+ return String(iso).trim();
157
+ const dt = new Date(`${d}T12:00:00`);
158
+ if (!Number.isFinite(dt.getTime()))
159
+ return d;
160
+ return dt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
161
+ }
162
+ function formatLocationEntry(loc) {
163
+ if (loc.approximate?.trim())
164
+ return loc.approximate.trim();
165
+ const parts = [loc.street, loc.city, loc.stateRegion, loc.postalCode, loc.country]
166
+ .map((x) => (x || '').trim())
167
+ .filter(Boolean);
168
+ return parts.join(', ');
169
+ }
170
+ function primaryLocation(p) {
171
+ const locs = Array.isArray(p.locations) ? p.locations : [];
172
+ const primary = locs.find((l) => l.isPrimary) || locs[0];
173
+ if (primary) {
174
+ const formatted = formatLocationEntry(primary);
175
+ if (formatted) {
176
+ const label = primary.label?.trim();
177
+ return label ? `${formatted} (${label})` : formatted;
178
+ }
179
+ }
180
+ return p.address?.trim() || null;
181
+ }
182
+ const SMOKING_LABELS = {
183
+ non_smoker: 'Non-smoker',
184
+ occasional: 'Occasional',
185
+ smoker: 'Smoker',
186
+ former: 'Former smoker',
187
+ unknown: 'Unknown',
188
+ };
189
+ const DRINKING_LABELS = {
190
+ none: 'Does not drink',
191
+ social: 'Social',
192
+ regular: 'Regular',
193
+ sober: 'Sober / recovery',
194
+ unknown: 'Unknown',
195
+ };
196
+ function lifestyleLines(ctx) {
197
+ const life = ctx?.lifestyle;
198
+ if (!life)
199
+ return [];
200
+ const rows = [];
201
+ if (life.smoking)
202
+ rows.push(['Smoking', SMOKING_LABELS[life.smoking] || life.smoking]);
203
+ if (life.drinking)
204
+ rows.push(['Drinking', DRINKING_LABELS[life.drinking] || life.drinking]);
205
+ if (life.substances?.length)
206
+ rows.push(['Substances', life.substances.join(', ')]);
207
+ if (life.notes?.trim())
208
+ rows.push(['Lifestyle', life.notes.trim()]);
209
+ return rows;
210
+ }
211
+ export async function fetchPeoplePage(creds, opts = {}) {
212
+ const header = authHeader(creds);
213
+ if (!header)
214
+ throw new Error('Not logged in');
215
+ const params = new URLSearchParams();
216
+ if (opts.q)
217
+ params.set('q', opts.q);
218
+ if (opts.letter)
219
+ params.set('letter', opts.letter);
220
+ params.set('limit', String(opts.limit ?? 80));
221
+ params.set('offset', String(opts.offset ?? 0));
222
+ return fetchJsonWithDeadline(`${creds.apiBase}/api/cli/people?${params}`, {
223
+ headers: { Authorization: header, Accept: 'application/json', 'User-Agent': CLI_USER_AGENT },
224
+ }, {
225
+ timeoutMessage: 'Loading people timed out after 15 seconds. Check your connection and retry dayze people list.',
226
+ httpErrorMessage: (status, bodyPreview) => `Failed to list people (${status}): ${bodyPreview}`,
227
+ });
228
+ }
229
+ export async function fetchAllPeople(creds, opts = {}) {
230
+ const pageSize = 200;
231
+ let offset = 0;
232
+ const all = [];
233
+ for (;;) {
234
+ const page = await fetchPeoplePage(creds, { ...opts, limit: pageSize, offset });
235
+ all.push(...page.people);
236
+ if (!page.hasMore || page.people.length === 0)
237
+ break;
238
+ offset += page.people.length;
239
+ if (offset > 5000)
240
+ break;
241
+ }
242
+ return all;
243
+ }
244
+ export async function fetchPersonDetail(creds, id) {
245
+ const header = authHeader(creds);
246
+ if (!header)
247
+ throw new Error('Not logged in');
248
+ const bust = `_=${Date.now()}`;
249
+ const res = await fetch(`${creds.apiBase}/api/cli/people?id=${encodeURIComponent(id)}&${bust}`, {
250
+ headers: {
251
+ Authorization: header,
252
+ Accept: 'application/json',
253
+ 'User-Agent': CLI_USER_AGENT,
254
+ 'Cache-Control': 'no-store',
255
+ },
256
+ cache: 'no-store',
257
+ });
258
+ if (!res.ok) {
259
+ const text = await res.text().catch(() => '');
260
+ throw new Error(`Failed to load contact (${res.status}): ${text.slice(0, 200)}`);
261
+ }
262
+ const json = (await res.json());
263
+ return json.person;
264
+ }
265
+ export async function patchPerson(creds, id, updates, opts = {}) {
266
+ const header = authHeader(creds);
267
+ if (!header)
268
+ throw new Error('Not logged in');
269
+ const res = await fetch(`${creds.apiBase}/api/cli/people`, {
270
+ method: 'PATCH',
271
+ headers: {
272
+ Authorization: header,
273
+ Accept: 'application/json',
274
+ 'Content-Type': 'application/json',
275
+ 'User-Agent': CLI_USER_AGENT,
276
+ },
277
+ body: JSON.stringify({ id, updates, appendNotes: opts.appendNotes }),
278
+ });
279
+ if (!res.ok) {
280
+ const text = await res.text().catch(() => '');
281
+ throw new Error(`Failed to update contact (${res.status}): ${text.slice(0, 240)}`);
282
+ }
283
+ const json = (await res.json());
284
+ return json.person;
285
+ }
286
+ export async function fetchPersonMoney(creds, personId, limit = 50) {
287
+ const header = authHeader(creds);
288
+ if (!header)
289
+ throw new Error('Not logged in');
290
+ const params = new URLSearchParams({
291
+ person_id: personId,
292
+ limit: String(limit),
293
+ _t: String(Date.now()),
294
+ });
295
+ const res = await fetch(`${creds.apiBase}/api/cli/people/transactions?${params}`, {
296
+ headers: {
297
+ Authorization: header,
298
+ Accept: 'application/json',
299
+ 'User-Agent': CLI_USER_AGENT,
300
+ },
301
+ });
302
+ if (!res.ok) {
303
+ const text = await res.text().catch(() => '');
304
+ throw new Error(`Failed to load money (${res.status}): ${text.slice(0, 240)}`);
305
+ }
306
+ return res.json();
307
+ }
308
+ export async function fetchPaidForYou(creds, personId, limit = 100) {
309
+ const header = authHeader(creds);
310
+ if (!header)
311
+ throw new Error('Not logged in');
312
+ const params = new URLSearchParams({
313
+ person_id: personId,
314
+ limit: String(limit),
315
+ _t: String(Date.now()),
316
+ });
317
+ return fetchJsonWithDeadline(`${creds.apiBase}/api/cli/people/paid-for-you?${params}`, {
318
+ headers: { Authorization: header, Accept: 'application/json', 'User-Agent': CLI_USER_AGENT },
319
+ }, {
320
+ timeoutMessage: 'Loading paid-for-you timed out after 15 seconds. Check your connection and retry dayze people paid-for.',
321
+ httpErrorMessage: (status, bodyPreview) => `Failed to load paid-for-you (${status}): ${bodyPreview}`,
322
+ });
323
+ }
324
+ export function printPaidForYou(ledger, personName) {
325
+ const name = personName || ledger.person?.name || 'Contact';
326
+ section(`Paid for you · ${name}`);
327
+ if (!ledger.entries?.length) {
328
+ console.log(ui.c.dim(' (nothing logged as paid for you yet)'));
329
+ return;
330
+ }
331
+ for (const t of ledger.totals || []) {
332
+ kv(t.currency, `${formatMoneyAmount(t.total, t.currency)} · ${t.count} ${t.count === 1 ? 'item' : 'items'}`);
333
+ }
334
+ console.log('');
335
+ for (const e of ledger.entries.slice(0, 40)) {
336
+ const kind = e.source_kind === 'food' ? 'food' : 'exp';
337
+ const label = e.label?.trim() || '—';
338
+ console.log(` ${ui.c.dim(e.date)} ${formatMoneyAmount(e.amount, e.currency)} ${ui.c.dim(kind)} ${label}`);
339
+ }
340
+ if (ledger.entries.length > 40) {
341
+ console.log(ui.c.dim(` … +${ledger.entries.length - 40} more`));
342
+ }
343
+ }
344
+ export async function logPersonMoney(creds, input) {
345
+ const header = authHeader(creds);
346
+ if (!header)
347
+ throw new Error('Not logged in');
348
+ const res = await fetch(`${creds.apiBase}/api/cli/people/transactions`, {
349
+ method: 'POST',
350
+ headers: {
351
+ Authorization: header,
352
+ Accept: 'application/json',
353
+ 'Content-Type': 'application/json',
354
+ 'User-Agent': CLI_USER_AGENT,
355
+ },
356
+ body: JSON.stringify({
357
+ person_id: input.personId,
358
+ direction: input.direction,
359
+ amount: input.amount,
360
+ currency: input.currency,
361
+ date: input.date,
362
+ note: input.note,
363
+ }),
364
+ });
365
+ if (!res.ok) {
366
+ const text = await res.text().catch(() => '');
367
+ throw new Error(`Failed to log money (${res.status}): ${text.slice(0, 240)}`);
368
+ }
369
+ const json = (await res.json());
370
+ return json.entry;
371
+ }
372
+ function formatMoneyAmount(amount, currency) {
373
+ try {
374
+ return new Intl.NumberFormat(undefined, {
375
+ style: 'currency',
376
+ currency: currency || 'USD',
377
+ maximumFractionDigits: 2,
378
+ }).format(amount);
379
+ }
380
+ catch {
381
+ return `${currency} ${amount.toLocaleString(undefined, {
382
+ minimumFractionDigits: 2,
383
+ maximumFractionDigits: 2,
384
+ })}`;
385
+ }
386
+ }
387
+ export function printPersonMoney(ledger, personName) {
388
+ const name = personName || ledger.person?.name || 'Contact';
389
+ section(`Money · you ↔ ${name}`);
390
+ if (!ledger.entries?.length) {
391
+ console.log(ui.c.dim(' (none yet — press t to log)'));
392
+ return;
393
+ }
394
+ for (const t of ledger.totals || []) {
395
+ kv(t.currency, `sent ${formatMoneyAmount(t.sent, t.currency)} · recv ${formatMoneyAmount(t.received, t.currency)} · net ${formatMoneyAmount(t.net, t.currency)}`);
396
+ }
397
+ console.log('');
398
+ for (const e of ledger.entries.slice(0, 20)) {
399
+ const arrow = e.direction === 'to' ? ui.c.dim('you →') : ui.c.brand('← you');
400
+ const label = e.direction === 'to' ? 'sent' : 'recv';
401
+ const note = e.description?.trim() || e.merchant || e.category || '';
402
+ console.log(` ${ui.c.dim(e.date)} ${arrow} ${formatMoneyAmount(e.amount, e.currency)} ${ui.c.dim(label)}${note ? ` ${note}` : ''}`);
403
+ }
404
+ if (ledger.entries.length > 20) {
405
+ console.log(ui.c.dim(` … +${ledger.entries.length - 20} more`));
406
+ }
407
+ }
408
+ async function postPeopleAction(creds, body) {
409
+ const header = authHeader(creds);
410
+ if (!header)
411
+ throw new Error('Not logged in');
412
+ const res = await fetch(`${creds.apiBase}/api/cli/people`, {
413
+ method: 'POST',
414
+ headers: {
415
+ Authorization: header,
416
+ Accept: 'application/json',
417
+ 'Content-Type': 'application/json',
418
+ 'User-Agent': CLI_USER_AGENT,
419
+ },
420
+ body: JSON.stringify(body),
421
+ });
422
+ if (!res.ok) {
423
+ const text = await res.text().catch(() => '');
424
+ throw new Error(`Failed (${res.status}): ${text.slice(0, 240)}`);
425
+ }
426
+ return (await res.json());
427
+ }
428
+ function toPersonAgentContext(p) {
429
+ return {
430
+ id: p.id,
431
+ name: p.name,
432
+ relationship: p.relationship,
433
+ tier: p.tier,
434
+ birthday: formatBirthdayDisplay(p.birthday, p.birthday_precision) || p.birthday,
435
+ occupation: p.occupation,
436
+ company: p.company,
437
+ address: p.address ?? primaryLocation(p),
438
+ email: p.email,
439
+ phone: p.phone,
440
+ instagram: p.instagram,
441
+ twitter: p.twitter,
442
+ linkedin: p.linkedin,
443
+ website: p.website,
444
+ notes: p.notes,
445
+ interactionCount: p.interaction_count,
446
+ firstMet: p.first_met,
447
+ firstMetLocation: p.first_met_location,
448
+ birthdayPrecision: p.birthday_precision,
449
+ };
450
+ }
451
+ function fieldValue(p, key) {
452
+ const v = p[key];
453
+ if (v == null)
454
+ return '';
455
+ return String(v);
456
+ }
457
+ function mergeIntoDirectory(directory, updated) {
458
+ const i = directory.findIndex((x) => x.id === updated.id);
459
+ if (i < 0)
460
+ return;
461
+ directory[i] = {
462
+ ...directory[i],
463
+ name: updated.name,
464
+ relationship: updated.relationship,
465
+ occupation: updated.occupation,
466
+ company: updated.company,
467
+ email: updated.email,
468
+ phone: updated.phone,
469
+ birthday: updated.birthday,
470
+ birthday_precision: updated.birthday_precision,
471
+ notes: updated.notes,
472
+ tier: updated.tier,
473
+ last_interaction_at: updated.last_interaction_at,
474
+ updated_at: updated.updated_at,
475
+ instagram: updated.instagram,
476
+ address: updated.address,
477
+ financial_context: updated.financial_context,
478
+ interaction_count: updated.interaction_count,
479
+ };
480
+ }
481
+ function matchHaystack(p) {
482
+ return [
483
+ p.name,
484
+ p.email,
485
+ p.company,
486
+ p.occupation,
487
+ p.relationship,
488
+ p.phone,
489
+ p.instagram,
490
+ p.notes,
491
+ p.address,
492
+ p.tier,
493
+ ]
494
+ .filter(Boolean)
495
+ .join(' ')
496
+ .toLowerCase();
497
+ }
498
+ /** Token filter (fzf-ish): every whitespace-separated token must match somewhere. */
499
+ export function filterPeople(people, query) {
500
+ const q = query.trim().toLowerCase();
501
+ if (!q)
502
+ return people;
503
+ const tokens = q.split(/\s+/).filter(Boolean);
504
+ return people.filter((p) => {
505
+ const hay = matchHaystack(p);
506
+ return tokens.every((t) => hay.includes(t));
507
+ });
508
+ }
509
+ function pad(s, width) {
510
+ if (width <= 0)
511
+ return '';
512
+ if (s.length >= width) {
513
+ if (width === 1)
514
+ return '…';
515
+ return `${s.slice(0, Math.max(0, width - 1))}…`;
516
+ }
517
+ return s + ' '.repeat(width - s.length);
518
+ }
519
+ function plural(n, one, many = `${one}s`) {
520
+ return `${n} ${n === 1 ? one : many}`;
521
+ }
522
+ function igHandle(ig) {
523
+ if (!ig)
524
+ return '—';
525
+ const h = ig.replace(/^@/, '').trim();
526
+ return h ? `@${h}` : '—';
527
+ }
528
+ function formatNetWorth(p) {
529
+ const nw = p.financial_context?.netWorth;
530
+ if (!nw || nw.amount == null || !Number.isFinite(Number(nw.amount)))
531
+ return null;
532
+ const n = Number(nw.amount);
533
+ const cur = (nw.currency || 'USD').toUpperCase();
534
+ if (Math.abs(n) >= 1_000_000)
535
+ return `${cur} ${(n / 1_000_000).toFixed(1)}M`;
536
+ if (Math.abs(n) >= 1_000)
537
+ return `${cur} ${(n / 1_000).toFixed(0)}K`;
538
+ return `${cur} ${n.toLocaleString()}`;
539
+ }
540
+ /** How complete the dossier is (identifiers agencies care about). */
541
+ function dossierScore(p) {
542
+ const checks = [
543
+ Boolean(p.relationship),
544
+ Boolean(p.email || p.phone),
545
+ Boolean(p.instagram || p.occupation || p.company),
546
+ Boolean(p.birthday),
547
+ Boolean(p.last_interaction_at),
548
+ ];
549
+ const filled = checks.filter(Boolean).length;
550
+ const total = checks.length;
551
+ const bar = '●'.repeat(filled) + '○'.repeat(total - filled);
552
+ return { filled, total, bar };
553
+ }
554
+ function pad2(n) {
555
+ return String(n).padStart(2, '0');
556
+ }
557
+ /** Compact human age for list columns: just now · 5m · 3h · 2d · 1w · 3mo · 2y */
558
+ function formatWhenList(iso) {
559
+ if (!iso)
560
+ return '—';
561
+ const t = new Date(iso).getTime();
562
+ if (!Number.isFinite(t))
563
+ return '—';
564
+ const sec = Math.max(0, Math.floor((Date.now() - t) / 1000));
565
+ if (sec < 45)
566
+ return 'now';
567
+ if (sec < 3600)
568
+ return `${Math.max(1, Math.floor(sec / 60))}m`;
569
+ if (sec < 86400)
570
+ return `${Math.floor(sec / 3600)}h`;
571
+ const days = Math.floor(sec / 86400);
572
+ if (days === 1)
573
+ return '1d';
574
+ if (days < 14)
575
+ return `${days}d`;
576
+ if (days < 60)
577
+ return `${Math.floor(days / 7)}w`;
578
+ if (days < 730)
579
+ return `${Math.floor(days / 30)}mo`;
580
+ return `${Math.floor(days / 365)}y`;
581
+ }
582
+ /** Relative age with hours / minutes / seconds (detail view). */
583
+ function formatAgePrecise(iso) {
584
+ if (!iso)
585
+ return '—';
586
+ const t = new Date(iso).getTime();
587
+ if (!Number.isFinite(t))
588
+ return '—';
589
+ let sec = Math.max(0, Math.floor((Date.now() - t) / 1000));
590
+ if (sec < 60)
591
+ return `${sec}s`;
592
+ const mTotal = Math.floor(sec / 60);
593
+ const s = sec % 60;
594
+ if (mTotal < 60)
595
+ return `${mTotal}m ${pad2(s)}s`;
596
+ const hTotal = Math.floor(mTotal / 60);
597
+ const m = mTotal % 60;
598
+ if (hTotal < 48)
599
+ return `${hTotal}h ${pad2(m)}m ${pad2(s)}s`;
600
+ const days = Math.floor(hTotal / 24);
601
+ const h = hTotal % 24;
602
+ if (days < 14)
603
+ return `${days}d ${h}h ${pad2(m)}m`;
604
+ if (days < 60)
605
+ return `${Math.floor(days / 7)}w ${days % 7}d`;
606
+ if (days < 730)
607
+ return `${Math.floor(days / 30)}mo`;
608
+ return `${Math.floor(days / 365)}y`;
609
+ }
610
+ /** Detail line: absolute + precise age. */
611
+ function formatWhenDetail(iso) {
612
+ if (!iso)
613
+ return '—';
614
+ const d = new Date(iso);
615
+ if (!Number.isFinite(d.getTime()))
616
+ return String(iso);
617
+ const abs = `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}:${pad2(d.getSeconds())}`;
618
+ return `${abs} (${formatAgePrecise(iso)} ago)`;
619
+ }
620
+ /** Phone terminals (~35–55 cols) need a name-first single line. */
621
+ function listDensity() {
622
+ const w = process.stdout.columns || 100;
623
+ if (w < 56)
624
+ return 'phone';
625
+ if (w < 100)
626
+ return 'tablet';
627
+ return 'desktop';
628
+ }
629
+ function termWidth() {
630
+ return Math.max(28, process.stdout.columns || 80);
631
+ }
632
+ /** Right-hand meta for phone rows — follows active sort. */
633
+ function phoneMeta(p, sort) {
634
+ const prec = p.birthday_precision;
635
+ if (sort === 'day-desc' || sort === 'day-asc') {
636
+ const dayN = dayNumberFromBirthday(p.birthday ?? null);
637
+ return dayN != null ? formatDayNumberForPrecision(p.birthday, prec) : '—';
638
+ }
639
+ if (sort === 'birthday') {
640
+ const toBday = daysToNextBirthday(p.birthday ?? null, new Date(), prec);
641
+ if (toBday === 0)
642
+ return 'today';
643
+ return formatDaysToBday(toBday);
644
+ }
645
+ if (sort === 'last')
646
+ return formatWhenList(p.last_interaction_at);
647
+ // name sort — show last contact as the useful glance signal
648
+ return formatWhenList(p.last_interaction_at);
649
+ }
650
+ function phoneMetaHeader(sort) {
651
+ if (sort === 'day-desc' || sort === 'day-asc')
652
+ return 'DAY';
653
+ if (sort === 'birthday')
654
+ return '→BD';
655
+ if (sort === 'last')
656
+ return 'LAST';
657
+ return 'LAST';
658
+ }
659
+ function cols() {
660
+ const density = listDensity();
661
+ const width = termWidth();
662
+ const idxW = density === 'phone' ? 3 : 4;
663
+ if (density === 'phone') {
664
+ const metaW = 6;
665
+ const nameW = Math.max(10, width - 2 - idxW - 1 - metaW - 1);
666
+ return { idxW, nameW, relW: 0, dayW: 0, bdayW: 0, igW: 0, whenW: metaW, scoreW: 0 };
667
+ }
668
+ if (density === 'tablet') {
669
+ // # NAME REL DAY LAST
670
+ const dayW = 7;
671
+ const whenW = 5;
672
+ const relW = 7;
673
+ const fixed = idxW + dayW + whenW + relW + 10;
674
+ const nameW = Math.max(12, Math.min(22, width - fixed));
675
+ return { idxW, nameW, relW, dayW, bdayW: 0, igW: 0, whenW, scoreW: 0 };
676
+ }
677
+ const dayW = 8;
678
+ const bdayW = 9;
679
+ const scoreW = 7;
680
+ const whenW = 10;
681
+ const fixed = idxW + dayW + bdayW + scoreW + whenW * 2 + 18;
682
+ const flex = Math.max(36, width - fixed);
683
+ const igW = Math.min(10, Math.max(7, Math.floor(flex * 0.18)));
684
+ const nameW = Math.min(22, Math.max(12, Math.floor(flex * 0.48)));
685
+ const relW = Math.min(10, Math.max(6, Math.floor(flex * 0.2)));
686
+ return { idxW, nameW, relW, dayW, bdayW, igW, whenW, scoreW };
687
+ }
688
+ function formatRow(p, index1, selected, sort = 'name') {
689
+ const dens = listDensity();
690
+ const { idxW, nameW, relW, dayW, bdayW, igW, whenW, scoreW } = cols();
691
+ const prec = p.birthday_precision;
692
+ const dayN = dayNumberFromBirthday(p.birthday ?? null);
693
+ const toBday = daysToNextBirthday(p.birthday ?? null, new Date(), prec);
694
+ const idx = pad(String(index1), idxW);
695
+ if (dens === 'phone') {
696
+ const name = pad(p.name || '', nameW);
697
+ const meta = pad(phoneMeta(p, sort), whenW);
698
+ const mid = `${idx} ${name} ${meta}`;
699
+ if (selected)
700
+ return `${ui.c.brandBold('❯')} ${ui.c.bold(mid)}`;
701
+ return ` ${mid}`;
702
+ }
703
+ if (dens === 'tablet') {
704
+ const name = pad(p.name || '', nameW);
705
+ const rel = pad(p.relationship || '—', relW);
706
+ const day = pad(dayN != null ? formatDayNumberForPrecision(p.birthday, prec) : '—', dayW);
707
+ const touched = pad(formatWhenList(p.last_interaction_at), whenW);
708
+ const mid = `${idx} ${name} ${rel} ${day} ${touched}`;
709
+ if (selected)
710
+ return `${ui.c.brandBold('❯')} ${ui.c.bold(mid)}`;
711
+ return ` ${mid}`;
712
+ }
713
+ const name = pad(p.name || '', nameW);
714
+ const rel = pad(p.relationship || '—', relW);
715
+ const day = pad(dayN != null ? formatDayNumberForPrecision(p.birthday, prec) : '—', dayW);
716
+ let bdayRaw = formatDaysToBday(toBday);
717
+ if (toBday === 0)
718
+ bdayRaw = 'today';
719
+ const bdayCell = pad(bdayRaw, bdayW);
720
+ const ig = pad(igHandle(p.instagram), igW);
721
+ const touched = pad(formatWhenList(p.last_interaction_at), whenW);
722
+ const updated = pad(formatWhenList(p.updated_at), whenW);
723
+ const score = pad(dossierScore(p).bar, scoreW);
724
+ const mid = `${idx} ${name} ${rel} ${day} ${toBday === 0 ? ui.c.brandBold(bdayCell) : bdayCell} ${ig} ${touched} ${updated} ${score}`;
725
+ if (selected)
726
+ return `${ui.c.brandBold('❯')} ${ui.c.bold(mid)}`;
727
+ return ` ${mid}`;
728
+ }
729
+ function sortColumnActive(sort, col) {
730
+ switch (col) {
731
+ case 'name':
732
+ return sort === 'name';
733
+ case 'day':
734
+ return sort === 'day-desc' || sort === 'day-asc';
735
+ case 'bday':
736
+ return sort === 'birthday';
737
+ case 'contact':
738
+ return sort === 'last';
739
+ }
740
+ }
741
+ function hdrCell(label, width, active) {
742
+ const text = pad(label, width);
743
+ return active ? ui.c.brandBold(text) : ui.c.dim(text);
744
+ }
745
+ function headerRow(sort = 'name') {
746
+ const density = listDensity();
747
+ const { idxW, nameW, relW, dayW, bdayW, igW, whenW, scoreW } = cols();
748
+ if (density === 'phone') {
749
+ return (` ${ui.c.dim(pad('#', idxW))} ${hdrCell('NAME', nameW, sortColumnActive(sort, 'name'))} ` +
750
+ `${hdrCell(phoneMetaHeader(sort), whenW, true)}`);
751
+ }
752
+ if (density === 'tablet') {
753
+ const dayLabel = sort === 'day-asc' ? 'DAY↑' : sort === 'day-desc' ? 'DAY↓' : 'DAY';
754
+ return (` ${ui.c.dim(pad('#', idxW))} ${hdrCell('NAME', nameW, sortColumnActive(sort, 'name'))} ` +
755
+ `${ui.c.dim(pad('REL', relW))} ${hdrCell(dayLabel, dayW, sortColumnActive(sort, 'day'))} ` +
756
+ `${hdrCell('LAST', whenW, sortColumnActive(sort, 'contact'))}`);
757
+ }
758
+ const dayLabel = sort === 'day-asc' ? 'DAY ↑' : sort === 'day-desc' ? 'DAY ↓' : 'DAY';
759
+ return (` ${ui.c.dim(pad('#', idxW))} ${hdrCell('NAME', nameW, sortColumnActive(sort, 'name'))} ` +
760
+ `${ui.c.dim(pad('REL', relW))} ${hdrCell(dayLabel, dayW, sortColumnActive(sort, 'day'))} ` +
761
+ `${hdrCell('BIRTHDAY', bdayW, sortColumnActive(sort, 'bday'))} ${ui.c.dim(pad('IG', igW))} ` +
762
+ `${hdrCell('INTERACTED', whenW, sortColumnActive(sort, 'contact'))} ` +
763
+ `${ui.c.dim(pad('UPDATED', whenW))} ${ui.c.dim(pad('DOSSIER', scoreW))}`);
764
+ }
765
+ function tableWidth() {
766
+ const density = listDensity();
767
+ if (density === 'phone')
768
+ return termWidth();
769
+ const c = cols();
770
+ if (density === 'tablet') {
771
+ return c.idxW + c.nameW + c.relW + c.dayW + c.whenW + 12;
772
+ }
773
+ return c.idxW + c.nameW + c.relW + c.dayW + c.bdayW + c.igW + c.whenW * 2 + c.scoreW + 24;
774
+ }
775
+ function firstLetter(name) {
776
+ const ch = (name || '?').trim().charAt(0).toUpperCase();
777
+ return /[A-Z]/.test(ch) ? ch : '#';
778
+ }
779
+ /** Letters that have at least one contact (A–Z). */
780
+ function lettersPresent(people) {
781
+ const set = new Set();
782
+ for (const p of people) {
783
+ const L = firstLetter(p.name);
784
+ if (L !== '#')
785
+ set.add(L);
786
+ }
787
+ return [...set].sort();
788
+ }
789
+ function currentJumpLetter(filter, selectedName) {
790
+ const f = filter.trim().toUpperCase();
791
+ if (f.length === 1 && /[A-Z]/.test(f))
792
+ return f;
793
+ if (selectedName) {
794
+ const L = firstLetter(selectedName);
795
+ return L === '#' ? null : L;
796
+ }
797
+ return null;
798
+ }
799
+ /** Compact A–Z index — denser on phone so it stays one line. */
800
+ function alphabetBar(letters, active) {
801
+ if (!letters.length)
802
+ return '';
803
+ const sep = listDensity() === 'phone' ? '' : ' ';
804
+ return letters
805
+ .map((L) => (L === active ? ui.c.brandBold(`[${L}]`) : ui.c.dim(L)))
806
+ .join(sep);
807
+ }
808
+ export function printPeopleTable(people, title, sort = 'name') {
809
+ const withIg = people.filter((p) => p.instagram).length;
810
+ const withBday = people.filter((p) => p.birthday).length;
811
+ const bdaySoon = people.filter((p) => {
812
+ const d = daysToNextBirthday(p.birthday ?? null, new Date(), p.birthday_precision);
813
+ return d != null && d <= 14;
814
+ }).length;
815
+ console.log(`${ui.c.brandBold(title || 'People')} ${ui.c.dim(`${plural(people.length, 'record')} · sort ${peopleSortLabel(sort)} · ${withBday} bday · ${bdaySoon} ≤14d · ${withIg} IG`)}`);
816
+ console.log(headerRow(sort));
817
+ console.log(ui.c.dim('─'.repeat(Math.min(process.stdout.columns || 96, tableWidth()))));
818
+ let lastLetter = '';
819
+ people.forEach((p, i) => {
820
+ if (sort === 'name') {
821
+ const L = firstLetter(p.name);
822
+ if (L !== lastLetter) {
823
+ lastLetter = L;
824
+ console.log(ui.c.brand(` ${L}`));
825
+ }
826
+ }
827
+ console.log(formatRow(p, i + 1, false, sort));
828
+ });
829
+ console.log('');
830
+ console.log(ui.c.dim(' INTERACTED = last contact · UPDATED = last profile edit · active sort column highlighted'));
831
+ console.log('');
832
+ }
833
+ export function printPersonDetail(p, footerHint = true, money) {
834
+ const score = dossierScore(p);
835
+ const nw = formatNetWorth(p);
836
+ const dayN = dayNumberFromBirthday(p.birthday ?? null);
837
+ const toBday = daysToNextBirthday(p.birthday ?? null, new Date(), p.birthday_precision);
838
+ const location = primaryLocation(p);
839
+ const lifestyle = lifestyleLines(p.conversation_context);
840
+ const hobbies = p.conversation_context?.hobbies?.filter(Boolean) ?? [];
841
+ const interests = p.conversation_context?.interests?.filter(Boolean) ?? [];
842
+ const birthDisplay = formatBirthdayDisplay(p.birthday, p.birthday_precision);
843
+ const prec = resolveBirthdayPrecision(p.birthday_precision);
844
+ console.log('');
845
+ console.log(`${ui.c.brandBold(p.name)} ${ui.c.dim(score.bar + ` ${score.filled}/${score.total}`)}`);
846
+ if (p.tier)
847
+ console.log(ui.c.dim(` tier ${p.tier}`));
848
+ console.log(ui.c.dim('─'.repeat(52)));
849
+ section('Dayze');
850
+ if (dayN != null) {
851
+ kv('Day number', ui.c.brandBold(formatDayNumber(dayN, prec !== 'day')));
852
+ }
853
+ else {
854
+ kv('Day number', '—');
855
+ }
856
+ const alive = formatTimeAlive(timeAliveFromBirth(p.birthday, p.birth_time, { precision: p.birthday_precision }));
857
+ if (alive)
858
+ kv('Alive', ui.c.brandBold(alive));
859
+ if (toBday != null) {
860
+ const label = toBday === 0
861
+ ? ui.c.brandBold('today 🎂')
862
+ : `${toBday} day${toBday === 1 ? '' : 's'}`;
863
+ kv('→ Birthday', label);
864
+ }
865
+ else {
866
+ kv('→ Birthday', prec !== 'day' && p.birthday ? 'unknown (month/day)' : '—');
867
+ }
868
+ if (birthDisplay) {
869
+ kv('Birthday', prec === 'year' ? `${birthDisplay} (year only)` : prec === 'month' ? `${birthDisplay} (month)` : birthDisplay);
870
+ }
871
+ if (p.birth_time && prec === 'day') {
872
+ kv('Birth time', String(p.birth_time).slice(0, 8));
873
+ }
874
+ section('Identifiers');
875
+ const ids = [
876
+ ['Instagram', p.instagram ? igHandle(p.instagram) : null],
877
+ ['Email', p.email],
878
+ ['Phone', p.phone],
879
+ ['LinkedIn', p.linkedin],
880
+ ['Twitter/X', p.twitter],
881
+ ['Website', p.website],
882
+ ['Channel', p.preferred_channel],
883
+ ['Record id', p.id],
884
+ ];
885
+ let anyId = false;
886
+ for (const [label, val] of ids) {
887
+ if (val) {
888
+ anyId = true;
889
+ kv(label, val);
890
+ }
891
+ }
892
+ if (!anyId)
893
+ console.log(ui.c.dim(' (none)'));
894
+ section('Profile');
895
+ const profile = [
896
+ ['Relationship', p.relationship],
897
+ ['Occupation', p.occupation],
898
+ ['Company', p.company],
899
+ ['Pronouns', p.pronouns],
900
+ ['Gender', p.gender],
901
+ ['Net worth', nw],
902
+ ];
903
+ let anyProfile = false;
904
+ for (const [label, val] of profile) {
905
+ if (val) {
906
+ anyProfile = true;
907
+ kv(label, val);
908
+ }
909
+ }
910
+ if (!anyProfile)
911
+ console.log(ui.c.dim(' (none)'));
912
+ if (location) {
913
+ section('Location');
914
+ kv('Current', location);
915
+ // If structured primary ≠ freeform address, show address as secondary
916
+ if (p.address?.trim() && location !== p.address.trim() && !location.startsWith(p.address.trim())) {
917
+ kv('Address', p.address.trim());
918
+ }
919
+ }
920
+ if (p.first_met || p.first_met_location || p.discovery_source) {
921
+ section('How you met');
922
+ if (p.first_met)
923
+ kv('First met', formatDateLabel(p.first_met) || p.first_met);
924
+ if (p.first_met_location)
925
+ kv('Met at', p.first_met_location);
926
+ if (p.discovery_source)
927
+ kv('Via', p.discovery_source);
928
+ }
929
+ if (lifestyle.length || hobbies.length || interests.length || p.conversation_context?.religion) {
930
+ section('Context');
931
+ for (const [label, val] of lifestyle)
932
+ kv(label, val);
933
+ if (hobbies.length)
934
+ kv('Hobbies', hobbies.join(', '));
935
+ if (interests.length)
936
+ kv('Interests', interests.join(', '));
937
+ if (p.conversation_context?.religion)
938
+ kv('Religion', p.conversation_context.religion);
939
+ }
940
+ if (money) {
941
+ printPersonMoney(money, p.name);
942
+ }
943
+ section('Activity');
944
+ kv('Last interacted', formatWhenDetail(p.last_interaction_at));
945
+ kv('Last updated', formatWhenDetail(p.updated_at));
946
+ if (p.interaction_count != null)
947
+ kv('Interactions', String(p.interaction_count));
948
+ if (p.notes?.trim()) {
949
+ section('Notes');
950
+ for (const line of p.notes.trim().split('\n')) {
951
+ console.log(` ${line}`);
952
+ }
953
+ }
954
+ console.log('');
955
+ if (footerHint) {
956
+ console.log(ui.c.dim(' a agent · e edit · n note · t money · Enter / Esc back'));
957
+ }
958
+ console.log('');
959
+ }
960
+ export async function resolvePersonByQuery(creds, query) {
961
+ const all = await fetchAllPeople(creds);
962
+ const hits = filterPeople(all, query);
963
+ if (hits.length === 0)
964
+ return null;
965
+ // Prefer exact name match
966
+ const exact = hits.find((p) => p.name.toLowerCase() === query.trim().toLowerCase());
967
+ return fetchPersonDetail(creds, (exact || hits[0]).id);
968
+ }
969
+ /**
970
+ * Interactive address book — fzf filter + Ctrl+S sort cycle.
971
+ */
972
+ export async function runPeopleBrowser(creds, initialQuery, initialSort = 'name') {
973
+ const spinner = new ui.Spinner('Loading contacts');
974
+ spinner.start();
975
+ let directory;
976
+ try {
977
+ directory = await fetchAllPeople(creds);
978
+ }
979
+ finally {
980
+ spinner.stop();
981
+ }
982
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
983
+ const sorted = sortPeople(filterPeople(directory, initialQuery || ''), initialSort);
984
+ printPeopleTable(sorted, 'People', initialSort);
985
+ return;
986
+ }
987
+ const { emitKeypressEvents } = await import('node:readline');
988
+ emitKeypressEvents(process.stdin);
989
+ process.stdin.setRawMode(true);
990
+ process.stdin.resume();
991
+ process.stdin.setEncoding('utf8');
992
+ let filter = initialQuery || '';
993
+ let sort = initialSort;
994
+ let cursor = 0; // index in filtered list
995
+ let scroll = 0; // first visible index
996
+ let mode = 'list';
997
+ let detail = null;
998
+ let detailMoney = null;
999
+ let dirty = true;
1000
+ let busy = false;
1001
+ let aliveTimer = null;
1002
+ const loadDetailMoney = async (personId) => {
1003
+ try {
1004
+ detailMoney = await fetchPersonMoney(creds, personId);
1005
+ }
1006
+ catch {
1007
+ detailMoney = {
1008
+ person: { id: personId, name: detail?.name || '' },
1009
+ entries: [],
1010
+ totals: [],
1011
+ };
1012
+ }
1013
+ };
1014
+ const visibleRows = () => {
1015
+ const chrome = listDensity() === 'phone' ? 6 : 7;
1016
+ return Math.max(6, Math.min(28, (process.stdout.rows || 24) - chrome));
1017
+ };
1018
+ const filtered = () => sortPeople(filterPeople(directory, filter), sort);
1019
+ const ensureVisible = () => {
1020
+ const rows = visibleRows();
1021
+ const list = filtered();
1022
+ if (cursor < 0)
1023
+ cursor = 0;
1024
+ if (cursor >= list.length)
1025
+ cursor = Math.max(0, list.length - 1);
1026
+ if (cursor < scroll)
1027
+ scroll = cursor;
1028
+ if (cursor >= scroll + rows)
1029
+ scroll = cursor - rows + 1;
1030
+ if (scroll < 0)
1031
+ scroll = 0;
1032
+ };
1033
+ const stopAliveTick = () => {
1034
+ if (aliveTimer) {
1035
+ clearInterval(aliveTimer);
1036
+ aliveTimer = null;
1037
+ }
1038
+ };
1039
+ const syncAliveTick = () => {
1040
+ stopAliveTick();
1041
+ if (mode !== 'detail' || !detail || busy)
1042
+ return;
1043
+ const can = formatTimeAlive(timeAliveFromBirth(detail.birthday, detail.birth_time, {
1044
+ precision: detail.birthday_precision,
1045
+ })) != null;
1046
+ if (!can)
1047
+ return;
1048
+ aliveTimer = setInterval(() => {
1049
+ if (busy || mode !== 'detail' || !detail)
1050
+ return;
1051
+ dirty = true;
1052
+ render();
1053
+ }, 1000);
1054
+ };
1055
+ const cleanup = () => {
1056
+ stopAliveTick();
1057
+ try {
1058
+ process.stdin.setRawMode(false);
1059
+ }
1060
+ catch {
1061
+ /* ignore */
1062
+ }
1063
+ process.stdin.pause();
1064
+ process.stdin.removeAllListeners('keypress');
1065
+ process.stdout.write('\x1b[?25h'); // show cursor
1066
+ };
1067
+ const clearScreen = () => {
1068
+ process.stdout.write('\x1b[?25l\x1b[2J\x1b[H');
1069
+ };
1070
+ const enterRaw = () => {
1071
+ try {
1072
+ process.stdin.setRawMode(true);
1073
+ }
1074
+ catch {
1075
+ /* ignore */
1076
+ }
1077
+ process.stdin.resume();
1078
+ process.stdout.write('\x1b[?25l');
1079
+ };
1080
+ const leaveRaw = () => {
1081
+ try {
1082
+ process.stdin.setRawMode(false);
1083
+ }
1084
+ catch {
1085
+ /* ignore */
1086
+ }
1087
+ process.stdout.write('\x1b[?25h');
1088
+ };
1089
+ // Set once key handler is created — pause during readline prompts.
1090
+ let keyHandler = null;
1091
+ const pauseKeys = () => {
1092
+ stopAliveTick();
1093
+ if (keyHandler)
1094
+ process.stdin.removeListener('keypress', keyHandler);
1095
+ leaveRaw();
1096
+ };
1097
+ const resumeKeys = () => {
1098
+ enterRaw();
1099
+ if (keyHandler)
1100
+ process.stdin.on('keypress', keyHandler);
1101
+ syncAliveTick();
1102
+ };
1103
+ const runDetailEdit = async () => {
1104
+ if (!detail)
1105
+ return;
1106
+ pauseKeys();
1107
+ console.log('');
1108
+ console.log(ui.c.bold(`Edit ${detail.name}`));
1109
+ EDITABLE_FIELDS.forEach((f, i) => {
1110
+ const cur = fieldValue(detail, f.key);
1111
+ const preview = cur ? (cur.length > 48 ? `${cur.slice(0, 47)}…` : cur) : '—';
1112
+ console.log(` ${ui.c.dim(String(i + 1).padStart(2))} ${f.label.padEnd(14)} ${ui.c.dim(preview)}`);
1113
+ });
1114
+ console.log('');
1115
+ const pick = await promptLine('Field number (or name, blank cancel): ');
1116
+ if (!pick) {
1117
+ resumeKeys();
1118
+ dirty = true;
1119
+ render();
1120
+ return;
1121
+ }
1122
+ const byNum = /^\d+$/.test(pick) ? EDITABLE_FIELDS[parseInt(pick, 10) - 1] : undefined;
1123
+ const byName = EDITABLE_FIELDS.find((f) => f.key === pick.toLowerCase() || f.label.toLowerCase() === pick.toLowerCase());
1124
+ const field = byNum || byName;
1125
+ if (!field) {
1126
+ ui.err(`Unknown field “${pick}”`);
1127
+ resumeKeys();
1128
+ dirty = true;
1129
+ render();
1130
+ return;
1131
+ }
1132
+ const current = fieldValue(detail, field.key);
1133
+ console.log(ui.c.dim(`Current ${field.label}: ${current || '(empty)'}`));
1134
+ const hint = field.key === 'birthday'
1135
+ ? 'YYYY, YYYY-MM, or YYYY-MM-DD (year only OK)'
1136
+ : field.key === 'birth_time'
1137
+ ? 'HH:mm or HH:mm:ss'
1138
+ : 'empty clears, . keeps';
1139
+ const next = await promptLine(`New ${field.label} (${hint}): `);
1140
+ if (next === '.') {
1141
+ resumeKeys();
1142
+ dirty = true;
1143
+ render();
1144
+ return;
1145
+ }
1146
+ try {
1147
+ let updates = {
1148
+ [field.key]: next === '' ? null : next,
1149
+ };
1150
+ if (field.key === 'birthday' && next !== '') {
1151
+ const normalized = normalizeBirthdayInput(next);
1152
+ if (!normalized) {
1153
+ ui.err('Invalid birthday — use YYYY, YYYY-MM, or YYYY-MM-DD');
1154
+ resumeKeys();
1155
+ dirty = true;
1156
+ render();
1157
+ return;
1158
+ }
1159
+ updates = { birthday: next }; // API normalizes + sets precision
1160
+ }
1161
+ if (field.key === 'birth_time' && next !== '') {
1162
+ const normalized = normalizeBirthTimeInput(next);
1163
+ if (normalized === undefined) {
1164
+ ui.err('Invalid birth time — use HH:mm or HH:mm:ss');
1165
+ resumeKeys();
1166
+ dirty = true;
1167
+ render();
1168
+ return;
1169
+ }
1170
+ updates = { birth_time: normalized };
1171
+ }
1172
+ detail = await patchPerson(creds, detail.id, updates);
1173
+ mergeIntoDirectory(directory, detail);
1174
+ ui.ok(`Updated ${field.label}`);
1175
+ }
1176
+ catch (err) {
1177
+ ui.err(err instanceof Error ? err.message : String(err));
1178
+ }
1179
+ resumeKeys();
1180
+ dirty = true;
1181
+ render();
1182
+ };
1183
+ const runDetailNote = async () => {
1184
+ if (!detail)
1185
+ return;
1186
+ pauseKeys();
1187
+ console.log('');
1188
+ const note = await promptLine(`Append note for ${detail.name}: `);
1189
+ if (!note) {
1190
+ resumeKeys();
1191
+ dirty = true;
1192
+ render();
1193
+ return;
1194
+ }
1195
+ try {
1196
+ detail = await patchPerson(creds, detail.id, { notes: note }, { appendNotes: true });
1197
+ mergeIntoDirectory(directory, detail);
1198
+ ui.ok('Note saved');
1199
+ }
1200
+ catch (err) {
1201
+ ui.err(err instanceof Error ? err.message : String(err));
1202
+ }
1203
+ resumeKeys();
1204
+ dirty = true;
1205
+ render();
1206
+ };
1207
+ const runDetailMoney = async () => {
1208
+ if (!detail)
1209
+ return;
1210
+ pauseKeys();
1211
+ console.log('');
1212
+ console.log(ui.c.bold(`Money · you ↔ ${detail.name}`));
1213
+ console.log(ui.c.dim(' to = you sent them · from = they sent you'));
1214
+ const dirRaw = (await promptLine('Direction [to/from]: ')).toLowerCase();
1215
+ const direction = dirRaw === 'to' || dirRaw === 'sent' || dirRaw === 'pay' || dirRaw === 'out'
1216
+ ? 'to'
1217
+ : dirRaw === 'from' || dirRaw === 'recv' || dirRaw === 'received' || dirRaw === 'in'
1218
+ ? 'from'
1219
+ : null;
1220
+ if (!direction) {
1221
+ ui.err('Use to or from');
1222
+ resumeKeys();
1223
+ dirty = true;
1224
+ render();
1225
+ return;
1226
+ }
1227
+ const amountRaw = await promptLine('Amount: ');
1228
+ const amount = Number(amountRaw.replace(/[$,]/g, ''));
1229
+ if (!(amount > 0)) {
1230
+ ui.err('Enter a positive amount');
1231
+ resumeKeys();
1232
+ dirty = true;
1233
+ render();
1234
+ return;
1235
+ }
1236
+ const currency = ((await promptLine('Currency [USD]: ')) || 'USD').toUpperCase();
1237
+ const note = await promptLine('Note (optional): ');
1238
+ try {
1239
+ const entry = await logPersonMoney(creds, {
1240
+ personId: detail.id,
1241
+ direction,
1242
+ amount,
1243
+ currency,
1244
+ note: note || undefined,
1245
+ });
1246
+ await loadDetailMoney(detail.id);
1247
+ ui.ok(`Logged ${direction === 'to' ? 'you →' : '← you'} ${formatMoneyAmount(entry.amount, entry.currency)}`);
1248
+ }
1249
+ catch (err) {
1250
+ ui.err(err instanceof Error ? err.message : String(err));
1251
+ }
1252
+ resumeKeys();
1253
+ dirty = true;
1254
+ render();
1255
+ };
1256
+ const runDetailAgent = async () => {
1257
+ if (!detail)
1258
+ return;
1259
+ const personId = detail.id;
1260
+ pauseKeys();
1261
+ console.log('');
1262
+ console.log(ui.c.dim(`Dayze agent for ${detail.name} · e.g. “update occupation to …”, “enrich from LinkedIn”, “add note that …”`));
1263
+ const instruction = await promptLine(ui.promptLabel());
1264
+ if (!instruction) {
1265
+ resumeKeys();
1266
+ dirty = true;
1267
+ render();
1268
+ return;
1269
+ }
1270
+ const agentSpinner = new ui.Spinner('Dayze');
1271
+ agentSpinner.start();
1272
+ let printedHeader = false;
1273
+ let startedReply = false;
1274
+ let replyText = '';
1275
+ let didUpdate = false;
1276
+ try {
1277
+ const personContext = toPersonAgentContext(detail);
1278
+ const result = await askAgent(creds, instruction, [], undefined, {
1279
+ onThinking: (step) => {
1280
+ agentSpinner.stop();
1281
+ ui.thinking(step);
1282
+ },
1283
+ onToolCall: (tool, d) => {
1284
+ agentSpinner.stop();
1285
+ ui.toolCall(tool, d);
1286
+ },
1287
+ onToolResult: (tool, d) => {
1288
+ agentSpinner.stop();
1289
+ ui.toolDone(tool, d);
1290
+ },
1291
+ onFirstText: () => {
1292
+ agentSpinner.stop();
1293
+ if (!printedHeader) {
1294
+ printedHeader = true;
1295
+ process.stdout.write(`${ui.agentLabel()}\n`);
1296
+ }
1297
+ startedReply = true;
1298
+ },
1299
+ onText: (chunk) => {
1300
+ if (!startedReply) {
1301
+ agentSpinner.stop();
1302
+ if (!printedHeader) {
1303
+ printedHeader = true;
1304
+ process.stdout.write(`${ui.agentLabel()}\n`);
1305
+ }
1306
+ startedReply = true;
1307
+ }
1308
+ process.stdout.write(chunk);
1309
+ },
1310
+ }, {
1311
+ personContext,
1312
+ pageContext: {
1313
+ path: `/people/${personId}`,
1314
+ pathname: `/people/${personId}`,
1315
+ surface: 'dayze_cli_contact',
1316
+ client: 'dayze-cli',
1317
+ area: 'people',
1318
+ },
1319
+ });
1320
+ agentSpinner.stop();
1321
+ replyText = result.reply;
1322
+ if (startedReply)
1323
+ process.stdout.write('\n');
1324
+ else
1325
+ console.log(`${ui.agentLabel()}\n${result.reply}\n`);
1326
+ didUpdate = result.toolsUsed.includes('update_person');
1327
+ // Brief settle so DB write is visible, then always re-fetch
1328
+ if (didUpdate)
1329
+ await new Promise((r) => setTimeout(r, 200));
1330
+ detail = await fetchPersonDetail(creds, personId);
1331
+ mergeIntoDirectory(directory, detail);
1332
+ }
1333
+ catch (err) {
1334
+ agentSpinner.stop();
1335
+ ui.err(err instanceof Error ? err.message : String(err));
1336
+ try {
1337
+ detail = await fetchPersonDetail(creds, personId);
1338
+ mergeIntoDirectory(directory, detail);
1339
+ }
1340
+ catch {
1341
+ /* keep prior detail */
1342
+ }
1343
+ }
1344
+ // Replace agent transcript with the refreshed contact card
1345
+ resumeKeys();
1346
+ clearScreen();
1347
+ dirty = false;
1348
+ if (detail) {
1349
+ printPersonDetail(detail, true, detailMoney);
1350
+ syncAliveTick();
1351
+ if (didUpdate) {
1352
+ ui.ok('Contact updated');
1353
+ }
1354
+ else if (replyText) {
1355
+ console.log(ui.c.dim(' (no profile fields changed)'));
1356
+ }
1357
+ console.log('');
1358
+ }
1359
+ else {
1360
+ dirty = true;
1361
+ render();
1362
+ }
1363
+ };
1364
+ const render = () => {
1365
+ if (!dirty)
1366
+ return;
1367
+ dirty = false;
1368
+ clearScreen();
1369
+ if (mode === 'detail' && detail) {
1370
+ printPersonDetail(detail, true, detailMoney);
1371
+ syncAliveTick();
1372
+ return;
1373
+ }
1374
+ stopAliveTick();
1375
+ ensureVisible();
1376
+ const list = filtered();
1377
+ const rows = visibleRows();
1378
+ const end = Math.min(list.length, scroll + rows);
1379
+ const phone = listDensity() === 'phone';
1380
+ if (phone) {
1381
+ console.log(`${ui.c.brandBold('◆ People')} ${ui.c.dim(`${list.length}`)} ${ui.c.brand(peopleSortLabel(sort))}`);
1382
+ console.log(`${ui.c.brand('/')}${filter}${ui.c.dim('▌')}`);
1383
+ }
1384
+ else {
1385
+ console.log(`${ui.c.brandBold('◆ Address book')} ${ui.c.dim(`${list.length === directory.length ? plural(directory.length, 'record') : `${list.length} / ${directory.length}`} · sort `)}${ui.c.brand(peopleSortLabel(sort))}${ui.c.dim(' · Ctrl+S')}`);
1386
+ console.log(`${ui.c.brand('/')} ${filter}${ui.c.dim('▌')} ${ui.c.dim('type to filter · [ ] page')}`);
1387
+ }
1388
+ const letters = lettersPresent(directory);
1389
+ const listForLetter = filtered();
1390
+ const activeLetter = currentJumpLetter(filter, listForLetter[cursor]?.name);
1391
+ const bar = alphabetBar(letters, activeLetter);
1392
+ if (bar)
1393
+ console.log(phone ? bar : ` ${bar}`);
1394
+ console.log(headerRow(sort));
1395
+ console.log(ui.c.dim('─'.repeat(Math.min(termWidth(), tableWidth()))));
1396
+ if (!list.length) {
1397
+ console.log(ui.c.dim(' No matches.'));
1398
+ }
1399
+ else {
1400
+ // Letter headers only when sort is alphabetical (skip on phone — saves space)
1401
+ let lastLetter = '';
1402
+ for (let i = scroll; i < end; i++) {
1403
+ const p = list[i];
1404
+ if (!phone && sort === 'name') {
1405
+ const L = firstLetter(p.name);
1406
+ if (L !== lastLetter) {
1407
+ lastLetter = L;
1408
+ console.log(ui.c.brand(` ${L}`));
1409
+ }
1410
+ }
1411
+ console.log(formatRow(p, i + 1, i === cursor, sort));
1412
+ }
1413
+ }
1414
+ const pos = list.length ? `${cursor + 1}/${list.length}` : '0/0';
1415
+ console.log('');
1416
+ console.log(ui.c.dim(phone
1417
+ ? ` ${pos} · type · ↑↓ · Ctrl+S · Esc`
1418
+ : ` ${pos} · type · [ ] page · ↑↓ ⇧↑↓ PgUp/Dn Home/End Ctrl+S Esc`));
1419
+ };
1420
+ dirty = true;
1421
+ render();
1422
+ await new Promise((resolve) => {
1423
+ const STEP = 10;
1424
+ const moveBy = (delta) => {
1425
+ const listLen = filtered().length;
1426
+ cursor = Math.max(0, Math.min(listLen - 1, cursor + delta));
1427
+ dirty = true;
1428
+ render();
1429
+ };
1430
+ const onKey = async (_ch, key) => {
1431
+ if (!key || busy)
1432
+ return;
1433
+ if (key.ctrl && key.name === 'c') {
1434
+ cleanup();
1435
+ console.log('');
1436
+ resolve();
1437
+ return;
1438
+ }
1439
+ if (mode === 'detail') {
1440
+ if (key.name === 'return' ||
1441
+ key.name === 'escape' ||
1442
+ key.name === 'backspace' ||
1443
+ key.name === 'left') {
1444
+ mode = 'list';
1445
+ detail = null;
1446
+ detailMoney = null;
1447
+ dirty = true;
1448
+ render();
1449
+ return;
1450
+ }
1451
+ const seq = key.sequence;
1452
+ if (!key.ctrl && !key.meta && seq && (seq === 'a' || seq === 'A' || seq === '/')) {
1453
+ busy = true;
1454
+ try {
1455
+ await runDetailAgent();
1456
+ }
1457
+ finally {
1458
+ busy = false;
1459
+ }
1460
+ return;
1461
+ }
1462
+ if (!key.ctrl && !key.meta && seq && (seq === 'e' || seq === 'E')) {
1463
+ busy = true;
1464
+ try {
1465
+ await runDetailEdit();
1466
+ }
1467
+ finally {
1468
+ busy = false;
1469
+ }
1470
+ return;
1471
+ }
1472
+ if (!key.ctrl && !key.meta && seq && (seq === 'n' || seq === 'N')) {
1473
+ busy = true;
1474
+ try {
1475
+ await runDetailNote();
1476
+ }
1477
+ finally {
1478
+ busy = false;
1479
+ }
1480
+ return;
1481
+ }
1482
+ if (!key.ctrl && !key.meta && seq && (seq === 't' || seq === 'T' || seq === 'm' || seq === 'M')) {
1483
+ busy = true;
1484
+ try {
1485
+ await runDetailMoney();
1486
+ }
1487
+ finally {
1488
+ busy = false;
1489
+ }
1490
+ return;
1491
+ }
1492
+ return;
1493
+ }
1494
+ // Esc: clear filter, or quit if already clear (fzf-style)
1495
+ if (key.name === 'escape') {
1496
+ if (filter) {
1497
+ filter = '';
1498
+ cursor = 0;
1499
+ scroll = 0;
1500
+ dirty = true;
1501
+ render();
1502
+ }
1503
+ else {
1504
+ cleanup();
1505
+ console.log('');
1506
+ resolve();
1507
+ }
1508
+ return;
1509
+ }
1510
+ // `[` / `]` — page up / page down (letters still go to the filter)
1511
+ if (!key.ctrl && !key.meta && key.sequence === '[') {
1512
+ moveBy(-visibleRows());
1513
+ return;
1514
+ }
1515
+ if (!key.ctrl && !key.meta && key.sequence === ']') {
1516
+ moveBy(visibleRows());
1517
+ return;
1518
+ }
1519
+ if (key.name === 'return') {
1520
+ const list = filtered();
1521
+ const selected = list[cursor];
1522
+ if (!selected)
1523
+ return;
1524
+ busy = true;
1525
+ try {
1526
+ detail = await fetchPersonDetail(creds, selected.id);
1527
+ await loadDetailMoney(selected.id);
1528
+ mode = 'detail';
1529
+ dirty = true;
1530
+ render();
1531
+ }
1532
+ catch (err) {
1533
+ cleanup();
1534
+ ui.err(err instanceof Error ? err.message : String(err));
1535
+ resolve();
1536
+ }
1537
+ finally {
1538
+ busy = false;
1539
+ }
1540
+ return;
1541
+ }
1542
+ // Navigation — no letter keys (those always go to the filter, fzf-style)
1543
+ if (key.shift && key.name === 'down') {
1544
+ moveBy(STEP);
1545
+ return;
1546
+ }
1547
+ if (key.shift && key.name === 'up') {
1548
+ moveBy(-STEP);
1549
+ return;
1550
+ }
1551
+ if (key.name === 'down' || (key.ctrl && key.name === 'n')) {
1552
+ moveBy(1);
1553
+ return;
1554
+ }
1555
+ if (key.name === 'up' || (key.ctrl && key.name === 'p')) {
1556
+ moveBy(-1);
1557
+ return;
1558
+ }
1559
+ if (key.name === 'home' || (key.ctrl && key.name === 'a')) {
1560
+ cursor = 0;
1561
+ scroll = 0;
1562
+ dirty = true;
1563
+ render();
1564
+ return;
1565
+ }
1566
+ if (key.name === 'end' || (key.ctrl && key.name === 'e')) {
1567
+ cursor = Math.max(0, filtered().length - 1);
1568
+ dirty = true;
1569
+ render();
1570
+ return;
1571
+ }
1572
+ if (key.name === 'pagedown' || (key.ctrl && (key.name === 'd' || key.name === 'f'))) {
1573
+ moveBy(visibleRows());
1574
+ return;
1575
+ }
1576
+ if (key.name === 'pageup' || (key.ctrl && (key.name === 'u' || key.name === 'b'))) {
1577
+ moveBy(-visibleRows());
1578
+ return;
1579
+ }
1580
+ if (key.name === 'backspace') {
1581
+ if (filter.length) {
1582
+ filter = filter.slice(0, -1);
1583
+ cursor = 0;
1584
+ scroll = 0;
1585
+ dirty = true;
1586
+ render();
1587
+ }
1588
+ return;
1589
+ }
1590
+ // Ctrl+L clear filter (keep typing letters free)
1591
+ if (key.ctrl && key.name === 'l') {
1592
+ filter = '';
1593
+ cursor = 0;
1594
+ scroll = 0;
1595
+ dirty = true;
1596
+ render();
1597
+ return;
1598
+ }
1599
+ // Ctrl+S cycle sort (letters stay reserved for filter — fzf + file-manager hybrid)
1600
+ if (key.ctrl && key.name === 's') {
1601
+ const i = PEOPLE_SORT_CYCLE.indexOf(sort);
1602
+ sort = PEOPLE_SORT_CYCLE[(i + 1) % PEOPLE_SORT_CYCLE.length];
1603
+ cursor = 0;
1604
+ scroll = 0;
1605
+ dirty = true;
1606
+ render();
1607
+ return;
1608
+ }
1609
+ // Every printable key (incl. space, j/k/g) → live filter
1610
+ if (!key.ctrl &&
1611
+ !key.meta &&
1612
+ key.sequence &&
1613
+ key.sequence.length === 1 &&
1614
+ key.sequence >= ' ' &&
1615
+ key.sequence !== '\x7f') {
1616
+ filter += key.sequence;
1617
+ cursor = 0;
1618
+ scroll = 0;
1619
+ dirty = true;
1620
+ render();
1621
+ }
1622
+ };
1623
+ process.stdin.on('keypress', onKey);
1624
+ keyHandler = onKey;
1625
+ });
1626
+ }
1627
+ function peelSortAndLetter(rest) {
1628
+ const letterFlag = rest.find((a) => a.startsWith('--letter='));
1629
+ const letter = letterFlag?.split('=')[1] ||
1630
+ (rest.includes('--letter') ? rest[rest.indexOf('--letter') + 1] : undefined);
1631
+ const sortFlag = rest.find((a) => a.startsWith('--sort='));
1632
+ const sortRaw = sortFlag?.split('=')[1] ||
1633
+ (rest.includes('--sort') ? rest[rest.indexOf('--sort') + 1] : undefined);
1634
+ const sort = parsePeopleSort(sortRaw) || 'name';
1635
+ const queryParts = rest.filter((a, i) => {
1636
+ if (a.startsWith('--letter') || a.startsWith('--sort'))
1637
+ return false;
1638
+ if (rest[i - 1] === '--letter' || rest[i - 1] === '--sort')
1639
+ return false;
1640
+ return true;
1641
+ });
1642
+ return { sort, letter, query: queryParts.join(' ').trim() || undefined };
1643
+ }
1644
+ function peelFlag(args, name) {
1645
+ const eq = args.find((a) => a.startsWith(`--${name}=`));
1646
+ if (eq) {
1647
+ return {
1648
+ value: eq.slice(name.length + 3),
1649
+ rest: args.filter((a) => a !== eq),
1650
+ };
1651
+ }
1652
+ const idx = args.indexOf(`--${name}`);
1653
+ if (idx >= 0) {
1654
+ const value = args[idx + 1];
1655
+ return {
1656
+ value,
1657
+ rest: args.filter((_, i) => i !== idx && i !== idx + 1),
1658
+ };
1659
+ }
1660
+ return { rest: args };
1661
+ }
1662
+ export function parsePeopleArgs(positional) {
1663
+ const [head, ...rest] = positional;
1664
+ if (!head)
1665
+ return { kind: 'browse' };
1666
+ if (head === 'help' || head === '--help' || head === '-h')
1667
+ return { kind: 'help' };
1668
+ if (head === 'add')
1669
+ return { kind: 'add', fields: parseAddArgs(rest, PEOPLE_ADD_FIELDS) };
1670
+ if (head === 'list' || head === 'ls') {
1671
+ const { sort, letter, query } = peelSortAndLetter(rest);
1672
+ return { kind: 'list', query, letter, sort };
1673
+ }
1674
+ if (head === 'show' || head === 'get' || head === 'view') {
1675
+ const q = rest.join(' ').trim();
1676
+ return q ? { kind: 'show', query: q } : { kind: 'help' };
1677
+ }
1678
+ if (head === 'paid-for' || head === 'paid-for-you' || head === 'paidforyou') {
1679
+ const query = rest.join(' ').trim();
1680
+ return query ? { kind: 'paid-for', query } : { kind: 'help' };
1681
+ }
1682
+ if (head === 'money' || head === 'pay' || head === 'receive' || head === 'recv') {
1683
+ // dayze people money <name>
1684
+ // dayze people money <name> to|from <amount> [currency] [note…]
1685
+ // dayze people pay <name> <amount> [currency] [note…]
1686
+ // dayze people receive <name> <amount> [currency] [note…]
1687
+ let direction = head === 'pay' ? 'to' : head === 'receive' || head === 'recv' ? 'from' : undefined;
1688
+ let parts = [...rest];
1689
+ if (!direction && parts.length >= 2) {
1690
+ const dirIdx = parts.findIndex((p) => ['to', 'from', 'sent', 'recv', 'received', 'pay', 'in', 'out'].includes(p.toLowerCase()));
1691
+ if (dirIdx >= 0) {
1692
+ const d = parts[dirIdx].toLowerCase();
1693
+ direction =
1694
+ d === 'to' || d === 'sent' || d === 'pay' || d === 'out' ? 'to' : 'from';
1695
+ parts = [...parts.slice(0, dirIdx), ...parts.slice(dirIdx + 1)];
1696
+ }
1697
+ }
1698
+ if (direction && parts.length >= 2) {
1699
+ // Last numeric-ish token before optional currency/note is amount — find first number
1700
+ let amountIdx = -1;
1701
+ for (let i = 0; i < parts.length; i++) {
1702
+ const n = Number(String(parts[i]).replace(/[$,]/g, ''));
1703
+ if (Number.isFinite(n) && n > 0) {
1704
+ amountIdx = i;
1705
+ break;
1706
+ }
1707
+ }
1708
+ if (amountIdx < 0)
1709
+ return { kind: 'help' };
1710
+ const query = parts.slice(0, amountIdx).join(' ').trim();
1711
+ const amount = Number(String(parts[amountIdx]).replace(/[$,]/g, ''));
1712
+ const after = parts.slice(amountIdx + 1);
1713
+ let currency = 'USD';
1714
+ let noteParts = after;
1715
+ if (after[0] && /^[A-Za-z]{3}$/.test(after[0])) {
1716
+ currency = after[0].toUpperCase();
1717
+ noteParts = after.slice(1);
1718
+ }
1719
+ if (!query || !(amount > 0))
1720
+ return { kind: 'help' };
1721
+ return {
1722
+ kind: 'money',
1723
+ query,
1724
+ direction,
1725
+ amount,
1726
+ currency,
1727
+ note: noteParts.join(' ').trim() || undefined,
1728
+ };
1729
+ }
1730
+ const query = parts.join(' ').trim();
1731
+ return query ? { kind: 'money', query } : { kind: 'help' };
1732
+ }
1733
+ if (head === 'log' || head === 'touch') {
1734
+ const summaryFlag = peelFlag(rest, 'summary');
1735
+ const typeFlag = peelFlag(summaryFlag.rest, 'type');
1736
+ const leftover = typeFlag.rest;
1737
+ const knownTypes = new Set(['message', 'call', 'meeting', 'note', 'check_in', 'check-in']);
1738
+ let type = typeFlag.value || 'note';
1739
+ const nameParts = [];
1740
+ for (const part of leftover) {
1741
+ if (!typeFlag.value && knownTypes.has(part.toLowerCase()) && nameParts.length > 0) {
1742
+ type = part.toLowerCase() === 'check-in' ? 'check_in' : part.toLowerCase();
1743
+ continue;
1744
+ }
1745
+ nameParts.push(part);
1746
+ }
1747
+ const query = nameParts.join(' ').trim();
1748
+ if (!query)
1749
+ return { kind: 'help' };
1750
+ return {
1751
+ kind: 'log',
1752
+ query,
1753
+ type: type === 'check-in' ? 'check_in' : type,
1754
+ summary: summaryFlag.value,
1755
+ };
1756
+ }
1757
+ if (head === 'alias') {
1758
+ if (rest.length < 2)
1759
+ return { kind: 'help' };
1760
+ const alias = rest[rest.length - 1];
1761
+ const query = rest.slice(0, -1).join(' ').trim();
1762
+ if (!query || !alias)
1763
+ return { kind: 'help' };
1764
+ return { kind: 'alias', query, alias };
1765
+ }
1766
+ if (head === 'merge') {
1767
+ const keepFlag = peelFlag(rest, 'keep');
1768
+ const queries = keepFlag.rest.map((s) => s.trim()).filter(Boolean);
1769
+ if (queries.length < 2 && !(keepFlag.value && queries.length >= 1)) {
1770
+ return { kind: 'help' };
1771
+ }
1772
+ const keepQuery = keepFlag.value?.trim() || queries[0];
1773
+ const dropQueries = keepFlag.value
1774
+ ? queries
1775
+ : queries.slice(1);
1776
+ if (dropQueries.length < 1)
1777
+ return { kind: 'help' };
1778
+ return { kind: 'merge', keepQuery, dropQueries };
1779
+ }
1780
+ if (head === 'browse' || head === 'ui') {
1781
+ const { sort, query } = peelSortAndLetter(rest);
1782
+ return { kind: 'browse', query, sort };
1783
+ }
1784
+ // `dayze people <query>` or `dayze people --sort=birthday`
1785
+ const { sort, query } = peelSortAndLetter(positional);
1786
+ return { kind: 'browse', query, sort };
1787
+ }
1788
+ export function printPeopleHelp() {
1789
+ console.log(`
1790
+ ${ui.c.brandBold('dayze people')} ${ui.c.dim('— Dayze entity address book')}
1791
+
1792
+ ${ui.c.bold('Browse')} interactive · type to filter · Ctrl+S cycles sort
1793
+ dayze people
1794
+ dayze people --sort=birthday
1795
+ dayze people model
1796
+
1797
+ ${ui.c.bold('List')}
1798
+ dayze people list
1799
+ dayze people list --sort=day
1800
+ dayze people list --sort=birthday
1801
+ dayze people list --sort=last
1802
+ dayze people list --letter=A
1803
+ dayze people list | less
1804
+
1805
+ ${ui.c.bold('Show')}
1806
+ dayze people show <name|@handle|email>
1807
+
1808
+ ${ui.c.bold('Add')} non-interactive
1809
+ dayze people add "Maya Chen" --email=maya@example.com --birthday=1990-05-17
1810
+ Options: ${PEOPLE_ADD_FIELDS.map(field => `--${field}`).join(', ')}
1811
+ Use --flag=value or --flag value. --json prints the created contact.
1812
+
1813
+ ${ui.c.bold('CRM')}
1814
+ dayze people log <name> [message|call|meeting|note] [--summary=…]
1815
+ dayze people alias <name> <nickname>
1816
+ dayze people merge <keep> <drop…> · or --keep="Primary Name"
1817
+ dayze people money <name> · ledger you ↔ them
1818
+ dayze people money <name> to <amt> [CUR] … · you sent them
1819
+ dayze people money <name> from <amt> [CUR] … · they sent you
1820
+ dayze people pay <name> <amt> [CUR] [note]
1821
+ dayze people receive <name> <amt> [CUR] [note]
1822
+ dayze people paid-for <name> · what they paid for you
1823
+
1824
+ ${ui.c.bold('Sort')} (letters filter — never bind sort to a letter)
1825
+ Ctrl+S cycles: name → day↓ → day↑ → →bday → last → …
1826
+ --sort=name|day|day-asc|birthday|last
1827
+
1828
+ ${ui.c.bold('Columns')}
1829
+ DAY Dayze day number (same math as Home)
1830
+ BIRTHDAY days until next birthday
1831
+ IG / INTERACTED / UPDATED / DOSSIER
1832
+ INTERACTED last contact (relative) · UPDATED last profile edit
1833
+ Detail view shows full timestamps with h/m/s
1834
+
1835
+ ${ui.c.bold('Keys')}
1836
+ ↑↓ ⇧↑↓±10 PgUp/Dn Home/End Ctrl+N/P
1837
+ [ ] page up/down · Ctrl+S sort · Ctrl+L clear · type filter · ⌫ · Esc
1838
+ Detail: a agent · e edit · n note · t money · Enter/Esc back
1839
+ `.trimEnd());
1840
+ }
1841
+ export async function runPeopleCommand(creds, positional, options = {}) {
1842
+ const json = Boolean(options.json);
1843
+ const cmd = parsePeopleArgs(positional);
1844
+ switch (cmd.kind) {
1845
+ case 'add': {
1846
+ const { person } = await postAdd(creds, 'people', {
1847
+ ...cmd.fields, action: 'add',
1848
+ });
1849
+ if (json)
1850
+ printJson(person);
1851
+ else
1852
+ ui.ok(`Added “${person.name}” (${person.id})`);
1853
+ return;
1854
+ }
1855
+ case 'help':
1856
+ printPeopleHelp();
1857
+ return;
1858
+ case 'list': {
1859
+ let people = await fetchAllPeople(creds, {
1860
+ q: cmd.query,
1861
+ letter: cmd.letter,
1862
+ });
1863
+ if (cmd.letter && !cmd.query) {
1864
+ const L = cmd.letter.toUpperCase().slice(0, 1);
1865
+ people = people.filter((p) => firstLetter(p.name) === L);
1866
+ }
1867
+ else if (cmd.query) {
1868
+ people = filterPeople(people, cmd.query);
1869
+ }
1870
+ const sort = cmd.sort || 'name';
1871
+ people = sortPeople(people, sort);
1872
+ if (json) {
1873
+ printJson(people);
1874
+ return;
1875
+ }
1876
+ printPeopleTable(people, 'People', sort);
1877
+ return;
1878
+ }
1879
+ case 'show': {
1880
+ const person = await resolvePersonByQuery(creds, cmd.query);
1881
+ if (!person) {
1882
+ if (json)
1883
+ printJson({ error: `No contact matched “${cmd.query}”` });
1884
+ else
1885
+ ui.err(`No contact matched “${cmd.query}”`);
1886
+ process.exitCode = 1;
1887
+ return;
1888
+ }
1889
+ let money = null;
1890
+ try {
1891
+ money = await fetchPersonMoney(creds, person.id);
1892
+ }
1893
+ catch {
1894
+ money = null;
1895
+ }
1896
+ if (json) {
1897
+ printJson({ ...person, money });
1898
+ return;
1899
+ }
1900
+ printPersonDetail(person, false, money);
1901
+ return;
1902
+ }
1903
+ case 'money': {
1904
+ const person = await resolvePersonByQuery(creds, cmd.query);
1905
+ if (!person) {
1906
+ ui.err(`No contact matched “${cmd.query}”`);
1907
+ process.exitCode = 1;
1908
+ return;
1909
+ }
1910
+ if (cmd.direction && cmd.amount != null) {
1911
+ const entry = await logPersonMoney(creds, {
1912
+ personId: person.id,
1913
+ direction: cmd.direction,
1914
+ amount: cmd.amount,
1915
+ currency: cmd.currency,
1916
+ note: cmd.note,
1917
+ });
1918
+ ui.ok(`Logged ${cmd.direction === 'to' ? 'you →' : '← you'} ${person.name}: ${formatMoneyAmount(entry.amount, entry.currency)}`);
1919
+ }
1920
+ const ledger = await fetchPersonMoney(creds, person.id);
1921
+ printPersonMoney(ledger, person.name);
1922
+ console.log('');
1923
+ return;
1924
+ }
1925
+ case 'paid-for': {
1926
+ const person = await resolvePersonByQuery(creds, cmd.query);
1927
+ if (!person) {
1928
+ if (json)
1929
+ printJson({ error: `No contact matched “${cmd.query}”` });
1930
+ else
1931
+ ui.err(`No contact matched “${cmd.query}”`);
1932
+ process.exitCode = 1;
1933
+ return;
1934
+ }
1935
+ const ledger = await fetchPaidForYou(creds, person.id);
1936
+ if (json) {
1937
+ printJson(ledger);
1938
+ return;
1939
+ }
1940
+ printPaidForYou(ledger, person.name);
1941
+ console.log('');
1942
+ return;
1943
+ }
1944
+ case 'log': {
1945
+ const person = await resolvePersonByQuery(creds, cmd.query);
1946
+ if (!person) {
1947
+ ui.err(`No contact matched “${cmd.query}”`);
1948
+ process.exitCode = 1;
1949
+ return;
1950
+ }
1951
+ const json = await postPeopleAction(creds, {
1952
+ action: 'log',
1953
+ id: person.id,
1954
+ type: cmd.type,
1955
+ summary: cmd.summary,
1956
+ });
1957
+ const updated = json.person;
1958
+ ui.ok(`Logged ${cmd.type} with ${person.name}${cmd.summary ? `: “${cmd.summary}”` : ''}`);
1959
+ if (updated)
1960
+ printPersonDetail(updated, false);
1961
+ return;
1962
+ }
1963
+ case 'alias': {
1964
+ const person = await resolvePersonByQuery(creds, cmd.query);
1965
+ if (!person) {
1966
+ ui.err(`No contact matched “${cmd.query}”`);
1967
+ process.exitCode = 1;
1968
+ return;
1969
+ }
1970
+ await postPeopleAction(creds, {
1971
+ action: 'alias',
1972
+ id: person.id,
1973
+ alias: cmd.alias,
1974
+ });
1975
+ ui.ok(`Alias “${cmd.alias}” → ${person.name}`);
1976
+ return;
1977
+ }
1978
+ case 'merge': {
1979
+ const keep = await resolvePersonByQuery(creds, cmd.keepQuery);
1980
+ if (!keep) {
1981
+ ui.err(`No contact matched keep “${cmd.keepQuery}”`);
1982
+ process.exitCode = 1;
1983
+ return;
1984
+ }
1985
+ const sources = [];
1986
+ for (const q of cmd.dropQueries) {
1987
+ const p = await resolvePersonByQuery(creds, q);
1988
+ if (!p) {
1989
+ ui.err(`No contact matched “${q}”`);
1990
+ process.exitCode = 1;
1991
+ return;
1992
+ }
1993
+ if (p.id === keep.id)
1994
+ continue;
1995
+ sources.push(p.id);
1996
+ }
1997
+ if (sources.length < 1) {
1998
+ ui.err('Need at least one other contact to merge into the keep target');
1999
+ process.exitCode = 1;
2000
+ return;
2001
+ }
2002
+ const json = await postPeopleAction(creds, {
2003
+ action: 'merge',
2004
+ targetPersonId: keep.id,
2005
+ sourcePersonIds: sources,
2006
+ });
2007
+ ui.ok(`Merged ${plural(sources.length, 'contact')} into ${keep.name}`);
2008
+ const person = json.person;
2009
+ if (person?.id) {
2010
+ try {
2011
+ const detail = await fetchPersonDetail(creds, String(person.id));
2012
+ printPersonDetail(detail, false);
2013
+ }
2014
+ catch {
2015
+ /* ignore */
2016
+ }
2017
+ }
2018
+ return;
2019
+ }
2020
+ case 'browse':
2021
+ default: {
2022
+ if (json) {
2023
+ // `--json` is for scripts: default to a full directory array (same as `list`).
2024
+ let people = await fetchAllPeople(creds, { q: cmd.query });
2025
+ if (cmd.query)
2026
+ people = filterPeople(people, cmd.query);
2027
+ people = sortPeople(people, cmd.sort || 'name');
2028
+ printJson(people);
2029
+ return;
2030
+ }
2031
+ await runPeopleBrowser(creds, cmd.query, cmd.sort || 'name');
2032
+ }
2033
+ }
2034
+ }