@andorra-labs/code 0.1.13 → 0.1.14

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.
Files changed (105) hide show
  1. package/dist/src/account-presentation.js +4 -1
  2. package/dist/src/agent-execution.js +300 -140
  3. package/dist/src/agent-mcp.js +2 -2
  4. package/dist/src/andorra/endpoint.d.ts +7 -0
  5. package/dist/src/andorra/endpoint.js +46 -0
  6. package/dist/src/andorra/entry.d.ts +21 -0
  7. package/dist/src/andorra/entry.js +100 -0
  8. package/dist/src/andorra/errors.d.ts +2 -0
  9. package/dist/src/andorra/errors.js +39 -0
  10. package/dist/src/andorra/hosted.d.ts +52 -0
  11. package/dist/src/andorra/hosted.js +126 -0
  12. package/dist/src/andorra/monitor.d.ts +151 -0
  13. package/dist/src/andorra/monitor.js +393 -0
  14. package/dist/src/andorra/notices.d.ts +7 -0
  15. package/dist/src/andorra/notices.js +15 -0
  16. package/dist/src/andorra/opt-in.d.ts +58 -0
  17. package/dist/src/andorra/opt-in.js +112 -0
  18. package/dist/src/andorra/request-watch.d.ts +6 -0
  19. package/dist/src/andorra/request-watch.js +10 -0
  20. package/dist/src/andorra/state.d.ts +86 -0
  21. package/dist/src/andorra/state.js +238 -0
  22. package/dist/src/andorra/terminal.d.ts +68 -0
  23. package/dist/src/andorra/terminal.js +125 -0
  24. package/dist/src/andorra/usage-format.d.ts +9 -0
  25. package/dist/src/andorra/usage-format.js +19 -0
  26. package/dist/src/anthropic-credentials.js +9 -1
  27. package/dist/src/app-server/protocol.d.ts +6 -2
  28. package/dist/src/app-server/protocol.js +1 -1
  29. package/dist/src/app-server.d.ts +27 -0
  30. package/dist/src/app-server.js +292 -85
  31. package/dist/src/auth/AuthManager.d.ts +9 -0
  32. package/dist/src/auth/AuthManager.js +161 -21
  33. package/dist/src/auth/deployment.d.ts +1 -0
  34. package/dist/src/auth/deployment.js +1 -0
  35. package/dist/src/auth/index.d.ts +1 -1
  36. package/dist/src/auth/index.js +1 -1
  37. package/dist/src/auth/store.d.ts +26 -0
  38. package/dist/src/auth/store.js +34 -1
  39. package/dist/src/browser-runner.js +1 -1
  40. package/dist/src/browser-stealth.d.ts +19 -1
  41. package/dist/src/browser-stealth.js +23 -3
  42. package/dist/src/browser-ui/tokens.css +4 -4
  43. package/dist/src/browser-view.d.ts +65 -0
  44. package/dist/src/browser-view.js +229 -16
  45. package/dist/src/cli.js +43 -26
  46. package/dist/src/command-screens.d.ts +17 -1
  47. package/dist/src/command-screens.js +192 -21
  48. package/dist/src/commands.d.ts +7 -1
  49. package/dist/src/commands.js +78 -27
  50. package/dist/src/config.d.ts +6 -1
  51. package/dist/src/config.js +86 -3
  52. package/dist/src/dashboard-view.d.ts +2 -0
  53. package/dist/src/dashboard-view.js +11 -2
  54. package/dist/src/decision/PreparedSteps.js +1 -1
  55. package/dist/src/decision/applyToolMenu.js +1 -1
  56. package/dist/src/decision/toolFamilies.js +1 -1
  57. package/dist/src/decision/types.d.ts +1 -0
  58. package/dist/src/graph-health.d.ts +11 -0
  59. package/dist/src/graph-health.js +36 -4
  60. package/dist/src/graph-manager-chat.d.ts +33 -0
  61. package/dist/src/graph-manager-chat.js +159 -5
  62. package/dist/src/graph-runner.js +27 -0
  63. package/dist/src/graph-selection.js +2 -1
  64. package/dist/src/graph-ui/app.js +25 -2
  65. package/dist/src/graph-ui/manager.js +40 -5
  66. package/dist/src/graph-ui/style.css +5 -2
  67. package/dist/src/graph-ui/tokens.css +4 -4
  68. package/dist/src/graphs.js +1 -3
  69. package/dist/src/hardened-runtime.js +1 -1
  70. package/dist/src/membership-errors.js +1 -1
  71. package/dist/src/membership.d.ts +10 -2
  72. package/dist/src/membership.js +20 -6
  73. package/dist/src/model-context-windows.d.ts +2 -0
  74. package/dist/src/model-context-windows.js +24 -0
  75. package/dist/src/model-health-cache.js +1 -1
  76. package/dist/src/model-metadata.d.ts +1 -0
  77. package/dist/src/model-metadata.js +40 -3
  78. package/dist/src/palette.d.ts +1 -0
  79. package/dist/src/palette.js +1 -1
  80. package/dist/src/permissions.js +17 -4
  81. package/dist/src/provider-connection.js +15 -0
  82. package/dist/src/provider-settings.d.ts +16 -1
  83. package/dist/src/provider-settings.js +36 -20
  84. package/dist/src/providers.d.ts +14 -2
  85. package/dist/src/providers.js +69 -11
  86. package/dist/src/react-runtime.js +12 -7
  87. package/dist/src/remote/engine-pool.js +5 -4
  88. package/dist/src/run-control.d.ts +2 -2
  89. package/dist/src/run-control.js +9 -6
  90. package/dist/src/runtime.d.ts +2 -0
  91. package/dist/src/runtime.js +2 -1
  92. package/dist/src/sessions.d.ts +1 -0
  93. package/dist/src/sessions.js +4 -2
  94. package/dist/src/skills/bundled/graph-manager/errors.md +1 -1
  95. package/dist/src/skills/bundled/provenance.json +738 -738
  96. package/dist/src/subagent-run.d.ts +2 -0
  97. package/dist/src/subagent-run.js +14 -3
  98. package/dist/src/telemetry/schema.d.ts +1 -1
  99. package/dist/src/telemetry/schema.js +2 -2
  100. package/dist/src/terminal-ui.d.ts +21 -0
  101. package/dist/src/terminal-ui.js +73 -10
  102. package/dist/src/transcript.js +3 -0
  103. package/dist/src/types.d.ts +3 -0
  104. package/dist/src/workspace-instructions.js +1 -1
  105. package/package.json +12 -1
