@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
@@ -1,6 +1,6 @@
1
1
  import { currentGraphSubject } from './graph-selection.js';
2
2
  import { loadAccessibleGraph, type Membership } from './membership.js';
3
- import type { CommandState } from './commands.js';
3
+ import { type CommandState } from './commands.js';
4
4
  import type { Config } from './config.js';
5
5
  import { type ProviderConfig } from './providers.js';
6
6
  import type { ModelAdapter } from './types.js';
@@ -16,6 +16,7 @@ export interface CommandScreenUI {
16
16
  loadScreen<T>(title: string, load: (signal: AbortSignal) => Promise<T>, options?: {
17
17
  description?: string;
18
18
  signal?: AbortSignal;
19
+ yieldToQuestions?: boolean;
19
20
  }): Promise<T | undefined>;
20
21
  select(title: string, items: {
21
22
  id: string;
@@ -33,14 +34,25 @@ export interface CommandScreenUI {
33
34
  collapsePrefix?: string;
34
35
  footer?: string;
35
36
  yieldToQuestions?: boolean;
37
+ /** Rows that can change while the select is open: called with `redraw` when it opens, returns the cleanup for when it closes. */
38
+ refresh?: (redraw: (items: {
39
+ id: string;
40
+ label: string;
41
+ description?: string;
42
+ bold?: boolean;
43
+ separator?: boolean;
44
+ }[]) => void) => () => void;
36
45
  }): Promise<string | undefined>;
37
46
  showScreen(title: string, lines: string[], options?: {
38
47
  signal?: AbortSignal;
48
+ yieldToQuestions?: boolean;
39
49
  }): Promise<void>;
40
50
  }
41
51
  export declare function pickPermissionMode(state: CommandState, ui: CommandScreenUI, signal: AbortSignal, options?: {
42
52
  yieldToQuestions?: boolean;
43
53
  }): Promise<string | undefined>;
54
+ /** The config with `model` on `providerId` as the selected pair: what choosing it in /model saves. */
55
+ export declare function withSelectedModel(config: Config, providerId: string, model: string): Config;
44
56
  export declare function isScreenCommand(line: string): boolean;
45
57
  export declare function runCommandScreen(line: string, state: CommandState, ui: CommandScreenUI, persist: (config: Config) => Promise<void>, signal: AbortSignal, adapterFactory?: (provider: ProviderConfig) => ModelAdapter, graphAccess?: {
46
58
  load: typeof loadAccessibleGraph;
@@ -56,12 +68,23 @@ type ModelTreeRow = {
56
68
  model?: string;
57
69
  };
58
70
  export declare const modelTreeId: (row: ModelTreeRow) => string;
71
+ /**
72
+ * The `refresh` option for a select whose rows depend on Andorra's state: while the select is open, every settled
73
+ * check (and an added or removed entry) builds the rows again, and the select is redrawn in place only when they
74
+ * differ from what is on screen. Empty when the client has no monitor to listen to.
75
+ */
76
+ export declare function andorraRefresh<Row>(state: CommandState, rows: () => Row[]): {
77
+ refresh?: (redraw: (items: Row[]) => void) => () => void;
78
+ };
59
79
  /**
60
80
  * The /model screen: every configured provider as a collapsed row ending in `>`, with its models
61
81
  * indented beneath once expanded (Right Arrow or Enter expands, Left Arrow collapses). A provider's
62
- * models load the first time it opens; when discovery fails its configured models are shown instead.
82
+ * models load the first time it opens, behind a loading row in the open tree; when discovery fails its
83
+ * configured models are shown instead.
63
84
  */
64
- export declare function pickProviderModel(state: CommandState, ui: CommandScreenUI, adapterFactory: (provider: ProviderConfig) => ModelAdapter, signal: AbortSignal): Promise<{
85
+ export declare function pickProviderModel(state: CommandState, ui: CommandScreenUI, adapterFactory: (provider: ProviderConfig) => ModelAdapter, signal: AbortSignal, options?: {
86
+ yieldToQuestions?: boolean;
87
+ }): Promise<{
65
88
  provider: string;
66
89
  model: string;
67
90
  } | undefined>;
@@ -1,4 +1,5 @@
1
1
  import { executeCommand } from './commands.js';
2
+ import { WORKING_SPINNER_FRAMES, WORKING_SPINNER_TICK_MS } from './session-title.js';
2
3
  import { PERMISSION_OPTIONS } from './permissions.js';
3
4
  import { editProviderSettings } from './provider-settings.js';
4
5
  import { retireRemovedCodexAccounts, retireUnsavedCodexAccounts } from './codex-auth.js';
@@ -7,12 +8,16 @@ import { importProvidersFromRemote } from './provider-import.js';
7
8
  import { DEFAULT_GRAPH, listGraphs, withoutDeletedGraphs } from './graphs.js';
8
9
  import { graphStorageDirectory } from './graph-account.js';
9
10
  import { configuredGraphSelection, currentGraphSubject, saveGraphSelection } from './graph-selection.js';
10
- import { getMembership, loadAccessibleGraph, requireGraphMembership, ANDORRA_GRAPH_SELECTION } from './membership.js';
11
+ import { getMembership, loadAccessibleGraph, requireGraphMembership } from './membership.js';
11
12
  import { FREE_CUSTOM_GRAPH_LIMIT, FREE_GRAPH_LIMIT_MESSAGE, readGraphQuota } from './graph-quota.js';
12
13
  import { GraphProviderUnavailableError } from './graph-provider-portability.js';
13
14
  import { confirmAndApplyModelOverride } from './model-override.js';
15
+ import { andorraRefusal } from './commands.js';
16
+ import { ANDORRA_REMOVE_FAILED, removingAndorraEntry } from './andorra/state.js';
17
+ import { cleanModelName } from './andorra/entry.js';
18
+ import { ANDORRA_MODEL_GONE } from './andorra/notices.js';
14
19
  import { reconcileSubagentPair } from './config.js';
15
- import { applyModelContextWindow, createAdapter, providerLabel, providerModels, recordProviderModel } from './providers.js';
20
+ import { applyModelContextWindow, createAdapter, modelDisplayName, providerLabel, providerModels, recordProviderModel } from './providers.js';
16
21
  import { configDirectory } from './config.js';
17
22
  import { listBundles, installBundle, removeBundle, removeBundleTransactional, setBundleEnabled, validateMcpServer } from './extensions.js';
18
23
  import { join } from 'node:path';
@@ -20,6 +25,21 @@ export function pickPermissionMode(state, ui, signal, options = {}) {
20
25
  const current = state.permissions ?? (state.yolo ? 'full-access' : 'ask-for-approval');
21
26
  return ui.select('Update Model Permissions', PERMISSION_OPTIONS.map((option, index) => ({ id: option.id, label: `${index + 1}. ${option.label}${option.id === current ? ' (current)' : ''}`, description: option.description })), { selectedId: current, description: 'Remembered for this workspace. Restricted commands require the Codex CLI OS sandbox.', signal, ...options });
22
27
  }
28
+ /** The config with `model` on `providerId` as the selected pair: what choosing it in /model saves. */
29
+ export function withSelectedModel(config, providerId, model) {
30
+ const draft = structuredClone(config);
31
+ const next = draft.providers.find(item => item.id === providerId);
32
+ if (!next)
33
+ throw new Error(`Unknown provider: ${providerId}`);
34
+ draft.provider = providerId;
35
+ recordProviderModel(next, model);
36
+ if (next.model !== model) {
37
+ next.model = model;
38
+ applyModelContextWindow(next, model);
39
+ delete next.reasoningEffort;
40
+ }
41
+ return draft;
42
+ }
23
43
  export function isScreenCommand(line) {
24
44
  return ['/model', '/providers', '/graph', '/usage', '/permissions', '/skills', '/plugins', '/mcp', '/subagent'].includes(line.trim());
25
45
  }
@@ -34,8 +54,11 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
34
54
  signal.throwIfAborted();
35
55
  const previousProviders = [...state.config.providers];
36
56
  const reconciled = reconcileSubagentPair(draft);
57
+ // Removing Andorra: the decision is recorded before the config without the entry is saved (and put back when
58
+ // the save fails), so a check in another process can never create the entry again in between.
59
+ const removesAndorra = previousProviders.some(item => item.type === 'andorra' && !reconciled.providers.some(next => next.id === item.id && next.type === 'andorra'));
37
60
  try {
38
- await persist(reconciled);
61
+ await (removesAndorra ? removingAndorraEntry(configDirectory(), () => persist(reconciled)) : persist(reconciled));
39
62
  }
40
63
  catch {
41
64
  await retireUnsavedCodexAccounts(reconciled.providers, state.config.providers, { signal });
@@ -48,6 +71,8 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
48
71
  return unchanged;
49
72
  }
50
73
  Object.assign(state.config, reconciled);
74
+ if (removesAndorra)
75
+ await state.andorra?.entryChanged?.();
51
76
  await retireRemovedCodexAccounts(previousProviders, reconciled.providers, { signal }).catch(() => { });
52
77
  await retireAnthropicAccounts(droppedAnthropicAccounts(previousProviders, reconciled.providers)).catch(() => { });
53
78
  if (reconciled.externalSubagent === undefined)
@@ -71,7 +96,7 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
71
96
  const providerPicked = await ui.select('External subagent provider', [
72
97
  ...state.config.providers.map(item => {
73
98
  const models = providerModels(item);
74
- return { id: item.id, label: `${providerLabel(item, state.config.providers)} (${item.type})`, description: `Models: ${models.slice(0, 4).join(', ')}${models.length > 4 ? '…' : ''}`, ...(current?.provider === item.id ? { bold: true } : {}) };
99
+ return { id: item.id, label: `${providerLabel(item, state.config.providers)} (${item.type})`, description: `Models: ${models.slice(0, 4).map(model => modelDisplayName(item, model)).join(', ')}${models.length > 4 ? '…' : ''}`, ...(current?.provider === item.id ? { bold: true } : {}) };
75
100
  }),
76
101
  ...(current === undefined ? [] : [{ id: CLEAR_SUBAGENT_SELECTION, label: 'Clear the setting', description: 'External hosts will be asked to pick a provider/model on every run.', separator: true }]),
77
102
  ], { ...(current ? { selectedId: current.provider } : {}), description: 'The provider and model external hosts (Claude CLI, Codex CLI) must use to run Andorra as a subagent. Mandatory: without a saved pair they receive PROVIDER_NOT_SET.', signal });
@@ -118,7 +143,7 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
118
143
  return unchanged;
119
144
  }
120
145
  const modelPicked = await ui.select('External subagent model', available.map(id => ({
121
- id, label: configured.includes(id) && !discovered.includes(id) ? `${id} (configured)` : id,
146
+ id, label: configured.includes(id) && !discovered.includes(id) ? `${modelDisplayName(target, id)} (configured)` : modelDisplayName(target, id),
122
147
  ...(current?.provider === target.id && current.model === id ? { bold: true } : {}),
123
148
  })), { selectedId: current?.provider === target.id ? current.model : target.model, description: `Provider: ${providerLabel(target, state.config.providers)}`, signal });
124
149
  if (modelPicked === undefined || signal.aborted)
@@ -160,6 +185,11 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
160
185
  const target = state.config.providers.find(item => item.id === picked.provider);
161
186
  if (!target)
162
187
  throw new Error('Invalid model selection');
188
+ const refusal = andorraRefusal(state, target.id);
189
+ if (refusal) {
190
+ await ui.showScreen('Andorra', [refusal], { signal });
191
+ return unchanged;
192
+ }
163
193
  const selected = picked.model;
164
194
  let overrideApplied = false;
165
195
  if (state.graph) {
@@ -171,7 +201,7 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
171
201
  resolveDirectory: async () => graphStorageDirectory(undefined, await graphSubject()),
172
202
  confirm: async (question) => {
173
203
  const choice = await ui.select('Override graph models?', [
174
- { id: 'override', label: `Override every node with ${target.id}/${selected}`, description: 'Saves the graph; every node and delegation follows this model.' },
204
+ { id: 'override', label: `Override every node with ${target.id}/${modelDisplayName(target, selected)}`, description: 'Saves the graph; every node and delegation follows this model.' },
175
205
  { id: 'keep', label: 'Keep the models selected in the graph', description: 'Cancels this model change; nothing is saved.' },
176
206
  ], { description: question, signal });
177
207
  return choice === 'override';
@@ -189,26 +219,65 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
189
219
  }
190
220
  if (target.id === state.config.provider && selected === target.model)
191
221
  return overrideApplied ? { clear: true } : unchanged;
192
- const draft = structuredClone(state.config);
193
- draft.provider = target.id;
194
- const next = draft.providers.find(item => item.id === target.id);
195
- recordProviderModel(next, selected);
196
- if (next.model !== selected) {
197
- next.model = selected;
198
- applyModelContextWindow(next, selected);
199
- delete next.reasoningEffort;
200
- }
201
- return await save(draft);
222
+ return await save(withSelectedModel(state.config, target.id, selected));
202
223
  }
203
224
  if (command === '/providers') {
204
- while (!signal.aborted) {
205
- const selected = await ui.select('Providers', [
206
- ...state.config.providers.map(item => ({ id: item.id, label: providerLabel(item, state.config.providers) })),
225
+ if (!await waitForAndorraCheck(state, ui, signal))
226
+ return unchanged;
227
+ // Saves Andorra because the user chose it; a refusal is shown as its plain sentence. Returns the saved entry's id.
228
+ const addAndorra = async () => {
229
+ const added = await state.andorra?.add?.();
230
+ if (added && !added.added && added.message && !signal.aborted)
231
+ await ui.showScreen('Andorra', [added.message], { signal });
232
+ return added?.added ? added.id ?? state.config.providers.find(item => item.type === 'andorra')?.id : undefined;
233
+ };
234
+ // The rows as the monitor's latest answer has them. They are built again each time the list is drawn, and
235
+ // again in place when a check answers while the list is open (the on-open check runs in the background when
236
+ // there is no Andorra entry, so its answer usually arrives after the list is on screen).
237
+ const rows = () => {
238
+ // Listed by default: while Andorra is offered and the user has not removed it, it is a row like any other
239
+ // provider, first, with its models as the description. It is saved the first time it is chosen.
240
+ const listed = state.andorra?.add ? state.andorra.listed?.() : undefined;
241
+ return [
242
+ ...(listed ? [{ id: LISTED_ANDORRA, label: providerLabel(listed, [listed, ...state.config.providers]), description: providerModels(listed).map(model => modelDisplayName(listed, model)).join(', ') }] : []),
243
+ ...state.config.providers.map(item => {
244
+ const refusal = andorraRefusal(state, item.id);
245
+ return { id: item.id, label: providerLabel(item, state.config.providers), ...(refusal ? { description: refusal } : {}) };
246
+ }),
207
247
  { id: ':add', label: '+ Add provider' },
208
248
  { id: ':import', label: 'Import from remote connection' },
209
- ], { selectedId: state.config.provider, editPrefix: ':edit:', footer: 'Up/Down Move | Enter Select | Right/e Edit | Esc Back', signal });
249
+ ];
250
+ };
251
+ while (!signal.aborted) {
252
+ const selected = await ui.select('Providers', rows(), { selectedId: state.config.provider, editPrefix: ':edit:', footer: 'Up/Down Move | Enter Select | Right/e Edit | Esc Back', signal,
253
+ ...andorraRefresh(state, rows) });
210
254
  if (selected === undefined || signal.aborted)
211
255
  return unchanged;
256
+ if (selected === `:edit:${LISTED_ANDORRA}`) {
257
+ // Nothing of a listed, never-saved Andorra can be edited; it can be used, or taken off the list.
258
+ const action = await ui.select('Andorra', [
259
+ { id: 'use', label: 'Use Andorra', description: 'Saves it to your providers and selects it.' },
260
+ { id: 'remove', label: 'Remove from this list', description: 'It can be added again from + Add provider while it is offered.' },
261
+ { id: 'back', label: 'Back' },
262
+ ], { selectedId: 'back', signal });
263
+ if (action === 'remove') {
264
+ // Not recorded: it would come back at the next start, so say that nothing was removed.
265
+ if (await state.andorra?.hide?.() === false && !signal.aborted)
266
+ await ui.showScreen('Andorra', [ANDORRA_REMOVE_FAILED], { signal });
267
+ continue;
268
+ }
269
+ if (action !== 'use')
270
+ continue;
271
+ }
272
+ if (selected === LISTED_ANDORRA || selected === `:edit:${LISTED_ANDORRA}`) {
273
+ // The user's own choice: save the entry, then select it as any provider is selected.
274
+ const id = await addAndorra();
275
+ if (id === undefined || signal.aborted)
276
+ continue;
277
+ const draft = structuredClone(state.config);
278
+ draft.provider = id;
279
+ return await save(draft);
280
+ }
212
281
  if (selected === ':import') {
213
282
  const draft = await importProvidersFromRemote(state.config, ui, signal);
214
283
  if (draft)
@@ -219,7 +288,7 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
219
288
  const id = selected === ':add' ? undefined : selected.slice(6);
220
289
  if (id && !state.config.providers.some(item => item.id === id))
221
290
  throw new Error('Invalid provider selection');
222
- const draft = await editProviderSettings(state.config, id, ui, signal);
291
+ const draft = await editProviderSettings(state.config, id, ui, signal, undefined, undefined, undefined, undefined, id === undefined && state.andorra?.add ? { description: () => andorraOffer(state), add: async () => { await addAndorra(); }, refresh: rows => andorraRefresh(state, rows).refresh } : undefined);
223
292
  if (draft)
224
293
  return await save(draft);
225
294
  continue;
@@ -228,6 +297,11 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
228
297
  return unchanged;
229
298
  if (!state.config.providers.some(item => item.id === selected))
230
299
  throw new Error('Invalid provider selection');
300
+ const refusal = andorraRefusal(state, selected);
301
+ if (refusal) {
302
+ await ui.showScreen('Andorra', [refusal], { signal });
303
+ continue;
304
+ }
231
305
  const draft = structuredClone(state.config);
232
306
  draft.provider = selected;
233
307
  return await save(draft);
@@ -248,7 +322,7 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
248
322
  id: DEFAULT_GRAPH.id,
249
323
  label: 'Default',
250
324
  description: 'Andorra Agent only. Reads project instructions and completes the task without an Orchestrator.',
251
- }, { id: ANDORRA_GRAPH_SELECTION, label: 'Andorra', description: free ? 'Premium graph: Orchestrator -> Andorra Agent -> Done' : 'Paid graph: Orchestrator -> Andorra Agent -> Done' }, ...withoutDeletedGraphs(saved).filter(graph => graph.id !== 'default').map(graph => ({ id: graph.id, label: `${graph.name} (${graph.id}@${graph.revision})`, description: 'Saved custom graph' })), { id: ':divider', label: '', separator: true }, { id: ':create', label: 'Create new graph', description: atLimit ? 'Free tier includes 1 custom graph. Upgrade to Premium for more graphs.' : 'Open the web graph builder' }, { id: ':edit', label: 'Edit Graphs', bold: true, description: 'Open saved graphs in the web graph builder' }];
325
+ }, ...withoutDeletedGraphs(saved).filter(graph => graph.id !== 'default').map(graph => ({ id: graph.id, label: `${graph.name} (${graph.id}@${graph.revision})`, description: 'Saved custom graph' })), { id: ':divider', label: '', separator: true }, { id: ':create', label: 'Create new graph', description: atLimit ? 'Free tier includes 1 custom graph. Upgrade to Premium for more graphs.' : 'Open the web graph builder' }, { id: ':edit', label: 'Edit Graphs', bold: true, description: 'Open saved graphs in the web graph builder' }];
252
326
  while (!signal.aborted) {
253
327
  const selected = await ui.select('Graph', items, { selectedId: state.graph ?? DEFAULT_GRAPH.id, description: 'Choose and save your default graph for this account, or create one in the web builder. After saving, reopen /graph to select it.', signal });
254
328
  if (selected === undefined || signal.aborted)
@@ -266,8 +340,7 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
266
340
  const changed = selected !== (state.graph ?? 'default');
267
341
  if (changed) {
268
342
  const name = selected === 'default' ? DEFAULT_GRAPH.name
269
- : selected === ANDORRA_GRAPH_SELECTION ? 'Andorra'
270
- : saved.find(graph => graph.id === selected).name;
343
+ : saved.find(graph => graph.id === selected).name;
271
344
  const confirmation = await ui.select(`Switch to ${name}?`, [
272
345
  { id: 'switch', label: `Switch to ${name}`, description: 'Use this graph for subsequent tasks and start fresh.' },
273
346
  { id: 'back', label: 'Keep current graph', description: 'Return to the graph list. Nothing changes.' },
@@ -282,7 +355,7 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
282
355
  }
283
356
  let unavailable;
284
357
  if (selected !== 'default') {
285
- if (selected !== ANDORRA_GRAPH_SELECTION && !saved.some(graph => graph.id === selected))
358
+ if (!saved.some(graph => graph.id === selected))
286
359
  throw new Error('Invalid graph selection');
287
360
  try {
288
361
  await graphAccess.load(selected, signal);
@@ -521,6 +594,18 @@ async function runExtensionScreen(command, state, ui, save, signal) {
521
594
  }
522
595
  export const MODEL_TREE_EXPAND = ':expand:';
523
596
  export const MODEL_TREE_COLLAPSE = ':collapse:';
597
+ /** How long a /model provider loads before its loading row and spinner are drawn, so a quick answer never flashes one. */
598
+ const MODEL_LOADING_GRACE_MS = 150;
599
+ /**
600
+ * Lets an answer already in hand (a stub, a cache) land before the tree is drawn again, waiting on microtasks only:
601
+ * no key or terminal event can be handled meanwhile, so nothing typed is lost while no screen is open.
602
+ */
603
+ async function settleWithoutYielding(job) {
604
+ let settled = false;
605
+ void job.then(() => { settled = true; });
606
+ for (let turn = 0; turn < 32 && !settled; turn++)
607
+ await Promise.resolve();
608
+ }
524
609
  export const modelTreeId = (row) => JSON.stringify(row.model === undefined ? [row.provider] : [row.provider, row.model]);
525
610
  function parseModelTreeId(id) {
526
611
  try {
@@ -535,99 +620,252 @@ function parseModelTreeId(id) {
535
620
  catch { /* not a tree id */ }
536
621
  return undefined;
537
622
  }
623
+ /** The row of a listed, not yet saved Andorra. Not a provider id (ids have no colon). */
624
+ const LISTED_ANDORRA = ':andorra';
625
+ /** The hosted model names while Andorra can be added (offered to this account, no entry yet); undefined otherwise. */
626
+ function andorraOffer(state) {
627
+ if (!state.andorra?.add || state.config.providers.some(item => item.type === 'andorra'))
628
+ return undefined;
629
+ const models = state.andorra.offer?.();
630
+ return models?.length ? models.map(model => cleanModelName(model.name) ?? model.id).join(', ') : undefined;
631
+ }
632
+ /**
633
+ * The `refresh` option for a select whose rows depend on Andorra's state: while the select is open, every settled
634
+ * check (and an added or removed entry) builds the rows again, and the select is redrawn in place only when they
635
+ * differ from what is on screen. Empty when the client has no monitor to listen to.
636
+ */
637
+ export function andorraRefresh(state, rows) {
638
+ const subscribe = state.andorra?.subscribe;
639
+ if (!subscribe)
640
+ return {};
641
+ return {
642
+ refresh: redraw => {
643
+ let drawn = JSON.stringify(rows());
644
+ return subscribe(() => {
645
+ const next = rows();
646
+ const text = JSON.stringify(next);
647
+ if (text === drawn)
648
+ return;
649
+ drawn = text;
650
+ redraw(next);
651
+ });
652
+ },
653
+ };
654
+ }
655
+ /**
656
+ * Runs the on-open Andorra check. With an Andorra entry in the list it runs behind a loading screen, because the
657
+ * answer decides how that row is drawn; `state.andorra.opened()` bounds the wait. Without one the list is drawn
658
+ * at once and the check runs in the background. False when the screen was cancelled (Esc on the loading screen
659
+ * or the screen's signal aborted).
660
+ */
661
+ async function waitForAndorraCheck(state, ui, signal, yields = {}) {
662
+ const andorra = state.andorra;
663
+ if (!andorra)
664
+ return true;
665
+ if (!state.config.providers.some(item => item.type === 'andorra')) {
666
+ void andorra.opened().catch(() => { });
667
+ return !signal.aborted;
668
+ }
669
+ const done = await ui.loadScreen('Andorra', loadSignal => new Promise(resolve => {
670
+ const finish = () => resolve(true);
671
+ if (loadSignal.aborted)
672
+ return finish();
673
+ loadSignal.addEventListener('abort', finish, { once: true });
674
+ andorra.opened().catch(() => { }).then(() => { loadSignal.removeEventListener('abort', finish); finish(); });
675
+ }), { description: 'Checking Andorra availability', signal, ...yields });
676
+ return done === true && !signal.aborted;
677
+ }
538
678
  /**
539
679
  * The /model screen: every configured provider as a collapsed row ending in `>`, with its models
540
680
  * indented beneath once expanded (Right Arrow or Enter expands, Left Arrow collapses). A provider's
541
- * models load the first time it opens; when discovery fails its configured models are shown instead.
681
+ * models load the first time it opens, behind a loading row in the open tree; when discovery fails its
682
+ * configured models are shown instead.
542
683
  */
543
- export async function pickProviderModel(state, ui, adapterFactory, signal) {
544
- const providers = state.config.providers;
684
+ export async function pickProviderModel(state, ui, adapterFactory, signal, options = {}) {
685
+ // Opened while a run is working, the tree closes when the run asks a question (an approval, a clarification).
686
+ const yields = options.yieldToQuestions ? { yieldToQuestions: true } : {};
687
+ if (!await waitForAndorraCheck(state, ui, signal, yields))
688
+ return undefined;
689
+ // A listed, not yet saved Andorra is shown first, like a saved provider. Its models come from the hosted answer:
690
+ // no request is ever sent on its behalf before the user picks it.
691
+ const listedNow = () => state.andorra?.add ? state.andorra.listed?.() : undefined;
692
+ let listed = listedNow();
693
+ let listedId = listed?.id;
694
+ let providers = listed ? [listed, ...state.config.providers] : state.config.providers;
545
695
  const active = providers.find(item => item.id === state.config.provider);
546
696
  const expanded = new Set();
547
697
  const loaded = new Map();
548
698
  let cursor = active ? modelTreeId({ provider: active.id }) : undefined;
549
- const load = async (provider) => {
699
+ // Discovery runs behind the open tree: the expanded provider shows a loading row where its first model will be,
700
+ // and the rows are redrawn in place when the answer lands. Closing the picker abandons every load still running.
701
+ const loads = new AbortController();
702
+ const abandon = () => loads.abort();
703
+ signal.addEventListener('abort', abandon, { once: true });
704
+ const pending = new Map();
705
+ const pendingSince = new Map();
706
+ let frame = 0;
707
+ let redrawOpen;
708
+ const load = (provider) => {
550
709
  if (loaded.has(provider.id))
551
- return true;
552
- let discovered = [];
553
- let note;
554
- try {
555
- const models = await ui.loadScreen('Models', async (loadSignal) => {
710
+ return undefined;
711
+ if (provider === listed) {
712
+ loaded.set(provider.id, { models: providerModels(provider), configured: new Set() });
713
+ return undefined;
714
+ }
715
+ const running = pending.get(provider.id);
716
+ if (running)
717
+ return running;
718
+ const job = (async () => {
719
+ let discovered = [];
720
+ let note;
721
+ try {
556
722
  const adapter = adapterFactory(provider);
557
723
  if (!adapter.listModels)
558
724
  throw new Error('Model discovery unavailable');
559
- return adapter.listModels(loadSignal);
560
- }, { description: `Loading available models from ${providerLabel(provider, providers)}`, signal });
561
- if (models === undefined)
562
- return false;
563
- discovered = [...new Set(models)].filter(id => typeof id === 'string' && id.trim().length > 0);
564
- if (!discovered.length)
565
- note = 'The provider returned no models.';
566
- }
567
- catch (error) {
568
- if (signal.aborted || (error instanceof Error && error.name === 'AbortError'))
569
- return false;
570
- note = 'Could not load models; check the endpoint and credentials in /providers. Showing configured models.';
571
- }
572
- const configured = providerModels(provider).filter(id => !discovered.includes(id));
573
- loaded.set(provider.id, { models: [...discovered, ...configured], configured: new Set(configured), ...(note ? { note } : {}) });
574
- return true;
725
+ const models = await adapter.listModels(loads.signal);
726
+ discovered = [...new Set(models)].filter(id => typeof id === 'string' && id.trim().length > 0);
727
+ if (!discovered.length)
728
+ note = 'The provider returned no models.';
729
+ }
730
+ catch {
731
+ if (loads.signal.aborted)
732
+ return;
733
+ note = 'Could not load models; check the endpoint and credentials in /providers. Showing configured models.';
734
+ }
735
+ if (loads.signal.aborted)
736
+ return;
737
+ const configured = providerModels(provider).filter(id => !discovered.includes(id));
738
+ loaded.set(provider.id, { models: [...discovered, ...configured], configured: new Set(configured), ...(note ? { note } : {}) });
739
+ })().finally(() => { pending.delete(provider.id); pendingSince.delete(provider.id); redrawOpen?.(); });
740
+ pending.set(provider.id, job);
741
+ pendingSince.set(provider.id, Date.now());
742
+ return job;
575
743
  };
576
- while (!signal.aborted) {
744
+ const rows = () => {
745
+ // Rebuilt each time the tree is drawn, and in place when a check answers while it is open.
746
+ listed = listedNow();
747
+ if (listed !== undefined) {
748
+ listedId = listed.id;
749
+ if (expanded.has(listed.id))
750
+ loaded.set(listed.id, { models: providerModels(listed), configured: new Set() });
751
+ }
752
+ providers = listed ? [listed, ...state.config.providers] : state.config.providers;
577
753
  const items = [];
578
754
  for (const provider of providers) {
579
755
  const open = expanded.has(provider.id);
580
756
  const isActive = provider.id === active?.id;
581
757
  const entry = loaded.get(provider.id);
758
+ const refusal = andorraRefusal(state, provider.id);
582
759
  items.push({
583
760
  id: modelTreeId({ provider: provider.id }),
584
761
  label: `${providerLabel(provider, providers)}${isActive ? ' (current)' : ''} ${open ? 'v' : '>'}`,
585
- ...(open && entry?.note ? { description: entry.note } : {}),
762
+ ...(refusal ? { description: refusal } : open && entry?.note ? { description: entry.note } : {}),
586
763
  ...(isActive ? { bold: true } : {}),
587
764
  });
765
+ if (open && !entry && pending.has(provider.id)) {
766
+ // Takes the place of the first model once the load has run past the grace period (the spinner's ticks
767
+ // redraw it in); picking it does nothing, like the empty-list row.
768
+ if (Date.now() - (pendingSince.get(provider.id) ?? 0) >= MODEL_LOADING_GRACE_MS)
769
+ items.push({ id: modelTreeId({ provider: provider.id, model: '' }), label: ` ${WORKING_SPINNER_FRAMES[frame % WORKING_SPINNER_FRAMES.length]} Loading models…` });
770
+ continue;
771
+ }
588
772
  if (!open || !entry)
589
773
  continue;
590
774
  if (!entry.models.length)
591
775
  items.push({ id: modelTreeId({ provider: provider.id, model: '' }), label: ' No models available' });
592
776
  for (const model of entry.models)
593
- items.push({ id: modelTreeId({ provider: provider.id, model }), label: ` ${model}${entry.configured.has(model) ? " (configured)" : ""}` });
777
+ items.push({ id: modelTreeId({ provider: provider.id, model }), label: ` ${modelDisplayName(provider, model)}${entry.configured.has(model) ? " (configured)" : ""}` });
594
778
  }
595
- const choice = await ui.select('Models', items, {
596
- ...(cursor ? { selectedId: cursor } : {}),
597
- checkedId: active ? modelTreeId({ provider: active.id, model: active.model }) : '',
598
- ...(active ? { description: `Current: ${providerLabel(active, providers)} / ${active.model}` } : {}),
599
- expandPrefix: MODEL_TREE_EXPAND, collapsePrefix: MODEL_TREE_COLLAPSE,
600
- footer: '↑↓ Move · → Expand · ← Collapse · Enter Select · Esc Back',
601
- signal,
602
- });
603
- if (choice === undefined || signal.aborted)
604
- return undefined;
605
- const action = choice.startsWith(MODEL_TREE_EXPAND) ? 'expand' : choice.startsWith(MODEL_TREE_COLLAPSE) ? 'collapse' : 'pick';
606
- const row = parseModelTreeId(action === 'expand' ? choice.slice(MODEL_TREE_EXPAND.length) : action === 'collapse' ? choice.slice(MODEL_TREE_COLLAPSE.length) : choice);
607
- const provider = row && providers.find(item => item.id === row.provider);
608
- if (!row || !provider)
609
- throw new Error('Invalid model selection');
610
- cursor = modelTreeId(row);
611
- if (action === 'collapse') {
612
- // Left on a model row folds its provider, like a file tree.
613
- expanded.delete(provider.id);
614
- cursor = modelTreeId({ provider: provider.id });
615
- continue;
616
- }
617
- if (row.model === undefined) {
618
- if (action === 'pick' && expanded.has(provider.id)) {
779
+ return items;
780
+ };
781
+ try {
782
+ while (!signal.aborted) {
783
+ const choice = await ui.select('Models', rows(), {
784
+ ...(cursor ? { selectedId: cursor } : {}),
785
+ checkedId: active ? modelTreeId({ provider: active.id, model: active.model }) : '',
786
+ ...(active ? { description: `Current: ${providerLabel(active, providers)} / ${modelDisplayName(active, active.model)}` } : {}),
787
+ expandPrefix: MODEL_TREE_EXPAND, collapsePrefix: MODEL_TREE_COLLAPSE,
788
+ footer: '↑↓ Move · → Expand · ← Collapse · Enter Select · Esc Back',
789
+ signal, ...yields,
790
+ refresh: redraw => {
791
+ const stopAndorra = andorraRefresh(state, rows).refresh?.(redraw);
792
+ redrawOpen = () => redraw(rows());
793
+ // The loading row's spinner turns while any provider is still loading.
794
+ const spinner = pending.size ? setInterval(() => {
795
+ if (!pending.size) {
796
+ clearInterval(spinner);
797
+ return;
798
+ }
799
+ frame++;
800
+ redraw(rows());
801
+ }, WORKING_SPINNER_TICK_MS) : undefined;
802
+ spinner?.unref?.();
803
+ return () => { redrawOpen = undefined; if (spinner)
804
+ clearInterval(spinner); stopAndorra?.(); };
805
+ },
806
+ });
807
+ if (choice === undefined || signal.aborted)
808
+ return undefined;
809
+ const action = choice.startsWith(MODEL_TREE_EXPAND) ? 'expand' : choice.startsWith(MODEL_TREE_COLLAPSE) ? 'collapse' : 'pick';
810
+ const row = parseModelTreeId(action === 'expand' ? choice.slice(MODEL_TREE_EXPAND.length) : action === 'collapse' ? choice.slice(MODEL_TREE_COLLAPSE.length) : choice);
811
+ const provider = row && providers.find(item => item.id === row.provider);
812
+ // The listed Andorra can leave the tree while it is open (turned off, or removed elsewhere): draw it again.
813
+ if (row && !provider && row.provider === listedId)
814
+ continue;
815
+ if (!row || !provider)
816
+ throw new Error('Invalid model selection');
817
+ cursor = modelTreeId(row);
818
+ if (action === 'collapse') {
819
+ // Left on a model row folds its provider, like a file tree.
619
820
  expanded.delete(provider.id);
821
+ cursor = modelTreeId({ provider: provider.id });
620
822
  continue;
621
823
  }
622
- if (await load(provider))
824
+ if (row.model === undefined) {
825
+ if (action === 'pick' && expanded.has(provider.id)) {
826
+ expanded.delete(provider.id);
827
+ continue;
828
+ }
623
829
  expanded.add(provider.id);
624
- continue;
830
+ // The tree is drawn again at once, keeping the keyboard; a slow answer lands in it through `refresh`.
831
+ const job = load(provider);
832
+ if (job)
833
+ await settleWithoutYielding(job);
834
+ continue;
835
+ }
836
+ if (action === 'expand' || row.model === '')
837
+ continue;
838
+ if (!loaded.get(provider.id)?.models.includes(row.model))
839
+ throw new Error('Invalid model selection');
840
+ if (provider === listed) {
841
+ // The user's own choice of an Andorra model: the entry is saved first; the caller then selects it as usual.
842
+ const added = await state.andorra?.add?.(row.model);
843
+ if (!added?.added) {
844
+ if (added?.message && !signal.aborted)
845
+ await ui.showScreen('Andorra', [added.message], { signal, ...yields });
846
+ continue;
847
+ }
848
+ const saved = state.config.providers.find(item => item.id === (added.id ?? provider.id));
849
+ if (added.modelServed === false || (saved !== undefined && !providerModels(saved).includes(row.model))) {
850
+ // The offer changed between the tree being drawn and the pick: the entry was saved with what is served
851
+ // now, and the model that is gone is not selected. Say so and draw the tree with the saved entry's models.
852
+ if (!signal.aborted)
853
+ await ui.showScreen('Andorra', [added.message ?? ANDORRA_MODEL_GONE], { signal, ...yields });
854
+ if (saved !== undefined) {
855
+ loaded.set(saved.id, { models: providerModels(saved), configured: new Set() });
856
+ expanded.add(saved.id);
857
+ cursor = modelTreeId({ provider: saved.id });
858
+ }
859
+ continue;
860
+ }
861
+ return { provider: added.id ?? provider.id, model: row.model };
862
+ }
863
+ return { provider: provider.id, model: row.model };
625
864
  }
626
- if (action === 'expand' || row.model === '')
627
- continue;
628
- if (!loaded.get(provider.id)?.models.includes(row.model))
629
- throw new Error('Invalid model selection');
630
- return { provider: provider.id, model: row.model };
865
+ return undefined;
866
+ }
867
+ finally {
868
+ signal.removeEventListener('abort', abandon);
869
+ abandon();
631
870
  }
632
- return undefined;
633
871
  }