sprag-cli 3.81.0 → 3.82.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.
package/docs/TEAM.ko.md CHANGED
@@ -24,9 +24,9 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
24
24
 
25
25
  하루 단위 집계 업로드는 마지막 성공 이후 5분에 한 번 이하로 실행됩니다. SessionStart 훅(그리고 작은 로컬 파일만 읽는 프롬프트 훅)이 띄운 분리된 자식 프로세스가 보냅니다. 네트워크가 끊기는 등 동기화가 실패하면 5분 주기 대신 15분, 30분, 60분 뒤에 다시 시도합니다(최대 60분 간격). 마지막으로 올린 날짜를 기억해 두었다가 그 전날부터 최대 30일 치를 다시 보내므로, 며칠 꺼져 있던 컴퓨터도 처음 성공하는 동기화에서 빠진 날을 따라잡습니다. 하루 단위 행은 덮어쓰기라 다시 보내도 안전합니다. 프롬프트 수집을 켠 엔터프라이즈 팀의 프롬프트 업로드는 따로 30분 타이머로 움직입니다("프롬프트 사용량 (엔터프라이즈)" 절 참고). statusline 을 그리는 경로에서는 절대 실행되지 않습니다.
26
26
 
27
- 팀에 참여한 동안 statusline 에 `team` 칩이 나타나 멤버 ID 와 가상 사무실(Sprag 타운)에서 받은 동물을 보여 줍니다. 예를 들면 `member-1e500474 🦊 여우 12명 중 3위` 처럼 조직에서 순위에 오른 사람 가운데 몇 위인지도 함께 보여 줍니다. 동물은 5분마다 도는 전체 동기화가 서버에서 받아 `team.json` 에 저장한 순위로 정합니다. 서버가 아직 이 기능을 지원하지 않거나 마지막으로 받은 지 하루가 넘었다면 멤버 ID 만 표시합니다. 칩을 그릴 때는 로컬 파일만 읽습니다. 버전 칩 바로 앞에 놓이며, `--segments team` 으로 이 칩만 따로 볼 수 있습니다.
27
+ 팀에 참여한 동안 statusline 에 `team` 칩이 나타나 멤버 ID 와 가상 사무실(Sprag 타운)에서 받은 동물을 보여 줍니다. 예를 들면 `member-1e500474 🦊 여우 12명 중 3위` 처럼 조직에서 순위에 오른 사람 가운데 몇 위인지도 함께 보여 줍니다. 동물은 5분마다 도는 전체 동기화가 서버에서 받아 `team.json` 에 저장한 순위로 정합니다. 서버가 아직 이 기능을 지원하지 않거나 마지막으로 받은 지 하루가 넘었다면 멤버 ID 만 표시합니다. 칩을 그릴 때는 로컬 파일만 읽습니다. IntelliJ 터미널은 글꼴에 동물 이모지가 없어 narrow 모드로 그리므로, 이때와 text 모드에서는 `member-1e500474 여우 12명 중 3위` 처럼 이모지 없이 이름만 보여 줍니다. 버전 칩 바로 앞에 놓이며, `--segments team` 으로 이 칩만 따로 볼 수 있습니다.
28
28
 
29
- 목적지는 `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` 입니다(Supabase, ap-northeast-2 리전). 호출하는 RPC 는 `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put`(엔터프라이즈 프롬프트 수집일 때만), `member_set_sync`(업로드 스위치 상태 호출, "업로드 스위치" 참고), `member_set_info`(OS 이름과 버전, `arch` 인자는 항상 빈 값), `member_standing`(statusline 칩에 쓸 본인의 사무실 동물과 순위만 받고 다른 사람의 수치는 받지 않음) 입니다.
29
+ 목적지는 `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` 입니다(Supabase, ap-northeast-2 리전). 호출하는 RPC 는 `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put`(엔터프라이즈 프롬프트 수집일 때만), `member_set_sync`(업로드 스위치 상태 호출, "업로드 스위치" 참고), `member_set_info`(OS 이름과 버전, `arch` 인자는 항상 빈 값), `member_set_name`(`sprag team name` 을 실행할 때만), `member_standing`(statusline 칩에 쓸 본인의 사무실 동물과 순위만 받고 다른 사람의 수치는 받지 않음) 입니다.
30
30
 
