sprag-cli 3.104.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 +6 -6
- package/docs/TEAM.md +6 -6
- package/package.json +2 -2
- package/src/commands/install.js +2 -2
- package/src/commands/saved.js +7 -11
- package/src/commands/team.js +51 -21
- package/src/formatters/statusline.js +88 -49
- package/src/glyphs.js +7 -0
- package/src/team-standing.js +158 -18
- package/src/team-sync.js +41 -9
package/docs/TEAM.ko.md
CHANGED
|
@@ -57,9 +57,9 @@ Sprag 은 기본적으로 로컬에서만 동작합니다. 팀 기능은 켜야
|
|
|
57
57
|
|
|
58
58
|
## CLI에서 팀 만들기
|
|
59
59
|
|
|
60
|
-
웹 대시보드 없이도, 내가 오너나 어드민인 조직 안에 팀을 만들 수 있습니다. 조직 ID는 대시보드에 있고, 조직 개설은 Sprag가 합니다("조직과 좌석" 절 참고). 로그인은 메일로 받는 6자리 코드(
|
|
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
|
-
첫 단계는
|
|
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/ 에서 등록된 오너나 어드민이 이메일
|
|
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
|
|
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
|
|
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
|
|
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.
|
|
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.
|
|
96
|
+
"smol-toml": "^1.9.1"
|
|
97
97
|
}
|
|
98
98
|
}
|
package/src/commands/install.js
CHANGED
|
@@ -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). 상태줄
|
|
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
|
|
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');
|
package/src/commands/saved.js
CHANGED
|
@@ -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
|
|
88
|
-
//
|
|
89
|
-
|
|
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
|
-
|
|
93
|
-
console.log(
|
|
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
|
-
|
|
97
|
-
console.log(
|
|
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
|
|
package/src/commands/team.js
CHANGED
|
@@ -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,
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
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
|
|
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;
|
|
@@ -31,6 +31,7 @@ import { modelFamily } from '../savings-ledger.js';
|
|
|
31
31
|
import { shareLegend } from '../model-share.js';
|
|
32
32
|
import { STAR_URL } from '../star-note.js';
|
|
33
33
|
import { speciesLabel } from '../office-species.js';
|
|
34
|
+
import { standingFeedbackShort } from '../team-standing.js';
|
|
34
35
|
import { cellWidth } from '../cell-width.js';
|
|
35
36
|
|
|
36
37
|
// The 8-color ANSI defaults (RED=31, GREEN=32, YELLOW=33…) read as garish
|
|
@@ -55,6 +56,7 @@ const RESET = '\x1b[0m';
|
|
|
55
56
|
const RED = fg(251, 113, 133, '\x1b[31m');
|
|
56
57
|
const GREEN = fg(52, 211, 153, '\x1b[32m');
|
|
57
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
|
|
58
60
|
const CYAN = fg(34, 211, 238, '\x1b[36m');
|
|
59
61
|
const MAGENTA = fg(167, 139, 250, '\x1b[35m');
|
|
60
62
|
const GRAY = fg(100, 116, 139, '\x1b[90m');
|
|
@@ -429,6 +431,48 @@ function buildTeamSeg(team, c, mode = 'icon', now = Date.now()) {
|
|
|
429
431
|
return `${c(GRAY)}${plan}${team.label}${org}${animal ? `${place} ${animal}` : ''}${c(RESET)}`;
|
|
430
432
|
}
|
|
431
433
|
|
|
434
|
+
/**
|
|
435
|
+
* The team line (multi-line layout): the licensed team this machine belongs
|
|
436
|
+
* to, on a line of its own so it never blends into the diagnostics chips, and
|
|
437
|
+
* what the standing asks of you. Head: plan, organization, team, member id.
|
|
438
|
+
* Breakdown: the rank with the animal, then the short feedback from
|
|
439
|
+
* src/team-standing.js (people to pass for #1, the next species and what it
|
|
440
|
+
* takes). Null for a machine that has not joined; the chip above stands in on
|
|
441
|
+
* the single-line layouts.
|
|
442
|
+
* icon: "👥 Pro · amazon · AWS-FSI · member-1e500474 | 종합 점수 12명 중 3위, 팀 4명 중 1위 🦊 여우 · 1위까지 2명 · 다음 🐆 치타: 2명 더 (77%부터)"
|
|
443
|
+
* text: "Pro · amazon · AWS-FSI · member-1e500474 | overall score #3 of 12, team #1 of 4 Fox · 2 to pass for #1 · next Cheetah: 2 more (77% and up)"
|
|
444
|
+
*/
|
|
445
|
+
function buildTeamLine(team, c, isIcon, g, mode = 'icon', now = Date.now()) {
|
|
446
|
+
if (!team || typeof team !== 'object' || !team.label) return null;
|
|
447
|
+
const ko = team.lang === 'ko';
|
|
448
|
+
const emoji = mode === 'icon';
|
|
449
|
+
const plan = typeof team.plan === 'string' && team.plan ? `${team.plan[0].toUpperCase()}${team.plan.slice(1)}` : null;
|
|
450
|
+
const org = typeof team.org === 'string' && team.org ? team.org : null;
|
|
451
|
+
const teamName = typeof team.team === 'string' && team.team && team.team !== org ? team.team : null;
|
|
452
|
+
// Narrow has no verified glyph for the team, so its head starts with the words.
|
|
453
|
+
const head = `${isIcon && g.team ? `${g.team} ` : ''}${[plan, org, teamName, team.label].filter(Boolean).join(' · ')}`;
|
|
454
|
+
const st = team.standing;
|
|
455
|
+
const fresh = st && Number.isFinite(st.fetchedAt) && now - st.fetchedAt <= TEAM_STANDING_MAX_AGE_MS;
|
|
456
|
+
const parts = [];
|
|
457
|
+
if (fresh) {
|
|
458
|
+
const animal = speciesLabel(st.grade, team.lang, { emoji });
|
|
459
|
+
const ranked = animal && Number.isInteger(st.rank) && Number.isInteger(st.ranked) && st.rank >= 1 && st.ranked >= st.rank;
|
|
460
|
+
if (ranked) {
|
|
461
|
+
const inTeam = Number.isInteger(st.teamRank) && Number.isInteger(st.teamRanked)
|
|
462
|
+
&& st.teamRank >= 1 && st.teamRanked >= st.teamRank && st.teamRanked < st.ranked;
|
|
463
|
+
const teamPlace = inTeam ? (ko ? `, 팀 ${st.teamRanked}명 중 ${st.teamRank}위` : `, team #${st.teamRank} of ${st.teamRanked}`) : '';
|
|
464
|
+
parts.push(ko ? `종합 점수 ${st.ranked}명 중 ${st.rank}위${teamPlace} ${animal}` : `overall score #${st.rank} of ${st.ranked}${teamPlace} ${animal}`);
|
|
465
|
+
} else if (animal) {
|
|
466
|
+
parts.push(animal);
|
|
467
|
+
}
|
|
468
|
+
parts.push(...standingFeedbackShort(st, team.lang, { emoji }));
|
|
469
|
+
}
|
|
470
|
+
const tail = parts.length
|
|
471
|
+
? ` ${c(GRAY)}|${c(RESET)} ${parts.map((p) => `${c(GRAY)}${p}${c(RESET)}`).join(` ${c(GRAY)}·${c(RESET)} `)}`
|
|
472
|
+
: '';
|
|
473
|
+
return { usd: 0, line: `${c(GRAY)}${c(BOLD)}${head}${c(RESET)}${tail}` };
|
|
474
|
+
}
|
|
475
|
+
|
|
432
476
|
/**
|
|
433
477
|
* Harness 🅷 segment builder — shared by the full report and the no-session
|
|
434
478
|
* fallback line. Best-effort: never throws into the statusline (corrupted
|
|
@@ -1158,30 +1202,20 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
|
|
|
1158
1202
|
const delegateSeg = savingsChip || (delegationSaved === 0 ? unresolvedSeg : null);
|
|
1159
1203
|
const delegateExtra = savingsChip && delegationSaved === 0 ? unresolvedSeg : null;
|
|
1160
1204
|
|
|
1161
|
-
// Sonnet delegations the guard ran at high effort because
|
|
1162
|
-
//
|
|
1163
|
-
//
|
|
1164
|
-
//
|
|
1165
|
-
//
|
|
1166
|
-
//
|
|
1167
|
-
//
|
|
1168
|
-
// text
|
|
1169
|
-
// 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"
|
|
1170
1213
|
const raisedInfo = data.effortRaises;
|
|
1171
1214
|
const raised = Number(raisedInfo && raisedInfo.count) || 0;
|
|
1172
|
-
const keptUsd = Number(raisedInfo && raisedInfo.kept) || 0;
|
|
1173
|
-
const keptRuns = Number(raisedInfo && raisedInfo.keptRuns) || 0;
|
|
1174
|
-
const hasKept = raised > 0 && keptRuns > 0 && keptUsd !== 0;
|
|
1175
|
-
const keptTone = keptUsd < 0 ? RED : GREEN;
|
|
1176
1215
|
const raisedSince = formatSince(raisedInfo && raisedInfo.since);
|
|
1177
|
-
const
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
raisedSeg = `${c(keptTone)}${effortLabel}${c(RESET)} ${formatMoney(keptUsd)}${sinceInline(raisedSince)}`
|
|
1181
|
-
+ (verbose ? ` ${c(GRAY)}· ${raised} raised${c(RESET)}` : '');
|
|
1182
|
-
} else if (raised > 0) {
|
|
1183
|
-
raisedSeg = `${c(GRAY)}${verbose ? `effort raised ×${raised}` : isIcon ? `${g.effort}↑${raised}` : `effort↑${raised}`}${c(RESET)}`;
|
|
1184
|
-
}
|
|
1216
|
+
const raisedSeg = raised > 0
|
|
1217
|
+
? `${c(GRAY)}${verbose ? `effort guard ×${raised}` : isIcon ? `${g.effort}↑${raised}` : `effort↑${raised}`}${c(RESET)}`
|
|
1218
|
+
: null;
|
|
1185
1219
|
|
|
1186
1220
|
// Routing-savings headline line (multi-line layout). The lifetime sum from
|
|
1187
1221
|
// the delegation ledger — the number the whole tool exists to grow, so it
|
|
@@ -1226,25 +1260,24 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
|
|
|
1226
1260
|
(pairText ? ` ${c(GRAY)}|${c(RESET)} ${pairText}` : '');
|
|
1227
1261
|
}
|
|
1228
1262
|
|
|
1229
|
-
// The
|
|
1230
|
-
//
|
|
1231
|
-
//
|
|
1232
|
-
//
|
|
1233
|
-
//
|
|
1234
|
-
//
|
|
1235
|
-
//
|
|
1236
|
-
//
|
|
1237
|
-
//
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
const
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
`${c(
|
|
1245
|
-
`${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)}` +
|
|
1246
1279
|
sinceWord(raisedSince) +
|
|
1247
|
-
` ${c(GRAY)}|${c(RESET)} ${
|
|
1280
|
+
` ${c(GRAY)}|${c(RESET)} ${c(GRAY)}sonnet medium→high${c(RESET)}`;
|
|
1248
1281
|
}
|
|
1249
1282
|
|
|
1250
1283
|
return {
|
|
@@ -1254,10 +1287,10 @@ function buildDelegatedSeg(data, singleLine, c, isIcon, verbose, g) {
|
|
|
1254
1287
|
// the dropped runs matter. The raise chip steps aside for its own line the
|
|
1255
1288
|
// same way, and stays on line 2 while there is no line to carry it.
|
|
1256
1289
|
chips: totalsLine
|
|
1257
|
-
? (totalsNum === 0 ? [unresolvedSeg,
|
|
1258
|
-
: [delegateSeg, raisedSeg, delegateExtra],
|
|
1290
|
+
? (totalsNum === 0 ? [unresolvedSeg, guardLine ? null : raisedSeg] : [guardLine ? null : raisedSeg])
|
|
1291
|
+
: [delegateSeg, guardLine ? null : raisedSeg, delegateExtra],
|
|
1259
1292
|
headline: totalsLine ? { usd: Number(totals && totals.total) || 0, line: totalsLine } : null,
|
|
1260
|
-
|
|
1293
|
+
guardLine,
|
|
1261
1294
|
};
|
|
1262
1295
|
}
|
|
1263
1296
|
|
|
@@ -1531,7 +1564,7 @@ function arrangeSegments(order, s) {
|
|
|
1531
1564
|
/**
|
|
1532
1565
|
* The headline lines that sit above the chips, as one string of `line\n` pairs.
|
|
1533
1566
|
*/
|
|
1534
|
-
function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v) {
|
|
1567
|
+
function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v, teamLine = null) {
|
|
1535
1568
|
// Each savings source that earned real money gets a headline line, ordered
|
|
1536
1569
|
// biggest saver first — the top line is the one the eye lands on, so it
|
|
1537
1570
|
// goes to whichever habit is actually paying for the tool. The diagnostics
|
|
@@ -1540,9 +1573,11 @@ function buildHeadlines(delegated, doc2md, want, eol, columns = 0, c = (v) => v)
|
|
|
1540
1573
|
if (delegated.headline && want('delegated')) headlines.push(delegated.headline);
|
|
1541
1574
|
if (doc2md.headline && want('doc2md')) headlines.push(doc2md.headline);
|
|
1542
1575
|
headlines.sort((a, b) => b.usd - a.usd);
|
|
1543
|
-
// The effort
|
|
1544
|
-
//
|
|
1545
|
-
if (delegated.
|
|
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 });
|
|
1579
|
+
// The team line comes last: identity and standing, after the money.
|
|
1580
|
+
if (teamLine && want('team')) headlines.push(teamLine);
|
|
1546
1581
|
const rows = columns
|
|
1547
1582
|
? headlines.flatMap((h) => wrapHeadline(h.line, availWidth(columns), c))
|
|
1548
1583
|
: headlines.map((h) => h.line);
|
|
@@ -1602,6 +1637,9 @@ export function formatReport(data, { color = true, verbose = false, timer = true
|
|
|
1602
1637
|
|
|
1603
1638
|
// One slot per chip; segmentsNamed() maps the names in the segment list onto
|
|
1604
1639
|
// these slots, so this is the only place that knows how each chip is built.
|
|
1640
|
+
// The team gets a line of its own in the multi-line layout (buildTeamLine),
|
|
1641
|
+
// and its chip steps aside; the single-line layout keeps the chip.
|
|
1642
|
+
const teamLine = singleLine ? null : buildTeamLine(data.team, c, isIcon, g, mode);
|
|
1605
1643
|
const built = {
|
|
1606
1644
|
capWarn: buildCapWarnSeg(capWarn, c, isIcon, g, color, mode),
|
|
1607
1645
|
spike: buildSpikeSeg(spikeChip, c),
|
|
@@ -1638,7 +1676,8 @@ export function formatReport(data, { color = true, verbose = false, timer = true
|
|
|
1638
1676
|
// check — this render path never touches the network.
|
|
1639
1677
|
version: buildVersionSeg(options.version, data.update, c, isIcon, verbose, g),
|
|
1640
1678
|
// Member id and office animal, from team.json; null unless this machine joined a team.
|
|
1641
|
-
team
|
|
1679
|
+
// Null when the team line carries it (multi-line layout), so no empty slot is drawn.
|
|
1680
|
+
team: teamLine ? null : buildTeamSeg(data.team, c, mode),
|
|
1642
1681
|
// Delegation-rule registry (`rules 10 · ⚠1`), opt-in through `--segments`.
|
|
1643
1682
|
rules: buildRulesSeg(data.ruleStats, c, g),
|
|
1644
1683
|
};
|
|
@@ -1651,8 +1690,8 @@ export function formatReport(data, { color = true, verbose = false, timer = true
|
|
|
1651
1690
|
// "erase from cursor to EOL" CSI. Only emitted when color (i.e. ANSI) is
|
|
1652
1691
|
// allowed — --no-color/NO_COLOR consumers expect escape-free output.
|
|
1653
1692
|
const eol = color ? '\x1b[K' : '';
|
|
1654
|
-
if (singleLine || !columns) return buildHeadlines(delegated, doc2md, want, eol) + segs.join(' · ') + eol;
|
|
1655
|
-
const headlines = buildHeadlines(delegated, doc2md, want, eol, columns, c);
|
|
1693
|
+
if (singleLine || !columns) return buildHeadlines(delegated, doc2md, want, eol, 0, c, teamLine) + segs.join(' · ') + eol;
|
|
1694
|
+
const headlines = buildHeadlines(delegated, doc2md, want, eol, columns, c, teamLine);
|
|
1656
1695
|
|
|
1657
1696
|
// The chips that stop the work: layoutChips drops from the tail when the
|
|
1658
1697
|
// terminal is narrow, and these must survive that.
|
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
|
|
@@ -56,6 +59,8 @@ const ICON = {
|
|
|
56
59
|
hit: '🧠',
|
|
57
60
|
ttl: '⏳',
|
|
58
61
|
month: '💵',
|
|
62
|
+
// Team: the people this machine is ranked among. U+1F465, East Asian Width W.
|
|
63
|
+
team: '👥',
|
|
59
64
|
ctx: '📦',
|
|
60
65
|
saved: '💰',
|
|
61
66
|
used: '📊',
|
|
@@ -81,12 +86,14 @@ const NARROW = {
|
|
|
81
86
|
korean: '⌨', // an input/typing convention rather than a hand
|
|
82
87
|
model: '◈',
|
|
83
88
|
effort: '▲', // a magnitude: how hard the turn is being worked
|
|
89
|
+
flame: '', // no font-verified flame; the guard line starts with ▲ alone
|
|
84
90
|
ultra: '◕', // a nearly full dial; shared with the unknown-window icon, the only ◕ in the line
|
|
85
91
|
routing: '⇉', // sent down a different path
|
|
86
92
|
doc: '≣', // stacked lines: a page of text
|
|
87
93
|
hit: '◉', // bullseye: a cache hit
|
|
88
94
|
ttl: '◔', // a partly elapsed dial
|
|
89
95
|
month: '∑', // a running total
|
|
96
|
+
team: '', // no glyph verified in the font yet; the team line's own words lead it
|
|
90
97
|
ctx: '◧', // a box filling up
|
|
91
98
|
saved: '✓',
|
|
92
99
|
used: '◩', // a split square: what the spend is made of
|
package/src/team-standing.js
CHANGED
|
@@ -17,21 +17,73 @@
|
|
|
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
|
|
21
|
-
*
|
|
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);
|
|
34
|
+
/**
|
|
35
|
+
* Percentage points from the score percentile `sr` up to the floor of species
|
|
36
|
+
* `g`, at least 1 while the floor is not cleared, 0 when it already is (then
|
|
37
|
+
* only the delegation rule stands in the way). Null without a percentile or a
|
|
38
|
+
* floor (the idle row has none).
|
|
39
|
+
*/
|
|
40
|
+
export function pointsTo(g, sr) {
|
|
41
|
+
if (!g || !(g.minSr >= 0) || !Number.isFinite(sr)) return null;
|
|
42
|
+
const pts = Math.ceil((g.minSr - sr) * 100 - 1e-9);
|
|
43
|
+
return pts <= 0 ? 0 : pts;
|
|
44
|
+
}
|
|
29
45
|
/** The species one row up the ladder, or null on the top row and for unknown keys. */
|
|
30
46
|
export function nextGradeUp(key) {
|
|
31
47
|
const i = GRADES.findIndex((g) => g.key === key);
|
|
32
48
|
return i > 0 ? GRADES[i - 1] : null;
|
|
33
49
|
}
|
|
34
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
|
+
|
|
35
87
|
/**
|
|
36
88
|
* @param {object|null|undefined} st team.json `standing`
|
|
37
89
|
* @param {{ lang?: 'ko'|'en', org?: string|null }} [opts]
|
|
@@ -85,8 +137,8 @@ export function standingGuideLines(st, { lang = 'en', org = null, team = null }
|
|
|
85
137
|
const w = Array.isArray(st.weights) && st.weights.length >= 2 ? st.weights : null;
|
|
86
138
|
if (w) {
|
|
87
139
|
const parts = ko
|
|
88
|
-
? [`기간 지출 순위 ${
|
|
89
|
-
: [`the spend rank (${
|
|
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])})`] : [])];
|
|
90
142
|
lines.push(ko
|
|
91
143
|
? ` 종합 점수는 ${parts.slice(0, -1).join(', ')}${parts.length > 1 ? '와 ' : ''}${parts[parts.length - 1]}를 더한 값입니다.`
|
|
92
144
|
: ` The overall score adds ${parts.slice(0, -1).join(', ')}${parts.length > 1 ? ' and ' : ''}${parts[parts.length - 1]}.`);
|
|
@@ -111,30 +163,57 @@ export function standingGuideLines(st, { lang = 'en', org = null, team = null }
|
|
|
111
163
|
lines.push(` ${ko ? '이 컴퓨터' : 'This machine'}: ${parts.join(' · ')}`);
|
|
112
164
|
}
|
|
113
165
|
|
|
114
|
-
// The next species up, as the office drawer says it
|
|
115
|
-
//
|
|
116
|
-
|
|
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);
|
|
117
172
|
const up = nextGradeUp(st.grade);
|
|
118
173
|
const floorNote = (g) => (g && g.minSr >= 0
|
|
119
174
|
? (ko
|
|
120
|
-
? ` (백분위 ${has(
|
|
121
|
-
: ` (percentile ${has(
|
|
175
|
+
? ` (백분위 ${has(sr) ? `지금 ${pct(sr)}, ` : ''}${floorPct(g)}%부터)`
|
|
176
|
+
: ` (percentile ${has(sr) ? `now ${pct(sr)}, ` : ''}${floorPct(g)}% and up)`)
|
|
122
177
|
: '');
|
|
123
|
-
if (
|
|
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) {
|
|
124
185
|
const s = label(next.grade);
|
|
186
|
+
const g = GRADES.find((r) => r.key === next.grade);
|
|
125
187
|
const x = Math.max(1, Number(next.pass) || 0);
|
|
126
|
-
|
|
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);
|
|
127
191
|
let text;
|
|
128
|
-
if (
|
|
129
|
-
|
|
192
|
+
if (pts !== null) {
|
|
193
|
+
// With the percentile: where you are, how many points more, and the
|
|
194
|
+
// people that amounts to.
|
|
195
|
+
const now = pct(sr);
|
|
196
|
+
if (next.needDlg && !(Number(next.pass) > 0)) {
|
|
197
|
+
text = ko
|
|
198
|
+
? `${s}. 백분위는 이미 ${floorPct(g)}%를 넘었고 위임 비율을 회사 중앙값${c} 이상으로 올리면 됩니다.`
|
|
199
|
+
: `${s}. Your percentile already clears ${floorPct(g)}%; raise the delegation share to the company median${c}.`;
|
|
200
|
+
} else if (next.needDlg) {
|
|
201
|
+
text = ko
|
|
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}.`;
|
|
204
|
+
} else {
|
|
205
|
+
text = ko
|
|
206
|
+
? `${s}. 지금 백분위 ${now}, ${Math.max(1, pts)}%p 더 오르면 됩니다 (${x}명 앞지르기).`
|
|
207
|
+
: `${s}. Percentile now ${now}; ${Math.max(1, pts)} pts more and you are there (pass ${x}).`;
|
|
208
|
+
}
|
|
209
|
+
} else if (next.needDlg && !(Number(next.pass) > 0)) {
|
|
210
|
+
text = `${ko ? `위임 비율을 회사 중앙값${c} 이상으로 올리면 ${s}` : `raise the delegation share to the company median${c} to become ${s}`}${floorNote(g)}`;
|
|
130
211
|
} else if (next.needDlg) {
|
|
131
|
-
text = ko ? `${x}명을 더 앞지르고 위임 비율이 회사
|
|
212
|
+
text = `${ko ? `${x}명을 더 앞지르고 위임 비율이 회사 중앙값${c} 이상이면 ${s}` : `pass ${x} more and reach the company median delegation share${c} to become ${s}`}${floorNote(g)}`;
|
|
132
213
|
} else {
|
|
133
|
-
text = ko ? `${x}명을 더 앞지르면 ${s}` : `pass ${x} more to become ${s}`;
|
|
214
|
+
text = `${ko ? `${x}명을 더 앞지르면 ${s}` : `pass ${x} more to become ${s}`}${floorNote(g)}`;
|
|
134
215
|
}
|
|
135
|
-
lines.push(` ${ko ? '다음 등급' : 'Next species'}: ${text}
|
|
136
|
-
} else if (st.idle === true || st.grade === 'chick') {
|
|
137
|
-
lines.push(ko ? ' 다음 등급: 이 기간에 지출이 생기면 순위에 오릅니다.' : ' Next species: spend in this period puts you in the standings.');
|
|
216
|
+
lines.push(` ${ko ? '다음 등급' : 'Next species'}: ${text}`);
|
|
138
217
|
} else if (!up) {
|
|
139
218
|
lines.push(ko ? ' 다음 등급: 도감에서 가장 높은 종입니다.' : ' Next species: the top species in the field guide.');
|
|
140
219
|
} else {
|
|
@@ -148,6 +227,67 @@ export function standingGuideLines(st, { lang = 'en', org = null, team = null }
|
|
|
148
227
|
return lines;
|
|
149
228
|
}
|
|
150
229
|
|
|
230
|
+
/**
|
|
231
|
+
* The short form for the statusline's team line: where the rank puts you and
|
|
232
|
+
* what the next species takes, as two or three phrases. The same facts as the
|
|
233
|
+
* block above, without the sentences.
|
|
234
|
+
* ['1위까지 2명', '다음 🐆 치타: 2명 더 (77%부터)']
|
|
235
|
+
* `emoji: false` keeps the species names bare (narrow and text modes).
|
|
236
|
+
*/
|
|
237
|
+
export function standingFeedbackShort(st, lang = 'en', { emoji = true } = {}) {
|
|
238
|
+
if (!st || typeof st !== 'object' || typeof st.grade !== 'string') return [];
|
|
239
|
+
const ko = lang === 'ko';
|
|
240
|
+
const label = (k) => speciesLabel(k, lang, { emoji }) || k;
|
|
241
|
+
const has = (v) => Number.isFinite(v);
|
|
242
|
+
const ranked = Number.isInteger(st.rank) && Number.isInteger(st.ranked) && st.rank >= 1 && st.ranked >= st.rank;
|
|
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
|
+
}
|
|
252
|
+
const out = [];
|
|
253
|
+
if (st.crown) out.push(ko ? `${emoji ? '👑 ' : ''}회사 1위` : `${emoji ? '👑 ' : ''}#1 in the company`);
|
|
254
|
+
else if (st.rank === 1 && st.ranked === 1) out.push(ko ? '혼자 순위에 있음' : 'alone in the standings');
|
|
255
|
+
else if (st.rank === 1) out.push(ko ? '회사 1위' : '#1 in the company');
|
|
256
|
+
else out.push(ko ? `1위까지 ${st.rank - 1}명` : `${st.rank - 1} to pass for #1`);
|
|
257
|
+
|
|
258
|
+
const sr = scorePctOf(st);
|
|
259
|
+
const next = nextOf(st, sr);
|
|
260
|
+
const up = nextGradeUp(st.grade);
|
|
261
|
+
const floor = (g) => (g && g.minSr >= 0 ? (ko ? `${floorPct(g)}%부터` : `${floorPct(g)}% and up`) : '');
|
|
262
|
+
if (next) {
|
|
263
|
+
const s = label(next.grade);
|
|
264
|
+
const g = GRADES.find((x) => x.key === next.grade);
|
|
265
|
+
const x = Math.max(1, Number(next.pass) || 0);
|
|
266
|
+
const c = has(st.medianDlg) ? pct(st.medianDlg) : (ko ? '회사 중앙값' : 'the company median');
|
|
267
|
+
const pts = pointsTo(g, sr);
|
|
268
|
+
if (pts !== null) {
|
|
269
|
+
// With the percentile: where you are and how many points more.
|
|
270
|
+
const now = pct(sr);
|
|
271
|
+
if (next.needDlg && !(Number(next.pass) > 0)) out.push(ko ? `지금 ${now}, 위임 비율 ${c} 이상이면 ${s}` : `now ${now}, delegation share ${c} or more for ${s}`);
|
|
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}`);
|
|
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})`);
|
|
274
|
+
} else if (next.needDlg && !(Number(next.pass) > 0)) {
|
|
275
|
+
out.push(ko ? `다음 ${s}: 위임 비율 ${c} 이상` : `next ${s}: delegation share ${c} or more`);
|
|
276
|
+
} else if (next.needDlg) {
|
|
277
|
+
out.push(ko ? `다음 ${s}: ${x}명 더, 위임 비율 ${c} 이상` : `next ${s}: ${x} more and delegation share ${c} or more`);
|
|
278
|
+
} else {
|
|
279
|
+
out.push(ko ? `다음 ${s}: ${x}명 더${floor(g) ? ` (${floor(g)})` : ''}` : `next ${s}: ${x} more${floor(g) ? ` (${floor(g)})` : ''}`);
|
|
280
|
+
}
|
|
281
|
+
} else if (idle) {
|
|
282
|
+
out.push(ko ? '지출이 생기면 순위에 오름' : 'spend to enter the standings');
|
|
283
|
+
} else if (!up) {
|
|
284
|
+
out.push(ko ? '도감 최상위' : 'top of the field guide');
|
|
285
|
+
} else {
|
|
286
|
+
out.push(ko ? `다음 ${label(up.key)} (${floor(up)})` : `next ${label(up.key)} (${floor(up)})`);
|
|
287
|
+
}
|
|
288
|
+
return out;
|
|
289
|
+
}
|
|
290
|
+
|
|
151
291
|
/**
|
|
152
292
|
* The field guide: every species by tier, best first, with the percentile each
|
|
153
293
|
* one starts at and a marker on the caller's own. Shared by the ranked and the
|
package/src/team-sync.js
CHANGED
|
@@ -159,6 +159,13 @@ export function readTeamChip({ dir = userDataDir() } = {}) {
|
|
|
159
159
|
? {
|
|
160
160
|
grade: st.grade, rank: Number.isFinite(st.rank) ? st.rank : null, ranked: Number.isFinite(st.ranked) ? st.ranked : null,
|
|
161
161
|
teamRank: Number.isFinite(st.teamRank) ? st.teamRank : null, teamRanked: Number.isFinite(st.teamRanked) ? st.teamRanked : null,
|
|
162
|
+
// What the team line says about moving up (src/team-standing.js standingFeedbackShort).
|
|
163
|
+
crown: !!st.crown,
|
|
164
|
+
next: st.next && typeof st.next === 'object' && typeof st.next.grade === 'string'
|
|
165
|
+
? { grade: st.next.grade, pass: Number.isFinite(st.next.pass) ? st.next.pass : 0, needDlg: !!st.next.needDlg }
|
|
166
|
+
: null,
|
|
167
|
+
idle: typeof st.idle === 'boolean' ? st.idle : null,
|
|
168
|
+
medianDlg: Number.isFinite(st.medianDlg) ? st.medianDlg : null,
|
|
162
169
|
fetchedAt: Number(st.fetchedAt) || 0,
|
|
163
170
|
}
|
|
164
171
|
: null,
|
|
@@ -291,7 +298,7 @@ export async function rpc(fn, params, {
|
|
|
291
298
|
* as rpc(). Errors carry the server's own message. The access token only ever
|
|
292
299
|
* lives in memory: it is never written to disk or printed.
|
|
293
300
|
*/
|
|
294
|
-
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' } = {}) {
|
|
295
302
|
trustSystemCA();
|
|
296
303
|
const ctl = new AbortController();
|
|
297
304
|
const timer = setTimeout(() => ctl.abort(), timeoutMs);
|
|
@@ -299,7 +306,7 @@ async function apiJson(path, { body, accessToken, label, fetch = globalThis.fetc
|
|
|
299
306
|
const headers = { apikey: key, 'Content-Type': 'application/json' };
|
|
300
307
|
if (accessToken) headers.Authorization = `Bearer ${accessToken}`;
|
|
301
308
|
if (prefer) headers.Prefer = prefer;
|
|
302
|
-
const res = await fetch(`${url}${path}`, { method
|
|
309
|
+
const res = await fetch(`${url}${path}`, { method, headers, body: method === 'GET' ? undefined : JSON.stringify(body || {}), signal: ctl.signal });
|
|
303
310
|
let data = null;
|
|
304
311
|
try { data = await res.json(); } catch { /* empty or non-JSON body */ }
|
|
305
312
|
if (!res.ok) {
|
|
@@ -315,16 +322,41 @@ async function apiJson(path, { body, accessToken, label, fetch = globalThis.fetc
|
|
|
315
322
|
}
|
|
316
323
|
}
|
|
317
324
|
|
|
318
|
-
/**
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
/** 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
|
+
*/
|
|
324
330
|
export async function verifySignInCode({ email, code, fetch } = {}) {
|
|
325
331
|
const r = await apiJson('/auth/v1/verify', { body: { type: 'email', email, token: code }, label: 'verify', fetch });
|
|
326
332
|
if (!r || !r.access_token || !r.user || !r.user.id) throw new Error('verify: no session returned');
|
|
327
|
-
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 };
|
|
328
360
|
}
|
|
329
361
|
|
|
330
362
|
/**
|