@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
@@ -17,25 +17,28 @@ import { droppedCodexSlots, removeCodexAccount } from './codex-auth.js';
17
17
  import { testProviderConnection } from './provider-connection.js';
18
18
  import { CodexAccountAuth } from './codex-browser-auth.js';
19
19
  import { AnthropicConsoleAuth, droppedAnthropicAccounts } from './anthropic-console-auth.js';
20
- import { claudeSignIn, grokSignIn, OpenCodeSignIn } from './managed-sign-in.js';
20
+ import { claudeSignIn, googleSignIn, grokSignIn, OpenCodeSignIn } from './managed-sign-in.js';
21
21
  import { applySignInImports, detectSignIns, isDetectableSignInType } from './sign-in-detection.js';
22
22
  import { OPENCODE_BASE_URL, sharedOpenCodeServer } from './opencode-cli-provider.js';
23
+ import { GOOGLE_BASE_URL } from './google-provider.js';
23
24
  import { GROK_BASE_URL } from './grok-provider.js';
24
25
  import { anthropicAccountHome } from './anthropic-credentials.js';
25
26
  import { codexAccountHome } from './codex-rpc.js';
26
27
  import { configuredModelSnapshot, discoverModelMetadata, resolveModelContext } from './model-metadata.js';
28
+ import { liveModelTarget } from './live-model.js';
27
29
  import { graphLeavesNodesToSession, graphMcpServers, isDeletedGraph, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
28
30
  import { exportAgentDefinition, readAgentDefinition } from './agent-definitions.js';
29
31
  import { blockingHealthFailures, checkGraphModelHealth, formatGraphHealthFailure, resumeModelNodes } from './graph-health.js';
30
32
  import { bindPortableGraphProviders, GraphProviderUnavailableError } from './graph-provider-portability.js';
31
33
  import { applyModelOverride, applyNodeModelOverrides } from './model-override.js';
32
34
  import { freeTierGraphViolation, readGraphQuota } from './graph-quota.js';
33
- import { ANDORRA_GRAPH_SELECTION, SOFTWARE_ENGINEER_HARNESS, getAndorraHarness, getMembership, loadAccessibleGraph } from './membership.js';
35
+ import { RETIRED_ANDORRA_SELECTION, SOFTWARE_ENGINEER_HARNESS, currentGraphSelection, getMembership, loadAccessibleGraph } from './membership.js';
34
36
  import { loadProfile, saveProfile, ProfileAccountError, ProfileTextError } from './profile.js';
35
37
  import { hostedDecisionPolicy } from './decision/hostedPolicy.js';
36
38
  import { createAccountPresentationReader, publishableMembership } from './account-presentation.js';
37
39
  import { getAuthStatus, login, logout, setAuthSignOutReporter } from './auth/index.js';
38
40
  import { configuredGraphSelection, currentGraphSubject, identityStillHolds } from './graph-selection.js';
41
+ import { announceGraphVisibilityChange, graphVisibilityFor, importGraphVisibility, onGraphVisibilityChange, relinkGraphVisibility, setGraphVisibility } from './graph-visibility.js';
39
42
  import { graphStorageAccess } from './graph-account.js';
40
43
  import { GraphAccessSync } from './graph-sync.js';
41
44
  import { canExtendLineage, displayHistory, lineagePoints, lineageThrough, SessionStore, projectIdentity, removeSessionSnapshot, savedSessionFields, sessionName, validSavedSession } from './sessions.js';
@@ -44,7 +47,7 @@ import { writePendingAgentInteraction, removePendingAgentInteraction } from './s
44
47
  import { summarizeSessionPrompt, titleRequestSupported } from './session-summary.js';
45
48
  import { createTools } from './tools.js';
46
49
  import { TimerRegistry, WAKE_RETRY_MS } from './timers.js';
47
- import { confirmAutoFixWake, isFinishedPullRequest, markAutoFixDelivered, withoutPendingFix, newPullRequest, parsePullRequestUrl, PullRequestCreateDetector, pullRequestNeedsWatch, pullRequestSettings, PullRequestWatcher, readPullRequest, removePullRequest, runGh, applyPullRequestSettingsAsReadableAccount, noAccountMessage, readPullRequestAsAnyAccount, withPullRequest, writePullRequest } from './pull-requests.js';
50
+ import { confirmAutoFixWake, isFinishedPullRequest, markAutoFixDelivered, withoutPendingFix, newPullRequest, parsePullRequestUrl, PullRequestCreateDetector, pullRequestNeedsWatch, pullRequestSettings, PullRequestWatcher, listPullRequests, readPullRequest, removePullRequest, runGh, applyPullRequestSettingsAsReadableAccount, noAccountMessage, readPullRequestAsAnyAccount, withPullRequest, writePullRequest } from './pull-requests.js';
48
51
  import { AutomationStore } from './automations.js';
49
52
  import { executeAutomation } from './automation-runner.js';
50
53
  import { automationService, automationServiceRunning, reconcileAutomationService } from './automation-service.js';
@@ -93,6 +96,13 @@ import { checkoutBranch, gitDiff, gitStatus, listBranches, listExtensions, listR
93
96
  import { withReasoningEvents } from './app-server/reasoning.js';
94
97
  import { APP_SERVER_PROTOCOL_VERSION, APP_SERVER_CAPABILITIES, } from './app-server/protocol.js';
95
98
  import { RemotePeerError } from './remote/errors.js';
99
+ import { fallbackProviderId, hasAndorraEntry, virtualAndorraEntry } from './andorra/entry.js';
100
+ import { ANDORRA_CHANGED_MESSAGE, ANDORRA_UNAVAILABLE_MESSAGE } from './andorra/endpoint.js';
101
+ import { andorraAnnouncement } from './andorra/notices.js';
102
+ import { ANDORRA_REMOVE_FAILED, recordAndorraRemoved, removingAndorraEntry } from './andorra/state.js';
103
+ import { addAndorraEntry, saveAndorraAnswer } from './andorra/opt-in.js';
104
+ import { HostedMonitor } from './andorra/monitor.js';
105
+ import { watchRequests } from './andorra/request-watch.js';
96
106
  const SELECTION_HEALTH_TIMEOUT_MS = 60_000;
97
107
  class AppServerError extends Error {
98
108
  code;
@@ -161,7 +171,7 @@ function providerAuthView(view, includeUrl) {
161
171
  return result;
162
172
  }
163
173
  const MANAGED_SIGN_IN_HOSTS = {
164
- claude: ['claude.com', 'claude.ai', 'anthropic.com'], grok: ['x.ai', 'grok.com'], opencode: undefined,
174
+ claude: ['claude.com', 'claude.ai', 'anthropic.com'], grok: ['x.ai', 'grok.com'], google: ['accounts.google.com'], opencode: undefined,
165
175
  };
166
176
  function managedAuthView(type, view, includeUrl) {
167
177
  if (!['signedOut', 'starting', 'waiting', 'signedIn', 'cancelled', 'error'].includes(view.state))
@@ -367,6 +377,9 @@ function providerView(provider, providers) {
367
377
  ...(provider.apiKeyEnv === undefined ? {} : { apiKeyEnv: provider.apiKeyEnv }),
368
378
  ...(provider.models === undefined ? {} : { models: [...provider.models] }),
369
379
  ...(provider.modelContextWindows === undefined ? {} : { modelContextWindows: { ...provider.modelContextWindows } }),
380
+ ...(provider.type !== 'andorra' || provider.modelNames === undefined ? {} : { modelNames: { ...provider.modelNames } }),
381
+ ...(provider.type !== 'andorra' || provider.modelParameters === undefined ? {} : { modelParameters: { ...provider.modelParameters } }),
382
+ ...(provider.type !== 'andorra' || provider.freeModels === undefined ? {} : { freeModels: [...provider.freeModels] }),
370
383
  ...(provider.contextWindow === undefined ? {} : { contextWindow: provider.contextWindow }),
371
384
  ...(provider.reasoningEffort === undefined ? {} : { reasoningEffort: provider.reasoningEffort }),
372
385
  ...(provider.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: provider.requestTimeoutMs }),
@@ -510,6 +523,14 @@ export function mergeProviderSecrets(stored, incoming) {
510
523
  if (previousEntry?.modelContextWindows !== undefined)
511
524
  provider.modelContextWindows = previousEntry.modelContextWindows;
512
525
  }
526
+ // The engine keeps an Andorra entry's display names from the router; a client never sets them.
527
+ if (provider.type === 'andorra' && previousEntry?.type === 'andorra' && previousEntry.modelNames !== undefined)
528
+ provider.modelNames = { ...previousEntry.modelNames };
529
+ // Likewise the sizes and the free list: they describe what the router serves, so only the router sets them.
530
+ if (provider.type === 'andorra' && previousEntry?.type === 'andorra' && previousEntry.modelParameters !== undefined)
531
+ provider.modelParameters = { ...previousEntry.modelParameters };
532
+ if (provider.type === 'andorra' && previousEntry?.type === 'andorra' && previousEntry.freeModels !== undefined)
533
+ provider.freeModels = [...previousEntry.freeModels];
513
534
  if (source.name === null)
514
535
  delete provider.name;
515
536
  else if (source.name === undefined) {
@@ -580,6 +601,7 @@ function sessionSummary(record) {
580
601
  ...(record.parentId === undefined ? {} : { parentId: record.parentId }),
581
602
  ...(record.projectId === undefined ? {} : { projectId: record.projectId }),
582
603
  ...(record.archived === undefined ? {} : { archived: record.archived }),
604
+ ...(record.jevEnabled === undefined ? {} : { jevEnabled: record.jevEnabled }),
583
605
  ...(record.history?.length ? { lastTask: record.history[record.history.length - 1].direction ?? record.history[record.history.length - 1].task } : {}),
584
606
  ...(finished === undefined ? {} : { lastTurnStatus: finished }),
585
607
  usage: { inputTokens: record.usage.inputTokens, outputTokens: record.usage.outputTokens, requests: record.usage.requests, ...(record.usage.cacheRead === undefined ? {} : { cacheRead: record.usage.cacheRead }), ...(record.usage.cacheWrite === undefined ? {} : { cacheWrite: record.usage.cacheWrite }),
@@ -684,6 +706,7 @@ export class AppServer {
684
706
  anthropicAuth;
685
707
  claudeSignIn;
686
708
  grokSignIn;
709
+ googleSignIn;
687
710
  openCodeSignIn;
688
711
  signInProbes;
689
712
  detectedSignIns = new Map();
@@ -695,6 +718,8 @@ export class AppServer {
695
718
  reviewWaiters = new Map();
696
719
  reviewWaitsStarting = new Set();
697
720
  graphSync = new GraphAccessSync(undefined, undefined, () => this.emit('graphs.changed', {}));
721
+ // A visibility change made in this process, by a client or by the graph manager's tool in a run, reloads every client's list.
722
+ stopGraphVisibilityWatch = onGraphVisibilityChange(() => this.emit('graphs.changed', {}));
698
723
  terminals;
699
724
  backgroundTasks = new BackgroundTasks();
700
725
  stopBackgroundWatch = () => { };
@@ -728,6 +753,7 @@ export class AppServer {
728
753
  slotWrites = new Map();
729
754
  runTask;
730
755
  titleReleases = new Map();
756
+ titleAnswered = new Set(); // runs whose model has answered at least once
731
757
  sessionTitles = new Map();
732
758
  workGeneration = 0;
733
759
  operations = new Set();
@@ -743,6 +769,8 @@ export class AppServer {
743
769
  remoteOps = Promise.resolve();
744
770
  closed = false;
745
771
  emitsStopped = false;
772
+ hosted;
773
+ hostedStarted = false;
746
774
  telemetrySettle = Promise.resolve();
747
775
  onStop;
748
776
  constructor(options) {
@@ -758,6 +786,7 @@ export class AppServer {
758
786
  this.anthropicAuth = options.anthropicAuth ?? new AnthropicConsoleAuth();
759
787
  this.claudeSignIn = options.managedSignIn?.claude ?? claudeSignIn();
760
788
  this.grokSignIn = options.managedSignIn?.grok ?? grokSignIn();
789
+ this.googleSignIn = options.managedSignIn?.google ?? googleSignIn();
761
790
  this.openCodeSignIn = options.managedSignIn?.opencode ?? new OpenCodeSignIn();
762
791
  this.signInProbes = options.signInProbes;
763
792
  this.retireCodexAccount = options.removeCodexAccount ?? removeCodexAccount;
@@ -792,6 +821,17 @@ export class AppServer {
792
821
  return { key, directory: join(this.directory, 'browser-profiles', key) };
793
822
  },
794
823
  });
824
+ this.hosted = new HostedMonitor({
825
+ surface: 'desktop', home: this.directory,
826
+ ...(options.hostedCheck === undefined ? {} : { check: options.hostedCheck }),
827
+ ...(options.hostedNow === undefined ? {} : { now: options.hostedNow }),
828
+ applyEntry: answer => this.applyHostedEntry(answer),
829
+ hasEntry: async () => hasAndorraEntry(await loadConfig(this.directory)),
830
+ onChange: () => { void this.hostedStatus().then(payload => { if (!this.closed)
831
+ this.emit('andorra.status', payload); }, () => { }); },
832
+ onAnnounce: ({ promotionId }) => this.emit('andorra.announce', { message: andorraAnnouncement(), promotionId }),
833
+ onNotice: () => this.emit('andorra.notice', { message: ANDORRA_CHANGED_MESSAGE }),
834
+ });
795
835
  this.timers.onDue = () => this.checkTimers();
796
836
  this.timers.onArmed = timer => {
797
837
  if (timer.owner === undefined)
@@ -914,6 +954,84 @@ export class AppServer {
914
954
  this.autoArchiveCheck.unref();
915
955
  void this.reapSessions();
916
956
  }
957
+ // One monitor per engine; an automation worker shares the home with the desktop engine and checks nothing.
958
+ if (process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed && !this.hostedStarted) {
959
+ this.hostedStarted = true;
960
+ void this.hosted.start();
961
+ }
962
+ }
963
+ /**
964
+ * Keeps the Andorra entry current from an enabled answer. A missing entry is created only when the user added
965
+ * Andorra: that decision is read inside this engine's queue of config writes and inside the cross-process
966
+ * config lock, so an add or a removal recorded just before, here or in another process, is the one that counts.
967
+ */
968
+ async applyHostedEntry(answer) {
969
+ const saved = await this.serializeConfig(async () => this.closed ? undefined : saveAndorraAnswer(this.directory, answer));
970
+ if (saved)
971
+ this.emit('config.changed', { config: await this.analyticsConfigView(saved) });
972
+ }
973
+ /**
974
+ * What clients are told about Andorra: its availability, whether it can be added, and, while it is offered and
975
+ * the user has not removed it, the entry to LIST: a provider view built from the hosted answer that is not in
976
+ * the saved config (`listed`). A client shows it as an ordinary provider and saves it with `andorra.add` the
977
+ * first time the user picks it. `usage`, when known, is what to show for the hosted models (HostedMonitor.usage).
978
+ */
979
+ async hostedStatus() {
980
+ const status = this.hosted.availability();
981
+ const offered = this.hosted.offered();
982
+ const usage = this.hosted.usage();
983
+ const base = { status, offered, ...(usage === undefined ? {} : { usage }) };
984
+ const answer = this.hosted.listed() ? this.hosted.enabledAnswer() : undefined;
985
+ if (!answer)
986
+ return base;
987
+ const config = await loadConfig(this.directory).catch(() => undefined);
988
+ const entry = config && virtualAndorraEntry(config, answer);
989
+ return entry ? { ...base, listed: providerView(entry, [entry, ...config.providers]) } : base;
990
+ }
991
+ /** The user removed the listed, never-saved Andorra: it is no longer listed (Add Provider still offers it). */
992
+ async hideListedEntry() {
993
+ if (hasAndorraEntry(await loadConfig(this.directory)))
994
+ throw new AppServerError('invalid-params', 'Andorra is a saved provider: remove it with providers.update');
995
+ // A removal that could not be recorded removed nothing: the entry stays listed and the window is told.
996
+ if (!await this.serializeConfig(() => recordAndorraRemoved(this.directory)))
997
+ throw new Error(ANDORRA_REMOVE_FAILED);
998
+ await this.hosted.entryChanged();
999
+ return { removed: true };
1000
+ }
1001
+ /** Saves the Andorra provider because the user asked for it; with `select`, it becomes the active provider in the same write. */
1002
+ async addHostedEntry(select, model) {
1003
+ if (this.closed)
1004
+ return { added: false, message: ANDORRA_UNAVAILABLE_MESSAGE };
1005
+ let saved;
1006
+ let result;
1007
+ try {
1008
+ result = await addAndorraEntry({
1009
+ home: this.directory,
1010
+ monitor: this.hosted,
1011
+ ...(select === undefined ? {} : { select }),
1012
+ ...(model === undefined ? {} : { model }),
1013
+ serialize: body => this.serializeConfig(body),
1014
+ change: async (update) => {
1015
+ if (update(await loadConfig(this.directory)) === undefined)
1016
+ return;
1017
+ let wrote = false;
1018
+ const next = await changeConfigFile(this.directory, current => {
1019
+ const updated = update(current);
1020
+ wrote = updated !== undefined;
1021
+ return updated ?? current;
1022
+ });
1023
+ if (wrote)
1024
+ saved = next;
1025
+ },
1026
+ });
1027
+ }
1028
+ catch (error) {
1029
+ throw error instanceof ConfigConflictError ? new AppServerError('busy', message(error)) : new AppServerError('invalid-params', message(error));
1030
+ }
1031
+ if (saved)
1032
+ this.emit('config.changed', { config: await this.analyticsConfigView(saved) });
1033
+ await this.hosted.entryChanged();
1034
+ return result;
917
1035
  }
918
1036
  reapSessions() {
919
1037
  const next = this.autoArchivePass.then(() => this.autoArchiveSessions())
@@ -1065,6 +1183,22 @@ export class AppServer {
1065
1183
  return { providers: providerViews(config.providers), active: config.provider };
1066
1184
  }
1067
1185
  case 'providers.update': return this.updateProviders(params);
1186
+ case 'andorra.status': {
1187
+ if (params.check !== undefined && typeof params.check !== 'boolean')
1188
+ throw new AppServerError('invalid-params', 'check must be a boolean');
1189
+ if (params.check === true && !this.closed)
1190
+ await this.hosted.check('open');
1191
+ return this.hostedStatus();
1192
+ }
1193
+ case 'andorra.add': {
1194
+ if (params.model !== undefined && typeof params.model !== 'string')
1195
+ throw new AppServerError('invalid-params', 'model must be a string');
1196
+ if (params.select !== undefined && typeof params.select !== 'boolean')
1197
+ throw new AppServerError('invalid-params', 'select must be a boolean');
1198
+ // `model` without `select`: the window selects it itself afterwards, and is told when it is not served.
1199
+ return this.addHostedEntry(params.select === true ? { ...(typeof params.model === 'string' ? { model: params.model } : {}) } : undefined, typeof params.model === 'string' ? params.model : undefined);
1200
+ }
1201
+ case 'andorra.remove': return this.hideListedEntry();
1068
1202
  case 'providers.discover': return this.discoverModels(params);
1069
1203
  case 'providers.test': return this.testProviderEndpoint(params);
1070
1204
  case 'providers.detectSignIns': return this.detectProviderSignIns(params);
@@ -1101,9 +1235,11 @@ export class AppServer {
1101
1235
  const { session, goal, text: notice, changed } = await this.setSessionGoal(params);
1102
1236
  return { session: this.summary(session), goal: goal ?? null, text: notice, changed };
1103
1237
  }
1238
+ case 'sessions.setJev': return { session: this.summary(await this.setSessionJev(params)) };
1104
1239
  case 'sessions.setArchived': return { session: this.summary(await this.setSessionArchived(params)) };
1105
1240
  case 'sessions.delete': return this.deleteSession(params);
1106
1241
  case 'sessions.pullRequest.get': return { pullRequest: pullRequestForClients(await readPullRequest(this.directory, identifier(params.id, 'id'))) };
1242
+ case 'sessions.pullRequest.list': return { pullRequests: (await listPullRequests(this.directory)).map(entry => ({ sessionId: entry.sessionId, pullRequest: pullRequestForClients(entry.pullRequest) })) };
1107
1243
  case 'sessions.pullRequest.update': {
1108
1244
  let settings;
1109
1245
  try {
@@ -1151,6 +1287,8 @@ export class AppServer {
1151
1287
  case 'graphs.list': return this.listGraphs(params);
1152
1288
  case 'graphs.get': return this.getGraph(params);
1153
1289
  case 'graphs.select': return this.selectGraph(params);
1290
+ case 'graphs.visibility.set': return this.setGraphVisibilityMethod(params);
1291
+ case 'graphs.visibility.import': return this.importGraphVisibilityMethod(params);
1154
1292
  case 'agents.export': return this.exportAgent(params);
1155
1293
  case 'editor.open': return this.openEditor();
1156
1294
  case 'editor.close': return this.closeEditor();
@@ -1214,6 +1352,16 @@ export class AppServer {
1214
1352
  await this.browserViews.closeTab(sessionId, optionalIdentifier(params.tabId, 'tabId'));
1215
1353
  return { ok: true };
1216
1354
  }
1355
+ case 'browser.view.show': {
1356
+ const sessionId = identifier(params.sessionId, 'sessionId');
1357
+ await this.browserViews.showWindow(sessionId);
1358
+ return { ok: true };
1359
+ }
1360
+ case 'browser.view.hide': {
1361
+ const sessionId = identifier(params.sessionId, 'sessionId');
1362
+ await this.browserViews.hideWindow(sessionId);
1363
+ return { ok: true };
1364
+ }
1217
1365
  case 'browser.view.stream': {
1218
1366
  const sessionId = identifier(params.sessionId, 'sessionId');
1219
1367
  if (typeof params.enabled !== 'boolean')
@@ -1886,46 +2034,55 @@ export class AppServer {
1886
2034
  const removedSlots = [];
1887
2035
  const removedAnthropic = [];
1888
2036
  const saved = await this.serializeConfig(async () => {
1889
- try {
1890
- return await changeConfigFile(this.directory, current => {
1891
- let providers;
1892
- if (upsert !== undefined) {
1893
- if (!upsert || typeof upsert !== 'object' || Array.isArray(upsert))
1894
- throw new AppServerError('invalid-params', 'A provider to upsert must be an object');
1895
- if (previous !== undefined && !sameProvider(storedEntry(current.providers, String(upsert.id ?? '')), previous)) {
1896
- throw new AppServerError('busy', 'That provider changed elsewhere. Reload it and try again.');
2037
+ const save = async () => {
2038
+ try {
2039
+ const next = await changeConfigFile(this.directory, current => {
2040
+ let providers;
2041
+ if (upsert !== undefined) {
2042
+ if (!upsert || typeof upsert !== 'object' || Array.isArray(upsert))
2043
+ throw new AppServerError('invalid-params', 'A provider to upsert must be an object');
2044
+ if (previous !== undefined && !sameProvider(storedEntry(current.providers, String(upsert.id ?? '')), previous)) {
2045
+ throw new AppServerError('busy', 'That provider changed elsewhere. Reload it and try again.');
2046
+ }
2047
+ const [entry] = mergeProviderSecrets(current.providers, [upsert]);
2048
+ const index = current.providers.findIndex(item => item.id === entry.id);
2049
+ providers = index < 0 ? [...current.providers, entry] : current.providers.map((item, at) => at === index ? entry : item);
2050
+ providers = allocateCodexAccountSlots(current.providers, providers);
2051
+ removedSlots.length = 0;
2052
+ removedSlots.push(...droppedCodexSlots(current.providers, providers));
2053
+ removedAnthropic.length = 0;
2054
+ removedAnthropic.push(...droppedAnthropicAccounts(current.providers, providers));
1897
2055
  }
1898
- const [entry] = mergeProviderSecrets(current.providers, [upsert]);
1899
- const index = current.providers.findIndex(item => item.id === entry.id);
1900
- providers = index < 0 ? [...current.providers, entry] : current.providers.map((item, at) => at === index ? entry : item);
1901
- providers = allocateCodexAccountSlots(current.providers, providers);
1902
- removedSlots.length = 0;
1903
- removedSlots.push(...droppedCodexSlots(current.providers, providers));
1904
- removedAnthropic.length = 0;
1905
- removedAnthropic.push(...droppedAnthropicAccounts(current.providers, providers));
1906
- }
1907
- else if (remove !== undefined) {
1908
- removedSlots.length = 0;
1909
- providers = current.providers.filter(item => item.id !== remove);
1910
- removedSlots.push(...droppedCodexSlots(current.providers, providers));
1911
- removedAnthropic.length = 0;
1912
- removedAnthropic.push(...droppedAnthropicAccounts(current.providers, providers));
1913
- }
1914
- else {
1915
- providers = current.providers.map(item => item.id === clearKey ? { ...item, apiKey: undefined } : item);
1916
- }
1917
- const ids = new Set(providers.map(item => item.id));
1918
- const requested = typeof params.active === 'string' && params.active ? params.active : current.provider;
1919
- const provider = ids.has(requested) ? requested : (providers[0]?.id ?? '');
1920
- return reconcileSubagentPair({ ...current, providers, provider });
1921
- });
1922
- }
1923
- catch (error) {
1924
- if (error instanceof AppServerError)
1925
- throw error;
1926
- throw error instanceof ConfigConflictError ? new AppServerError('busy', message(error)) : new AppServerError('invalid-params', message(error));
1927
- }
2056
+ else if (remove !== undefined) {
2057
+ removedSlots.length = 0;
2058
+ providers = current.providers.filter(item => item.id !== remove);
2059
+ removedSlots.push(...droppedCodexSlots(current.providers, providers));
2060
+ removedAnthropic.length = 0;
2061
+ removedAnthropic.push(...droppedAnthropicAccounts(current.providers, providers));
2062
+ }
2063
+ else {
2064
+ providers = current.providers.map(item => item.id === clearKey ? { ...item, apiKey: undefined } : item);
2065
+ }
2066
+ const ids = new Set(providers.map(item => item.id));
2067
+ const requested = typeof params.active === 'string' && params.active ? params.active : current.provider;
2068
+ const provider = ids.has(requested) ? requested : fallbackProviderId(providers);
2069
+ return reconcileSubagentPair({ ...current, providers, provider });
2070
+ });
2071
+ return next;
2072
+ }
2073
+ catch (error) {
2074
+ if (error instanceof AppServerError)
2075
+ throw error;
2076
+ throw error instanceof ConfigConflictError ? new AppServerError('busy', message(error)) : new AppServerError('invalid-params', message(error));
2077
+ }
2078
+ };
2079
+ // Removing Andorra: the decision is recorded before the config without the entry is saved (and put back when
2080
+ // the save fails), so a check in another process can never create the entry again in between.
2081
+ const removesAndorra = remove !== undefined
2082
+ && (await loadConfig(this.directory).catch(() => undefined))?.providers.some(item => item.id === remove && item.type === 'andorra') === true;
2083
+ return removesAndorra ? removingAndorraEntry(this.directory, save) : save();
1928
2084
  });
2085
+ await this.hosted.entryChanged();
1929
2086
  const view = await this.analyticsConfigView(saved);
1930
2087
  this.emit('config.changed', { config: view });
1931
2088
  await this.retireSlots(removedSlots);
@@ -1952,9 +2109,9 @@ export class AppServer {
1952
2109
  async discoverModels(params) {
1953
2110
  let provider;
1954
2111
  if (params.providerType !== undefined) {
1955
- const catalogs = { claude: 'https://api.anthropic.com', 'opencode-go': 'https://opencode.ai/inference/go', grok: GROK_BASE_URL, opencode: OPENCODE_BASE_URL };
2112
+ const catalogs = { claude: 'https://api.anthropic.com', 'opencode-go': 'https://opencode.ai/inference/go', grok: GROK_BASE_URL, google: GOOGLE_BASE_URL, opencode: OPENCODE_BASE_URL };
1956
2113
  if (params.providerId !== undefined || typeof params.providerType !== 'string' || !Object.hasOwn(catalogs, params.providerType)) {
1957
- throw new AppServerError('invalid-params', 'providerType must be claude, grok, opencode or opencode-go, without providerId');
2114
+ throw new AppServerError('invalid-params', 'providerType must be claude, grok, google, opencode or opencode-go, without providerId');
1958
2115
  }
1959
2116
  const type = params.providerType;
1960
2117
  provider = { id: 'catalog', type, model: type === 'opencode' ? 'catalog/catalog' : 'catalog', baseUrl: catalogs[type] };
@@ -1977,7 +2134,7 @@ export class AppServer {
1977
2134
  async detectProviderSignIns(params) {
1978
2135
  const skip = params.skip;
1979
2136
  if (Object.keys(params).some(key => key !== 'skip') || (skip !== undefined && (!Array.isArray(skip) || skip.length > 8 || skip.some(type => !isDetectableSignInType(type))))) {
1980
- throw new AppServerError('invalid-params', 'Sign-in detection accepts only skip, a list of claude, codex, grok or opencode.');
2137
+ throw new AppServerError('invalid-params', 'Sign-in detection accepts only skip, a list of claude, codex, grok, opencode or google.');
1981
2138
  }
1982
2139
  const config = await loadConfig(this.directory);
1983
2140
  const { signIns } = await this.operation(60_000, signal => detectSignIns(config, signal, {
@@ -2028,10 +2185,10 @@ export class AppServer {
2028
2185
  return { config: view, added };
2029
2186
  }
2030
2187
  async providerAuth(action, params) {
2031
- if (params.providerType === 'claude' || params.providerType === 'grok' || params.providerType === 'opencode')
2188
+ if (params.providerType === 'claude' || params.providerType === 'grok' || params.providerType === 'google' || params.providerType === 'opencode')
2032
2189
  return this.managedProviderAuth(action, params);
2033
2190
  if (action === 'submit')
2034
- throw new AppServerError('invalid-params', 'Only Claude, Grok and OpenCode sign-ins accept a pasted code.');
2191
+ throw new AppServerError('invalid-params', 'Only Claude, Grok, Google and OpenCode sign-ins accept a pasted code.');
2035
2192
  if (params.providerType === 'anthropic')
2036
2193
  return this.anthropicProviderAuth(action, params);
2037
2194
  if (params.providerType !== 'codex' || Object.keys(params).some(key => !['providerType', 'attemptId', 'providerId'].includes(key))) {
@@ -2064,7 +2221,7 @@ export class AppServer {
2064
2221
  }
2065
2222
  async managedProviderAuth(action, params) {
2066
2223
  const type = params.providerType;
2067
- const product = type === 'claude' ? 'Claude' : type === 'grok' ? 'Grok' : 'OpenCode';
2224
+ const product = type === 'claude' ? 'Claude' : type === 'grok' ? 'Grok' : type === 'google' ? 'Google' : 'OpenCode';
2068
2225
  const allowed = ['providerType', 'attemptId', 'providerId', 'code', ...(type === 'opencode' ? ['signInProvider', 'signInMethod'] : [])];
2069
2226
  if (Object.keys(params).some(key => !allowed.includes(key))) {
2070
2227
  throw new AppServerError('invalid-params', `${product} sign-in accepts providerType, an optional attemptId and providerId${type === 'opencode' ? ', signInProvider and signInMethod' : ''}, and a code to submit.`);
@@ -2096,7 +2253,7 @@ export class AppServer {
2096
2253
  : await service.status(id);
2097
2254
  }
2098
2255
  else {
2099
- const service = type === 'claude' ? this.claudeSignIn : this.grokSignIn;
2256
+ const service = type === 'claude' ? this.claudeSignIn : type === 'google' ? this.googleSignIn : this.grokSignIn;
2100
2257
  view = action === 'start' ? await service.start(id)
2101
2258
  : action === 'cancel' ? await service.cancel(id)
2102
2259
  : action === 'submit' ? await service.submitCode(id, code)
@@ -2190,6 +2347,7 @@ export class AppServer {
2190
2347
  ...(access.dailyDecisionUsed === undefined ? {} : { dailyDecisionUsed: access.dailyDecisionUsed }),
2191
2348
  ...(access.decisionsSinceRollout === undefined ? {} : { decisionsSinceRollout: access.decisionsSinceRollout }),
2192
2349
  ...(access.fairUse === undefined ? {} : { fairUse: access.fairUse }),
2350
+ ...(access.unlimited === undefined ? {} : { unlimited: access.unlimited }),
2193
2351
  ...(access.windowDays === undefined ? {} : { windowDays: access.windowDays }),
2194
2352
  ...(access.windowDecisionLimit === undefined ? {} : { windowDecisionLimit: access.windowDecisionLimit }),
2195
2353
  ...(access.windowDecisionUsed === undefined ? {} : { windowDecisionUsed: access.windowDecisionUsed }),
@@ -2253,6 +2411,7 @@ export class AppServer {
2253
2411
  try {
2254
2412
  const status = await this.operation(180_000, signal => login({ signal, onMessage: detail => this.emit('account.login.message', { message: detail }) }));
2255
2413
  await this.publishAccount();
2414
+ this.checkHostedAfterAccountChange();
2256
2415
  return { signedIn: status.signedIn, subject: status.subject };
2257
2416
  }
2258
2417
  catch (error) {
@@ -2264,12 +2423,18 @@ export class AppServer {
2264
2423
  try {
2265
2424
  const { revoked } = await logout();
2266
2425
  await this.publishAccount();
2426
+ this.checkHostedAfterAccountChange();
2267
2427
  return { revoked };
2268
2428
  }
2269
2429
  catch (error) {
2270
2430
  throw new AppServerError('auth', message(error));
2271
2431
  }
2272
2432
  }
2433
+ /** Signing in or out changes what Andorra offers this account: ask now instead of at the next interval. */
2434
+ checkHostedAfterAccountChange() {
2435
+ if (process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed)
2436
+ void this.hosted.check('account');
2437
+ }
2273
2438
  async publishAccount() {
2274
2439
  try {
2275
2440
  this.emit('account.changed', await this.accountStatus());
@@ -2384,6 +2549,27 @@ export class AppServer {
2384
2549
  return renamed;
2385
2550
  });
2386
2551
  }
2552
+ async setSessionJev(params) {
2553
+ const id = identifier(params.id, 'id');
2554
+ if (typeof params.enabled !== 'boolean')
2555
+ throw new AppServerError('invalid-params', 'enabled must be a boolean');
2556
+ const enabled = params.enabled;
2557
+ if (this.startingSession === id || this.starting)
2558
+ throw new AppServerError('busy', 'That task is starting. Wait for it to begin, then change Jev.');
2559
+ const ownRunId = this.run?.sessionId === id ? this.run.runId
2560
+ : this.finishingRunId !== undefined && this.finishingSessionId === id ? this.finishingRunId : undefined;
2561
+ return this.withSessionMutation(id, async () => {
2562
+ const record = await this.readSession(id);
2563
+ if ((record.jevEnabled !== false) === enabled)
2564
+ return record;
2565
+ if (await sessionHasOpenRun(this.directory, id, ownRunId === undefined ? {} : { ignoreRunId: ownRunId }))
2566
+ throw new AppServerError('busy', 'That task is running in another window. Stop the run or wait for it to finish, then change Jev.');
2567
+ const updated = { ...record, jevEnabled: enabled };
2568
+ await this.store().save(savedSessionFields(updated));
2569
+ this.emit('session.updated', { session: this.summary(updated) });
2570
+ return updated;
2571
+ });
2572
+ }
2387
2573
  async setSessionGoal(params) {
2388
2574
  const id = identifier(params.id, 'id');
2389
2575
  const command = typeof params.command === 'string' ? params.command : '';
@@ -2605,7 +2791,7 @@ export class AppServer {
2605
2791
  if (turns[turns.length - 1] !== turn)
2606
2792
  throw new AppServerError('invalid-params', 'That attempt is no longer the newest turn in the session, so it cannot be resumed.');
2607
2793
  const rawSelection = typeof source.graphSelection === 'string' ? source.graphSelection : source.graph?.id;
2608
- const graphId = rawSelection === 'software-engineer' ? 'default' : rawSelection === 'andorra' ? ':andorra' : rawSelection;
2794
+ const graphId = rawSelection === 'software-engineer' ? 'default' : rawSelection === 'andorra' ? RETIRED_ANDORRA_SELECTION : rawSelection;
2609
2795
  if (!await claimRunResume(this.directory, originalRunId))
2610
2796
  throw new AppServerError('busy', 'That run is already being resumed by another engine.');
2611
2797
  const inheritedPermissions = params.permissions === undefined && isPermissionMode(source.permissions)
@@ -2709,9 +2895,9 @@ export class AppServer {
2709
2895
  }
2710
2896
  async loadResumeGraph(selection, signal, overrideAllNodes, nodeModelOverrides, config) {
2711
2897
  if (overrideAllNodes || nodeModelOverrides === undefined) {
2712
- return this.loadGraph(selection, signal, undefined, { bindProviders: !overrideAllNodes, allowDeleted: true });
2898
+ return this.loadGraph(selection, signal, undefined, { bindProviders: !overrideAllNodes, allowDeleted: true, allowRetired: true });
2713
2899
  }
2714
- const raw = await this.loadGraph(selection, signal, undefined, { bindProviders: false, allowDeleted: true });
2900
+ const raw = await this.loadGraph(selection, signal, undefined, { bindProviders: false, allowDeleted: true, allowRetired: true });
2715
2901
  const prebound = structuredClone(raw);
2716
2902
  for (const [nodeId, pair] of Object.entries(nodeModelOverrides)) {
2717
2903
  const node = prebound.nodes[nodeId];
@@ -2773,7 +2959,10 @@ export class AppServer {
2773
2959
  const runState = params.state !== undefined && typeof params.state === 'object' && params.state !== null && !Array.isArray(params.state)
2774
2960
  ? structuredClone(params.state) : undefined;
2775
2961
  const implicit = params.graph === undefined || params.graph === '';
2776
- let selection = implicit ? configuredGraphSelection(config, await currentGraphSubject()) : identifier(params.graph, 'graph');
2962
+ // A resumed attempt keeps the graph it stopped on, the removed Andorra preset included: its journal and
2963
+ // checkpoints name that graph's nodes. A new task that names the preset runs Default.
2964
+ let selection = implicit ? configuredGraphSelection(config, await currentGraphSubject())
2965
+ : internal?.resumedFrom !== undefined ? identifier(params.graph, 'graph') : currentGraphSelection(identifier(params.graph, 'graph'));
2777
2966
  if (implicit && await this.selectionIsDeleted(selection))
2778
2967
  selection = 'default';
2779
2968
  const requested = params.permissions === undefined ? undefined : permissionMode(params.permissions);
@@ -2825,7 +3014,9 @@ export class AppServer {
2825
3014
  inheritedTurns: existing.history.length, lineage: lineagePoints(existing, existing.usage, existing.history.length) };
2826
3015
  await copySessionSkill(this.directory, existing.id, record.id).catch(error => this.log('warn', `Could not carry the session's active skill to its continuation: ${message(error)}`));
2827
3016
  }
2828
- record = { ...record, workspace: root, projectId: record.projectId ?? await this.projectIdFor(root), updatedAt: new Date().toISOString() };
3017
+ if (params.jevEnabled !== undefined && typeof params.jevEnabled !== 'boolean')
3018
+ throw new AppServerError('invalid-params', 'jevEnabled must be a boolean');
3019
+ record = { ...record, workspace: root, projectId: record.projectId ?? await this.projectIdFor(root), updatedAt: new Date().toISOString(), ...(params.jevEnabled === undefined ? {} : { jevEnabled: params.jevEnabled }) };
2829
3020
  const controller = new AbortController();
2830
3021
  const runId = randomUUID();
2831
3022
  const telemetryRunId = randomUUID();
@@ -3151,7 +3342,7 @@ export class AppServer {
3151
3342
  const openRecord = { id: runId, status: 'running', sessionId: record.id, startedAt, pid: process.pid, graphSelection: selection, graph: { id: selection }, provider: provider.id, model: modelId,
3152
3343
  surface: configuredSurface('desktop'),
3153
3344
  ...(accountSubject ? { accountSubject } : {}),
3154
- telemetry: { runId: telemetryRunId, nodes: 0, subagents: false, jevEnabled: config.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off', permissionMode: internal?.inheritedPermissions ?? effective, startSent: false },
3345
+ telemetry: { runId: telemetryRunId, nodes: 0, subagents: false, jevEnabled: config.jevEnabled !== false && record.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off', permissionMode: internal?.inheritedPermissions ?? effective, startSent: false },
3155
3346
  ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(effort === undefined ? {} : { reasoningEffort: effort }),
3156
3347
  ...(automationContext === undefined ? {} : { automationContext }),
3157
3348
  ...(internal?.inheritedPermissions === undefined ? {} : { permissions: internal.inheritedPermissions }),
@@ -3202,7 +3393,7 @@ export class AppServer {
3202
3393
  const permissionControl = new RunControl();
3203
3394
  permissionControl.permissions = effective;
3204
3395
  permissionControl.yolo = effective === 'full-access';
3205
- this.run = { runId, sessionId: record.id, controller, workspace: root, steers: liveSteers, steersClosed: false,
3396
+ this.run = { runId, sessionId: record.id, controller, workspace: root, steers: liveSteers, subagents: new Set(), steersClosed: false,
3206
3397
  permissionControl, permissionRevision: 0, approvals: new Set(), boundPermissions: internal?.inheritedPermissions !== undefined,
3207
3398
  codeIntelPermissions: effective, ...(lineage.length === 0 ? {} : { lineage: [...lineage] }) };
3208
3399
  {
@@ -3245,7 +3436,8 @@ export class AppServer {
3245
3436
  controller.signal.addEventListener('abort', () => resolve(), { once: true });
3246
3437
  })]);
3247
3438
  const settled = released
3248
- .then(() => controller.signal.aborted || this.workGeneration !== generation ? '' : summarizeSessionPrompt(task, createAdapter(provider), modelId, controller.signal))
3439
+ // A run Andorra refused (unavailable, sign in, allowance, busy) ended without an answer: no second request follows the refusal.
3440
+ .then(() => controller.signal.aborted || this.workGeneration !== generation || (provider.type === 'andorra' && !this.titleAnswered.has(runId)) ? '' : summarizeSessionPrompt(task, createAdapter(provider), modelId, controller.signal))
3249
3441
  .then(async (summary) => {
3250
3442
  if (!summary || controller.signal.aborted || record.renamed === true)
3251
3443
  return;
@@ -3266,6 +3458,7 @@ export class AppServer {
3266
3458
  })
3267
3459
  .finally(() => {
3268
3460
  this.titleReleases.delete(runId);
3461
+ this.titleAnswered.delete(runId);
3269
3462
  if (this.sessionTitles.get(record.id) === controller)
3270
3463
  this.sessionTitles.delete(record.id);
3271
3464
  this.operations.delete(controller);
@@ -3321,6 +3514,11 @@ export class AppServer {
3321
3514
  let localCacheReadTokens = 0;
3322
3515
  const probeUsage = { requests: 0, inputTokens: 0, outputTokens: 0 };
3323
3516
  const probeModels = new Map();
3517
+ // Set by the first model request this run sends to an Andorra provider (the health probe's included): the
3518
+ // hosted usage is asked for again when such a run ends.
3519
+ let askedAndorra = false;
3520
+ const watchAndorra = (providerType, adapter) => providerType === 'andorra' ? watchRequests(adapter, () => { askedAndorra = true; }) : adapter;
3521
+ const watchResolved = (resolved) => ({ ...resolved, adapter: watchAndorra(resolved.providerType, resolved.adapter) });
3324
3522
  let history = (input.record.contextHistory ?? input.record.history ?? []).filter(turn => turn.runId !== runId).slice(-SESSION_HISTORY_TURNS);
3325
3523
  const armedRunIdSet = new Set(armedRunIds ?? []);
3326
3524
  const contextSeed = history.filter(turn => !armedRunIdSet.has(turn.runId ?? ''));
@@ -3433,7 +3631,7 @@ export class AppServer {
3433
3631
  }
3434
3632
  const startedHandle = createRunHandle(telemetryRunId, startedAt, {
3435
3633
  graphId: selection, ...graphShape(graph), permissionMode: boundPermissions ?? permissions,
3436
- jevEnabled: config.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off',
3634
+ jevEnabled: config.jevEnabled !== false && input.record.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off',
3437
3635
  }, root);
3438
3636
  telemetryHandle = startedHandle;
3439
3637
  telemetryStart = reportRunStarted(telemetrySurfaceFor(config), startedHandle).catch(() => { });
@@ -3479,7 +3677,8 @@ export class AppServer {
3479
3677
  }
3480
3678
  probeModels.set(key, entry);
3481
3679
  },
3482
- createAdapter: provider => this.tracedAdapter(createAdapter(provider), provider.id),
3680
+ createAdapter: provider => watchAndorra(provider.type, this.tracedAdapter(createAdapter(provider), provider.id)),
3681
+ andorra: () => this.hosted.gate(),
3483
3682
  }));
3484
3683
  healthSettled = healthProbe.then(() => undefined, () => undefined);
3485
3684
  const judgeHealth = async () => {
@@ -3603,7 +3802,7 @@ export class AppServer {
3603
3802
  await healthGate;
3604
3803
  runGoal = input.record.goal?.status === 'active' ? input.record.goal : undefined;
3605
3804
  const options = {
3606
- task, runId, provider: provider.id, model: snapshot.model, adapter: this.tracedAdapter(this.reasoningAdapter(createAdapter(snapshot)), provider.id),
3805
+ task, runId, provider: provider.id, model: snapshot.model, adapter: watchAndorra(provider.type, this.tracedAdapter(this.reasoningAdapter(createAdapter(snapshot, { sessionId: input.record.id })), provider.id)),
3607
3806
  ...(openingAttachments === undefined ? {} : { attachments: openingAttachments }),
3608
3807
  ...(snapshot.contextWindow === undefined ? {} : { contextWindow: snapshot.contextWindow }),
3609
3808
  tools: [...createTools(), createBrowserPanelTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined, panelHold),
@@ -3613,54 +3812,30 @@ export class AppServer {
3613
3812
  instructions: `${await loadWorkspaceInstructions(root, signal, systemPromptOverrideFor(graph, config.systemPromptOverride))}${extension.instructions}`,
3614
3813
  codeIntel, todoStore: new TodoStore(), ...(commandMemory ? { commandMemory } : {}), ...(projectMemory ? { projectMemory } : {}),
3615
3814
  limits: resolveConfiguredLimits(config),
3616
- ...hostedDecisionPolicy(membership, config.jevEnabled !== false, config.decisions),
3815
+ ...hostedDecisionPolicy(membership, config.jevEnabled !== false && input.record.jevEnabled !== false, config.decisions),
3617
3816
  ...(config.efficiency ? { efficiency: config.efficiency } : {}),
3618
3817
  ...(runGoal ? { goalCompletionVerification: { goal: runGoal.text } } : {}),
3619
3818
  modelPinned: modelPinned || overrideAllNodes,
3620
3819
  ...(entryHistory ? { entryHistory: true } : {}),
3621
3820
  ...(startNode === undefined ? {} : { startNode }),
3622
3821
  configuredModels: config.providers.map(item => ({ id: item.id, model: item.model, ...(item.models ? { models: [...item.models] } : {}) })),
3623
- resolveModel: (id, model, modelSignal) => this.resolveModel(config, id, model, modelSignal, id === provider.id && (model === undefined || model === modelId) ? reasoningEffort : undefined),
3624
- resolveProvider: id => this.resolveProvider(config, id),
3822
+ resolveModel: (id, model, modelSignal) => this.resolveModel(config, id, model, modelSignal, id === provider.id && (model === undefined || model === modelId) ? reasoningEffort : undefined, input.record.id).then(watchResolved),
3823
+ resolveProvider: id => watchResolved(this.resolveProvider(config, id, input.record.id)),
3625
3824
  getLiveModel: async (nodeId, fallbackProvider, fallbackModel, modelSignal) => {
3626
3825
  while (true) {
3627
3826
  const current = liveRun?.modelSelection;
3628
3827
  if (!current)
3629
3828
  return undefined;
3630
- const [rootId, roleId] = (nodeId ?? '').split('/');
3631
- const fallback = roleId?.endsWith('#fallback') || rootId.endsWith('#fallback');
3632
- const own = liveRun?.modelGraph?.nodes[rootId.replace(/#fallback$/, '')];
3633
- const nodeOverride = current.nodeOverrides?.[rootId.replace(/#fallback$/, '')];
3634
- if (current.nodeOnly === true && nodeOverride === undefined && own?.provider === undefined)
3829
+ const target = liveModelTarget(current, liveRun?.modelGraph?.nodes, nodeId);
3830
+ if (target === undefined)
3635
3831
  return undefined;
3636
- const policy = own?.subagents;
3637
- const role = policy?.roles?.find(item => item.id === roleId?.replace(/#fallback$/, ''));
3638
- const parentProvider = nodeOverride?.provider ?? own?.provider ?? current.provider;
3639
- const parentModel = nodeOverride?.model ?? own?.model ?? (own?.provider === undefined ? current.model : undefined);
3640
- let targetProvider = parentProvider, targetModel = parentModel;
3641
- if (fallback && own?.retry?.fallback) {
3642
- targetProvider = own.retry.fallback.provider;
3643
- targetModel = own.retry.fallback.model;
3644
- }
3645
- const inheritedProvider = targetProvider, inheritedModel = targetModel;
3646
- if (roleId && policy?.modelPolicy === 'specific') {
3647
- targetProvider = policy.provider ?? inheritedProvider;
3648
- targetModel = policy.model;
3649
- }
3650
- else if (roleId && policy?.modelPolicy === 'per-role') {
3651
- targetProvider = role?.provider ?? inheritedProvider;
3652
- targetModel = role?.model ?? (targetProvider === inheritedProvider ? inheritedModel : undefined);
3653
- }
3654
- if (current.overrideAllNodes && nodeOverride === undefined) {
3655
- targetProvider = current.provider;
3656
- targetModel = current.model;
3657
- }
3832
+ const targetProvider = target.provider, targetModel = target.model;
3658
3833
  const effectiveModel = targetModel ?? current.config.providers.find(item => item.id === targetProvider)?.model;
3659
3834
  if (targetProvider === fallbackProvider && effectiveModel === fallbackModel)
3660
3835
  return undefined;
3661
3836
  const selectedEffort = targetProvider === current.provider && effectiveModel === current.model
3662
3837
  ? current.reasoningEffort : undefined;
3663
- const resolved = await this.resolveModel(current.config, targetProvider, targetModel, modelSignal, selectedEffort);
3838
+ const resolved = watchResolved(await this.resolveModel(current.config, targetProvider, targetModel, modelSignal, selectedEffort, input.record.id));
3664
3839
  if (liveRun?.modelSelection !== current)
3665
3840
  continue;
3666
3841
  return { ...resolved, provider: targetProvider };
@@ -3682,6 +3857,23 @@ export class AppServer {
3682
3857
  if (answered)
3683
3858
  this.modelHealth.add(answered, event.data.model);
3684
3859
  }
3860
+ if ((event.type === 'subagent.started' || event.type === 'subagent.completed') && typeof event.data.subagentId === 'string') {
3861
+ const live = this.run?.runId === runId ? this.run : undefined;
3862
+ const subagentId = event.data.subagentId;
3863
+ if (event.type === 'subagent.started')
3864
+ live?.subagents.add(subagentId);
3865
+ else {
3866
+ live?.subagents.delete(subagentId);
3867
+ // A message the subagent never read goes to the agent that started it, which is next to act.
3868
+ const unread = liveSteers.filter(entry => entry.subagentId === subagentId);
3869
+ for (const entry of unread) {
3870
+ delete entry.subagentId;
3871
+ entry.content = `(The user sent this to a subagent that finished before reading it.)\n${entry.content}`;
3872
+ }
3873
+ if (unread.length > 0)
3874
+ live?.permissionControl.notifySteer();
3875
+ }
3876
+ }
3685
3877
  if (event.type === 'graph.node.completed' && typeof event.data.nodeId === 'string') {
3686
3878
  const nodeId = event.data.nodeId;
3687
3879
  const attempts = new Set([runId, ...lineage]);
@@ -3713,7 +3905,7 @@ export class AppServer {
3713
3905
  },
3714
3906
  onNodeCheckpoint: persistCheckpoint,
3715
3907
  getSteeringMessages: async () => {
3716
- const live = takeSteers(entry => entry.wake === undefined);
3908
+ const live = takeSteers(entry => entry.wake === undefined && entry.subagentId === undefined);
3717
3909
  for (const entry of live) {
3718
3910
  for (const dir of entry.roots ?? [])
3719
3911
  if (!attachmentRoots.includes(dir))
@@ -3726,6 +3918,16 @@ export class AppServer {
3726
3918
  deliveredIds.add(entry.id);
3727
3919
  return [...armedBatch, ...live].map(entry => ({ role: 'user', content: entry.content, ...(entry.images.length ? { images: entry.images } : {}) }));
3728
3920
  },
3921
+ getSubagentSteeringMessages: async (subagentId) => {
3922
+ const own = takeSteers(entry => entry.subagentId === subagentId);
3923
+ for (const entry of own) {
3924
+ for (const dir of entry.roots ?? [])
3925
+ if (!attachmentRoots.includes(dir))
3926
+ attachmentRoots.push(dir);
3927
+ deliveredSteers.push(entry);
3928
+ }
3929
+ return own.map(entry => ({ role: 'user', content: `Message from the user, sent to you while you work. Follow it:\n${entry.content}`, ...(entry.images.length ? { images: entry.images } : {}) }));
3930
+ },
3729
3931
  getNodeSteeringMessages: async (nodeId) => {
3730
3932
  const own = takeSteers(entry => entry.wake?.origin?.nodeId === nodeId);
3731
3933
  for (const entry of own)
@@ -3751,6 +3953,9 @@ export class AppServer {
3751
3953
  panelHold.stop();
3752
3954
  healthAbort.abort();
3753
3955
  await healthSettled;
3956
+ // However the run ended, a run that spent from the hosted allowance asks for the new figure; never awaited.
3957
+ if (askedAndorra && process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed)
3958
+ void this.hosted.check('run-end').catch(() => { });
3754
3959
  await codeIntelSettled;
3755
3960
  if (steering?.length || [...nodeArmed.values()].some(list => list.length > 0)) {
3756
3961
  this.log('warn', `The direction sent with the resume was not delivered: the continued attempt reached no agent turn boundary to read it. Send it again as a follow-up.`);
@@ -3803,9 +4008,13 @@ export class AppServer {
3803
4008
  await trajectory.record('run.finished', { runId, status: closedWithRun && result?.status === 'cancelled' ? 'interrupted' : result?.status ?? (closedWithRun ? 'interrupted' : controller.signal.aborted ? 'cancelled' : 'infrastructure_error'), usage: runUsage, ...(result?.toolCalls !== undefined ? { toolCalls: result.toolCalls } : {}), ...(result === undefined && failure !== undefined ? { error: message(failure) } : {}) });
3804
4009
  await trajectory.flush();
3805
4010
  }
3806
- const steers = deliveredSteers.map(entry => ({ text: entry.text, ...(entry.refs?.length ? { attachments: entry.refs } : {}), ...(entry.wake === undefined ? {} : { wake: 'timer' }) }));
4011
+ // A message read by a subagent keeps its recipient in the record and stays out of the history later
4012
+ // tasks are given: it was an instruction for that subagent's work, not for the run's own agent.
4013
+ const steers = deliveredSteers.map(entry => ({ text: entry.text, ...(entry.refs?.length ? { attachments: entry.refs } : {}), ...(entry.wake === undefined ? {} : { wake: 'timer' }),
4014
+ ...(entry.subagentId === undefined ? {} : { subagentId: entry.subagentId }) }));
4015
+ const contextSteers = steers.filter(steer => steer.subagentId === undefined);
3807
4016
  archive.push({ task, completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(steers.length ? { steers } : {}), ...(wake === undefined ? {} : { wake }) });
3808
- history = [...history, { task, completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(steers.length ? { steers } : {}), ...(wake === undefined ? {} : { wake }) }].slice(-SESSION_HISTORY_TURNS);
4017
+ history = [...history, { task, completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(contextSteers.length ? { steers: contextSteers } : {}), ...(wake === undefined ? {} : { wake }) }].slice(-SESSION_HISTORY_TURNS);
3809
4018
  const record = { ...input.record, history: archive, contextHistory: history, updatedAt: new Date().toISOString(), usage,
3810
4019
  ...(result ? { widgets: result.widgets } : {}),
3811
4020
  context: contextUsedTokens > 0 ? { usedTokens: contextUsedTokens, ...(contextWindow === undefined ? {} : { window: contextWindow }),
@@ -4185,14 +4394,15 @@ export class AppServer {
4185
4394
  live.codeIntelSync = step.then(() => undefined, () => undefined);
4186
4395
  return step;
4187
4396
  }
4188
- async resolveModel(config, id, model, signal, reasoningEffort) {
4397
+ /** `sessionId`: the session whose run will talk to this adapter; a run passes its own, known before `this.run` is set. */
4398
+ async resolveModel(config, id, model, signal, reasoningEffort, sessionId = this.run?.sessionId) {
4189
4399
  const provider = config.providers.find(item => item.id === id);
4190
4400
  if (!provider)
4191
4401
  throw new Error(`Unknown provider: ${id}. Add it in Settings, then retry.`);
4192
4402
  const resolved = await resolveModelContext(provider, model || provider.model, signal);
4193
4403
  if (reasoningEffort !== undefined)
4194
4404
  resolved.reasoningEffort = reasoningEffort;
4195
- return { model: resolved.model, adapter: this.tracedAdapter(this.reasoningAdapter(createAdapter(resolved)), id), ...(resolved.contextWindow === undefined ? {} : { contextWindow: resolved.contextWindow }), ...(resolved.reasoningEffort === undefined ? {} : { reasoningEffort: resolved.reasoningEffort }), providerType: provider.type, baseUrl: provider.baseUrl };
4405
+ return { model: resolved.model, adapter: this.tracedAdapter(this.reasoningAdapter(createAdapter(resolved, { sessionId })), id), ...(resolved.contextWindow === undefined ? {} : { contextWindow: resolved.contextWindow }), ...(resolved.reasoningEffort === undefined ? {} : { reasoningEffort: resolved.reasoningEffort }), providerType: provider.type, baseUrl: provider.baseUrl };
4196
4406
  }
4197
4407
  async analyticsConfigView(config) {
4198
4408
  try {
@@ -4204,11 +4414,11 @@ export class AppServer {
4204
4414
  return configView(config);
4205
4415
  }
4206
4416
  }
4207
- resolveProvider(config, id) {
4417
+ resolveProvider(config, id, sessionId = this.run?.sessionId) {
4208
4418
  const provider = config.providers.find(item => item.id === id);
4209
4419
  if (!provider)
4210
4420
  throw new Error(`Unknown provider: ${id}. Add it in Settings, then retry.`);
4211
- return { model: provider.model, adapter: this.tracedAdapter(this.reasoningAdapter(createAdapter(provider)), id), ...(provider.contextWindow === undefined ? {} : { contextWindow: provider.contextWindow }), providerType: provider.type, baseUrl: provider.baseUrl };
4421
+ return { model: provider.model, adapter: this.tracedAdapter(this.reasoningAdapter(createAdapter(provider, { sessionId })), id), ...(provider.contextWindow === undefined ? {} : { contextWindow: provider.contextWindow }), providerType: provider.type, baseUrl: provider.baseUrl };
4212
4422
  }
4213
4423
  codeIntelligence(root, permissions, signal, options = {}) {
4214
4424
  const opened = this.codeIntelOpening.then(() => options.onlyWhileIdle && (this.run !== undefined || this.starting)
@@ -4270,8 +4480,11 @@ export class AppServer {
4270
4480
  return writer;
4271
4481
  }
4272
4482
  async recordRunEvent(runId, event) {
4273
- if (event.type === 'agent.model.completed')
4483
+ if (event.type === 'agent.model.completed') {
4484
+ if (this.titleReleases.has(runId))
4485
+ this.titleAnswered.add(runId);
4274
4486
  this.releaseTitleWaiter(runId);
4487
+ }
4275
4488
  await this.journalFor(runId).append(event);
4276
4489
  if (event.type === 'graph.started' || event.type === 'graph.node.started')
4277
4490
  bootMark(`run.event.${event.type}`, typeof event.data?.nodeId === 'string' ? `node=${event.data.nodeId}` : undefined);
@@ -4438,6 +4651,8 @@ export class AppServer {
4438
4651
  }
4439
4652
  const refs = resolved?.refs ?? [];
4440
4653
  const roots = await Promise.all(createdSpools.map(dir => realpath(dir).catch(() => dir)));
4654
+ // A subagent that has already finished cannot read a message, so it goes to the run's own agent.
4655
+ const subagentId = typeof params.subagentId === 'string' && live.subagents.has(params.subagentId) ? params.subagentId : undefined;
4441
4656
  if (this.run !== live || live.steersClosed) {
4442
4657
  await Promise.all(createdSpools.map(dir => rm(dir, { recursive: true, force: true }).catch(() => { })));
4443
4658
  throw live.controller.signal.aborted || live.steersClosed
@@ -4452,14 +4667,15 @@ export class AppServer {
4452
4667
  ...(refs.length ? { refs } : {}),
4453
4668
  ...(roots.length ? { roots } : {}),
4454
4669
  at: new Date().toISOString(),
4670
+ ...(subagentId === undefined ? {} : { subagentId }),
4455
4671
  };
4456
4672
  live.steers.push(entry);
4457
4673
  await this.recordRunEvent(runId, {
4458
4674
  type: 'run.steered',
4459
4675
  time: entry.at,
4460
- data: { runId, sessionId: live.sessionId, steerId: entry.id, text: entry.text, ...(refs.length ? { attachments: refs } : {}) },
4676
+ data: { runId, sessionId: live.sessionId, steerId: entry.id, text: entry.text, ...(refs.length ? { attachments: refs } : {}), ...(subagentId === undefined ? {} : { subagentId }) },
4461
4677
  });
4462
- live.permissionControl.notifySteer();
4678
+ live.permissionControl.notifySteer(subagentId);
4463
4679
  return { queued: true };
4464
4680
  }
4465
4681
  async selectionIsDeleted(selection) {
@@ -4500,17 +4716,62 @@ export class AppServer {
4500
4716
  const free = membership.paid !== true;
4501
4717
  const confirmed = free && subject !== undefined && membership.subject === subject && !membership.unavailable;
4502
4718
  const kept = confirmed ? (await readGraphQuota(directory, saved)).freeGraphId : undefined;
4503
- if (status.signedIn && !free)
4504
- graphs.push({ id: ANDORRA_GRAPH_SELECTION, name: 'Andorra', revision: getAndorraHarness().revision, preset: true });
4505
4719
  for (const graph of withoutDeletedGraphs(saved)) {
4506
4720
  if (graph.id === 'default' || (free && (graph.id !== kept || freeTierGraphViolation(graph) !== undefined)))
4507
4721
  continue;
4508
4722
  const info = await stat(join(directory, 'graphs', graph.id, 'latest.json')).catch(() => undefined);
4509
4723
  graphs.push({ id: graph.id, name: graph.name, revision: graph.revision, preset: false, ...(info ? { updatedAt: info.mtime.toISOString() } : {}) });
4510
4724
  }
4511
- const configured = configuredGraphSelection(await loadConfig(this.directory), subject);
4725
+ const config = await loadConfig(this.directory);
4726
+ const configured = configuredGraphSelection(config, subject);
4512
4727
  const selected = saved.some(graph => graph.id === configured && isDeletedGraph(graph)) ? 'default' : configured;
4513
- return { graphs, selected, paid: membership.paid === true, ...(subject === undefined ? {} : { subject }) };
4728
+ return { graphs, selected, paid: membership.paid === true, ...(subject === undefined ? {} : { subject, visibility: graphVisibilityFor(config, subject) }) };
4729
+ }
4730
+ /** The caller names the account it read; a change made for an account that is no longer signed in is refused. */
4731
+ async visibilitySubject(params) {
4732
+ const subject = await currentGraphSubject();
4733
+ if (subject === undefined)
4734
+ throw new AppServerError('invalid-params', 'Sign in to Andorra Code to choose where a graph is listed.');
4735
+ if (params.subject !== subject)
4736
+ throw new AppServerError('busy', 'The account changed while project visibility was being saved. Choose it again.');
4737
+ return subject;
4738
+ }
4739
+ visibilityPaths(value, name) {
4740
+ if (!Array.isArray(value) || value.some(path => typeof path !== 'string' || !path || path.length > 4096 || path.includes('\0'))) {
4741
+ throw new AppServerError('invalid-params', `${name} must be a list of project paths`);
4742
+ }
4743
+ return value;
4744
+ }
4745
+ async setGraphVisibilityMethod(params) {
4746
+ const graphId = identifier(params.graphId, 'graphId');
4747
+ if (graphId === 'default')
4748
+ throw new AppServerError('invalid-params', 'The bundled Default graph is always listed in every project.');
4749
+ const projects = params.projects === null ? undefined : this.visibilityPaths(params.projects, 'projects');
4750
+ const subject = await this.visibilitySubject(params);
4751
+ try {
4752
+ return { subject, visibility: await setGraphVisibility(this.directory, subject, graphId, projects) };
4753
+ }
4754
+ catch (error) {
4755
+ throw new AppServerError('storage', message(error));
4756
+ }
4757
+ }
4758
+ async importGraphVisibilityMethod(params) {
4759
+ const raw = params.visibility;
4760
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
4761
+ throw new AppServerError('invalid-params', 'visibility must map graph ids to project paths');
4762
+ const entries = {};
4763
+ for (const [graphId, paths] of Object.entries(raw)) {
4764
+ if (!/^[\w-]{1,128}$/.test(graphId) || graphId === 'default')
4765
+ continue;
4766
+ entries[graphId] = this.visibilityPaths(paths, `visibility.${graphId}`);
4767
+ }
4768
+ const subject = await this.visibilitySubject(params);
4769
+ try {
4770
+ return { subject, visibility: await importGraphVisibility(this.directory, subject, entries) };
4771
+ }
4772
+ catch (error) {
4773
+ throw new AppServerError('storage', message(error));
4774
+ }
4514
4775
  }
4515
4776
  async exportAgent(params) {
4516
4777
  const id = identifier(params.id, 'id');
@@ -4524,7 +4785,7 @@ export class AppServer {
4524
4785
  return { name: definition.name, json: JSON.stringify(exportAgentDefinition(definition), null, 2) };
4525
4786
  }
4526
4787
  async getGraph(params) {
4527
- const id = identifier(params.id, 'id');
4788
+ const id = currentGraphSelection(identifier(params.id, 'id'));
4528
4789
  const revision = params.revision === undefined ? undefined : Number(params.revision);
4529
4790
  if (revision !== undefined && (!Number.isSafeInteger(revision) || revision < 1))
4530
4791
  throw new AppServerError('invalid-params', 'revision must be a positive integer');
@@ -4535,15 +4796,6 @@ export class AppServer {
4535
4796
  ? structuredClone(SOFTWARE_ENGINEER_HARNESS)
4536
4797
  : await loadGraph(id, revision, directory);
4537
4798
  }
4538
- if (id === ANDORRA_GRAPH_SELECTION) {
4539
- try {
4540
- return await this.loadGraph(ANDORRA_GRAPH_SELECTION);
4541
- }
4542
- catch (error) {
4543
- const paid = error instanceof Error && /Paid membership/.test(error.message);
4544
- throw new AppServerError(paid ? 'auth' : 'invalid-params', message(error));
4545
- }
4546
- }
4547
4799
  return await loadGraph(id, revision, directory);
4548
4800
  };
4549
4801
  const graph = await read();
@@ -4561,7 +4813,7 @@ export class AppServer {
4561
4813
  return { graph, ...(execution !== undefined ? { execution } : {}), ...(subject === undefined ? {} : { subject }) };
4562
4814
  }
4563
4815
  async selectGraph(params) {
4564
- const id = identifier(params.id, 'id');
4816
+ const id = currentGraphSelection(identifier(params.id, 'id'));
4565
4817
  const madeFor = params.subject === undefined || params.subject === '' ? undefined : identifier(params.subject, 'subject');
4566
4818
  const madeSignedOut = madeFor === undefined && params.signedOut === true;
4567
4819
  const identityHolds = async () => identityStillHolds({
@@ -4598,13 +4850,6 @@ export class AppServer {
4598
4850
  modelWarning = formatGraphHealthFailure(health, 'Open the graph in Studio, correct the model selections, then select it again.');
4599
4851
  }
4600
4852
  const withWarning = (answer) => modelWarning === undefined ? answer : { ...answer, modelWarning };
4601
- if (id === ANDORRA_GRAPH_SELECTION) {
4602
- if (!await identityHolds()) {
4603
- throw new AppServerError('busy', 'The account changed while the graph was being selected. Choose it again.');
4604
- }
4605
- const current = await loadConfig(this.directory);
4606
- return withWarning({ config: await this.analyticsConfigView(current), selected: id, persisted: false });
4607
- }
4608
4853
  const subject = await currentGraphSubject();
4609
4854
  if (!await identityHolds()) {
4610
4855
  throw new AppServerError('busy', 'The account changed while the graph was being selected. Choose it again.');
@@ -5239,7 +5484,10 @@ export class AppServer {
5239
5484
  .catch((error) => { throw new AppServerError('storage', message(error)); });
5240
5485
  const fromKey = workspacePermissionKey(from);
5241
5486
  const toKey = workspacePermissionKey(to);
5242
- await changeConfigFile(this.directory, config => {
5487
+ let visibilityMoved = false;
5488
+ await changeConfigFile(this.directory, current => {
5489
+ const config = relinkGraphVisibility(current, from, to, merged);
5490
+ visibilityMoved = config !== current;
5243
5491
  // A merged-away project takes its permission mode and per-project extension overrides with it: the surviving
5244
5492
  // folder keeps whatever it had. Only a rename carries them across, because there the destination is the same
5245
5493
  // project in a new place.
@@ -5251,6 +5499,8 @@ export class AppServer {
5251
5499
  }
5252
5500
  return rekeyProjectExtensions(config, fromKey, toKey, merged);
5253
5501
  }).catch((error) => { throw new AppServerError('storage', message(error)); });
5502
+ if (visibilityMoved)
5503
+ announceGraphVisibilityChange();
5254
5504
  if (merged) {
5255
5505
  const { removeProjectEntry, rememberProjectIdentity } = await import('./remote/pairing.js');
5256
5506
  await removeProjectEntry(from, this.directory)
@@ -5849,10 +6099,12 @@ export class AppServer {
5849
6099
  await this.anthropicAuth.close().catch(() => { });
5850
6100
  await this.claudeSignIn.close().catch(() => { });
5851
6101
  await this.grokSignIn.close().catch(() => { });
6102
+ await this.googleSignIn.close().catch(() => { });
5852
6103
  await this.openCodeSignIn.close().catch(() => { });
5853
6104
  await sharedOpenCodeServer().close().catch(() => { });
5854
6105
  if (this.automationCheck)
5855
6106
  clearInterval(this.automationCheck);
6107
+ this.hosted.stop();
5856
6108
  await this.pullRequestWatcher.stop().catch(() => { });
5857
6109
  for (const waiter of [...this.reviewWaiters.values()])
5858
6110
  waiter({ kind: 'aborted' });
@@ -5884,6 +6136,7 @@ export class AppServer {
5884
6136
  await this.telemetrySettle;
5885
6137
  await drainTelemetry({ home: this.directory, surface: configuredSurface('desktop') });
5886
6138
  this.emitsStopped = true;
6139
+ this.stopGraphVisibilityWatch();
5887
6140
  this.terminals.shutdown();
5888
6141
  await Promise.race([
5889
6142
  this.browserViews.close(),