sprag-cli 3.105.0 → 3.106.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
@@ -57,9 +57,9 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
57
57
 
58
58
  ## CLI에서 팀 만들기
59
59
 
60
- 웹 대시보드 없이도, 내가 오너나 어드민인 조직 안에 팀을 만들 수 있습니다. 조직 ID는 대시보드에 있고, 조직 개설은 Sprag가 합니다("조직과 좌석" 절 참고). 로그인은 메일로 받는 6자리 코드(15분간 유효)로 하며, Sprag 은 로그인 세션을 저장하지 않습니다.
60
+ 웹 대시보드 없이도, 내가 오너나 어드민인 조직 안에 팀을 만들 수 있습니다. 조직 ID는 대시보드에 있고, 조직 개설은 Sprag가 합니다("조직과 좌석" 절 참고). 로그인은 메일로 받는 6자리 코드(30분간 유효)와 인증 앱 코드로 합니다. 인증 앱이 없는 계정은 sprag.io/team 에서 먼저 등록합니다. Sprag 은 로그인 세션을 저장하지 않습니다.
61
61
 
62
- 터미널에서는 명령 하나를 실행하고 묻는 대로 답하면 됩니다 (이메일, 코드, 팀 이름).
62
+ 터미널에서는 명령 하나를 실행하고 묻는 대로 답하면 됩니다 (이메일, 코드, 팀 이름, 인증 앱 코드). 코드는 명령이 열어 주는 https://sprag.io/team/ 에서 이메일을 입력해 요청합니다. 코드 요청이 브라우저에서만 되는 Cloudflare 확인을 거치기 때문입니다. 메일로 받은 코드는 터미널에 입력합니다.
63
63
 
64
64
  ```bash
65
65
  sprag team create --org <조직 ID>
@@ -69,11 +69,11 @@ sprag team create --org <조직 ID>
69
69
 
70
70
  ```bash
71
71
  sprag team create --org <조직 ID> --email you@example.com --name "Acme"
72
- # 메일로 코드가 오면 이어서 실행합니다
73
- sprag team create --org <조직 ID> --email you@example.com --name "Acme" --code 123456
72
+ # https://sprag.io/team/ 에서 그 이메일로 코드를 요청해 받으면 이어서 실행합니다
73
+ sprag team create --org <조직 ID> --email you@example.com --name "Acme" --code 123456 --app-code 654321
74
74
  ```
75
75
 
76
- 첫 단계는 코드만 보냅니다. 두 번째 단계에서 코드를 확인하고 팀을 만든 뒤 초대 토큰, 멤버용 명령(`npm i -g sprag-cli@latest && sprag team join <토큰>`), 조직용 환경 변수(`export SPRAG_TEAM_TOKEN=<토큰>`), 대시보드 주소를 출력합니다. 같은 이메일로 https://sprag.io/team/ 에 로그인하면 팀을 관리할 수 있습니다.
76
+ 첫 단계는 코드를 어디서 요청하는지만 알려 줍니다. 두 번째 단계에서 코드와 인증 앱 코드를 확인하고 팀을 만든 뒤 초대 토큰, 멤버용 명령(`npm i -g sprag-cli@latest && sprag team join <토큰>`), 조직용 환경 변수(`export SPRAG_TEAM_TOKEN=<토큰>`), 대시보드 주소를 출력합니다. 같은 이메일로 https://sprag.io/team/ 에 로그인하면 팀을 관리할 수 있습니다.
77
77
 
78
78
  기본적으로 이 PC가 첫 멤버로 참여하고 동기화를 한 번 실행합니다. 참여하지 않으려면 `--no-join` 을 붙입니다. 이미 팀에 참여한 PC에서는 먼저 `sprag team leave` 를 실행하거나 `--no-join` 을 붙여야 합니다.
79
79
 
@@ -165,7 +165,7 @@ Sprag 운영자는 ops 콘솔(sprag.io/ops/)에서 조직마다 최소 Sprag 버
165
165
 
166
166
  ## 대시보드
167
167
 
168
- https://sprag.io/team/ 에서 등록된 오너나 어드민이 이메일 코드로 로그인하고, 팀을 만들고, 초대 토큰을 받습니다. 새 조직은 support@sprag.io 로 문의합니다. 오너, 어드민, 초대 대기 중 어느 쪽에도 없는 이메일은 코드를 보내기 전에 거절하며, 조직 오너에게 추가를 요청하라고 안내합니다. 초대받은 사람은 처음 로그인할 때 자동으로 오너나 어드민이 됩니다. 여기서 구성원별 지출과 절감액을 보고, 규칙 탭에서 조직 룰과 팀 룰을 관리하고, 구성원을 내보낼 수 있습니다. 조직 패널에는 요금제, 한도 대비 사용 좌석, 어드민, 전체 팀이 보입니다. 슈퍼유저는 sprag.io/ops/ 에서 모든 조직을 보고, 조직의 개요 탭에서 어느 조직에든 팀을 만들 수 있습니다. 팀을 만들면 그 팀의 초대 토큰이 화면에 나옵니다. 오너와 어드민과 슈퍼유저는 팀을 삭제할 수 있습니다. 팀 화면에서 초대와 등록을 다루는 탭에 있는 '팀 삭제' 버튼을 쓰거나 /ops/ 조직 개요 탭의 팀 행에서 삭제 버튼을 누릅니다. 일시정지 멤버를 포함해 활동 멤버가 남아 있으면 거절하므로 먼저 멤버를 모두 제거해야 합니다. 팀을 삭제하면 과거 멤버의 사용 기록과 이전 활동 기록도 함께 지워지고 되돌릴 수 없습니다. 활동 로그에는 기계마다 '삭제됨' 항목이 하나씩 남습니다.
168
+ https://sprag.io/team/ 에서 등록된 오너나 어드민이 이메일 코드와 인증 앱(Google Authenticator처럼 6자리 코드를 만드는 TOTP 앱)으로 로그인해 팀을 만들고 초대 토큰을 받습니다. 처음 로그인할 때 QR 코드를 스캔해 앱을 등록하고 그다음부터는 이메일 코드 뒤에 앱 코드를 입력합니다. 로그인 세션은 7일이 지나면 다시 로그인을 요구합니다. 조직 패널에서 어느 어드민이 앱을 등록했는지 보이고, 오너는 휴대폰을 잃은 어드민의 앱을 초기화할 수 있으며, 슈퍼유저는 sprag.io/ops/ 에서 누구의 앱이든 초기화합니다. 멤버는 로그인하지 않으므로 영향이 없습니다. 새 조직은 support@sprag.io 로 문의합니다. 오너, 어드민, 초대 대기 중 어느 쪽에도 없는 이메일은 코드를 보내기 전에 거절하며, 조직 오너에게 추가를 요청하라고 안내합니다. 초대받은 사람은 처음 로그인할 때 자동으로 오너나 어드민이 됩니다. 여기서 구성원별 지출과 절감액을 보고, 규칙 탭에서 조직 룰과 팀 룰을 관리하고, 구성원을 내보낼 수 있습니다. 조직 패널에는 요금제, 한도 대비 사용 좌석, 어드민, 전체 팀이 보입니다. 슈퍼유저는 sprag.io/ops/ 에서 모든 조직을 보고, 조직의 개요 탭에서 어느 조직에든 팀을 만들 수 있습니다. 팀을 만들면 그 팀의 초대 토큰이 화면에 나옵니다. 오너와 어드민과 슈퍼유저는 팀을 삭제할 수 있습니다. 팀 화면에서 초대와 등록을 다루는 탭에 있는 '팀 삭제' 버튼을 쓰거나 /ops/ 조직 개요 탭의 팀 행에서 삭제 버튼을 누릅니다. 일시정지 멤버를 포함해 활동 멤버가 남아 있으면 거절하므로 먼저 멤버를 모두 제거해야 합니다. 팀을 삭제하면 과거 멤버의 사용 기록과 이전 활동 기록도 함께 지워지고 되돌릴 수 없습니다. 활동 로그에는 기계마다 '삭제됨' 항목이 하나씩 남습니다.
169
169
 
170
170
  여러 팀을 한 번에 만들려면 "+ 새 팀"을 누르고 "여러 팀 한 번에 만들기"를 펼친 뒤 한 줄에 팀 이름을 하나씩 붙여 넣습니다. 한 번에 50개까지 만들 수 있습니다. 빈 줄과 조직에 이미 있는 이름, 목록에 두 번 나온 이름, 80자를 넘는 이름은 건너뛰고 따로 알려 줍니다. 만들다가 하나가 실패하면 그 이름에서 멈추고 아직 만들지 못한 이름은 다시 실행할 수 있도록 입력란에 남겨 둡니다. 팀 목록과 타운 탭의 "가입 명령어 내보내기"를 누르면 팀마다 한 줄씩 담긴 CSV를 받습니다. 열은 `team`, `team_id`, `invite_token`, `join_command`(`npm i -g sprag-cli@latest && sprag team join <토큰>`), `shell_profile`(`export SPRAG_TEAM_TOKEN=<토큰>`), `managed_settings`(관리형 설정 JSON)입니다. 일괄 생성이 끝나면 방금 만든 팀만 내보내는 버튼도 나옵니다. 이 파일에는 목록에 있는 모든 팀의 초대 토큰이 들어 있으므로 각 줄은 해당 팀에만 전달하고, 파일이 새어 나가면 그 팀의 토큰을 교체하십시오.
171
171
 
package/docs/TEAM.md CHANGED
@@ -57,9 +57,9 @@ Destination: `https://hiycfjwswtkixyoqkznm.supabase.co/rest/v1/rpc/*` (Supabase,
57
57
 
58
58
  ## Create a team from the CLI
59
59
 
60
- You can set up a team without the web dashboard, inside an organization you own or administer (the organization id is in the dashboard; Sprag opens organizations, see "Organizations and seats"). Signing in uses a 6-digit code emailed to you (valid 15 minutes). Sprag never stores the sign-in session.
60
+ You can set up a team without the web dashboard, inside an organization you own or administer (the organization id is in the dashboard; Sprag opens organizations, see "Organizations and seats"). Signing in uses a 6-digit code emailed to you (valid 30 minutes) and then a code from your authenticator app; an account without an app enrolls one on sprag.io/team first. Sprag never stores the sign-in session.
61
61
 
62
- In a terminal, run one command and answer the prompts (email, code, team name):
62
+ In a terminal, run one command and answer the prompts (email, code, team name, authenticator code). The command opens https://sprag.io/team/ for the code: enter your email there, because the code request passes a Cloudflare check that only a browser can run, and type the emailed code into the terminal.
63
63
 
64
64
  ```bash
65
65
  sprag team create --org <org-id>
@@ -69,11 +69,11 @@ From an agent or any shell without a terminal, it takes two steps:
69
69
 
70
70
  ```bash
71
71
  sprag team create --org <org-id> --email you@example.com --name "Acme"
