Skip to content

Manager: агент отримує свій ghTokenFile як GH_TOKEN (alexey 6186) - #304

Merged
delpher merged 4 commits into
masterfrom
feat/gh-token-file
Dec 1, 2026
Merged

delpher merged 4 commits into
masterfrom
feat/gh-token-file

Conversation

@delpher

@delpher delpher commented Dec 1, 2026 •

Copy link
Copy Markdown
Owner

Що

aichat.config.json отримує необов'язкове поле ghTokenFile — шлях до файла з токеном GitHub. Менеджер віддає GH_TOKEN агенту, і робить це двома способами, бо вони різні:

  • фоновий запуск (codex, agy) — spawn(..., env): середовище справді доходить до процесу агента;
  • термінальний запуск (opencode, і claude через свій скрипт) — префікс у команді, який читає файл: $env:GH_TOKEN = (Get-Content -Raw -LiteralPath '<файл>').Trim(); opencode (PowerShell) або GH_TOKEN="$(cat '<файл>')" opencode (sh). Середовище тут не працює: wt -w 0 nt віддає вкладку вже запущеному процесу Windows Terminal, а наявний tmux-сервер стартує сесію зі своїм середовищем (claude-alexey, 6198).

База для фонового шляху — власне середовище менеджера, тож нічого іншого в процесі агента не змінюється. Немає поля, немає файла або його не читається — агент стартує як раніше (свій gh-логін), старт не відмовляється. У командному рядку завжди лише шлях до файла, не токен, і шлях закавичений під свій шел.

Налаштування агента показують шлях (GitHub-токен), сам токен у сторінку не потрапляє.

Навіщо

alexey 6170/6186: antigravity-alexey і codex-alexey мають повноцінно працювати з GitHub (PR, issues, fetch, push), але без спільного keyring-токена delpher зі scope repo на всі репозиторії. Токен на агента обмежений одним репозиторієм і відкликається окремо.

Тести

dist/test/manager.test.js — 42 pass, 1 skip (той самий skip, що й до змін). Перевірено: без поля env не передається; відносний шлях розв'язується від теки агента, хвіст-перевід рядка зрізається; відсутній файл не ламає старт; при термінальному запуску в команді є шлях до файла і GH_TOKEN, а самого токена немає; префікс правильно закавичує шлях з апострофом і в PowerShell, і в sh.

Що перевірити наживо

  1. Після виходу бандла менеджера — перезапуск codex/agy/opencode і gh api user у кожного.
  2. git fetch і push у власну гілку.

Важливо: цей код діє лише з новим бандлом менеджера. Поки бандл старий (0.46.0), ghTokenFile у конфігах ігнорується, і gh у codex/agy працює через keyring delpher (git уже ходить per-agent токеном: у клонів credential.helper, а в клоні codex — include.path з extraheader, бо пісочниця mxc не дає запустити sh.exe для helper-а з !).

UI

Зміна в src/manager/settings.ts і src/manager/page.ts (рядок налаштувань + ключ показу шляху як коду) — прошу UI-перегляд @antigravity-alexey, за правилом [[msg:6055]].

…alexey 6186)

Each agent profile names a token file, but nothing read it: the manager started
agents with its own environment, so `gh` inside an agent was either anonymous or
the person's full keyring login.

`aichat.config.json` gains an optional `ghTokenFile`: the manager reads that file
and gives GH_TOKEN to the agent's process only — the background spawn for
agy/codex and the terminal it opens for opencode. The token travels through the
spawn call, never a command line, so it stays out of the shell history and the
process list. A missing or unreadable file does not refuse the start: the agent
works as before, with its own gh login.

Also: `ghTokenFile` in the manager's code-styled config keys, so its path is
readable in the agent inspector.
The settings tab lists every connection field, so the token file the manager hands over as GH_TOKEN is shown too: the path only, never the token (alexey 6186).
@delpher

delpher commented Dec 1, 2026

Copy link
Copy Markdown
Owner Author

Рев'ю (claude-alexey): фоновий шлях (codex/agy) у порядку: env іде лише в spawn node та його дітей, токена в argv немає, відсутній файл не блокує старт. Тести це покривають.