31
31
  ## CLI에서 팀 만들기
32
32
 
@@ -62,6 +62,14 @@ Sprag 이 올라갈 항목 목록을 보여 주고 확인을 묻습니다. `--na
62
62
 
63
63
  결과는 `sprag team status` 로 확인합니다.
64
64
 
65
+ 참여한 뒤에 표시 이름을 바꾸려면 아래 명령을 실행합니다. `SPRAG_TEAM_TOKEN` 으로 자동 참여해 구성원 ID로 표시되는 컴퓨터도 같은 방법으로 바꿉니다.
66
+
67
+ ```bash
68
+ sprag team name "김미나"
69
+ ```
70
+
71
+ 바꾼 뒤부터 대시보드에 새 이름이 나오며, 이미 올라간 날짜별 집계는 같은 구성원에 그대로 남습니다. 이름은 앞뒤 공백을 지우고 80자에서 자릅니다. 나중에 `--name` 없이 `sprag team join` 을 다시 실행하면 이 컴퓨터가 마지막으로 쓴 이름을 그대로 씁니다. 이름 없이 `sprag team name` 만 실행하면 지금 이름을 보여 줍니다.
72
+
65
73
  ## 조직 단위로 등록하기
66
74
 
67
75
  구성원이 각자 명령을 실행하지 않아도 모든 컴퓨터를 등록하려면 환경에 `SPRAG_TEAM_TOKEN=<토큰>` 을 지정합니다. 흔한 위치는 두 곳입니다.
@@ -94,6 +102,7 @@ Sprag 은 룰을 `~/.claude/ratchet-team.md`(Codex 는 `<CODEX_HOME>/ratchet-tea
94
102
  | 명령 | 설명 |
95
103
  |---|---|
96
104
  | `sprag team join [토큰] [--name <이름>] [--yes]` | 팀에 참여 |
105
+ | `sprag team name [<이름>]` | 대시보드에 나오는 표시 이름 보기 또는 바꾸기 |
97
106
  | `sprag team status [--show-payload]` | 팀, 플랜, 프롬프트 수집 설정, 표시 이름, 마지막 동기화를 보여 줍니다. `--show-payload` 를 붙이면 보내는 기기 정보와 올라갈 하루 단위 행도 그대로 출력합니다 |
98
107
  | `sprag team sync [--force] [--rules-only]` | 지금 업로드하고 룰을 받습니다. `--force` 는 5분 간격을 무시하고, `--rules-only` 는 조직·팀 룰만 받고 아무것도 올리지 않습니다 |
99
108
  | `sprag team rules` | 받아 둔 조직·팀 룰 보기 |
package/docs/TEAM.md CHANGED
@@ -24,9 +24,9 @@ Not sent: prompts, transcripts, file paths, project names, rule text, API keys.
24
24
 
25
25
  The daily aggregate upload runs at most once every 5 minutes after the last successful one, from a detached child process that the SessionStart hook (and the prompt hook, which only reads a small local file) spawns. If a sync fails, for example because the network is down, it is retried after 15, then 30, then 60 minutes (60 at most) instead of every 5 minutes. The CLI remembers the last day it uploaded and re-sends from the day before it, up to 30 days, so a machine that was offline for days catches up on its first successful sync. Re-sending a day is safe because each day is an upsert. The prompt upload of an Enterprise team with capture on has its own 30-minute timer (see "Prompt usage (Enterprise)"). It never runs on the statusline path.
26
26
 
27
- While this machine is joined, the statusline shows a `team` chip with your member id and your animal from the virtual office (Sprag Town), for example `member-1e500474 🦊 Fox #3 of 12`, with your overall rank among the ranked people of the organization. The animal comes from the standing the full sync fetches every 5 minutes and stores in `team.json`; if the server does not offer it yet, or the last fetch is more than a day old, only the member id is shown. Rendering the chip reads local files only. It sits just before the version chip, and `--segments team` shows it on its own.
27
+ While this machine is joined, the statusline shows a `team` chip with your member id and your animal from the virtual office (Sprag Town), for example `member-1e500474 🦊 Fox #3 of 12`, with your overall rank among the ranked people of the organization. The animal comes from the standing the full sync fetches every 5 minutes and stores in `team.json`; if the server does not offer it yet, or the last fetch is more than a day old, only the member id is shown. Rendering the chip reads local files only. It sits just before the version chip, and `--segments team` shows it on its own. IntelliJ's terminal font has no animal emoji, so there (narrow mode) and in text mode the chip drops the emoji and keeps the name: `member-1e500474 Fox #3 of 12`.
28
28
 
