@flinbein/pappai-runner-codex 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,14 +1,14 @@
1
1
  # @flinbein/pappai-runner-codex
2
2
 
3
- Внешний раннер для [pappai](https://github.com/flinbein/pappai). Он передаёт события и вызовы методов в Codex CLI через `app-server`. Одноразовый исполнитель открывает временный thread на одно задание. Постоянный исполнитель последовательно выполняет ходы в одном thread и восстанавливает историю после остановки процесса.
3
+ This external runner delivers [pappai](https://github.com/flinbein/pappai) events and method calls to the Codex CLI through `app-server`. A one-shot executor creates an ephemeral thread for a single assignment. A persistent executor processes turns sequentially in one thread and resumes it after a process restart.
4
4
 
5
- ## Установка
5
+ ## Installation
6
6
 
7
- Нужны контроллер pappai с поддержкой PROFILE и административной конфигурации раннера, Linux x86_64 с рабочим bubblewrap, Node.js 24.2+ и нативная musl-сборка Codex CLI. Совместимость проверяется с `0.170.0`. Установите CLI отдельно на постоянный том. Путь `codexExecutablePath` должен вести к самому исполняемому файлу.
7
+ The runner requires a pappai controller that supports PROFILE nodes and administrator-supplied runner configuration, Linux x86_64 with working bubblewrap, Node.js 24.2+, and the native musl distribution of the Codex CLI. Compatibility tests use Codex `0.170.0`. Install the CLI separately on a persistent volume. Set `codexExecutablePath` to the executable itself.
8
8
 
9
- 1. Смонтируйте постоянный приватный том в `/run/pappai/private`. Выделите в нём каталоги `profiles` и `state` с правами `0700` владельца процесса pappai. Храните код раннера и CLI в каталогах, доступных для записи только администратору.
10
- 2. Установите пакет, например `npm install --prefix /run/pappai/private/runners --omit=dev @flinbein/pappai-runner-codex`.
11
- 3. Через `call` вызовите `$.runners.add` на workspace (`node: "~"`) с приведёнными ниже данными. При регистрации также можно передать поле `settingsSchema` с содержимым [схемы настроек APP](examples/settings-schema.json).
9
+ 1. Mount a persistent private volume at `/run/pappai/private`. Create `profiles` and `state` directories there, owned by the pappai process user with mode `0700`. Only the administrator should have write access to the runner code and CLI installation.
10
+ 2. Install the package, for example with `npm install --prefix /run/pappai/private/runners --omit=dev @flinbein/pappai-runner-codex`.
11
+ 3. Use `call` to invoke `$.runners.add` on the workspace (`node: "~"`) with the following arguments. To have the controller validate APP settings, supply the [settings schema](examples/settings-schema.json) in the `settingsSchema` field when registering the runner.
12
12
 
13
13
  ```json
14
14
  {
@@ -22,29 +22,39 @@
22
22
  }
23
23
  ```
24
24
 
25
- ## Первый вызов
25
+ ## Updating an existing registration
26
26
 
27
- 1. На workspace или TEAM вызовите `$.profile.create` с именем и пермитами. Сохраните полученный ID.
28
- 2. Подготовьте `auth.json` штатным входом в Codex CLI и поместите файл в доступный вызывающему каталог. На ноде PROFILE вызовите `codex.setup` с `{"authFile":"/tmp/codex-auth.json"}`. Контроллер читает обычный файл от имени вызывающего. `codex.status({})` возвращает `{"configured":true}` после импорта. `codex.remove({})` удаляет сохранённое подключение.
29
- 3. На workspace или TEAM вызовите `$.app.create` с `name`, `profile`, `permissions` и `source: {"manifest": …}`. В качестве манифеста используйте [одноразовый](examples/oneShot.json) или [постоянный](examples/persistent.json) пример.
30
- 4. На PROFILE вызовите `$.profile.scope.set({"scope":["ID_APP"]})` с настоящим ID созданной APP, затем `$.profile.enable({})`. На APP вызовите `$.app.start({})`.
31
- 5. Вызовите `agent.execute` на APP с `{"input":"Переведи на русский: the build passed"}`. Декларация метода в примере требует строку в ответе. Для своего метода можно указать другую выходную JSON Schema. Раннер проверяет результат перед ответом.
27
+ Find the installed entry point with `$.runners.get({})` on the workspace. Wait for active Codex turns to finish, then use the administrator terminal to install the desired package version under the same npm prefix as the registered entry point. For example, for an entry point under `/run/pappai/private/runners/node_modules/`, use `npm install --prefix /run/pappai/private/runners --omit=dev --ignore-scripts --save-exact @flinbein/pappai-runner-codex@VERSION`. Replace `VERSION` with the release number.
32
28
 
33
- Первые назначения проходят проверку доступа до отправки события в модель. При запуске учётные данные берутся из явно привязанного профиля. Для разных APP с одним профилем создаются раздельные истории. Значение `idleTimeoutMs` постоянной APP позволяет освободить процесс между заданиями.
29
+ Call `$.runners.restart({"name":"codex"})` on the workspace to load the installed package with its saved configuration. Restart affects all active Codex workers. Use the same procedure with the previous package version to roll back.
34
30
 
35
- Поддерживаются API-ключ и импортированная авторизация подписки ChatGPT. Один хост раннера владеет каталогом профилей и координирует обновление токена для всех своих APP. У каждого исполнителя только краткоживущая авторизация подписки. Не подключайте одну копию хранилища профилей к нескольким хостам раннера одновременно. Проверка ротации использует настоящий Codex и локальный тестовый OAuth-сервер.
31
+ ## First call
36
32
 
37
- У постоянной APP можно дополнительно объявить методы `agent.getHistory` и `agent.interrupt` в `features`. История возвращает сообщения пользователя и финальные реплики модели с курсором продолжения. Прерывание адресуется текущему активному ходу и требует обычного разрешения на метод. При отсутствии активного хода контроллер возвращает ошибку. Оба метода работают без вызова модели.
33
+ 1. Call `$.profile.create` on the workspace or a TEAM with a name and permissions. Save the returned ID.
34
+ 2. Sign in with the Codex CLI and place the resulting `auth.json` in a directory the caller can read. Call `codex.setup` on the PROFILE with `{"authFile":"/tmp/codex-auth.json"}`. The controller reads the regular file as the caller. After import, `codex.status({})` returns `{"configured":true}`. Use `codex.remove({})` to remove the stored connection.
35
+ 3. Call `$.app.create` on the workspace or a TEAM with `name`, `profile`, `permissions` and `source.manifest`. Use the [one-shot](examples/oneShot.json) or [persistent](examples/persistent.json) manifest.
36
+ 4. Call `$.profile.scope.set({"scope":["APP_ID"]})` on the PROFILE using the new APP's ID, then call `$.profile.enable({})`. Call `$.app.start({})` on the APP.
37
+ 5. Call `agent.execute` on the APP with `{"input":"Translate into Russian: the build passed"}`. The example method declares a string result. You can declare a different output JSON Schema for your own method. The runner validates the result before replying.
38
38
 
39
- ## Граница первой версии
39
+ The controller checks assignment access before an event reaches the model. Each executor obtains model credentials from its assigned profile at startup. APPs that share a profile keep separate conversation histories. Set `idleTimeoutMs` on a persistent APP to release its process between assignments.
40
40
 
41
- Исполнитель работает в изолированном каталоге. Подключение к модели является служебным каналом. Для операций в pappai модель получает инструменты `pappai_dir`, `pappai_help`, `pappai_call` и `pappai_publish`. Контроллер выполняет их от имени конкретного исполнителя с учётом PROFILE. Shell, файловые инструменты Codex и пользовательские настройки из рабочего каталога отключены. Поля `run.settings` выбирают модель, усилие рассуждения и инструкцию. Административный путь к CLI и хранилищам задают при регистрации раннера.
41
+ The runner supports API keys and imported ChatGPT subscription credentials. A single runner host owns the profiles directory and coordinates token refresh across its APPs. Each subscription worker receives only short-lived credentials. Give each runner host exclusive use of its profile storage. The rotation test uses the native Codex CLI and a local OAuth test server.
42
+
43
+ A persistent APP can also declare `agent.getHistory` and `agent.interrupt` under `features`. History returns user messages and final assistant replies with a pagination cursor. Interrupt targets the active turn and requires permission to call the method. If no turn is active, the controller returns an error. Both methods run without a model call.
44
+
45
+ ## Executor permissions
46
+
47
+ The executor runs in an isolated directory. Its connection to the model is a service channel. For workspace operations, the model receives the `pappai_dir`, `pappai_help`, `pappai_call` and `pappai_publish` tools. The controller authorizes calls as the assigned APP using its effective permissions. The PROFILE supplies the model credentials, and its scope controls which APPs may use them.
48
+
49
+ Workers support Code Mode. For example, `functions.exec` can run `text(await tools.pappai_dir({}))`. Keep the native `bin/codex-code-mode-host` beside `bin/codex` in the trusted CLI distribution. The runner mounts that helper read-only for APP workers. The separate credential refresh process keeps Code Mode disabled. The helper shares the app-server's network namespace. The JavaScript environment exposes the selected tools, and nested pappai calls undergo the usual controller permission checks.
50
+
51
+ Shell, native Codex file tools and user configuration from the working directory are disabled. Use `run.settings` to select the model, reasoning effort and developer instructions. The administrator sets the CLI and storage paths when registering the runner.
42
52
 
43
53
  ## HTTP MCP
44
54
 
45
- На PROFILE вызовите `codex.mcp.set({"name":"tasks","url":"https://tasks.example.org/mcp","bearerFile":"/tmp/tasks-token"})`. Поле `bearerFile` необязательно, файл содержит один bearer-токен. Каждая запись сохраняется целиком. Повторное сохранение без `bearerFile` снимает токен. `codex.mcp.get({})` возвращает URL и признак авторизации. `codex.mcp.delete({"name":"tasks"})` удаляет запись. Изменения применяются при следующем запуске исполнителя. Для немедленного отзыва отключите профиль.
55
+ To configure a shared server, call `codex.mcp.set({"name":"tasks","url":"https://tasks.example.org/mcp","bearerFile":"/tmp/tasks-token"})` on the PROFILE. The optional file contains one bearer token. Each call replaces the entire entry. Omitting `bearerFile` removes any previous token. `codex.mcp.get({})` lists URLs and indicates which entries have credentials. `codex.mcp.delete({"name":"tasks"})` deletes an entry. Changes apply on the next executor launch. Disable the profile to revoke access immediately.
46
56
 
47
- В `run.settings` конкретной APP укажите выбранные серверы. Например, конфигурация ниже подключает общие задачи с авторизацией PROFILE и личный HTTP-сервер APP с открытым доступом. Имена в двух списках должны различаться.
57
+ In the APP's `run.settings`, select shared servers by name under `mcp.profile`, and declare APP-owned HTTP endpoints under `mcp.servers`. This example selects the PROFILE's authenticated task service and an APP-local calendar endpoint that accepts unauthenticated requests.
48
58
 
49
59
  ```json
50
60
  {
@@ -55,12 +65,19 @@
55
65
  }
56
66
  ```
57
67
 
58
- Исполнителю требуется эффективное право `network:true`. При запрете сети раннер убирает HTTP MCP до подключения. Для внешних адресов требуется HTTPS, для локального теста допустим HTTP на loopback. Поля команды, параметры авторизации в URL, OAuth-вход MCP и пользовательские stdio-команды в этой версии недоступны. [Модель MCP и результаты исследований](https://github.com/flinbein/pappai/blob/master/docs/dev/runners/mcp.md)
68
+ | Connection | Effective network permission required at launch |
69
+ |---|---|
70
+ | APP endpoint in `mcp.servers` | The APP allows network access. |
71
+ | Selected endpoint in `mcp.profile` | Both the APP and its assigned PROFILE allow network access for this APP. |
72
+
73
+ The runner omits denied endpoints and their credentials before Codex initializes. Servers enabled together must have distinct names. A suppressed PROFILE entry never supplies credentials to an APP endpoint, even when their names match. Controllers that omit the `profileMcpNetwork` grant can still supply APP endpoints subject to the network permission they dispatch. Upgrade the controller and runner together for the full permission model.
74
+
75
+ External endpoints require HTTPS. Loopback tests may use HTTP on `127.0.0.1` or `[::1]`. URLs cannot include credentials, a query, or a fragment. The runner supports HTTP endpoints only. MCP OAuth login, stdio commands, and raw Codex configuration for managed servers are unsupported. [MCP design and protocol probes](https://github.com/flinbein/pappai/blob/master/docs/dev/runners/mcp.md)
59
76
 
60
- ## Разработка и публикация
77
+ ## Development and publishing
61
78
 
62
- Выполните `npm ci --ignore-scripts` и `npm test`. Для тестов на Linux подготовьте доступный текущему пользователю каталог `/run/pappai/private`. Для проверки с настоящим CLI задайте `PAPPAI_TEST_CODEX_CLI` с абсолютным путём к нативному исполняемому файлу; в Linux для этой проверки требуется bubblewrap. Проверка установленного npm-архива через настоящий контроллер находится в [pappai](https://github.com/flinbein/pappai/blob/master/tests/codex-package.test.ts).
79
+ Run `npm ci --ignore-scripts` and `npm test`. On Linux, create `/run/pappai/private` with write access for the test user. To run tests with the real CLI, set `PAPPAI_TEST_CODEX_CLI` to the absolute path of the native executable. Linux integration tests require bubblewrap. The [controller acceptance test](https://github.com/flinbein/pappai/blob/master/tests/codex-package.test.ts) exercises the installed npm archive through pappai.
63
80
 
64
- Каждый push в `master` запускает тесты и публикацию в публичный npm registry. Номер patch увеличивается на номер запуска workflow минус один. Повторный запуск уже опубликованной сборки сверяет контрольную сумму архива. Первый запуск серии `0.1` использует версию `0.1.0`.
81
+ Each push to `master` runs the tests and publishes to the public npm registry. The workflow adds its run number minus one to the base patch version. Re-running a published build verifies the archive checksum. The first build of the `0.1` series uses version `0.1.0`.
65
82
 
66
- В настройках npm Trusted Publisher укажите GitHub, владельца `flinbein`, репозиторий `pappai-runner-codex`, файл `publish.yml` и разрешите прямую публикацию (`npm publish`). Для создания пакета владелец scope может один раз опубликовать проверенный архив локально, войдя через браузер, или сохранить краткосрочный granular token как Actions secret `NPM_TOKEN`. После настройки OIDC секрет можно удалить. [Настройка в npm](https://docs.npmjs.com/trusted-publishers/)
83
+ In npm Trusted Publisher settings, choose GitHub, owner `flinbein`, repository `pappai-runner-codex`, and workflow `publish.yml`. Enable direct publication (`npm publish`). To create the package, the scope owner can publish the verified archive locally after signing in through the browser, or supply a short-lived granular token through the Actions secret `NPM_TOKEN`. Remove the secret once OIDC publishing is configured. [npm trusted publisher setup](https://docs.npmjs.com/trusted-publishers/)
@@ -2,11 +2,11 @@
2
2
  "run": {
3
3
  "type": "codex",
4
4
  "settings": {
5
- "developerInstructions": "Выполни поручение из data.input. Ответь на языке пользователя.",
5
+ "developerInstructions": "Complete the task in data.input. Reply in the user's language.",
6
6
  "features": {
7
7
  "agent.execute": {
8
8
  "type": "method",
9
- "description": "Выполнить текстовое поручение",
9
+ "description": "Complete a text assignment",
10
10
  "version": "1",
11
11
  "schema": {
12
12
  "input": {
@@ -2,11 +2,11 @@
2
2
  "run": {
3
3
  "type": "codex",
4
4
  "settings": {
5
- "developerInstructions": "Выполни поручение из data.input. Ответь на языке пользователя.",
5
+ "developerInstructions": "Complete the task in data.input. Reply in the user's language.",
6
6
  "features": {
7
7
  "agent.execute": {
8
8
  "type": "method",
9
- "description": "Выполнить текстовое поручение",
9
+ "description": "Complete a text assignment",
10
10
  "version": "1",
11
11
  "schema": {
12
12
  "input": {
@@ -30,7 +30,7 @@
30
30
  "agent.getHistory": {
31
31
  "type": "method",
32
32
  "version": "1",
33
- "description": "Вернуть страницу истории диалога",
33
+ "description": "Return a page of conversation history",
34
34
  "schema": {
35
35
  "input": {
36
36
  "type": "object",
@@ -51,7 +51,7 @@
51
51
  "agent.interrupt": {
52
52
  "type": "method",
53
53
  "version": "1",
54
- "description": "Прервать активный ход",
54
+ "description": "Interrupt the active turn",
55
55
  "schema": {
56
56
  "input": {
57
57
  "type": "object",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flinbein/pappai-runner-codex",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Codex app-server runner for pappai",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
package/src/http-mcp.mjs CHANGED
@@ -84,7 +84,8 @@ export async function resolveHttpMcp(config,job) {
84
84
  const mcp=job.settings?.mcp;
85
85
  if (!mcp || (job.sandbox!==null && job.sandbox?.network!==true)) return denied;
86
86
  keys(mcp,['profile','servers']);
87
- const selected=mcp.profile ?? [];
87
+ // Older controllers omit this grant. Ignore denied selections before reading profile storage.
88
+ const selected=job.profileMcpNetwork===true ? (mcp.profile ?? []) : [];
88
89
  if (!Array.isArray(selected) || selected.length>64) throw Error('Invalid MCP profile selection');
89
90
  const local=mcp.servers ?? {};
90
91
  if (!local || typeof local!=='object' || Array.isArray(local) || Object.keys(local).length+selected.length>64) throw Error('Invalid MCP servers');
package/src/policy.mjs CHANGED
@@ -35,7 +35,7 @@ async function privateDir(path) {
35
35
  return path;
36
36
  }
37
37
 
38
- function configToml(modelBaseUrl) {
38
+ function configToml(modelBaseUrl, codeMode) {
39
39
  const lines = [
40
40
  'approval_policy="never"', 'default_permissions="pappai"', 'web_search="disabled"',
41
41
  'cli_auth_credentials_store="file"', 'mcp_oauth_credentials_store="file"',
@@ -54,7 +54,8 @@ function configToml(modelBaseUrl) {
54
54
  return [...lines,
55
55
  '[permissions.pappai.filesystem]', '"/work"="read"', '"/state"="deny"', '"/proc"="deny"',
56
56
  '[permissions.pappai.network]', 'enabled=false',
57
- '[features]', ...['apps','browser_use','browser_use_external','code_mode','code_mode_host',
57
+ '[features]', `code_mode=${codeMode}`, `code_mode_host=${codeMode}`,
58
+ ...['apps','browser_use','browser_use_external',
58
59
  'computer_use','goals','hooks','image_generation','in_app_browser','memories','multi_agent_v2',
59
60
  'plugins','remote_plugin','shell_snapshot','shell_tool','skill_search','unified_exec','view_image',
60
61
  'workspace_dependencies'].map(key => `${key}=false`),
@@ -68,19 +69,20 @@ function configToml(modelBaseUrl) {
68
69
  async function namespace(config, state, profileOwner, mcp) {
69
70
  const binary = await canonicalFile(config.codexExecutablePath, 'Codex executable');
70
71
  const bwrap = await canonicalFile(join(dirname(dirname(binary)), 'codex-resources', 'bwrap'), 'bundled Codex bubblewrap');
72
+ const codeModeHost = profileOwner ? null : await canonicalFile(join(dirname(binary), 'codex-code-mode-host'), 'bundled Codex Code Mode host');
71
73
  const mounts = (await readFile('/proc/self/mountinfo', 'utf8')).trim().split('\n').map(line => {
72
74
  const fields = line.split(' ');
73
75
  const target = fields[4].replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
74
76
  return {target, readonly:fields[5].split(',').includes('ro')};
75
77
  });
76
- if (![binary,bwrap].every(path => protectedBinary(path,mounts))) {
78
+ if (![binary,bwrap,...(codeModeHost ? [codeModeHost] : [])].every(path => protectedBinary(path,mounts))) {
77
79
  throw Error('Codex distribution must be on a read-only mount or below /run/pappai/private');
78
80
  }
79
81
  if (typeof config.stateDir !== 'string' || !config.stateDir.startsWith('/run/pappai/private/')) {
80
82
  throw new Error('Runner state must be below /run/pappai/private');
81
83
  }
82
84
  const root = await privateDir(config.stateDir);
83
- const toml = configToml(config.modelBaseUrl);
85
+ const toml = configToml(config.modelBaseUrl, codeModeHost !== null);
84
86
  const run = await mkdtemp(join(root, 'run-'));
85
87
  const cleanup = () => rm(run, { recursive: true, force: true });
86
88
  try {
@@ -96,6 +98,7 @@ async function namespace(config, state, profileOwner, mcp) {
96
98
  '--die-with-parent', '--new-session', '--dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp',
97
99
  '--dir', work, '--tmpfs', '/state', '--dir', home, '--dir', '/state/home', '--ro-bind', binary, cliPath,
98
100
  '--ro-bind', bwrap, '/opt/codex/bin/bwrap'];
101
+ if (codeModeHost) args.push('--ro-bind', codeModeHost, '/opt/codex/bin/codex-code-mode-host');
99
102
  if (profileOwner) args.push('--bind', dirname(profileOwner.authPath), home);
100
103
  args.push('--ro-bind', configFile, home + '/config.toml', '--ro-bind', requirements, '/etc/codex/requirements.toml');
101
104
  for (const path of ['/etc/resolv.conf','/etc/hosts','/etc/ssl/certs/ca-certificates.crt']) {