@andorra-labs/code 0.1.13 → 0.1.15

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 (168) hide show
  1. package/dist/src/account-presentation.js +4 -1
  2. package/dist/src/acp-agent.d.ts +54 -0
  3. package/dist/src/acp-agent.js +991 -0
  4. package/dist/src/agent-execution.js +304 -140
  5. package/dist/src/agent-mcp-catalog.js +2 -0
  6. package/dist/src/agent-mcp.d.ts +2 -0
  7. package/dist/src/agent-mcp.js +86 -4
  8. package/dist/src/andorra/endpoint.d.ts +7 -0
  9. package/dist/src/andorra/endpoint.js +46 -0
  10. package/dist/src/andorra/entry.d.ts +21 -0
  11. package/dist/src/andorra/entry.js +118 -0
  12. package/dist/src/andorra/errors.d.ts +2 -0
  13. package/dist/src/andorra/errors.js +39 -0
  14. package/dist/src/andorra/hosted.d.ts +55 -0
  15. package/dist/src/andorra/hosted.js +130 -0
  16. package/dist/src/andorra/monitor.d.ts +151 -0
  17. package/dist/src/andorra/monitor.js +393 -0
  18. package/dist/src/andorra/notices.d.ts +16 -0
  19. package/dist/src/andorra/notices.js +38 -0
  20. package/dist/src/andorra/opt-in.d.ts +58 -0
  21. package/dist/src/andorra/opt-in.js +112 -0
  22. package/dist/src/andorra/request-watch.d.ts +6 -0
  23. package/dist/src/andorra/request-watch.js +10 -0
  24. package/dist/src/andorra/state.d.ts +86 -0
  25. package/dist/src/andorra/state.js +238 -0
  26. package/dist/src/andorra/terminal.d.ts +70 -0
  27. package/dist/src/andorra/terminal.js +125 -0
  28. package/dist/src/andorra/usage-format.d.ts +9 -0
  29. package/dist/src/andorra/usage-format.js +19 -0
  30. package/dist/src/anthropic-credentials.js +9 -1
  31. package/dist/src/app-server/protocol.d.ts +10 -2
  32. package/dist/src/app-server/protocol.js +1 -1
  33. package/dist/src/app-server/workspace.d.ts +1 -0
  34. package/dist/src/app-server/workspace.js +141 -10
  35. package/dist/src/app-server.d.ts +35 -0
  36. package/dist/src/app-server.js +377 -124
  37. package/dist/src/auth/AuthManager.d.ts +9 -0
  38. package/dist/src/auth/AuthManager.js +164 -24
  39. package/dist/src/auth/deployment.d.ts +1 -0
  40. package/dist/src/auth/deployment.js +1 -0
  41. package/dist/src/auth/index.d.ts +1 -1
  42. package/dist/src/auth/index.js +1 -1
  43. package/dist/src/auth/store.d.ts +26 -0
  44. package/dist/src/auth/store.js +34 -1
  45. package/dist/src/browser-bridge.d.ts +1 -0
  46. package/dist/src/browser-bridge.js +5 -2
  47. package/dist/src/browser-external-app.d.ts +27 -0
  48. package/dist/src/browser-external-app.js +60 -0
  49. package/dist/src/browser-panel-tool.d.ts +6 -0
  50. package/dist/src/browser-panel-tool.js +36 -0
  51. package/dist/src/browser-runner.js +1 -1
  52. package/dist/src/browser-server.d.ts +5 -0
  53. package/dist/src/browser-server.js +27 -3
  54. package/dist/src/browser-stealth.d.ts +19 -1
  55. package/dist/src/browser-stealth.js +23 -3
  56. package/dist/src/browser-ui/tokens.css +4 -4
  57. package/dist/src/browser-view.d.ts +81 -0
  58. package/dist/src/browser-view.js +289 -18
  59. package/dist/src/bug-report.d.ts +81 -0
  60. package/dist/src/bug-report.js +235 -0
  61. package/dist/src/claude-provider.d.ts +2 -1
  62. package/dist/src/claude-provider.js +10 -8
  63. package/dist/src/cli-sign-in.d.ts +3 -1
  64. package/dist/src/cli-sign-in.js +4 -1
  65. package/dist/src/cli.js +205 -58
  66. package/dist/src/coding-tools.js +7 -7
  67. package/dist/src/command-screens.d.ts +26 -3
  68. package/dist/src/command-screens.js +323 -85
  69. package/dist/src/commands.d.ts +7 -1
  70. package/dist/src/commands.js +79 -27
  71. package/dist/src/completion-gates.d.ts +22 -0
  72. package/dist/src/completion-gates.js +11 -0
  73. package/dist/src/config.d.ts +11 -1
  74. package/dist/src/config.js +134 -3
  75. package/dist/src/dashboard-view.d.ts +2 -0
  76. package/dist/src/dashboard-view.js +11 -2
  77. package/dist/src/decision/PreparedSteps.js +1 -1
  78. package/dist/src/decision/applyToolMenu.js +1 -1
  79. package/dist/src/decision/toolFamilies.js +1 -1
  80. package/dist/src/decision/types.d.ts +1 -0
  81. package/dist/src/google-provider.d.ts +31 -0
  82. package/dist/src/google-provider.js +153 -0
  83. package/dist/src/graph-health.d.ts +11 -0
  84. package/dist/src/graph-health.js +36 -4
  85. package/dist/src/graph-manager-chat.d.ts +33 -0
  86. package/dist/src/graph-manager-chat.js +165 -6
  87. package/dist/src/graph-runner.js +27 -0
  88. package/dist/src/graph-selection.js +2 -1
  89. package/dist/src/graph-sync.d.ts +1 -0
  90. package/dist/src/graph-sync.js +93 -34
  91. package/dist/src/graph-tool.d.ts +2 -0
  92. package/dist/src/graph-tool.js +2 -2
  93. package/dist/src/graph-ui/app.js +92 -10
  94. package/dist/src/graph-ui/edge-router.js +121 -53
  95. package/dist/src/graph-ui/manager.js +40 -5
  96. package/dist/src/graph-ui/style.css +5 -2
  97. package/dist/src/graph-ui/tokens.css +4 -4
  98. package/dist/src/graph-visibility.d.ts +31 -0
  99. package/dist/src/graph-visibility.js +102 -0
  100. package/dist/src/graphs.js +1 -3
  101. package/dist/src/hardened-runtime.js +1 -1
  102. package/dist/src/live-model.d.ts +24 -0
  103. package/dist/src/live-model.js +37 -0
  104. package/dist/src/managed-sign-in.d.ts +1 -0
  105. package/dist/src/managed-sign-in.js +13 -0
  106. package/dist/src/membership-errors.d.ts +2 -0
  107. package/dist/src/membership-errors.js +6 -2
  108. package/dist/src/membership.d.ts +13 -2
  109. package/dist/src/membership.js +39 -8
  110. package/dist/src/model-context-windows.d.ts +2 -0
  111. package/dist/src/model-context-windows.js +24 -0
  112. package/dist/src/model-health-cache.js +1 -1
  113. package/dist/src/model-metadata.d.ts +1 -0
  114. package/dist/src/model-metadata.js +47 -3
  115. package/dist/src/paged-transcript.d.ts +2 -0
  116. package/dist/src/paged-transcript.js +16 -0
  117. package/dist/src/palette.d.ts +1 -0
  118. package/dist/src/palette.js +1 -1
  119. package/dist/src/permissions.js +17 -4
  120. package/dist/src/provider-connection.js +32 -0
  121. package/dist/src/provider-engine.d.ts +5 -0
  122. package/dist/src/provider-engine.js +3 -3
  123. package/dist/src/provider-import.js +3 -1
  124. package/dist/src/provider-settings.d.ts +16 -1
  125. package/dist/src/provider-settings.js +50 -22
  126. package/dist/src/providers.d.ts +29 -3
  127. package/dist/src/providers.js +100 -18
  128. package/dist/src/react-runtime.js +33 -12
  129. package/dist/src/read-document-tool.d.ts +2 -0
  130. package/dist/src/read-document-tool.js +6 -6
  131. package/dist/src/remote/engine-pool.js +31 -6
  132. package/dist/src/run-control.d.ts +2 -2
  133. package/dist/src/run-control.js +9 -6
  134. package/dist/src/runtime-environment.d.ts +1 -0
  135. package/dist/src/runtime-environment.js +13 -0
  136. package/dist/src/runtime.d.ts +2 -0
  137. package/dist/src/runtime.js +2 -1
  138. package/dist/src/save-lock.js +14 -7
  139. package/dist/src/session-title.d.ts +3 -0
  140. package/dist/src/session-title.js +5 -2
  141. package/dist/src/sessions.d.ts +1 -0
  142. package/dist/src/sessions.js +4 -2
  143. package/dist/src/sign-in-detection.d.ts +1 -1
  144. package/dist/src/sign-in-detection.js +10 -3
  145. package/dist/src/sign-in-offer.js +1 -1
  146. package/dist/src/skill-commands.js +1 -1
  147. package/dist/src/skills/bundled/bug-report/SKILL.md +80 -0
  148. package/dist/src/skills/bundled/graph-manager/SKILL.md +9 -1
  149. package/dist/src/skills/bundled/graph-manager/errors.md +2 -1
  150. package/dist/src/skills/bundled/provenance.json +743 -738
  151. package/dist/src/skills/runtime-skills.js +1 -0
  152. package/dist/src/subagent-run.d.ts +2 -0
  153. package/dist/src/subagent-run.js +14 -3
  154. package/dist/src/telemetry/schema.d.ts +1 -1
  155. package/dist/src/telemetry/schema.js +2 -2
  156. package/dist/src/telemetry/uploader.d.ts +7 -1
  157. package/dist/src/telemetry/uploader.js +11 -2
  158. package/dist/src/terminal-links.d.ts +16 -0
  159. package/dist/src/terminal-links.js +113 -0
  160. package/dist/src/terminal-ui.d.ts +29 -1
  161. package/dist/src/terminal-ui.js +113 -24
  162. package/dist/src/tool-catalog.js +1 -1
  163. package/dist/src/trajectory.js +6 -1
  164. package/dist/src/transcript.d.ts +2 -0
  165. package/dist/src/transcript.js +5 -1
  166. package/dist/src/types.d.ts +5 -0
  167. package/dist/src/workspace-instructions.js +1 -1
  168. package/package.json +13 -1