29
- Destination: `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` (Supabase, region ap-northeast-2). The calls are the RPCs `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put` (Enterprise prompt capture only), `member_set_sync` (the upload-switch status call, see "The upload switch") `member_set_info` (OS name and version; the `arch` argument is always empty) and `member_standing` (your own office animal and rank for the statusline chip; it returns nobody else's figures); `sprag team create` also calls `team_create` with your sign-in session.
29
+ Destination: `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` (Supabase, region ap-northeast-2). The calls are the RPCs `team_join`, `ledger_upsert`, `team_rules_get`, `team_rule_propose`, `team_leave`, `prompt_chunk_put` (Enterprise prompt capture only), `member_set_sync` (the upload-switch status call, see "The upload switch") `member_set_info` (OS name and version; the `arch` argument is always empty), `member_set_name` (only when you run `sprag team name`) and `member_standing` (your own office animal and rank for the statusline chip; it returns nobody else's figures); `sprag team create` also calls `team_create` with your sign-in session.
30
30
 
31
31
  ## Create a team from the CLI
32
32
 
@@ -62,6 +62,14 @@ Sprag prints the list of what will be uploaded and asks for confirmation. `--nam
62
62
 
63
63
  Check the result with `sprag team status`.
64
64
 
65
+ To change the display name after joining, including a machine that joined through `SPRAG_TEAM_TOKEN` under its member ID, run:
66
+
67
+ ```bash
68
+ sprag team name "Mina Kim"
69
+ ```
70
+
71
+ The dashboard shows the new name from then on; the uploaded days stay with the same member. Names are trimmed and cut at 80 characters. A later `sprag team join` without `--name` keeps the name this machine last used. `sprag team name` without a name prints the current one.
72
+
65
73
  ## Enroll an organization
66
74
 
67
75
  To enroll every machine without each person running a command, set `SPRAG_TEAM_TOKEN=<token>` in the environment. Two common places:
@@ -94,6 +102,7 @@ Sprag writes the rules to `~/.claude/ratchet-team.md` (Codex: `<CODEX_HOME>/ratc
94
102
  | Command | What it does |
95
103
  |---|---|
96
104
  | `sprag team join [token] [--name <n>] [--yes]` | Join a team |
105
+ | `sprag team name [<n>]` | Show or change your display name on the dashboard |
97
106
  | `sprag team status [--show-payload]` | Team, plan, prompt-capture flag, display name, last sync. `--show-payload` also prints the device info and the exact daily rows that would be uploaded |
98
107
  | `sprag team sync [--force] [--rules-only]` | Upload now and pull rules. `--force` ignores the 5-minute interval; `--rules-only` pulls the organization and team rules and uploads nothing |
99
108
  | `sprag team rules` | Show the cached organization and team rules |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.81.0",
3
+ "version": "3.82.0",
4
4
  "description": "Model-delegation router for Claude Code and Codex: lookups, checks and test runs go to cheaper models, documents go in as compact Markdown, and a live statusline shows spend and savings.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,5 +1,5 @@
1
1
  /**
2
- * team — `sprag team <create|join|leave|status|sync|rules|propose>`.
2
+ * team — `sprag team <create|join|name|leave|status|sync|rules|propose>`.
3
3
  *
4
4
  * The opt-in team layer. `join` shows exactly what will be uploaded (daily
5
5
  * aggregates only) and asks before enrolling. `sync --background` is what the
@@ -16,6 +16,7 @@ import { memberId } from '../member-id.js';
16
16
  import {
17
17
  loadTeamState, deviceInfo, isJoined, joinTeam, leaveTeam, syncTeam, autoJoin, aggregateDaily, rpc,
18
18
  teamRulesCachePath, teamSyncDisabled, requestSignInCode, verifySignInCode, createTeam, isSeatLimitError, isOrgExpiredError,
19
+ setDisplayName,
19
20
  } from '../team-sync.js';
20
21
 
21
22
  const T = {
@@ -24,6 +25,7 @@ const T = {
24
25
  'Usage: sprag team <command>',
25
26
  ' create [--email <e>] [--name <n>] [--code <6 digits>] [--org <org-id>] [--no-join] create a team (you become the owner)',
26
27
  ' join [token] [--name <n>] [--yes] join a team (token or SPRAG_TEAM_TOKEN)',
28
+ ' name [<n>] show or change your display name',
27
29
  ' leave leave the team and stop uploading',
28
30
  ' status [--show-payload] membership, last sync, what is sent',
29
31
  ' sync [--force] [--rules-only] upload aggregates, prompts (Enterprise capture) and pull rules now',
@@ -66,6 +68,9 @@ const T = {
66
68
  needText: 'Missing rule text. Usage: sprag team propose <text> [--scope ratchet|model]',
67
69
  badScope: 'Scope must be ratchet or model.',
68
70
  needJoin: 'Join a team first: sprag team join <token>',
71
+ renamed: (n) => `Display name changed to "${n}". The dashboard shows it from now on.`,
72
+ nameHint: 'Change it with: sprag team name "<new name>"',
73
+ nameUnsupported: 'The team server does not support renaming yet. Try again after it is updated.',
69
74
  createUsage: 'Usage: sprag team create --email <e> --name "<team name>" [--code <6 digits>] [--no-join]',
70
75
  badEmail: 'That does not look like an email address.',
71
76
  badCode: 'The code is 6 digits, like 123456.',
@@ -90,6 +95,7 @@ const T = {
90
95
  '사용법: sprag team <명령>',
91
96
  ' create [--email <e>] [--name <이름>] [--code <6자리>] [--org <조직 ID>] [--no-join] 팀 만들기 (만든 사람이 조직 오너)',
92
97
  ' join [토큰] [--name <이름>] [--yes] 팀에 참여 (토큰 또는 SPRAG_TEAM_TOKEN)',
98
+ ' name [<이름>] 표시 이름 보기 또는 바꾸기',
93
99
  ' leave 팀에서 나가고 업로드 중단',
94
100
  ' status [--show-payload] 참여 상태, 마지막 동기화, 보내는 내용',
95
101
  ' sync [--force] [--rules-only] 지금 집계를 올리고 규칙을 받기',
@@ -132,6 +138,9 @@ const T = {
132
138
  needText: '규칙 내용이 없습니다. 사용법: sprag team propose <내용> [--scope ratchet|model]',
133
139
  badScope: '범위는 ratchet 또는 model 이어야 합니다.',
134
140
  needJoin: '먼저 팀에 참여하세요: sprag team join <토큰>',
141
+ renamed: (n) => `표시 이름을 바꿨습니다: ${n}. 이제부터 대시보드에 이 이름이 나옵니다.`,
142
+ nameHint: '바꾸려면: sprag team name "<새 이름>"',
143
+ nameUnsupported: '팀 서버가 아직 이름 변경을 지원하지 않습니다. 서버가 갱신된 뒤 다시 시도하세요.',
135
144
  createUsage: '사용법: sprag team create --email <e> --name "<팀 이름>" [--code <6자리>] [--no-join]',
136
145
  badEmail: '이메일 주소 형식이 아닙니다',
137
146
  badCode: '코드는 123456 같은 6자리 숫자입니다',
@@ -180,6 +189,8 @@ async function confirm(question) {
180
189
 
181
190
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
182
191
  const CODE_RE = /^\d{6}$/;
192
+ // The default display name is the machine id; `status` and `join` then point at `team name`.
193
+ const MACHINE_NAME_RE = /^member-[0-9a-f]{8}$/;
183
194
 
184
195
  /** `sprag team create`: sign in by emailed code, insert the team, join as first member. */
185
196
  async function createFlow({ m, out, hasFlag, getArg, version, fetch, interactive, ask }) {
@@ -256,8 +267,9 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
256
267
  case 'join': {
257
268
  const token = (args[2] && !args[2].startsWith('--') ? args[2] : null) || process.env.SPRAG_TEAM_TOKEN;
258
269
  if (!token) { console.error(m.noToken); return process.exit(2); }
270
+ // A rejoin keeps the name this machine had before (`team leave` keeps it in team.json).
259
271
  let name = getArg('--name');
260
- if (!name) name = memberId();
272
+ if (!name) name = String(loadTeamState().displayName || '').trim() || memberId();
261
273
  out(m.willSend);
262
274
  out(m.asName(name));
263
275
  out(m.asDevice(memberId()));
@@ -268,6 +280,22 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
268
280
  const st = await joinTeam({ token, displayName: name, fetch, version });
269
281
  out(m.joined(st.teamName));
270
282
  if (st.orgName && st.seatsUsed != null && st.seatLimit != null) out(m.orgCreated(st.orgName, st.seatsUsed, st.seatLimit));
283
+ if (MACHINE_NAME_RE.test(String(st.displayName || ''))) out(m.nameHint);
284
+ return undefined;
285
+ }
286
+ case 'name':
287
+ case 'rename': {
288
+ const st = loadTeamState();
289
+ if (!isJoined(st)) { console.error(m.needJoin); return process.exit(2); }
290
+ const next = args.slice(2).filter((a) => !a.startsWith('--')).join(' ').trim();
291
+ if (!next) { out(`${m.name}: ${st.displayName}`); out(m.nameHint); return undefined; }
292
+ if (teamSyncDisabled()) { out(m.disabled); return undefined; }
293
+ try {
294
+ out(m.renamed(await setDisplayName({ displayName: next, fetch })));
295
+ } catch (e) {
296
+ if (/Could not find the function|PGRST202/i.test(String(e && e.message))) { console.error(m.nameUnsupported); return process.exit(1); }
297
+ throw e;
298
+ }
271
299
  return undefined;
272
300
  }
273
301
  case 'leave':
@@ -285,6 +313,7 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
285
313
  out(st.lastPromptUploadAt ? m.lastPrompts(new Date(st.lastPromptUploadAt).toLocaleString(), st.lastPromptCount || 0) : m.noPrompts);
286
314
  }
287
315
  out(`${m.name}: ${st.displayName}`);
316
+ if (MACHINE_NAME_RE.test(String(st.displayName || ''))) out(` ${m.nameHint}`);
288
317
  out(st.lastSyncAt ? m.lastSync(new Date(st.lastSyncAt).toLocaleString(), st.lastSyncRows || 0) : m.neverSynced);
289
318
  if (st.lastError) out(isOrgExpiredError(st.lastError) ? m.orgExpired : `${m.lastError}: ${st.lastError}`);
290
319
  if (hasFlag('--show-payload')) {
@@ -374,12 +374,14 @@ const TEAM_STANDING_MAX_AGE_MS = 24 * 60 * 60 * 1000;
374
374
  * member is in the team's virtual office and the rank (`member-1e500474 🦊 Fox #3 of 12`). Renders only
375
375
  * for a joined machine. A missing, unknown or day-old standing leaves just the
376
376
  * member label. Gray like the other identity chips; the emoji brings its own colour.
377
+ * The emoji draws only in icon mode: narrow (the IntelliJ default, whose font has
378
+ * no animal emoji) and text keep the animal's name and the rank.
377
379
  */
378
- function buildTeamSeg(team, c, now = Date.now()) {
380
+ function buildTeamSeg(team, c, mode = 'icon', now = Date.now()) {
379
381
  if (!team || typeof team !== 'object' || !team.label) return null;
380
382
  const st = team.standing;
381
383
  const fresh = st && Number.isFinite(st.fetchedAt) && now - st.fetchedAt <= TEAM_STANDING_MAX_AGE_MS;
382
- const animal = fresh ? speciesLabel(st.grade, team.lang) : null;
384
+ const animal = fresh ? speciesLabel(st.grade, team.lang, { emoji: mode === 'icon' }) : null;
383
385
  // The rank among the ranked people, the same standing the office drawer shows; a ghost has none.
384
386
  const ranked = animal && Number.isInteger(st.rank) && Number.isInteger(st.ranked) && st.rank >= 1 && st.ranked >= st.rank;
385
387
  const place = ranked ? (team.lang === 'ko' ? ` ${st.ranked}명 중 ${st.rank}위` : ` #${st.rank} of ${st.ranked}`) : '';
@@ -575,7 +577,7 @@ export function formatNoSession({ caps = null, model = null, effort = null, wind
575
577
  const effortSeg = buildEffortSeg(effort, c, isIcon, g);
576
578
  if (effortSeg) segs.push(effortSeg);
577
579
  segs.push(`${c(GRAY)}${g.hit} no session data${windowLabel ? ` · ${windowLabel}` : ''}${c(RESET)}`);
578
- const teamSeg = buildTeamSeg(team, c);
580
+ const teamSeg = buildTeamSeg(team, c, mode);
579
581
  if (teamSeg) segs.push(teamSeg);
580
582
  if (versionSeg && !(update && update.available)) segs.push(versionSeg);
581
583
  return segs.join(' · ') + (color ? '\x1b[K' : '');
@@ -1401,7 +1403,7 @@ export function formatReport(data, { color = true, verbose = false, timer = true
1401
1403
  // check — this render path never touches the network.
1402
1404
  version: buildVersionSeg(options.version, data.update, c, isIcon, verbose, g),
1403
1405
  // Member id and office animal, from team.json; null unless this machine joined a team.
1404
- team: buildTeamSeg(data.team, c),
1406
+ team: buildTeamSeg(data.team, c, mode),
1405
1407
  // Delegation-rule registry (`rules 10 · ⚠1`), opt-in through `--segments`.
1406
1408
  rules: buildRulesSeg(data.ruleStats, c, g),
1407
1409
  };
@@ -42,8 +42,13 @@ export const SPECIES = {
42
42
  ghost: { emoji: '👻', en: 'Ghost', ko: '유령' },
43
43
  };
44
44
 
45
- /** `"<emoji> <name>"` for a grade key in the given language, or null for an unknown key. */
46
- export function speciesLabel(grade, lang = 'en') {
45
+ /**
46
+ * `"<emoji> <name>"` for a grade key in the given language, or null for an unknown key.
47
+ * `emoji: false` leaves just the name, for terminals whose font has no animal emoji (IntelliJ).
48
+ */
49
+ export function speciesLabel(grade, lang = 'en', { emoji = true } = {}) {
47
50
  const s = Object.prototype.hasOwnProperty.call(SPECIES, grade) ? SPECIES[grade] : null;
48
- return s ? `${s.emoji} ${lang === 'ko' ? s.ko : s.en}` : null;
51
+ if (!s) return null;
52
+ const name = lang === 'ko' ? s.ko : s.en;
53
+ return emoji ? `${s.emoji} ${name}` : name;
49
54
  }
package/src/team-sync.js CHANGED
@@ -483,6 +483,26 @@ export async function joinTeam({
483
483
  return out;
484
484
  }
485
485
 
486
+ export const DISPLAY_NAME_MAX = 80;
487
+
488
+ /**
489
+ * Rename this machine's member row (`sprag team name <n>`). The server trims
490
+ * and cuts the name the same way; its answer is what gets stored locally.
491
+ * Throws when not joined or the name is empty, before any fetch.
492
+ */
493
+ export async function setDisplayName({ displayName, fetch, dir = userDataDir() } = {}) {
494
+ // Array.from counts code points like Postgres left() does, so an emoji is never split.
495
+ const name = Array.from(String(displayName || '').trim()).slice(0, DISPLAY_NAME_MAX).join('').trim();
496
+ if (!name) throw new Error('display name is empty');
497
+ const state = loadTeamState(dir);
498
+ if (!isJoined(state)) throw new Error('not in a team');
499
+ const r = await rpc('member_set_name', { member_key: state.memberKey, display_name: name }, { fetch });
500
+ const stored = typeof r === 'string' && r.trim() ? r : name;
501
+ // Re-read so a background sync that saved in the meantime keeps its fields.
502
+ saveTeamState({ ...loadTeamState(dir), displayName: stored }, dir);
503
+ return stored;
504
+ }
505
+
486
506
  export async function leaveTeam({ fetch, dir = userDataDir(), now = Date.now() } = {}) {
487
507
  const prev = loadTeamState(dir);
488
508
  let lastError;