72
- # the code arrives by email, then:
73
- sprag team create --org <org-id> --email you@example.com --name "Acme" --code 123456
72
+ # request the code at https://sprag.io/team/ with that email, then:
73
+ sprag team create --org <org-id> --email you@example.com --name "Acme" --code 123456 --app-code 654321
74
74
  ```
75
75
 
76
- The first step only sends the code. The second verifies it and creates the team. It then prints the invite token, the member command (`npm i -g sprag-cli@latest && sprag team join <token>`), the organization line (`export SPRAG_TEAM_TOKEN=<token>`) and the dashboard address. Sign in to https://sprag.io/team/ with the same email to manage the team.
76
+ The first step only prints where to request the code. The second verifies it, asks for the authenticator code and creates the team. It then prints the invite token, the member command (`npm i -g sprag-cli@latest && sprag team join <token>`), the organization line (`export SPRAG_TEAM_TOKEN=<token>`) and the dashboard address. Sign in to https://sprag.io/team/ with the same email to manage the team.
77
77
 
78
78
  By default this machine joins as the first member and runs one sync. Pass `--no-join` to skip that. If this machine is already in a team, run `sprag team leave` first or pass `--no-join`.
79
79
 
@@ -166,7 +166,7 @@ If the upgrade fails, for example because the required version is not published
166
166
 
167
167
  ## The dashboard
168
168
 
169
- https://sprag.io/team/ is where a registered owner or admin signs in with an email code, creates a team and gets the invite token. A new organization starts by writing to support@sprag.io. An email that is not an owner, an admin or a pending invite is refused before any code is sent, with a message to ask the organization's owner to add it. Invited people become owner or admin automatically on their first sign-in. From there they see per-member spend and savings, manage organization and team rules on the Rules tab, and remove members. The organization panel shows the plan, seats used against the limit, admins and every team. The superuser sees every organization at sprag.io/ops/ and can create a team in any of them from the organization's Overview tab, which shows the new team's invite token. Owners, admins and the superuser can delete a team (the "Delete team" button in the "Invite & enroll" tab of a team, or the Delete button on the team's row in the organization's Overview tab at /ops/). Sprag refuses while the team still has active members, including paused ones, so remove them first. Deleting a team also erases the usage history and earlier activity of its past members, and it cannot be undone; the activity log keeps one "deleted" entry per machine.
169
+ https://sprag.io/team/ is where a registered owner or admin signs in with an email code and an authenticator app (TOTP, the kind Google Authenticator makes), creates a team and gets the invite token. The first sign-in enrolls the app by scanning a QR code; every later sign-in asks for the email code and then the app's 6-digit code. A session lasts seven days and then asks for a new sign-in. The organization panel shows which admins have enrolled, an owner can reset an admin's app when the phone is lost, and the superuser can reset anyone's at sprag.io/ops/. Members never sign in and are not affected. A new organization starts by writing to support@sprag.io. An email that is not an owner, an admin or a pending invite is refused before any code is sent, with a message to ask the organization's owner to add it. Invited people become owner or admin automatically on their first sign-in. From there they see per-member spend and savings, manage organization and team rules on the Rules tab, and remove members. The organization panel shows the plan, seats used against the limit, admins and every team. The superuser sees every organization at sprag.io/ops/ and can create a team in any of them from the organization's Overview tab, which shows the new team's invite token. Owners, admins and the superuser can delete a team (the "Delete team" button in the "Invite & enroll" tab of a team, or the Delete button on the team's row in the organization's Overview tab at /ops/). Sprag refuses while the team still has active members, including paused ones, so remove them first. Deleting a team also erases the usage history and earlier activity of its past members, and it cannot be undone; the activity log keeps one "deleted" entry per machine.
170
170
 
171
171
  To create several teams at once, open "+ New team", then "Create several teams at once", and paste one team name per line (up to 50 per run). Blank lines, names already in the organization, names listed twice and names over 80 characters are skipped and listed. If one creation fails, the run stops there and the names not yet created stay in the box for another run. "Export join commands" (under the Teams list and on the Town tab) downloads a CSV with one row per team: `team`, `team_id`, `invite_token`, `join_command` (`npm i -g sprag-cli@latest && sprag team join <token>`), `shell_profile` (`export SPRAG_TEAM_TOKEN=<token>`) and `managed_settings` (the managed settings JSON). After a bulk run, a button exports only the teams it created. The file holds every listed team's invite token, so share each row only with that team, and rotate a team's token if the file leaks.
172
172
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sprag-cli",
3
- "version": "3.105.0",
3
+ "version": "3.106.0",
4
4
  "description": "The delegation layer for Claude Code and Codex: each task goes to the model and effort that fits it, down to cheaper models for lookups and up to higher effort when a cheaper run would miss, backed by public replay cases, with a live statusline and team rules for Pro and Enterprise.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -93,6 +93,6 @@
93
93
  },
94
94
  "author": "DeepPulse (https://www.youtube.com/@DeepPulseKR)",
95
95
  "dependencies": {
96
- "smol-toml": "^1.9.0"
96
+ "smol-toml": "^1.9.1"
97
97
  }
98
98
  }
@@ -396,8 +396,8 @@ export async function run({ hasFlag }) {
396
396
  ? ' 서브에이전트 위임 프롬프트에 룰이 정한 상한과 이미 읽은 경로를 덧붙입니다.'
397
397
  : ' appends the rule\'s caps and already-read paths to every subagent delegation prompt.');
398
398
  console.log(lang === 'ko'
399
- ? ' effort 없이 Sonnet에 보낸 위임은 high로 올립니다(실측: 여러 파일 조회 medium 0/3, high 2/3). 상태줄 🔬 Effort saved 가 그 위임이 낸 절감이고 횟수는 그 뒤에 붙습니다.'
400
- : ' a Sonnet delegation sent without an effort runs at high (measured: multi-file lookup 0/3 at medium, 2/3 at high). The statusline shows what those runs saved as 🔬 Effort saved, with the count beside it.');
399
+ ? ' effort 없이 Sonnet에 보낸 위임은 high로 올립니다(실측: 여러 파일 조회 medium 0/3, high 2/3). 상태줄 맨 위 🔬🔥 Effort guard 줄이 그 횟수이고 조용한 오답을 막는 품질 장치라 금액은 주장하지 않습니다.'
400
+ : ' a Sonnet delegation sent without an effort runs at high (measured: multi-file lookup 0/3 at medium, 2/3 at high). The statusline counts them on its top line as 🔬🔥 Effort guard; it is a quality measure against silently wrong results, so no amount is claimed.');
401
401
  console.log(lang === 'ko'
402
402
  ? ' 근거: https://sprag.io/proof/ 끄기: sprag delegate off'
403
403
  : ' evidence: https://sprag.io/proof/ turn off: sprag delegate off');
@@ -81,21 +81,17 @@ function printEffortRaises({ ko, money, totals, since }) {
81
81
  const count = Number(totals?.count) || 0;
82
82
  if (count <= 0) return;
83
83
  const cost = money(Number(totals.cost) || 0);
84
- const keptRuns = Number(totals.keptRuns) || 0;
85
84
  const missing = Number(totals.costMissing) || 0;
86
85
  const unpriced = missing > 0 ? ` +${missing} unpriced` : '';
87
- // The same shape as the routing line above it: the saving first, then what it
88
- // is made of. A raise no rule routed has no saving to show and is counted apart.
89
- const kept = keptRuns > 0 ? money(Number(totals.kept) || 0) : (ko ? '측정 없음' : 'none measured');
90
- const unmatched = count - keptRuns;
86
+ // The guard is a quality measure, not a saver: the count and what the raised
87
+ // runs cost, and no saving of its own. What those runs saved by routing is
88
+ // Routing saved's figure above and is not repeated here.
91
89
  if (ko) {
92
- const runs = `상향 ${count}회${unmatched > 0 && keptRuns > 0 ? ` (룰 없는 ${unmatched}회는 절감 미측정)` : ''}`;
93
- console.log(`effort 절감: ${kept} · ${runs} · 실행 비용 ${cost}${unpriced} (${since})`);
94
- console.log(' effort 없이 Sonnet에 보낸 위임을 high로 올린 횟수와 그 위임이 낸 라우팅 절감입니다. 이 절감은 위 라우팅 절감에 이미 들어 있습니다.');
90
+ console.log(`effort 가드: 상향 ${count}회 · 실행 비용 ${cost}${unpriced} (${since})`);
91
+ console.log(' effort 없이 Sonnet에 보낸 위임을 high로 올려 조용한 저품질 결과를 막습니다. 근거는 재생 실험입니다(여러 파일 조회를 medium 0/3, high 2/3 그대로 전달, 비용 약 25% 증가). 효과는 품질이라 금액으로 재지 않습니다.');
95
92
  } else {
96
- const runs = `${count} raised${unmatched > 0 && keptRuns > 0 ? ` (${unmatched} with no rule, saving not measured)` : ''}`;
97
- console.log(`Effort saved: ${kept} · ${runs} · run cost ${cost}${unpriced} (${since})`);
98
- console.log(' Sonnet delegations sent without an effort ran at high; the saving is what those runs saved by routing and is already inside the routing figure above.');
93
+ console.log(`Effort guard: ${count} raised · run cost ${cost}${unpriced} (${since})`);
94
+ console.log(' Sonnet delegations sent without an effort run at high so that a silently wrong result does not come back. The evidence is the replay (a multi-file lookup relayable 0/3 at medium, 2/3 at high, about 25% more cost). The effect is quality, so no amount is claimed for it.');
99
95
  }
100
96
  }
101
97
 
@@ -9,6 +9,7 @@
9
9
  */
10
10
 
11
11
  import { createInterface } from 'node:readline';
12
+ import { spawn } from 'node:child_process';
12
13
  import { readFileSync } from 'node:fs';
13
14
  import { userLanguage } from '../config.js';
14
15
  import { pendingPrompts } from '../team-prompts.js';
@@ -18,7 +19,7 @@ import { ruleStatsSummary } from '../team-rule-stats.js';
18
19
  import { orgMinVersion, readOrgUpgrade, orgUpgradeInFlight } from '../org-upgrade.js';
19
20
  import {
20
21
  loadTeamState, deviceInfo, isJoined, joinTeam, leaveTeam, syncTeam, autoJoin, aggregateDaily, rpc,
21
- teamRulesCachePath, teamSyncDisabled, requestSignInCode, verifySignInCode, createTeam, isSeatLimitError, isOrgExpiredError,
22
+ teamRulesCachePath, teamSyncDisabled, verifySignInCode, listAuthenticators, verifyAuthenticatorCode, createTeam, isSeatLimitError, isOrgExpiredError,
22
23
  setDisplayName,
23
24
  } from '../team-sync.js';
24
25
  import { standingGuideLines } from '../team-standing.js';
@@ -27,7 +28,7 @@ const T = {
27
28
  en: {
28
29
  usage: [
29
30
  'Usage: sprag team <command>',
30
- ' create [--email <e>] [--name <n>] [--code <6 digits>] [--org <org-id>] [--no-join] create a team (you become the owner)',
31
+ ' create [--email <e>] [--name <n>] [--code <6 digits>] [--app-code <6 digits>] [--org <org-id>] [--no-join] create a team (you become the owner)',
31
32
  ' join [token] [--name <n>] [--yes] join a team (token or SPRAG_TEAM_TOKEN)',
32
33
  ' name [<n>] show or change your display name',
33
34
  ' leave leave the team and stop uploading',
@@ -80,7 +81,7 @@ const T = {
80
81
  renamed: (n) => `Display name changed to "${n}". The dashboard shows it from now on.`,
81
82
  nameHint: 'Change it with: sprag team name "<new name>"',
82
83
  nameUnsupported: 'The team server does not support renaming yet. Try again after it is updated.',
83
- createUsage: 'Usage: sprag team create --email <e> --name "<team name>" [--code <6 digits>] [--no-join]',
84
+ createUsage: 'Usage: sprag team create --email <e> --name "<team name>" [--code <6 digits>] [--app-code <6 digits>] [--no-join]',
84
85
  badEmail: 'That does not look like an email address.',
85
86
  badCode: 'The code is 6 digits, like 123456.',
86
87
  needEmail: 'Missing --email. Usage: sprag team create --email <e> --name "<team name>"',
@@ -88,9 +89,13 @@ const T = {
88
89
  alreadyJoined: (n) => `This machine is already in team "${n}". Run \`sprag team leave\` first, or pass --no-join.`,
89
90
  askEmail: 'Your email: ',
90
91
  askCode: 'Code from the email (6 digits): ',
92
+ askAppCode: 'Code from your authenticator app (6 digits): ',
93
+ badAppCode: 'The authenticator code is 6 digits, like 123456.',
94
+ needAppCode: (e, n) => `Missing --app-code. Run: sprag team create --email ${e} --name "${n}" --code <code> --app-code <authenticator code>`,
95
+ noAuthenticator: 'This account has no authenticator app yet. Sign in once at https://sprag.io/team/ to enroll one (Google Authenticator or any app that makes 6-digit codes), then run this again.',
91
96
  askTeamName: (d) => `Team name [${d}]: `,
92
- codeSent: (e) => `A 6-digit code was sent to ${e} (valid 15 minutes).`,
93
- rerun: (e, n) => `Then run: sprag team create --email ${e} --name "${n}" --code <code>`,
97
+ getCode: (e) => `Request your sign-in code at ${CODE_URL} : enter ${e} there and the 6-digit code arrives by mail (valid 30 minutes). The request runs in the browser because it passes a Cloudflare check.`,
98
+ rerun: (e, n) => `Then run: sprag team create --email ${e} --name "${n}" --code <code> --app-code <authenticator code>`,
94
99
  created: (n) => `Created team "${n}".`,
