@certalis/agent-smith 0.1.1 → 0.1.3

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/dist/bin.js CHANGED
@@ -1275,12 +1275,30 @@ function parseNumber(value) {
1275
1275
  const parsed = Number(value);
1276
1276
  return Number.isFinite(parsed) ? parsed : undefined;
1277
1277
  }
1278
+ function normalizeEnrollmentEmail(value) {
1279
+ if (typeof value !== "string")
1280
+ return;
1281
+ const email = value.trim().toLowerCase();
1282
+ return email.length <= 254 && patterns.email.test(email) ? email : undefined;
1283
+ }
1284
+ function sanitizeEnrollmentEmails(value) {
1285
+ if (!Array.isArray(value))
1286
+ return;
1287
+ const emails = value.map(normalizeEnrollmentEmail).filter((email) => email !== undefined);
1288
+ return [...new Set(emails)].slice(0, MAX_ENROLLMENT_EMAILS);
1289
+ }
1278
1290
  function sanitizeConfigData(value) {
1279
1291
  if (!isRecord(value)) {
1280
1292
  return {};
1281
1293
  }
1282
1294
  const sanitized = {};
1283
1295
  for (const [key, entry] of Object.entries(value)) {
1296
+ if (key === "enrollment_emails") {
1297
+ const emails = sanitizeEnrollmentEmails(entry);
1298
+ if (emails)
1299
+ sanitized.enrollment_emails = emails;
1300
+ continue;
1301
+ }
1284
1302
  if (key === "team_routing") {
1285
1303
  const teamRouting = sanitizeTeamRouting(entry);
1286
1304
  if (teamRouting)
@@ -1430,7 +1448,7 @@ function sanitizeTeamRouting(value) {
1430
1448
  }
1431
1449
  return result;
1432
1450
  }
1433
- var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, Config;
1451
+ var log2, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, Config;
1434
1452
  var init_src4 = __esm(() => {
1435
1453
  init_src2();
1436
1454
  init_src3();
@@ -1674,11 +1692,28 @@ var init_src4 = __esm(() => {
1674
1692
  this.persistAccountAllowlist(current.filter((uuid) => uuid !== accountUuid));
1675
1693
  }
1676
1694
  persistAccountAllowlist(accountUuids) {
1677
- const teamRouting = {
1695
+ this.persistStrictly("team_routing", {
1678
1696
  ...this.data.team_routing,
1679
1697
  allowlisted_account_uuids: accountUuids
1680
- };
1681
- const next = { ...this.data, team_routing: teamRouting };
1698
+ });
1699
+ }
1700
+ getEnrollmentEmails() {
1701
+ return [...this.data.enrollment_emails ?? []];
1702
+ }
1703
+ setEnrollmentEmails(emails) {
1704
+ const normalized = emails.map(normalizeEnrollmentEmail);
1705
+ if (normalized.some((email) => email === undefined)) {
1706
+ throw new ValidationError("Invalid enrollment email", "enrollment_emails");
1707
+ }
1708
+ const unique = [...new Set(normalized)];
1709
+ if (unique.length > MAX_ENROLLMENT_EMAILS) {
1710
+ throw new ValidationError(`At most ${MAX_ENROLLMENT_EMAILS} enrollment emails`, "enrollment_emails");
1711
+ }
1712
+ this.persistStrictly("enrollment_emails", unique);
1713
+ return [...unique];
1714
+ }
1715
+ persistStrictly(key, value) {
1716
+ const next = { ...this.data, [key]: value };
1682
1717
  const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
1683
1718
  try {
1684
1719
  writeFileSync(temporary, JSON.stringify(next, null, 2), {
@@ -1689,13 +1724,9 @@ var init_src4 = __esm(() => {
1689
1724
  } finally {
1690
1725
  rmSync(temporary, { force: true });
1691
1726
  }
1692
- const oldValue = this.data.team_routing;
1727
+ const oldValue = this.data[key];
1693
1728
  this.data = next;
1694
- this.emit("change", {
1695
- key: "team_routing",
1696
- oldValue,
1697
- newValue: teamRouting
1698
- });
1729
+ this.emit("change", { key, oldValue, newValue: value });
1699
1730
  }
1700
1731
  getRuntime() {
1701
1732
  const defaults = {
@@ -4422,6 +4453,9 @@ class BaseProvider {
4422
4453
  isWeeklyBucket(_bucket) {
4423
4454
  return false;
4424
4455
  }
4456
+ isFiveHourBucket(_bucket) {
4457
+ return false;
4458
+ }
4425
4459
  getClientSessionId(headers2) {
4426
4460
  return headers2.get("x-claude-code-session-id");
4427
4461
  }
@@ -4659,6 +4693,9 @@ var init_provider = __esm(() => {
4659
4693
  isWeeklyBucket(bucket) {
4660
4694
  return bucket.startsWith("unified7d");
4661
4695
  }
4696
+ isFiveHourBucket(bucket) {
4697
+ return bucket === "unified5h";
4698
+ }
4662
4699
  prepareHeaders(headers2, account2) {
4663
4700
  const newHeaders = new Headers(headers2);
4664
4701
  deleteClientCredentialHeaders(newHeaders);
@@ -5596,6 +5633,9 @@ var init_provider4 = __esm(() => {
5596
5633
  isWeeklyBucket(bucket) {
5597
5634
  return bucket === "unified7d";
5598
5635
  }
5636
+ isFiveHourBucket(bucket) {
5637
+ return bucket === "unified5h";
5638
+ }
5599
5639
  supportsWebSocket(upstreamPath) {
5600
5640
  return upstreamPath === "/responses";
5601
5641
  }
@@ -7014,72 +7054,157 @@ function enrollmentPage() {
7014
7054
  return new Response(`<!doctype html>
7015
7055
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
7016
7056
  <title>Connect a Claude subscription</title>
7017
- <style nonce="${nonce}">
7018
- :root{color-scheme:light;font-family:"Avenir Next",Avenir,"Segoe UI",sans-serif;color:#17334a;background:#edf3f7;line-height:1.6}
7019
- body{margin:0;padding:clamp(20px,6vw,64px)}main{max-width:42rem;margin:auto;background:#fff;padding:clamp(24px,5vw,48px);border-top:6px solid #235e82}
7020
- h1{font-size:clamp(1.8rem,5vw,2.5rem);line-height:1.2;margin:0 0 24px}h2{font-size:1.2rem;margin-top:32px}p{max-width:65ch}button,a.button{font:inherit;display:inline-block;border:0;border-radius:6px;background:#235e82;color:#fff;padding:12px 20px;text-decoration:none;cursor:pointer}button:disabled{opacity:.55;cursor:wait}button:focus-visible,a:focus-visible,input:focus-visible{outline:3px solid #b15c00;outline-offset:4px}input[type=password]{box-sizing:border-box;display:block;width:100%;font:inherit;padding:12px;border:1px solid #647686;border-radius:4px;margin:8px 0 16px}label{display:block}#account{font-weight:600;overflow-wrap:anywhere}#status{white-space:pre-line}small{display:block;margin-top:32px;color:#4b6172}[hidden]{display:none!important}
7021
- </style></head><body><main>
7022
- <h1>Connect your Claude subscription</h1>
7023
- <p>This adds your subscription to the shared agents pool. Only connect an account you have permission to share. Your password stays with Claude; the pool stores the authorization needed to run agents.</p>
7024
- <section id="begin"><h2>1. Sign in with Claude</h2><p>You will open Claude in a separate tab. Choose the account you want to share.</p><button id="start" type="button">Connect Claude</button><p><a id="authorize" class="button" target="_blank" rel="noopener noreferrer" hidden>Open Claude sign-in</a></p></section>
7025
- <form id="verify" hidden><h2>2. Check your account</h2><label for="code">Paste the authorization code from Claude</label><input id="code" type="password" autocomplete="off" spellcheck="false" required maxlength="4096"><button type="submit">Check account</button></form>
7026
- <form id="confirm" hidden><h2>3. Add this subscription</h2><p>Claude verified this account:</p><p id="account"></p><label><input id="consent" type="checkbox" required> I authorize the shared agents pool to use this subscription.</label><p><button type="submit">Add subscription to pool</button></p><p>Wrong account? Do not confirm. Close this page and ask the operator for a new link.</p></form>
7027
- <section id="connected" hidden><h2>Subscription connected</h2><p id="connected-account"></p><p>Testing this flow? Disconnect removes this seat's saved credentials and pool membership before letting you sign in again.</p><button id="disconnect" type="button">Disconnect and try again</button><p>Keep this page open to disconnect. This button expires after 24 hours; a page reload or server restart requires operator help. It does not sign you out of Claude's website, cancel your subscription, or stop a request already running.</p></section>
7028
- <p id="status" role="status" aria-live="polite"></p>
7029
- <small>This private link works once. After starting, each step expires in 10 minutes. Do not share this link or paste authorization codes into chat. Reloading this page requires a new invitation.</small>
7030
- <noscript>JavaScript is required for this private sign-in flow.</noscript>
7031
- </main><script nonce="${nonce}">
7057
+ <style nonce="${nonce}">${styles}</style></head><body>
7058
+ <header>Shared agents pool<small>Connect a Claude subscription</small><div class="bar"><span id="progress"></span></div></header>
7059
+ <main>
7060
+ <ol id="stepper" aria-label="Progress">
7061
+ <li data-step="email"><span class="dot">1</span><span class="label">Email</span></li>
7062
+ <li data-step="signin"><span class="dot">2</span><span class="label">Sign in</span></li>
7063
+ <li data-step="code"><span class="dot">3</span><span class="label">Paste code</span></li>
7064
+ <li data-step="confirm"><span class="dot">4</span><span class="label">Confirm</span></li>
7065
+ <li data-step="done"><span class="dot">5</span><span class="label">Done</span></li>
7066
+ </ol>
7067
+ <section class="card" id="step-email" hidden>
7068
+ <div class="avatar">${icon("mail")}</div>
7069
+ <h1 tabindex="-1">Connect your Claude subscription</h1>
7070
+ <p class="lead">This adds your subscription to the shared agents pool. Start with your work email: if it is on this pool's list, the next step lets you sign in with Claude.</p>
7071
+ <form id="request">
7072
+ <p class="notice err" id="email-error" role="alert" hidden></p>
7073
+ <label for="email">Work email<input id="email" type="email" autocomplete="email" spellcheck="false" required maxlength="254"></label>
7074
+ <button class="button" type="submit">Continue</button>
7075
+ </form>
7076
+ </section>
7077
+ <section class="card" id="step-signin" hidden>
7078
+ <p class="notice" id="signin-notice" role="status" hidden></p>
7079
+ <div class="avatar">${icon("key")}</div>
7080
+ <h1 tabindex="-1">Sign in with Claude</h1>
7081
+ <p class="lead" id="signin-for" hidden>Use the Claude account of <strong id="signin-email"></strong>. Only connect an account you have permission to share.</p>
7082
+ <ul class="facts">
7083
+ <li>Claude opens in a new tab. Sign in and pick the account to share.</li>
7084
+ <li>Your password stays with Claude. The pool only keeps the authorization it needs to run agents.</li>
7085
+ <li>Claude then shows a code: you paste it here in the next step.</li>
7086
+ </ul>
7087
+ <button class="button" id="start" type="button">Continue to Claude ${icon("open")}</button>
7088
+ </section>
7089
+ <section class="card" id="step-code" hidden>
7090
+ <div class="avatar">${icon("code")}</div>
7091
+ <h1 tabindex="-1">Paste the code from Claude</h1>
7092
+ <p class="lead" id="code-lead">Claude opened in a new tab. Once you have signed in, it shows an authorization code: copy it and paste it below.</p>
7093
+ <form id="verify">
7094
+ <label for="code">Authorization code<input id="code" type="password" autocomplete="off" spellcheck="false" required maxlength="4096"><span class="hint">The code stays hidden on screen. Never paste it into chat.</span></label>
7095
+ <button class="button" type="submit">Verify account</button>
7096
+ </form>
7097
+ <p class="aside">Closed the Claude tab? <a class="link" id="reopen" target="_blank" rel="noopener noreferrer">Open Claude sign-in again ${icon("open")}</a></p>
7098
+ </section>
7099
+ <section class="card" id="step-confirm" hidden>
7100
+ <div class="avatar">${icon("person")}</div>
7101
+ <h1 tabindex="-1">Is this the right account?</h1>
7102
+ <p class="lead">Claude verified the account below. Check it before adding it to the pool.</p>
7103
+ <form id="confirm">
7104
+ <div class="account">${icon("check")}<span id="account"></span></div>
7105
+ <label class="consent"><input id="consent" type="checkbox" required><span>I authorize the shared agents pool to use this subscription.</span></label>
7106
+ <button class="button" type="submit">Add to the pool</button>
7107
+ </form>
7108
+ <p class="aside">Wrong account? Do not confirm: start again and sign in with the right one.<a class="button secondary" href="/pool-enroll">Start again</a></p>
7109
+ </section>
7110
+ <section class="card" id="step-done" hidden>
7111
+ <div class="avatar ok">${icon("check")}</div>
7112
+ <h1 tabindex="-1">Subscription connected</h1>
7113
+ <p class="lead"><strong id="connected-account"></strong> is now part of the shared agents pool. You can close this page.</p>
7114
+ <div class="aside"><strong>Changed your mind?</strong> Disconnect removes this account's saved authorization and pool membership. It stays available for 24 hours while this page is open; it does not sign you out of Claude or cancel your subscription.<button class="button secondary" id="disconnect" type="button">Disconnect</button></div>
7115
+ </section>
7116
+ <section class="card" id="step-error" hidden>
7117
+ <div class="avatar err">${icon("alert")}</div>
7118
+ <h1 tabindex="-1">This sign-in can't continue</h1>
7119
+ <p class="lead" id="error-message"></p>
7120
+ <p class="aside">Nothing was added to the pool from this step.<a class="button secondary" href="/pool-enroll">Start again</a></p>
7121
+ </section>
7122
+ <p id="status" class="notice err" role="alert" hidden></p>
7123
+ </main>
7124
+ <footer>Each step expires after 10 minutes. Nothing is added to the pool until you confirm.</footer>
7125
+ <noscript><p class="notice err">JavaScript is required for this sign-in.</p></noscript>
7126
+ <script nonce="${nonce}">
7032
7127
  let token = location.hash.slice(1);
7033
7128
  history.replaceState(null, '', location.pathname);
7034
7129
  addEventListener('hashchange', () => { if (location.hash) location.reload(); });
7035
7130
  const get = id => document.getElementById(id);
7036
- const status = get('status');
7037
- async function post(step, values) {
7038
- const response = await fetch('/pool-enroll/' + step, {method:'POST', credentials:'omit', cache:'no-store', redirect:'error', headers:{'content-type':'application/json'}, body:JSON.stringify({token, ...values})});
7131
+ const steps = ['email', 'signin', 'code', 'confirm', 'done'];
7132
+ let current = 'email';
7133
+ function show(step) {
7134
+ const failed = step === 'error';
7135
+ const index = steps.indexOf(failed ? current : step);
7136
+ if (!failed) current = step;
7137
+ for (const name of [...steps, 'error']) get('step-' + name).hidden = name !== step;
7138
+ document.querySelectorAll('#stepper li').forEach((item, position) => {
7139
+ item.className = position < index || step === 'done' ? 'done' : position === index ? (failed ? 'failed' : 'active') : '';
7140
+ item.querySelector('.dot').innerHTML = item.className === 'done' ? '${icon("check")}' : String(position + 1);
7141
+ if (position === index) item.setAttribute('aria-current', 'step'); else item.removeAttribute('aria-current');
7142
+ });
7143
+ get('progress').style.width = Math.max(5, ((index + (step === 'done' ? 1 : 0)) / steps.length) * 100) + '%';
7144
+ (step === 'email' ? get('email') : get('step-' + step).querySelector('h1')).focus();
7145
+ }
7146
+ async function send(step, body) {
7147
+ const response = await fetch('/pool-enroll/' + step, {method:'POST', credentials:'omit', cache:'no-store', redirect:'error', headers:{'content-type':'application/json'}, body:JSON.stringify(body)});
7039
7148
  const data = await response.json();
7040
- if (!response.ok) throw new Error(data.error || 'Sign-in failed. Ask the operator for a new link.');
7149
+ if (!response.ok) throw new Error(data.error || 'Sign-in failed. Start again.');
7041
7150
  token = data.token || '';
7042
7151
  return data;
7043
7152
  }
7153
+ const post = (step, values) => send(step, {token, ...values});
7044
7154
  function fail(error) {
7045
- token = ''; get('code').value = ''; get('begin').hidden = true; get('verify').hidden = true; get('confirm').hidden = true;
7046
- status.textContent = error instanceof Error ? error.message : 'Sign-in failed. Ask for a new link.';
7155
+ token = ''; get('code').value = '';
7156
+ get('error-message').textContent = error instanceof Error ? error.message : 'Sign-in failed. Start again.';
7157
+ show('error');
7047
7158
  }
7048
- if (!/^[A-Za-z0-9_-]{43}$/.test(token)) fail(new Error('Open the private invitation link supplied by your pool operator.'));
7159
+ show(/^[A-Za-z0-9_-]{43}$/.test(token) ? 'signin' : 'email');
7160
+ get('request').addEventListener('submit', async event => {
7161
+ event.preventDefault(); event.submitter.disabled = true; get('email-error').hidden = true;
7162
+ try {
7163
+ const data = await send('request', {email: get('email').value});
7164
+ get('signin-email').textContent = data.email; get('signin-for').hidden = false;
7165
+ show('signin');
7166
+ } catch (error) {
7167
+ get('email-error').textContent = error instanceof Error ? error.message : 'This email cannot connect. Ask the operator.';
7168
+ get('email-error').hidden = false; get('email').focus();
7169
+ } finally { event.submitter.disabled = false; }
7170
+ });
7049
7171
  get('start').addEventListener('click', async () => {
7172
+ const tab = window.open('', '_blank');
7050
7173
  get('start').disabled = true;
7051
7174
  try {
7052
7175
  const data = await post('start', {});
7053
7176
  const url = new URL(data.authUrl);
7054
- if (url.origin !== 'https://claude.ai' || url.pathname !== '/oauth/authorize') throw new Error('Invalid sign-in destination. Ask the operator for help.');
7055
- get('authorize').href = url.href; get('authorize').hidden = false; get('start').hidden = true;
7056
- get('verify').hidden = false; status.textContent = 'Open Claude sign-in above, then return here with the code.';
7057
- } catch(error) { fail(error); }
7177
+ if (url.origin !== 'https://claude.ai' || url.pathname !== '/oauth/authorize') throw new Error('Invalid sign-in destination. Ask for help.');
7178
+ get('reopen').href = url.href;
7179
+ if (tab) { tab.opener = null; tab.location.href = url.href; }
7180
+ else get('code-lead').textContent = 'Your browser blocked the new tab. Open Claude sign-in with the link below, sign in, then paste the code it shows.';
7181
+ show('code');
7182
+ } catch (error) { if (tab) tab.close(); fail(error); }
7058
7183
  });
7059
7184
  get('verify').addEventListener('submit', async event => {
7060
- event.preventDefault(); const button = event.submitter; button.disabled = true;
7185
+ event.preventDefault(); event.submitter.disabled = true;
7061
7186
  const code = get('code').value.trim(); get('code').value = '';
7062
- try { const data = await post('verify', {code}); get('begin').hidden = true; get('verify').hidden = true; get('account').textContent = data.email; get('confirm').hidden = false; status.textContent = 'Check the account above before confirming.'; }
7063
- catch(error) { fail(error); }
7187
+ try { const data = await post('verify', {code}); get('account').textContent = data.email; show('confirm'); }
7188
+ catch (error) { fail(error); }
7064
7189
  });
7065
7190
  get('confirm').addEventListener('submit', async event => {
7066
7191
  event.preventDefault(); if (!get('consent').checked) return; event.submitter.disabled = true;
7067
- try { await post('confirm', {consent:true}); get('confirm').hidden = true; get('connected-account').textContent = get('account').textContent; get('connected').hidden = false; status.textContent = 'Subscription connected. If you are testing, disconnect before closing this page.'; }
7068
- catch(error) { fail(error); }
7192
+ try { await post('confirm', {consent:true}); get('connected-account').textContent = get('account').textContent; show('done'); }
7193
+ catch (error) { fail(error); }
7069
7194
  });
7070
7195
  get('disconnect').addEventListener('click', async () => {
7071
- get('disconnect').disabled = true;
7196
+ get('disconnect').disabled = true; get('status').hidden = true;
7072
7197
  try {
7073
7198
  await post('disconnect', {});
7074
- get('connected').hidden = true; get('connected-account').textContent = ''; get('account').textContent = '';
7075
- get('consent').checked = false; get('code').value = '';
7076
- get('authorize').removeAttribute('href'); get('authorize').hidden = true;
7199
+ get('account').textContent = ''; get('connected-account').textContent = ''; get('consent').checked = false;
7077
7200
  document.querySelectorAll('button').forEach(button => { button.disabled = false; });
7078
- get('start').hidden = false; get('begin').hidden = false;
7079
- status.textContent = 'Subscription disconnected. It is no longer in the pool. You can close this page or connect again.';
7080
- } catch(error) {
7201
+ get('signin-notice').textContent = 'Subscription disconnected: it is no longer in the pool. You can connect again or close this page.';
7202
+ get('signin-notice').hidden = false;
7203
+ show('signin');
7204
+ } catch (error) {
7081
7205
  get('disconnect').disabled = false;
7082
- status.textContent = 'Removal is not confirmed. ' + (error instanceof Error ? error.message : 'Keep this page open and ask the operator to check this seat.');
7206
+ get('status').textContent = 'Removal is not confirmed. ' + (error instanceof Error ? error.message : 'Keep this page open and ask for help with this seat.');
7207
+ get('status').hidden = false;
7083
7208
  }
7084
7209
  });
7085
7210
  </script></body></html>`, {
@@ -7093,7 +7218,61 @@ get('disconnect').addEventListener('click', async () => {
7093
7218
  }
7094
7219
  });
7095
7220
  }
7096
- var init_enrollment_page = () => {};
7221
+ var icons, icon = (name) => `<svg viewBox="0 0 24 24" aria-hidden="true">${icons[name]}</svg>`, styles = `
7222
+ :root{--page:#faf9f6;--card:#fff;--text:#191b21;--muted:#5a606b;--faint:#9aa0ab;--line:#e6e8ec;--border:rgba(25,27,33,.14);--brand:#fb5d22;--accent:#dc5518;--tint:#fff3ec;--ink:#182025;--ink-hover:#2a333b;--ok:#17a06b;--ok-bg:#e3f6ed;--ok-text:#0c6444;--err:#d92d20;--err-bg:#fef3f2;--err-text:#912018;color-scheme:light;font:15px/1.55 "Public Sans",ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;color:var(--text);background:var(--page)}
7223
+ *{box-sizing:border-box}body{margin:0;min-height:100vh}
7224
+ header{position:relative;background:#fff;border-bottom:1px solid var(--line);padding:16px clamp(16px,4vw,32px);font-weight:600}
7225
+ header small{display:block;font-weight:400;color:var(--muted);font-size:13px}
7226
+ .bar{position:absolute;left:0;right:0;bottom:-1px;height:4px;background:#f2f1ec}.bar span{display:block;height:100%;width:5%;background:var(--ink);transition:width .3s ease-in-out}
7227
+ main{max-width:560px;margin:0 auto;padding:32px 16px 48px}
7228
+ ol{list-style:none;display:flex;margin:0 0 28px;padding:0}
7229
+ ol li{flex:1;display:flex;flex-direction:column;align-items:center;gap:6px;position:relative;font-size:13px;color:var(--faint)}
7230
+ ol li+li::before{content:"";position:absolute;top:15px;right:calc(50% + 20px);width:calc(100% - 40px);height:2px;background:var(--line)}
7231
+ ol li.done+li::before{background:var(--ok-text)}
7232
+ ol .dot{width:32px;height:32px;border-radius:50%;display:grid;place-items:center;font-weight:600;background:var(--line);color:var(--faint);border:2px solid var(--line)}
7233
+ ol .dot svg{width:16px;height:16px;stroke:#fff;stroke-width:3}
7234
+ ol li.active{color:var(--accent);font-weight:600}ol li.active .dot{background:var(--brand);border-color:var(--brand);color:#fff}
7235
+ ol li.done{color:var(--muted)}ol li.done .dot{background:var(--ok);border-color:var(--ok)}
7236
+ ol li.failed .dot{background:var(--err);border-color:var(--err);color:#fff}
7237
+ .card{background:var(--card);border-radius:16px;box-shadow:0 1px 2px rgba(16,18,24,.05);border:1px solid rgba(25,27,33,.08);padding:clamp(24px,5vw,40px);text-align:center}
7238
+ .avatar{width:64px;height:64px;margin:0 auto 16px;border-radius:50%;display:grid;place-items:center;background:var(--tint)}
7239
+ .avatar svg,.button svg{width:28px;height:28px;fill:none;stroke:var(--accent);stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
7240
+ .avatar.ok{background:var(--ok-bg)}.avatar.ok svg{stroke:var(--ok-text);stroke-width:2.4}.avatar.err{background:var(--err-bg)}.avatar.err svg{stroke:var(--err)}
7241
+ h1{font-size:22px;line-height:1.3;margin:0 0 8px;outline:none}
7242
+ .lead{color:var(--muted);margin:0 auto 24px;max-width:42ch}
7243
+ .facts{list-style:none;padding:0;margin:0 0 28px;text-align:left;display:grid;gap:10px}
7244
+ .facts li{display:flex;gap:10px;align-items:flex-start}.facts li::before{content:"";flex:none;width:6px;height:6px;margin-top:9px;border-radius:50%;background:var(--brand)}
7245
+ .button{font:inherit;font-weight:600;display:inline-flex;align-items:center;justify-content:center;gap:8px;width:100%;min-height:44px;padding:10px 16px;border-radius:9px;border:0;background:var(--ink);color:#fff;cursor:pointer;text-decoration:none}
7246
+ .button:hover{background:var(--ink-hover);box-shadow:0 6px 18px -6px rgb(24 32 37/.5)}.button svg{width:18px;height:18px;stroke:currentColor}
7247
+ .button.secondary{background:#fff;color:var(--text);border:1px solid var(--border)}.button.secondary:hover{box-shadow:0 1px 3px rgba(47,43,67,.12)}
7248
+ .button:disabled{opacity:.5;cursor:progress;box-shadow:none}
7249
+ .button:focus-visible,input:focus-visible,a:focus-visible{outline:3px solid var(--brand);outline-offset:3px}
7250
+ .link{display:inline-flex;align-items:center;gap:6px;color:var(--accent);font-weight:600;text-decoration:none}.link svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:2}
7251
+ form{text-align:left;display:grid;gap:16px}label{font-weight:600}
7252
+ input[type=password],input[type=email]{display:block;width:100%;font:inherit;padding:11px 12px;margin-top:6px;border:1px solid var(--border);border-radius:9px;background:#fff}
7253
+ .hint{font-size:13px;color:var(--muted);margin:6px 0 0;font-weight:400}
7254
+ .account{display:flex;align-items:center;gap:12px;padding:14px 16px;border-radius:12px;background:var(--page);border:1px solid rgba(25,27,33,.08);font-weight:600;overflow-wrap:anywhere}
7255
+ .account svg{flex:none;width:22px;height:22px;fill:none;stroke:var(--ok-text);stroke-width:2.4}
7256
+ .consent{display:flex;gap:10px;align-items:flex-start;font-weight:400}.consent input{width:18px;height:18px;margin:2px 0 0;accent-color:var(--ink)}
7257
+ .notice{border-radius:12px;padding:12px 16px;margin:0 0 20px;text-align:left;background:var(--ok-bg);color:var(--ok-text)}
7258
+ .notice.err{background:var(--err-bg);color:var(--err-text)}
7259
+ .aside{margin-top:24px;padding-top:20px;border-top:1px solid var(--line);text-align:left;color:var(--muted);font-size:14px}
7260
+ .aside .button{margin-top:12px}
7261
+ footer{max-width:560px;margin:0 auto;padding:0 16px 32px;color:var(--muted);font-size:13px;text-align:center}
7262
+ @media (max-width:480px){ol li:not(.active) .label{display:none}}
7263
+ [hidden]{display:none!important}
7264
+ `;
7265
+ var init_enrollment_page = __esm(() => {
7266
+ icons = {
7267
+ mail: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>',
7268
+ key: '<path d="M15 7.5a3.5 3.5 0 1 1-3.4 4.3L4 19.5V22h3v-2h2v-2h2l1.2-1.2A3.5 3.5 0 0 1 15 7.5Z"/><circle cx="16" cy="11" r="1"/>',
7269
+ code: '<rect x="4" y="6" width="16" height="12" rx="2"/><path d="M8 10h.01M12 10h.01M16 10h.01M8 14h8"/>',
7270
+ person: '<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>',
7271
+ check: '<path d="m5 12.5 4.5 4.5L19 7.5"/>',
7272
+ alert: '<path d="M12 8v5M12 16.5h.01"/><circle cx="12" cy="12" r="9"/>',
7273
+ open: '<path d="M14 5h5v5M19 5l-8 8M18 14v4a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h4"/>'
7274
+ };
7275
+ });
7097
7276
 
7098
7277
  // ../../packages/api/src/handlers/enrollment.ts
7099
7278
  import { createHash, randomBytes as randomBytes2 } from "crypto";
@@ -7135,13 +7314,59 @@ class EnrollmentHandlers {
7135
7314
  return await action();
7136
7315
  } catch (error) {
7137
7316
  return error instanceof EnrollmentError ? json({ error: error.message }, error.status) : json({
7138
- error: "Enrollment could not be saved. Ask the operator to check the seat and issue a new link."
7317
+ error: "Enrollment could not be saved. Ask the operator to check the seat."
7139
7318
  }, 500);
7140
7319
  }
7141
7320
  }
7142
- issue = (req) => this.guarded(async () => {
7321
+ requireClaudeCode() {
7143
7322
  if (!this.context.providerRegistry.getOAuthProvider("claude-code"))
7144
7323
  throw new EnrollmentError(400, "Provider 'claude-code' is disabled. Set providers.claude-code.enabled to true in your config.");
7324
+ }
7325
+ reserve(name) {
7326
+ if (this.context.dbOps.getAccountByName(name))
7327
+ throw new EnrollmentError(409, "This seat is already in the pool.");
7328
+ for (const entry of this.entries.values())
7329
+ if (entry.details.name === name && entry.state.kind === "busy")
7330
+ throw new EnrollmentError(409, "Sign-in is already in progress");
7331
+ for (const [key, entry] of this.entries)
7332
+ if (entry.details.name === name)
7333
+ this.entries.delete(key);
7334
+ if (this.entries.size >= 100)
7335
+ throw new EnrollmentError(429, "Too many pending invitations");
7336
+ }
7337
+ request(body) {
7338
+ this.requireClaudeCode();
7339
+ if (Object.keys(body).some((key) => key !== "email"))
7340
+ throw new EnrollmentError(400, "Unknown request field");
7341
+ const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
7342
+ if (!this.context.config.getEnrollmentEmails().includes(email))
7343
+ throw new EnrollmentError(403, "This email is not on the list. Ask the operator to add it.");
7344
+ const name = email.slice(0, email.indexOf("@")).replace(/[^a-z0-9._+-]/g, "-").slice(0, 64);
7345
+ this.reserve(name);
7346
+ const issued = this.mint({ name, email, contactEmail: email }, { kind: "invited" }, tenMinutes);
7347
+ return json({ ...issued, email });
7348
+ }
7349
+ emails = (req) => this.guarded(async () => {
7350
+ const body = await readBody(req);
7351
+ const lists = Object.entries(body);
7352
+ if (lists.some(([key, value]) => key !== "add" && key !== "remove" || !Array.isArray(value) || value.some((email) => typeof email !== "string")))
7353
+ throw new EnrollmentError(400, "Expected { add?: string[], remove?: string[] }");
7354
+ const { config } = this.context;
7355
+ const add = body.add ?? [];
7356
+ const remove = new Set((body.remove ?? []).map((email) => email.trim().toLowerCase()));
7357
+ if (add.length === 0 && remove.size === 0)
7358
+ return json({ emails: config.getEnrollmentEmails() });
7359
+ const next = [...config.getEnrollmentEmails(), ...add].filter((email) => !remove.has(email.trim().toLowerCase()));
7360
+ try {
7361
+ return json({ emails: config.setEnrollmentEmails(next) });
7362
+ } catch (error) {
7363
+ if (error instanceof ValidationError)
7364
+ throw new EnrollmentError(400, error.message);
7365
+ throw error;
7366
+ }
7367
+ });
7368
+ issue = (req) => this.guarded(async () => {
7369
+ this.requireClaudeCode();
7145
7370
  const input = await readBody(req);
7146
7371
  const allowed = new Set(["name", "email", "contactEmail", "slackUserId"]);
7147
7372
  if (Object.keys(input).some((key) => !allowed.has(key)))
@@ -7164,16 +7389,7 @@ class EnrollmentHandlers {
7164
7389
  }
7165
7390
  if (details.name.length > 80 || details.slackUserId && !/^U[A-Z0-9]{8,20}$/.test(details.slackUserId) || [details.email, details.contactEmail].some((email) => email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)))
7166
7391
  throw new EnrollmentError(400, "Invalid invitation details");
7167
- if (this.context.dbOps.getAccountByName(details.name))
7168
- throw new EnrollmentError(409, "Seat already exists");
7169
- for (const entry of this.entries.values())
7170
- if (entry.details.name === details.name && entry.state.kind === "busy")
7171
- throw new EnrollmentError(409, "Sign-in is already in progress");
7172
- for (const [key, entry] of this.entries)
7173
- if (entry.details.name === details.name)
7174
- this.entries.delete(key);
7175
- if (this.entries.size >= 100)
7176
- throw new EnrollmentError(429, "Too many pending invitations");
7392
+ this.reserve(details.name);
7177
7393
  const issued = this.mint(details, { kind: "invited" }, oneDay);
7178
7394
  return json({
7179
7395
  url: `${this.origin.origin}/pool-enroll#${issued.token}`,
@@ -7195,12 +7411,14 @@ class EnrollmentHandlers {
7195
7411
  if (req.headers.get("origin") !== this.origin.origin)
7196
7412
  throw new EnrollmentError(403, "Untrusted enrollment origin");
7197
7413
  const body = await readBody(req);
7414
+ if (url.pathname === "/pool-enroll/request")
7415
+ return this.request(body);
7198
7416
  const token = typeof body.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(body.token) ? body.token : "";
7199
7417
  const key = hash(token);
7200
7418
  const entry = this.entries.get(key);
7201
7419
  const expected = url.pathname === "/pool-enroll/start" ? "invited" : url.pathname === "/pool-enroll/verify" ? "started" : url.pathname === "/pool-enroll/confirm" ? "verified" : "connected";
7202
7420
  if (!entry || entry.expiresAt <= this.now() || entry.state.kind !== expected)
7203
- throw new EnrollmentError(410, "This link has expired or was already used. Ask the operator for a new link.");
7421
+ throw new EnrollmentError(410, "This sign-in has expired or was already used. Start again.");
7204
7422
  const state = entry.state;
7205
7423
  entry.state = { kind: "busy" };
7206
7424
  try {
@@ -7219,12 +7437,12 @@ class EnrollmentHandlers {
7219
7437
  try {
7220
7438
  seat = await this.oauth.verifyClaudeSeat(state.flow, body.code.trim());
7221
7439
  } catch {
7222
- throw new EnrollmentError(400, "Claude sign-in could not be verified. Ask for a new link and try again.");
7440
+ throw new EnrollmentError(400, "Claude sign-in could not be verified. Start again.");
7223
7441
  }
7224
7442
  this.assertCurrent(key, entry);
7225
7443
  const { email } = seat.identity;
7226
7444
  if (!email || entry.details.email && email.toLowerCase() !== entry.details.email.toLowerCase())
7227
- throw new EnrollmentError(400, "This Claude account does not match the invitation. Ask for a new link.");
7445
+ throw new EnrollmentError(400, "This Claude account does not match your email. Start again and sign in with the matching account.");
7228
7446
  this.assertNewSeat(entry.details.name, seat);
7229
7447
  return json({
7230
7448
  ...this.mint(entry.details, { kind: "verified", seat }, tenMinutes),
@@ -7267,7 +7485,7 @@ class EnrollmentHandlers {
7267
7485
  }
7268
7486
  assertCurrent(key, entry) {
7269
7487
  if (this.entries.get(key) !== entry || entry.expiresAt <= this.now())
7270
- throw new EnrollmentError(410, "Sign-in expired. Ask for a new link.");
7488
+ throw new EnrollmentError(410, "Sign-in expired. Start again.");
7271
7489
  }
7272
7490
  assertNewSeat(name, seat) {
7273
7491
  if (this.context.dbOps.getAccountByName(name) || this.context.dbOps.getAccountsByProvider("claude-code").some((account2) => account2.account_uuid === seat.identity.accountUuid))
@@ -7347,11 +7565,13 @@ async function readBody(req) {
7347
7565
  }
7348
7566
  var paths, tenMinutes = 600000, oneDay = 86400000, headers2, json = (value, status = 200) => Response.json(value, { status, headers: headers2 }), hash = (token) => createHash("sha256").update(token).digest("hex"), EnrollmentError;
7349
7567
  var init_enrollment = __esm(() => {
7568
+ init_src2();
7350
7569
  init_src8();
7351
7570
  init_src();
7352
7571
  init_enrollment_page();
7353
7572
  paths = new Set([
7354
7573
  "/pool-enroll",
7574
+ "/pool-enroll/request",
7355
7575
  "/pool-enroll/start",
7356
7576
  "/pool-enroll/verify",
7357
7577
  "/pool-enroll/confirm",
@@ -7768,8 +7988,10 @@ class APIRouter {
7768
7988
  this.registerHandlers();
7769
7989
  }
7770
7990
  registerHandlers() {
7771
- if (this.enrollment)
7991
+ if (this.enrollment) {
7772
7992
  this.staticHandlers.set("POST:/api/enrollment-invitations", this.enrollment.issue);
7993
+ this.staticHandlers.set("POST:/api/enrollment-emails", this.enrollment.emails);
7994
+ }
7773
7995
  const { config, dbOps, getProviders, getRuntimeHealth, providerRegistry } = this.context;
7774
7996
  const healthHandler = createHealthHandler(dbOps, config, getProviders, getRuntimeHealth);
7775
7997
  const statsHandler = createStatsHandler(dbOps);
@@ -7960,6 +8182,50 @@ var init_background_tasks = __esm(() => {
7960
8182
  backgroundTasks = new Set;
7961
8183
  });
7962
8184
 
8185
+ // ../../packages/proxy/src/seat-usage.ts
8186
+ function liveUtilization(window2, now) {
8187
+ if (window2.utilization === null)
8188
+ return 0;
8189
+ const windowOpen = window2.resetAt === null ? isCurrentQuotaWindow(window2, now) : window2.resetAt > now;
8190
+ return windowOpen ? window2.utilization : 0;
8191
+ }
8192
+ function isAheadOfWeeklyPace(window2, now) {
8193
+ if (window2.resetAt === null || window2.resetAt <= now)
8194
+ return false;
8195
+ const elapsedShareOfWeek = 1 - (window2.resetAt - now) / WEEK_MS;
8196
+ return liveUtilization(window2, now) > elapsedShareOfWeek;
8197
+ }
8198
+ function highestUtilization(windows, now) {
8199
+ return Math.max(0, ...windows.map(([, window2]) => liveUtilization(window2, now)));
8200
+ }
8201
+ function seatUsage(provider, account2, model, now) {
8202
+ const buckets = provider.quotaBucketsFor(model);
8203
+ const windows = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket]) => buckets?.includes(bucket) ?? true);
8204
+ const weekly = windows.filter(([bucket]) => provider.isWeeklyBucket(bucket));
8205
+ const fiveHour = windows.filter(([bucket]) => provider.isFiveHourBucket(bucket));
8206
+ return {
8207
+ aheadOfWeeklyPace: weekly.some(([, window2]) => isAheadOfWeeklyPace(window2, now)),
8208
+ fiveHour: highestUtilization(fiveHour, now),
8209
+ weekly: highestUtilization(weekly, now)
8210
+ };
8211
+ }
8212
+ function soonestWeeklyReset(provider, account2, now) {
8213
+ const resets = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => provider.isWeeklyBucket(bucket) && window2.resetAt !== null && window2.resetAt > now).map(([, window2]) => window2.resetAt);
8214
+ return Math.min(...resets, Number.POSITIVE_INFINITY);
8215
+ }
8216
+ function compareSeatUsage(provider, model, now) {
8217
+ return (left, right) => {
8218
+ const a = seatUsage(provider, left, model, now);
8219
+ const b = seatUsage(provider, right, model, now);
8220
+ return Number(a.aheadOfWeeklyPace) - Number(b.aheadOfWeeklyPace) || a.fiveHour - b.fiveHour || a.weekly - b.weekly || soonestWeeklyReset(provider, left, now) - soonestWeeklyReset(provider, right, now);
8221
+ };
8222
+ }
8223
+ var WEEK_MS;
8224
+ var init_seat_usage = __esm(() => {
8225
+ init_src();
8226
+ WEEK_MS = 7 * 24 * 60 * 60 * 1000;
8227
+ });
8228
+
7963
8229
  // ../../packages/proxy/src/team-router.ts
7964
8230
  import { createHash as createHash2 } from "crypto";
7965
8231
  function isRecord5(value) {
@@ -8018,7 +8284,7 @@ class TeamRouter {
8018
8284
  }
8019
8285
  if (!config.distributionEnabled || !key)
8020
8286
  return eligible;
8021
- const selected = this.leastLoadedPriorityAccount(eligible, store?.countConversationPinsByAccount(now - PIN_TTL_MS));
8287
+ const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider, request2.model, now), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
8022
8288
  this.touchPin(key, selected.id, now, store);
8023
8289
  return [
8024
8290
  selected,
@@ -8064,18 +8330,10 @@ class TeamRouter {
8064
8330
  return persistedCounts.get(accountId) ?? 0;
8065
8331
  return [...this.pins.values()].filter((pin) => pin.accountId === accountId).length;
8066
8332
  }
8067
- leastLoadedPriorityAccount(accounts, persistedCounts) {
8333
+ leastUsedPriorityAccount(accounts, byUsage, persistedCounts) {
8068
8334
  const priority = Math.min(...accounts.map((account2) => account2.priority ?? 0));
8069
8335
  const tier = accounts.filter((account2) => (account2.priority ?? 0) === priority);
8070
- return [...tier].sort((left, right) => {
8071
- const activeDifference = this.activePins(left.id, persistedCounts) - this.activePins(right.id, persistedCounts);
8072
- if (activeDifference !== 0)
8073
- return activeDifference;
8074
- const inFlightDifference = (this.inFlight.get(left.id) ?? 0) - (this.inFlight.get(right.id) ?? 0);
8075
- if (inFlightDifference !== 0)
8076
- return inFlightDifference;
8077
- return left.name.localeCompare(right.name);
8078
- })[0];
8336
+ return [...tier].sort((left, right) => byUsage(left, right) || this.activePins(left.id, persistedCounts) - this.activePins(right.id, persistedCounts) || (this.inFlight.get(left.id) ?? 0) - (this.inFlight.get(right.id) ?? 0) || left.name.localeCompare(right.name))[0];
8079
8337
  }
8080
8338
  removeExpiredPins(now, store) {
8081
8339
  for (const [key, pin] of this.pins) {
@@ -8091,6 +8349,7 @@ class TeamRouter {
8091
8349
  }
8092
8350
  var MAX_OPENING_BYTES, PIN_TTL_MS;
8093
8351
  var init_team_router = __esm(() => {
8352
+ init_seat_usage();
8094
8353
  MAX_OPENING_BYTES = 64 * 1024;
8095
8354
  PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
8096
8355
  });
@@ -8138,13 +8397,6 @@ function getSoonestQuotaReset(meta, ctx, now = Date.now()) {
8138
8397
  const resets = ctx.dbOps.getAvailableAccountsByProvider(ctx.providerName).flatMap((account2) => Object.entries(account2.quota_state?.windows ?? {}).map(([bucket, window2]) => ({ account: account2, bucket, window: window2 }))).filter(({ account: account2, bucket, window: window2 }) => window2.resetAt !== null && window2.resetAt > now && isQuotaBlocking(ctx.provider, account2, bucket, window2, ctx.runtime.quotaThreshold, now, meta.model, pooledMaxUsage(account2, ctx))).map(({ window: window2 }) => window2.resetAt);
8139
8398
  return resets.length > 0 ? Math.min(...resets) : null;
8140
8399
  }
8141
- function soonestWeeklyReset(provider, account2, now) {
8142
- const windows = account2.quota_state?.windows ?? {};
8143
- const resets = Object.entries(windows).filter(([name, window2]) => {
8144
- return provider.isWeeklyBucket(name) && window2.resetAt !== null && window2.resetAt > now;
8145
- }).map(([, window2]) => window2.resetAt);
8146
- return Math.min(...resets, Number.POSITIVE_INFINITY);
8147
- }
8148
8400
  function selectRevalidationProbe(accounts, ctx, now) {
8149
8401
  const probes = ctx.quotaProbeAt;
8150
8402
  const lastProbeAt = probes?.get(ctx.providerName);
@@ -8177,6 +8429,7 @@ function selectAccountsForRequest(meta, ctx, teamRequest, options) {
8177
8429
  var QUOTA_PROBE_INTERVAL_MS = 60000;
8178
8430
  var init_account_selector = __esm(() => {
8179
8431
  init_src();
8432
+ init_seat_usage();
8180
8433
  init_team_router();
8181
8434
  });
8182
8435