@@ -65,7 +65,7 @@ export const GRAPH_AGENT_GUIDE = [
65
65
  'Sessions that already ran it keep resuming. andorra_graphs_list {includeDeleted:true} lists deleted graphs with deleted=true.',
66
66
  'andorra_graph_restore {id, expectedRevision} publishes the next revision without the marker.',
67
67
  'A deleted graph still counts toward a free account\'s one custom graph, so a free account restores it rather than replacing it.',
68
- 'DEFAULT_GRAPH: the bundled Default graph and the Andorra preset cannot be deleted.',
68
+ 'DEFAULT_GRAPH: the bundled Default graph cannot be deleted.',
69
69
  'CONFIRMATION_MISMATCH: confirm must equal id. GRAPH_IN_USE: an automation runs the graph; the error lists them; change them first.',
70
70
  'GRAPH_DELETED: the graph is deleted; restore it before editing or deleting it again. GRAPH_NOT_DELETED: restore needs a deleted graph.',
71
71
  'RESERVED_METADATA: metadata.deletedAt is set only by the delete and restore tools; andorra_graph_patch and publishing refuse it.',
@@ -413,7 +413,7 @@ export class AgentMcpBackend {
413
413
  const tool = deleting ? 'andorra_graph_delete' : 'andorra_graph_restore';
414
414
  const id = field(args, 'id');
415
415
  if (id === 'default' || id.includes(':'))
416
- throw new AgentMcpError('DEFAULT_GRAPH', 'The bundled Default graph and the Andorra preset cannot be deleted or restored.');
416
+ throw new AgentMcpError('DEFAULT_GRAPH', 'The bundled Default graph cannot be deleted or restored.');
417
417
  if (!safeId(id))
418
418
  throw new AgentMcpError('INVALID_GRAPH_ID', 'Graph id must be a safe identifier of 1-80 characters.');
419
419
  if (Object.keys(args).some(key => !['id', 'expectedRevision', ...(deleting ? ['confirm'] : [])].includes(key)))
@@ -0,0 +1,7 @@
1
+ export declare const ANDORRA_UNAVAILABLE_MESSAGE = "Andorra is not available at the moment.";
2
+ export declare const ANDORRA_SIGN_IN_MESSAGE = "Sign in to use Andorra models.";
3
+ export declare const ANDORRA_CHANGED_MESSAGE = "Andorra model availability may have changed.";
4
+ export declare const ANDORRA_PROVIDER_BASE_URL: string;
5
+ export declare function andorraBaseUrl(env?: NodeJS.ProcessEnv): string;
6
+ /** The account token for Andorra's router; undefined means signed out. */
7
+ export declare function andorraAccessToken(signal?: AbortSignal, env?: NodeJS.ProcessEnv): Promise<string | undefined>;
@@ -0,0 +1,46 @@
1
+ import { AUTH_DEPLOYMENT } from '../auth/deployment.js';
2
+ export const ANDORRA_UNAVAILABLE_MESSAGE = 'Andorra is not available at the moment.';
3
+ export const ANDORRA_SIGN_IN_MESSAGE = 'Sign in to use Andorra models.';
4
+ export const ANDORRA_CHANGED_MESSAGE = 'Andorra model availability may have changed.';
5
+ export const ANDORRA_PROVIDER_BASE_URL = `${AUTH_DEPLOYMENT.inferenceBaseUrl}/v1`;
6
+ const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
7
+ /**
8
+ * The development override, only when it is a plain loopback http origin and its token is set too: the URL
9
+ * alone is ignored, so requests then go to the production router with the account token.
10
+ */
11
+ function loopbackOverride(env) {
12
+ const raw = env.ANDORRA_INFERENCE_URL;
13
+ if (!raw || !env.ANDORRA_INFERENCE_TOKEN)
14
+ return undefined;
15
+ let url;
16
+ try {
17
+ url = new URL(raw);
18
+ }
19
+ catch {
20
+ return undefined;
21
+ }
22
+ if (url.protocol !== 'http:' || !LOOPBACK_HOSTS.has(url.hostname) || url.username || url.password)
23
+ return undefined;
24
+ if ((url.pathname !== '/' && url.pathname !== '') || url.search || url.hash)
25
+ return undefined;
26
+ return url.origin;
27
+ }
28
+ export function andorraBaseUrl(env = process.env) {
29
+ const override = loopbackOverride(env);
30
+ return override ? `${override}/v1` : ANDORRA_PROVIDER_BASE_URL;
31
+ }
32
+ /** The account token for Andorra's router; undefined means signed out. */
33
+ export async function andorraAccessToken(signal, env = process.env) {
34
+ if (loopbackOverride(env))
35
+ return env.ANDORRA_INFERENCE_TOKEN || undefined;
36
+ const { getAccessToken, AuthError, AUTH_REFRESH_BUDGET_MS } = await import('../auth/index.js');
37
+ const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(AUTH_REFRESH_BUDGET_MS)]) : AbortSignal.timeout(AUTH_REFRESH_BUDGET_MS);
38
+ try {
39
+ return (await getAccessToken(bounded)) || undefined;
40
+ }
41
+ catch (error) {
42
+ if (error instanceof AuthError && (error.code === 'login_required' || error.code === 'invalid_token'))
43
+ return undefined;
44
+ throw error;
45
+ }
46
+ }
@@ -0,0 +1,21 @@
1
+ import { type Config } from '../config.js';
2
+ import { type ProviderConfig } from '../providers.js';
3
+ import type { HostedAnswer } from './hosted.js';
4
+ export declare function hasAndorraEntry(config: Pick<Config, 'providers'>): boolean;
5
+ /** A router-supplied model name made safe to show: one line, no control characters, at most 80 characters; undefined when nothing is left. */
6
+ export declare function cleanModelName(name: string): string | undefined;
7
+ /** Whether a missing entry may be created: only once the user added Andorra ('create'); otherwise an existing entry is only kept current. */
8
+ export type AndorraEntryMode = 'create' | 'refresh';
9
+ /**
10
+ * The config with the Andorra entry added or refreshed from a hosted answer, or undefined when nothing changes.
11
+ * Never mutates `config`, and never changes the selected provider unless the config had no providers at all.
12
+ * An existing entry is refreshed in every mode; a missing one is created, first in the list, only in 'create' mode.
13
+ */
14
+ export declare function applyAndorraEntry(config: Config, answer: HostedAnswer, mode: AndorraEntryMode): Config | undefined;
15
+ /**
16
+ * The entry Andorra would be saved as from this answer, for a config that has none: what a client lists while
17
+ * Andorra is offered and not saved yet. It exists in memory only; nothing validates, saves or sends requests with it.
18
+ */
19
+ export declare function virtualAndorraEntry(config: Pick<Config, 'providers'>, answer: HostedAnswer): ProviderConfig | undefined;
20
+ /** The provider to select when the active one goes away: never Andorra by position. */
21
+ export declare function fallbackProviderId(providers: readonly Pick<ProviderConfig, 'id' | 'type'>[]): string;
@@ -0,0 +1,100 @@
1
+ import { reconcileSubagentPair } from '../config.js';
2
+ import { applyModelContextWindow, MAX_MODEL_DISPLAY_NAME_LENGTH } from '../providers.js';
3
+ import { ANDORRA_PROVIDER_BASE_URL } from './endpoint.js';
4
+ const ANDORRA_ID = 'andorra';
5
+ const ANDORRA_NAME = 'Andorra';
6
+ export function hasAndorraEntry(config) {
7
+ return config.providers.some(provider => provider.type === 'andorra');
8
+ }
9
+ function freeId(providers) {
10
+ const taken = new Set(providers.map(provider => provider.id));
11
+ if (!taken.has(ANDORRA_ID))
12
+ return ANDORRA_ID;
13
+ let suffix = 2;
14
+ while (taken.has(`${ANDORRA_ID}-${suffix}`))
15
+ suffix += 1;
16
+ return `${ANDORRA_ID}-${suffix}`;
17
+ }
18
+ function sameList(a, b) {
19
+ return !!a && a.length === b.length && a.every((value, index) => value === b[index]);
20
+ }
21
+ function sameWindows(a, b) {
22
+ if (!a)
23
+ return false;
24
+ const keys = Object.keys(b);
25
+ return Object.keys(a).length === keys.length && keys.every(key => Object.hasOwn(a, key) && a[key] === b[key]);
26
+ }
27
+ function sameNames(a, b) {
28
+ const left = a ?? {};
29
+ const keys = Object.keys(b);
30
+ return Object.keys(left).length === keys.length && keys.every(key => Object.hasOwn(left, key) && left[key] === b[key]);
31
+ }
32
+ // Line breaks and tabs become spaces; every other control, format or bidi character is dropped.
33
+ const SPACING = /[\t\n\v\f\r\u0085\u2028\u2029]/g;
34
+ const INVISIBLE = /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff]/g;
35
+ /** A router-supplied model name made safe to show: one line, no control characters, at most 80 characters; undefined when nothing is left. */
36
+ export function cleanModelName(name) {
37
+ const cleaned = name.replace(SPACING, ' ').replace(INVISIBLE, '').replace(/\s+/g, ' ').trim();
38
+ const capped = [...cleaned].slice(0, MAX_MODEL_DISPLAY_NAME_LENGTH).join('').trim();
39
+ return capped || undefined;
40
+ }
41
+ /** The display names worth keeping: cleaned, and only where they differ from the id (the id is shown otherwise). */
42
+ function hostedNames(answer) {
43
+ const names = {};
44
+ for (const model of answer.models) {
45
+ const name = cleanModelName(model.name);
46
+ if (name !== undefined && name !== model.id && !['__proto__', 'constructor', 'prototype'].includes(model.id))
47
+ names[model.id] = name;
48
+ }
49
+ return names;
50
+ }
51
+ /**
52
+ * The config with the Andorra entry added or refreshed from a hosted answer, or undefined when nothing changes.
53
+ * Never mutates `config`, and never changes the selected provider unless the config had no providers at all.
54
+ * An existing entry is refreshed in every mode; a missing one is created, first in the list, only in 'create' mode.
55
+ */
56
+ export function applyAndorraEntry(config, answer, mode) {
57
+ if (!answer.enabled || answer.models.length === 0)
58
+ return undefined;
59
+ const models = answer.models.map(model => model.id);
60
+ const modelContextWindows = {};
61
+ for (const model of answer.models)
62
+ modelContextWindows[model.id] = model.contextWindow;
63
+ const modelNames = hostedNames(answer);
64
+ const named = Object.keys(modelNames).length ? { modelNames } : {};
65
+ const index = config.providers.findIndex(provider => provider.type === 'andorra');
66
+ if (index < 0) {
67
+ if (mode !== 'create')
68
+ return undefined;
69
+ const entry = { id: freeId(config.providers), type: 'andorra', name: ANDORRA_NAME, baseUrl: ANDORRA_PROVIDER_BASE_URL,
70
+ model: models[0], models, modelContextWindows, ...named };
71
+ return { ...config, providers: [entry, ...config.providers], provider: config.providers.length === 0 ? entry.id : config.provider };
72
+ }
73
+ const existing = config.providers[index];
74
+ const model = models.includes(existing.model) ? existing.model : models[0];
75
+ if (model === existing.model && sameList(existing.models, models) && sameWindows(existing.modelContextWindows, modelContextWindows)
76
+ && sameNames(existing.modelNames, modelNames))
77
+ return undefined;
78
+ const { modelNames: _previous, ...rest } = existing;
79
+ const refreshed = { ...rest, model, models, modelContextWindows, ...named };
80
+ if (refreshed.contextWindow !== undefined)
81
+ applyModelContextWindow(refreshed, model);
82
+ const providers = config.providers.slice();
83
+ providers[index] = refreshed;
84
+ // A model the hosted answer dropped may be the one the external subagent setting names: that pair is cleared, as it
85
+ // is for every other change of a provider's model list, so the config still validates and the refresh can be saved.
86
+ return reconcileSubagentPair({ ...config, providers });
87
+ }
88
+ /**
89
+ * The entry Andorra would be saved as from this answer, for a config that has none: what a client lists while
90
+ * Andorra is offered and not saved yet. It exists in memory only; nothing validates, saves or sends requests with it.
91
+ */
92
+ export function virtualAndorraEntry(config, answer) {
93
+ if (hasAndorraEntry(config))
94
+ return undefined;
95
+ return applyAndorraEntry({ version: 1, provider: '', providers: [...config.providers] }, answer, 'create')?.providers[0];
96
+ }
97
+ /** The provider to select when the active one goes away: never Andorra by position. */
98
+ export function fallbackProviderId(providers) {
99
+ return providers.find(provider => provider.type !== 'andorra')?.id ?? providers[0]?.id ?? '';
100
+ }
@@ -0,0 +1,2 @@
1
+ /** The plain message for one of the router's refusals; undefined = not a refusal this client words itself. */
2
+ export declare function andorraRefusal(status: number, body: unknown, retryAfter: string | null): string | undefined;
@@ -0,0 +1,39 @@
1
+ import { ANDORRA_SIGN_IN_MESSAGE, ANDORRA_UNAVAILABLE_MESSAGE } from './endpoint.js';
2
+ import { formatWeekReset } from './usage-format.js';
3
+ function record(value) {
4
+ return typeof value === 'object' && value !== null && !Array.isArray(value) ? value : undefined;
5
+ }
6
+ /**
7
+ * When the allowance resets, as the usage meter words it: "Sun 11:59 PM", the week's last minute in local time; "at the
8
+ * end of the week" when the time is missing or cannot be read.
9
+ */
10
+ function resetWhen(resetsAt) {
11
+ const when = typeof resetsAt === 'string' ? formatWeekReset(resetsAt) : '';
12
+ return when || 'at the end of the week';
13
+ }
14
+ /** Seconds from a `retry-after` header, only as a plain integer from 1 to 3600. */
15
+ function retrySeconds(retryAfter) {
16
+ if (retryAfter === null || !/^\d+$/.test(retryAfter))
17
+ return undefined;
18
+ const seconds = Number(retryAfter);
19
+ return seconds >= 1 && seconds <= 3600 ? seconds : undefined;
20
+ }
21
+ /** The plain message for one of the router's refusals; undefined = not a refusal this client words itself. */
22
+ export function andorraRefusal(status, body, retryAfter) {
23
+ const error = record(record(body)?.error);
24
+ const code = error?.code;
25
+ if (status === 503 && code === 'hosted_unavailable')
26
+ return ANDORRA_UNAVAILABLE_MESSAGE;
27
+ if (status === 404 && code === 'model_unavailable')
28
+ return ANDORRA_UNAVAILABLE_MESSAGE;
29
+ if (status === 401 && code === 'unauthorized')
30
+ return ANDORRA_SIGN_IN_MESSAGE;
31
+ if (status === 429 && code === 'weekly_allowance_reached') {
32
+ return `You have used this week's Andorra allowance. It resets ${resetWhen(error?.resetsAt)}.`;
33
+ }
34
+ if (status === 429 && code === 'hosted_busy') {
35
+ const seconds = retrySeconds(retryAfter);
36
+ return `Andorra is busy. Try again in ${seconds === undefined ? 'a moment' : `${seconds} second${seconds === 1 ? '' : 's'}`}.`;
37
+ }
38
+ return undefined;
39
+ }
@@ -0,0 +1,52 @@
1
+ export interface HostedModel {
2
+ id: string;
3
+ name: string;
4
+ contextWindow: number;
5
+ }
6
+ /** How much of the account's weekly allowance is used (0-100) and when it renews (ISO timestamp). */
7
+ export interface HostedAllowance {
8
+ usedPercent: number;
9
+ resetsAt: string;
10
+ }
11
+ export interface HostedAnswer {
12
+ enabled: boolean;
13
+ promotionId: string | null;
14
+ models: HostedModel[];
15
+ allowance?: HostedAllowance;
16
+ available?: boolean;
17
+ }
18
+ export type HostedCheck = {
19
+ kind: 'answer';
20
+ answer: HostedAnswer;
21
+ } | {
22
+ kind: 'signed-out';
23
+ } | {
24
+ kind: 'failed';
25
+ };
26
+ export declare const HOSTED_CHECK_TIMEOUT_MS = 5000;
27
+ export declare function parseHostedAnswer(value: unknown): HostedAnswer | undefined;
28
+ export interface HostedClientDeps {
29
+ accessToken(signal?: AbortSignal): Promise<string | undefined>;
30
+ baseUrl(): string;
31
+ fetch: typeof fetch;
32
+ }
33
+ export declare function createHostedClient(deps?: Partial<HostedClientDeps>): (signal?: AbortSignal) => Promise<HostedCheck>;
34
+ /** Set by this repository's test runner (`scripts/run-tests.mjs`) for the test files it starts, and by nothing else. */
35
+ export declare const TEST_RUN_MARKER = "ANDORRA_TEST_RUN_ID";
36
+ /**
37
+ * The check a monitor runs when none is injected. In a run of this repository's own test runner (its marker
38
+ * variable is set) it asks nothing unless the loopback override is set, so a test that builds a client without
39
+ * injecting a check can never reach the production router with a developer's account. Nothing a user's own tools
40
+ * set (Node's test-runner variables among them) switches the check off.
41
+ */
42
+ export declare function defaultHostedCheck(env?: NodeJS.ProcessEnv): (signal?: AbortSignal) => Promise<HostedCheck>;
43
+ /**
44
+ * For a process that runs no monitor (a subagent run): asks the router once whether Andorra is on, so a run that
45
+ * cannot start is refused with the plain sentence and no model request. Undefined when the check failed.
46
+ */
47
+ export declare function hostedGate(check?: (signal?: AbortSignal) => Promise<HostedCheck>): () => Promise<{
48
+ available: true;
49
+ } | {
50
+ available: false;
51
+ message: string;
52
+ } | undefined>;
@@ -0,0 +1,126 @@
1
+ import { ANDORRA_PROVIDER_BASE_URL, ANDORRA_SIGN_IN_MESSAGE, ANDORRA_UNAVAILABLE_MESSAGE, andorraAccessToken, andorraBaseUrl } from './endpoint.js';
2
+ export const HOSTED_CHECK_TIMEOUT_MS = 5_000;
3
+ const HOSTED_BODY_LIMIT = 64 * 1024;
4
+ function record(value) {
5
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
6
+ }
7
+ export function parseHostedAnswer(value) {
8
+ const body = record(value);
9
+ if (!body || typeof body.enabled !== 'boolean')
10
+ return undefined;
11
+ if (!body.enabled)
12
+ return { enabled: false, promotionId: null, models: [] };
13
+ if (typeof body.promotionId !== 'string' || !body.promotionId || !Array.isArray(body.models) || body.models.length === 0)
14
+ return undefined;
15
+ const models = [];
16
+ for (const entry of body.models) {
17
+ const item = record(entry);
18
+ if (!item || typeof item.id !== 'string' || item.id.length < 1 || item.id.length > 500)
19
+ return undefined;
20
+ if (typeof item.contextWindow !== 'number' || !Number.isSafeInteger(item.contextWindow) || item.contextWindow <= 0)
21
+ return undefined;
22
+ const name = typeof item.name === 'string' && item.name ? item.name : item.id;
23
+ models.push({ id: item.id, name, contextWindow: item.contextWindow });
24
+ }
25
+ const answer = { enabled: true, promotionId: body.promotionId, models };
26
+ const allowance = parseAllowance(body.allowance);
27
+ if (allowance)
28
+ answer.allowance = allowance;
29
+ if (typeof body.available === 'boolean')
30
+ answer.available = body.available;
31
+ return answer;
32
+ }
33
+ /** A malformed allowance is dropped on its own; it never fails the whole answer. */
34
+ function parseAllowance(value) {
35
+ const item = record(value);
36
+ if (!item)
37
+ return undefined;
38
+ const { usedPercent, resetsAt } = item;
39
+ if (typeof usedPercent !== 'number' || !Number.isInteger(usedPercent) || usedPercent < 0 || usedPercent > 100)
40
+ return undefined;
41
+ if (typeof resetsAt !== 'string' || !Number.isFinite(Date.parse(resetsAt)))
42
+ return undefined;
43
+ return { usedPercent, resetsAt };
44
+ }
45
+ async function readBounded(response) {
46
+ const reader = response.body?.getReader();
47
+ if (!reader)
48
+ return undefined;
49
+ const chunks = [];
50
+ let size = 0;
51
+ try {
52
+ for (;;) {
53
+ const { done, value } = await reader.read();
54
+ if (done)
55
+ break;
56
+ size += value.byteLength;
57
+ if (size > HOSTED_BODY_LIMIT)
58
+ return undefined;
59
+ chunks.push(value);
60
+ }
61
+ }
62
+ finally {
63
+ await reader.cancel().catch(() => { });
64
+ reader.releaseLock();
65
+ }
66
+ return Buffer.concat(chunks).toString('utf8');
67
+ }
68
+ export function createHostedClient(deps = {}) {
69
+ const accessToken = deps.accessToken ?? ((signal) => andorraAccessToken(signal));
70
+ const baseUrl = deps.baseUrl ?? (() => andorraBaseUrl());
71
+ const doFetch = deps.fetch ?? globalThis.fetch;
72
+ return async (signal) => {
73
+ try {
74
+ const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(HOSTED_CHECK_TIMEOUT_MS)]) : AbortSignal.timeout(HOSTED_CHECK_TIMEOUT_MS);
75
+ const token = await accessToken(bounded);
76
+ if (!token)
77
+ return { kind: 'signed-out' };
78
+ const response = await doFetch(`${baseUrl().replace(/\/+$/, '')}/hosted`, {
79
+ method: 'GET', redirect: 'error', signal: bounded, headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
80
+ });
81
+ if (response.status === 401) {
82
+ await response.body?.cancel().catch(() => { });
83
+ return { kind: 'signed-out' };
84
+ }
85
+ if (response.status !== 200) {
86
+ await response.body?.cancel().catch(() => { });
87
+ return { kind: 'failed' };
88
+ }
89
+ const text = await readBounded(response);
90
+ if (text === undefined)
91
+ return { kind: 'failed' };
92
+ const answer = parseHostedAnswer(JSON.parse(text));
93
+ return answer ? { kind: 'answer', answer } : { kind: 'failed' };
94
+ }
95
+ catch {
96
+ return { kind: 'failed' };
97
+ }
98
+ };
99
+ }
100
+ /** Set by this repository's test runner (`scripts/run-tests.mjs`) for the test files it starts, and by nothing else. */
101
+ export const TEST_RUN_MARKER = 'ANDORRA_TEST_RUN_ID';
102
+ /**
103
+ * The check a monitor runs when none is injected. In a run of this repository's own test runner (its marker
104
+ * variable is set) it asks nothing unless the loopback override is set, so a test that builds a client without
105
+ * injecting a check can never reach the production router with a developer's account. Nothing a user's own tools
106
+ * set (Node's test-runner variables among them) switches the check off.
107
+ */
108
+ export function defaultHostedCheck(env = process.env) {
109
+ if (env[TEST_RUN_MARKER] && andorraBaseUrl(env) === ANDORRA_PROVIDER_BASE_URL)
110
+ return async () => ({ kind: 'failed' });
111
+ return createHostedClient();
112
+ }
113
+ /**
114
+ * For a process that runs no monitor (a subagent run): asks the router once whether Andorra is on, so a run that
115
+ * cannot start is refused with the plain sentence and no model request. Undefined when the check failed.
116
+ */
117
+ export function hostedGate(check = defaultHostedCheck()) {
118
+ return async () => {
119
+ const result = await check().catch(() => ({ kind: 'failed' }));
120
+ if (result.kind === 'signed-out')
121
+ return { available: false, message: ANDORRA_SIGN_IN_MESSAGE };
122
+ if (result.kind === 'failed')
123
+ return undefined;
124
+ return result.answer.enabled ? { available: true } : { available: false, message: ANDORRA_UNAVAILABLE_MESSAGE };
125
+ };
126
+ }
@@ -0,0 +1,151 @@
1
+ import { type HostedAnswer, type HostedCheck, type HostedModel } from './hosted.js';
2
+ import { type AndorraAvailability, type HostedSurface } from './state.js';
3
+ export declare const HOSTED_CHECK_INTERVAL_MS: number;
4
+ export declare const HOSTED_OPEN_THROTTLE_MS = 30000;
5
+ /**
6
+ * How soon the router is asked again after a check failed or answered that nothing can serve a request, while
7
+ * signed in with an enabled answer on hand: an account with nothing to show is not asked every minute in an outage.
8
+ */
9
+ export declare const HOSTED_RETRY_INTERVAL_MS = 60000;
10
+ /** How many counted failures in a row (see HOSTED_FAILURE_SPACING_MS) make the usage read "not available". */
11
+ export declare const HOSTED_FAILURES_TO_UNAVAILABLE = 2;
12
+ /**
13
+ * A failed check counts toward HOSTED_FAILURES_TO_UNAVAILABLE only this long after the last failure that counted (the
14
+ * first always counts), so one blip seen by two checks moments apart (an interval check and a run-end check) is one failure.
15
+ */
16
+ export declare const HOSTED_FAILURE_SPACING_MS = 30000;
17
+ /**
18
+ * `account`: the user signed in or out. `add`: the user asked to add Andorra. `gate`: a run is about to start.
19
+ * `run-end`: a run that used an Andorra model ended. `retry`: the follow-up after a failed or unavailable check.
20
+ * Only `open` is throttled.
21
+ */
22
+ export type HostedCheckCause = 'startup' | 'interval' | 'open' | 'account' | 'add' | 'gate' | 'run-end' | 'retry';
23
+ /** What a client shows for the hosted models: the share of the weekly allowance used, or that they cannot answer now. */
24
+ export type HostedUsage = {
25
+ kind: 'meter';
26
+ usedPercent: number;
27
+ resetsAt: string;
28
+ } | {
29
+ kind: 'not-available';
30
+ };
31
+ export interface HostedTimers {
32
+ setInterval: typeof setInterval;
33
+ clearInterval: typeof clearInterval;
34
+ setTimeout?: typeof setTimeout;
35
+ clearTimeout?: typeof clearTimeout;
36
+ }
37
+ /** How long an answer counts as fresh: for refusing a run without asking again, and for adding without asking first. */
38
+ export declare const HOSTED_FRESH_MS = 30000;
39
+ export interface HostedAnnouncement {
40
+ promotionId: string;
41
+ offered: boolean;
42
+ }
43
+ export interface HostedMonitorOptions {
44
+ surface: HostedSurface;
45
+ home?: string;
46
+ check?: (signal?: AbortSignal) => Promise<HostedCheck>;
47
+ /**
48
+ * Called for enabled answers only: keeps an existing entry current, and creates a missing one only when the
49
+ * user added Andorra. It reads that decision itself (`andorraEntryMode`) inside its serialized config write.
50
+ */
51
+ applyEntry: (answer: HostedAnswer) => Promise<void>;
52
+ /** Whether the saved config holds an Andorra entry now. */
53
+ hasEntry: () => boolean | Promise<boolean>;
54
+ /** `offered`: there is no entry yet, so the message should say how to add one. */
55
+ onAnnounce: (announcement: HostedAnnouncement) => void;
56
+ onNotice: () => void;
57
+ /** Fired after every check has settled and after `entryChanged()`, whether or not anything differs: for lists that redraw themselves. */
58
+ onSettled?: () => void;
59
+ /** Fired when the availability, the offer, the listed models or the usage differ from the last ones reported. */
60
+ onChange?: (availability: AndorraAvailability, offered: boolean) => void;
61
+ now?: () => number;
62
+ timers?: HostedTimers;
63
+ }
64
+ /**
65
+ * Keeps one client's view of whether Andorra is offered: checks at startup, every
66
+ * HOSTED_CHECK_INTERVAL_MS, and when the provider list opens (at most once per
67
+ * HOSTED_OPEN_THROTTLE_MS). A failed check never changes the snapshot, the entry or the messages;
68
+ * it only counts toward the usage reading "not available", and asks again after HOSTED_RETRY_INTERVAL_MS.
69
+ * It creates nothing by itself: the entry appears when the user adds it (`addAndorraEntry`).
70
+ */
71
+ export declare class HostedMonitor {
72
+ private readonly options;
73
+ private readonly home;
74
+ private readonly runCheck;
75
+ private readonly now;
76
+ private readonly timers;
77
+ private answer;
78
+ /** The allowance and availability of the last answer a check in this process received; never read from the state file. */
79
+ private live;
80
+ private failures;
81
+ private failedAt;
82
+ private retry;
83
+ private signedIn;
84
+ private answeredAt;
85
+ private entryPresent;
86
+ private reported;
87
+ private decision;
88
+ private inflight;
89
+ private lastOpen;
90
+ private handle;
91
+ private stopped;
92
+ private generation;
93
+ private abort;
94
+ /** What this surface has shown, kept here while the state file could not be written, so nothing replays. */
95
+ private unsaved;
96
+ constructor(options: HostedMonitorOptions);
97
+ start(): Promise<void>;
98
+ check(cause: HostedCheckCause): Promise<AndorraAvailability>;
99
+ availability(): AndorraAvailability;
100
+ /**
101
+ * What to show for the hosted models: nothing while signed out or without an enabled answer on hand (received
102
+ * in this process, or saved by an earlier one); "not available" after HOSTED_FAILURES_TO_UNAVAILABLE counted
103
+ * failures in a row (see HOSTED_FAILURE_SPACING_MS); otherwise, from an answer received in this process only, "not
104
+ * available" when the router said nothing can answer, or the allowance used when it sent one. A saved answer holds no allowance, so it never gives a meter.
105
+ */
106
+ usage(): HostedUsage | undefined;
107
+ /** True when a check in this process answered (an answer, or signed out) within the last HOSTED_FRESH_MS. */
108
+ answeredRecently(): boolean;
109
+ /**
110
+ * What a run about to start on Andorra may rely on without sending a model request. A refusal is returned only
111
+ * from fresh knowledge: an "off" answer of the last HOSTED_FRESH_MS, or a check made right now. Anything older
112
+ * (and every "signed out", because another process sharing this home may have signed in since, and asking again
113
+ * costs nothing while still signed out) is asked again first: one check, bounded by the check's own timeout. A
114
+ * check already under way (the one after /login, say) is awaited rather than answered around. Undefined means
115
+ * nothing is known (no check has answered, or the one just made failed): the run's own probe then decides.
116
+ */
117
+ gate(): Promise<AndorraAvailability | undefined>;
118
+ /** The answer Andorra can be added from: one a check in this process received, signed in, turned on, with models. */
119
+ enabledAnswer(): HostedAnswer | undefined;
120
+ /** The hosted models while Andorra is offered to this account and not added yet; undefined otherwise. */
121
+ offer(): HostedModel[] | undefined;
122
+ /** Whether Andorra can be added now: hosted models are on for this account and the config has no entry. */
123
+ offered(): boolean;
124
+ /**
125
+ * The hosted models while Andorra is LISTED without being saved: offered, and not removed by the user. A client
126
+ * shows it then as an ordinary provider, first in its lists; the entry is written the first time the user picks it.
127
+ */
128
+ listed(): HostedModel[] | undefined;
129
+ /** Call after the entry was added or removed: reports the changed offer. */
130
+ entryChanged(): Promise<void>;
131
+ stop(): void;
132
+ /** Asks again after HOSTED_RETRY_INTERVAL_MS: one pending retry at most, replaced each time. */
133
+ private armRetry;
134
+ private clearRetry;
135
+ /** The user's decision as the state file has it; the last one known when the file cannot be read. */
136
+ private decided;
137
+ private present;
138
+ private report;
139
+ private run;
140
+ /**
141
+ * Records what the usage is read from, apart from the answer so it never reaches the state file, and asks
142
+ * again soon while the router cannot be reached or says nothing can answer, for an account that has hosted models
143
+ * to show: signed in, with the answer on hand (this one, or the one held before a failed check) enabled.
144
+ */
145
+ private track;
146
+ private settle;
147
+ /** Writes the state through the shared queue; while it cannot be written, what was shown is remembered here. */
148
+ private save;
149
+ private messages;
150
+ private fire;
151
+ }