@@ -23,6 +23,8 @@ export const AGENT_MCP_CATALOG = [
23
23
  { name: 'andorra_graph_delete', description: 'Soft-delete a graph after the user confirms in chat: publishes a revision marked deleted, hides it from listings and new runs, keeps every revision. confirm must repeat the id.', inputSchema: obj({ id: str, expectedRevision: { type: 'integer', minimum: 1 }, confirm: str }, ['id', 'expectedRevision', 'confirm']) },
24
24
  { name: 'andorra_graph_restore', description: 'Restore a soft-deleted graph by publishing the next revision without the deleted marker.', inputSchema: obj({ id: str, expectedRevision: { type: 'integer', minimum: 1 } }, ['id', 'expectedRevision']) },
25
25
  { name: 'andorra_graph_discard', description: 'Discard an unpublished local graph draft.', inputSchema: obj(graphDraftSchema, ['draftId']) },
26
+ { name: 'andorra_graph_visibility_get', description: 'Read which projects list a published graph in their graph picker (everywhere, or only the named project paths), and the registered project paths it can be limited to.', inputSchema: obj({ id: str }, ['id']) },
27
+ { name: 'andorra_graph_visibility_set', description: 'Choose which projects list a published graph. projects is "this" (the project this task runs in), "all" (every project), or a list of registered project paths (andorra_graph_visibility_get lists them).', inputSchema: obj({ id: str, projects: { oneOf: [{ type: 'string', enum: ['this', 'all'] }, { type: 'array', items: str, minItems: 1 }] } }, ['id', 'projects']) },
26
28
  { name: 'andorra_projects_list', description: 'List registered projects and discovered session workspaces.', inputSchema: obj({}) },
27
29
  { name: 'andorra_sessions_list', description: 'Search sessions by project, status and last X minutes (lookbackMinutes). Supports paginated results.', inputSchema: obj({ ...searchFilters, status: { type: 'string', enum: ['completed', 'pending', 'running', 'required_input', 'incomplete'] },
28
30
  offset: num, limit: { type: 'integer', minimum: 1, maximum: 100 } }) },
@@ -87,7 +87,9 @@ export declare class AgentMcpBackend {
87
87
  private upsertEdge;
88
88
  call(name: string, rawArgs?: unknown, options?: {
89
89
  beforeSave?: () => void;
90
+ workspace?: string;
90
91
  }): Promise<AgentMcpReply>;
92
+ private graphVisibility;
91
93
  private dispatch;
92
94
  }
93
95
  export { AGENT_MCP_TOOL_NAMES };
@@ -1,8 +1,11 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { realpath } from 'node:fs/promises';
3
+ import { isAbsolute, relative } from 'node:path';
2
4
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
5
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
6
  import { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';
5
7
  import { configDirectory, loadConfig } from './config.js';
8
+ import { graphVisibilityFor, setGraphVisibility } from './graph-visibility.js';
6
9
  import { graphStorageDirectory } from './graph-account.js';
7
10
  import { GraphSync } from './graph-sync.js';
8
11
  import { stampGraphProviderProfiles } from './graph-provider-portability.js';
@@ -65,7 +68,16 @@ export const GRAPH_AGENT_GUIDE = [
65
68
  'Sessions that already ran it keep resuming. andorra_graphs_list {includeDeleted:true} lists deleted graphs with deleted=true.',
66
69
  'andorra_graph_restore {id, expectedRevision} publishes the next revision without the marker.',
67
70
  '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.',
71
+ 'DEFAULT_GRAPH: the bundled Default graph cannot be deleted.',
72
+ '',
73
+ '## Project visibility',
74
+ 'A published graph is listed in every project\'s graph picker until it is limited to some projects.',
75
+ 'andorra_graph_visibility_get {id} reports {visibleIn: "all"} or {visibleIn: "projects", projects: [paths]}.',
76
+ 'andorra_graph_visibility_set {id, projects} changes it: "this" limits the graph to the project the task runs in,',
77
+ '"all" lists it everywhere again, and a list of paths names registered projects; the get reply lists them in registeredProjects.',
78
+ 'When the user asks for a graph to be visible only in a project, call andorra_graph_visibility_set after publishing;',
79
+ 'never record visibility in graph metadata, which nothing reads. The bundled Default graph is always listed everywhere.',
80
+ 'PROJECT_NOT_REGISTERED: the path is not a project in the sidebar; the error lists the registered ones.',
69
81
  'CONFIRMATION_MISMATCH: confirm must equal id. GRAPH_IN_USE: an automation runs the graph; the error lists them; change them first.',
70
82
  'GRAPH_DELETED: the graph is deleted; restore it before editing or deleting it again. GRAPH_NOT_DELETED: restore needs a deleted graph.',
71
83
  'RESERVED_METADATA: metadata.deletedAt is set only by the delete and restore tools; andorra_graph_patch and publishing refuse it.',
@@ -413,7 +425,7 @@ export class AgentMcpBackend {
413
425
  const tool = deleting ? 'andorra_graph_delete' : 'andorra_graph_restore';
414
426
  const id = field(args, 'id');
415
427
  if (id === 'default' || id.includes(':'))
416
- throw new AgentMcpError('DEFAULT_GRAPH', 'The bundled Default graph and the Andorra preset cannot be deleted or restored.');
428
+ throw new AgentMcpError('DEFAULT_GRAPH', 'The bundled Default graph cannot be deleted or restored.');
417
429
  if (!safeId(id))
418
430
  throw new AgentMcpError('INVALID_GRAPH_ID', 'Graph id must be a safe identifier of 1-80 characters.');
419
431
  if (Object.keys(args).some(key => !['id', 'expectedRevision', ...(deleting ? ['confirm'] : [])].includes(key)))
@@ -533,7 +545,7 @@ export class AgentMcpBackend {
533
545
  }
534
546
  async call(name, rawArgs = {}, options = {}) {
535
547
  try {
536
- return { ok: true, data: await this.dispatch(name, argsRecord(rawArgs), options.beforeSave) };
548
+ return { ok: true, data: await this.dispatch(name, argsRecord(rawArgs), options.beforeSave, options.workspace) };
537
549
  }
538
550
  catch (error) {
539
551
  if (error instanceof GraphConflictError)
@@ -543,6 +555,9 @@ export class AgentMcpBackend {
543
555
  return { ok: false, error: { code: error.code, message: error.message } };
544
556
  if (error instanceof FreeTierLimitError)
545
557
  return { ok: false, error: { code: error.code, message: error.message } };
558
+ if (error instanceof PaidMembershipRequiredError && error.unavailable)
559
+ return { ok: false, error: { code: 'MEMBERSHIP_UNAVAILABLE',
560
+ message: error.message + ' An open draft is kept: repeat the same call after a short wait.' } };
546
561
  if (error instanceof PaidMembershipRequiredError) {
547
562
  const status = await getAuthStatus().catch(() => undefined);
548
563
  return { ok: false, error: status?.signedIn
@@ -556,7 +571,71 @@ export class AgentMcpBackend {
556
571
  return { ok: false, error: backendIssue(error) };
557
572
  }
558
573
  }
559
- async dispatch(name, args, beforeSave) {
574
+ async graphVisibility(setting, args, access, beforeSave, workspace) {
575
+ const id = field(args, 'id');
576
+ if (id === 'default')
577
+ throw new AgentMcpError('DEFAULT_GRAPH', 'The bundled Default graph is always listed in every project.');
578
+ if (!access.subject)
579
+ throw new AgentMcpError('AUTH_REQUIRED', 'Sign in to your Andorra Code account to choose where a graph is listed.');
580
+ const graph = await this.readGraph(id, access.directory);
581
+ if (isDeletedGraph(graph))
582
+ throw new AgentMcpError('GRAPH_DELETED', 'Graph ' + id + ' is deleted. Restore it with andorra_graph_restore before changing where it is listed.');
583
+ const describe = (visibility) => {
584
+ const projects = visibility[id];
585
+ return projects === undefined ? { id, visibleIn: 'all' } : { id, visibleIn: 'projects', projects };
586
+ };
587
+ if (!setting) {
588
+ const config = await loadConfig(this.directory);
589
+ await this.assertGraphIdentity(access);
590
+ // The registered projects are what a list of paths may name; the graphs tool has no project listing of its own.
591
+ return { ...describe(graphVisibilityFor(config, access.subject)), registeredProjects: (config.projects ?? []).map(project => project.path) };
592
+ }
593
+ const requested = args.projects;
594
+ const registered = ((await loadConfig(this.directory)).projects ?? []).map(project => project.path);
595
+ const same = (a, b) => process.platform === 'win32' ? a.toLowerCase() === b.toLowerCase() : a === b;
596
+ const notRegistered = (path) => new AgentMcpError('PROJECT_NOT_REGISTERED', path + ' is not a project in the Andorra sidebar. Registered projects: ' + (registered.length ? registered.join(', ') : 'none') + '.');
597
+ const resolveProject = async (path, containing) => {
598
+ let real;
599
+ try {
600
+ real = await realpath(path);
601
+ }
602
+ catch {
603
+ real = path;
604
+ }
605
+ const exact = registered.find(project => same(project, real) || same(project, path));
606
+ if (exact)
607
+ return exact;
608
+ if (containing) {
609
+ // A task can run in a folder inside a project; it belongs to the closest registered project that holds it.
610
+ const holders = registered.filter(project => { const rel = relative(project, real); return rel !== '' && !rel.startsWith('..') && !isAbsolute(rel); });
611
+ const closest = holders.sort((a, b) => b.length - a.length)[0];
612
+ if (closest)
613
+ return closest;
614
+ }
615
+ throw notRegistered(path);
616
+ };
617
+ let projects;
618
+ if (requested === 'all')
619
+ projects = undefined;
620
+ else if (requested === 'this') {
621
+ const here = workspace ?? this.options.subagentWorkspace ?? process.cwd();
622
+ projects = [await resolveProject(here, true)];
623
+ }
624
+ else if (Array.isArray(requested) && requested.length > 0 && requested.every(path => typeof path === 'string' && path.trim() && !path.includes('\0'))) {
625
+ projects = [];
626
+ for (const path of requested)
627
+ projects.push(await resolveProject(path.trim(), false));
628
+ }
629
+ else
630
+ throw new AgentMcpError('INVALID_ARGUMENTS', 'projects must be "this", "all", or a non-empty list of registered project paths.');
631
+ beforeSave?.();
632
+ await this.assertGraphIdentity(access);
633
+ const visibility = await setGraphVisibility(this.directory, access.subject, id, projects);
634
+ return { ...describe(visibility), note: projects === undefined
635
+ ? 'The graph is listed in every project.'
636
+ : 'The graph is listed only in ' + projects.join(', ') + '. Other projects no longer offer it in the graph picker.' };
637
+ }
638
+ async dispatch(name, args, beforeSave, workspace) {
560
639
  if (name === 'andorra_graph_guide')
561
640
  return { architecture: GRAPH_AGENT_GUIDE, resourceUri: 'andorra://graph/architecture' };
562
641
  if (name === 'andorra_projects_list')
@@ -655,6 +734,9 @@ export class AgentMcpBackend {
655
734
  return cancelled ? { cancelled: true } : { cancelled: false, note: 'No subagent run is active in this process.' };
656
735
  }
657
736
  const access = await this.graphAccess();
737
+ if (name === 'andorra_graph_visibility_get' || name === 'andorra_graph_visibility_set') {
738
+ return this.graphVisibility(name === 'andorra_graph_visibility_set', args, access, beforeSave, workspace);
739
+ }
658
740
  if (name === 'andorra_graphs_list') {
659
741
  if (args.includeDeleted !== undefined && typeof args.includeDeleted !== 'boolean')
660
742
  throw new AgentMcpError('INVALID_ARGUMENTS', 'includeDeleted must be a boolean when supplied.');
@@ -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,118 @@
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
+ function sameNumbers(a, b) {
33
+ const left = a ?? {};
34
+ const keys = Object.keys(b);
35
+ return Object.keys(left).length === keys.length && keys.every(key => Object.hasOwn(left, key) && left[key] === b[key]);
36
+ }
37
+ const UNSAFE_KEYS = ['__proto__', 'constructor', 'prototype'];
38
+ /** The sizes the answer states, by model id. */
39
+ function hostedParameters(answer) {
40
+ const sizes = {};
41
+ for (const model of answer.models)
42
+ if (model.parametersBillions !== undefined && !UNSAFE_KEYS.includes(model.id))
43
+ sizes[model.id] = model.parametersBillions;
44
+ return sizes;
45
+ }
46
+ // Line breaks and tabs become spaces; every other control, format or bidi character is dropped.
47
+ const SPACING = /[\t\n\v\f\r\u0085\u2028\u2029]/g;
48
+ const INVISIBLE = /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u206f\ufeff]/g;
49
+ /** A router-supplied model name made safe to show: one line, no control characters, at most 80 characters; undefined when nothing is left. */
50
+ export function cleanModelName(name) {
51
+ const cleaned = name.replace(SPACING, ' ').replace(INVISIBLE, '').replace(/\s+/g, ' ').trim();
52
+ const capped = [...cleaned].slice(0, MAX_MODEL_DISPLAY_NAME_LENGTH).join('').trim();
53
+ return capped || undefined;
54
+ }
55
+ /** The display names worth keeping: cleaned, and only where they differ from the id (the id is shown otherwise). */
56
+ function hostedNames(answer) {
57
+ const names = {};
58
+ for (const model of answer.models) {
59
+ const name = cleanModelName(model.name);
60
+ if (name !== undefined && name !== model.id && !['__proto__', 'constructor', 'prototype'].includes(model.id))
61
+ names[model.id] = name;
62
+ }
63
+ return names;
64
+ }
65
+ /**
66
+ * The config with the Andorra entry added or refreshed from a hosted answer, or undefined when nothing changes.
67
+ * Never mutates `config`, and never changes the selected provider unless the config had no providers at all.
68
+ * An existing entry is refreshed in every mode; a missing one is created, first in the list, only in 'create' mode.
69
+ */
70
+ export function applyAndorraEntry(config, answer, mode) {
71
+ if (!answer.enabled || answer.models.length === 0)
72
+ return undefined;
73
+ const models = answer.models.map(model => model.id);
74
+ const modelContextWindows = {};
75
+ for (const model of answer.models)
76
+ modelContextWindows[model.id] = model.contextWindow;
77
+ const modelNames = hostedNames(answer);
78
+ const modelParameters = hostedParameters(answer);
79
+ const freeModels = answer.models.filter(model => model.free === true).map(model => model.id);
80
+ const named = { ...(Object.keys(modelNames).length ? { modelNames } : {}),
81
+ ...(Object.keys(modelParameters).length ? { modelParameters } : {}), ...(freeModels.length ? { freeModels } : {}) };
82
+ const index = config.providers.findIndex(provider => provider.type === 'andorra');
83
+ if (index < 0) {
84
+ if (mode !== 'create')
85
+ return undefined;
86
+ const entry = { id: freeId(config.providers), type: 'andorra', name: ANDORRA_NAME, baseUrl: ANDORRA_PROVIDER_BASE_URL,
87
+ model: models[0], models, modelContextWindows, ...named };
88
+ return { ...config, providers: [entry, ...config.providers], provider: config.providers.length === 0 ? entry.id : config.provider };
89
+ }
90
+ const existing = config.providers[index];
91
+ const model = models.includes(existing.model) ? existing.model : models[0];
92
+ if (model === existing.model && sameList(existing.models, models) && sameWindows(existing.modelContextWindows, modelContextWindows)
93
+ && sameNames(existing.modelNames, modelNames) && sameNumbers(existing.modelParameters, modelParameters)
94
+ && sameList(existing.freeModels ?? [], freeModels))
95
+ return undefined;
96
+ const { modelNames: _previous, modelParameters: _sizes, freeModels: _free, ...rest } = existing;
97
+ const refreshed = { ...rest, model, models, modelContextWindows, ...named };
98
+ if (refreshed.contextWindow !== undefined)
99
+ applyModelContextWindow(refreshed, model);
100
+ const providers = config.providers.slice();
101
+ providers[index] = refreshed;
102
+ // A model the hosted answer dropped may be the one the external subagent setting names: that pair is cleared, as it
103
+ // is for every other change of a provider's model list, so the config still validates and the refresh can be saved.
104
+ return reconcileSubagentPair({ ...config, providers });
105
+ }
106
+ /**
107
+ * The entry Andorra would be saved as from this answer, for a config that has none: what a client lists while
108
+ * Andorra is offered and not saved yet. It exists in memory only; nothing validates, saves or sends requests with it.
109
+ */
110
+ export function virtualAndorraEntry(config, answer) {
111
+ if (hasAndorraEntry(config))
112
+ return undefined;
113
+ return applyAndorraEntry({ version: 1, provider: '', providers: [...config.providers] }, answer, 'create')?.providers[0];
114
+ }
115
+ /** The provider to select when the active one goes away: never Andorra by position. */
116
+ export function fallbackProviderId(providers) {
117
+ return providers.find(provider => provider.type !== 'andorra')?.id ?? providers[0]?.id ?? '';
118
+ }
@@ -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,55 @@
1
+ /** `parametersBillions`: the model's size, where the router states one. `free`: served past the weekly allowance. */
2
+ export interface HostedModel {
3
+ id: string;
4
+ name: string;
5
+ contextWindow: number;
6
+ parametersBillions?: number;
7
+ free?: boolean;
8
+ }
9
+ /** How much of the account's weekly allowance is used (0-100) and when it renews (ISO timestamp). */
10
+ export interface HostedAllowance {
11
+ usedPercent: number;
12
+ resetsAt: string;
13
+ }
14
+ export interface HostedAnswer {
15
+ enabled: boolean;
16
+ promotionId: string | null;
17
+ models: HostedModel[];
18
+ allowance?: HostedAllowance;
19
+ available?: boolean;
20
+ }
21
+ export type HostedCheck = {
22
+ kind: 'answer';
23
+ answer: HostedAnswer;
24
+ } | {
25
+ kind: 'signed-out';
26
+ } | {
27
+ kind: 'failed';
28
+ };
29
+ export declare const HOSTED_CHECK_TIMEOUT_MS = 5000;
30
+ export declare function parseHostedAnswer(value: unknown): HostedAnswer | undefined;
31
+ export interface HostedClientDeps {
32
+ accessToken(signal?: AbortSignal): Promise<string | undefined>;
33
+ baseUrl(): string;
34
+ fetch: typeof fetch;
35
+ }
36
+ export declare function createHostedClient(deps?: Partial<HostedClientDeps>): (signal?: AbortSignal) => Promise<HostedCheck>;
37
+ /** Set by this repository's test runner (`scripts/run-tests.mjs`) for the test files it starts, and by nothing else. */
38
+ export declare const TEST_RUN_MARKER = "ANDORRA_TEST_RUN_ID";
39
+ /**
40
+ * The check a monitor runs when none is injected. In a run of this repository's own test runner (its marker
41
+ * variable is set) it asks nothing unless the loopback override is set, so a test that builds a client without
42
+ * injecting a check can never reach the production router with a developer's account. Nothing a user's own tools
43
+ * set (Node's test-runner variables among them) switches the check off.
44
+ */
45
+ export declare function defaultHostedCheck(env?: NodeJS.ProcessEnv): (signal?: AbortSignal) => Promise<HostedCheck>;
46
+ /**
47
+ * For a process that runs no monitor (a subagent run): asks the router once whether Andorra is on, so a run that
48
+ * cannot start is refused with the plain sentence and no model request. Undefined when the check failed.
49
+ */
50
+ export declare function hostedGate(check?: (signal?: AbortSignal) => Promise<HostedCheck>): () => Promise<{
51
+ available: true;
52
+ } | {
53
+ available: false;
54
+ message: string;
55
+ } | undefined>;
@@ -0,0 +1,130 @@
1
+ import { isModelParameters } from '../providers.js';
2
+ import { ANDORRA_PROVIDER_BASE_URL, ANDORRA_SIGN_IN_MESSAGE, ANDORRA_UNAVAILABLE_MESSAGE, andorraAccessToken, andorraBaseUrl } from './endpoint.js';
3
+ export const HOSTED_CHECK_TIMEOUT_MS = 5_000;
4
+ const HOSTED_BODY_LIMIT = 64 * 1024;
5
+ function record(value) {
6
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
7
+ }
8
+ export function parseHostedAnswer(value) {
9
+ const body = record(value);
10
+ if (!body || typeof body.enabled !== 'boolean')
11
+ return undefined;
12
+ if (!body.enabled)
13
+ return { enabled: false, promotionId: null, models: [] };
14
+ if (typeof body.promotionId !== 'string' || !body.promotionId || !Array.isArray(body.models) || body.models.length === 0)
15
+ return undefined;
16
+ const models = [];
17
+ for (const entry of body.models) {
18
+ const item = record(entry);
19
+ if (!item || typeof item.id !== 'string' || item.id.length < 1 || item.id.length > 500)
20
+ return undefined;
21
+ if (typeof item.contextWindow !== 'number' || !Number.isSafeInteger(item.contextWindow) || item.contextWindow <= 0)
22
+ return undefined;
23
+ const name = typeof item.name === 'string' && item.name ? item.name : item.id;
24
+ // Both are optional and descriptive: a malformed one is dropped on its own and never fails the answer.
25
+ models.push({ id: item.id, name, contextWindow: item.contextWindow,
26
+ ...(isModelParameters(item.parametersBillions) ? { parametersBillions: item.parametersBillions } : {}),
27
+ ...(item.free === true ? { free: true } : {}) });
28
+ }
29
+ const answer = { enabled: true, promotionId: body.promotionId, models };
30
+ const allowance = parseAllowance(body.allowance);
31
+ if (allowance)
32
+ answer.allowance = allowance;
33
+ if (typeof body.available === 'boolean')
34
+ answer.available = body.available;
35
+ return answer;
36
+ }
37
+ /** A malformed allowance is dropped on its own; it never fails the whole answer. */
38
+ function parseAllowance(value) {
39
+ const item = record(value);
40
+ if (!item)
41
+ return undefined;
42
+ const { usedPercent, resetsAt } = item;
43
+ if (typeof usedPercent !== 'number' || !Number.isInteger(usedPercent) || usedPercent < 0 || usedPercent > 100)
44
+ return undefined;
45
+ if (typeof resetsAt !== 'string' || !Number.isFinite(Date.parse(resetsAt)))
46
+ return undefined;
47
+ return { usedPercent, resetsAt };
48
+ }
49
+ async function readBounded(response) {
50
+ const reader = response.body?.getReader();
51
+ if (!reader)
52
+ return undefined;
53
+ const chunks = [];
54
+ let size = 0;
55
+ try {
56
+ for (;;) {
57
+ const { done, value } = await reader.read();
58
+ if (done)
59
+ break;
60
+ size += value.byteLength;
61
+ if (size > HOSTED_BODY_LIMIT)
62
+ return undefined;
63
+ chunks.push(value);
64
+ }
65
+ }
66
+ finally {
67
+ await reader.cancel().catch(() => { });
68
+ reader.releaseLock();
69
+ }
70
+ return Buffer.concat(chunks).toString('utf8');
71
+ }
72
+ export function createHostedClient(deps = {}) {
73
+ const accessToken = deps.accessToken ?? ((signal) => andorraAccessToken(signal));
74
+ const baseUrl = deps.baseUrl ?? (() => andorraBaseUrl());
75
+ const doFetch = deps.fetch ?? globalThis.fetch;
76
+ return async (signal) => {
77
+ try {
78
+ const bounded = signal ? AbortSignal.any([signal, AbortSignal.timeout(HOSTED_CHECK_TIMEOUT_MS)]) : AbortSignal.timeout(HOSTED_CHECK_TIMEOUT_MS);
79
+ const token = await accessToken(bounded);
80
+ if (!token)
81
+ return { kind: 'signed-out' };
82
+ const response = await doFetch(`${baseUrl().replace(/\/+$/, '')}/hosted`, {
83
+ method: 'GET', redirect: 'error', signal: bounded, headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' },
84
+ });
85
+ if (response.status === 401) {
86
+ await response.body?.cancel().catch(() => { });
87
+ return { kind: 'signed-out' };
88
+ }
89
+ if (response.status !== 200) {
90
+ await response.body?.cancel().catch(() => { });
91
+ return { kind: 'failed' };
92
+ }
93
+ const text = await readBounded(response);
94
+ if (text === undefined)
95
+ return { kind: 'failed' };
96
+ const answer = parseHostedAnswer(JSON.parse(text));
97
+ return answer ? { kind: 'answer', answer } : { kind: 'failed' };
98
+ }
99
+ catch {
100
+ return { kind: 'failed' };
101
+ }
102
+ };
103
+ }
104
+ /** Set by this repository's test runner (`scripts/run-tests.mjs`) for the test files it starts, and by nothing else. */
105
+ export const TEST_RUN_MARKER = 'ANDORRA_TEST_RUN_ID';
106
+ /**
107
+ * The check a monitor runs when none is injected. In a run of this repository's own test runner (its marker
108
+ * variable is set) it asks nothing unless the loopback override is set, so a test that builds a client without
109
+ * injecting a check can never reach the production router with a developer's account. Nothing a user's own tools
110
+ * set (Node's test-runner variables among them) switches the check off.
111
+ */
112
+ export function defaultHostedCheck(env = process.env) {
113
+ if (env[TEST_RUN_MARKER] && andorraBaseUrl(env) === ANDORRA_PROVIDER_BASE_URL)
114
+ return async () => ({ kind: 'failed' });
115
+ return createHostedClient();
116
+ }
117
+ /**
118
+ * For a process that runs no monitor (a subagent run): asks the router once whether Andorra is on, so a run that
119
+ * cannot start is refused with the plain sentence and no model request. Undefined when the check failed.
120
+ */
121
+ export function hostedGate(check = defaultHostedCheck()) {
122
+ return async () => {
123
+ const result = await check().catch(() => ({ kind: 'failed' }));
124
+ if (result.kind === 'signed-out')
125
+ return { available: false, message: ANDORRA_SIGN_IN_MESSAGE };
126
+ if (result.kind === 'failed')
127
+ return undefined;
128
+ return result.answer.enabled ? { available: true } : { available: false, message: ANDORRA_UNAVAILABLE_MESSAGE };
129
+ };
130
+ }