@hanzo/sources 0.0.0-stage → 0.1.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/LICENSE-APACHE +205 -0
- package/LICENSE-MIT +21 -0
- package/dist/accounts.d.ts +17 -0
- package/dist/accounts.js +37 -0
- package/dist/client.d.ts +46 -0
- package/dist/client.js +85 -0
- package/dist/data.d.ts +23 -0
- package/dist/data.js +33 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +9 -0
- package/dist/logic.d.ts +50 -0
- package/dist/logic.js +167 -0
- package/dist/mount.d.ts +29 -0
- package/dist/mount.js +37 -0
- package/dist/picker.d.ts +14 -0
- package/dist/picker.js +27 -0
- package/dist/types.d.ts +104 -0
- package/dist/types.js +6 -0
- package/dist/view.d.ts +34 -0
- package/dist/view.js +118 -0
- package/package.json +61 -3
- package/README.md +0 -3
package/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and
|
|
10
|
+
distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
|
13
|
+
owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities
|
|
16
|
+
that control, are controlled by, or are under common control with that entity.
|
|
17
|
+
For the purposes of this definition, "control" means (i) the power, direct or
|
|
18
|
+
indirect, to cause the direction or management of such entity, whether by
|
|
19
|
+
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
20
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
21
|
+
|
|
22
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
|
23
|
+
permissions granted by this License.
|
|
24
|
+
|
|
25
|
+
"Source" form shall mean the preferred form for making modifications, including
|
|
26
|
+
but not limited to software source code, documentation source, and configuration
|
|
27
|
+
files.
|
|
28
|
+
|
|
29
|
+
"Object" form shall mean any form resulting from mechanical transformation or
|
|
30
|
+
translation of a Source form, including but not limited to compiled object code,
|
|
31
|
+
generated documentation, and conversions to other media types.
|
|
32
|
+
|
|
33
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made
|
|
34
|
+
available under the License, as indicated by a copyright notice that is included
|
|
35
|
+
in or attached to the work (an example is provided in the Appendix below).
|
|
36
|
+
|
|
37
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
|
38
|
+
is based on (or derived from) the Work and for which the editorial revisions,
|
|
39
|
+
annotations, elaborations, or other modifications represent, as a whole, an
|
|
40
|
+
original work of authorship. For the purposes of this License, Derivative Works
|
|
41
|
+
shall not include works that remain separable from, or merely link (or bind by
|
|
42
|
+
name) to the interfaces of, the Work and Derivative Works thereof.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the original version
|
|
45
|
+
of the Work and any modifications or additions to that Work or Derivative Works
|
|
46
|
+
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
|
47
|
+
by the copyright owner or by an individual or Legal Entity authorized to submit
|
|
48
|
+
on behalf of the copyright owner. For the purposes of this definition,
|
|
49
|
+
"submitted" means any form of electronic, verbal, or written communication sent
|
|
50
|
+
to the Licensor or its representatives, including but not limited to
|
|
51
|
+
communication on electronic mailing lists, source code control systems, and
|
|
52
|
+
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
|
53
|
+
the purpose of discussing and improving the Work, but excluding communication
|
|
54
|
+
that is conspicuously marked or otherwise designated in writing by the copyright
|
|
55
|
+
owner as "Not a Contribution."
|
|
56
|
+
|
|
57
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
|
58
|
+
of whom a Contribution has been received by Licensor and subsequently
|
|
59
|
+
incorporated within the Work.
|
|
60
|
+
|
|
61
|
+
2. Grant of Copyright License.
|
|
62
|
+
|
|
63
|
+
Subject to the terms and conditions of this License, each Contributor hereby
|
|
64
|
+
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
|
65
|
+
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
|
66
|
+
publicly display, publicly perform, sublicense, and distribute the Work and such
|
|
67
|
+
Derivative Works in Source or Object form.
|
|
68
|
+
|
|
69
|
+
3. Grant of Patent License.
|
|
70
|
+
|
|
71
|
+
Subject to the terms and conditions of this License, each Contributor hereby
|
|
72
|
+
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
|
73
|
+
irrevocable (except as stated in this section) patent license to make, have
|
|
74
|
+
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
|
75
|
+
such license applies only to those patent claims licensable by such Contributor
|
|
76
|
+
that are necessarily infringed by their Contribution(s) alone or by combination
|
|
77
|
+
of their Contribution(s) with the Work to which such Contribution(s) was
|
|
78
|
+
submitted. If You institute patent litigation against any entity (including a
|
|
79
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
|
80
|
+
Contribution incorporated within the Work constitutes direct or contributory
|
|
81
|
+
patent infringement, then any patent licenses granted to You under this License
|
|
82
|
+
for that Work shall terminate as of the date such litigation is filed.
|
|
83
|
+
|
|
84
|
+
4. Redistribution.
|
|
85
|
+
|
|
86
|
+
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
|
87
|
+
in any medium, with or without modifications, and in Source or Object form,
|
|
88
|
+
provided that You meet the following conditions:
|
|
89
|
+
|
|
90
|
+
You must give any other recipients of the Work or Derivative Works a copy of
|
|
91
|
+
this License; and
|
|
92
|
+
You must cause any modified files to carry prominent notices stating that You
|
|
93
|
+
changed the files; and
|
|
94
|
+
You must retain, in the Source form of any Derivative Works that You distribute,
|
|
95
|
+
all copyright, patent, trademark, and attribution notices from the Source form
|
|
96
|
+
of the Work, excluding those notices that do not pertain to any part of the
|
|
97
|
+
Derivative Works; and
|
|
98
|
+
If the Work includes a "NOTICE" text file as part of its distribution, then any
|
|
99
|
+
Derivative Works that You distribute must include a readable copy of the
|
|
100
|
+
attribution notices contained within such NOTICE file, excluding those notices
|
|
101
|
+
that do not pertain to any part of the Derivative Works, in at least one of the
|
|
102
|
+
following places: within a NOTICE text file distributed as part of the
|
|
103
|
+
Derivative Works; within the Source form or documentation, if provided along
|
|
104
|
+
with the Derivative Works; or, within a display generated by the Derivative
|
|
105
|
+
Works, if and wherever such third-party notices normally appear. The contents of
|
|
106
|
+
the NOTICE file are for informational purposes only and do not modify the
|
|
107
|
+
License. You may add Your own attribution notices within Derivative Works that
|
|
108
|
+
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
|
109
|
+
provided that such additional attribution notices cannot be construed as
|
|
110
|
+
modifying the License.
|
|
111
|
+
You may add Your own copyright statement to Your modifications and may provide
|
|
112
|
+
additional or different license terms and conditions for use, reproduction, or
|
|
113
|
+
distribution of Your modifications, or for any such Derivative Works as a whole,
|
|
114
|
+
provided Your use, reproduction, and distribution of the Work otherwise complies
|
|
115
|
+
with the conditions stated in this License.
|
|
116
|
+
|
|
117
|
+
5. Submission of Contributions.
|
|
118
|
+
|
|
119
|
+
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
|
120
|
+
for inclusion in the Work by You to the Licensor shall be under the terms and
|
|
121
|
+
conditions of this License, without any additional terms or conditions.
|
|
122
|
+
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
|
123
|
+
any separate license agreement you may have executed with Licensor regarding
|
|
124
|
+
such Contributions.
|
|
125
|
+
|
|
126
|
+
6. Trademarks.
|
|
127
|
+
|
|
128
|
+
This License does not grant permission to use the trade names, trademarks,
|
|
129
|
+
service marks, or product names of the Licensor, except as required for
|
|
130
|
+
reasonable and customary use in describing the origin of the Work and
|
|
131
|
+
reproducing the content of the NOTICE file.
|
|
132
|
+
|
|
133
|
+
7. Disclaimer of Warranty.
|
|
134
|
+
|
|
135
|
+
Unless required by applicable law or agreed to in writing, Licensor provides the
|
|
136
|
+
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
137
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
|
138
|
+
including, without limitation, any warranties or conditions of TITLE,
|
|
139
|
+
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
|
140
|
+
solely responsible for determining the appropriateness of using or
|
|
141
|
+
redistributing the Work and assume any risks associated with Your exercise of
|
|
142
|
+
permissions under this License.
|
|
143
|
+
|
|
144
|
+
8. Limitation of Liability.
|
|
145
|
+
|
|
146
|
+
In no event and under no legal theory, whether in tort (including negligence),
|
|
147
|
+
contract, or otherwise, unless required by applicable law (such as deliberate
|
|
148
|
+
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
|
149
|
+
liable to You for damages, including any direct, indirect, special, incidental,
|
|
150
|
+
or consequential damages of any character arising as a result of this License or
|
|
151
|
+
out of the use or inability to use the Work (including but not limited to
|
|
152
|
+
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
|
153
|
+
any and all other commercial damages or losses), even if such Contributor has
|
|
154
|
+
been advised of the possibility of such damages.
|
|
155
|
+
|
|
156
|
+
9. Accepting Warranty or Additional Liability.
|
|
157
|
+
|
|
158
|
+
While redistributing the Work or Derivative Works thereof, You may choose to
|
|
159
|
+
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
|
160
|
+
other liability obligations and/or rights consistent with this License. However,
|
|
161
|
+
in accepting such obligations, You may act only on Your own behalf and on Your
|
|
162
|
+
sole responsibility, not on behalf of any other Contributor, and only if You
|
|
163
|
+
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
|
164
|
+
incurred by, or claims asserted against, such Contributor by reason of your
|
|
165
|
+
accepting any such warranty or additional liability.
|
|
166
|
+
|
|
167
|
+
END OF TERMS AND CONDITIONS
|
|
168
|
+
|
|
169
|
+
APPENDIX: How to apply the Apache License to your work
|
|
170
|
+
|
|
171
|
+
To apply the Apache License to your work, attach the following boilerplate
|
|
172
|
+
notice, with the fields enclosed by brackets "[]" replaced with your own
|
|
173
|
+
identifying information. (Don't include the brackets!) The text should be
|
|
174
|
+
enclosed in the appropriate comment syntax for the file format. We also
|
|
175
|
+
recommend that a file or class name and description of purpose be included on
|
|
176
|
+
the same "printed page" as the copyright notice for easier identification within
|
|
177
|
+
third-party archives.
|
|
178
|
+
|
|
179
|
+
Copyright [yyyy] [name of copyright owner]
|
|
180
|
+
|
|
181
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
182
|
+
you may not use this file except in compliance with the License.
|
|
183
|
+
You may obtain a copy of the License at
|
|
184
|
+
|
|
185
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
186
|
+
|
|
187
|
+
Unless required by applicable law or agreed to in writing, software
|
|
188
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
189
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
190
|
+
See the License for the specific language governing permissions and
|
|
191
|
+
limitations under the License.
|
|
192
|
+
|
|
193
|
+
Copyright 2026 Hanzo AI, Inc
|
|
194
|
+
|
|
195
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
196
|
+
you may not use this file except in compliance with the License.
|
|
197
|
+
You may obtain a copy of the License at
|
|
198
|
+
|
|
199
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
200
|
+
|
|
201
|
+
Unless required by applicable law or agreed to in writing, software
|
|
202
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
203
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
204
|
+
See the License for the specific language governing permissions and
|
|
205
|
+
limitations under the License.
|
package/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Hanzo AI, Inc
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Account, Choice, Source, Surface, Usage } from './types.js';
|
|
2
|
+
export interface Picked {
|
|
3
|
+
/** The account chosen; null for the Hanzo cell. */
|
|
4
|
+
account: Account | null;
|
|
5
|
+
/** `/v1/dev`'s execution for it; null for a login on this very device, which the host runs itself. */
|
|
6
|
+
choice: Choice | null;
|
|
7
|
+
}
|
|
8
|
+
export declare function Accounts({ accounts, sources, usage, surface, deviceId, now, selected, onPick, }: {
|
|
9
|
+
accounts: Account[];
|
|
10
|
+
sources: Source[];
|
|
11
|
+
usage: Usage;
|
|
12
|
+
surface: Surface;
|
|
13
|
+
deviceId?: string;
|
|
14
|
+
now: Date;
|
|
15
|
+
selected?: Choice | null;
|
|
16
|
+
onPick?: (pick: Picked) => void;
|
|
17
|
+
}): import("react").JSX.Element;
|
package/dist/accounts.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
// The account rows both the view and the picker draw: every login a device
|
|
4
|
+
// detected and every key in KMS, each `on <device name>` with its plan, usage
|
|
5
|
+
// windows, credits and state; the ones this surface cannot use are greyed and
|
|
6
|
+
// say why on the row.
|
|
7
|
+
import { useI18n } from '@hanzo/i18n/react';
|
|
8
|
+
import { Badge, Button, Progress, Text, XStack, YStack } from '@hanzo/ui';
|
|
9
|
+
import { ago, availability, choose, level, listed, money, named, percent, resets, snapshotOf } from './logic.js';
|
|
10
|
+
const EDGE = 'var(--border-strong)';
|
|
11
|
+
export function Accounts({ accounts, sources, usage, surface, deviceId, now, selected, onPick, }) {
|
|
12
|
+
const { t } = useI18n();
|
|
13
|
+
return (_jsxs(YStack, { gap: "$2", "data-slot": "accounts", children: [onPick ? (_jsxs(XStack, { gap: "$2.5", items: "center", justify: "space-between", flexWrap: "wrap", borderWidth: 1, borderColor: EDGE, rounded: "$3", p: "$3.5", "data-slot": "account", "data-id": "cell", "data-usable": "true", "data-selected": !selected || selected.via === 'cell' ? 'true' : 'false', children: [_jsxs(YStack, { flex: 1, minW: 160, children: [_jsx(Text, { fontSize: "$3", fontWeight: "600", color: "$ink", children: t('Hanzo cell') }), _jsx(Text, { fontSize: "$2", color: "$aside", children: t('Zen models, no account needed') })] }), _jsx(Button, { size: "sm", variant: "outline", onPress: () => onPick({ account: null, choice: { via: 'cell' } }), children: t('Use') })] })) : null, listed(accounts, sources, surface, deviceId).map((a) => (_jsx(Row, { account: a, sources: sources, usage: usage, surface: surface, deviceId: deviceId, now: now, selected: selected, onPick: onPick }, a.id)))] }));
|
|
14
|
+
}
|
|
15
|
+
function Row({ account: a, sources, usage, surface, deviceId, now, selected, onPick, }) {
|
|
16
|
+
const { t, locale } = useI18n();
|
|
17
|
+
const source = sources.find((s) => s.id === a.sourceId);
|
|
18
|
+
const can = availability(a, source, surface, deviceId, t);
|
|
19
|
+
const snap = snapshotOf(usage, a);
|
|
20
|
+
const choice = choose(a, source, surface, deviceId);
|
|
21
|
+
const here = Boolean(deviceId && source?.id === deviceId && can.usable);
|
|
22
|
+
const on = a.kind === 'key' ? t('API key in Hanzo KMS') : t('on {device}', { device: a.sourceId ? named(sources, a.sourceId) : t('this device') });
|
|
23
|
+
const chosen = selected && choice && selected.via === choice.via && (selected.via === 'key' ? selected.account === a.id : selected.via === 'desktop' && selected.source === choice.source && selected.instance === choice.instance);
|
|
24
|
+
const c = snap?.credits;
|
|
25
|
+
return (_jsxs(YStack, { gap: "$1.5", borderWidth: 1, borderColor: EDGE, rounded: "$3", p: "$3.5", opacity: can.usable ? 1 : 0.6, "data-slot": "account", "data-id": a.id, "data-usable": can.usable ? 'true' : 'false', "data-selected": chosen ? 'true' : 'false', children: [_jsxs(XStack, { gap: "$2.5", items: "center", justify: "space-between", flexWrap: "wrap", children: [_jsxs(YStack, { flex: 1, minW: 160, children: [_jsxs(Text, { fontSize: "$3", fontWeight: "600", color: "$ink", children: [a.provider, a.plan ? ` · ${a.plan}` : '', a.kind === 'key' && a.label ? ` · ${a.label}` : ''] }), _jsxs(Text, { fontSize: "$2", color: "$aside", "data-slot": "account-on", children: [on, a.state ? ` · ${a.state.replace(/_/g, ' ')}` : '', a.kind === 'key' && a.fingerprint ? ` · …${a.fingerprint.slice(-4)}` : '', source && source.state !== 'online' && source.state !== 'revoked' && source.last_seen ? ` · ${t('last seen {when} ago', { when: ago(source.last_seen, now, t) })}` : ''] })] }), onPick && can.usable ? (_jsx(Button, { size: "sm", variant: chosen ? 'primary' : 'outline', "aria-pressed": Boolean(chosen), onPress: () => onPick({ account: a, choice }), children: here ? t('Use here') : can.reason ?? t('Use') })) : null, !onPick && a.kind === 'login' ? _jsx(Badge, { variant: "secondary", size: "sm", children: a.shared ? t('Shared with my other devices') : t('On this device only') }) : null, !onPick && a.kind === 'key' ? _jsx(Badge, { variant: "secondary", size: "sm", children: t('API key') }) : null] }), !can.usable ? (_jsx(Text, { fontSize: "$2", color: "$soft", "data-slot": "reason", children: can.reason })) : null, snap?.windows.map((w) => {
|
|
26
|
+
const used = percent(w.usedPercent);
|
|
27
|
+
const lv = level(used);
|
|
28
|
+
const when = resets(w.resetsAt, now, t);
|
|
29
|
+
return (_jsxs(YStack, { gap: "$1", "data-slot": "window", children: [_jsxs(XStack, { justify: "space-between", gap: "$2", children: [_jsx(Text, { fontSize: "$2", color: "$ink", children: w.label }), _jsxs(Text, { fontSize: "$2", color: "$soft", fontVariant: ['tabular-nums'], children: [t('{percent}% used', { percent: used }), when ? ` · ${t('resets {when}', { when })}` : ''] })] }), _jsx(Progress, { value: used, size: "sm", indicatorColor: lv === 'high' ? 'var(--state-error)' : lv === 'warn' ? 'var(--chrome-dot-yellow)' : 'var(--foreground)', "aria-label": t('{label}: {percent}% used', { label: w.label, percent: used }) })] }, `${w.kind}/${w.label}`));
|
|
30
|
+
}), snap?.error ? _jsx(Text, { fontSize: "$2", color: "var(--state-error)", children: t('The last refresh failed: {code}', { code: snap.error }) }) : null, c ? (_jsx(Text, { fontSize: "$2", color: "$soft", fontVariant: ['tabular-nums'], "data-slot": "credits", children: [
|
|
31
|
+
c.balance !== undefined ? t('Balance {amount}', { amount: money(c.balance, c.currency, locale) }) : '',
|
|
32
|
+
c.spent !== undefined ? t('Spent {amount}', { amount: money(c.spent, c.currency, locale) }) : '',
|
|
33
|
+
c.limit !== undefined ? t('Limit {amount}', { amount: money(c.limit, c.currency, locale) }) : '',
|
|
34
|
+
]
|
|
35
|
+
.filter(Boolean)
|
|
36
|
+
.join(' · ') })) : null] }));
|
|
37
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The cloud client: `GET /v1/sources`, `GET /v1/sources/usage`,
|
|
3
|
+
* `GET|POST|DELETE /v1/sources/accounts`, `DELETE /v1/sources/{id}`. The host
|
|
4
|
+
* names the gateway and holds the IAM token; nothing here signs anyone in.
|
|
5
|
+
*/
|
|
6
|
+
import type { Account, By, Range, Source, Usage } from './types.js';
|
|
7
|
+
export interface ClientOptions {
|
|
8
|
+
/** The gateway's origin, e.g. https://api.hanzo.ai. */
|
|
9
|
+
apiBase: string;
|
|
10
|
+
/** The IAM bearer, or a function that reads it when a request is made. */
|
|
11
|
+
token: string | null | (() => string | null);
|
|
12
|
+
/** The organization the person works in, sent as X-Org-Id. */
|
|
13
|
+
org?: string | null | (() => string | null);
|
|
14
|
+
fetch?: typeof fetch;
|
|
15
|
+
}
|
|
16
|
+
/** A read the cloud refused or could not answer. `status` is 0 for a network failure. */
|
|
17
|
+
export declare class SourcesError extends Error {
|
|
18
|
+
status: number;
|
|
19
|
+
constructor(message: string, status: number);
|
|
20
|
+
}
|
|
21
|
+
/** The window a range reads: the last `days` days up to `now`. */
|
|
22
|
+
export declare function span(days: number, now?: Date): {
|
|
23
|
+
from: string;
|
|
24
|
+
to: string;
|
|
25
|
+
};
|
|
26
|
+
export declare function createClient(opts: ClientOptions): {
|
|
27
|
+
/** Whether a token is held: the view asks before it reads. */
|
|
28
|
+
signedIn: () => boolean;
|
|
29
|
+
/** The caller's own sources, newest heartbeat first. */
|
|
30
|
+
sources(signal?: AbortSignal): Promise<Source[]>;
|
|
31
|
+
/** Revoke: the cloud drops its routes and answers 410 to the next heartbeat. */
|
|
32
|
+
revoke(id: string): Promise<void>;
|
|
33
|
+
/** Every login the caller's sources detected and every key in KMS. A missing class list is `local`. */
|
|
34
|
+
accounts(signal?: AbortSignal): Promise<Account[]>;
|
|
35
|
+
/** Seal a key into KMS. The value is sent once and never returned. */
|
|
36
|
+
addKey(key: {
|
|
37
|
+
provider: string;
|
|
38
|
+
label: string;
|
|
39
|
+
value: string;
|
|
40
|
+
}): Promise<Account>;
|
|
41
|
+
/** Delete a key (its KMS secret first, then the row). */
|
|
42
|
+
removeAccount(id: string): Promise<void>;
|
|
43
|
+
/** Totals by `by`, and the latest snapshot per (source, provider). Counts that are not numbers read as 0. */
|
|
44
|
+
usage(by: By, range: Range, now?: Date, signal?: AbortSignal): Promise<Usage>;
|
|
45
|
+
};
|
|
46
|
+
export type Client = ReturnType<typeof createClient>;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** A read the cloud refused or could not answer. `status` is 0 for a network failure. */
|
|
2
|
+
export class SourcesError extends Error {
|
|
3
|
+
status;
|
|
4
|
+
constructor(message, status) {
|
|
5
|
+
super(message);
|
|
6
|
+
this.status = status;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
|
|
10
|
+
const read = (v) => (typeof v === 'function' ? v() : v);
|
|
11
|
+
/** The window a range reads: the last `days` days up to `now`. */
|
|
12
|
+
export function span(days, now = new Date()) {
|
|
13
|
+
return { from: new Date(now.getTime() - days * 86_400_000).toISOString(), to: now.toISOString() };
|
|
14
|
+
}
|
|
15
|
+
export function createClient(opts) {
|
|
16
|
+
const base = opts.apiBase.replace(/\/+$/, '');
|
|
17
|
+
const get = opts.fetch ?? ((...a) => fetch(...a));
|
|
18
|
+
async function call(path, init = {}) {
|
|
19
|
+
const headers = { ...init.headers };
|
|
20
|
+
const token = read(opts.token);
|
|
21
|
+
if (token)
|
|
22
|
+
headers.Authorization = `Bearer ${token}`;
|
|
23
|
+
const org = read(opts.org ?? null);
|
|
24
|
+
if (org)
|
|
25
|
+
headers['X-Org-Id'] = org;
|
|
26
|
+
let res;
|
|
27
|
+
try {
|
|
28
|
+
res = await get(`${base}${path}`, { ...init, headers });
|
|
29
|
+
}
|
|
30
|
+
catch (e) {
|
|
31
|
+
if (e.name === 'AbortError')
|
|
32
|
+
throw e;
|
|
33
|
+
throw new SourcesError('Could not reach Hanzo.', 0);
|
|
34
|
+
}
|
|
35
|
+
if (!res.ok)
|
|
36
|
+
throw new SourcesError(`Hanzo answered ${res.status}.`, res.status);
|
|
37
|
+
return res.status === 204 ? undefined : (await res.json());
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
/** Whether a token is held: the view asks before it reads. */
|
|
41
|
+
signedIn: () => Boolean(read(opts.token)),
|
|
42
|
+
/** The caller's own sources, newest heartbeat first. */
|
|
43
|
+
async sources(signal) {
|
|
44
|
+
const body = await call('/v1/sources', { signal });
|
|
45
|
+
return (body.sources ?? []).map((s) => ({ ...s, providers: s.providers ?? [] }));
|
|
46
|
+
},
|
|
47
|
+
/** Revoke: the cloud drops its routes and answers 410 to the next heartbeat. */
|
|
48
|
+
async revoke(id) {
|
|
49
|
+
await call(`/v1/sources/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
|
50
|
+
},
|
|
51
|
+
/** Every login the caller's sources detected and every key in KMS. A missing class list is `local`. */
|
|
52
|
+
async accounts(signal) {
|
|
53
|
+
const body = await call('/v1/sources/accounts', { signal });
|
|
54
|
+
return (body.accounts ?? []).map((a) => ({ ...a, classes: a.classes?.length ? a.classes : ['local'] }));
|
|
55
|
+
},
|
|
56
|
+
/** Seal a key into KMS. The value is sent once and never returned. */
|
|
57
|
+
async addKey(key) {
|
|
58
|
+
return call('/v1/sources/accounts', {
|
|
59
|
+
method: 'POST',
|
|
60
|
+
headers: { 'Content-Type': 'application/json' },
|
|
61
|
+
body: JSON.stringify({ ...key, kind: 'key' }),
|
|
62
|
+
});
|
|
63
|
+
},
|
|
64
|
+
/** Delete a key (its KMS secret first, then the row). */
|
|
65
|
+
async removeAccount(id) {
|
|
66
|
+
await call(`/v1/sources/accounts/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
|
67
|
+
},
|
|
68
|
+
/** Totals by `by`, and the latest snapshot per (source, provider). Counts that are not numbers read as 0. */
|
|
69
|
+
async usage(by, range, now = new Date(), signal) {
|
|
70
|
+
const { from, to } = span(range, now);
|
|
71
|
+
const q = new URLSearchParams({ by, from, to });
|
|
72
|
+
const body = await call(`/v1/sources/usage?${q}`, { signal });
|
|
73
|
+
return {
|
|
74
|
+
rows: (body.rows ?? []).map((r) => ({
|
|
75
|
+
key: String(r.key),
|
|
76
|
+
inputTokens: num(r.inputTokens),
|
|
77
|
+
outputTokens: num(r.outputTokens),
|
|
78
|
+
cacheTokens: num(r.cacheTokens),
|
|
79
|
+
costUsd: num(r.costUsd),
|
|
80
|
+
})),
|
|
81
|
+
snapshots: (body.snapshots ?? []).map((s) => ({ ...s, windows: s.windows ?? [] })),
|
|
82
|
+
};
|
|
83
|
+
},
|
|
84
|
+
};
|
|
85
|
+
}
|
package/dist/data.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { Client } from './client.js';
|
|
2
|
+
import type { Account, Range, Source, Usage } from './types.js';
|
|
3
|
+
export interface Loaded {
|
|
4
|
+
sources: Source[];
|
|
5
|
+
accounts: Account[];
|
|
6
|
+
provider: Usage;
|
|
7
|
+
model: Usage;
|
|
8
|
+
source: Usage;
|
|
9
|
+
at: Date;
|
|
10
|
+
}
|
|
11
|
+
export type Read = {
|
|
12
|
+
is: 'loading';
|
|
13
|
+
} | {
|
|
14
|
+
is: 'error';
|
|
15
|
+
status: number;
|
|
16
|
+
} | ({
|
|
17
|
+
is: 'ready';
|
|
18
|
+
} & Loaded);
|
|
19
|
+
/**
|
|
20
|
+
* Reads the registry, the accounts and the totals, again when `range` or `bump`
|
|
21
|
+
* change, and not at all while no token is held. `all: false` is the picker's read: no per-model or per-source totals.
|
|
22
|
+
*/
|
|
23
|
+
export declare function useRead(client: Client, range: Range, bump: number, all?: boolean): Read;
|
package/dist/data.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { useEffect, useState } from 'react';
|
|
3
|
+
const NONE = { rows: [], snapshots: [] };
|
|
4
|
+
/**
|
|
5
|
+
* Reads the registry, the accounts and the totals, again when `range` or `bump`
|
|
6
|
+
* change, and not at all while no token is held. `all: false` is the picker's read: no per-model or per-source totals.
|
|
7
|
+
*/
|
|
8
|
+
export function useRead(client, range, bump, all = true) {
|
|
9
|
+
const enabled = client.signedIn();
|
|
10
|
+
const [read, set] = useState({ is: 'loading' });
|
|
11
|
+
useEffect(() => {
|
|
12
|
+
if (!enabled)
|
|
13
|
+
return;
|
|
14
|
+
const abort = new AbortController();
|
|
15
|
+
const now = new Date();
|
|
16
|
+
set({ is: 'loading' });
|
|
17
|
+
const s = abort.signal;
|
|
18
|
+
Promise.all([
|
|
19
|
+
client.sources(s),
|
|
20
|
+
client.accounts(s),
|
|
21
|
+
client.usage('provider', range, now, s),
|
|
22
|
+
all ? client.usage('model', range, now, s) : NONE,
|
|
23
|
+
all ? client.usage('source', range, now, s) : NONE,
|
|
24
|
+
])
|
|
25
|
+
.then(([sources, accounts, provider, model, source]) => set({ is: 'ready', sources, accounts, provider, model, source, at: now }))
|
|
26
|
+
.catch((e) => {
|
|
27
|
+
if (e.name !== 'AbortError')
|
|
28
|
+
set({ is: 'error', status: e.status ?? 0 });
|
|
29
|
+
});
|
|
30
|
+
return () => abort.abort();
|
|
31
|
+
}, [client, range, bump, all, enabled]);
|
|
32
|
+
return read;
|
|
33
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// @hanzo/sources: the one view of every linked desktop and browser, the account
|
|
2
|
+
// picker, the cloud client and the availability rule (HIP-1350). This root is
|
|
3
|
+
// pure and loads in plain Node. The components are subpaths:
|
|
4
|
+
// '@hanzo/sources/view' SourcesView
|
|
5
|
+
// '@hanzo/sources/picker' AccountPicker
|
|
6
|
+
// '@hanzo/sources/mount' mountSources(element, options), for a host without React
|
|
7
|
+
export * from './types.js';
|
|
8
|
+
export * from './client.js';
|
|
9
|
+
export * from './logic.js';
|
package/dist/logic.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Aggregation, formatting and the availability rule (HIP-1350): pure, no React, no fetch. */
|
|
2
|
+
import { type Say } from '@hanzo/i18n';
|
|
3
|
+
import type { Account, Availability, Choice, Row, Snapshot, Source, Surface, Usage } from './types.js';
|
|
4
|
+
/** Input, output and cache tokens together. */
|
|
5
|
+
export declare const tokens: (r: Pick<Row, 'inputTokens' | 'outputTokens' | 'cacheTokens'>) => number;
|
|
6
|
+
/** The sum of rows: what a heading over them says. */
|
|
7
|
+
export declare function total(rows: Row[]): Row;
|
|
8
|
+
/** Rows by tokens, heaviest first; equal weight keeps the key's order so a redraw never shuffles. */
|
|
9
|
+
export declare const heaviest: (rows: Row[]) => Row[];
|
|
10
|
+
/** 950, 1.2K, 3.4M, 1.1B: what a count looks like in a column. */
|
|
11
|
+
export declare function compact(n: number): string;
|
|
12
|
+
/** Dollars in the reader's locale; cents under $100, whole dollars above. */
|
|
13
|
+
export declare function dollars(n: number, locale?: string): string;
|
|
14
|
+
/** An amount in the currency a provider reported; a code Intl does not know is printed as it came. */
|
|
15
|
+
export declare function money(n: number, currency: string, locale?: string): string;
|
|
16
|
+
/** A used share clamped to a bar: 0..100, whole numbers. */
|
|
17
|
+
export declare const percent: (n: number) => number;
|
|
18
|
+
/** Where a limit sits: `high` from 90%, `warn` from 75%. The view colours by it. */
|
|
19
|
+
export declare const level: (used: number) => 'ok' | 'warn' | 'high';
|
|
20
|
+
/** When a window resets, relative: `in 3h`, `in 2d`, or '' when unknown or past. */
|
|
21
|
+
export declare function resets(at: string | undefined, now?: Date, t?: Say): string;
|
|
22
|
+
/** How long ago: `now`, `12m`, `3h`, `2d`, `5w`, `4mo`, `2y`. '' for an instant that is not one. */
|
|
23
|
+
export declare function ago(at: string, now?: Date, t?: Say): string;
|
|
24
|
+
/** Sources as a list reads them: online first, then by the latest heartbeat; revoked last. */
|
|
25
|
+
export declare function ordered(sources: Source[]): Source[];
|
|
26
|
+
/** A provider's latest snapshots, one per source that reported it, freshest first. */
|
|
27
|
+
export declare function snapshotsFor(usage: Usage, provider: string): Snapshot[];
|
|
28
|
+
/** The snapshot an account reads its windows and credits from: its own source's, for its own provider. */
|
|
29
|
+
export declare const snapshotOf: (usage: Usage, a: Pick<Account, 'provider' | 'sourceId'>) => Snapshot | undefined;
|
|
30
|
+
/** Every provider named by a total or a snapshot, in the order the totals weigh them. */
|
|
31
|
+
export declare function providers(usage: Usage): string[];
|
|
32
|
+
/** A source's name from its id, for a heading; the id when it was revoked and unlisted. */
|
|
33
|
+
export declare const named: (sources: Source[], id: string) => string;
|
|
34
|
+
/**
|
|
35
|
+
* Accounts as a picker lists them: those usable here first, then by provider and
|
|
36
|
+
* label, so a redraw never shuffles. Greyed accounts stay in view with their reason.
|
|
37
|
+
*/
|
|
38
|
+
export declare function listed(accounts: Account[], sources: Source[], surface: Surface, deviceId?: string): Account[];
|
|
39
|
+
/**
|
|
40
|
+
* Whether `account` can run a session on `surface`, and why not: one pure
|
|
41
|
+
* function of the account, its source, the surface and the account's classes
|
|
42
|
+
* from cloud (HIP-1350, "One view, one picker, four surfaces"). `deviceId` is the
|
|
43
|
+
* source id of the device the surface runs on, when it is a linked source.
|
|
44
|
+
* The reasons are the table's one-line strings, `<device>` filled in.
|
|
45
|
+
*/
|
|
46
|
+
export declare function availability(account: Account, source: Source | undefined, surface: Surface, deviceId?: string, t?: Say): Availability;
|
|
47
|
+
/** What choosing an account returns, or null when it is not usable here. */
|
|
48
|
+
export declare function choose(account: Account, source: Source | undefined, surface: Surface, deviceId?: string): Choice | null;
|
|
49
|
+
/** The default: a cloud cell on Hanzo's own models, which needs no account. */
|
|
50
|
+
export declare const CELL: Choice;
|
package/dist/logic.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/** Aggregation, formatting and the availability rule (HIP-1350): pure, no React, no fetch. */
|
|
2
|
+
import { english } from '@hanzo/i18n';
|
|
3
|
+
/** Input, output and cache tokens together. */
|
|
4
|
+
export const tokens = (r) => r.inputTokens + r.outputTokens + r.cacheTokens;
|
|
5
|
+
/** The sum of rows: what a heading over them says. */
|
|
6
|
+
export function total(rows) {
|
|
7
|
+
return rows.reduce((a, r) => ({
|
|
8
|
+
key: 'total',
|
|
9
|
+
inputTokens: a.inputTokens + r.inputTokens,
|
|
10
|
+
outputTokens: a.outputTokens + r.outputTokens,
|
|
11
|
+
cacheTokens: a.cacheTokens + r.cacheTokens,
|
|
12
|
+
costUsd: a.costUsd + r.costUsd,
|
|
13
|
+
}), { key: 'total', inputTokens: 0, outputTokens: 0, cacheTokens: 0, costUsd: 0 });
|
|
14
|
+
}
|
|
15
|
+
/** Rows by tokens, heaviest first; equal weight keeps the key's order so a redraw never shuffles. */
|
|
16
|
+
export const heaviest = (rows) => [...rows].sort((a, b) => tokens(b) - tokens(a) || a.key.localeCompare(b.key));
|
|
17
|
+
/** 950, 1.2K, 3.4M, 1.1B: what a count looks like in a column. */
|
|
18
|
+
export function compact(n) {
|
|
19
|
+
const v = Math.max(0, Math.round(n));
|
|
20
|
+
if (v < 1000)
|
|
21
|
+
return String(v);
|
|
22
|
+
const units = ['K', 'M', 'B'];
|
|
23
|
+
let x = v / 1000;
|
|
24
|
+
let i = 0;
|
|
25
|
+
while (Math.round(x * 10) / 10 >= 1000 && i < units.length - 1) {
|
|
26
|
+
x /= 1000;
|
|
27
|
+
i++;
|
|
28
|
+
}
|
|
29
|
+
return `${x >= 100 ? Math.round(x) : Math.round(x * 10) / 10}${units[i]}`;
|
|
30
|
+
}
|
|
31
|
+
/** Dollars in the reader's locale; cents under $100, whole dollars above. */
|
|
32
|
+
export function dollars(n, locale = 'en-US') {
|
|
33
|
+
const big = Math.abs(n) >= 100;
|
|
34
|
+
return new Intl.NumberFormat(locale, {
|
|
35
|
+
style: 'currency',
|
|
36
|
+
currency: 'USD',
|
|
37
|
+
minimumFractionDigits: big ? 0 : 2,
|
|
38
|
+
maximumFractionDigits: big ? 0 : 2,
|
|
39
|
+
}).format(n);
|
|
40
|
+
}
|
|
41
|
+
/** An amount in the currency a provider reported; a code Intl does not know is printed as it came. */
|
|
42
|
+
export function money(n, currency, locale = 'en-US') {
|
|
43
|
+
try {
|
|
44
|
+
return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(n);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return `${n} ${currency}`;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/** A used share clamped to a bar: 0..100, whole numbers. */
|
|
51
|
+
export const percent = (n) => (Number.isFinite(n) ? Math.min(100, Math.max(0, Math.round(n))) : 0);
|
|
52
|
+
/** Where a limit sits: `high` from 90%, `warn` from 75%. The view colours by it. */
|
|
53
|
+
export const level = (used) => (used >= 90 ? 'high' : used >= 75 ? 'warn' : 'ok');
|
|
54
|
+
/** When a window resets, relative: `in 3h`, `in 2d`, or '' when unknown or past. */
|
|
55
|
+
export function resets(at, now = new Date(), t = english) {
|
|
56
|
+
if (!at)
|
|
57
|
+
return '';
|
|
58
|
+
const ms = new Date(at).getTime() - now.getTime();
|
|
59
|
+
if (!Number.isFinite(ms) || ms <= 0)
|
|
60
|
+
return '';
|
|
61
|
+
const m = Math.ceil(ms / 60_000);
|
|
62
|
+
if (m < 60)
|
|
63
|
+
return t('in {n}m', { n: m });
|
|
64
|
+
const h = Math.floor(m / 60);
|
|
65
|
+
if (h < 24)
|
|
66
|
+
return t('in {n}h', { n: h });
|
|
67
|
+
return t('in {n}d', { n: Math.floor(h / 24) });
|
|
68
|
+
}
|
|
69
|
+
/** How long ago: `now`, `12m`, `3h`, `2d`, `5w`, `4mo`, `2y`. '' for an instant that is not one. */
|
|
70
|
+
export function ago(at, now = new Date(), t = english) {
|
|
71
|
+
const then = new Date(at).getTime();
|
|
72
|
+
if (Number.isNaN(then))
|
|
73
|
+
return '';
|
|
74
|
+
const m = Math.max(0, Math.floor((now.getTime() - then) / 60_000));
|
|
75
|
+
if (m < 1)
|
|
76
|
+
return t('now');
|
|
77
|
+
if (m < 60)
|
|
78
|
+
return t('{n}m', { n: m });
|
|
79
|
+
const h = Math.floor(m / 60);
|
|
80
|
+
if (h < 24)
|
|
81
|
+
return t('{n}h', { n: h });
|
|
82
|
+
const d = Math.floor(h / 24);
|
|
83
|
+
if (d < 7)
|
|
84
|
+
return t('{n}d', { n: d });
|
|
85
|
+
if (d < 30)
|
|
86
|
+
return t('{n}w', { n: Math.floor(d / 7) });
|
|
87
|
+
if (d < 365)
|
|
88
|
+
return t('{n}mo', { n: Math.floor(d / 30) });
|
|
89
|
+
return t('{n}y', { n: Math.floor(d / 365) });
|
|
90
|
+
}
|
|
91
|
+
/** Sources as a list reads them: online first, then by the latest heartbeat; revoked last. */
|
|
92
|
+
export function ordered(sources) {
|
|
93
|
+
const rank = (s) => (s.state === 'online' ? 0 : s.state === 'offline' ? 1 : 2);
|
|
94
|
+
const seen = (s) => (s.last_seen ? new Date(s.last_seen).getTime() || 0 : 0);
|
|
95
|
+
return [...sources].sort((a, b) => rank(a) - rank(b) || seen(b) - seen(a) || a.name.localeCompare(b.name));
|
|
96
|
+
}
|
|
97
|
+
/** A provider's latest snapshots, one per source that reported it, freshest first. */
|
|
98
|
+
export function snapshotsFor(usage, provider) {
|
|
99
|
+
return usage.snapshots
|
|
100
|
+
.filter((s) => s.provider === provider)
|
|
101
|
+
.sort((a, b) => b.fetchedAt.localeCompare(a.fetchedAt) || a.sourceId.localeCompare(b.sourceId));
|
|
102
|
+
}
|
|
103
|
+
/** The snapshot an account reads its windows and credits from: its own source's, for its own provider. */
|
|
104
|
+
export const snapshotOf = (usage, a) => usage.snapshots.find((s) => s.provider === a.provider && s.sourceId === a.sourceId);
|
|
105
|
+
/** Every provider named by a total or a snapshot, in the order the totals weigh them. */
|
|
106
|
+
export function providers(usage) {
|
|
107
|
+
const seen = heaviest(usage.rows).map((r) => r.key);
|
|
108
|
+
for (const s of usage.snapshots)
|
|
109
|
+
if (!seen.includes(s.provider))
|
|
110
|
+
seen.push(s.provider);
|
|
111
|
+
return seen;
|
|
112
|
+
}
|
|
113
|
+
/** A source's name from its id, for a heading; the id when it was revoked and unlisted. */
|
|
114
|
+
export const named = (sources, id) => sources.find((s) => s.id === id)?.name ?? id;
|
|
115
|
+
/**
|
|
116
|
+
* Accounts as a picker lists them: those usable here first, then by provider and
|
|
117
|
+
* label, so a redraw never shuffles. Greyed accounts stay in view with their reason.
|
|
118
|
+
*/
|
|
119
|
+
export function listed(accounts, sources, surface, deviceId) {
|
|
120
|
+
const usable = (a) => (availability(a, sources.find((s) => s.id === a.sourceId), surface, deviceId).usable ? 0 : 1);
|
|
121
|
+
return [...accounts].sort((a, b) => usable(a) - usable(b) || a.provider.localeCompare(b.provider) || (a.label ?? a.instance ?? '').localeCompare(b.label ?? b.instance ?? '') || a.id.localeCompare(b.id));
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Whether `account` can run a session on `surface`, and why not: one pure
|
|
125
|
+
* function of the account, its source, the surface and the account's classes
|
|
126
|
+
* from cloud (HIP-1350, "One view, one picker, four surfaces"). `deviceId` is the
|
|
127
|
+
* source id of the device the surface runs on, when it is a linked source.
|
|
128
|
+
* The reasons are the table's one-line strings, `<device>` filled in.
|
|
129
|
+
*/
|
|
130
|
+
export function availability(account, source, surface, deviceId, t = english) {
|
|
131
|
+
const classes = account.classes?.length ? account.classes : ['local'];
|
|
132
|
+
const device = source?.name ?? t('this device');
|
|
133
|
+
if (account.kind === 'key') {
|
|
134
|
+
if (surface === 'extension')
|
|
135
|
+
return { usable: false, reason: t('Runs from Hanzo Dev or hanzo.app') };
|
|
136
|
+
return { usable: true };
|
|
137
|
+
}
|
|
138
|
+
if (!source || source.state === 'revoked')
|
|
139
|
+
return { usable: false, reason: t('{device} was unlinked', { device }) };
|
|
140
|
+
if (source.kind === 'browser')
|
|
141
|
+
return { usable: false, reason: t('Browser accounts are view-only') };
|
|
142
|
+
if (deviceId && source.id === deviceId)
|
|
143
|
+
return { usable: true };
|
|
144
|
+
if (classes.includes('desktop')) {
|
|
145
|
+
if (surface === 'extension')
|
|
146
|
+
return { usable: false, reason: t('Runs from Hanzo Dev or hanzo.app') };
|
|
147
|
+
if (source.state !== 'online')
|
|
148
|
+
return { usable: false, reason: t('{device} is offline', { device }) };
|
|
149
|
+
if (!account.shared)
|
|
150
|
+
return { usable: false, reason: t('Turn on Share on {device}', { device }) };
|
|
151
|
+
return { usable: true, reason: t('Run on {device}', { device }) };
|
|
152
|
+
}
|
|
153
|
+
return { usable: false, reason: t('Stays on {device}: its terms do not allow remote use', { device }) };
|
|
154
|
+
}
|
|
155
|
+
/** What choosing an account returns, or null when it is not usable here. */
|
|
156
|
+
export function choose(account, source, surface, deviceId) {
|
|
157
|
+
if (!availability(account, source, surface, deviceId).usable)
|
|
158
|
+
return null;
|
|
159
|
+
if (account.kind === 'key')
|
|
160
|
+
return { via: 'key', account: account.id };
|
|
161
|
+
// A login on this very device runs in the desktop app itself, not through a route.
|
|
162
|
+
if (deviceId && source?.id === deviceId)
|
|
163
|
+
return null;
|
|
164
|
+
return { via: 'desktop', source: source.id, instance: account.instance ?? '' };
|
|
165
|
+
}
|
|
166
|
+
/** The default: a cloud cell on Hanzo's own models, which needs no account. */
|
|
167
|
+
export const CELL = { via: 'cell' };
|
package/dist/mount.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Picked } from './accounts.js';
|
|
2
|
+
import type { Choice, Surface } from './types.js';
|
|
3
|
+
export interface MountOptions {
|
|
4
|
+
surface: Surface;
|
|
5
|
+
/** The IAM bearer, or a function that reads it when a request is made. */
|
|
6
|
+
token: string | null | (() => string | null);
|
|
7
|
+
/** The gateway's origin, e.g. https://api.hanzo.ai. */
|
|
8
|
+
apiBase: string;
|
|
9
|
+
/** The source id of the device this surface runs on, when it is a linked one. */
|
|
10
|
+
deviceId?: string;
|
|
11
|
+
org?: string | null | (() => string | null);
|
|
12
|
+
/** An org admin: adds the People tab. */
|
|
13
|
+
admin?: boolean;
|
|
14
|
+
/** `picker` draws the account picker alone; `view` (default) the whole view. */
|
|
15
|
+
mode?: 'view' | 'picker';
|
|
16
|
+
/** Makes account rows choosable. Required for `picker`. */
|
|
17
|
+
onPick?: (pick: Picked) => void;
|
|
18
|
+
selected?: Choice | null;
|
|
19
|
+
/** Where a signed-out person goes; defaults to https://hanzo.ai/login. */
|
|
20
|
+
signIn?: string;
|
|
21
|
+
/** `light` or `dark`; the gui theme the mount carries. */
|
|
22
|
+
theme?: 'light' | 'dark';
|
|
23
|
+
}
|
|
24
|
+
export interface Mounted {
|
|
25
|
+
/** Redraw with changed options (a new token, a different surface). */
|
|
26
|
+
update(next: Partial<MountOptions>): void;
|
|
27
|
+
unmount(): void;
|
|
28
|
+
}
|
|
29
|
+
export declare function mountSources(element: HTMLElement, options: MountOptions): Mounted;
|
package/dist/mount.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
// `mountSources`: the sources view or the picker in any page, with no React in
|
|
3
|
+
// the host. The Hanzo extension's popup and a plain page call it; a React host
|
|
4
|
+
// (hanzo.app, Dev's web) renders `SourcesView` / `AccountPicker` itself.
|
|
5
|
+
//
|
|
6
|
+
// The host loads @hanzo/design's `styles.css` (the tokens); this mounts gui's
|
|
7
|
+
// provider and its generated sheet once, so nothing else is needed.
|
|
8
|
+
import { createRoot } from 'react-dom/client';
|
|
9
|
+
import { GuiProvider } from '@hanzo/gui';
|
|
10
|
+
import { css, monochrome } from '@hanzo/ui/gui-config';
|
|
11
|
+
import { createClient } from './client.js';
|
|
12
|
+
import { AccountPicker } from './picker.js';
|
|
13
|
+
import { SourcesView } from './view.js';
|
|
14
|
+
const SHEET = 'hanzo-sources-gui';
|
|
15
|
+
export function mountSources(element, options) {
|
|
16
|
+
if (!document.getElementById(SHEET)) {
|
|
17
|
+
const sheet = document.createElement('style');
|
|
18
|
+
sheet.id = SHEET;
|
|
19
|
+
sheet.textContent = css(monochrome);
|
|
20
|
+
document.head.append(sheet);
|
|
21
|
+
}
|
|
22
|
+
let opts = options;
|
|
23
|
+
const root = createRoot(element);
|
|
24
|
+
const draw = () => {
|
|
25
|
+
const client = createClient({ apiBase: opts.apiBase, token: opts.token, org: opts.org });
|
|
26
|
+
const props = { client, surface: opts.surface, deviceId: opts.deviceId, selected: opts.selected, signIn: opts.signIn };
|
|
27
|
+
root.render(_jsx(GuiProvider, { config: monochrome, defaultTheme: opts.theme ?? 'light', disableInjectCSS: true, children: opts.mode === 'picker' ? (_jsx(AccountPicker, { ...props, onPick: opts.onPick ?? (() => { }) })) : (_jsx(SourcesView, { ...props, admin: opts.admin, onPick: opts.onPick })) }));
|
|
28
|
+
};
|
|
29
|
+
draw();
|
|
30
|
+
return {
|
|
31
|
+
update(next) {
|
|
32
|
+
opts = { ...opts, ...next };
|
|
33
|
+
draw();
|
|
34
|
+
},
|
|
35
|
+
unmount: () => root.unmount(),
|
|
36
|
+
};
|
|
37
|
+
}
|
package/dist/picker.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { type Picked } from './accounts.js';
|
|
2
|
+
import type { Client } from './client.js';
|
|
3
|
+
import type { Choice, Surface } from './types.js';
|
|
4
|
+
export type { Picked };
|
|
5
|
+
export interface AccountPickerProps {
|
|
6
|
+
client: Client;
|
|
7
|
+
surface: Surface;
|
|
8
|
+
deviceId?: string;
|
|
9
|
+
onPick: (pick: Picked) => void;
|
|
10
|
+
/** The route in use; the Hanzo cell when none. */
|
|
11
|
+
selected?: Choice | null;
|
|
12
|
+
signIn?: string;
|
|
13
|
+
}
|
|
14
|
+
export declare function AccountPicker({ client, surface, deviceId, onPick, selected, signIn }: AccountPickerProps): import("react").JSX.Element;
|
package/dist/picker.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
// The account picker: the model/provider picker's contract for Hanzo's own
|
|
4
|
+
// accounts. It lists the Hanzo cell and every account the person has, those
|
|
5
|
+
// usable on this surface first and the rest greyed with their reason, and calls
|
|
6
|
+
// `onPick` with the account and its route: `{via:"desktop", source, instance}`
|
|
7
|
+
// for a login on another device, `{via:"key", account}` for a key, `{via:"cell"}`
|
|
8
|
+
// for the default. A login on this very device returns `choice: null`: the host
|
|
9
|
+
// runs it itself.
|
|
10
|
+
import { useState } from 'react';
|
|
11
|
+
import { useI18n } from '@hanzo/i18n/react';
|
|
12
|
+
import { Text, YStack } from '@hanzo/ui';
|
|
13
|
+
import { Accounts } from './accounts.js';
|
|
14
|
+
import { useRead } from './data.js';
|
|
15
|
+
import { Failed, Loading, SIGN_IN, SignedOut } from './view.js';
|
|
16
|
+
export function AccountPicker({ client, surface, deviceId, onPick, selected, signIn = SIGN_IN }) {
|
|
17
|
+
const { t } = useI18n();
|
|
18
|
+
const [bump, setBump] = useState(0);
|
|
19
|
+
const read = useRead(client, 7, bump, false);
|
|
20
|
+
if (!client.signedIn())
|
|
21
|
+
return _jsx(SignedOut, { href: signIn });
|
|
22
|
+
if (read.is === 'loading')
|
|
23
|
+
return _jsx(Loading, {});
|
|
24
|
+
if (read.is === 'error')
|
|
25
|
+
return _jsx(Failed, { status: read.status, onRetry: () => setBump((n) => n + 1), signIn: signIn });
|
|
26
|
+
return (_jsxs(YStack, { gap: "$2", "data-slot": "picker", children: [_jsx(Accounts, { accounts: read.accounts, sources: read.sources, usage: read.provider, surface: surface, deviceId: deviceId, now: read.at, selected: selected, onPick: onPick }), read.accounts.length === 0 ? _jsx(Text, { fontSize: "$2", color: "$aside", children: t('No provider accounts yet. Link the Hanzo Dev desktop app to bring your logins here.') }) : null] }));
|
|
27
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shapes of `/v1/sources` (HIP-1350). Usage is Hanzo Dev's usage model
|
|
3
|
+
* (`@hanzodev/usage` schema.ts) plus the registry's own fields.
|
|
4
|
+
*/
|
|
5
|
+
export type SourceKind = 'desktop' | 'browser';
|
|
6
|
+
export type SourceState = 'online' | 'offline' | 'revoked';
|
|
7
|
+
export type AccountKind = 'login' | 'key';
|
|
8
|
+
/** What a provider account may be used for. `local` is the fail-closed default. */
|
|
9
|
+
export type RouteClass = 'local' | 'desktop' | 'key' | 'cell';
|
|
10
|
+
/** Where a person is looking from. `web` is hanzo.app, hanzo.team and hanzo.bot. */
|
|
11
|
+
export type Surface = 'extension' | 'desktop' | 'web';
|
|
12
|
+
export interface ProviderState {
|
|
13
|
+
provider: string;
|
|
14
|
+
instance: string;
|
|
15
|
+
kind: AccountKind;
|
|
16
|
+
state: string;
|
|
17
|
+
plan?: string;
|
|
18
|
+
shared?: boolean;
|
|
19
|
+
}
|
|
20
|
+
export interface Source {
|
|
21
|
+
id: string;
|
|
22
|
+
kind: SourceKind;
|
|
23
|
+
name: string;
|
|
24
|
+
os: string;
|
|
25
|
+
arch?: string;
|
|
26
|
+
version?: string;
|
|
27
|
+
state: SourceState;
|
|
28
|
+
last_seen?: string;
|
|
29
|
+
linked_at: string;
|
|
30
|
+
zap?: string;
|
|
31
|
+
providers: ProviderState[];
|
|
32
|
+
}
|
|
33
|
+
/** A login a desktop or browser detected, or a key held in Hanzo KMS: `GET /v1/sources/accounts`. */
|
|
34
|
+
export interface Account {
|
|
35
|
+
id: string;
|
|
36
|
+
provider: string;
|
|
37
|
+
kind: AccountKind;
|
|
38
|
+
label?: string;
|
|
39
|
+
fingerprint?: string;
|
|
40
|
+
created?: string;
|
|
41
|
+
classes: RouteClass[];
|
|
42
|
+
sourceId?: string;
|
|
43
|
+
instance?: string;
|
|
44
|
+
state?: string;
|
|
45
|
+
plan?: string;
|
|
46
|
+
shared?: boolean;
|
|
47
|
+
}
|
|
48
|
+
export interface Window {
|
|
49
|
+
kind: 'session' | 'daily' | 'weekly' | 'monthly' | 'credits' | 'other';
|
|
50
|
+
label: string;
|
|
51
|
+
usedPercent: number;
|
|
52
|
+
windowMinutes?: number;
|
|
53
|
+
resetsAt?: string;
|
|
54
|
+
}
|
|
55
|
+
export interface Snapshot {
|
|
56
|
+
sourceId: string;
|
|
57
|
+
provider: string;
|
|
58
|
+
fetchedAt: string;
|
|
59
|
+
source: string;
|
|
60
|
+
plan?: string;
|
|
61
|
+
windows: Window[];
|
|
62
|
+
credits?: {
|
|
63
|
+
currency: string;
|
|
64
|
+
balance?: number;
|
|
65
|
+
spent?: number;
|
|
66
|
+
limit?: number;
|
|
67
|
+
};
|
|
68
|
+
status?: {
|
|
69
|
+
indicator: string;
|
|
70
|
+
description?: string;
|
|
71
|
+
};
|
|
72
|
+
error?: string;
|
|
73
|
+
}
|
|
74
|
+
export interface Row {
|
|
75
|
+
key: string;
|
|
76
|
+
inputTokens: number;
|
|
77
|
+
outputTokens: number;
|
|
78
|
+
cacheTokens: number;
|
|
79
|
+
costUsd: number;
|
|
80
|
+
}
|
|
81
|
+
export interface Usage {
|
|
82
|
+
rows: Row[];
|
|
83
|
+
snapshots: Snapshot[];
|
|
84
|
+
}
|
|
85
|
+
export type By = 'source' | 'provider' | 'model' | 'user';
|
|
86
|
+
/** The ranges the view offers, in days. */
|
|
87
|
+
export declare const RANGES: readonly [7, 30];
|
|
88
|
+
export type Range = (typeof RANGES)[number];
|
|
89
|
+
/** Whether an account can run a session here, and the one line that says why not (or how). */
|
|
90
|
+
export interface Availability {
|
|
91
|
+
usable: boolean;
|
|
92
|
+
reason?: string;
|
|
93
|
+
}
|
|
94
|
+
/** What choosing an account returns: `/v1/dev`'s `execution` field (HIP-1350, Routing). */
|
|
95
|
+
export type Choice = {
|
|
96
|
+
via: 'cell';
|
|
97
|
+
} | {
|
|
98
|
+
via: 'key';
|
|
99
|
+
account: string;
|
|
100
|
+
} | {
|
|
101
|
+
via: 'desktop';
|
|
102
|
+
source: string;
|
|
103
|
+
instance: string;
|
|
104
|
+
};
|
package/dist/types.js
ADDED
package/dist/view.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { type Picked } from './accounts.js';
|
|
2
|
+
import type { Client } from './client.js';
|
|
3
|
+
import { type Choice, type Surface } from './types.js';
|
|
4
|
+
/** Where a signed-out person goes. IAM owns sign-in; the host's origin decides nothing here. */
|
|
5
|
+
export declare const SIGN_IN = "https://hanzo.ai/login";
|
|
6
|
+
export interface SourcesViewProps {
|
|
7
|
+
client: Client;
|
|
8
|
+
/** Where this view runs: decides which accounts are usable here. */
|
|
9
|
+
surface: Surface;
|
|
10
|
+
/** The source id of the device this surface runs on, when it is a linked one. */
|
|
11
|
+
deviceId?: string;
|
|
12
|
+
/** An org admin: adds the People tab, per-user totals only. */
|
|
13
|
+
admin?: boolean;
|
|
14
|
+
/** Makes account rows choosable: the picker contract. */
|
|
15
|
+
onPick?: (pick: Picked) => void;
|
|
16
|
+
/** The account in use, marked on its row. */
|
|
17
|
+
selected?: Choice | null;
|
|
18
|
+
signIn?: string;
|
|
19
|
+
}
|
|
20
|
+
export declare function SourcesView({ client, surface, deviceId, admin, onPick, selected, signIn }: SourcesViewProps): import("react").JSX.Element;
|
|
21
|
+
export declare function SignedOut({ href }: {
|
|
22
|
+
href: string;
|
|
23
|
+
}): import("react").JSX.Element;
|
|
24
|
+
export declare function Loading(): import("react").JSX.Element;
|
|
25
|
+
export declare function Failed({ status, onRetry, signIn }: {
|
|
26
|
+
status: number;
|
|
27
|
+
onRetry: () => void;
|
|
28
|
+
signIn?: string;
|
|
29
|
+
}): import("react").JSX.Element;
|
|
30
|
+
export declare function Section({ title, slot, children }: {
|
|
31
|
+
title: string;
|
|
32
|
+
slot: string;
|
|
33
|
+
children: React.ReactNode;
|
|
34
|
+
}): import("react").JSX.Element;
|
package/dist/view.js
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
// The sources view (HIP-1350, "One view"): every desktop and browser a person
|
|
4
|
+
// linked to Hanzo, every account each detected, and what they used. One
|
|
5
|
+
// component for every surface; the host passes a client and says where it runs.
|
|
6
|
+
// It holds no credential and reports nothing: metadata only, never prompts or code.
|
|
7
|
+
import { useCallback, useEffect, useState } from 'react';
|
|
8
|
+
import { useI18n } from '@hanzo/i18n/react';
|
|
9
|
+
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, Button, Spinner, Tabs, TabsList, TabsTrigger, Text, XStack, YStack, } from '@hanzo/ui';
|
|
10
|
+
import { Accounts } from './accounts.js';
|
|
11
|
+
import { useRead } from './data.js';
|
|
12
|
+
import { ago, compact, dollars, heaviest, ordered, tokens, total } from './logic.js';
|
|
13
|
+
import { RANGES } from './types.js';
|
|
14
|
+
const EDGE = 'var(--border-strong)';
|
|
15
|
+
/** Where a signed-out person goes. IAM owns sign-in; the host's origin decides nothing here. */
|
|
16
|
+
export const SIGN_IN = 'https://hanzo.ai/login';
|
|
17
|
+
export function SourcesView({ client, surface, deviceId, admin, onPick, selected, signIn = SIGN_IN }) {
|
|
18
|
+
const { t } = useI18n();
|
|
19
|
+
const [range, setRange] = useState(7);
|
|
20
|
+
const [bump, setBump] = useState(0);
|
|
21
|
+
const [tab, setTab] = useState('mine');
|
|
22
|
+
const read = useRead(client, range, bump);
|
|
23
|
+
if (!client.signedIn())
|
|
24
|
+
return _jsx(SignedOut, { href: signIn });
|
|
25
|
+
return (_jsxs(YStack, { gap: "$5", "data-slot": "sources", children: [_jsxs(YStack, { gap: "$1.5", children: [_jsx(Text, { fontSize: "$3", color: "$soft", children: t('Every desktop and browser you linked to Hanzo, and what each used.') }), _jsx(Text, { fontSize: "$2", color: "$aside", "data-slot": "sources-copy", children: t('Only metadata is reported: token counts, cost and plan limits. Never your prompts, replies or code. A subscription login stays on the device that holds it.') })] }), _jsxs(XStack, { gap: "$3", items: "center", justify: "space-between", flexWrap: "wrap", children: [admin ? (_jsx(Tabs, { value: tab, onValueChange: (v) => setTab(v === 'people' ? 'people' : 'mine'), children: _jsxs(TabsList, { children: [_jsx(TabsTrigger, { value: "mine", children: t('Your sources') }), _jsx(TabsTrigger, { value: "people", children: t('People') })] }) })) : (_jsx("span", {})), _jsx(RangePicker, { range: range, onChange: setRange })] }), tab === 'people' && admin ? (_jsx(People, { client: client, range: range })) : read.is === 'loading' ? (_jsx(Loading, {})) : read.is === 'error' ? (_jsx(Failed, { status: read.status, onRetry: () => setBump((n) => n + 1), signIn: signIn })) : (_jsx(Ready, { read: read, client: client, surface: surface, deviceId: deviceId, range: range, onPick: onPick, selected: selected, onRevoked: () => setBump((n) => n + 1) }))] }));
|
|
26
|
+
}
|
|
27
|
+
export function SignedOut({ href }) {
|
|
28
|
+
const { t } = useI18n();
|
|
29
|
+
return (_jsxs(YStack, { gap: "$2", "data-slot": "sources-signed-out", children: [_jsx(Text, { fontSize: "$3", color: "$soft", children: t('Sign in to see your linked sources.') }), _jsx(XStack, { children: _jsx(Button, { size: "sm", variant: "primary", render: _jsx("a", { href: href }), children: t('Sign in') }) })] }));
|
|
30
|
+
}
|
|
31
|
+
export function Loading() {
|
|
32
|
+
const { t } = useI18n();
|
|
33
|
+
return (_jsxs(XStack, { gap: "$2", items: "center", role: "status", children: [_jsx(Spinner, { size: 16 }), _jsx(Text, { fontSize: "$3", color: "$soft", children: t('Reading your sources…') })] }));
|
|
34
|
+
}
|
|
35
|
+
function RangePicker({ range, onChange }) {
|
|
36
|
+
const { t } = useI18n();
|
|
37
|
+
return (_jsx(Tabs, { value: String(range), onValueChange: (v) => onChange(Number(v) === 30 ? 30 : 7), "data-slot": "sources-range", "aria-label": t('Range'), children: _jsx(TabsList, { children: RANGES.map((d) => (_jsx(TabsTrigger, { value: String(d), children: t('{n} days', { n: d }) }, d))) }) }));
|
|
38
|
+
}
|
|
39
|
+
export function Failed({ status, onRetry, signIn = SIGN_IN }) {
|
|
40
|
+
const { t } = useI18n();
|
|
41
|
+
const denied = status === 401 || status === 403;
|
|
42
|
+
return (_jsxs(YStack, { gap: "$2", role: "alert", "data-slot": "sources-error", children: [_jsx(Text, { fontSize: "$3", color: "var(--state-error)", children: denied
|
|
43
|
+
? t('Sign in again to see your linked sources.')
|
|
44
|
+
: status === 0
|
|
45
|
+
? t('Could not reach Hanzo. Check your connection.')
|
|
46
|
+
: t('Hanzo could not read your linked sources ({status}).', { status }) }), _jsxs(XStack, { gap: "$2", children: [denied ? _jsx(Button, { size: "sm", variant: "primary", render: _jsx("a", { href: signIn }), children: t('Sign in') }) : null, _jsx(Button, { size: "sm", variant: "outline", onPress: onRetry, children: t('Try again') })] })] }));
|
|
47
|
+
}
|
|
48
|
+
function Ready({ read, client, surface, deviceId, range, onPick, selected, onRevoked, }) {
|
|
49
|
+
const { t } = useI18n();
|
|
50
|
+
if (read.sources.length === 0 && read.accounts.length === 0) {
|
|
51
|
+
return (_jsxs(YStack, { gap: "$1.5", borderWidth: 1, borderColor: EDGE, rounded: "$3", p: "$4", "data-slot": "sources-empty", children: [_jsx(Text, { fontSize: "$4", fontWeight: "600", color: "$ink", children: t('Nothing is linked yet') }), _jsx(Text, { fontSize: "$3", color: "$soft", children: t('Link the Hanzo Dev desktop app or the Hanzo browser extension to your account and it appears here, with its usage.') })] }));
|
|
52
|
+
}
|
|
53
|
+
const by = (id) => read.source.rows.find((r) => r.key === id);
|
|
54
|
+
return (_jsxs(YStack, { gap: "$6", children: [_jsx(Section, { title: t('Linked sources'), slot: "sources-list", children: ordered(read.sources).map((s) => (_jsx(SourceRow, { client: client, source: s, used: by(s.id), now: read.at, onRevoked: onRevoked }, s.id))) }), _jsxs(Section, { title: t('Accounts'), slot: "sources-accounts", children: [read.accounts.length === 0 ? (_jsx(Text, { fontSize: "$3", color: "$soft", children: t('No provider accounts reported.') })) : null, _jsx(Accounts, { accounts: read.accounts, sources: read.sources, usage: read.provider, surface: surface, deviceId: deviceId, now: read.at, selected: selected, onPick: onPick })] }), _jsx(Totals, { title: t('Usage by provider · last {n} days', { n: range }), slot: "sources-providers", rows: read.provider.rows }), _jsx(Totals, { title: t('Models · last {n} days', { n: range }), slot: "sources-models", rows: read.model.rows, model: true })] }));
|
|
55
|
+
}
|
|
56
|
+
export function Section({ title, slot, children }) {
|
|
57
|
+
return (_jsxs(YStack, { gap: "$2.5", "data-slot": slot, children: [_jsx(Text, { fontSize: "$4", fontWeight: "600", color: "$ink", render: "h3", children: title }), children] }));
|
|
58
|
+
}
|
|
59
|
+
function Dot({ state }) {
|
|
60
|
+
const { t } = useI18n();
|
|
61
|
+
const label = state === 'online' ? t('Online') : state === 'offline' ? t('Offline') : t('Revoked');
|
|
62
|
+
return (_jsx(YStack, { role: "img", "aria-label": label, "data-state": state, width: 8, height: 8, rounded: 999, shrink: 0, bg: state === 'online' ? 'var(--state-online)' : state === 'revoked' ? 'var(--state-error)' : 'var(--border-strong)' }));
|
|
63
|
+
}
|
|
64
|
+
function SourceRow({ client, source: s, used, now, onRevoked }) {
|
|
65
|
+
const { t, locale } = useI18n();
|
|
66
|
+
const [ask, setAsk] = useState(false);
|
|
67
|
+
const [busy, setBusy] = useState(false);
|
|
68
|
+
const [refused, setRefused] = useState(false);
|
|
69
|
+
const revoke = useCallback(async () => {
|
|
70
|
+
setBusy(true);
|
|
71
|
+
setRefused(false);
|
|
72
|
+
try {
|
|
73
|
+
await client.revoke(s.id);
|
|
74
|
+
setAsk(false);
|
|
75
|
+
onRevoked();
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
setRefused(true);
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
setBusy(false);
|
|
82
|
+
}
|
|
83
|
+
}, [client, s.id, onRevoked]);
|
|
84
|
+
const seen = s.state === 'online' ? t('online now') : s.last_seen ? t('last seen {when} ago', { when: ago(s.last_seen, now, t) }) : t('never seen');
|
|
85
|
+
return (_jsxs(YStack, { gap: "$2", borderWidth: 1, borderColor: EDGE, rounded: "$3", p: "$3.5", "data-slot": "source", "data-id": s.id, "data-state": s.state, children: [_jsxs(XStack, { gap: "$2.5", items: "center", justify: "space-between", flexWrap: "wrap", children: [_jsxs(XStack, { gap: "$2.5", items: "center", flex: 1, minW: 0, children: [_jsx(Dot, { state: s.state }), _jsxs(YStack, { flex: 1, minW: 0, children: [_jsx(Text, { fontSize: "$3", fontWeight: "600", color: "$ink", numberOfLines: 1, children: s.name }), _jsxs(Text, { fontSize: "$2", color: "$aside", children: [[s.kind === 'browser' ? t('Browser') : t('Desktop'), s.os, s.version].filter(Boolean).join(' · '), " \u00B7 ", seen] })] })] }), s.state !== 'revoked' ? (_jsx(Button, { size: "sm", variant: "outline", "aria-label": t('Revoke {name}', { name: s.name }), onPress: () => setAsk(true), children: t('Revoke') })) : null] }), used ? (_jsx(Text, { fontSize: "$2", color: "$soft", fontVariant: ['tabular-nums'], children: t('{tokens} tokens · {cost}', { tokens: compact(tokens(used)), cost: dollars(used.costUsd, locale) }) })) : null, _jsx(AlertDialog, { open: ask, onOpenChange: (o) => !busy && setAsk(o), children: _jsxs(AlertDialogContent, { children: [_jsxs(AlertDialogHeader, { children: [_jsx(AlertDialogTitle, { children: t('Revoke {name}?', { name: s.name }) }), _jsx(AlertDialogDescription, { children: t('It stops reporting and its link to your account is cut. Its past usage stays in your totals. Link it again from the app to bring it back.') })] }), refused ? _jsx(Text, { fontSize: "$2", color: "var(--state-error)", role: "alert", children: t('Could not revoke. Try again.') }) : null, _jsxs(AlertDialogFooter, { children: [_jsx(AlertDialogCancel, { children: t('Cancel') }), _jsx(AlertDialogAction, { variant: "destructive", disabled: busy, onPress: () => void revoke(), children: t('Revoke') })] })] }) })] }));
|
|
86
|
+
}
|
|
87
|
+
/** Tokens and cost by provider or model over the range. The cloud totals a range; it does not split it by day. */
|
|
88
|
+
function Totals({ title, slot, rows, model }) {
|
|
89
|
+
const { t, locale } = useI18n();
|
|
90
|
+
if (rows.length === 0) {
|
|
91
|
+
return model ? null : (_jsx(Section, { title: title, slot: slot, children: _jsx(Text, { fontSize: "$3", color: "$soft", "data-slot": "sources-no-usage", children: t('No usage reported in this range.') }) }));
|
|
92
|
+
}
|
|
93
|
+
const sum = total(rows);
|
|
94
|
+
return (_jsxs(Section, { title: title, slot: slot, children: [_jsx(YStack, { borderWidth: 1, borderColor: EDGE, rounded: "$3", overflow: "hidden", children: heaviest(rows).map((r) => (_jsxs(XStack, { gap: "$1.5", columnGap: "$3", px: "$3.5", py: "$2.5", justify: "space-between", items: "center", flexWrap: "wrap", "data-slot": model ? 'model' : 'provider', "data-provider": r.key, children: [_jsx(Text, { fontSize: "$2", color: "$ink", flex: 1, minW: 160, children: r.key }), _jsx(Text, { fontSize: "$2", color: "$soft", fontVariant: ['tabular-nums'], children: t('{input} in · {output} out · {cache} cache', { input: compact(r.inputTokens), output: compact(r.outputTokens), cache: compact(r.cacheTokens) }) }), _jsx(Text, { fontSize: "$2", color: "$ink", fontVariant: ['tabular-nums'], minW: 64, text: "end", children: dollars(r.costUsd, locale) })] }, r.key))) }), _jsx(Text, { fontSize: "$2", color: "$aside", fontVariant: ['tabular-nums'], children: t('Total {tokens} tokens · {cost}', { tokens: compact(tokens(sum)), cost: dollars(sum.costUsd, locale) }) })] }));
|
|
95
|
+
}
|
|
96
|
+
/** An org admin's per-person totals: counts and cost, never another person's sources or accounts. */
|
|
97
|
+
function People({ client, range }) {
|
|
98
|
+
const { t, locale } = useI18n();
|
|
99
|
+
const [read, set] = useState({ is: 'loading' });
|
|
100
|
+
const [bump, setBump] = useState(0);
|
|
101
|
+
useEffect(() => {
|
|
102
|
+
const abort = new AbortController();
|
|
103
|
+
set({ is: 'loading' });
|
|
104
|
+
client
|
|
105
|
+
.usage('user', range, new Date(), abort.signal)
|
|
106
|
+
.then((u) => set({ is: 'ready', rows: u.rows }))
|
|
107
|
+
.catch((e) => {
|
|
108
|
+
if (e.name !== 'AbortError')
|
|
109
|
+
set({ is: 'error', status: e.status ?? 0 });
|
|
110
|
+
});
|
|
111
|
+
return () => abort.abort();
|
|
112
|
+
}, [client, range, bump]);
|
|
113
|
+
if (read.is === 'loading')
|
|
114
|
+
return _jsx(Loading, {});
|
|
115
|
+
if (read.is === 'error')
|
|
116
|
+
return _jsx(Failed, { status: read.status, onRetry: () => setBump((n) => n + 1) });
|
|
117
|
+
return (_jsxs(Section, { title: t('People · last {n} days', { n: range }), slot: "sources-people", children: [_jsx(Text, { fontSize: "$2", color: "$aside", children: t('Totals only. An admin never sees another person’s sources, plans or labels.') }), read.rows.length === 0 ? (_jsx(Text, { fontSize: "$3", color: "$soft", children: t('No usage reported in this range.') })) : (_jsx(YStack, { borderWidth: 1, borderColor: EDGE, rounded: "$3", overflow: "hidden", children: heaviest(read.rows).map((r) => (_jsxs(XStack, { gap: "$3", px: "$3.5", py: "$2.5", justify: "space-between", "data-slot": "person", children: [_jsx(Text, { fontSize: "$2", color: "$ink", flex: 1, minW: 0, numberOfLines: 1, children: r.key }), _jsx(Text, { fontSize: "$2", color: "$soft", fontVariant: ['tabular-nums'], children: t('{tokens} tokens', { tokens: compact(tokens(r)) }) }), _jsx(Text, { fontSize: "$2", color: "$ink", fontVariant: ['tabular-nums'], minW: 64, text: "end", children: dollars(r.costUsd, locale) })] }, r.key))) }))] }));
|
|
118
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hanzo/sources",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Hanzo's linked sources: the one view of every desktop and browser a person linked, the account picker, the cloud client and the availability rule (HIP-1350).",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./*": {
|
|
16
|
+
"types": "./dist/*.d.ts",
|
|
17
|
+
"import": "./dist/*.js",
|
|
18
|
+
"default": "./dist/*.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"LICENSE-APACHE",
|
|
24
|
+
"LICENSE-MIT"
|
|
25
|
+
],
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"publishConfig": {
|
|
28
|
+
"access": "public",
|
|
29
|
+
"registry": "https://registry.npmjs.org/"
|
|
30
|
+
},
|
|
31
|
+
"license": "Apache-2.0 OR MIT",
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"@hanzo/design": ">=0.5.39",
|
|
34
|
+
"@hanzo/gui": "^8.3.5",
|
|
35
|
+
"@hanzo/i18n": ">=0.5.5",
|
|
36
|
+
"@hanzo/ui": ">=8.33.5",
|
|
37
|
+
"react": ">=19.2.8",
|
|
38
|
+
"react-dom": ">=19.2.8"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"@hanzo/design": "0.5.39",
|
|
42
|
+
"@hanzo/gui": "8.3.5",
|
|
43
|
+
"@hanzo/i18n": "0.5.5",
|
|
44
|
+
"@hanzo/ui": "8.33.6",
|
|
45
|
+
"@playwright/test": "^1.65.1",
|
|
46
|
+
"@types/node": "26.5.0",
|
|
47
|
+
"@types/react": "19.2.18",
|
|
48
|
+
"@types/react-dom": "19.2.7",
|
|
49
|
+
"happy-dom": "20.14.6",
|
|
50
|
+
"react": "19.2.8",
|
|
51
|
+
"react-dom": "19.2.8",
|
|
52
|
+
"react-native-web": "0.21.2",
|
|
53
|
+
"typescript": "7.0.2",
|
|
54
|
+
"vite": "8.3.2",
|
|
55
|
+
"vitest": "4.1.11"
|
|
56
|
+
},
|
|
57
|
+
"scripts": {
|
|
58
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json && node ../app/scripts/specifiers.mjs ./dist",
|
|
59
|
+
"typecheck": "tsc --noEmit",
|
|
60
|
+
"test": "vitest run",
|
|
61
|
+
"lint:design": "hanzo-design-lint src",
|
|
62
|
+
"e2e": "playwright test"
|
|
63
|
+
}
|
|
6
64
|
}
|
package/README.md
DELETED