95
100
  inviteToken: 'Invite token',
96
101
  memberCmd: 'Member command',
@@ -102,7 +107,7 @@ const T = {
102
107
  ko: {
103
108
  usage: [
104
109
  '사용법: sprag team <명령>',
105
- ' create [--email <e>] [--name <이름>] [--code <6자리>] [--org <조직 ID>] [--no-join] 팀 만들기 (만든 사람이 조직 오너)',
110
+ ' create [--email <e>] [--name <이름>] [--code <6자리>] [--app-code <6자리>] [--org <조직 ID>] [--no-join] 팀 만들기 (만든 사람이 조직 오너)',
106
111
  ' join [토큰] [--name <이름>] [--yes] 팀에 참여 (토큰 또는 SPRAG_TEAM_TOKEN)',
107
112
  ' name [<이름>] 표시 이름 보기 또는 바꾸기',
108
113
  ' leave 팀에서 나가고 업로드 중단',
@@ -155,7 +160,7 @@ const T = {
155
160
  renamed: (n) => `표시 이름을 바꿨습니다: ${n}. 이제부터 대시보드에 이 이름이 나옵니다.`,
156
161
  nameHint: '바꾸려면: sprag team name "<새 이름>"',
157
162
  nameUnsupported: '팀 서버가 아직 이름 변경을 지원하지 않습니다. 서버가 갱신된 뒤 다시 시도하세요.',
158
- createUsage: '사용법: sprag team create --email <e> --name "<팀 이름>" [--code <6자리>] [--no-join]',
163
+ createUsage: '사용법: sprag team create --email <e> --name "<팀 이름>" [--code <6자리>] [--app-code <6자리>] [--no-join]',
159
164
  badEmail: '이메일 주소 형식이 아닙니다',
160
165
  badCode: '코드는 123456 같은 6자리 숫자입니다',
161
166
  needEmail: '--email 이 없습니다. 사용법: sprag team create --email <e> --name "<팀 이름>"',
@@ -163,9 +168,13 @@ const T = {
163
168
  alreadyJoined: (n) => `이 PC는 이미 팀 "${n}" 에 참여 중입니다. 먼저 \`sprag team leave\` 를 실행하거나 --no-join 을 붙이세요`,
164
169
  askEmail: '이메일: ',
165
170
  askCode: '메일로 받은 코드 (6자리): ',
171
+ askAppCode: '인증 앱 코드 (6자리): ',
172
+ badAppCode: '인증 앱 코드는 123456 같은 6자리 숫자입니다',
173
+ needAppCode: (e, n) => `--app-code 가 없습니다. 실행: sprag team create --email ${e} --name "${n}" --code <코드> --app-code <인증 앱 코드>`,
174
+ noAuthenticator: '이 계정에는 아직 인증 앱이 없습니다. https://sprag.io/team/ 에 한 번 로그인해 인증 앱(Google Authenticator처럼 6자리 코드를 만드는 앱)을 등록한 뒤 다시 실행하세요',
166
175
  askTeamName: (d) => `팀 이름 [${d}]: `,
167
- codeSent: (e) => `${e} 로 6자리 코드를 보냈습니다 (15분간 유효)`,
168
- rerun: (e, n) => `받은 코드로 다시 실행하세요: sprag team create --email ${e} --name "${n}" --code <코드>`,
176
+ getCode: (e) => `로그인 코드는 ${CODE_URL} 에서 요청하세요. 거기에 ${e} 을 입력하면 6자리 코드가 메일로 옵니다(30분간 유효). Cloudflare 확인을 거치기 때문에 브라우저에서 요청합니다`,
177
+ rerun: (e, n) => `받은 코드로 다시 실행하세요: sprag team create --email ${e} --name "${n}" --code <코드> --app-code <인증 앱 코드>`,
169
178
  created: (n) => `팀 "${n}" 을 만들었습니다`,
170
179
  inviteToken: '초대 토큰',
171
180
  memberCmd: '멤버용 명령',
@@ -203,12 +212,25 @@ async function confirm(question) {
203
212
  }
204
213
 
205
214
  const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
215
+ /** Where the sign-in code is requested: the page runs the Cloudflare check the team server demands. */
216
+ const CODE_URL = 'https://sprag.io/team/';
217
+ /** Opens the URL in the default browser and never fails: the message already carries the address. */
218
+ function openInBrowser(url) {
219
+ const win = process.platform === 'win32';
220
+ const cmd = process.platform === 'darwin' ? 'open' : win ? 'cmd' : 'xdg-open';
221
+ const args = win ? ['/c', 'start', '', url] : [url];
222
+ try {
223
+ const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
224
+ child.on('error', () => {});
225
+ child.unref();
226
+ } catch { /* no opener on this machine */ }
227
+ }
206
228
  const CODE_RE = /^\d{6}$/;
207
229
  // The default display name is the machine id; `status` and `join` then point at `team name`.
208
230
  const MACHINE_NAME_RE = /^member-[0-9a-f]{8}$/;
209
231
 
210
232
  /** `sprag team create`: sign in by emailed code, insert the team, join as first member. */
211
- async function createFlow({ m, out, hasFlag, getArg, version, fetch, interactive, ask }) {
233
+ async function createFlow({ m, out, hasFlag, getArg, version, fetch, interactive, ask, openUrl = openInBrowser }) {
212
234
  const noJoin = hasFlag('--no-join');
213
235
  const st0 = loadTeamState();
214
236
  if (isJoined(st0) && !noJoin) { console.error(m.alreadyJoined(st0.teamName || '')); return process.exit(1); }
@@ -227,21 +249,29 @@ async function createFlow({ m, out, hasFlag, getArg, version, fetch, interactive
227
249
 
228
250
  let useCode = code;
229
251
  if (!useCode) {
230
- if (!interactive) {
231
- await requestSignInCode({ email, fetch });
232
- out(m.codeSent(email));
233
- out(m.rerun(email, name || defaultName));
234
- return undefined;
235
- }
236
- await requestSignInCode({ email, fetch });
237
- out(m.codeSent(email));
252
+ /* The code request passes Cloudflare Turnstile, so it happens on the sign-in page, not here. */
253
+ out(m.getCode(email));
254
+ if (!interactive) { out(m.rerun(email, name || defaultName)); return undefined; }
255
+ openUrl(CODE_URL);
238
256
  useCode = await ask(m.askCode);
239
257
  if (!CODE_RE.test(useCode)) { console.error(m.badCode); return process.exit(2); }
240
258
  }
241
259
  if (!name && interactive) name = (await ask(m.askTeamName(defaultName))) || defaultName;
242
260
  if (!name) { console.error(m.needName); return process.exit(2); }
243
261
 
244
- const { accessToken, userId } = await verifySignInCode({ email, code: useCode, fetch });
262
+ const first = await verifySignInCode({ email, code: useCode, fetch });
263
+ const userId = first.userId;
264
+ /* Second step: the authenticator app. The server refuses team_create below aal2 (sprag-team 20261108000100). */
265
+ const apps = await listAuthenticators({ accessToken: first.accessToken, factors: first.factors, fetch });
266
+ if (!apps.length) { console.error(m.noAuthenticator); return process.exit(1); }
267
+ let appCode = getArg('--app-code');
268
+ if (appCode !== undefined && appCode !== null && !CODE_RE.test(String(appCode))) { console.error(m.badAppCode); return process.exit(2); }
269
+ if (!appCode) {
270
+ if (!interactive) { console.error(m.needAppCode(email, name)); return process.exit(2); }
271
+ appCode = await ask(m.askAppCode);
272
+ if (!CODE_RE.test(appCode)) { console.error(m.badAppCode); return process.exit(2); }
273
+ }
274
+ const { accessToken } = await verifyAuthenticatorCode({ accessToken: first.accessToken, factorId: apps[0].id, code: appCode, fetch });
245
275
  let team;
246
276
  try {
247
277
  team = await createTeam({ name, accessToken, userId, orgId: org || null, fetch });
@@ -268,7 +298,7 @@ async function createFlow({ m, out, hasFlag, getArg, version, fetch, interactive
268
298
  return undefined;
269
299
  }
270
300
 
271
- export async function run({ args, hasFlag, getArg, version, fetch, interactive, ask }) {
301
+ export async function run({ args, hasFlag, getArg, version, fetch, interactive, ask, openUrl }) {
272
302
  const m = T[userLanguage()] || T.en;
273
303
  const verb = args[1];
274
304
  const out = (s) => console.log(s);
@@ -277,7 +307,7 @@ export async function run({ args, hasFlag, getArg, version, fetch, interactive,
277
307
  switch (verb) {
278
308
  case 'create': {
279
309
  const tty = interactive !== undefined ? interactive : !!(process.stdin.isTTY && process.stdout.isTTY);
280
- return await createFlow({ m, out, hasFlag, getArg, version, fetch, interactive: tty, ask: ask || prompt });
310
+ return await createFlow({ m, out, hasFlag, getArg, version, fetch, interactive: tty, ask: ask || prompt, openUrl });
281
311
  }
282
312
  case 'join': {
283
313
  const token = (args[2] && !args[2].startsWith('--') ? args[2] : null) || process.env.SPRAG_TEAM_TOKEN;
@@ -56,6 +56,7 @@ const RESET = '\x1b[0m';
56
56
  const RED = fg(251, 113, 133, '\x1b[31m');
57
57
  const GREEN = fg(52, 211, 153, '\x1b[32m');
58
58
  const YELLOW = fg(251, 191, 36, '\x1b[33m');
59
+ const ORANGE = fg(251, 146, 60, '\x1b[33m'); // orange-400 #FB923C: the effort guard's flame tone
59
60
  const CYAN = fg(34, 211, 238, '\x1b[36m');
60
61
  const MAGENTA = fg(167, 139, 250, '\x1b[35m');
61
62
  const GRAY = fg(100, 116, 139, '\x1b[90m');
@@ -1201,30 +1202,20 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1201
1202
  const delegateSeg = savingsChip || (delegationSaved === 0 ? unresolvedSeg : null);
1202
1203
  const delegateExtra = savingsChip && delegationSaved === 0 ? unresolvedSeg : null;
1203
1204
 
1204
- // Sonnet delegations the guard ran at high effort because the call passed
1205
- // none, in the shape of the other two savings: "Effort saved" is the routing
1206
- // saving those raised runs produced (a part of Routing saved, never added to
1207
- // it), and the raise count rides as the breakdown. A raise with no measured
1208
- // saving (no registered rule routed the run) keeps the gray count chip, as a
1209
- // bare document count does for Doc2md. `sprag saved` prints what the runs cost.
1210
- // icon: "🔬 $12.4" verbose: "🔬 Effort saved $12.4 · 3 raised"
1211
- // text: "Effort saved $12.4"
1212
- // no saving measured: icon "🔬↑3" | text "effort↑3" | verbose "effort raised ×3"
1205
+ // The effort guard: Sonnet delegations the guard ran at high effort because
1206
+ // the call passed none (effort-raise-ledger's totals). It is a quality
1207
+ // measure, not a saver. A raise costs tokens, and what it prevents is a
1208
+ // silently wrong result that nobody would know to rerun, so no amount is
1209
+ // claimed for it. The chip is the count alone, gray, as a bare document
1210
+ // count is for Doc2md; the multi-line layout gives the guard the top line
1211
+ // (guardLine below) and the chip steps aside.
1212
+ // icon "🔬↑3" | text "effort↑3" | verbose "effort guard ×3"
1213
1213
  const raisedInfo = data.effortRaises;
1214
1214
  const raised = Number(raisedInfo && raisedInfo.count) || 0;
1215
- const keptUsd = Number(raisedInfo && raisedInfo.kept) || 0;
1216
- const keptRuns = Number(raisedInfo && raisedInfo.keptRuns) || 0;
1217
- const hasKept = raised > 0 && keptRuns > 0 && keptUsd !== 0;
1218
- const keptTone = keptUsd < 0 ? RED : GREEN;
1219
1215
  const raisedSince = formatSince(raisedInfo && raisedInfo.since);
1220
- const effortLabel = isIcon ? (verbose ? `${g.effort} Effort saved` : g.effort) : 'Effort saved';
1221
- let raisedSeg = null;
1222
- if (hasKept) {
1223
- raisedSeg = `${c(keptTone)}${effortLabel}${c(RESET)} ${formatMoney(keptUsd)}${sinceInline(raisedSince)}`
1224
- + (verbose ? ` ${c(GRAY)}· ${raised} raised${c(RESET)}` : '');
1225
- } else if (raised > 0) {
1226
- raisedSeg = `${c(GRAY)}${verbose ? `effort raised ×${raised}` : isIcon ? `${g.effort}↑${raised}` : `effort↑${raised}`}${c(RESET)}`;
1227
- }
1216
+ const raisedSeg = raised > 0
1217
+ ? `${c(GRAY)}${verbose ? `effort guard ×${raised}` : isIcon ? `${g.effort}↑${raised}` : `effort↑${raised}`}${c(RESET)}`
1218
+ : null;
1228
1219
 
1229
1220
  // Routing-savings headline line (multi-line layout). The lifetime sum from
1230
1221
  // the delegation ledger — the number the whole tool exists to grow, so it
@@ -1269,25 +1260,24 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1269
1260
  (pairText ? ` ${c(GRAY)}|${c(RESET)} ${pairText}` : '');
1270
1261
  }
1271
1262
 
1272
- // The Effort saved line (multi-line layout), under the savings lines and in
1273
- // their anatomy: the figure, the same reset mark as Routing saved, then the
1274
- // breakdown, where the raise count sits as `medium→high ×N $X` (Claude
1275
- // Code's default effort to the one the guard set). Raises that no rule
1276
- // routed have no saving to show and are counted as `no rule ×N (n/a)`, as
1277
- // Doc2md counts a format with no baseline. Built only beside a Routing saved
1278
- // line and only with a measured saving; a bare count stays a chip.
1279
- // icon: "🔬 Effort saved $12.4 since 11/1 | medium→high ×2 $12.4 · no rule ×1 (n/a)"
1280
- // text: "Effort saved $12.4 since 11/1 | medium→high ×2 $12.4 · no rule ×1 (n/a)"
1281
- let raisedLine = null;
1282
- if (totalsLine && hasKept) {
1283
- const head = isIcon ? `${g.effort} Effort saved` : 'Effort saved';
1284
- const parts = [`${c(GRAY)}medium→high ×${keptRuns} ${formatMoney(keptUsd)}${c(RESET)}`];
1285
- if (raised > keptRuns) parts.push(`${c(GRAY)}no rule ×${raised - keptRuns} ${verbose ? '(no saving measured)' : '(n/a)'}${c(RESET)}`);
1286
- raisedLine =
1287
- `${c(keptTone)}${c(BOLD)}${head}${c(RESET)} ` +
1288
- `${c(keptTone)}${formatMoney(keptUsd)}${c(RESET)}` +
1263
+ // The effort guard line (multi-line layout): the top line of the statusline,
1264
+ // above the savings, since what it stands for is the quality of the
1265
+ // delegated work the savings rest on. The count, with the same reset mark as
1266
+ // Routing saved, then the raise itself (`sonnet medium→high`, Claude Code's
1267
+ // default effort to the one the guard set). No money: what a guarded run
1268
+ // saved by routing is Routing saved's figure, and what the guard prevented
1269
+ // (a silently wrong result) has no price anyone measured. Bold in the flame
1270
+ // tone, with 🔥 after 🔬 where the font has it.
1271
+ // icon: "🔬🔥 Effort guard ×3 since 11/1 | sonnet medium→high"
1272
+ // text: "Effort guard ×3 since 11/1 | sonnet medium→high"
1273
+ let guardLine = null;
1274
+ if (!singleLine && raised > 0) {
1275
+ const head = isIcon ? `${g.effort}${g.flame} Effort guard` : 'Effort guard';
1276
+ guardLine =
1277
+ `${c(ORANGE)}${c(BOLD)}${head}${c(RESET)} ` +
1278
+ `${c(ORANGE)}×${raised}${c(RESET)}` +
1289
1279
  sinceWord(raisedSince) +
1290
- ` ${c(GRAY)}|${c(RESET)} ${parts.join(` ${c(GRAY)}·${c(RESET)} `)}`;
1280
+ ` ${c(GRAY)}|${c(RESET)} ${c(GRAY)}sonnet medium→high${c(RESET)}`;
1291
1281
  }
1292
1282
 
1293
1283
  return {
@@ -1297,10 +1287,10 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
1297
1287
  // the dropped runs matter. The raise chip steps aside for its own line the
1298
1288
  // same way, and stays on line 2 while there is no line to carry it.
1299
1289
  chips: totalsLine
1300
- ? (totalsNum === 0 ? [unresolvedSeg, raisedLine ? null : raisedSeg] : [raisedLine ? null : raisedSeg])
1301
- : [delegateSeg, raisedSeg, delegateExtra],
1290
+ ? (totalsNum === 0 ? [unresolvedSeg, guardLine ? null : raisedSeg] : [guardLine ? null : raisedSeg])
1291
+ : [delegateSeg, guardLine ? null : raisedSeg, delegateExtra],
1302
1292
  headline: totalsLine ? { usd: Number(totals && totals.total) || 0, line: totalsLine } : null,
1303
- raisedHeadline: raisedLine ? { usd: keptUsd, line: raisedLine } : null,
1293
+ guardLine,
1304
1294
  };
1305
1295
  }
1306
1296
 
@@ -1583,9 +1573,9 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v,
1583
1573
  if (delegated.headline && want('delegated')) headlines.push(delegated.headline);
1584
1574
  if (doc2md.headline && want('doc2md')) headlines.push(doc2md.headline);
1585
1575
  headlines.sort((a, b) => b.usd - a.usd);
1586
- // The effort-raise line closes the savings lines rather than competing with
1587
- // them: its figure is a part of Routing saved, not a saver of its own.
1588
- if (delegated.raisedHeadline && want('delegated')) headlines.push(delegated.raisedHeadline);
1576
+ // The effort guard line leads them all: it stands for the quality of the
1577
+ // delegated work the savings rest on, and it claims no money of its own.
1578
+ if (delegated.guardLine && want('delegated')) headlines.unshift({ usd: 0, line: delegated.guardLine });
1589
1579
  // The team line comes last: identity and standing, after the money.
1590
1580
  if (teamLine && want('team')) headlines.push(teamLine);
1591
1581
  const rows = columns
package/src/glyphs.js CHANGED
@@ -46,6 +46,9 @@ const ICON = {
46
46
  // cells while being counted as one, and the line shifts on every repaint. 🔬
47
47
  // is W, so it measures the same as its neighbours.
48
48
  effort: '🔬',
49
+ // The effort guard's flame, drawn right after 🔬 on its headline line: the
50
+ // guard is the one thing the statusline shows off. U+1F525, East Asian Width W.
51
+ flame: '🔥',
49
52
  // Ultracode: many arms working at once, which is what it turns on (every task
50
53
  // fans out to parallel subagents). U+1F419, East Asian Width W like the rest
51
54
  // of this set. 🎼 (orchestration) was the first pick but did not read as
@@ -83,6 +86,7 @@ const NARROW = {
83
86
  korean: '⌨', // an input/typing convention rather than a hand
84
87
  model: '◈',
85
88
  effort: '▲', // a magnitude: how hard the turn is being worked
89
+ flame: '', // no font-verified flame; the guard line starts with ▲ alone
86
90
  ultra: '◕', // a nearly full dial; shared with the unknown-window icon, the only ◕ in the line
87
91
  routing: '⇉', // sent down a different path
88
92
  doc: '≣', // stacked lines: a page of text
@@ -17,13 +17,18 @@
17
17
  * The personal figures come from the server's member_standing (team-sync.js
18
18
  * refreshStanding): `dlg`, `medianDlg`, `scorePct`, `spent`, `weights`, `idle`
19
19
  * and `next` ({ grade, pass, needDlg }). An older server sends none of them;
20
- * the block then names the next species from the ladder and says where the
21
- * distance will come from. Pure: no I/O, so the tests pin every wording.
20
+ * the percentile is then read off the rank and the distance computed the way
21
+ * the office drawer does (scorePctOf, nextOf), so the figures never wait for
22
+ * the server. Alone in the standings the percentile is 50% by definition and
23
+ * nothing moves it, and both blocks say so instead of naming a next species.
24
+ * Pure: no I/O, so the tests pin every wording.
22
25
  */
23
26
 
24
27
  import { GRADES, TIER_NAMES, speciesLabel } from './office-species.js';
25
28
 
26
29
  const pct = (v) => `${Math.round(Number(v) * 100)}%`;
30
+ /** A weight as a percentage with one decimal where it has one: 0.625 → 62.5%, 0.5 → 50%. */
31
+ const pctW = (v) => `${Math.round(Number(v) * 1000) / 10}%`;
27
32
  const money = (v) => `$${Number(v).toFixed(2)}`;
28
33
  const floorPct = (g) => Math.round(g.minSr * 100);
29
34
  /**
@@ -43,6 +48,42 @@ export function nextGradeUp(key) {
43
48
  return i > 0 ? GRADES[i - 1] : null;
44
49
  }
45
50
 
51
+ const isRanked = (st) => Number.isInteger(st.rank) && Number.isInteger(st.ranked) && st.rank >= 1 && st.ranked >= st.rank;
52
+
53
+ /**
54
+ * The score percentile the species follow (0 lowest, 1 highest). Alone in the
55
+ * standings it is 0.5 by definition (office-scene.js rank() below two people).
56
+ * Otherwise the server's `scorePct` when it sent one, else read off the rank:
57
+ * the office ranks a score as (people below + ties / 2) / (people − 1), so
58
+ * without ties rank r of n is (n − r) / (n − 1). Ties (two identical scores)
59
+ * would put the true value a little lower. Null when there is no rank.
60
+ */
61
+ export function scorePctOf(st) {
62
+ if (!st || typeof st !== 'object' || !isRanked(st)) return null;
63
+ if (st.ranked < 2) return 0.5;
64
+ if (Number.isFinite(st.scorePct)) return st.scorePct;
65
+ return (st.ranked - st.rank) / (st.ranked - 1);
66
+ }
67
+
68
+ /**
69
+ * The next species up and the distance to it, { grade, pass, needDlg }: the
70
+ * server's `next` when it sent one, otherwise the office drawer's arithmetic on
71
+ * the percentile: people to pass = ceil((floor − percentile) × (people − 1)).
72
+ * Whether the delegation-share rule still stands in the way is known only with
73
+ * the share and the median; without them a species with the rule keeps it.
74
+ * Null when idle, alone, on the top row, or without a percentile.
75
+ */
76
+ export function nextOf(st, sr = scorePctOf(st)) {
77
+ if (!st || typeof st !== 'object') return null;
78
+ const srv = st.next && typeof st.next === 'object' && typeof st.next.grade === 'string' ? st.next : null;
79
+ if (srv) return srv;
80
+ if (st.idle === true || st.grade === 'chick' || !Number.isFinite(sr) || !isRanked(st) || st.ranked < 2) return null;
81
+ const up = nextGradeUp(st.grade);
82
+ if (!up || !(up.minSr >= 0)) return null;
83
+ const dlgOk = Number.isFinite(st.dlg) && Number.isFinite(st.medianDlg) && st.dlg >= st.medianDlg;
84
+ return { grade: up.key, pass: Math.max(0, Math.ceil((up.minSr - sr) * (st.ranked - 1) - 1e-6)), needDlg: up.needDlg && !dlgOk };
85
+ }
86
+
46
87
  /**
47
88
  * @param {object|null|undefined} st team.json `standing`
48
89
  * @param {{ lang?: 'ko'|'en', org?: string|null }} [opts]
@@ -96,8 +137,8 @@ export function standingGuideLines(st, { lang = 'en', org = null, team = null }
96
137
  const w = Array.isArray(st.weights) && st.weights.length >= 2 ? st.weights : null;
97
138
  if (w) {
98
139
  const parts = ko
99
- ? [`기간 지출 순위 ${pct(w[0])}`, `위임 비율 순위 ${pct(w[1])}`, ...(w[2] > 0 ? [`프롬프트 수 순위 ${pct(w[2])}`] : [])]
100
- : [`the spend rank (${pct(w[0])})`, `the delegation-share rank (${pct(w[1])})`, ...(w[2] > 0 ? [`the prompt-count rank (${pct(w[2])})`] : [])];
140
+ ? [`기간 지출 순위 ${pctW(w[0])}`, `위임 비율 순위 ${pctW(w[1])}`, ...(w[2] > 0 ? [`프롬프트 수 순위 ${pctW(w[2])}`] : [])]
141
+ : [`the spend rank (${pctW(w[0])})`, `the delegation-share rank (${pctW(w[1])})`, ...(w[2] > 0 ? [`the prompt-count rank (${pctW(w[2])})`] : [])];
101
142
  lines.push(ko
102
143
  ? ` 종합 점수는 ${parts.slice(0, -1).join(', ')}${parts.length > 1 ? '와 ' : ''}${parts[parts.length - 1]}를 더한 값입니다.`
103
144
  : ` The overall score adds ${parts.slice(0, -1).join(', ')}${parts.length > 1 ? ' and ' : ''}${parts[parts.length - 1]}.`);
@@ -122,49 +163,57 @@ export function standingGuideLines(st, { lang = 'en', org = null, team = null }
122
163
  lines.push(` ${ko ? '이 컴퓨터' : 'This machine'}: ${parts.join(' · ')}`);
123
164
  }
124
165
 
125
- // The next species up, as the office drawer says it, with the percentile it
126
- // starts at; the ladder alone when the server sent no distance.
127
- const next = st.next && typeof st.next === 'object' && typeof st.next.grade === 'string' ? st.next : null;
166
+ // The next species up, as the office drawer says it. The percentile is the
167
+ // server's or read off the rank (scorePctOf), the distance the server's or
168
+ // the drawer's arithmetic (nextOf). Alone in the standings neither moves.
169
+ const sr = scorePctOf(st);
170
+ const solo = st.ranked === 1;
171
+ const next = solo ? null : nextOf(st, sr);
128
172
  const up = nextGradeUp(st.grade);
129
173
  const floorNote = (g) => (g && g.minSr >= 0
130
174
  ? (ko
131
- ? ` (백분위 ${has(st.scorePct) ? `지금 ${pct(st.scorePct)}, ` : ''}${floorPct(g)}%부터)`
132
- : ` (percentile ${has(st.scorePct) ? `now ${pct(st.scorePct)}, ` : ''}${floorPct(g)}% and up)`)
175
+ ? ` (백분위 ${has(sr) ? `지금 ${pct(sr)}, ` : ''}${floorPct(g)}%부터)`
176
+ : ` (percentile ${has(sr) ? `now ${pct(sr)}, ` : ''}${floorPct(g)}% and up)`)
133
177
  : '');
134
- if (next) {
178
+ if (st.idle === true || st.grade === 'chick') {
179
+ lines.push(ko ? ' 다음 등급: 이 기간에 지출이 생기면 순위에 오릅니다.' : ' Next species: spend in this period puts you in the standings.');
180
+ } else if (solo) {
181
+ lines.push(ko
182
+ ? ` 다음 등급: 혼자일 때는 백분위가 50%에 고정되어 ${animal}에 머뭅니다. 동료가 한 명이라도 참여하면 지출 순위와 위임 비율 순위로 등급이 갈립니다.`
183
+ : ` Next species: alone, the percentile stays at 50% and so does the ${animal}. As soon as one colleague joins, the spend rank and the delegation-share rank decide the species.`);
184
+ } else if (next) {
135
185
  const s = label(next.grade);
136
186
  const g = GRADES.find((r) => r.key === next.grade);
137
187
  const x = Math.max(1, Number(next.pass) || 0);
138
- const c = has(st.medianDlg) ? pct(st.medianDlg) : (ko ? '알 수 없음' : 'unknown');
139
- const pts = pointsTo(g, st.scorePct);
188
+ // The median in brackets when the server sent it; the rule is named either way.
189
+ const c = has(st.medianDlg) ? `${ko ? '' : ' '}(${pct(st.medianDlg)})` : '';
190
+ const pts = pointsTo(g, sr);
140
191
  let text;
141
192
  if (pts !== null) {
142
- // With the percentile on record: where you are, how many points more,
143
- // and the people that amounts to.
144
- const now = pct(st.scorePct);
193
+ // With the percentile: where you are, how many points more, and the
194
+ // people that amounts to.
195
+ const now = pct(sr);
145
196
  if (next.needDlg && !(Number(next.pass) > 0)) {
146
197
  text = ko
147
- ? `${s}. 백분위는 이미 ${floorPct(g)}%를 넘었고 위임 비율을 회사 중앙값(${c}) 이상으로 올리면 됩니다.`
148
- : `${s}. Your percentile already clears ${floorPct(g)}%; raise the delegation share to the company median (${c}).`;
198
+ ? `${s}. 백분위는 이미 ${floorPct(g)}%를 넘었고 위임 비율을 회사 중앙값${c} 이상으로 올리면 됩니다.`
199
+ : `${s}. Your percentile already clears ${floorPct(g)}%; raise the delegation share to the company median${c}.`;
149
200
  } else if (next.needDlg) {
150
201
  text = ko
151
- ? `${s}. 지금 백분위 ${now}, ${pts}%p 더 오르고(${x}명 앞지르기) 위임 비율이 회사 중앙값(${c}) 이상이면 됩니다.`
152
- : `${s}. Percentile now ${now}; ${pts} pts more (pass ${x}) and a delegation share at or above the company median (${c}).`;
202
+ ? `${s}. 지금 백분위 ${now}, ${pts}%p 더 오르고(${x}명 앞지르기) 위임 비율이 회사 중앙값${c} 이상이면 됩니다.`
203
+ : `${s}. Percentile now ${now}; ${pts} pts more (pass ${x}) and a delegation share at or above the company median${c}.`;
153
204
  } else {
154
205
  text = ko
155
206
  ? `${s}. 지금 백분위 ${now}, ${Math.max(1, pts)}%p 더 오르면 됩니다 (${x}명 앞지르기).`
156
207
  : `${s}. Percentile now ${now}; ${Math.max(1, pts)} pts more and you are there (pass ${x}).`;
157
208
  }
158
209
  } else if (next.needDlg && !(Number(next.pass) > 0)) {
159
- text = `${ko ? `위임 비율을 회사 중앙값(${c}) 이상으로 올리면 ${s}` : `raise the delegation share to the company median (${c}) to become ${s}`}${floorNote(g)}`;
210
+ text = `${ko ? `위임 비율을 회사 중앙값${c} 이상으로 올리면 ${s}` : `raise the delegation share to the company median${c} to become ${s}`}${floorNote(g)}`;
160
211
  } else if (next.needDlg) {
161
- text = `${ko ? `${x}명을 더 앞지르고 위임 비율이 회사 중앙값(${c}) 이상이면 ${s}` : `pass ${x} more and reach the company median delegation share (${c}) to become ${s}`}${floorNote(g)}`;
212
+ text = `${ko ? `${x}명을 더 앞지르고 위임 비율이 회사 중앙값${c} 이상이면 ${s}` : `pass ${x} more and reach the company median delegation share${c} to become ${s}`}${floorNote(g)}`;
162
213
  } else {
163
214
  text = `${ko ? `${x}명을 더 앞지르면 ${s}` : `pass ${x} more to become ${s}`}${floorNote(g)}`;
164
215
  }
165
216
  lines.push(` ${ko ? '다음 등급' : 'Next species'}: ${text}`);
166
- } else if (st.idle === true || st.grade === 'chick') {
167
- lines.push(ko ? ' 다음 등급: 이 기간에 지출이 생기면 순위에 오릅니다.' : ' Next species: spend in this period puts you in the standings.');
168
217
  } else if (!up) {
169
218
  lines.push(ko ? ' 다음 등급: 도감에서 가장 높은 종입니다.' : ' Next species: the top species in the field guide.');
170
219
  } else {
@@ -192,13 +241,22 @@ export function standingFeedbackShort(st, lang = 'en', { emoji = true } = {}) {
192
241
  const has = (v) => Number.isFinite(v);
193
242
  const ranked = Number.isInteger(st.rank) && Number.isInteger(st.ranked) && st.rank >= 1 && st.ranked >= st.rank;
194
243
  if (st.grade === 'ghost' || !ranked) return [ko ? '이 기간 업로드 없음' : 'no usage this period'];
244
+ const idle = st.idle === true || st.grade === 'chick';
245
+ // Alone in the standings the percentile is 50% by definition and nothing
246
+ // moves it, so the line says that and what would: a colleague joining.
247
+ if (st.ranked === 1 && !idle) {
248
+ return ko
249
+ ? ['지금 50%, 혼자라 고정', '동료가 참여하면 순위 시작']
250
+ : ['now 50%, fixed while alone', 'standings start when a colleague joins'];
251
+ }
195
252
  const out = [];
196
253
  if (st.crown) out.push(ko ? `${emoji ? '👑 ' : ''}회사 1위` : `${emoji ? '👑 ' : ''}#1 in the company`);
197
254
  else if (st.rank === 1 && st.ranked === 1) out.push(ko ? '혼자 순위에 있음' : 'alone in the standings');
198
255
  else if (st.rank === 1) out.push(ko ? '회사 1위' : '#1 in the company');
199
256
  else out.push(ko ? `1위까지 ${st.rank - 1}명` : `${st.rank - 1} to pass for #1`);
200
257
 
201
- const next = st.next && typeof st.next === 'object' && typeof st.next.grade === 'string' ? st.next : null;
258
+ const sr = scorePctOf(st);
259
+ const next = nextOf(st, sr);
202
260
  const up = nextGradeUp(st.grade);
203
261
  const floor = (g) => (g && g.minSr >= 0 ? (ko ? `${floorPct(g)}%부터` : `${floorPct(g)}% and up`) : '');
204
262
  if (next) {
@@ -206,10 +264,10 @@ export function standingFeedbackShort(st, lang = 'en', { emoji = true } = {}) {
206
264
  const g = GRADES.find((x) => x.key === next.grade);
207
265
  const x = Math.max(1, Number(next.pass) || 0);
208
266
  const c = has(st.medianDlg) ? pct(st.medianDlg) : (ko ? '회사 중앙값' : 'the company median');
209
- const pts = pointsTo(g, st.scorePct);
267
+ const pts = pointsTo(g, sr);
210
268
  if (pts !== null) {
211
- // With the percentile on record: where you are and how many points more.
212
- const now = pct(st.scorePct);
269
+ // With the percentile: where you are and how many points more.
270
+ const now = pct(sr);
213
271
  if (next.needDlg && !(Number(next.pass) > 0)) out.push(ko ? `지금 ${now}, 위임 비율 ${c} 이상이면 ${s}` : `now ${now}, delegation share ${c} or more for ${s}`);
214
272
  else if (next.needDlg) out.push(ko ? `지금 ${now}, ${pts}%p 더 오르고 위임 비율 ${c} 이상이면 ${s}` : `now ${now}, ${pts} pts more and delegation share ${c} or more for ${s}`);
215
273
  else out.push(ko ? `지금 ${now}, ${Math.max(1, pts)}%p 더 오르면 ${s} (${x}명 앞지르기)` : `now ${now}, ${Math.max(1, pts)} pts more for ${s} (pass ${x})`);
@@ -220,7 +278,7 @@ export function standingFeedbackShort(st, lang = 'en', { emoji = true } = {}) {
220
278
  } else {
221
279
  out.push(ko ? `다음 ${s}: ${x}명 더${floor(g) ? ` (${floor(g)})` : ''}` : `next ${s}: ${x} more${floor(g) ? ` (${floor(g)})` : ''}`);
222
280
  }
223
- } else if (st.idle === true || st.grade === 'chick') {
281
+ } else if (idle) {
224
282
  out.push(ko ? '지출이 생기면 순위에 오름' : 'spend to enter the standings');
225
283
  } else if (!up) {
226
284
  out.push(ko ? '도감 최상위' : 'top of the field guide');
package/src/team-sync.js CHANGED
@@ -298,7 +298,7 @@ export async function rpc(fn, params, {
298
298
  * as rpc(). Errors carry the server's own message. The access token only ever
299
299
  * lives in memory: it is never written to disk or printed.
300
300
  */
301
- async function apiJson(path, { body, accessToken, label, fetch = globalThis.fetch, timeoutMs = 8000, url = teamApiUrl(), key = teamAnonKey(), prefer } = {}) {
301
+ async function apiJson(path, { body, accessToken, label, fetch = globalThis.fetch, timeoutMs = 8000, url = teamApiUrl(), key = teamAnonKey(), prefer, method = 'POST' } = {}) {
302
302
  trustSystemCA();
303
303
  const ctl = new AbortController();
304
304
  const timer = setTimeout(() => ctl.abort(), timeoutMs);
@@ -306,7 +306,7 @@ async function apiJson(path, { body, accessToken, label, fetch = globalThis.fetc
306
306
  const headers = { apikey: key, 'Content-Type': 'application/json' };
307
307
  if (accessToken) headers.Authorization = `Bearer ${accessToken}`;
308
308
  if (prefer) headers.Prefer = prefer;
309
- const res = await fetch(`${url}${path}`, { method: 'POST', headers, body: JSON.stringify(body || {}), signal: ctl.signal });
309
+ const res = await fetch(`${url}${path}`, { method, headers, body: method === 'GET' ? undefined : JSON.stringify(body || {}), signal: ctl.signal });
310
310
  let data = null;
311
311
  try { data = await res.json(); } catch { /* empty or non-JSON body */ }
312
312
  if (!res.ok) {
@@ -322,16 +322,41 @@ async function apiJson(path, { body, accessToken, label, fetch = globalThis.fetc
322
322
  }
323
323
  }
324
324
 
325
- /** Email a 6-digit sign-in code (valid 15 minutes). Creates the user if new. */
326
- export async function requestSignInCode({ email, fetch } = {}) {
327
- await apiJson('/auth/v1/otp', { body: { email, create_user: true }, label: 'sign-in', fetch });
328
- }
329
-
330
- /** Exchange the emailed code for a session. Returns { accessToken, userId }. */
325
+ /**
326
+ * Exchange the emailed code for a session. Returns { accessToken, userId, factors }.
327
+ * The session is aal1: the server refuses every owner and admin action until an
328
+ * authenticator code is verified too (verifyAuthenticatorCode).
329
+ */
331
330
  export async function verifySignInCode({ email, code, fetch } = {}) {
332
331
  const r = await apiJson('/auth/v1/verify', { body: { type: 'email', email, token: code }, label: 'verify', fetch });
333
332
  if (!r || !r.access_token || !r.user || !r.user.id) throw new Error('verify: no session returned');
334
- return { accessToken: r.access_token, userId: r.user.id };
333
+ return { accessToken: r.access_token, userId: r.user.id, factors: Array.isArray(r.user.factors) ? r.user.factors : null };
334
+ }
335
+
336
+ /**
337
+ * The verified authenticator apps (TOTP factors) of the signed-in account, from the
338
+ * sign-in answer when it carried them, otherwise from GET /auth/v1/user. Empty when
339
+ * the person has not enrolled one yet (that happens on sprag.io/team).
340
+ */
341
+ export async function listAuthenticators({ accessToken, factors = null, fetch } = {}) {
342
+ let all = factors;
343
+ if (!Array.isArray(all)) {
344
+ const u = await apiJson('/auth/v1/user', { method: 'GET', accessToken, label: 'authenticators', fetch });
345
+ all = (u && Array.isArray(u.factors)) ? u.factors : [];
346
+ }
347
+ return all.filter((f) => f && f.factor_type === 'totp' && f.status === 'verified').map((f) => ({ id: f.id, name: f.friendly_name || '' }));
348
+ }
349
+
350
+ /**
351
+ * The second sign-in step: challenge one authenticator factor and verify the 6-digit
352
+ * code from the app. Returns { accessToken } for the aal2 session the server accepts.
353
+ */
354
+ export async function verifyAuthenticatorCode({ accessToken, factorId, code, fetch } = {}) {
355
+ const ch = await apiJson(`/auth/v1/factors/${encodeURIComponent(factorId)}/challenge`, { accessToken, label: 'authenticator', fetch });
356
+ if (!ch || !ch.id) throw new Error('authenticator: no challenge returned');
357
+ const r = await apiJson(`/auth/v1/factors/${encodeURIComponent(factorId)}/verify`, { body: { challenge_id: ch.id, code }, accessToken, label: 'authenticator', fetch });
358
+ if (!r || !r.access_token) throw new Error('authenticator: no session returned');
359
+ return { accessToken: r.access_token };
335
360
  }
336
361
 
337
362
  /**