@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/server.js CHANGED
@@ -1386,6 +1386,9 @@ class BaseProvider {
1386
1386
  isWeeklyBucket(_bucket) {
1387
1387
  return false;
1388
1388
  }
1389
+ isFiveHourBucket(_bucket) {
1390
+ return false;
1391
+ }
1389
1392
  getClientSessionId(headers2) {
1390
1393
  return headers2.get("x-claude-code-session-id");
1391
1394
  }
@@ -1623,6 +1626,9 @@ var init_provider = __esm(() => {
1623
1626
  isWeeklyBucket(bucket) {
1624
1627
  return bucket.startsWith("unified7d");
1625
1628
  }
1629
+ isFiveHourBucket(bucket) {
1630
+ return bucket === "unified5h";
1631
+ }
1626
1632
  prepareHeaders(headers2, account2) {
1627
1633
  const newHeaders = new Headers(headers2);
1628
1634
  deleteClientCredentialHeaders(newHeaders);
@@ -2560,6 +2566,9 @@ var init_provider4 = __esm(() => {
2560
2566
  isWeeklyBucket(bucket) {
2561
2567
  return bucket === "unified7d";
2562
2568
  }
2569
+ isFiveHourBucket(bucket) {
2570
+ return bucket === "unified5h";
2571
+ }
2563
2572
  supportsWebSocket(upstreamPath) {
2564
2573
  return upstreamPath === "/responses";
2565
2574
  }
@@ -3831,12 +3840,30 @@ function parseNumber(value) {
3831
3840
  const parsed = Number(value);
3832
3841
  return Number.isFinite(parsed) ? parsed : undefined;
3833
3842
  }
3843
+ function normalizeEnrollmentEmail(value) {
3844
+ if (typeof value !== "string")
3845
+ return;
3846
+ const email = value.trim().toLowerCase();
3847
+ return email.length <= 254 && patterns.email.test(email) ? email : undefined;
3848
+ }
3849
+ function sanitizeEnrollmentEmails(value) {
3850
+ if (!Array.isArray(value))
3851
+ return;
3852
+ const emails = value.map(normalizeEnrollmentEmail).filter((email) => email !== undefined);
3853
+ return [...new Set(emails)].slice(0, MAX_ENROLLMENT_EMAILS);
3854
+ }
3834
3855
  function sanitizeConfigData(value) {
3835
3856
  if (!isRecord(value)) {
3836
3857
  return {};
3837
3858
  }
3838
3859
  const sanitized = {};
3839
3860
  for (const [key, entry] of Object.entries(value)) {
3861
+ if (key === "enrollment_emails") {
3862
+ const emails = sanitizeEnrollmentEmails(entry);
3863
+ if (emails)
3864
+ sanitized.enrollment_emails = emails;
3865
+ continue;
3866
+ }
3840
3867
  if (key === "team_routing") {
3841
3868
  const teamRouting = sanitizeTeamRouting(entry);
3842
3869
  if (teamRouting)
@@ -3986,7 +4013,7 @@ function sanitizeTeamRouting(value) {
3986
4013
  }
3987
4014
  return result;
3988
4015
  }
3989
- var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, Config;
4016
+ var log6, PROVIDER_STRATEGIES, BUILTIN_PROVIDER_CONFIGS, BUILTIN_PROVIDER_CONFIG_BY_NAME, PROVIDER_NAME_PATTERN, TEAM_ROUTING_DEFAULTS, MAX_ENROLLMENT_EMAILS = 200, Config;
3990
4017
  var init_src7 = __esm(() => {
3991
4018
  init_src2();
3992
4019
  init_src4();
@@ -4230,11 +4257,28 @@ var init_src7 = __esm(() => {
4230
4257
  this.persistAccountAllowlist(current.filter((uuid) => uuid !== accountUuid));
4231
4258
  }
4232
4259
  persistAccountAllowlist(accountUuids) {
4233
- const teamRouting = {
4260
+ this.persistStrictly("team_routing", {
4234
4261
  ...this.data.team_routing,
4235
4262
  allowlisted_account_uuids: accountUuids
4236
- };
4237
- const next = { ...this.data, team_routing: teamRouting };
4263
+ });
4264
+ }
4265
+ getEnrollmentEmails() {
4266
+ return [...this.data.enrollment_emails ?? []];
4267
+ }
4268
+ setEnrollmentEmails(emails) {
4269
+ const normalized = emails.map(normalizeEnrollmentEmail);
4270
+ if (normalized.some((email) => email === undefined)) {
4271
+ throw new ValidationError("Invalid enrollment email", "enrollment_emails");
4272
+ }
4273
+ const unique = [...new Set(normalized)];
4274
+ if (unique.length > MAX_ENROLLMENT_EMAILS) {
4275
+ throw new ValidationError(`At most ${MAX_ENROLLMENT_EMAILS} enrollment emails`, "enrollment_emails");
4276
+ }
4277
+ this.persistStrictly("enrollment_emails", unique);
4278
+ return [...unique];
4279
+ }
4280
+ persistStrictly(key, value) {
4281
+ const next = { ...this.data, [key]: value };
4238
4282
  const temporary = `${this.configPath}.${crypto.randomUUID()}.tmp`;
4239
4283
  try {
4240
4284
  writeFileSync(temporary, JSON.stringify(next, null, 2), {
@@ -4245,13 +4289,9 @@ var init_src7 = __esm(() => {
4245
4289
  } finally {
4246
4290
  rmSync(temporary, { force: true });
4247
4291
  }
4248
- const oldValue = this.data.team_routing;
4292
+ const oldValue = this.data[key];
4249
4293
  this.data = next;
4250
- this.emit("change", {
4251
- key: "team_routing",
4252
- oldValue,
4253
- newValue: teamRouting
4254
- });
4294
+ this.emit("change", { key, oldValue, newValue: value });
4255
4295
  }
4256
4296
  getRuntime() {
4257
4297
  const defaults = {
@@ -7013,72 +7053,157 @@ function enrollmentPage() {
7013
7053
  return new Response(`<!doctype html>
7014
7054
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
7015
7055
  <title>Connect a Claude subscription</title>
7016
- <style nonce="${nonce}">
7017
- :root{color-scheme:light;font-family:"Avenir Next",Avenir,"Segoe UI",sans-serif;color:#17334a;background:#edf3f7;line-height:1.6}
7018
- 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}
7019
- 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}
7020
- </style></head><body><main>
7021
- <h1>Connect your Claude subscription</h1>
7022
- <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>
7023
- <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>
7024
- <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>
7025
- <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>
7026
- <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>
7027
- <p id="status" role="status" aria-live="polite"></p>
7028
- <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>
7029
- <noscript>JavaScript is required for this private sign-in flow.</noscript>
7030
- </main><script nonce="${nonce}">
7056
+ <style nonce="${nonce}">${styles}</style></head><body>
7057
+ <header>Shared agents pool<small>Connect a Claude subscription</small><div class="bar"><span id="progress"></span></div></header>
7058
+ <main>
7059
+ <ol id="stepper" aria-label="Progress">
7060
+ <li data-step="email"><span class="dot">1</span><span class="label">Email</span></li>
7061
+ <li data-step="signin"><span class="dot">2</span><span class="label">Sign in</span></li>
7062
+ <li data-step="code"><span class="dot">3</span><span class="label">Paste code</span></li>
7063
+ <li data-step="confirm"><span class="dot">4</span><span class="label">Confirm</span></li>
7064
+ <li data-step="done"><span class="dot">5</span><span class="label">Done</span></li>
7065
+ </ol>
7066
+ <section class="card" id="step-email" hidden>
7067
+ <div class="avatar">${icon("mail")}</div>
7068
+ <h1 tabindex="-1">Connect your Claude subscription</h1>
7069
+ <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>
7070
+ <form id="request">
7071
+ <p class="notice err" id="email-error" role="alert" hidden></p>
7072
+ <label for="email">Work email<input id="email" type="email" autocomplete="email" spellcheck="false" required maxlength="254"></label>
7073
+ <button class="button" type="submit">Continue</button>
7074
+ </form>
7075
+ </section>
7076
+ <section class="card" id="step-signin" hidden>
7077
+ <p class="notice" id="signin-notice" role="status" hidden></p>
7078
+ <div class="avatar">${icon("key")}</div>
7079
+ <h1 tabindex="-1">Sign in with Claude</h1>
7080
+ <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>
7081
+ <ul class="facts">
7082
+ <li>Claude opens in a new tab. Sign in and pick the account to share.</li>
7083
+ <li>Your password stays with Claude. The pool only keeps the authorization it needs to run agents.</li>
7084
+ <li>Claude then shows a code: you paste it here in the next step.</li>
7085
+ </ul>
7086
+ <button class="button" id="start" type="button">Continue to Claude ${icon("open")}</button>
7087
+ </section>
7088
+ <section class="card" id="step-code" hidden>
7089
+ <div class="avatar">${icon("code")}</div>
7090
+ <h1 tabindex="-1">Paste the code from Claude</h1>
7091
+ <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>
7092
+ <form id="verify">
7093
+ <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>
7094
+ <button class="button" type="submit">Verify account</button>
7095
+ </form>
7096
+ <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>
7097
+ </section>
7098
+ <section class="card" id="step-confirm" hidden>
7099
+ <div class="avatar">${icon("person")}</div>
7100
+ <h1 tabindex="-1">Is this the right account?</h1>
7101
+ <p class="lead">Claude verified the account below. Check it before adding it to the pool.</p>
7102
+ <form id="confirm">
7103
+ <div class="account">${icon("check")}<span id="account"></span></div>
7104
+ <label class="consent"><input id="consent" type="checkbox" required><span>I authorize the shared agents pool to use this subscription.</span></label>
7105
+ <button class="button" type="submit">Add to the pool</button>
7106
+ </form>
7107
+ <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>
7108
+ </section>
7109
+ <section class="card" id="step-done" hidden>
7110
+ <div class="avatar ok">${icon("check")}</div>
7111
+ <h1 tabindex="-1">Subscription connected</h1>
7112
+ <p class="lead"><strong id="connected-account"></strong> is now part of the shared agents pool. You can close this page.</p>
7113
+ <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>
7114
+ </section>
7115
+ <section class="card" id="step-error" hidden>
7116
+ <div class="avatar err">${icon("alert")}</div>
7117
+ <h1 tabindex="-1">This sign-in can't continue</h1>
7118
+ <p class="lead" id="error-message"></p>
7119
+ <p class="aside">Nothing was added to the pool from this step.<a class="button secondary" href="/pool-enroll">Start again</a></p>
7120
+ </section>
7121
+ <p id="status" class="notice err" role="alert" hidden></p>
7122
+ </main>
7123
+ <footer>Each step expires after 10 minutes. Nothing is added to the pool until you confirm.</footer>
7124
+ <noscript><p class="notice err">JavaScript is required for this sign-in.</p></noscript>
7125
+ <script nonce="${nonce}">
7031
7126
  let token = location.hash.slice(1);
7032
7127
  history.replaceState(null, '', location.pathname);
7033
7128
  addEventListener('hashchange', () => { if (location.hash) location.reload(); });
7034
7129
  const get = id => document.getElementById(id);
7035
- const status = get('status');
7036
- async function post(step, values) {
7037
- 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})});
7130
+ const steps = ['email', 'signin', 'code', 'confirm', 'done'];
7131
+ let current = 'email';
7132
+ function show(step) {
7133
+ const failed = step === 'error';
7134
+ const index = steps.indexOf(failed ? current : step);
7135
+ if (!failed) current = step;
7136
+ for (const name of [...steps, 'error']) get('step-' + name).hidden = name !== step;
7137
+ document.querySelectorAll('#stepper li').forEach((item, position) => {
7138
+ item.className = position < index || step === 'done' ? 'done' : position === index ? (failed ? 'failed' : 'active') : '';
7139
+ item.querySelector('.dot').innerHTML = item.className === 'done' ? '${icon("check")}' : String(position + 1);
7140
+ if (position === index) item.setAttribute('aria-current', 'step'); else item.removeAttribute('aria-current');
7141
+ });
7142
+ get('progress').style.width = Math.max(5, ((index + (step === 'done' ? 1 : 0)) / steps.length) * 100) + '%';
7143
+ (step === 'email' ? get('email') : get('step-' + step).querySelector('h1')).focus();
7144
+ }
7145
+ async function send(step, body) {
7146
+ 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)});
7038
7147
  const data = await response.json();
7039
- if (!response.ok) throw new Error(data.error || 'Sign-in failed. Ask the operator for a new link.');
7148
+ if (!response.ok) throw new Error(data.error || 'Sign-in failed. Start again.');
7040
7149
  token = data.token || '';
7041
7150
  return data;
7042
7151
  }
7152
+ const post = (step, values) => send(step, {token, ...values});
7043
7153
  function fail(error) {
7044
- token = ''; get('code').value = ''; get('begin').hidden = true; get('verify').hidden = true; get('confirm').hidden = true;
7045
- status.textContent = error instanceof Error ? error.message : 'Sign-in failed. Ask for a new link.';
7154
+ token = ''; get('code').value = '';
7155
+ get('error-message').textContent = error instanceof Error ? error.message : 'Sign-in failed. Start again.';
7156
+ show('error');
7046
7157
  }
7047
- if (!/^[A-Za-z0-9_-]{43}$/.test(token)) fail(new Error('Open the private invitation link supplied by your pool operator.'));
7158
+ show(/^[A-Za-z0-9_-]{43}$/.test(token) ? 'signin' : 'email');
7159
+ get('request').addEventListener('submit', async event => {
7160
+ event.preventDefault(); event.submitter.disabled = true; get('email-error').hidden = true;
7161
+ try {
7162
+ const data = await send('request', {email: get('email').value});
7163
+ get('signin-email').textContent = data.email; get('signin-for').hidden = false;
7164
+ show('signin');
7165
+ } catch (error) {
7166
+ get('email-error').textContent = error instanceof Error ? error.message : 'This email cannot connect. Ask the operator.';
7167
+ get('email-error').hidden = false; get('email').focus();
7168
+ } finally { event.submitter.disabled = false; }
7169
+ });
7048
7170
  get('start').addEventListener('click', async () => {
7171
+ const tab = window.open('', '_blank');
7049
7172
  get('start').disabled = true;
7050
7173
  try {
7051
7174
  const data = await post('start', {});
7052
7175
  const url = new URL(data.authUrl);
7053
- if (url.origin !== 'https://claude.ai' || url.pathname !== '/oauth/authorize') throw new Error('Invalid sign-in destination. Ask the operator for help.');
7054
- get('authorize').href = url.href; get('authorize').hidden = false; get('start').hidden = true;
7055
- get('verify').hidden = false; status.textContent = 'Open Claude sign-in above, then return here with the code.';
7056
- } catch(error) { fail(error); }
7176
+ if (url.origin !== 'https://claude.ai' || url.pathname !== '/oauth/authorize') throw new Error('Invalid sign-in destination. Ask for help.');
7177
+ get('reopen').href = url.href;
7178
+ if (tab) { tab.opener = null; tab.location.href = url.href; }
7179
+ 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.';
7180
+ show('code');
7181
+ } catch (error) { if (tab) tab.close(); fail(error); }
7057
7182
  });
7058
7183
  get('verify').addEventListener('submit', async event => {
7059
- event.preventDefault(); const button = event.submitter; button.disabled = true;
7184
+ event.preventDefault(); event.submitter.disabled = true;
7060
7185
  const code = get('code').value.trim(); get('code').value = '';
7061
- 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.'; }
7062
- catch(error) { fail(error); }
7186
+ try { const data = await post('verify', {code}); get('account').textContent = data.email; show('confirm'); }
7187
+ catch (error) { fail(error); }
7063
7188
  });
7064
7189
  get('confirm').addEventListener('submit', async event => {
7065
7190
  event.preventDefault(); if (!get('consent').checked) return; event.submitter.disabled = true;
7066
- 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.'; }
7067
- catch(error) { fail(error); }
7191
+ try { await post('confirm', {consent:true}); get('connected-account').textContent = get('account').textContent; show('done'); }
7192
+ catch (error) { fail(error); }
7068
7193
  });
7069
7194
  get('disconnect').addEventListener('click', async () => {
7070
- get('disconnect').disabled = true;
7195
+ get('disconnect').disabled = true; get('status').hidden = true;
7071
7196
  try {
7072
7197
  await post('disconnect', {});
7073
- get('connected').hidden = true; get('connected-account').textContent = ''; get('account').textContent = '';
7074
- get('consent').checked = false; get('code').value = '';
7075
- get('authorize').removeAttribute('href'); get('authorize').hidden = true;
7198
+ get('account').textContent = ''; get('connected-account').textContent = ''; get('consent').checked = false;
7076
7199
  document.querySelectorAll('button').forEach(button => { button.disabled = false; });
7077
- get('start').hidden = false; get('begin').hidden = false;
7078
- status.textContent = 'Subscription disconnected. It is no longer in the pool. You can close this page or connect again.';
7079
- } catch(error) {
7200
+ get('signin-notice').textContent = 'Subscription disconnected: it is no longer in the pool. You can connect again or close this page.';
7201
+ get('signin-notice').hidden = false;
7202
+ show('signin');
7203
+ } catch (error) {
7080
7204
  get('disconnect').disabled = false;
7081
- status.textContent = 'Removal is not confirmed. ' + (error instanceof Error ? error.message : 'Keep this page open and ask the operator to check this seat.');
7205
+ get('status').textContent = 'Removal is not confirmed. ' + (error instanceof Error ? error.message : 'Keep this page open and ask for help with this seat.');
7206
+ get('status').hidden = false;
7082
7207
  }
7083
7208
  });
7084
7209
  </script></body></html>`, {
@@ -7092,7 +7217,61 @@ get('disconnect').addEventListener('click', async () => {
7092
7217
  }
7093
7218
  });
7094
7219
  }
7095
- var init_enrollment_page = () => {};
7220
+ var icons, icon = (name) => `<svg viewBox="0 0 24 24" aria-hidden="true">${icons[name]}</svg>`, styles = `
7221
+ :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)}
7222
+ *{box-sizing:border-box}body{margin:0;min-height:100vh}
7223
+ header{position:relative;background:#fff;border-bottom:1px solid var(--line);padding:16px clamp(16px,4vw,32px);font-weight:600}
7224
+ header small{display:block;font-weight:400;color:var(--muted);font-size:13px}
7225
+ .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}
7226
+ main{max-width:560px;margin:0 auto;padding:32px 16px 48px}
7227
+ ol{list-style:none;display:flex;margin:0 0 28px;padding:0}
7228
+ ol li{flex:1;display:flex;flex-direction:column;align-items:center;gap:6px;position:relative;font-size:13px;color:var(--faint)}
7229
+ ol li+li::before{content:"";position:absolute;top:15px;right:calc(50% + 20px);width:calc(100% - 40px);height:2px;background:var(--line)}
7230
+ ol li.done+li::before{background:var(--ok-text)}
7231
+ 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)}
7232
+ ol .dot svg{width:16px;height:16px;stroke:#fff;stroke-width:3}
7233
+ ol li.active{color:var(--accent);font-weight:600}ol li.active .dot{background:var(--brand);border-color:var(--brand);color:#fff}
7234
+ ol li.done{color:var(--muted)}ol li.done .dot{background:var(--ok);border-color:var(--ok)}
7235
+ ol li.failed .dot{background:var(--err);border-color:var(--err);color:#fff}
7236
+ .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}
7237
+ .avatar{width:64px;height:64px;margin:0 auto 16px;border-radius:50%;display:grid;place-items:center;background:var(--tint)}
7238
+ .avatar svg,.button svg{width:28px;height:28px;fill:none;stroke:var(--accent);stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
7239
+ .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)}
7240
+ h1{font-size:22px;line-height:1.3;margin:0 0 8px;outline:none}
7241
+ .lead{color:var(--muted);margin:0 auto 24px;max-width:42ch}
7242
+ .facts{list-style:none;padding:0;margin:0 0 28px;text-align:left;display:grid;gap:10px}
7243
+ .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)}
7244
+ .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}
7245
+ .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}
7246
+ .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)}
7247
+ .button:disabled{opacity:.5;cursor:progress;box-shadow:none}
7248
+ .button:focus-visible,input:focus-visible,a:focus-visible{outline:3px solid var(--brand);outline-offset:3px}
7249
+ .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}
7250
+ form{text-align:left;display:grid;gap:16px}label{font-weight:600}
7251
+ 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}
7252
+ .hint{font-size:13px;color:var(--muted);margin:6px 0 0;font-weight:400}
7253
+ .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}
7254
+ .account svg{flex:none;width:22px;height:22px;fill:none;stroke:var(--ok-text);stroke-width:2.4}
7255
+ .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)}
7256
+ .notice{border-radius:12px;padding:12px 16px;margin:0 0 20px;text-align:left;background:var(--ok-bg);color:var(--ok-text)}
7257
+ .notice.err{background:var(--err-bg);color:var(--err-text)}
7258
+ .aside{margin-top:24px;padding-top:20px;border-top:1px solid var(--line);text-align:left;color:var(--muted);font-size:14px}
7259
+ .aside .button{margin-top:12px}
7260
+ footer{max-width:560px;margin:0 auto;padding:0 16px 32px;color:var(--muted);font-size:13px;text-align:center}
7261
+ @media (max-width:480px){ol li:not(.active) .label{display:none}}
7262
+ [hidden]{display:none!important}
7263
+ `;
7264
+ var init_enrollment_page = __esm(() => {
7265
+ icons = {
7266
+ mail: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>',
7267
+ 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"/>',
7268
+ code: '<rect x="4" y="6" width="16" height="12" rx="2"/><path d="M8 10h.01M12 10h.01M16 10h.01M8 14h8"/>',
7269
+ person: '<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>',
7270
+ check: '<path d="m5 12.5 4.5 4.5L19 7.5"/>',
7271
+ alert: '<path d="M12 8v5M12 16.5h.01"/><circle cx="12" cy="12" r="9"/>',
7272
+ 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"/>'
7273
+ };
7274
+ });
7096
7275
 
7097
7276
  // ../../packages/api/src/handlers/enrollment.ts
7098
7277
  import { createHash, randomBytes as randomBytes2 } from "crypto";
@@ -7134,13 +7313,59 @@ class EnrollmentHandlers {
7134
7313
  return await action();
7135
7314
  } catch (error) {
7136
7315
  return error instanceof EnrollmentError ? json({ error: error.message }, error.status) : json({
7137
- error: "Enrollment could not be saved. Ask the operator to check the seat and issue a new link."
7316
+ error: "Enrollment could not be saved. Ask the operator to check the seat."
7138
7317
  }, 500);
7139
7318
  }
7140
7319
  }
7141
- issue = (req) => this.guarded(async () => {
7320
+ requireClaudeCode() {
7142
7321
  if (!this.context.providerRegistry.getOAuthProvider("claude-code"))
7143
7322
  throw new EnrollmentError(400, "Provider 'claude-code' is disabled. Set providers.claude-code.enabled to true in your config.");
7323
+ }
7324
+ reserve(name) {
7325
+ if (this.context.dbOps.getAccountByName(name))
7326
+ throw new EnrollmentError(409, "This seat is already in the pool.");
7327
+ for (const entry of this.entries.values())
7328
+ if (entry.details.name === name && entry.state.kind === "busy")
7329
+ throw new EnrollmentError(409, "Sign-in is already in progress");
7330
+ for (const [key, entry] of this.entries)
7331
+ if (entry.details.name === name)
7332
+ this.entries.delete(key);
7333
+ if (this.entries.size >= 100)
7334
+ throw new EnrollmentError(429, "Too many pending invitations");
7335
+ }
7336
+ request(body) {
7337
+ this.requireClaudeCode();
7338
+ if (Object.keys(body).some((key) => key !== "email"))
7339
+ throw new EnrollmentError(400, "Unknown request field");
7340
+ const email = typeof body.email === "string" ? body.email.trim().toLowerCase() : "";
7341
+ if (!this.context.config.getEnrollmentEmails().includes(email))
7342
+ throw new EnrollmentError(403, "This email is not on the list. Ask the operator to add it.");
7343
+ const name = email.slice(0, email.indexOf("@")).replace(/[^a-z0-9._+-]/g, "-").slice(0, 64);
7344
+ this.reserve(name);
7345
+ const issued = this.mint({ name, email, contactEmail: email }, { kind: "invited" }, tenMinutes);
7346
+ return json({ ...issued, email });
7347
+ }
7348
+ emails = (req) => this.guarded(async () => {
7349
+ const body = await readBody(req);
7350
+ const lists = Object.entries(body);
7351
+ if (lists.some(([key, value]) => key !== "add" && key !== "remove" || !Array.isArray(value) || value.some((email) => typeof email !== "string")))
7352
+ throw new EnrollmentError(400, "Expected { add?: string[], remove?: string[] }");
7353
+ const { config } = this.context;
7354
+ const add = body.add ?? [];
7355
+ const remove = new Set((body.remove ?? []).map((email) => email.trim().toLowerCase()));
7356
+ if (add.length === 0 && remove.size === 0)
7357
+ return json({ emails: config.getEnrollmentEmails() });
7358
+ const next = [...config.getEnrollmentEmails(), ...add].filter((email) => !remove.has(email.trim().toLowerCase()));
7359
+ try {
7360
+ return json({ emails: config.setEnrollmentEmails(next) });
7361
+ } catch (error) {
7362
+ if (error instanceof ValidationError)
7363
+ throw new EnrollmentError(400, error.message);
7364
+ throw error;
7365
+ }
7366
+ });
7367
+ issue = (req) => this.guarded(async () => {
7368
+ this.requireClaudeCode();
7144
7369
  const input = await readBody(req);
7145
7370
  const allowed = new Set(["name", "email", "contactEmail", "slackUserId"]);
7146
7371
  if (Object.keys(input).some((key) => !allowed.has(key)))
@@ -7163,16 +7388,7 @@ class EnrollmentHandlers {
7163
7388
  }
7164
7389
  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)))
7165
7390
  throw new EnrollmentError(400, "Invalid invitation details");
7166
- if (this.context.dbOps.getAccountByName(details.name))
7167
- throw new EnrollmentError(409, "Seat already exists");
7168
- for (const entry of this.entries.values())
7169
- if (entry.details.name === details.name && entry.state.kind === "busy")
7170
- throw new EnrollmentError(409, "Sign-in is already in progress");
7171
- for (const [key, entry] of this.entries)
7172
- if (entry.details.name === details.name)
7173
- this.entries.delete(key);
7174
- if (this.entries.size >= 100)
7175
- throw new EnrollmentError(429, "Too many pending invitations");
7391
+ this.reserve(details.name);
7176
7392
  const issued = this.mint(details, { kind: "invited" }, oneDay);
7177
7393
  return json({
7178
7394
  url: `${this.origin.origin}/pool-enroll#${issued.token}`,
@@ -7194,12 +7410,14 @@ class EnrollmentHandlers {
7194
7410
  if (req.headers.get("origin") !== this.origin.origin)
7195
7411
  throw new EnrollmentError(403, "Untrusted enrollment origin");
7196
7412
  const body = await readBody(req);
7413
+ if (url.pathname === "/pool-enroll/request")
7414
+ return this.request(body);
7197
7415
  const token = typeof body.token === "string" && /^[A-Za-z0-9_-]{43}$/.test(body.token) ? body.token : "";
7198
7416
  const key = hash(token);
7199
7417
  const entry = this.entries.get(key);
7200
7418
  const expected = url.pathname === "/pool-enroll/start" ? "invited" : url.pathname === "/pool-enroll/verify" ? "started" : url.pathname === "/pool-enroll/confirm" ? "verified" : "connected";
7201
7419
  if (!entry || entry.expiresAt <= this.now() || entry.state.kind !== expected)
7202
- throw new EnrollmentError(410, "This link has expired or was already used. Ask the operator for a new link.");
7420
+ throw new EnrollmentError(410, "This sign-in has expired or was already used. Start again.");
7203
7421
  const state = entry.state;
7204
7422
  entry.state = { kind: "busy" };
7205
7423
  try {
@@ -7218,12 +7436,12 @@ class EnrollmentHandlers {
7218
7436
  try {
7219
7437
  seat = await this.oauth.verifyClaudeSeat(state.flow, body.code.trim());
7220
7438
  } catch {
7221
- throw new EnrollmentError(400, "Claude sign-in could not be verified. Ask for a new link and try again.");
7439
+ throw new EnrollmentError(400, "Claude sign-in could not be verified. Start again.");
7222
7440
  }
7223
7441
  this.assertCurrent(key, entry);
7224
7442
  const { email } = seat.identity;
7225
7443
  if (!email || entry.details.email && email.toLowerCase() !== entry.details.email.toLowerCase())
7226
- throw new EnrollmentError(400, "This Claude account does not match the invitation. Ask for a new link.");
7444
+ throw new EnrollmentError(400, "This Claude account does not match your email. Start again and sign in with the matching account.");
7227
7445
  this.assertNewSeat(entry.details.name, seat);
7228
7446
  return json({
7229
7447
  ...this.mint(entry.details, { kind: "verified", seat }, tenMinutes),
@@ -7266,7 +7484,7 @@ class EnrollmentHandlers {
7266
7484
  }
7267
7485
  assertCurrent(key, entry) {
7268
7486
  if (this.entries.get(key) !== entry || entry.expiresAt <= this.now())
7269
- throw new EnrollmentError(410, "Sign-in expired. Ask for a new link.");
7487
+ throw new EnrollmentError(410, "Sign-in expired. Start again.");
7270
7488
  }
7271
7489
  assertNewSeat(name, seat) {
7272
7490
  if (this.context.dbOps.getAccountByName(name) || this.context.dbOps.getAccountsByProvider("claude-code").some((account2) => account2.account_uuid === seat.identity.accountUuid))
@@ -7346,11 +7564,13 @@ async function readBody(req) {
7346
7564
  }
7347
7565
  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;
7348
7566
  var init_enrollment = __esm(() => {
7567
+ init_src2();
7349
7568
  init_src6();
7350
7569
  init_src();
7351
7570
  init_enrollment_page();
7352
7571
  paths = new Set([
7353
7572
  "/pool-enroll",
7573
+ "/pool-enroll/request",
7354
7574
  "/pool-enroll/start",
7355
7575
  "/pool-enroll/verify",
7356
7576
  "/pool-enroll/confirm",
@@ -7767,8 +7987,10 @@ class APIRouter {
7767
7987
  this.registerHandlers();
7768
7988
  }
7769
7989
  registerHandlers() {
7770
- if (this.enrollment)
7990
+ if (this.enrollment) {
7771
7991
  this.staticHandlers.set("POST:/api/enrollment-invitations", this.enrollment.issue);
7992
+ this.staticHandlers.set("POST:/api/enrollment-emails", this.enrollment.emails);
7993
+ }
7772
7994
  const { config, dbOps, getProviders, getRuntimeHealth, providerRegistry } = this.context;
7773
7995
  const healthHandler = createHealthHandler(dbOps, config, getProviders, getRuntimeHealth);
7774
7996
  const statsHandler = createStatsHandler(dbOps);
@@ -7959,6 +8181,50 @@ var init_background_tasks = __esm(() => {
7959
8181
  backgroundTasks = new Set;
7960
8182
  });
7961
8183
 
8184
+ // ../../packages/proxy/src/seat-usage.ts
8185
+ function liveUtilization(window2, now) {
8186
+ if (window2.utilization === null)
8187
+ return 0;
8188
+ const windowOpen = window2.resetAt === null ? isCurrentQuotaWindow(window2, now) : window2.resetAt > now;
8189
+ return windowOpen ? window2.utilization : 0;
8190
+ }
8191
+ function isAheadOfWeeklyPace(window2, now) {
8192
+ if (window2.resetAt === null || window2.resetAt <= now)
8193
+ return false;
8194
+ const elapsedShareOfWeek = 1 - (window2.resetAt - now) / WEEK_MS;
8195
+ return liveUtilization(window2, now) > elapsedShareOfWeek;
8196
+ }
8197
+ function highestUtilization(windows, now) {
8198
+ return Math.max(0, ...windows.map(([, window2]) => liveUtilization(window2, now)));
8199
+ }
8200
+ function seatUsage(provider, account2, model, now) {
8201
+ const buckets = provider.quotaBucketsFor(model);
8202
+ const windows = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket]) => buckets?.includes(bucket) ?? true);
8203
+ const weekly = windows.filter(([bucket]) => provider.isWeeklyBucket(bucket));
8204
+ const fiveHour = windows.filter(([bucket]) => provider.isFiveHourBucket(bucket));
8205
+ return {
8206
+ aheadOfWeeklyPace: weekly.some(([, window2]) => isAheadOfWeeklyPace(window2, now)),
8207
+ fiveHour: highestUtilization(fiveHour, now),
8208
+ weekly: highestUtilization(weekly, now)
8209
+ };
8210
+ }
8211
+ function soonestWeeklyReset(provider, account2, now) {
8212
+ const resets = Object.entries(account2.quota_state?.windows ?? {}).filter(([bucket, window2]) => provider.isWeeklyBucket(bucket) && window2.resetAt !== null && window2.resetAt > now).map(([, window2]) => window2.resetAt);
8213
+ return Math.min(...resets, Number.POSITIVE_INFINITY);
8214
+ }
8215
+ function compareSeatUsage(provider, model, now) {
8216
+ return (left, right) => {
8217
+ const a = seatUsage(provider, left, model, now);
8218
+ const b = seatUsage(provider, right, model, now);
8219
+ return Number(a.aheadOfWeeklyPace) - Number(b.aheadOfWeeklyPace) || a.fiveHour - b.fiveHour || a.weekly - b.weekly || soonestWeeklyReset(provider, left, now) - soonestWeeklyReset(provider, right, now);
8220
+ };
8221
+ }
8222
+ var WEEK_MS;
8223
+ var init_seat_usage = __esm(() => {
8224
+ init_src();
8225
+ WEEK_MS = 7 * 24 * 60 * 60 * 1000;
8226
+ });
8227
+
7962
8228
  // ../../packages/proxy/src/team-router.ts
7963
8229
  import { createHash as createHash2 } from "crypto";
7964
8230
  function isRecord5(value) {
@@ -8017,7 +8283,7 @@ class TeamRouter {
8017
8283
  }
8018
8284
  if (!config.distributionEnabled || !key)
8019
8285
  return eligible;
8020
- const selected = this.leastLoadedPriorityAccount(eligible, store?.countConversationPinsByAccount(now - PIN_TTL_MS));
8286
+ const selected = this.leastUsedPriorityAccount(eligible, compareSeatUsage(provider, request2.model, now), store?.countConversationPinsByAccount(now - PIN_TTL_MS));
8021
8287
  this.touchPin(key, selected.id, now, store);
8022
8288
  return [
8023
8289
  selected,
@@ -8063,18 +8329,10 @@ class TeamRouter {
8063
8329
  return persistedCounts.get(accountId) ?? 0;
8064
8330
  return [...this.pins.values()].filter((pin) => pin.accountId === accountId).length;
8065
8331
  }
8066
- leastLoadedPriorityAccount(accounts, persistedCounts) {
8332
+ leastUsedPriorityAccount(accounts, byUsage, persistedCounts) {
8067
8333
  const priority = Math.min(...accounts.map((account2) => account2.priority ?? 0));
8068
8334
  const tier = accounts.filter((account2) => (account2.priority ?? 0) === priority);
8069
- return [...tier].sort((left, right) => {
8070
- const activeDifference = this.activePins(left.id, persistedCounts) - this.activePins(right.id, persistedCounts);
8071
- if (activeDifference !== 0)
8072
- return activeDifference;
8073
- const inFlightDifference = (this.inFlight.get(left.id) ?? 0) - (this.inFlight.get(right.id) ?? 0);
8074
- if (inFlightDifference !== 0)
8075
- return inFlightDifference;
8076
- return left.name.localeCompare(right.name);
8077
- })[0];
8335
+ 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];
8078
8336
  }
8079
8337
  removeExpiredPins(now, store) {
8080
8338
  for (const [key, pin] of this.pins) {
@@ -8090,6 +8348,7 @@ class TeamRouter {
8090
8348
  }
8091
8349
  var MAX_OPENING_BYTES, PIN_TTL_MS;
8092
8350
  var init_team_router = __esm(() => {
8351
+ init_seat_usage();
8093
8352
  MAX_OPENING_BYTES = 64 * 1024;
8094
8353
  PIN_TTL_MS = 30 * 24 * 60 * 60 * 1000;
8095
8354
  });
@@ -8137,13 +8396,6 @@ function getSoonestQuotaReset(meta, ctx, now = Date.now()) {
8137
8396
  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);
8138
8397
  return resets.length > 0 ? Math.min(...resets) : null;
8139
8398
  }
8140
- function soonestWeeklyReset(provider, account2, now) {
8141
- const windows = account2.quota_state?.windows ?? {};
8142
- const resets = Object.entries(windows).filter(([name, window2]) => {
8143
- return provider.isWeeklyBucket(name) && window2.resetAt !== null && window2.resetAt > now;
8144
- }).map(([, window2]) => window2.resetAt);
8145
- return Math.min(...resets, Number.POSITIVE_INFINITY);
8146
- }
8147
8399
  function selectRevalidationProbe(accounts, ctx, now) {
8148
8400
  const probes = ctx.quotaProbeAt;
8149
8401
  const lastProbeAt = probes?.get(ctx.providerName);
@@ -8176,6 +8428,7 @@ function selectAccountsForRequest(meta, ctx, teamRequest, options) {
8176
8428
  var QUOTA_PROBE_INTERVAL_MS = 60000;
8177
8429
  var init_account_selector = __esm(() => {
8178
8430
  init_src();
8431
+ init_seat_usage();
8179
8432
  init_team_router();
8180
8433
  });
8181
8434