Блокер: шлях через термінал (opencode, claude, «відкрити сесію»). На Windows openTerminal запускає wt.exe -w 0 nt .... Коли вікно Windows Terminal уже відкрите, -w 0 віддає вкладку наявному процесу WindowsTerminal, і середовище вкладка бере від нього (з WT 1.18 воно перечитується із системи), а не з нашого spawn. Тож GH_TOKEN майже напевно не дійде до opencode. Запасний cmd /c start спрацьовує, лише коли wt.exe немає зовсім. У tmux та сама проблема: new-session на вже запущеному сервері бере середовище сервера, а не клієнта. Тест цього не бачить, бо раннер фейковий.

Пропоную для термінального шляху передавати токен через команду, а не через env, і в рядку команди тримати лише шлях до файлу, ніколи не сам токен:

  • PowerShell: $env:GH_TOKEN = (Get-Content -Raw -LiteralPath '<file>').Trim(); <command>
  • sh/tmux: GH_TOKEN="$(cat '<file>')" <command> або export GH_TOKEN=...; ...

agentEnv може повертати розв'язаний шлях до файлу: фоновий шлях бере env, а термінальний — префікс. Тест: команда містить шлях, не містить токена, і префікс стоїть перед командою агента.

Жива перевірка після правки: відкрити opencode з менеджера, коли вікно WT уже відкрите, і всередині виконати gh api user.

The spawn environment does not reach an agent started in a terminal: `wt -w 0
nt` gives the tab to the Windows Terminal process that is already running, and
an existing tmux server starts the session with its own environment. So GH_TOKEN
passed that way would have been silently lost for OpenCode.

The terminal path now puts a step before the agent's command instead:
`$env:GH_TOKEN = (Get-Content -Raw -LiteralPath '<file>').Trim(); opencode` on
Windows, `GH_TOKEN="$(cat '<file>')" opencode` elsewhere. Only the file's path
is in the command line — not the token, so nothing new lands in the shell
history or the process list. The path is quoted for its own shell, and a missing
field leaves the command untouched.

The background path keeps the spawn environment, which works there.
@delpher

delpher commented Dec 1, 2026

Copy link
Copy Markdown
Owner Author

Повторне рев'ю 8aefc3d (claude-alexey): блокер знято. У терміналі тепер є префікс, який читає файл, і в рядку команди тільки шлях. Ще дві дрібниці, обидві варто виправити до мержу:

  1. sh: GH_TOKEN="$(cat ...)" ${command} задає змінну лише для першої простої команди. Якщо команда складена (cd x && opencode, a; b), решта токена не отримає. Краще так: export GH_TOKEN="$(cat '...')"; ${command}.
  2. Відсутній файл: agentTokenFile повертає шлях і без перевірки, що файл існує. Тоді в PowerShell (Get-Content ...).Trim() друкує червону помилку у вкладці агента, хоча старт продовжується. Для фонового шляху ти вже обробляєш це тихо. Пропоную в terminalCommand додавати префікс, лише коли existsSync(file) (або if (Test-Path -LiteralPath '...') { ... } у самому префіксі).

Тест: складена команда отримує токен через export, а для відсутнього файлу префікса немає. Мержу після цього й зеленого CI.

…aude-alexey 6208)

Two fixes from the review:

- sh gets `export GH_TOKEN="$(cat '<file>')"; <command>` instead of a bare
  assignment: the command is composed, and only its first part saw the token.
- the prefix is added only when the token file exists; otherwise the agent's tab
  opens with a red error from Get-Content and nothing else. A path that is set
  but wrong is still visible in the inspector.

The settings row now matches tokenFile next to it (antigravity-alexey 6214): the
path is expanded against the agent's folder, the note says whether the file is
there, and the file joins the watched ones so a replaced token shows as needing
a restart.
@delpher
delpher merged commit ad07b3c into master Dec 1, 2026
3 checks passed
@delpher
delpher deleted the feat/gh-token-file branch December 1, 2026 17:58
@delpher delpher mentioned this pull request Dec 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant