> ## Documentation Index
> Fetch the complete documentation index at: https://developer.box.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Build a campus AI assistant portal with Box Hubs AI Chat

> Provision one Box Hub per student service from a config file, then build a portal that embeds each hub's AI Chat and lists its sources with the Hubs API.

Students look for answers across admissions guides, housing policies, and academic calendars owned by different offices. In this tutorial, a script turns each student service's documentation folder into a Box Hub with Box AI enabled, plus one campus-wide hub, and grants students access. A small portal then embeds Box AI Chat: a focused chat on each service page and an **Ask the campus** button on the home page. The portal lists each hub's sources with the Hubs API, so items that content owners add to a hub display in the portal without code changes.

If you need a single hub, you do not need code: copy the embed code from the Box web app as described in Creating an AI Chat embed. This tutorial is for when you manage several hubs and want them in one portal. It extends the blog post Turn a Box Hub into a Campus AI Assistant in minutes.

## Before you start

Complete these setup steps before you build. You need:

* A free Box developer account, or a Box Enterprise account with **Box Hubs** and **Box AI for Hubs** enabled. See Configuring Box Hubs.
* A Box application configured with **Client Credentials Grant** authentication, authorized in the Admin Console, with these scopes:
  * **Read and write all files and folders stored in Box**
  * **Manage users** - required for the seed script to find your test student by email
  * **Manage groups** - required for the provisioning script to invite the students group to the service folders
* If you use a seed script, the app's **App Access Level** set to **App + Enterprise Access** on the **Configuration** tab. With the default **App Access Only**, the app cannot see the users in your enterprise, so the seed script cannot find your test student. After you change the access level, an admin must re-authorize the app in the Admin Console.
* A runtime for the stack you choose: Python 3.11+ for [Build by hand](#build-by-hand). [Build with an agent](#build-with-an-agent) also supports Node.js 20+, Java 17+, and .NET 8+.
* If you build with an agent, a coding agent such as Codex, Claude Code, or Cursor. Installing Box Agent Skills helps it use current Box APIs.

Every student who uses the portal needs a Box account in your enterprise, which is the Box account that owns your application, whether it is a free developer account or a Box Enterprise account. Students must also be signed in to Box in the same browser. The embedded chat runs with the student's own Box session, so it never answers from content the student cannot open in Box.

Keep the service folder IDs, students group ID, hub admin email, and enterprise ID handy. The prompt and your configuration files need them.

> [!TIP]
>
> To try the portal with sample content, skip the steps below and use a seed script. The Python working sample includes `seed.py`, [Build by hand](#build-by-hand) explains how to write it, and the [agent path](#build-with-an-agent) builds one for your stack. As your application's service account, the seed script creates the `Admissions` and `Housing` folders with fictional documents, creates the `Students` group with one test student, and writes the folder and group IDs to your configuration. You still need the hub admin email and the login email of a test student, a Box user in your enterprise who is not an admin. Use the steps below when you work with your offices' real folders.

> [accordion] 1. Create the service folders
>
> Each student service gets a folder. Each folder becomes the content of that service's hub, and all folders together feed the campus-wide hub. Box AI answers only from the files in them, so keep them limited to approved, current documentation.
>
> 1. In Box, create 2 folders: `Admissions` and `Housing`.
>
> 2. Upload each office's documents, such as application deadlines and requirements to `Admissions`, and residence hall guides and move-in dates to `Housing`.
>
> 3. Note each **folder ID** from the URL. For example, if the URL is `https://app.box.com/folder/123456789`, the folder ID is `123456789`.
>
> 4. **Share both folders with your application's service account.** This is required because Client Credentials Grant applications act as a separate service account user that does not automatically have access to your content.
>
> > [!WARNING]
> >
> > Without this step, the script fails with 404 "Not found" errors.
> >
> > To find your service account email: go to the [Developer Console](https://app.box.com/developers/console), open your app, select the **Configuration** tab, and look in the **App Details** sidebar for the **Service Account ID** (it looks like `AutomationUser_xxxxx_xxxxxx@boxdevedition.com`).
> >
> > Invite this email as a collaborator on each folder with the **Editor** role. Editor access is required because the script invites the students group to the folders.

> [accordion] 2. Create the students group
>
> A Box group controls who can use the portal's chat from one place. When a student joins or leaves, you change the group membership and nothing else.
>
> > [!TIP]
> >
> > This step requires Admin access. If you do not have access, contact your Box administrator.
>
> 1. Open the [Box Admin Console](https://app.box.com/master), select **Users & Groups**, and then select the **Groups** tab.
> 2. Create a group called `Students` and add the students who use the portal. For testing, add one Box user who is not an admin.
> 3. Find the group ID. Copy the numbers that display as part of the URL, or, with a developer token from the Developer Console, call the list groups endpoint and copy the `id` of the group:
>
> ```bash theme={null}
> curl "https://api.box.com/2.0/groups?filter_term=Students" \
>   -H "Authorization: Bearer <DEVELOPER_TOKEN>"
> ```

> [accordion] 3. Choose the hub admin
>
> The script creates the hubs as your application's service account, so the hubs belong to the service account. The service account can then read the hubs for the portal without extra setup. So that a person can manage the hubs in the Box web app, the script also adds one Box user as a **co-owner** of every hub.
>
> Choose the Box user who maintains student-facing content, and note their Box login email.

## Build with an agent

Besides the provisioning script and the portal, the agent builds a seed script that creates the service folders with sample documents and the students group. You do not need to create them in Box first. Gather these values:

* **Enterprise ID** - from the [Developer Console](https://app.box.com/developers/console), using the icon in the top-right
* **Hub admin email** - the Box login of the person who manages the hubs
* **Test student email** - the Box login of a user in your enterprise who is not an admin, for testing the portal

Choose your stack and copy the prompt. It lists these values as prerequisites, so the agent reads them from environment variables instead of trying to create them. Replace the `<ENTERPRISE_ID>`, `<ADMIN_EMAIL>`, and `<STUDENT_EMAIL>` placeholders if you want the agent to pre-fill the configuration. Otherwise, leave them and fill in the files yourself after scaffolding. Leave `<ADMISSIONS_FOLDER_ID>` and `<HOUSING_FOLDER_ID>` as they are. The seed script replaces them.

```md Python + Flask theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use Python. Target Python 3.11+, use pip and a virtual environment. Install exactly one Box package: "boxsdk~=10.0" (do NOT also install box-sdk-gen — both ship the box_sdk_gen module and conflict). Import Box APIs with `from box_sdk_gen import ...`. Also install flask, python-dotenv, and pytest for tests.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

Mirror the Python tab in the tutorial, and follow the seed script steps above for seed.py. Read already-exists errors from BoxAPIError.response_info.code. Run python3 seed.py, then python3 provision_hubs.py, then python3 portal.py.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json at startup and serve two pages from shared HTML templates in templates/ (home.html and service.html),
   filling {{PLACEHOLDER}} values with HTML-escaped strings.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Create a complete runnable project with:
- box_client.py, hubs.py, seed.py, provision_hubs.py, portal.py, hubs.config.json, sample-docs/, and templates/home.html and templates/service.html matching the tutorial
- a flat layout matching the tutorial (no unnecessary packages)
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md Python + FastAPI theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use Python with FastAPI. Target Python 3.11+, use pip and a virtual environment. Install exactly one Box package: "boxsdk~=10.0" (do NOT also install box-sdk-gen — both ship the box_sdk_gen module and conflict). Import Box APIs with `from box_sdk_gen import ...`. Also install fastapi, uvicorn, python-dotenv, pytest, and httpx (required by FastAPI's TestClient).

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

Mirror the Python tab in the tutorial for box_client.py, hubs.py, provision_hubs.py, and the templates, and follow the seed script steps above for seed.py. Adapt only portal.py to FastAPI + uvicorn, returning HTMLResponse. The Box Python SDK is synchronous — use plain def route handlers; do not await SDK methods. Read already-exists errors from BoxAPIError.response_info.code. Start uvicorn from a __main__ block on PORT so that `python3 portal.py` works. Run python3 seed.py, then python3 provision_hubs.py, then python3 portal.py.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json at startup and serve two pages from shared HTML templates in templates/ (home.html and service.html),
   filling {{PLACEHOLDER}} values with HTML-escaped strings.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Create a complete runnable project with:
- box_client.py, hubs.py, seed.py, provision_hubs.py, portal.py, hubs.config.json, sample-docs/, and templates/home.html and templates/service.html matching the tutorial
- a flat layout matching the tutorial, with the FastAPI app object in portal.py
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md TypeScript + Express theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use TypeScript on Node.js 20+. Use npm and exactly one Box package: box-node-sdk@10 (do NOT also install box-typescript-sdk-gen). Import BoxClient, BoxCcgAuth, CcgConfig, and BoxApiError from box-node-sdk. Also install dotenv, express, typescript, tsx, @types/node, @types/express, and a test runner such as node:test or vitest.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

The tutorial's Build by hand sample is Python (Flask). Use it as the behavioral spec for CCG enterprise auth, seeding, hub reuse and creation, enabling Box AI, adding only missing folders, hub and folder collaborations with already-exists handling, saving portal-config.json, and the two portal pages. Adapt the code to TypeScript and the HTTP layer to Express. Box Node SDK notes: list hub items with client.hubItems.getHubItemsV2025R0({ hubId, marker }), create a hub with client.hubs.createHubV2025R0({ title, description }), and enable Box AI with client.hubs.updateHubByIdV2025R0(hubId, { isAiEnabled: true }). Add folders with client.hubItems.manageHubItemsV2025R0(hubId, { operations: [{ action: 'add', item: { type: 'folder', id } }] }). Add hub collaborators with client.hubCollaborations.createHubCollaborationV2025R0({ hub: { type: 'hubs', id: hubId }, accessibleBy, role }), and folder collaborators with client.userCollaborations.createCollaboration. Read already-exists errors from BoxApiError.responseInfo.code. Run npx tsx seed.ts, then npx tsx provisionHubs.ts, then npx tsx portal.ts.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json at startup and serve two pages from shared HTML templates in templates/ (home.html and service.html),
   filling {{PLACEHOLDER}} values with HTML-escaped strings.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Create a complete runnable project with:
- boxClient.ts, hubs.ts, seed.ts, provisionHubs.ts, portal.ts, hubs.config.json, sample-docs/, and templates/home.html and templates/service.html mirroring the tutorial
- a flat TypeScript layout matching the tutorial
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md TypeScript + Fastify theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use TypeScript with Fastify on Node.js 20+. Use npm and exactly one Box package: box-node-sdk@10 (do NOT also install box-typescript-sdk-gen). Import BoxClient, BoxCcgAuth, CcgConfig, and BoxApiError from box-node-sdk. Also install fastify, dotenv, typescript, tsx, @types/node, and a test runner such as node:test or vitest.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

The tutorial's Build by hand sample is Python (Flask). Use it as the behavioral spec for CCG enterprise auth, seeding, hub reuse and creation, enabling Box AI, adding only missing folders, hub and folder collaborations with already-exists handling, saving portal-config.json, and the two portal pages. Adapt the code to TypeScript and the portal to Fastify, replying with content type text/html. Box Node SDK notes: list hub items with client.hubItems.getHubItemsV2025R0({ hubId, marker }), create a hub with client.hubs.createHubV2025R0({ title, description }), and enable Box AI with client.hubs.updateHubByIdV2025R0(hubId, { isAiEnabled: true }). Add folders with client.hubItems.manageHubItemsV2025R0(hubId, { operations: [{ action: 'add', item: { type: 'folder', id } }] }). Add hub collaborators with client.hubCollaborations.createHubCollaborationV2025R0({ hub: { type: 'hubs', id: hubId }, accessibleBy, role }), and folder collaborators with client.userCollaborations.createCollaboration. Export a function that builds the Fastify app without listening, so tests can call app.inject(). Read already-exists errors from BoxApiError.responseInfo.code. Add npm scripts: seed (npx tsx seed.ts), provision (npx tsx provisionHubs.ts), and start (starts the portal). Run npm run seed, then npm run provision, then npm start.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json at startup and serve two pages from shared HTML templates in templates/ (home.html and service.html),
   filling {{PLACEHOLDER}} values with HTML-escaped strings.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Create a complete runnable project with:
- boxClient.ts, hubs.ts, seed.ts, provisionHubs.ts, a Fastify portal module, hubs.config.json, sample-docs/, and templates/home.html and templates/service.html mirroring the tutorial
- an idiomatic Fastify + TypeScript layout; keep Box modules separate from the HTTP layer
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md TypeScript + Next.js theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use TypeScript with the latest stable Next.js and the App Router on Node.js 20+. Use npm and exactly one Box package: box-node-sdk@10 (do NOT also install box-typescript-sdk-gen). Import BoxClient, BoxCcgAuth, CcgConfig, and BoxApiError from box-node-sdk. Also install tsx and vitest.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

The tutorial's Build by hand sample is Python (Flask). Use it as the behavioral spec for CCG enterprise auth, seeding, hub reuse and creation, enabling Box AI, adding only missing folders, hub and folder collaborations with already-exists handling, saving portal-config.json, and the two portal pages. Adapt the code to TypeScript and the portal to Next.js. Box Node SDK notes: list hub items with client.hubItems.getHubItemsV2025R0({ hubId, marker }), create a hub with client.hubs.createHubV2025R0({ title, description }), and enable Box AI with client.hubs.updateHubByIdV2025R0(hubId, { isAiEnabled: true }). Add folders with client.hubItems.manageHubItemsV2025R0(hubId, { operations: [{ action: 'add', item: { type: 'folder', id } }] }). Add hub collaborators with client.hubCollaborations.createHubCollaborationV2025R0({ hub: { type: 'hubs', id: hubId }, accessibleBy, role }), and folder collaborators with client.userCollaborations.createCollaboration. Keep the Box client, BOX_CLIENT_SECRET, and every Box API call on the server; the browser receives only the rendered pages and their data (service titles and descriptions, hub IDs, and sources), BOX_EMBED_DOMAIN, and BOX_CHAT_BUTTON_SCRIPT. Put the Box modules in a shared folder that uses relative imports, so the standalone seed and provisioning scripts run with npx tsx outside the framework and the server code imports the same modules. The chat button script finds its own script tag by the src file name box_integrations_ai_chat_button.js, reads the data-* attributes from it, and mounts the button into document.body once without removing it. Use plain <a href> links between the home page and the service pages, not client-side navigation, so each page starts from a full page load and the chat button displays only on the home page. Render both pages as server components, and mark them export const dynamic = 'force-dynamic' so that next build does not call Box or read portal-config.json at build time. Call notFound() for unknown slugs. Load the chat button script on the home page with the next/script Script component and strategy afterInteractive, passing the data-* attributes as props; Script forwards them to the script tag. Script adds the tag in the browser after the page loads, so it is not in the page source: in the README, tell readers to check the tag and its data-hub-id in the browser's element inspector. Put the chat iframe and the BOX_AI_CHAT_CLOSE message listener in a 'use client' component that adds the listener in useEffect and removes it on cleanup. Read BOX_* variables with process.env in server code only. Do not add NEXT_PUBLIC_ variables. Next.js loads .env for server code; the standalone scripts load it with dotenv. Create the Box client on first use, not when a module loads, and reuse it. Add box-node-sdk to serverExternalPackages in next.config.ts so Next.js does not bundle it. Keep page markup in components that take plain props, so tests can render them with react-dom/server without Next.js or Box. Build the chat button Script props in a helper that tests check directly, and test the 404 by calling the service page function with an unknown slug and expecting notFound() to throw. Use "type": "module" in package.json, and run the scripts' main() only when the real paths of process.argv[1] and import.meta.url match. Read already-exists errors from BoxApiError.responseInfo.code. next dev and next start read PORT from the shell environment only, not from .env. Add a small launcher that loads .env with dotenv and starts next dev or next start with --port set to PORT, or 3000 when PORT is unset or empty. Add npm scripts: seed (npx tsx scripts/seed.ts), provision (npx tsx scripts/provisionHubs.ts), dev and start (through the launcher), build (next build), and test (vitest run). Run npm run seed, then npm run provision, then npm run dev.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json on the server and render the two pages as React Server components instead of HTML templates (no templates/ folder).
   Rely on the framework's escaping, and never pass Box data or configuration values to dangerouslySetInnerHTML.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Create a complete runnable project with:
- lib/boxClient.ts, lib/hubs.ts, scripts/seed.ts, scripts/provisionHubs.ts, app/page.tsx, app/services/[slug]/page.tsx, a client component for the chat iframe, hubs.config.json, and sample-docs/
- an idiomatic Next.js App Router layout with app/page.tsx and app/services/[slug]/page.tsx; keep the Box modules in lib/ separate from the pages
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md TypeScript + Nuxt theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use TypeScript with the latest stable Nuxt on Node.js 20+. Use npm and exactly one Box package: box-node-sdk@10 (do NOT also install box-typescript-sdk-gen). Import BoxClient, BoxCcgAuth, CcgConfig, and BoxApiError from box-node-sdk. Also install dotenv and tsx, and as dev dependencies vitest, @nuxt/test-utils, @vue/test-utils, happy-dom, typescript, and vue-tsc.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

The tutorial's Build by hand sample is Python (Flask). Use it as the behavioral spec for CCG enterprise auth, seeding, hub reuse and creation, enabling Box AI, adding only missing folders, hub and folder collaborations with already-exists handling, saving portal-config.json, and the two portal pages. Adapt the code to TypeScript and the portal to Nuxt. Box Node SDK notes: list hub items with client.hubItems.getHubItemsV2025R0({ hubId, marker }), create a hub with client.hubs.createHubV2025R0({ title, description }), and enable Box AI with client.hubs.updateHubByIdV2025R0(hubId, { isAiEnabled: true }). Add folders with client.hubItems.manageHubItemsV2025R0(hubId, { operations: [{ action: 'add', item: { type: 'folder', id } }] }). Add hub collaborators with client.hubCollaborations.createHubCollaborationV2025R0({ hub: { type: 'hubs', id: hubId }, accessibleBy, role }), and folder collaborators with client.userCollaborations.createCollaboration. Keep the Box client, BOX_CLIENT_SECRET, and every Box API call on the server; the browser receives only the rendered pages and their data (service titles and descriptions, hub IDs, and sources), BOX_EMBED_DOMAIN, and BOX_CHAT_BUTTON_SCRIPT. Put the Box modules in a shared folder that uses relative imports, so the standalone seed and provisioning scripts run with npx tsx outside the framework and the server code imports the same modules. The chat button script finds its own script tag by the src file name box_integrations_ai_chat_button.js, reads the data-* attributes from it, and mounts the button into document.body once without removing it. Use plain <a href> links between the home page and the service pages, not client-side navigation, so each page starts from a full page load and the chat button displays only on the home page. Serve the portal data from Nitro server routes that read portal-config.json and call Box, and load it in the pages with useFetch so that server-side rendering includes it. Return a 404 from the service route for unknown slugs, and in the page throw createError({ status: 404, statusText: 'Service not found', fatal: true }) when the route returns 404. Load the chat button script on the home page with useHead, passing the src and the data-* attributes in the script entry. Add the BOX_AI_CHAT_CLOSE message listener in onMounted and remove it in onBeforeUnmount. Make getBoxClient take the credentials as arguments: the standalone scripts pass process.env values, and the server routes pass useRuntimeConfig() values. Declare the server-only runtimeConfig keys boxClientId, boxClientSecret, and boxEnterpriseId as empty strings, and fill them from process.env only under $development in nuxt.config.ts. nuxt build also loads .env, so reading credentials into runtimeConfig outside $development writes the client secret into .output. Expose only BOX_EMBED_DOMAIN and BOX_CHAT_BUTTON_SCRIPT under runtimeConfig.public. The standalone scripts load .env with dotenv. In the README, note that a production server reads the credentials from NUXT_BOX_CLIENT_ID, NUXT_BOX_CLIENT_SECRET, and NUXT_BOX_ENTERPRISE_ID. nuxt dev and the built server already read PORT, including from .env in development; do not add port code. In page tests, mock the /api routes with registerEndpoint, set the public runtimeConfig through environmentOptions.nuxt.overrides in the Vitest config, and check useError() for the 404. Use "type": "module" in package.json, and run the scripts' main() only when the real paths of process.argv[1] and import.meta.url match. Read already-exists errors from BoxApiError.responseInfo.code. Add npm scripts: seed (npx tsx scripts/seed.ts), provision (npx tsx scripts/provisionHubs.ts), dev (nuxt dev), build (nuxt build), typecheck (nuxt typecheck), and test (vitest run). Run npm run seed, then npm run provision, then npm run dev.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json on the server and render the two pages as Vue components instead of HTML templates (no templates/ folder).
   Rely on the framework's escaping, and never pass Box data or configuration values to v-html.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Create a complete runnable project with:
- box/boxClient.ts, box/hubs.ts, scripts/seed.ts, scripts/provisionHubs.ts, server/api/portal.get.ts, server/api/services/[slug].get.ts, app/app.vue, app/pages/index.vue, app/pages/services/[slug].vue, hubs.config.json, and sample-docs/
- the Nuxt 4 layout with app/app.vue, app/pages/index.vue, app/pages/services/[slug].vue, and Nitro server routes in server/api/; keep the Box modules in a shared box/ folder separate from the pages
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md Node + Express theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use Node.js 20+ with JavaScript (not TypeScript) and Express. Use npm and exactly one Box package: box-node-sdk@10 (do NOT also install box-typescript-sdk-gen). Import BoxClient, BoxCcgAuth, CcgConfig, and BoxApiError from box-node-sdk. Also install express, dotenv, and use node:test for tests.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

The tutorial's Build by hand sample is Python (Flask). Use it as the behavioral spec for CCG enterprise auth, seeding, hub reuse and creation, enabling Box AI, adding only missing folders, hub and folder collaborations with already-exists handling, saving portal-config.json, and the two portal pages. Adapt the code to JavaScript and the HTTP layer to Express. Use ES modules ("type": "module" in package.json, name campus-ai-assistant) and include .js extensions in local imports. Export createApp() from portal.js and call listen only when portal.js is run directly. Read already-exists errors from BoxApiError.responseInfo.code. Do not run npm audit fix --force; it downgrades box-node-sdk. Run node seed.js, then node provisionHubs.js, then node portal.js.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json at startup and serve two pages from shared HTML templates in templates/ (home.html and service.html),
   filling {{PLACEHOLDER}} values with HTML-escaped strings.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Create a complete runnable project with:
- boxClient.js, hubs.js, seed.js, provisionHubs.js, portal.js, hubs.config.json, sample-docs/, and templates/home.html and templates/service.html mirroring the tutorial
- a flat Express + JavaScript layout; keep Box modules separate from the HTTP layer
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md Node + NestJS theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use Node.js 20+ with NestJS. NestJS projects use TypeScript by default. Use npm and exactly one Box package: box-node-sdk@10 (do NOT also install box-typescript-sdk-gen). Import BoxClient, BoxCcgAuth, CcgConfig, and BoxApiError from box-node-sdk. Also install @nestjs/core@^11, @nestjs/common@^11, @nestjs/platform-express@^11, reflect-metadata, rxjs, dotenv, and Jest with ts-jest and @nestjs/testing@^11. Pin NestJS to 11: NestJS 12 is ESM-only, which breaks a CommonJS build and Jest. Pin typescript@^5: ts-jest does not work with TypeScript 7.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

The tutorial's Build by hand sample is Python (Flask). Use it as the behavioral spec for CCG enterprise auth, seeding, hub reuse and creation, enabling Box AI, adding only missing folders, hub and folder collaborations with already-exists handling, saving portal-config.json, and the two portal pages. Adapt only the HTTP layer to NestJS. Run seeding and provisioning as standalone scripts that do not start the HTTP server. Return HTML with @Header('Content-Type', 'text/html') and throw NotFoundException for unknown slugs. Read already-exists errors from BoxApiError.responseInfo.code. Add npm scripts seed, provision, and start that build with tsc and then run the compiled output. Run npm run seed, then npm run provision, then npm start.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json at startup and serve two pages from shared HTML templates in templates/ (home.html and service.html),
   filling {{PLACEHOLDER}} values with HTML-escaped strings.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Create a complete runnable project with:
- a Box client provider, a hubs provider, standalone seed and provisioning scripts, sample-docs/, a portal controller with GET / and GET /services/:slug, hubs.config.json, and templates/home.html and templates/service.html mirroring the tutorial
- an idiomatic NestJS layout (module, controller, providers); keep the Box client, hub provisioning, and portal config in providers separate from the HTTP controller
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md Java + Spring Boot theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use Java 17+ with Spring Boot 3. Use Maven and exactly one Box artifact: com.box:box-java-sdk version 10 or later (do NOT also add box-java-sdk-gen). Use com.box.sdkgen.client.BoxClient with BoxCCGAuth, CCGConfig, BoxAPIError, and the generated managers and schemas under com.box.sdkgen. Also use spring-boot-starter-web, dotenv-java, and spring-boot-starter-test.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

The tutorial's Build by hand sample is Python (Flask). Use it as the behavioral spec for CCG enterprise auth, seeding, hub reuse and creation, enabling Box AI, adding only missing folders, hub and folder collaborations with already-exists handling, saving portal-config.json, and the two portal pages. Adapt the HTTP layer to Spring Web. Read templates/home.html and templates/service.html from the project directory at runtime and fill the {{PLACEHOLDER}} values with plain string replacement; do not add a template engine. Call the Hubs APIs through client.getHubs(), client.getHubItems(), and client.getHubCollaborations() (*V2025R0 methods), and folder collaborations through client.getUserCollaborations(). Box Java SDK notes: BoxCCGAuth and CCGConfig are in com.box.sdkgen.box.ccgauth (new CCGConfig.Builder(clientId, clientSecret).enterpriseId(...).build()), and BoxAPIError is in com.box.sdkgen.box.errors; read the code with getResponseInfo().getCode(). A hub item's getType() returns an EnumWrapper; call getValue() to get file, folder, or web_link. Each manage-items result item is a HubItemReferenceV2025R0 union; read folder IDs with getFolderReferenceV2025R0().getId(). Set server.port=${PORT:3000}. Before SpringApplication.run, copy each .env entry into a system property only if that key is not already set in the OS environment. Include a @SpringBootTest context-load test so startup wiring errors fail the test run; give it dummy BOX_* properties and a fixture portal config so it needs no .env or network. Run the Seed main class, then the ProvisionHubs main class, then mvn spring-boot:run.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json at startup and serve two pages from shared HTML templates in templates/ (home.html and service.html),
   filling {{PLACEHOLDER}} values with HTML-escaped strings.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Local dev and troubleshooting (document in README):
- Copy .env.example to .env in the project root and fill every variable before the first run.
- Load .env at startup with dotenv-java in both the provisioning entry point and the web app, so System.getenv-style lookups see BOX_* values. Check OS environment variables first so export in the shell still overrides .env.
- Run the seed and provisioning scripts as plain Java main classes with mvn compile exec:java, separate from web app startup. Set exec.mainClass to the ProvisionHubs class as a POM property, and run the seed with -Dexec.mainClass set to the Seed class.
- A generic Maven BUILD FAILURE with exit code 1 from the run command usually means startup failed, not compile. Document running with -e; typical causes are missing BOX_* variables or a missing portal-config.json.
- On macOS with a Homebrew JDK, note export JAVA_HOME/PATH if java is not found.

Create a complete runnable project with:
- a Box client factory, a HubService, a Seed main class, a ProvisionHubs main class, sample-docs/, a portal controller with GET / and GET /services/{slug}, hubs.config.json, and templates/home.html and templates/service.html mirroring the tutorial
- an idiomatic Spring Boot layout; keep the Box client, hub provisioning, and portal config in dedicated classes separate from the controller
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md Java + Quarkus theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use Java 17+ with the latest stable Quarkus 3.x platform BOM. Use Maven and exactly one Box artifact: com.box:box-java-sdk version 10 or later (do NOT also add box-java-sdk-gen). Use com.box.sdkgen.client.BoxClient with BoxCCGAuth, CCGConfig, BoxAPIError, and the generated managers and schemas under com.box.sdkgen. Also use quarkus-rest, jackson-databind for the JSON config files (the Box SDK puts Jackson on the runtime classpath only), dotenv-java, and quarkus-junit5.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

The tutorial's Build by hand sample is Python (Flask). Use it as the behavioral spec for CCG enterprise auth, seeding, hub reuse and creation, enabling Box AI, adding only missing folders, hub and folder collaborations with already-exists handling, saving portal-config.json, and the two portal pages. Adapt the HTTP layer to Quarkus REST (JAX-RS), producing text/html. Read templates/home.html and templates/service.html from the project directory at runtime and fill the {{PLACEHOLDER}} values with plain string replacement; do not add a template engine. Expose the BoxClient through the BoxSession bean rather than producing BoxClient directly as a CDI bean. Call the Hubs APIs through client.getHubs(), client.getHubItems(), and client.getHubCollaborations() (*V2025R0 methods), and folder collaborations through client.getUserCollaborations(). Box Java SDK notes: BoxCCGAuth and CCGConfig are in com.box.sdkgen.box.ccgauth (new CCGConfig.Builder(clientId, clientSecret).enterpriseId(...).build()), and BoxAPIError is in com.box.sdkgen.box.errors; read the code with getResponseInfo().getCode(). A hub item's getType() returns an EnumWrapper; call getValue() to get file, folder, or web_link. Each manage-items result item is a HubItemReferenceV2025R0 union; read folder IDs with getFolderReferenceV2025R0().getId(). Annotate the portal endpoints with @Blocking (the Box Java SDK is synchronous). Set quarkus.http.port=${PORT:3000}; Quarkus reads .env only for its own config properties, so BOX_* values still need dotenv-java. Run the Seed main class, then the ProvisionHubs main class, then mvn quarkus:dev.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json at startup and serve two pages from shared HTML templates in templates/ (home.html and service.html),
   filling {{PLACEHOLDER}} values with HTML-escaped strings.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Local dev and troubleshooting (document in README):
- Copy .env.example to .env in the project root and fill every variable before the first run.
- Load .env at startup with dotenv-java in both the provisioning entry point and the web app, so System.getenv-style lookups see BOX_* values. Check OS environment variables first so export in the shell still overrides .env.
- Run the seed and provisioning scripts as plain Java main classes with mvn compile exec:java, separate from web app startup. Set exec.mainClass to the ProvisionHubs class as a POM property, and run the seed with -Dexec.mainClass set to the Seed class.
- A generic Maven BUILD FAILURE with exit code 1 from the run command usually means startup failed, not compile. Document running with -e; typical causes are missing BOX_* variables or a missing portal-config.json.
- On macOS with a Homebrew JDK, note export JAVA_HOME/PATH if java is not found.

Create a complete runnable project with:
- an @ApplicationScoped BoxSession bean that holds the BoxClient, a HubService, a Seed main class, a ProvisionHubs main class, sample-docs/, a JAX-RS resource with GET / and GET /services/{slug}, hubs.config.json, and templates/home.html and templates/service.html mirroring the tutorial
- an idiomatic Quarkus layout; keep the Box client, hub provisioning, and portal config in dedicated beans separate from the JAX-RS resource
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md .NET + ASP.NET Core theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use .NET 8+ with ASP.NET Core controllers. Use NuGet and exactly one Box package: Box.V2.Core version 10 or later (do NOT also install Box.Sdk.Gen — v10 of Box.V2.Core already ships the generated client). Use BoxClient, BoxCcgAuth, CcgConfig, and BoxApiException from that package. Also add a test project with xUnit. Use the Microsoft.NET.Sdk.Web project SDK, which already includes ASP.NET Core; do not add a Microsoft.AspNetCore.App package reference.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

The tutorial's Build by hand sample is Python (Flask). Use it as the behavioral spec for CCG enterprise auth, seeding, hub reuse and creation, enabling Box AI, adding only missing folders, hub and folder collaborations with already-exists handling, saving portal-config.json, and the two portal pages. Adapt the HTTP layer to an ASP.NET Core controller returning text/html. Read templates/home.html and templates/service.html from the project directory at runtime and fill the {{PLACEHOLDER}} values with plain string replacement; do not add a template engine. Call the Hubs APIs through client.Hubs, client.HubItems, and client.HubCollaborations (*V2025R0Async methods), and folder collaborations through client.UserCollaborations. Box .NET SDK notes: the SDK is in the Box.Sdk.Gen namespaces. Set the enterprise with new CcgConfig(clientId, clientSecret) { EnterpriseId = ... }, then new BoxClient(new BoxCcgAuth(config)). Box.Sdk.Gen.Schemas defines Task and File types that clash with System.Threading.Tasks.Task and System.IO.File; add using aliases in files that import it. Read already-exists errors from BoxApiException.ResponseInfo.Code. Add a folder with new HubItemOperationV2025R0(HubItemOperationV2025R0ActionField.Add, new FolderReferenceV2025R0(id)), and read folder IDs from each result with operation.Item.FolderReferenceV2025R0?.Id. Run dotnet run -- seed, then dotnet run -- provision, then dotnet run.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json at startup and serve two pages from shared HTML templates in templates/ (home.html and service.html),
   filling {{PLACEHOLDER}} values with HTML-escaped strings.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Local dev and troubleshooting (document in README):
- Put the runnable web .csproj at the repository root so `dotnet run` works from the folder the user clones.
- Load `.env` at startup before reading BOX_* variables (parity with python-dotenv). Walk up from Directory.GetCurrentDirectory() to find `.env`. Never override variables already set in the process environment.
- Run seeding and provisioning from the same project with command-line switches (`dotnet run -- seed` and `dotnet run -- provision`), separate from starting the portal with `dotnet run`.
- Listen on http://localhost:<PORT>, defaulting to 3000.
- Create the test project under tests/ with `dotnet new xunit`, and exclude that folder from the root .csproj compile items. Do not add a .sln at the root (two project files there break `dotnet build`); run tests with `dotnet test tests/<Name>.Tests`.

Create a complete runnable project with:
- Configuration/EnvFileLoader.cs (loads .env at startup), a Box client factory, a HubService, seed and provisioning commands, sample-docs/, a portal controller with GET / and GET /services/{slug}, hubs.config.json, and templates/home.html and templates/service.html mirroring the tutorial
- an idiomatic ASP.NET Core layout with a root-level web .csproj; keep the Box client, hub provisioning, and portal config in dedicated services separate from the controller
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

```md .NET + Minimal APIs theme={null}
Build a production-minded campus AI assistant: a provisioning script that creates one Box Hub per student service plus a campus-wide hub from a config file, and a small web portal that embeds Box Hubs AI Chat and lists each hub's sources, by following this Box tutorial:
https://developer.box.com/tutorials/campus-ai-assistant

Use .NET 8+ with ASP.NET Core Minimal APIs. Use NuGet and exactly one Box package: Box.V2.Core version 10 or later (do NOT also install Box.Sdk.Gen — v10 of Box.V2.Core already ships the generated client). Use BoxClient, BoxCcgAuth, CcgConfig, and BoxApiException from that package. Also add a test project with xUnit.

Prerequisites already done in Box (see 'Before you start' in the tutorial).
Do NOT try to create these; read their values from environment variables:
- Enterprise ID: <ENTERPRISE_ID>
- Hub admin Box login email: <ADMIN_EMAIL>
- Test student Box login email: <STUDENT_EMAIL>, an existing non-admin user in the enterprise
- CCG app scopes enabled: Read and write all files and folders stored in Box, Manage groups, and Manage users
- CCG app App Access Level: App + Enterprise Access, so that the seed script can find the test student
- Box Hubs and Box AI for Hubs enabled for the enterprise

The service folders and the students group do not exist yet. Do NOT create them yourself with Box tools, the Box CLI, or API calls while you build.
Write a seed script that creates them when the user runs it (see below).

The tutorial's Build by hand sample is Python (Flask). Use it as the behavioral spec for CCG enterprise auth, seeding, hub reuse and creation, enabling Box AI, adding only missing folders, hub and folder collaborations with already-exists handling, saving portal-config.json, and the two portal pages. Adapt only the HTTP layer to Minimal APIs, returning Results.Content(html, "text/html"). Read templates/home.html and templates/service.html from the project directory at runtime and fill the {{PLACEHOLDER}} values with plain string replacement; do not add a template engine. Call the Hubs APIs through client.Hubs, client.HubItems, and client.HubCollaborations (*V2025R0Async methods), and folder collaborations through client.UserCollaborations. Box .NET SDK notes: the SDK is in the Box.Sdk.Gen namespaces. Set the enterprise with new CcgConfig(clientId, clientSecret) { EnterpriseId = ... }, then new BoxClient(new BoxCcgAuth(config)). Box.Sdk.Gen.Schemas defines Task and File types that clash with System.Threading.Tasks.Task and System.IO.File; add using aliases in files that import it. Read already-exists errors from BoxApiException.ResponseInfo.Code. Add a folder with new HubItemOperationV2025R0(HubItemOperationV2025R0ActionField.Add, new FolderReferenceV2025R0(id)), and read folder IDs from each result with operation.Item.FolderReferenceV2025R0?.Id. Run dotnet run -- seed, then dotnet run -- provision, then dotnet run.

hubs.config.json has a campusHub object (title, description) and a services array; each service has slug, title, description, and folderId.
Create it with an Admissions service (folderId <ADMISSIONS_FOLDER_ID>) and a Housing service (folderId <HOUSING_FOLDER_ID>), matching the tutorial. The seed script replaces the placeholder folder IDs.

The seed script must:
1. Authenticate the same way as the provisioning script, so the service account owns everything it creates and needs no extra collaboration.
2. For each service in hubs.config.json, reuse the folder named after the service title in the service account's root folder
   (GET /2.0/folders/0/items, following next_marker until it is empty), or create it there (POST /2.0/folders with parent ID 0).
   Write the folder ID to the service's folderId in hubs.config.json right away.
3. Upload every file in sample-docs/<slug>/ to that folder (POST https://upload.box.com/api/2.0/files/content), skipping files whose name is already in the folder.
   Create sample-docs/admissions/ and sample-docs/housing/ with two short Markdown documents each, about a fictional university:
   application deadlines and admission requirements, and move-in dates and residence halls. Include concrete dates and rules so that questions such as 'When is the move-in date?' have answers.
4. Invite HUB_ADMIN_LOGIN by login as an editor collaborator on each folder (POST /2.0/collaborations), so the hub admin can maintain the content.
5. Reuse the group named Students (GET /2.0/groups with filter_term Students, matching the exact name), or create it (POST /2.0/groups).
   Write STUDENTS_GROUP_ID to .env, replacing the existing line or adding one, without changing the other lines.
6. Find the test student by login (GET /2.0/users with filter_term TEST_STUDENT_LOGIN, matching the login case-insensitively).
   If no user matches, stop with an error that names TEST_STUDENT_LOGIN, the Manage users scope, and App + Enterprise Access: without either, Box returns an empty list instead of an error.
7. Add the test student to the group (POST /2.0/group_memberships) unless they are already a member (GET /2.0/groups/:id/memberships, paging with offset).
8. Print each action and be safe to re-run: handle already-exists collaboration errors as in step 8 of the provisioning script.

The provisioning script must:
1. Authenticate to Box with Client Credentials Grant (enterprise / service account).
   Use BOX_ENTERPRISE_ID — do NOT authenticate as a managed user.
2. Read hubs.config.json, and read portal-config.json if it exists to reuse hub IDs from a previous run
   (services matched by slug, plus campusHubId).
3. For each service, provision a hub from that service's folder. Then provision the campus-wide hub from all service folders.
4. To provision a hub: get the hub by its previous ID (GET /2.0/hubs/:id), or create it (POST /2.0/hubs) with the configured title and description.
   If getting a saved hub ID fails, stop with that error; do not create a replacement hub.
   Enable Box AI on it (PUT /2.0/hubs/:id with is_ai_enabled true).
   Save the hub ID to portal-config.json right away (see step 9), before adding folders or collaborators.
   All Hubs API calls use the 2025.0 API version through the SDK's *V2025R0 methods.
5. List the hub items (GET /2.0/hub_items?hub_id=..., following next_marker until it is empty),
   and add only the folders that are not in the hub yet (POST /2.0/hubs/:id/manage_items, action add, item type folder).
   Print the per-operation status from the response.
6. Add the students group as a hub collaborator with role viewer and the hub admin as co-owner by login email
   (POST /2.0/hub_collaborations).
7. Add the students group as a viewer collaborator on each of the hub's folders (POST /2.0/collaborations).
   Hub access does not grant file access, so this step is required.
8. Make steps 6-7 safe to re-run: when Box reports that the collaborator already exists
   (Box returns 409 with error code conflict; also accept user_already_collaborator), print that access already exists and continue.
9. Write portal-config.json with campusHubId and a services array (slug, title, description, hubId) each time a hub ID is known,
   keeping IDs from the previous run for hubs not processed yet, so a run that fails partway does not create duplicate hubs next time.

The portal must:
1. Read portal-config.json at startup and serve two pages from shared HTML templates in templates/ (home.html and service.html),
   filling {{PLACEHOLDER}} values with HTML-escaped strings.
2. Home page (GET /): list the services with links to /services/<slug>, and include the Box AI Chat button script:
   a script tag with src from BOX_CHAT_BUTTON_SCRIPT, data-hub-id set to the campus hub ID,
   data-custom-box-domain set to BOX_EMBED_DOMAIN, and data-button-text 'Ask the campus'.
3. Service page (GET /services/<slug>, 404 for unknown slugs): show the title, description, and a Sources list built from
   the hub items (GET /2.0/hub_items). Link file and folder items to https://<BOX_EMBED_DOMAIN>/<type>/<id>; show other items as plain text.
   Cache each hub's sources in memory for five minutes.
4. On the service page, embed the chat widget as an iframe with src https://<BOX_EMBED_DOMAIN>/ai-chat?hubId=<hub id>&showCloseButton=true,
   width 400, height 600, and allow 'local-network-access *; clipboard-read *; clipboard-write *'. Do NOT add a sharedLink parameter.
5. In the service page script, listen for window message events. Ignore events whose source is not the iframe's contentWindow.
   Do NOT compare event.origin to BOX_EMBED_DOMAIN: Box can serve the chat from the enterprise's custom domain, such as yourcompany.app.box.com.
   When event.data.type is BOX_AI_CHAT_CLOSE, hide the iframe and show an 'Open chat' button that shows the iframe again.
6. Default BOX_EMBED_DOMAIN to app.box.com when it is unset or empty, and listen on PORT (default 3000 when unset or empty; port 5000 conflicts with AirPlay Receiver on macOS).

Include a local test path that needs no public URL: run the seed script, then the provisioning script, then start the portal and open http://localhost:<PORT> (default 3000)
in a browser signed in to Box as the test student. Document the expected output in the README.
In the README, also explain how to skip the seed script and use existing folders and group: share each folder with the app service account as Editor,
set the folder IDs in hubs.config.json, and set STUDENTS_GROUP_ID in .env.

Read configuration from environment variables:
BOX_CLIENT_ID, BOX_CLIENT_SECRET, BOX_ENTERPRISE_ID, HUB_ADMIN_LOGIN, TEST_STUDENT_LOGIN (seed script only),
STUDENTS_GROUP_ID (written by the seed script; leave it empty in .env.example), BOX_EMBED_DOMAIN (optional), BOX_CHAT_BUTTON_SCRIPT, and PORT (optional).

Local dev and troubleshooting (document in README):
- Put the runnable web .csproj at the repository root so `dotnet run` works from the folder the user clones.
- Load `.env` at startup before reading BOX_* variables (parity with python-dotenv). Walk up from Directory.GetCurrentDirectory() to find `.env`. Never override variables already set in the process environment.
- Run seeding and provisioning from the same project with command-line switches (`dotnet run -- seed` and `dotnet run -- provision`), separate from starting the portal with `dotnet run`.
- Listen on http://localhost:<PORT>, defaulting to 3000.
- Create the test project under tests/ with `dotnet new xunit`, and exclude that folder from the root .csproj compile items. Do not add a .sln at the root (two project files there break `dotnet build`); run tests with `dotnet test tests/<Name>.Tests`.

Create a complete runnable project with:
- Configuration/EnvFileLoader.cs (loads .env at startup), a Box client factory, a HubService, seed and provisioning commands, sample-docs/, Program.cs with MapGet("/", ...) and MapGet("/services/{slug}", ...), hubs.config.json, and templates/home.html and templates/service.html mirroring the tutorial
- an idiomatic Minimal APIs layout (MapGet in Program.cs) with a root-level web .csproj; keep the Box client, hub provisioning, and portal config in dedicated classes separate from endpoint mapping
- dependency and run commands
- .env.example and .gitignore files
- focused unit tests for re-run safety (existing hub IDs reused, folders already in the hub skipped, already-exists errors handled,
  and existing seed folders, files, group, and group membership reused)
  and for page rendering (escaping, widget URL, 404 for unknown services), and a README with setup, run, and verify steps
- code that tests can import without side effects: run seeding and provisioning and start the server only when run directly, and let tests replace the Box calls with fakes

Never hard-code credentials. Add concise comments only where the Box-specific behavior is not obvious. Before writing code, summarize the architecture and list the files you will create.
```

Review generated code before using it in production. Never paste Box credentials into your
coding agent.

When the agent finishes, copy `.env.example` to `.env` and fill in your client ID, client secret, enterprise ID, hub admin email, and test student email. Then run the seed script with the command in the generated README. It writes the folder IDs to `hubs.config.json` and the students group ID to `.env`. To use your offices' real folders and group instead, complete [Before you start](#before-you-start), skip the seed script, add your folder IDs to `hubs.config.json`, and set the students group ID in `.env`. Then skip ahead to [Run and verify](#run-and-verify).

Prefer to write the code yourself? See [Build by hand](#build-by-hand) below.

## Build by hand

Use this path if you prefer to write the code yourself, or if you need a reference when the agent drifts. Complete [Before you start](#before-you-start) first, then follow the steps in order. The code is in Python. For other languages, use the [agent path](#build-with-an-agent).

You can also clone a working sample if you prefer to start from running code:

> [card] [Python working sample](https://github.com/box-community/box-campus-ai-assistant)
>
> Clone the provisioning script and Flask portal, add your Box credentials, and run `seed.py` to create sample folders, documents, and the students group.

> [accordion] 1. Set up the development environment
>
> 1. Open your terminal and create a new project directory:
>
> ```bash theme={null}
> mkdir campus-ai-assistant && cd campus-ai-assistant
> ```
>
> 2. Create a virtual environment and install the dependencies:
>
> ```bash theme={null}
> python3 -m venv .venv
> source .venv/bin/activate
> pip install "boxsdk~=10.0" flask python-dotenv
> ```
>
> > [!NOTE]
> >
> > After activation, your terminal prompt displays `(.venv)` at the beginning. Every time you open a new terminal window or tab, re-activate the virtual environment with `source .venv/bin/activate` from the project directory. If you see `ModuleNotFoundError`, the venv is usually not activated.
>
> 3. Create a `.env` file to store your configuration, then add the following content. Replace the placeholder values with your own:
>
> ```bash theme={null}
> BOX_CLIENT_ID=your_client_id
> BOX_CLIENT_SECRET=your_client_secret
> BOX_ENTERPRISE_ID=your_enterprise_id
> STUDENTS_GROUP_ID=your_group_id
> HUB_ADMIN_LOGIN=hub.admin@example.edu
> TEST_STUDENT_LOGIN=student@example.edu
> BOX_EMBED_DOMAIN=app.box.com
> BOX_CHAT_BUTTON_SCRIPT=https://cdn01.boxcdn.net/embeddable-ai-chat-script/2.8.0/box_integrations_ai_chat_button.js
> PORT=3000
> ```
>
> If you use the seed script in step 4, leave `STUDENTS_GROUP_ID` empty. The script fills it in. Set `TEST_STUDENT_LOGIN` to the login of a Box user in your enterprise who is not an admin. Only the seed script uses it. If your enterprise uses a custom Box domain, such as `yourcompany.app.box.com`, set `BOX_EMBED_DOMAIN` to it. `BOX_CHAT_BUTTON_SCRIPT` is the URL of the Box-hosted script for the chat button. To check for a newer version, open any hub in the Box web app, open the menu in the top-right corner, select **Embed**, and on the **Hub AI Chat** tab, select **Chat button**. The `src` value of the `script` tag is the current URL.
>
> > [!WARNING]
> >
> > Never commit `.env` files to version control. Add `.env` to your `.gitignore`.
>
> 4. Create `hubs.config.json`. It describes every hub the portal uses: one per student service and one campus-wide hub that combines all service folders. Replace the folder ID placeholders with your own. If you use the seed script in step 4, leave the placeholders. The script replaces them:
>
> ```json theme={null}
> {
>   "campusHub": {
>     "title": "Campus Assistant",
>     "description": "Answers from every student service."
>   },
>   "services": [
>     {
>       "slug": "admissions",
>       "title": "Admissions",
>       "description": "Application deadlines, requirements, and enrollment steps.",
>       "folderId": "<ADMISSIONS_FOLDER_ID>"
>     },
>     {
>       "slug": "housing",
>       "title": "Housing",
>       "description": "Residence halls, move-in dates, and housing policies.",
>       "folderId": "<HOUSING_FOLDER_ID>"
>     }
>   ]
> }
> ```
>
> To add a student service later, you add an entry here and run the provisioning script again.

> [accordion] 2. Authenticate the Box client
>
> Create the Box client module in your project directory:
>
> ```python box_client.py theme={null}
> # box_client.py
> import os
> from dotenv import load_dotenv
> from box_sdk_gen import (
>     BoxClient,
>     BoxCCGAuth,
>     CCGConfig,
> )
>
> load_dotenv()
>
> def get_box_client() -> BoxClient:
>     config = CCGConfig(
>         client_id=os.getenv("BOX_CLIENT_ID"),
>         client_secret=os.getenv("BOX_CLIENT_SECRET"),
>         enterprise_id=os.getenv("BOX_ENTERPRISE_ID"),
>     )
>     auth = BoxCCGAuth(config=config)
>     return BoxClient(auth=auth)
> ```
>
> > [!TIP]
> >
> > Client Credentials Grant is recommended for server-to-server automations where no end user is present. For other authentication options, see the authentication overview.

> [accordion] 3. Create the hub module
>
> Create the hub module. It lists hub items, creates or reuses a hub, turns on Box AI, adds folders that are not in the hub yet, and grants access. After a hub exists, `configure_hub` adds its folders and grants access to it:
>
> ```python hubs.py theme={null}
> # hubs.py
> from box_sdk_gen import (
>     BoxAPIError,
>     BoxClient,
>     CreateCollaborationAccessibleBy,
>     CreateCollaborationAccessibleByTypeField,
>     CreateCollaborationItem,
>     CreateCollaborationItemTypeField,
>     CreateCollaborationRole,
>     CreateHubCollaborationV2025R0AccessibleBy,
>     CreateHubCollaborationV2025R0Hub,
>     FolderReferenceV2025R0,
>     HubItemOperationV2025R0,
>     HubItemOperationV2025R0ActionField,
> )
>
> ALREADY_COLLABORATOR_CODES = {"user_already_collaborator", "conflict"}
>
> def list_hub_items(client: BoxClient, hub_id: str) -> list:
>     items, marker = [], None
>     while True:
>         page = client.hub_items.get_hub_items_v2025_r0(hub_id, marker=marker)
>         items.extend(page.entries or [])
>         marker = page.next_marker
>         if not marker:
>             return items
>
> def get_or_create_hub(client: BoxClient, hub_id: str | None, title: str, description: str) -> str:
>     if hub_id:
>         hub = client.hubs.get_hub_by_id_v2025_r0(hub_id)
>         print(f"Using existing hub: {hub.title} (ID: {hub.id})")
>     else:
>         hub = client.hubs.create_hub_v2025_r0(title, description=description)
>         print(f"Created hub: {hub.title} (ID: {hub.id})")
>     client.hubs.update_hub_by_id_v2025_r0(hub.id, is_ai_enabled=True)
>     return hub.id
>
> def add_folders_to_hub(client: BoxClient, hub_id: str, folder_ids: list[str]) -> None:
>     existing = {item.id for item in list_hub_items(client, hub_id)}
>     missing = [folder_id for folder_id in folder_ids if folder_id not in existing]
>     if not missing:
>         print(f"Hub {hub_id} already contains folders {', '.join(folder_ids)}")
>         return
>     result = client.hub_items.manage_hub_items_v2025_r0(
>         hub_id,
>         operations=[
>             HubItemOperationV2025R0(
>                 action=HubItemOperationV2025R0ActionField.ADD,
>                 item=FolderReferenceV2025R0(id=folder_id),
>             )
>             for folder_id in missing
>         ],
>     )
>     for operation in result.operations:
>         print(f"Add folder {operation.item.id} to hub {hub_id}: status {operation.status} {operation.error or ''}".rstrip())
>
> def _ignore_existing(error: BoxAPIError, message: str) -> None:
>     if error.response_info.code not in ALREADY_COLLABORATOR_CODES:
>         raise error
>     print(message)
>
> def add_hub_collaborator(
>     client: BoxClient,
>     hub_id: str,
>     accessible_by: CreateHubCollaborationV2025R0AccessibleBy,
>     role: str,
>     label: str,
> ) -> None:
>     try:
>         client.hub_collaborations.create_hub_collaboration_v2025_r0(
>             CreateHubCollaborationV2025R0Hub(id=hub_id),
>             accessible_by,
>             role,
>         )
>         print(f"Added {label} to hub {hub_id} as {role}")
>     except BoxAPIError as error:
>         _ignore_existing(error, f"{label} already has access to hub {hub_id}")
>
> def share_folder_with_group(client: BoxClient, folder_id: str, group_id: str) -> None:
>     try:
>         client.user_collaborations.create_collaboration(
>             CreateCollaborationItem(type=CreateCollaborationItemTypeField.FOLDER, id=folder_id),
>             CreateCollaborationAccessibleBy(type=CreateCollaborationAccessibleByTypeField.GROUP, id=group_id),
>             CreateCollaborationRole.VIEWER,
>         )
>         print(f"Added group {group_id} to folder {folder_id} as viewer")
>     except BoxAPIError as error:
>         _ignore_existing(error, f"Group {group_id} already has access to folder {folder_id}")
>
> def configure_hub(
>     client: BoxClient,
>     hub_id: str,
>     folder_ids: list[str],
>     group_id: str,
>     admin_login: str,
> ) -> None:
>     add_folders_to_hub(client, hub_id, folder_ids)
>     add_hub_collaborator(
>         client,
>         hub_id,
>         CreateHubCollaborationV2025R0AccessibleBy(type="group", id=group_id),
>         "viewer",
>         f"group {group_id}",
>     )
>     add_hub_collaborator(
>         client,
>         hub_id,
>         CreateHubCollaborationV2025R0AccessibleBy(type="user", login=admin_login),
>         "co-owner",
>         admin_login,
>     )
>     for folder_id in folder_ids:
>         share_folder_with_group(client, folder_id, group_id)
> ```
>
> Adding a folder to a hub indexes every file inside it, including subfolders. When content owners add or update files in the folder, the hub picks up the changes, so you do not need to re-run the script for content updates.
>
> > [!NOTE]
> >
> > Hub access does not replace file permissions. If students can open the hub but not the files in it, Box AI has nothing to answer from. That is why `configure_hub` grants the group access to both the hub and its folders.
>
> When a collaboration already exists, Box returns an error instead of creating a duplicate. The module treats that error as success, and it skips folders that are already in the hub, so you can run it again safely.

> [accordion] 4. Create the seed script (optional)
>
> Skip this step if you completed [Before you start](#before-you-start) with your offices' real folders and group. To try the portal with sample content instead, the seed script sets up Box for you as your application's service account. Because the service account owns the folders it creates, you do not need to share them with it. The script:
>
> * Creates a folder for each service in `hubs.config.json`, named after the service's `title`, and uploads the documents from `sample-docs/<slug>/`.
> * Invites the hub admin to each folder as an editor, so they can maintain the content.
> * Creates the `Students` group and adds one test student.
> * Writes the folder IDs to `hubs.config.json` and the group ID to `.env`.
>
> It needs the **Manage users** scope and **App + Enterprise Access** to find the test student by the `TEST_STUDENT_LOGIN` email that you set in `.env` in step 1.
>
> Create a `sample-docs` folder with an `admissions` and a `housing` subfolder, and add a few short documents to each, such as application deadlines and move-in dates. You can also copy the fictional documents from the `sample-docs` folder of the working sample. Then create the seed script:
>
> ```python seed.py theme={null}
> # seed.py
> import json
> import os
> import sys
> from pathlib import Path
> from dotenv import load_dotenv, set_key
> from box_sdk_gen import (
>     BoxAPIError,
>     BoxClient,
>     CreateCollaborationAccessibleBy,
>     CreateCollaborationAccessibleByTypeField,
>     CreateCollaborationItem,
>     CreateCollaborationItemTypeField,
>     CreateCollaborationRole,
>     CreateFolderParent,
>     CreateGroupMembershipGroup,
>     CreateGroupMembershipUser,
>     UploadFileAttributes,
>     UploadFileAttributesParentField,
> )
>
> from box_client import get_box_client
> from hubs import ALREADY_COLLABORATOR_CODES
>
> load_dotenv()
>
> ENV_FILE = Path(".env")
> HUBS_CONFIG = Path("hubs.config.json")
> SAMPLE_DOCS = Path("sample-docs")
> GROUP_NAME = "Students"
>
> def list_folder_items(client: BoxClient, folder_id: str) -> list:
>     items, marker = [], None
>     while True:
>         page = client.folders.get_folder_items(folder_id, usemarker=True, marker=marker, limit=1000)
>         items.extend(page.entries or [])
>         marker = page.next_marker
>         if not marker:
>             return items
>
> def get_or_create_folder(client: BoxClient, name: str) -> str:
>     for item in list_folder_items(client, "0"):
>         if item.type.value == "folder" and item.name == name:
>             print(f"Using existing folder: {name} (ID: {item.id})")
>             return item.id
>     folder = client.folders.create_folder(name, CreateFolderParent(id="0"))
>     print(f"Created folder: {name} (ID: {folder.id})")
>     return folder.id
>
> def upload_sample_docs(client: BoxClient, folder_id: str, docs_dir: Path) -> None:
>     existing = {item.name for item in list_folder_items(client, folder_id)}
>     for path in sorted(docs_dir.glob("*")):
>         if path.name in existing:
>             print(f"File {path.name} already exists in folder {folder_id}")
>             continue
>         with path.open("rb") as file:
>             client.uploads.upload_file(
>                 UploadFileAttributes(name=path.name, parent=UploadFileAttributesParentField(id=folder_id)),
>                 file,
>             )
>         print(f"Uploaded {path.name} to folder {folder_id}")
>
> def share_folder_with_user(client: BoxClient, folder_id: str, login: str) -> None:
>     try:
>         client.user_collaborations.create_collaboration(
>             CreateCollaborationItem(type=CreateCollaborationItemTypeField.FOLDER, id=folder_id),
>             CreateCollaborationAccessibleBy(type=CreateCollaborationAccessibleByTypeField.USER, login=login),
>             CreateCollaborationRole.EDITOR,
>         )
>         print(f"Added {login} to folder {folder_id} as editor")
>     except BoxAPIError as error:
>         if error.response_info.code not in ALREADY_COLLABORATOR_CODES:
>             raise
>         print(f"{login} already has access to folder {folder_id}")
>
> def get_or_create_group(client: BoxClient, name: str) -> str:
>     for group in client.groups.get_groups(filter_term=name).entries or []:
>         if group.name == name:
>             print(f"Using existing group: {name} (ID: {group.id})")
>             return group.id
>     group = client.groups.create_group(name)
>     print(f"Created group: {name} (ID: {group.id})")
>     return group.id
>
> def find_user_id(client: BoxClient, login: str) -> str:
>     for user in client.users.get_users(filter_term=login).entries or []:
>         if user.login.lower() == login.lower():
>             return user.id
>     sys.exit(
>         f"No user with login {login} found. Check TEST_STUDENT_LOGIN in .env, and make sure "
>         "the app has the Manage users scope and App + Enterprise Access. Without them, Box returns no users."
>     )
>
> def add_group_member(client: BoxClient, group_id: str, login: str) -> None:
>     user_id = find_user_id(client, login)
>     members, offset = [], 0
>     while True:
>         page = client.memberships.get_group_memberships(group_id, limit=100, offset=offset)
>         entries = page.entries or []
>         members.extend(membership.user.id for membership in entries if membership.user)
>         if len(entries) < 100:
>             break
>         offset += 100
>     if user_id in members:
>         print(f"{login} is already a member of group {group_id}")
>         return
>     client.memberships.create_group_membership(
>         CreateGroupMembershipUser(id=user_id),
>         CreateGroupMembershipGroup(id=group_id),
>     )
>     print(f"Added {login} to group {group_id}")
>
> def main() -> None:
>     admin_login = os.getenv("HUB_ADMIN_LOGIN")
>     student_login = os.getenv("TEST_STUDENT_LOGIN")
>     if not admin_login or not student_login:
>         sys.exit("Set HUB_ADMIN_LOGIN and TEST_STUDENT_LOGIN in .env before you run seed.py.")
>
>     config = json.loads(HUBS_CONFIG.read_text())
>     client = get_box_client()
>
>     for service in config["services"]:
>         print(f"\n== {service['title']} ==")
>         folder_id = get_or_create_folder(client, service["title"])
>         service["folderId"] = folder_id
>         HUBS_CONFIG.write_text(json.dumps(config, indent=2) + "\n")
>         upload_sample_docs(client, folder_id, SAMPLE_DOCS / service["slug"])
>         share_folder_with_user(client, folder_id, admin_login)
>
>     print(f"\n== {GROUP_NAME} group ==")
>     group_id = get_or_create_group(client, GROUP_NAME)
>     set_key(ENV_FILE, "STUDENTS_GROUP_ID", group_id, quote_mode="never")
>     add_group_member(client, group_id, student_login)
>
>     print(f"\nWrote folder IDs to {HUBS_CONFIG} and STUDENTS_GROUP_ID to {ENV_FILE}.")
>     print("Next, run: python3 provision_hubs.py")
>
> if __name__ == "__main__":
>     main()
> ```
>
> The script finds existing folders, files, and the group by name, so you can run it again safely. You run it in [Run and verify](#run-and-verify).

> [accordion] 5. Create the provisioning script
>
> Create the provisioning script. It reads `hubs.config.json`, provisions one hub per service and the campus-wide hub, and saves each hub ID to `portal-config.json` as soon as the hub exists. On later runs, it reads the IDs from `portal-config.json` and reuses the same hubs, including after a run that fails partway:
>
> ```python provision_hubs.py theme={null}
> # provision_hubs.py
> import json
> import os
> from pathlib import Path
> from dotenv import load_dotenv
>
> from box_client import get_box_client
> from hubs import configure_hub, get_or_create_hub
>
> load_dotenv()
>
> HUBS_CONFIG = Path("hubs.config.json")
> PORTAL_CONFIG = Path("portal-config.json")
>
> def save_portal_config(config: dict, hub_ids: dict[str, str], campus_hub_id: str | None) -> None:
>     services = [
>         {
>             "slug": service["slug"],
>             "title": service["title"],
>             "description": service["description"],
>             "hubId": hub_ids[service["slug"]],
>         }
>         for service in config["services"]
>         if service["slug"] in hub_ids
>     ]
>     PORTAL_CONFIG.write_text(json.dumps({"campusHubId": campus_hub_id, "services": services}, indent=2) + "\n")
>
> def main() -> None:
>     config = json.loads(HUBS_CONFIG.read_text())
>     previous = json.loads(PORTAL_CONFIG.read_text()) if PORTAL_CONFIG.exists() else {}
>     hub_ids = {service["slug"]: service["hubId"] for service in previous.get("services", [])}
>     campus_hub_id = previous.get("campusHubId")
>     group_id = os.getenv("STUDENTS_GROUP_ID")
>     admin_login = os.getenv("HUB_ADMIN_LOGIN")
>
>     client = get_box_client()
>
>     for service in config["services"]:
>         print(f"\n== {service['title']} ==")
>         hub_id = get_or_create_hub(client, hub_ids.get(service["slug"]), service["title"], service["description"])
>         hub_ids[service["slug"]] = hub_id
>         save_portal_config(config, hub_ids, campus_hub_id)
>         configure_hub(client, hub_id, [service["folderId"]], group_id, admin_login)
>
>     campus = config["campusHub"]
>     print(f"\n== {campus['title']} ==")
>     campus_hub_id = get_or_create_hub(client, campus_hub_id, campus["title"], campus["description"])
>     save_portal_config(config, hub_ids, campus_hub_id)
>     configure_hub(
>         client,
>         campus_hub_id,
>         [service["folderId"] for service in config["services"]],
>         group_id,
>         admin_login,
>     )
>
>     print(f"\nWrote {PORTAL_CONFIG} with {len(config['services']) + 1} hubs.")
>
> if __name__ == "__main__":
>     main()
> ```
>
> > [!WARNING]
> >
> > Keep `portal-config.json` after the first run. If you delete it, the next run creates a new set of hubs instead of reusing the existing ones.

> [accordion] 6. Create the portal pages
>
> The portal uses both Box AI Chat embedding modes, one on each of these 2 page templates. Create a `templates` folder in your project directory and add them:
>
> * **Home page:** the chat button. A Box-hosted script adds a floating **Ask the campus** button that opens a chat grounded in the campus-wide hub. Use this mode when the chat is secondary to the page content.
> * **Service page:** the chat widget. An `iframe` displays the chat for the service's hub next to the list of sources. Use this mode when the chat is the main way to use the page.
>
> ```html templates/home.html theme={null}
> <!doctype html>
> <html lang="en">
> <head>
>   <meta charset="utf-8">
>   <title>Campus Assistant</title>
>   <style>
>     body { font-family: system-ui, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; }
>     .services { list-style: none; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 1rem; }
>     .services li { border: 1px solid #ddd; border-radius: 8px; padding: 1rem; }
>   </style>
> </head>
> <body>
>   <h1>Campus Assistant</h1>
>   <p>Choose a student service, or select <strong>Ask the campus</strong> to ask about anything.</p>
>   <ul class="services">
>     {{SERVICE_CARDS}}
>   </ul>
>   <script
>     src="{{CHAT_BUTTON_SCRIPT}}"
>     data-hub-id="{{CAMPUS_HUB_ID}}"
>     data-custom-box-domain="{{EMBED_DOMAIN}}"
>     data-button-text="Ask the campus">
>   </script>
> </body>
> </html>
> ```
>
> ```html templates/service.html theme={null}
> <!doctype html>
> <html lang="en">
> <head>
>   <meta charset="utf-8">
>   <title>{{TITLE}} | Campus Assistant</title>
>   <style>
>     body { font-family: system-ui, sans-serif; max-width: 960px; margin: 2rem auto; padding: 0 1rem; }
>     .layout { display: flex; gap: 2rem; align-items: flex-start; }
>     .sources { flex: 1; }
>   </style>
> </head>
> <body>
>   <a href="/">All services</a>
>   <h1>{{TITLE}}</h1>
>   <p>{{DESCRIPTION}}</p>
>   <div class="layout">
>     <section class="sources">
>       <h2>Sources</h2>
>       <ul>
>         {{SOURCES}}
>       </ul>
>     </section>
>     <section>
>       <button id="open-chat" hidden>Open chat</button>
>       <iframe
>         id="chat"
>         src="{{CHAT_URL}}"
>         width="400"
>         height="600"
>         frameborder="0"
>         allow="local-network-access *; clipboard-read *; clipboard-write *"
>         allowfullscreen>
>       </iframe>
>     </section>
>   </div>
>   <script>
>     const chat = document.getElementById('chat');
>     const openChat = document.getElementById('open-chat');
>
>     window.addEventListener('message', (event) => {
>       if (event.source !== chat.contentWindow) return;
>       if (event.data && event.data.type === 'BOX_AI_CHAT_CLOSE') {
>         chat.hidden = true;
>         openChat.hidden = false;
>       }
>     });
>
>     openChat.addEventListener('click', () => {
>       chat.hidden = false;
>       openChat.hidden = true;
>     });
>   </script>
> </body>
> </html>
> ```
>
> The chat button script reads its settings from the attributes of its own `script` tag. `data-hub-id` is required and selects the hub that the chat answers from. Without it, the chat cannot load. `data-custom-box-domain` sets your Box domain, and `data-button-text` sets the button label. The portal fills in these values from `portal-config.json` and `.env`.
>
> The widget URL includes `showCloseButton=true`, so the chat displays a close button. When a student selects it, the chat sends a `BOX_AI_CHAT_CLOSE` message to the page, and the script hides the chat and displays an **Open chat** button. The script ignores messages that do not come from the chat `iframe`. It checks the sender instead of the domain because Box can serve the chat from your enterprise's custom domain, such as `yourcompany.app.box.com`, even when the `iframe` points to `app.box.com`.
>
> Neither embed passes a `sharedLink` parameter, so the chat works only for hub collaborators. For all parameters, see Box Hubs AI Chat embedding.

> [accordion] 7. Create the portal server
>
> Create the portal server. It fills in the page templates with the hub IDs from `portal-config.json`, and builds each service's source list from the Hubs API. Sources are cached for 5 minutes so that page views do not call Box every time:
>
> ```python portal.py theme={null}
> # portal.py
> import json
> import os
> import time
> from html import escape
> from pathlib import Path
> from dotenv import load_dotenv
> from flask import Flask, abort
>
> from box_client import get_box_client
> from hubs import list_hub_items
>
> load_dotenv()
>
> EMBED_DOMAIN = os.getenv("BOX_EMBED_DOMAIN") or "app.box.com"
> CHAT_BUTTON_SCRIPT = os.getenv("BOX_CHAT_BUTTON_SCRIPT")
> SOURCES_CACHE_SECONDS = 300
> PORTAL = json.loads(Path("portal-config.json").read_text())
> TEMPLATES = Path("templates")
>
> app = Flask(__name__)
> client = get_box_client()
> sources_cache: dict[str, tuple[float, list[dict]]] = {}
>
> def render(template: str, **values: str) -> str:
>     page = (TEMPLATES / template).read_text()
>     for key, value in values.items():
>         page = page.replace("{{" + key + "}}", value)
>     return page
>
> def hub_sources(hub_id: str) -> list[dict]:
>     cached = sources_cache.get(hub_id)
>     if cached and time.monotonic() - cached[0] < SOURCES_CACHE_SECONDS:
>         return cached[1]
>     sources = []
>     for item in list_hub_items(client, hub_id):
>         item_type = item.type.value
>         url = f"https://{EMBED_DOMAIN}/{item_type}/{item.id}" if item_type in ("file", "folder") else None
>         sources.append({"name": item.name, "url": url})
>     sources_cache[hub_id] = (time.monotonic(), sources)
>     return sources
>
> @app.get("/")
> def home():
>     cards = "\n".join(
>         f'<li><a href="/services/{escape(service["slug"])}">{escape(service["title"])}</a>'
>         f'<p>{escape(service["description"])}</p></li>'
>         for service in PORTAL["services"]
>     )
>     return render(
>         "home.html",
>         SERVICE_CARDS=cards,
>         CHAT_BUTTON_SCRIPT=escape(CHAT_BUTTON_SCRIPT),
>         CAMPUS_HUB_ID=escape(PORTAL["campusHubId"]),
>         EMBED_DOMAIN=escape(EMBED_DOMAIN),
>     )
>
> @app.get("/services/<slug>")
> def service(slug: str):
>     service = next((s for s in PORTAL["services"] if s["slug"] == slug), None)
>     if service is None:
>         abort(404)
>     sources = "\n".join(
>         f'<li><a href="{escape(source["url"])}" target="_blank" rel="noopener">{escape(source["name"])}</a></li>'
>         if source["url"]
>         else f"<li>{escape(source['name'])}</li>"
>         for source in hub_sources(service["hubId"])
>     )
>     chat_url = f"https://{EMBED_DOMAIN}/ai-chat?hubId={service['hubId']}&showCloseButton=true"
>     return render(
>         "service.html",
>         TITLE=escape(service["title"]),
>         DESCRIPTION=escape(service["description"]),
>         SOURCES=sources,
>         CHAT_URL=escape(chat_url),
>     )
>
> if __name__ == "__main__":
>     app.run(port=int(os.getenv("PORT", "3000")), debug=True)
> ```
>
> The source links open the files and folders in the Box web app, where Box applies the student's own permissions. The service account reads the hub items for the list, so every student sees the same list.
>
> At this point, your project directory should contain the following files:
>
> ```text theme={null}
> campus-ai-assistant/
> ├── .env
> ├── .venv/
> ├── box_client.py
> ├── hubs.config.json
> ├── hubs.py
> ├── portal.py
> ├── provision_hubs.py
> ├── sample-docs/       # Only if you use the seed script
> ├── seed.py            # Optional
> └── templates/
>     ├── home.html
>     └── service.html
> ```

When you finish scaffolding, continue to [Run and verify](#run-and-verify).

## Run and verify

Create the hubs and check them in Box before you start the portal. If the chat works in Box, any problem you hit later is in the portal.

The commands below are for Build by hand. If you built with an agent, use the matching commands from the generated README.

1. **Run the seed script**, if you created one. Make sure you are in the `campus-ai-assistant` directory, then run:

   ```bash theme={null}
   source .venv/bin/activate
   python3 seed.py
   ```

   You should see each folder, upload, and the group confirmed:

   ```text theme={null}
   == Admissions ==
   Created folder: Admissions (ID: 111111)
   Uploaded admission-requirements.md to folder 111111
   Uploaded application-deadlines.md to folder 111111
   Added hub.admin@example.edu to folder 111111 as editor

   == Housing ==
   Created folder: Housing (ID: 222222)
   Uploaded move-in-dates.md to folder 222222
   Uploaded residence-halls.md to folder 222222
   Added hub.admin@example.edu to folder 222222 as editor

   == Students group ==
   Created group: Students (ID: 333333)
   Added student@example.edu to group 333333

   Wrote folder IDs to hubs.config.json and STUDENTS_GROUP_ID to .env.
   Next, run: python3 provision_hubs.py
   ```

2. **Run the provisioning script:**

   ```bash theme={null}
   source .venv/bin/activate
   python3 provision_hubs.py
   ```

3. **Check the output.** You should see each hub confirmed, followed by the path of the portal configuration:

   ```text theme={null}
   == Admissions ==
   Created hub: Admissions (ID: 1000001)
   Add folder 111111 to hub 1000001: status 200
   Added group 333333 to hub 1000001 as viewer
   Added hub.admin@example.edu to hub 1000001 as co-owner
   Added group 333333 to folder 111111 as viewer

   == Housing ==
   Created hub: Housing (ID: 1000002)
   Add folder 222222 to hub 1000002: status 200
   Added group 333333 to hub 1000002 as viewer
   Added hub.admin@example.edu to hub 1000002 as co-owner
   Added group 333333 to folder 222222 as viewer

   == Campus Assistant ==
   Created hub: Campus Assistant (ID: 1000003)
   Add folder 111111 to hub 1000003: status 200
   Add folder 222222 to hub 1000003: status 200
   Added group 333333 to hub 1000003 as viewer
   Added hub.admin@example.edu to hub 1000003 as co-owner
   Group 333333 already has access to folder 111111
   Group 333333 already has access to folder 222222

   Wrote portal-config.json with 3 hubs.
   ```

   Run the script again. It reuses the hubs from `portal-config.json` and reports that the folders and collaborators already exist, instead of creating new hubs.

4. **Check the hubs in Box.** Sign in to Box as the hub admin, select **Hubs** in the left sidebar, and open **Admissions**, **Housing**, and **Campus Assistant**. Each hub lists its folders as hub content.

   > [!WARNING]
   >
   > Wait **a few minutes** for Box to index the files before you test the chat. A newly created hub might return empty or incomplete answers until indexing finishes.

5. **Start the portal:**

   ```bash theme={null}
   python3 portal.py
   ```

6. **Test as a student.** In a browser where you are signed in to Box as a member of the students group, open `http://localhost:3000`. Do not use a private or incognito window, because it does not share your Box session.
   * On the home page, select **Ask the campus** and ask a question that one of your documents answers, such as "When is the move-in date?". Confirm that the answer cites the document.
   * Select **Admissions**. The page lists the Admissions folder under **Sources**, and the chat answers admissions questions.
   * Select the close button in the chat. The chat hides and **Open chat** displays. Select **Open chat** to display the chat again.

## Scaling to production

> [accordion] Add a student service
>
> Create and share the service folder as in [Before you start](#before-you-start), add an entry to `hubs.config.json`, and run the provisioning script. The script creates the new hub, adds the new folder to the campus-wide hub, and updates `portal-config.json`. Restart the portal to display the new service.

> [accordion] Manage access through the group
>
> Neither embed uses a shared link, so only hub collaborators can use the chat. To give a student access, add them to the `Students` group in Box. To remove access, remove them from the group. You do not need to change the portal or re-run the script.

> [accordion] Keep the content curated
>
> Box AI answers only from the files in the service folders. Keep drafts and outdated versions out of them. To review new content before it reaches a hub, see the company brain tutorial.

> [accordion] Deploy the portal
>
> Before you deploy, run the portal on a production server instead of the development server, serve it over HTTPS, and store the values from `.env` in your hosting platform's secrets manager. Keep `portal-config.json` with the deployment so the portal uses the same hubs.

> [accordion] Use the pattern for other portals
>
> The same approach works for any portal that groups knowledge by team, such as an employee intranet with one hub per department or a partner portal with one hub per product line.

## Troubleshooting

> [accordion] ModuleNotFoundError: No module named '...'
>
> Your Python virtual environment is not activated. Run `source .venv/bin/activate` from the project directory before running any `python3` commands. Each new terminal tab needs its own activation.

> [accordion] invalid\_client: The client credentials are invalid
>
> Check your `.env` file:
>
> * Verify `BOX_CLIENT_ID` and `BOX_CLIENT_SECRET` match the values in **Developer Console** > **Configuration**.
> * Confirm `BOX_ENTERPRISE_ID` is your enterprise ID (found in **Admin Console** > **Account & Billing**, or **Developer Console** > icon in the top-right > **Copy Enterprise ID**).
> * Ensure your app is authorized in the Admin Console.
> * Make sure the app type is Client Credentials Grant.

> [accordion] 404 Not Found on a service folder
>
> The service account does not have access to a service folder. Invite the service account email (found in Developer Console > your app > **Configuration** > **App Details** sidebar) as a collaborator with the **Editor** role on every folder in `hubs.config.json`.

> [accordion] 404 not\_found when adding the group to a hub
>
> If the script adds the folders but fails with `404 not_found` when it adds the students group to a hub, check that `STUDENTS_GROUP_ID` is the `id` from the list groups response. If the error persists, contact Box Support with the `box-request-id` value from the error response.
>
> As a temporary workaround, invite each member of the group to the hubs as a viewer instead. In Python, add these functions to `hubs.py` after `add_hub_collaborator`. When Box returns `not_found` for the group, `add_hub_group_viewer` invites each member of the group:
>
> ```python hubs.py theme={null}
> def list_group_member_ids(client: BoxClient, group_id: str) -> list[str]:
>     user_ids, offset = [], 0
>     while True:
>         page = client.memberships.get_group_memberships(group_id, limit=100, offset=offset)
>         entries = page.entries or []
>         user_ids.extend(membership.user.id for membership in entries if membership.user)
>         if len(entries) < 100:
>             return user_ids
>         offset += 100
>
> def add_hub_group_viewer(client: BoxClient, hub_id: str, group_id: str) -> None:
>     group = CreateHubCollaborationV2025R0AccessibleBy(type="group", id=group_id)
>     try:
>         add_hub_collaborator(client, hub_id, group, "viewer", f"group {group_id}")
>     except BoxAPIError as error:
>         if error.response_info.code != "not_found":
>             raise
>         user_ids = list_group_member_ids(client, group_id)
>         print(f"Group {group_id} returned not_found on hub {hub_id}. Inviting {len(user_ids)} members as viewers")
>         for user_id in user_ids:
>             add_hub_collaborator(
>                 client,
>                 hub_id,
>                 CreateHubCollaborationV2025R0AccessibleBy(type="user", id=user_id),
>                 "viewer",
>                 f"user {user_id}",
>             )
> ```
>
> Then, in `configure_hub`, replace the `add_hub_collaborator` call for the group with:
>
> ```python hubs.py theme={null}
> add_hub_group_viewer(client, hub_id, group_id)
> ```
>
> Run the provisioning script again. Students get hub access individually, so when a student joins the group, run the script again to invite them to the hubs. The group still controls access to the service folders.

> [accordion] 403 insufficient\_scope when adding the group to a folder
>
> Your application is missing the **Manage groups** scope, which the script needs to invite the students group to the service folders. In the Developer Console, enable **Manage groups** on the **Configuration** tab, save the changes, and make sure the app is re-authorized. See Re-authorization on changes. Then run the script again. It reuses the hubs it already created.

> [accordion] No such file or directory: 'portal-config.json'
>
> The portal reads hub IDs from `portal-config.json`, which the provisioning script writes. Run the provisioning script first, and start the portal from the project directory.

> [accordion] The agent tried to create the folders or group
>
> The seed script creates the folders and the students group when you run it. The agent must not create them while it builds the project. Re-paste the prompt with the prerequisites block intact, or follow [Build by hand](#build-by-hand).

> [accordion] The seed script cannot find the test student
>
> If the seed script stops because no user matches the test student login, check the login email in `.env`. Then, on the **Configuration** tab of your app in the Developer Console, make sure the **Manage users** scope is enabled and the **App Access Level** is **App + Enterprise Access**. Without either setting, Box returns an empty list of users instead of an error. Save the changes, and re-authorize the app. See Re-authorization on changes. Then run the seed script again. It reuses the folders, files, and group it already created.

> [accordion] The Ask the campus button does not display or the chat does not load
>
> * Make sure `BOX_CHAT_BUTTON_SCRIPT` in `.env` contains only the script URL, not the whole `script` tag. The home page template adds the `data-hub-id` and `data-custom-box-domain` attributes.
> * If your enterprise uses a custom Box domain, such as `yourcompany.app.box.com`, set `BOX_EMBED_DOMAIN` to it and restart the portal.
> * If the chat displays "Oops! We can't seem to find what you're looking for", the browser is not signed in to Box as a hub collaborator. Confirm that the student is signed in to Box in the same browser, not in a private or incognito window, and is a member of the students group. Without a shared link, the chat loads only for hub collaborators.

> [accordion] The chat returns empty or generic answers
>
> * Wait a few minutes after creating the hubs. Indexing is not instantaneous.
> * Confirm the student is a member of the students group, and that the group has access to the folders as well as the hubs.
> * Make sure your documents contain text. Scanned PDFs without OCR are not searchable.

## Next steps

> [card] Build your company brain
>
> Review new content with Box AI before you publish it to a hub.

> [card] Box Embed
>
> See every embed option for hubs, folders, files, and Hubs AI Chat.

**RELATED GUIDES**
