@flinbein/pappai-runner-codex 0.0.0-stage → 0.1.4
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 +65 -2
- package/examples/oneShot.json +38 -0
- package/examples/persistent.json +69 -0
- package/examples/settings-schema.json +33 -0
- package/package.json +28 -4
- package/src/client.mjs +204 -0
- package/src/host.mjs +303 -0
- package/src/http-mcp.mjs +109 -0
- package/src/index.mjs +21 -0
- package/src/policy.mjs +150 -0
- package/src/profile.mjs +124 -0
- package/src/session-auth.mjs +71 -0
- package/src/tools.mjs +15 -0
package/README.md
CHANGED
|
@@ -1,3 +1,66 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @flinbein/pappai-runner-codex
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Внешний раннер для [pappai](https://github.com/flinbein/pappai). Он передаёт события и вызовы методов в Codex CLI через `app-server`. Одноразовый исполнитель открывает временный thread на одно задание. Постоянный исполнитель последовательно выполняет ходы в одном thread и восстанавливает историю после остановки процесса.
|
|
4
|
+
|
|
5
|
+
## Установка
|
|
6
|
+
|
|
7
|
+
Нужны контроллер pappai с поддержкой PROFILE и административной конфигурации раннера, Linux x86_64 с рабочим bubblewrap, Node.js 24.2+ и нативная musl-сборка Codex CLI. Совместимость проверяется с `0.170.0`. Установите CLI отдельно на постоянный том. Путь `codexExecutablePath` должен вести к самому исполняемому файлу.
|
|
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).
|
|
12
|
+
|
|
13
|
+
```json
|
|
14
|
+
{
|
|
15
|
+
"name": "codex",
|
|
16
|
+
"entrypoint": "/run/pappai/private/runners/node_modules/@flinbein/pappai-runner-codex/src/index.mjs",
|
|
17
|
+
"config": {
|
|
18
|
+
"codexExecutablePath": "/run/pappai/private/tools/codex/0.170.0/bin/codex",
|
|
19
|
+
"profilesDir": "/run/pappai/private/profiles",
|
|
20
|
+
"stateDir": "/run/pappai/private/state"
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Первый вызов
|
|
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. Раннер проверяет результат перед ответом.
|
|
32
|
+
|
|
33
|
+
Первые назначения проходят проверку доступа до отправки события в модель. При запуске учётные данные берутся из явно привязанного профиля. Для разных APP с одним профилем создаются раздельные истории. Значение `idleTimeoutMs` постоянной APP позволяет освободить процесс между заданиями.
|
|
34
|
+
|
|
35
|
+
Поддерживаются API-ключ и импортированная авторизация подписки ChatGPT. Один хост раннера владеет каталогом профилей и координирует обновление токена для всех своих APP. У каждого исполнителя только краткоживущая авторизация подписки. Не подключайте одну копию хранилища профилей к нескольким хостам раннера одновременно. Проверка ротации использует настоящий Codex и локальный тестовый OAuth-сервер.
|
|
36
|
+
|
|
37
|
+
У постоянной APP можно дополнительно объявить методы `agent.getHistory` и `agent.interrupt` в `features`. История возвращает сообщения пользователя и финальные реплики модели с курсором продолжения. Прерывание адресуется текущему активному ходу и требует обычного разрешения на метод. При отсутствии активного хода контроллер возвращает ошибку. Оба метода работают без вызова модели.
|
|
38
|
+
|
|
39
|
+
## Граница первой версии
|
|
40
|
+
|
|
41
|
+
Исполнитель работает в изолированном каталоге. Подключение к модели является служебным каналом. Для операций в pappai модель получает инструменты `pappai_dir`, `pappai_help`, `pappai_call` и `pappai_publish`. Контроллер выполняет их от имени конкретного исполнителя с учётом PROFILE. Shell, файловые инструменты Codex и пользовательские настройки из рабочего каталога отключены. Поля `run.settings` выбирают модель, усилие рассуждения и инструкцию. Административный путь к CLI и хранилищам задают при регистрации раннера.
|
|
42
|
+
|
|
43
|
+
## HTTP MCP
|
|
44
|
+
|
|
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"})` удаляет запись. Изменения применяются при следующем запуске исполнителя. Для немедленного отзыва отключите профиль.
|
|
46
|
+
|
|
47
|
+
В `run.settings` конкретной APP укажите выбранные серверы. Например, конфигурация ниже подключает общие задачи с авторизацией PROFILE и личный HTTP-сервер APP с открытым доступом. Имена в двух списках должны различаться.
|
|
48
|
+
|
|
49
|
+
```json
|
|
50
|
+
{
|
|
51
|
+
"mcp": {
|
|
52
|
+
"profile": ["tasks"],
|
|
53
|
+
"servers": { "calendar": { "url": "https://calendar.example.org/mcp" } }
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
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)
|
|
59
|
+
|
|
60
|
+
## Разработка и публикация
|
|
61
|
+
|
|
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).
|
|
63
|
+
|
|
64
|
+
Каждый push в `master` запускает тесты и публикацию в публичный npm registry. Номер patch увеличивается на номер запуска workflow минус один. Повторный запуск уже опубликованной сборки сверяет контрольную сумму архива. Первый запуск серии `0.1` использует версию `0.1.0`.
|
|
65
|
+
|
|
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/)
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"run": {
|
|
3
|
+
"type": "codex",
|
|
4
|
+
"settings": {
|
|
5
|
+
"developerInstructions": "Выполни поручение из data.input. Ответь на языке пользователя.",
|
|
6
|
+
"features": {
|
|
7
|
+
"agent.execute": {
|
|
8
|
+
"type": "method",
|
|
9
|
+
"description": "Выполнить текстовое поручение",
|
|
10
|
+
"version": "1",
|
|
11
|
+
"schema": {
|
|
12
|
+
"input": {
|
|
13
|
+
"type": "object",
|
|
14
|
+
"properties": {
|
|
15
|
+
"input": {
|
|
16
|
+
"type": "string",
|
|
17
|
+
"minLength": 1
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"required": [
|
|
21
|
+
"input"
|
|
22
|
+
],
|
|
23
|
+
"additionalProperties": false
|
|
24
|
+
},
|
|
25
|
+
"output": {
|
|
26
|
+
"type": "string"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"executors": {
|
|
34
|
+
"mode": "oneShot",
|
|
35
|
+
"poolSize": 2,
|
|
36
|
+
"maxLifetimeMs": 120000
|
|
37
|
+
}
|
|
38
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"run": {
|
|
3
|
+
"type": "codex",
|
|
4
|
+
"settings": {
|
|
5
|
+
"developerInstructions": "Выполни поручение из data.input. Ответь на языке пользователя.",
|
|
6
|
+
"features": {
|
|
7
|
+
"agent.execute": {
|
|
8
|
+
"type": "method",
|
|
9
|
+
"description": "Выполнить текстовое поручение",
|
|
10
|
+
"version": "1",
|
|
11
|
+
"schema": {
|
|
12
|
+
"input": {
|
|
13
|
+
"type": "object",
|
|
14
|
+
"properties": {
|
|
15
|
+
"input": {
|
|
16
|
+
"type": "string",
|
|
17
|
+
"minLength": 1
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"required": [
|
|
21
|
+
"input"
|
|
22
|
+
],
|
|
23
|
+
"additionalProperties": false
|
|
24
|
+
},
|
|
25
|
+
"output": {
|
|
26
|
+
"type": "string"
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"agent.getHistory": {
|
|
31
|
+
"type": "method",
|
|
32
|
+
"version": "1",
|
|
33
|
+
"description": "Вернуть страницу истории диалога",
|
|
34
|
+
"schema": {
|
|
35
|
+
"input": {
|
|
36
|
+
"type": "object",
|
|
37
|
+
"properties": {
|
|
38
|
+
"cursor": {
|
|
39
|
+
"type": "string"
|
|
40
|
+
},
|
|
41
|
+
"limit": {
|
|
42
|
+
"type": "integer",
|
|
43
|
+
"minimum": 1,
|
|
44
|
+
"maximum": 20
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"additionalProperties": false
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
"agent.interrupt": {
|
|
52
|
+
"type": "method",
|
|
53
|
+
"version": "1",
|
|
54
|
+
"description": "Прервать активный ход",
|
|
55
|
+
"schema": {
|
|
56
|
+
"input": {
|
|
57
|
+
"type": "object",
|
|
58
|
+
"additionalProperties": false
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
},
|
|
65
|
+
"executors": {
|
|
66
|
+
"mode": "persistent",
|
|
67
|
+
"idleTimeoutMs": 300000
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"type": "object",
|
|
3
|
+
"additionalProperties": false,
|
|
4
|
+
"properties": {
|
|
5
|
+
"model": {
|
|
6
|
+
"type": "string",
|
|
7
|
+
"minLength": 1,
|
|
8
|
+
"maxLength": 128
|
|
9
|
+
},
|
|
10
|
+
"effort": {
|
|
11
|
+
"enum": [
|
|
12
|
+
"none",
|
|
13
|
+
"minimal",
|
|
14
|
+
"low",
|
|
15
|
+
"medium",
|
|
16
|
+
"high",
|
|
17
|
+
"xhigh"
|
|
18
|
+
]
|
|
19
|
+
},
|
|
20
|
+
"developerInstructions": { "type": "string" },
|
|
21
|
+
"mcp": {
|
|
22
|
+
"type": "object",
|
|
23
|
+
"additionalProperties": false,
|
|
24
|
+
"properties": {
|
|
25
|
+
"profile": {"type":"array","maxItems":64,"uniqueItems":true,"items":{"type":"string","pattern":"^[a-z][a-z0-9_-]{0,47}$"}},
|
|
26
|
+
"servers": {
|
|
27
|
+
"type":"object","maxProperties":64,"propertyNames":{"pattern":"^[a-z][a-z0-9_-]{0,47}$"},
|
|
28
|
+
"additionalProperties":{"type":"object","additionalProperties":false,"required":["url"],"properties":{"url":{"type":"string","maxLength":2048}}}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flinbein/pappai-runner-codex",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.4",
|
|
4
|
+
"description": "Codex app-server runner for pappai",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.mjs",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=24.2.0"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src/",
|
|
12
|
+
"examples/",
|
|
13
|
+
"README.md"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"test": "node --test test/*.test.mjs"
|
|
17
|
+
},
|
|
18
|
+
"dependencies": {
|
|
19
|
+
"ajv": "^8.17.1",
|
|
20
|
+
"ajv-formats": "^3.0.1"
|
|
21
|
+
},
|
|
22
|
+
"publishConfig": {
|
|
23
|
+
"access": "public",
|
|
24
|
+
"registry": "https://registry.npmjs.org/"
|
|
25
|
+
},
|
|
26
|
+
"repository": {
|
|
27
|
+
"type": "git",
|
|
28
|
+
"url": "git+https://github.com/flinbein/pappai-runner-codex.git"
|
|
29
|
+
}
|
|
30
|
+
}
|
package/src/client.mjs
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
|
|
3
|
+
const maxFrame = 16 * 1024 * 1024
|
|
4
|
+
const rpcTimeout = 30_000
|
|
5
|
+
|
|
6
|
+
// Each app-server belongs to exactly one worker. Only an ended assistant
|
|
7
|
+
// message is a candidate result; deltas and commentary can be incomplete.
|
|
8
|
+
function finalText(item) {
|
|
9
|
+
if (item?.type === 'agentMessage' && (item.phase == null || item.phase === 'final_answer') &&
|
|
10
|
+
typeof item.text === 'string') return item.text
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export class AppServer {
|
|
14
|
+
#child
|
|
15
|
+
#requests = new Map()
|
|
16
|
+
#serial = 0
|
|
17
|
+
#turn
|
|
18
|
+
#failure
|
|
19
|
+
#closing
|
|
20
|
+
#ended = Promise.withResolvers()
|
|
21
|
+
#auth
|
|
22
|
+
#tool
|
|
23
|
+
#serverRequests = new Set()
|
|
24
|
+
#fail
|
|
25
|
+
|
|
26
|
+
constructor({executable,args,cwd,env,sessionAuth},onLoss,onTool) {
|
|
27
|
+
this.#auth = sessionAuth
|
|
28
|
+
this.#tool = onTool
|
|
29
|
+
const child = this.#child = spawn(executable,args,{cwd,env,stdio:'pipe',windowsHide:true})
|
|
30
|
+
const fail = error => {
|
|
31
|
+
if (this.#failure) return
|
|
32
|
+
this.#failure = error
|
|
33
|
+
for (const pending of this.#requests.values()) pending.reject(error)
|
|
34
|
+
this.#requests.clear()
|
|
35
|
+
this.#turn?.done.reject(error)
|
|
36
|
+
this.#turn?.ready.resolve(null)
|
|
37
|
+
if (!this.#closing) onLoss(error)
|
|
38
|
+
}
|
|
39
|
+
this.#fail = fail
|
|
40
|
+
// stderr may contain provider data. Drain it without exposing credentials,
|
|
41
|
+
// prompts or installation paths through a user-visible executor error.
|
|
42
|
+
child.stderr.resume()
|
|
43
|
+
child.stdin.on('error',() => fail(Error('Codex input closed')))
|
|
44
|
+
child.once('error',() => fail(Error('Could not launch Codex app-server')))
|
|
45
|
+
child.once('exit',(code,signal) => {
|
|
46
|
+
fail(Error('Codex app-server exited (' + (signal ?? code) + ')'))
|
|
47
|
+
// An inherited pipe must not retain a worker slot after its process exits.
|
|
48
|
+
const drain = setTimeout(() => { child.stdout.destroy(); child.stderr.destroy() },250)
|
|
49
|
+
child.once('close',() => clearTimeout(drain))
|
|
50
|
+
})
|
|
51
|
+
child.once('close',() => this.#ended.resolve(true))
|
|
52
|
+
let chunks = [], length = 0
|
|
53
|
+
child.stdout.on('data', chunk => {
|
|
54
|
+
if (this.#failure) return
|
|
55
|
+
let start = 0
|
|
56
|
+
for (let i = chunk.indexOf(10); i !== -1; i = chunk.indexOf(10,start)) {
|
|
57
|
+
if (length + i - start > maxFrame) return fail(Error('Codex protocol frame too large'))
|
|
58
|
+
chunks.push(chunk.subarray(start,i))
|
|
59
|
+
try { this.#message(JSON.parse(Buffer.concat(chunks).toString('utf8'))) }
|
|
60
|
+
catch { return fail(Error('Invalid Codex protocol frame')) }
|
|
61
|
+
chunks = []
|
|
62
|
+
length = 0
|
|
63
|
+
start = i + 1
|
|
64
|
+
}
|
|
65
|
+
if (start < chunk.length) {
|
|
66
|
+
length += chunk.length - start
|
|
67
|
+
if (length > maxFrame) return fail(Error('Codex protocol frame too large'))
|
|
68
|
+
chunks.push(chunk.subarray(start))
|
|
69
|
+
}
|
|
70
|
+
})
|
|
71
|
+
child.stdout.once('end',() => fail(Error('Codex output closed')))
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
#send(value) {
|
|
75
|
+
if (this.#failure) throw this.#failure
|
|
76
|
+
if (this.#closing) throw Error('Codex app-server is closing')
|
|
77
|
+
this.#child.stdin.write(JSON.stringify(value) + '\n')
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
#message(message) {
|
|
81
|
+
if (message.id !== undefined) {
|
|
82
|
+
if (message.method) {
|
|
83
|
+
if (this.#serverRequests.size >= 32 || this.#serverRequests.has(message.id)) throw Error('Too many open server requests')
|
|
84
|
+
this.#serverRequests.add(message.id)
|
|
85
|
+
void this.#serverRequest(message)
|
|
86
|
+
return
|
|
87
|
+
}
|
|
88
|
+
const request = this.#requests.get(message.id)
|
|
89
|
+
if (!request) return
|
|
90
|
+
this.#requests.delete(message.id)
|
|
91
|
+
if (message.error) request.reject(Error('Codex rejected ' + request.method))
|
|
92
|
+
else request.resolve(message.result)
|
|
93
|
+
return
|
|
94
|
+
}
|
|
95
|
+
const active = this.#turn
|
|
96
|
+
const {method,params} = message
|
|
97
|
+
if (!active || params?.threadId !== active.threadId ||
|
|
98
|
+
(method !== 'item/completed' && method !== 'turn/completed')) return
|
|
99
|
+
const id = method === 'turn/completed' ? params.turn.id : params.turnId
|
|
100
|
+
if (typeof id !== 'string' || (active.id && active.id !== id)) return
|
|
101
|
+
if (!active.records.has(id) && active.records.size >= 8) throw Error('Too many simultaneous turns')
|
|
102
|
+
const record = active.records.get(id) ?? {}
|
|
103
|
+
active.records.set(id,record)
|
|
104
|
+
if (method === 'item/completed') record.text = finalText(params.item) ?? record.text
|
|
105
|
+
else {
|
|
106
|
+
record.status = params.turn.status
|
|
107
|
+
for (const item of params.turn.items ?? []) record.text = finalText(item) ?? record.text
|
|
108
|
+
if (active.id === id) active.done.resolve(record)
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async #serverRequest({id,method,params}) {
|
|
113
|
+
let response
|
|
114
|
+
try {
|
|
115
|
+
if (method === 'account/chatgptAuthTokens/refresh' && this.#auth) {
|
|
116
|
+
response = {result:await this.#auth.refreshTokens(params)}
|
|
117
|
+
} else if (method === 'item/tool/call' && this.#tool) {
|
|
118
|
+
const active = this.#turn
|
|
119
|
+
if (!active || params.threadId !== active.threadId || typeof params.callId !== 'string' || !params.callId ||
|
|
120
|
+
typeof params.turnId !== 'string' || params.turnId !== await active.ready.promise || active !== this.#turn ||
|
|
121
|
+
active.records.get(params.turnId)?.status || active.callIds.has(params.callId) || active.callIds.size >= 1024)
|
|
122
|
+
throw Error('Tool request has no active assignment')
|
|
123
|
+
active.callIds.add(params.callId)
|
|
124
|
+
response = {result:await this.#tool(params)}
|
|
125
|
+
} else response = {error:{code:-32601,message:'Unsupported server request'}}
|
|
126
|
+
} catch {
|
|
127
|
+
response = {error:{code:-32000,message:'Runner rejected the server request'}}
|
|
128
|
+
} finally {
|
|
129
|
+
this.#serverRequests.delete(id)
|
|
130
|
+
}
|
|
131
|
+
if (!this.#failure && !this.#closing) this.#send({id,...response})
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async rpc(method,params) {
|
|
135
|
+
const id = ++this.#serial
|
|
136
|
+
const pending = Promise.withResolvers()
|
|
137
|
+
this.#requests.set(id,{...pending,method})
|
|
138
|
+
const timer = setTimeout(() => pending.reject(Error('Codex did not acknowledge ' + method)),rpcTimeout)
|
|
139
|
+
try {
|
|
140
|
+
this.#send({id,method,params})
|
|
141
|
+
return await pending.promise
|
|
142
|
+
} finally {
|
|
143
|
+
clearTimeout(timer)
|
|
144
|
+
this.#requests.delete(id)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async initialize({readAccount=true}={}) {
|
|
149
|
+
const {userAgent} = await this.rpc('initialize',{
|
|
150
|
+
clientInfo:{name:'pappai_runner_codex',version:'1'},capabilities:{experimentalApi:true},
|
|
151
|
+
})
|
|
152
|
+
if (typeof userAgent !== 'string' || !/\/0\.170\.0(?:\s|$)/.test(userAgent)) throw Error('Codex CLI 0.170.0 is required')
|
|
153
|
+
this.#send({method:'initialized'})
|
|
154
|
+
if (!readAccount) return
|
|
155
|
+
if (this.#auth) {
|
|
156
|
+
const login = await this.#auth.getTokens()
|
|
157
|
+
await this.rpc('account/login/start',login)
|
|
158
|
+
}
|
|
159
|
+
const {account} = await this.rpc('account/read',{})
|
|
160
|
+
if (!account) throw Error('Codex profile has no authenticated account')
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async turn(params,onStarted) {
|
|
164
|
+
const active = this.#turn = {threadId:params.threadId,records:new Map(),done:Promise.withResolvers(),
|
|
165
|
+
ready:Promise.withResolvers(),callIds:new Set()}
|
|
166
|
+
// Loss can occur before the turn/start acknowledgement.
|
|
167
|
+
active.done.promise.catch(() => {})
|
|
168
|
+
try {
|
|
169
|
+
const {turn} = await this.rpc('turn/start',params)
|
|
170
|
+
if (typeof turn?.id !== 'string' || !turn.id) throw Error('Codex returned no turn ID')
|
|
171
|
+
active.id = turn.id
|
|
172
|
+
await onStarted()
|
|
173
|
+
active.ready.resolve(turn.id)
|
|
174
|
+
const early = active.records.get(turn.id)
|
|
175
|
+
return early?.status ? early : await active.done.promise
|
|
176
|
+
} finally {
|
|
177
|
+
active.ready.resolve(null)
|
|
178
|
+
this.#turn = undefined
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async interrupt() {
|
|
183
|
+
const active = this.#turn
|
|
184
|
+
if (!active || !await active.ready.promise || active !== this.#turn || active.records.get(active.id)?.status)
|
|
185
|
+
throw Error('No active Codex turn')
|
|
186
|
+
active.interrupting ??= this.rpc('turn/interrupt',{threadId:active.threadId,turnId:active.id})
|
|
187
|
+
await active.interrupting
|
|
188
|
+
return {interrupted:true}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
close() {
|
|
192
|
+
if (this.#closing) return this.#closing
|
|
193
|
+
const kill = setTimeout(() => this.#child.kill('SIGKILL'),1000)
|
|
194
|
+
const deadline = setTimeout(() => {
|
|
195
|
+
this.#fail(Error('Codex executor stop could not be confirmed'))
|
|
196
|
+
for (const pipe of this.#child.stdio) pipe?.destroy()
|
|
197
|
+
this.#child.unref()
|
|
198
|
+
this.#ended.resolve(false)
|
|
199
|
+
},3000)
|
|
200
|
+
this.#closing = this.#ended.promise.finally(() => { clearTimeout(kill); clearTimeout(deadline) })
|
|
201
|
+
this.#child.stdin.end()
|
|
202
|
+
return this.#closing
|
|
203
|
+
}
|
|
204
|
+
}
|
package/src/host.mjs
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
|
3
|
+
import Ajv2020 from 'ajv/dist/2020.js'
|
|
4
|
+
import addFormats from 'ajv-formats'
|
|
5
|
+
import { AppServer } from './client.mjs'
|
|
6
|
+
import { dynamicTools, toolMethods } from './tools.mjs'
|
|
7
|
+
|
|
8
|
+
const ajv = new Ajv2020({strict:true,addUsedSchema:false,ownProperties:true})
|
|
9
|
+
addFormats(ajv)
|
|
10
|
+
|
|
11
|
+
async function savedThread(file) {
|
|
12
|
+
let value
|
|
13
|
+
try { value = await readFile(file,'utf8') }
|
|
14
|
+
catch (error) { if (error.code === 'ENOENT') return; throw Error('Cannot read APP thread state') }
|
|
15
|
+
try {
|
|
16
|
+
const {threadId} = JSON.parse(value)
|
|
17
|
+
if (typeof threadId === 'string' && threadId) return threadId
|
|
18
|
+
} catch { /* refuse to replace corrupt history */ }
|
|
19
|
+
throw Error('Invalid APP thread state')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function saveThread(file,threadId) {
|
|
23
|
+
const tmp = file + '.' + randomUUID()
|
|
24
|
+
try {
|
|
25
|
+
await writeFile(tmp,JSON.stringify({threadId}),{flag:'wx',mode:0o600})
|
|
26
|
+
await rename(tmp,file)
|
|
27
|
+
} catch {
|
|
28
|
+
throw Error('Cannot persist APP thread state')
|
|
29
|
+
} finally {
|
|
30
|
+
await unlink(tmp).catch(error => { if (error.code !== 'ENOENT') throw Error('Cannot clean up APP thread state') })
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function turnRequest(threadId,item,effort) {
|
|
35
|
+
const record = {from:item.from,...(item.method ? {method:item.method} : {event:item.event,subscription:item.subscription}),data:item.data}
|
|
36
|
+
const input = [{type:'text',text:JSON.stringify(record)}]
|
|
37
|
+
const params = {threadId,input,environments:[],...(effort && {effort})}
|
|
38
|
+
let validate
|
|
39
|
+
if (item.method && item.outputSchema !== undefined) {
|
|
40
|
+
const schema = item.outputSchema
|
|
41
|
+
validate = ajv.compile(schema)
|
|
42
|
+
if (typeof schema === 'object') ajv.removeSchema(schema)
|
|
43
|
+
// A root-relative reference must keep its original schema resource. Give
|
|
44
|
+
// these schemas to the model as instructions and validate locally.
|
|
45
|
+
if (/"\$(?:ref|dynamicRef|id|schema)"\s*:/.test(JSON.stringify(schema))) {
|
|
46
|
+
input.push({type:'text',text:'Return only a JSON object with a result property matching this JSON Schema: ' + JSON.stringify(schema)})
|
|
47
|
+
} else {
|
|
48
|
+
params.outputSchema = {type:'object',properties:{result:schema},required:['result'],additionalProperties:false}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return {params,validate}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function resultOf(text,validate) {
|
|
55
|
+
if (typeof text !== 'string' || !text.trim()) throw Error('Codex completed without a final assistant message')
|
|
56
|
+
if (Buffer.byteLength(text) > 1024 * 1024) throw Error('Codex result exceeds 1 MiB')
|
|
57
|
+
if (!validate) return text
|
|
58
|
+
let value
|
|
59
|
+
try { value = JSON.parse(text) } catch { throw Error('Codex returned malformed JSON') }
|
|
60
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || !Object.hasOwn(value,'result') ||
|
|
61
|
+
Object.keys(value).length !== 1 || !validate(value.result)) throw Error('Codex result does not match the output schema')
|
|
62
|
+
return value.result
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function history(client,threadId,data,hasTurns) {
|
|
66
|
+
const {limit=20,cursor}=data ?? {}
|
|
67
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 20 || (cursor != null &&
|
|
68
|
+
(typeof cursor !== 'string' || cursor.length > 4096))) throw Error('Invalid history page')
|
|
69
|
+
if (!hasTurns) return {messages:[],nextCursor:null}
|
|
70
|
+
const page = await client.rpc('thread/items/list',{threadId,limit,cursor,sortDirection:'asc'})
|
|
71
|
+
const messages = []
|
|
72
|
+
for (const {item} of page.data) {
|
|
73
|
+
const user = item.type === 'userMessage'
|
|
74
|
+
// The runner writes the pappai record as the first text block. Subsequent
|
|
75
|
+
// blocks can contain runner instructions for models with structured output.
|
|
76
|
+
let text = user && item.content[0]?.type === 'text' ? item.content[0].text : undefined
|
|
77
|
+
if (item.type === 'agentMessage' && (item.phase == null || item.phase === 'final_answer')) text = item.text
|
|
78
|
+
if (typeof text !== 'string') continue
|
|
79
|
+
const bytes = Buffer.from(text), truncated = bytes.length > 8192
|
|
80
|
+
messages.push({role:user ? 'user' : 'assistant',text:truncated ? bytes.subarray(0,8192).toString('utf8') : text,
|
|
81
|
+
...(truncated && {truncated:true})})
|
|
82
|
+
}
|
|
83
|
+
return {messages,nextCursor:page.nextCursor ?? null}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
class Worker {
|
|
87
|
+
#incoming = Promise.withResolvers()
|
|
88
|
+
#queued = false
|
|
89
|
+
#active
|
|
90
|
+
#cancelled
|
|
91
|
+
#cancelTimer
|
|
92
|
+
#client
|
|
93
|
+
#stopping = false
|
|
94
|
+
#issue
|
|
95
|
+
#started = false
|
|
96
|
+
#outgoing = new Map()
|
|
97
|
+
|
|
98
|
+
constructor(job,emit) {
|
|
99
|
+
this.job = job
|
|
100
|
+
this.emit = (type,fields={}) => emit(type,{appId:job.appId,id:job.id,...fields})
|
|
101
|
+
this.persistent = job.mode === 'persistent'
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
deliver(item) {
|
|
105
|
+
if (this.#stopping) return
|
|
106
|
+
if (this.#queued || this.#active) return this.stop('Concurrent delivery to Codex worker')
|
|
107
|
+
this.#queued = true
|
|
108
|
+
this.#incoming.resolve(item)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
cancel(id) {
|
|
112
|
+
if (this.#stopping) return
|
|
113
|
+
if (id !== this.#active?.id && (this.#started || id !== this.job.id) && !this.#queued) return
|
|
114
|
+
this.#cancelled = id
|
|
115
|
+
// The controller aborts outstanding executor requests on worker exit.
|
|
116
|
+
if (this.#active?.id === id && this.#outgoing.size) return this.stop()
|
|
117
|
+
if (this.#active?.id === id && this.#active.method !== 'agent.getHistory') this.#interrupt()
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async #tool({tool,namespace,arguments:params}) {
|
|
121
|
+
const method = toolMethods.get(tool)
|
|
122
|
+
if (!method || namespace != null || this.#stopping || !this.#active || this.#cancelled === this.#active.id ||
|
|
123
|
+
this.#outgoing.size >= 32 || !params || typeof params !== 'object' || Array.isArray(params) ||
|
|
124
|
+
Buffer.byteLength(JSON.stringify(params)) > 64 * 1024) throw Error('Invalid workspace tool request')
|
|
125
|
+
const id = randomUUID()
|
|
126
|
+
const pending = Promise.withResolvers()
|
|
127
|
+
this.#outgoing.set(id,pending)
|
|
128
|
+
try {
|
|
129
|
+
this.emit('request',{id,workerId:this.job.id,method,params})
|
|
130
|
+
const response = await pending.promise
|
|
131
|
+
const error = Object.hasOwn(response,'error')
|
|
132
|
+
const text = error ? String(response.error?.message ?? 'Workspace request failed') : JSON.stringify(response.result ?? null)
|
|
133
|
+
if (Buffer.byteLength(text) > 1024 * 1024) return {success:false,contentItems:[{type:'inputText',text:'Workspace result exceeds 1 MiB'}]}
|
|
134
|
+
return {success:!error,contentItems:[{type:'inputText',text}]}
|
|
135
|
+
} finally {
|
|
136
|
+
this.#outgoing.delete(id)
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
respond(id,response) {
|
|
141
|
+
this.#outgoing.get(id)?.resolve(response)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async interrupt(id) {
|
|
145
|
+
const fields = {id,workerId:this.job.id}
|
|
146
|
+
try {
|
|
147
|
+
if (!this.persistent || this.#stopping || !this.#client) throw Error('No active Codex turn')
|
|
148
|
+
const result = await this.#client.interrupt()
|
|
149
|
+
if (!this.#stopping) this.emit('reply',{...fields,result})
|
|
150
|
+
} catch (error) {
|
|
151
|
+
if (!this.#stopping) this.emit('reply',{...fields,error:{message:error.message}})
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
#interrupt() {
|
|
156
|
+
if (!this.#cancelTimer) this.#cancelTimer = setTimeout(() => this.stop('Codex turn cancellation timed out'),5000)
|
|
157
|
+
this.#client?.interrupt().catch(error => {
|
|
158
|
+
if (error.message !== 'No active Codex turn') this.stop('Could not interrupt Codex turn')
|
|
159
|
+
})
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
stop(issue) {
|
|
163
|
+
if (issue) this.#issue ??= issue
|
|
164
|
+
if (this.#stopping) return
|
|
165
|
+
this.#stopping = true
|
|
166
|
+
this.#incoming.resolve(null)
|
|
167
|
+
for (const pending of this.#outgoing.values()) pending.reject(Error('Worker stopped'))
|
|
168
|
+
this.#client?.close()
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async run(config,prepare) {
|
|
172
|
+
let spec, permanent = false
|
|
173
|
+
const lifetime = this.job.maxLifetimeMs && setTimeout(() => this.stop('Codex executor lifetime exceeded'),this.job.maxLifetimeMs)
|
|
174
|
+
try {
|
|
175
|
+
if (!this.job.profileId) throw Error('Codex requires an assigned profile')
|
|
176
|
+
spec = await prepare(config,this.job)
|
|
177
|
+
if (this.#stopping) return
|
|
178
|
+
const client = this.#client = new AppServer(spec,error => this.stop(error.message),params => this.#tool(params))
|
|
179
|
+
await client.initialize()
|
|
180
|
+
if (this.#stopping) return
|
|
181
|
+
const settings = this.job.settings
|
|
182
|
+
const params = {
|
|
183
|
+
...(settings.model && {model:settings.model}),
|
|
184
|
+
...(settings.developerInstructions && {developerInstructions:settings.developerInstructions}),
|
|
185
|
+
...spec.threadParams,
|
|
186
|
+
}
|
|
187
|
+
let stored = this.persistent && await savedThread(spec.stateFile)
|
|
188
|
+
const response = stored
|
|
189
|
+
? await client.rpc('thread/resume',{...params,threadId:stored,excludeTurns:true})
|
|
190
|
+
: await client.rpc('thread/start',{...params,ephemeral:!this.persistent,dynamicTools})
|
|
191
|
+
const threadId = response.thread?.id
|
|
192
|
+
if (!threadId || typeof threadId !== 'string' || (stored && threadId !== stored)) throw Error('Invalid Codex thread identity')
|
|
193
|
+
if (this.#stopping) return
|
|
194
|
+
this.#started = true
|
|
195
|
+
this.emit('started')
|
|
196
|
+
if (!this.job.holdFirst) this.deliver(this.job)
|
|
197
|
+
while (!this.#stopping) {
|
|
198
|
+
const item = await this.#incoming.promise
|
|
199
|
+
this.#incoming = Promise.withResolvers()
|
|
200
|
+
this.#queued = false
|
|
201
|
+
if (this.#stopping) break
|
|
202
|
+
this.#active = item
|
|
203
|
+
const fields = {id:item.id,workerId:this.job.id}
|
|
204
|
+
try {
|
|
205
|
+
if (item.method === 'agent.getHistory') {
|
|
206
|
+
if (!this.persistent) throw Error('History requires a persistent Codex APP')
|
|
207
|
+
const result = await history(client,threadId,item.data,stored)
|
|
208
|
+
if (!this.#stopping && this.#cancelled !== item.id) this.emit('reply',{...fields,result})
|
|
209
|
+
} else if (item.method === 'agent.interrupt') {
|
|
210
|
+
throw Error('No active Codex turn')
|
|
211
|
+
} else if (this.#cancelled !== item.id) {
|
|
212
|
+
const {params:request,validate} = turnRequest(threadId,item,settings.effort)
|
|
213
|
+
const record = await client.turn(request,async () => {
|
|
214
|
+
if (this.#cancelled === item.id) this.#interrupt()
|
|
215
|
+
if (this.persistent && !stored) {
|
|
216
|
+
await saveThread(spec.stateFile,threadId)
|
|
217
|
+
stored = threadId
|
|
218
|
+
}
|
|
219
|
+
}).catch(error => {
|
|
220
|
+
// An absent acknowledgement leaves the remote turn's state unknown.
|
|
221
|
+
// Retiring the worker prevents a second turn entering that thread.
|
|
222
|
+
this.stop(error.message)
|
|
223
|
+
throw error
|
|
224
|
+
})
|
|
225
|
+
if (this.#cancelled !== item.id && !this.#stopping) {
|
|
226
|
+
if (record.status !== 'completed') throw Error('Codex turn did not complete (' + record.status + ')')
|
|
227
|
+
if (item.method) this.emit('reply',{...fields,result:resultOf(record.text,validate)})
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (!this.#stopping && this.#cancelled !== item.id) {
|
|
232
|
+
if (!item.method) throw error
|
|
233
|
+
this.emit('reply',{...fields,error:{message:error.message}})
|
|
234
|
+
}
|
|
235
|
+
} finally {
|
|
236
|
+
clearTimeout(this.#cancelTimer)
|
|
237
|
+
this.#cancelTimer = undefined
|
|
238
|
+
this.#active = undefined
|
|
239
|
+
this.#cancelled = undefined
|
|
240
|
+
}
|
|
241
|
+
if (!this.#stopping) this.emit('written',fields)
|
|
242
|
+
if (this.#outgoing.size) this.stop()
|
|
243
|
+
if (!this.persistent) break
|
|
244
|
+
}
|
|
245
|
+
} catch (error) {
|
|
246
|
+
if (!this.#stopping) this.#issue ??= error.code ? 'Codex worker storage or runtime unavailable' : error.message
|
|
247
|
+
permanent = !this.#started && !this.#stopping
|
|
248
|
+
} finally {
|
|
249
|
+
clearTimeout(lifetime)
|
|
250
|
+
this.#stopping = true
|
|
251
|
+
const stopped = await this.#client?.close()
|
|
252
|
+
if (stopped === false) this.#issue = 'Codex executor stop could not be confirmed'
|
|
253
|
+
else {
|
|
254
|
+
try { await spec?.cleanup() } catch { this.#issue ??= 'Codex worker cleanup failed' }
|
|
255
|
+
}
|
|
256
|
+
this.emit('exit',{...(this.#issue && {issue:this.#issue}),...(!this.#started && this.#issue && {startFailed:true}),
|
|
257
|
+
...(permanent && {permanent:true}),...(stopped === false && {stopFailed:true})})
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export class RunnerHost {
|
|
263
|
+
#workers = new Map()
|
|
264
|
+
#closing = false
|
|
265
|
+
|
|
266
|
+
constructor(config,prepare,emit) {
|
|
267
|
+
this.config = config
|
|
268
|
+
this.prepare = prepare
|
|
269
|
+
this.emit = emit
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
receive(message) {
|
|
273
|
+
const {type,job,id} = message
|
|
274
|
+
if (type === 'dispatch') {
|
|
275
|
+
const conflict = job.mode === 'persistent' && [...this.#workers.values()].some(w => w.persistent && w.job.appId === job.appId)
|
|
276
|
+
if (this.#closing || this.#workers.has(job.id) || conflict) {
|
|
277
|
+
this.emit('exit',{appId:job.appId,id:job.id,startFailed:true,issue:'Codex worker already active or closing'})
|
|
278
|
+
return
|
|
279
|
+
}
|
|
280
|
+
const worker = new Worker(job,this.emit)
|
|
281
|
+
this.#workers.set(job.id,worker)
|
|
282
|
+
worker.done = worker.run(this.config,this.prepare).finally(() => this.#workers.delete(job.id))
|
|
283
|
+
return
|
|
284
|
+
}
|
|
285
|
+
const worker = this.#workers.get(id)
|
|
286
|
+
if (!worker) return
|
|
287
|
+
if (type === 'deliver') worker.deliver(message.item)
|
|
288
|
+
if (type === 'stop') worker.stop()
|
|
289
|
+
if (type === 'response') worker.respond(message.requestId,message.response)
|
|
290
|
+
if (type === 'notify' && typeof message.notification?.cancelled === 'string') worker.cancel(message.notification.cancelled)
|
|
291
|
+
if (type === 'notify' && typeof message.notification?.interrupt === 'string') void worker.interrupt(message.notification.interrupt)
|
|
292
|
+
if (type === 'reject' && message.message !== 'Call closed') {
|
|
293
|
+
worker.emit('reply',{workerId:id,id:message.callId,error:{message:message.message}})
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async close() {
|
|
298
|
+
this.#closing = true
|
|
299
|
+
const workers = [...this.#workers.values()]
|
|
300
|
+
for (const worker of workers) worker.stop()
|
|
301
|
+
await Promise.all(workers.map(worker => worker.done))
|
|
302
|
+
}
|
|
303
|
+
}
|
package/src/http-mcp.mjs
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { lstat, mkdir, readFile, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { profileDirectory } from './profile.mjs';
|
|
5
|
+
|
|
6
|
+
const denied = {configToml:'', requirementsToml:'[mcp_servers]\n'};
|
|
7
|
+
const keyPattern = /^[a-z][a-z0-9_-]{0,47}$/;
|
|
8
|
+
function validName(name) {
|
|
9
|
+
if (typeof name!=='string' || !keyPattern.test(name) || Object.hasOwn(Object.prototype,name)) throw Error('Invalid MCP name');
|
|
10
|
+
return name;
|
|
11
|
+
}
|
|
12
|
+
function keys(value, allowed) {
|
|
13
|
+
if (!value || typeof value!=='object' || Array.isArray(value) || Object.keys(value).some(k=>!allowed.includes(k)))
|
|
14
|
+
throw Error('Unsupported MCP settings');
|
|
15
|
+
}
|
|
16
|
+
function endpoint(value) {
|
|
17
|
+
if (typeof value!=='string' || value.length>2048) throw Error('Invalid MCP URL');
|
|
18
|
+
const url=new URL(value);
|
|
19
|
+
if (url.username || url.password || url.hash || url.search ||
|
|
20
|
+
!(url.protocol==='https:' || (url.protocol==='http:' && ['127.0.0.1','[::1]'].includes(url.hostname))))
|
|
21
|
+
throw Error('Expected HTTPS or local loopback HTTP MCP URL without credentials, query or fragment');
|
|
22
|
+
return url.href;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function serverDir(config,id,create) {
|
|
26
|
+
const directory=join(await profileDirectory(config,id,create),'mcp');
|
|
27
|
+
if (create) await mkdir(directory,{recursive:true,mode:0o700});
|
|
28
|
+
if (!(await lstat(directory)).isDirectory() || await realpath(directory)!==directory) throw Error('Invalid MCP storage');
|
|
29
|
+
return directory;
|
|
30
|
+
}
|
|
31
|
+
async function stored(directory,name) {
|
|
32
|
+
const path=join(directory,validName(name)+'.json');
|
|
33
|
+
if (!(await lstat(path)).isFile()) throw Error('Invalid MCP storage');
|
|
34
|
+
return JSON.parse(await readFile(path,'utf8'));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export async function mcpMethod(config,id,method,data={},reader) {
|
|
38
|
+
if (method==='mcp.get') {
|
|
39
|
+
keys(data,[]);
|
|
40
|
+
let directory;
|
|
41
|
+
try { directory=await serverDir(config,id,false); } catch (e) { if (e.code==='ENOENT') return {}; throw e; }
|
|
42
|
+
const entries=[];
|
|
43
|
+
for (const file of (await readdir(directory)).sort()) {
|
|
44
|
+
if (!file.endsWith('.json')) continue;
|
|
45
|
+
const name=file.slice(0,-5);
|
|
46
|
+
const item=await stored(directory,name);
|
|
47
|
+
entries.push([name,{url:item.url,authenticated:Boolean(item.bearer)}]);
|
|
48
|
+
}
|
|
49
|
+
return Object.fromEntries(entries);
|
|
50
|
+
}
|
|
51
|
+
if (method==='mcp.delete') {
|
|
52
|
+
keys(data,['name']); validName(data.name);
|
|
53
|
+
try { await rm(join(await serverDir(config,id,false),data.name+'.json'),{force:true}); }
|
|
54
|
+
catch(e) {if(e.code!=='ENOENT') throw e;}
|
|
55
|
+
return {};
|
|
56
|
+
}
|
|
57
|
+
if (method!=='mcp.set') throw Error('Unknown MCP operation');
|
|
58
|
+
keys(data,['name','url','bearerFile']);
|
|
59
|
+
const name=validName(data.name);
|
|
60
|
+
const entry={url:endpoint(data.url)};
|
|
61
|
+
if (Object.hasOwn(data,'bearerFile')) {
|
|
62
|
+
if (typeof data.bearerFile!=='string' || !data.bearerFile.startsWith('/')) throw Error('Expected absolute bearerFile');
|
|
63
|
+
const bytes=await reader(data.bearerFile);
|
|
64
|
+
const value=bytes.toString('utf8').trim();
|
|
65
|
+
if (value.length>8192 || !/^[A-Za-z0-9._~+/=-]+$/.test(value)) throw Error('Invalid bearer token');
|
|
66
|
+
entry.bearer=value;
|
|
67
|
+
}
|
|
68
|
+
const dir=await serverDir(config,id,true);
|
|
69
|
+
const path=join(dir,name+'.json');
|
|
70
|
+
try { await lstat(path); }
|
|
71
|
+
catch(error) {
|
|
72
|
+
if(error.code!=='ENOENT') throw error;
|
|
73
|
+
if ((await readdir(dir)).filter(file=>file.endsWith('.json')).length>=64) throw Error('Too many MCP servers');
|
|
74
|
+
}
|
|
75
|
+
const temp=join(dir,randomUUID()+'.tmp');
|
|
76
|
+
try {
|
|
77
|
+
await writeFile(temp,JSON.stringify(entry),{mode:0o600,flag:'wx'});
|
|
78
|
+
await rename(temp,path);
|
|
79
|
+
} finally { await rm(temp,{force:true}); }
|
|
80
|
+
return {};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function resolveHttpMcp(config,job) {
|
|
84
|
+
const mcp=job.settings?.mcp;
|
|
85
|
+
if (!mcp || (job.sandbox!==null && job.sandbox?.network!==true)) return denied;
|
|
86
|
+
keys(mcp,['profile','servers']);
|
|
87
|
+
const selected=mcp.profile ?? [];
|
|
88
|
+
if (!Array.isArray(selected) || selected.length>64) throw Error('Invalid MCP profile selection');
|
|
89
|
+
const local=mcp.servers ?? {};
|
|
90
|
+
if (!local || typeof local!=='object' || Array.isArray(local) || Object.keys(local).length+selected.length>64) throw Error('Invalid MCP servers');
|
|
91
|
+
const entries=new Map();
|
|
92
|
+
for (const [name,entry] of Object.entries(local)) {
|
|
93
|
+
keys(entry,['url']); entries.set(validName(name),{url:endpoint(entry.url)});
|
|
94
|
+
}
|
|
95
|
+
for (const name of selected) {
|
|
96
|
+
validName(name);
|
|
97
|
+
if (entries.has(name)) throw Error('Duplicate MCP server name');
|
|
98
|
+
try { entries.set(name,await stored(await serverDir(config,job.profileId,false),name)); }
|
|
99
|
+
catch (err) { if (err.code==='ENOENT') throw Error('Unknown profile MCP server'); throw err; }
|
|
100
|
+
}
|
|
101
|
+
if (!entries.size) return denied;
|
|
102
|
+
const configLines=[], requirements=[];
|
|
103
|
+
for (const [name,{url,bearer}] of entries) {
|
|
104
|
+
configLines.push('[mcp_servers.'+name+']','url='+JSON.stringify(endpoint(url)),'default_tools_approval_mode="approve"');
|
|
105
|
+
if (bearer) configLines.push('http_headers={Authorization='+JSON.stringify('Bearer '+bearer)+'}');
|
|
106
|
+
requirements.push('[mcp_servers.'+name+'.identity]','url='+JSON.stringify(endpoint(url)));
|
|
107
|
+
}
|
|
108
|
+
return {configToml:configLines.join('\n')+'\n', requirementsToml:requirements.join('\n')+'\n'};
|
|
109
|
+
}
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { RunnerHost } from './host.mjs'
|
|
2
|
+
import { prepareWorker } from './policy.mjs'
|
|
3
|
+
import { attachProfileMethods } from './profile.mjs'
|
|
4
|
+
|
|
5
|
+
if (typeof process.send !== 'function') throw Error('Start the Codex runner through the pappai runner registry')
|
|
6
|
+
const config = JSON.parse(process.env.PAPPAI_RUNNER_CONFIG ?? '{}')
|
|
7
|
+
attachProfileMethods()
|
|
8
|
+
const host = new RunnerHost(config,prepareWorker,(type,payload) => {
|
|
9
|
+
if (process.connected) process.send({type,payload},() => {})
|
|
10
|
+
})
|
|
11
|
+
async function close() {
|
|
12
|
+
await host.close()
|
|
13
|
+
if (process.connected) process.disconnect()
|
|
14
|
+
}
|
|
15
|
+
process.on('message', message => {
|
|
16
|
+
if (message?.type === 'close') void close()
|
|
17
|
+
else if (message) host.receive(message)
|
|
18
|
+
})
|
|
19
|
+
process.on('disconnect',() => { void host.close() })
|
|
20
|
+
process.on('SIGTERM',close)
|
|
21
|
+
process.on('SIGINT',close)
|
package/src/policy.mjs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { lstat, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, isAbsolute, join, normalize } from 'node:path';
|
|
4
|
+
import { AppServer } from './client.mjs';
|
|
5
|
+
import { resolveHttpMcp } from './http-mcp.mjs';
|
|
6
|
+
import { sessionAuth } from './session-auth.mjs';
|
|
7
|
+
|
|
8
|
+
const cliPath = '/opt/codex/bin/codex';
|
|
9
|
+
const home = '/state/codex';
|
|
10
|
+
const work = '/work';
|
|
11
|
+
|
|
12
|
+
async function canonicalFile(path, label) {
|
|
13
|
+
if (typeof path !== 'string' || !isAbsolute(path) || normalize(path) !== path ||
|
|
14
|
+
await realpath(path) !== path || !(await lstat(path)).isFile()) {
|
|
15
|
+
throw new Error(`Expected a canonical regular file for ${label}`);
|
|
16
|
+
}
|
|
17
|
+
return path;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function protectedBinary(path, mounts) {
|
|
21
|
+
if (path.startsWith('/run/pappai/private/')) return true;
|
|
22
|
+
const enclosing = mounts.filter(({target}) => target === '/' || path === target || path.startsWith(target + '/'));
|
|
23
|
+
const depth = Math.max(...enclosing.map(({target}) => target.length));
|
|
24
|
+
return enclosing.length > 0 && enclosing.filter(({target}) => target.length === depth).every(mount => mount.readonly);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function privateDir(path) {
|
|
28
|
+
if (typeof path !== 'string' || !isAbsolute(path) || normalize(path) !== path) {
|
|
29
|
+
throw new Error('Expected an absolute canonical runner state directory');
|
|
30
|
+
}
|
|
31
|
+
await mkdir(path, { recursive: true, mode: 0o700 });
|
|
32
|
+
const stat = await lstat(path);
|
|
33
|
+
if (!stat.isDirectory() || await realpath(path) !== path || (stat.mode & 0o077) !== 0 ||
|
|
34
|
+
stat.uid !== process.geteuid()) throw new Error('Runner state directory must be private and owned by the runner');
|
|
35
|
+
return path;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function configToml(modelBaseUrl) {
|
|
39
|
+
const lines = [
|
|
40
|
+
'approval_policy="never"', 'default_permissions="pappai"', 'web_search="disabled"',
|
|
41
|
+
'cli_auth_credentials_store="file"', 'mcp_oauth_credentials_store="file"',
|
|
42
|
+
'check_for_update_on_startup=false', 'project_doc_max_bytes=0',
|
|
43
|
+
];
|
|
44
|
+
if (modelBaseUrl !== undefined) {
|
|
45
|
+
const url = new URL(modelBaseUrl);
|
|
46
|
+
if (url.username || url.password || url.search || url.hash ||
|
|
47
|
+
!(url.protocol === 'https:' || (url.protocol === 'http:' && ['localhost','127.0.0.1','[::1]'].includes(url.hostname)))) {
|
|
48
|
+
throw new Error('Invalid administrator model endpoint');
|
|
49
|
+
}
|
|
50
|
+
lines.push('model_provider="pappai"', '[model_providers.pappai]', 'name="pappai"',
|
|
51
|
+
'wire_api="responses"', 'requires_openai_auth=true', 'supports_websockets=false',
|
|
52
|
+
`base_url=${JSON.stringify(url.href)}`);
|
|
53
|
+
}
|
|
54
|
+
return [...lines,
|
|
55
|
+
'[permissions.pappai.filesystem]', '"/work"="read"', '"/state"="deny"', '"/proc"="deny"',
|
|
56
|
+
'[permissions.pappai.network]', 'enabled=false',
|
|
57
|
+
'[features]', ...['apps','browser_use','browser_use_external','code_mode','code_mode_host',
|
|
58
|
+
'computer_use','goals','hooks','image_generation','in_app_browser','memories','multi_agent_v2',
|
|
59
|
+
'plugins','remote_plugin','shell_snapshot','shell_tool','skill_search','unified_exec','view_image',
|
|
60
|
+
'workspace_dependencies'].map(key => `${key}=false`),
|
|
61
|
+
'skip_host_skill_discovery=true', '[agents]', 'enabled=false', '[analytics]', 'enabled=false',
|
|
62
|
+
'[feedback]', 'enabled=false', '',
|
|
63
|
+
].join('\n');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Only the administrator supplies config. The APP cannot add mounts, a cwd, environment,
|
|
67
|
+
// config layers, or executable arguments. Personal state and installer files are never mounted.
|
|
68
|
+
async function namespace(config, state, profileOwner, mcp) {
|
|
69
|
+
const binary = await canonicalFile(config.codexExecutablePath, 'Codex executable');
|
|
70
|
+
const bwrap = await canonicalFile(join(dirname(dirname(binary)), 'codex-resources', 'bwrap'), 'bundled Codex bubblewrap');
|
|
71
|
+
const mounts = (await readFile('/proc/self/mountinfo', 'utf8')).trim().split('\n').map(line => {
|
|
72
|
+
const fields = line.split(' ');
|
|
73
|
+
const target = fields[4].replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
|
|
74
|
+
return {target, readonly:fields[5].split(',').includes('ro')};
|
|
75
|
+
});
|
|
76
|
+
if (![binary,bwrap].every(path => protectedBinary(path,mounts))) {
|
|
77
|
+
throw Error('Codex distribution must be on a read-only mount or below /run/pappai/private');
|
|
78
|
+
}
|
|
79
|
+
if (typeof config.stateDir !== 'string' || !config.stateDir.startsWith('/run/pappai/private/')) {
|
|
80
|
+
throw new Error('Runner state must be below /run/pappai/private');
|
|
81
|
+
}
|
|
82
|
+
const root = await privateDir(config.stateDir);
|
|
83
|
+
const toml = configToml(config.modelBaseUrl);
|
|
84
|
+
const run = await mkdtemp(join(root, 'run-'));
|
|
85
|
+
const cleanup = () => rm(run, { recursive: true, force: true });
|
|
86
|
+
try {
|
|
87
|
+
const configFile = join(run, 'config.toml');
|
|
88
|
+
const requirements = join(run, 'requirements.toml');
|
|
89
|
+
await writeFile(configFile, toml + (mcp?.configToml ?? ''), { mode: 0o600, flag: 'wx' });
|
|
90
|
+
await writeFile(requirements, mcp?.requirementsToml ?? '[mcp_servers]\n', { mode: 0o600, flag: 'wx' });
|
|
91
|
+
|
|
92
|
+
// This root has no shell, package manager, project checkout or system Codex settings.
|
|
93
|
+
// The shared network is the app-server's service channel. Model tools run with a
|
|
94
|
+
// separate, network-disabled permission profile and no selected environment.
|
|
95
|
+
const args = ['--unshare-all', '--unshare-user', '--share-net', '--cap-drop', 'ALL',
|
|
96
|
+
'--die-with-parent', '--new-session', '--dev', '/dev', '--proc', '/proc', '--tmpfs', '/tmp',
|
|
97
|
+
'--dir', work, '--tmpfs', '/state', '--dir', home, '--dir', '/state/home', '--ro-bind', binary, cliPath,
|
|
98
|
+
'--ro-bind', bwrap, '/opt/codex/bin/bwrap'];
|
|
99
|
+
if (profileOwner) args.push('--bind', dirname(profileOwner.authPath), home);
|
|
100
|
+
args.push('--ro-bind', configFile, home + '/config.toml', '--ro-bind', requirements, '/etc/codex/requirements.toml');
|
|
101
|
+
for (const path of ['/etc/resolv.conf','/etc/hosts','/etc/ssl/certs/ca-certificates.crt']) {
|
|
102
|
+
args.push('--ro-bind', path, path);
|
|
103
|
+
}
|
|
104
|
+
if (state) {
|
|
105
|
+
await privateDir(state);
|
|
106
|
+
for (const [dir, target] of [['sessions', home + '/sessions'], ['sqlite', '/state/sqlite']]) {
|
|
107
|
+
args.push('--bind', await privateDir(join(state, dir)), target);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
args.push('--remount-ro', '/', '--chdir', work, '--clearenv', '--setenv', 'HOME', '/state/home',
|
|
111
|
+
'--setenv', 'CODEX_HOME', home, '--setenv', 'CODEX_SQLITE_HOME', '/state/sqlite',
|
|
112
|
+
'--setenv', 'PATH', '/opt/codex/bin', '--setenv', 'TMPDIR', '/tmp');
|
|
113
|
+
if (profileOwner) args.push('--setenv', 'CODEX_REFRESH_TOKEN_URL_OVERRIDE', profileOwner.endpoint);
|
|
114
|
+
args.push('--', cliPath, 'app-server', '--stdio', '--strict-config');
|
|
115
|
+
return {
|
|
116
|
+
executable: '/usr/bin/bwrap', args, cwd: run, env: {},
|
|
117
|
+
threadParams: { cwd: work, permissions: 'pappai', approvalPolicy: 'never', environments: [] },
|
|
118
|
+
stateFile: state ? join(state, 'thread.json') : null, cleanup,
|
|
119
|
+
};
|
|
120
|
+
} catch (error) {
|
|
121
|
+
await cleanup();
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// Only this trusted control client can see the renewable credential. No turns,
|
|
127
|
+
// APP tools, or APP state are ever supplied to the profile owner.
|
|
128
|
+
export async function rotateProfile(config, authPath, endpoint = 'https://auth.openai.com/oauth/token') {
|
|
129
|
+
const spec = await namespace(config, null, {authPath,endpoint});
|
|
130
|
+
const rpc = new AppServer(spec, () => {});
|
|
131
|
+
const deadline = setTimeout(() => rpc.close(), 20_000);
|
|
132
|
+
try {
|
|
133
|
+
await rpc.initialize({readAccount:false});
|
|
134
|
+
await rpc.rpc('account/read', {refreshToken:true});
|
|
135
|
+
} finally {
|
|
136
|
+
clearTimeout(deadline);
|
|
137
|
+
await rpc.close();
|
|
138
|
+
await spec.cleanup();
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export async function prepareWorker(config, job) {
|
|
143
|
+
if (process.platform !== 'linux') throw new Error('Codex workers require Linux bubblewrap');
|
|
144
|
+
if (!job.profileId || typeof job.appId !== 'string' || !job.appId ||
|
|
145
|
+
!['oneShot','persistent'].includes(job.mode)) throw new Error('Invalid Codex worker assignment');
|
|
146
|
+
const auth = await sessionAuth(config, job.profileId, rotateProfile);
|
|
147
|
+
const key = createHash('sha256').update(job.appId).digest('hex');
|
|
148
|
+
const state = job.mode === 'persistent' ? join(config.stateDir, key) : null;
|
|
149
|
+
return {...await namespace(config, state, null, await resolveHttpMcp(config,job)), sessionAuth:auth};
|
|
150
|
+
}
|
package/src/profile.mjs
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, open, realpath, rename, rm } from 'node:fs/promises';
|
|
4
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
5
|
+
|
|
6
|
+
import { mcpMethod } from './http-mcp.mjs';
|
|
7
|
+
const methods = ['setup','status','remove','mcp.get','mcp.set','mcp.delete'];
|
|
8
|
+
const maxBytes = 1024 * 1024;
|
|
9
|
+
const profileOperations = new Map();
|
|
10
|
+
|
|
11
|
+
// The controller gives one runner host ownership of its profile storage. Configure,
|
|
12
|
+
// remove, and native token rotation share the same queue, including errors.
|
|
13
|
+
export function withProfileLock(config, id, work) {
|
|
14
|
+
const key = JSON.stringify([config.profilesDir ?? process.env.PAPPAI_PROFILES_DIR, id]);
|
|
15
|
+
const previous = profileOperations.get(key) ?? Promise.resolve();
|
|
16
|
+
const operation = previous.then(work);
|
|
17
|
+
const settled = operation.catch(() => {});
|
|
18
|
+
profileOperations.set(key, settled);
|
|
19
|
+
settled.then(() => { if (profileOperations.get(key) === settled) profileOperations.delete(key); });
|
|
20
|
+
return operation;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function directory(config, id, create) {
|
|
24
|
+
const root = config.profilesDir ?? process.env.PAPPAI_PROFILES_DIR ?? '/run/pappai/private/profiles';
|
|
25
|
+
if (typeof root !== 'string' || !isAbsolute(root) || root !== resolve(root)) throw Error('Invalid profiles directory');
|
|
26
|
+
if (process.platform === 'linux' && !root.startsWith('/run/pappai/private/')) throw Error('Profiles must use the private mount');
|
|
27
|
+
if (typeof id !== 'string' || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id)) throw Error('Invalid profile ID');
|
|
28
|
+
// The operator provisions the canonical root. Never follow a tenant-chosen link.
|
|
29
|
+
if (await realpath(root) !== root) throw Error('Invalid profiles directory');
|
|
30
|
+
let dir = root;
|
|
31
|
+
for (const part of [id,'codex']) {
|
|
32
|
+
dir = join(dir,part);
|
|
33
|
+
if (create) {
|
|
34
|
+
try { await mkdir(dir,{mode:0o700}); }
|
|
35
|
+
catch (e) { if (e.code !== 'EEXIST') throw e; }
|
|
36
|
+
}
|
|
37
|
+
if (!(await lstat(dir)).isDirectory() || await realpath(dir) !== dir) throw Error('Invalid profile directory');
|
|
38
|
+
}
|
|
39
|
+
return dir;
|
|
40
|
+
}
|
|
41
|
+
export { directory as profileDirectory };
|
|
42
|
+
|
|
43
|
+
export async function profileAuthPath(config, id) {
|
|
44
|
+
const path = join(await directory(config,id,false), 'auth.json');
|
|
45
|
+
const s = await lstat(path);
|
|
46
|
+
if (!s.isFile() || s.size > maxBytes || await realpath(path) !== path) throw Error('Invalid profile credentials');
|
|
47
|
+
return path;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function validateCredentials(bytes) {
|
|
51
|
+
if (!Buffer.isBuffer(bytes) || bytes.length > maxBytes) throw Error('Invalid Codex credentials');
|
|
52
|
+
let auth;
|
|
53
|
+
try { auth=JSON.parse(bytes.toString('utf8')); } catch { throw Error('Invalid Codex credentials'); }
|
|
54
|
+
const nonempty = value => typeof value==='string' && value.length>0;
|
|
55
|
+
if (!auth || !(nonempty(auth.OPENAI_API_KEY) || (nonempty(auth.tokens?.access_token) &&
|
|
56
|
+
nonempty(auth.tokens?.refresh_token)))) throw Error('Invalid Codex credentials');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function profileMethod(config, id, method, data, reader) {
|
|
60
|
+
return withProfileLock(config, id, () => runProfileMethod(config,id,method,data,reader));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function runProfileMethod(config, id, method, data, reader) {
|
|
64
|
+
if (method.startsWith('mcp.')) return mcpMethod(config,id,method,data,reader);
|
|
65
|
+
if (method==='status') {
|
|
66
|
+
try { await profileAuthPath(config,id); return {configured:true}; }
|
|
67
|
+
catch (e) { if (e.code==='ENOENT') return {configured:false}; throw e; }
|
|
68
|
+
}
|
|
69
|
+
if (method==='remove') {
|
|
70
|
+
try {
|
|
71
|
+
const dir=await directory(config,id,false);
|
|
72
|
+
const retired=join(dir,'..','codex-removed-'+randomUUID());
|
|
73
|
+
await rename(dir,retired);
|
|
74
|
+
await rm(retired,{recursive:true,force:true});
|
|
75
|
+
}
|
|
76
|
+
catch (e) { if (e.code!=='ENOENT') throw e; }
|
|
77
|
+
return {configured:false};
|
|
78
|
+
}
|
|
79
|
+
if (method!=='setup') throw Error('Unknown profile method');
|
|
80
|
+
if (typeof data?.authFile!=='string' || !data.authFile.startsWith('/') || Object.keys(data).length!==1)
|
|
81
|
+
throw Error('Expected an absolute authFile in the caller file view');
|
|
82
|
+
const bytes=await reader(data.authFile);
|
|
83
|
+
validateCredentials(bytes);
|
|
84
|
+
const dir=await directory(config,id,true);
|
|
85
|
+
const temp=join(dir,randomUUID()+'.tmp');
|
|
86
|
+
const file=await open(temp,constants.O_EXCL|constants.O_CREAT|constants.O_WRONLY,0o600);
|
|
87
|
+
try {
|
|
88
|
+
try { await file.writeFile(bytes); await file.sync(); } finally { await file.close(); }
|
|
89
|
+
await rename(temp,join(dir,'auth.json'));
|
|
90
|
+
} finally { await rm(temp,{force:true}); }
|
|
91
|
+
return {configured:true};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function attachProfileMethods() {
|
|
95
|
+
const config=JSON.parse(process.env.PAPPAI_RUNNER_CONFIG || '{}');
|
|
96
|
+
const requests=new Map();
|
|
97
|
+
const send=(type,payload)=>{ if (process.connected) process.send({type,payload},()=>{}); };
|
|
98
|
+
function read(id,path) {
|
|
99
|
+
const requestId=randomUUID();
|
|
100
|
+
return new Promise((resolve,reject)=>{
|
|
101
|
+
const timeout=setTimeout(()=>{requests.delete(requestId);reject(Error('Profile read timed out'));},25_000);
|
|
102
|
+
timeout.unref();
|
|
103
|
+
requests.set(requestId,{id,resolve,reject,timeout});
|
|
104
|
+
send('profileRead',{id,requestId,path});
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
process.on('message',msg=>{
|
|
108
|
+
if (msg?.type==='profileFile') {
|
|
109
|
+
const req=requests.get(msg.requestId);
|
|
110
|
+
if (!req || req.id!==msg.id) return;
|
|
111
|
+
clearTimeout(req.timeout);
|
|
112
|
+
requests.delete(msg.requestId);
|
|
113
|
+
if (msg.error) req.reject(Error('Access denied or file unavailable'));
|
|
114
|
+
else req.resolve(Buffer.from(msg.content,'base64'));
|
|
115
|
+
}
|
|
116
|
+
if (msg?.type!=='profileCall' || !methods.includes(msg.method)) return;
|
|
117
|
+
const operation=profileMethod(config,msg.profileId,msg.method,msg.data,path=>read(msg.id,path));
|
|
118
|
+
operation.then(result=>send('profileReply',{id:msg.id,result}),err=>{
|
|
119
|
+
const message = err.code ? 'Profile storage unavailable' : err.message;
|
|
120
|
+
send('profileReply',{id:msg.id,error:message});
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
send('profileMethods',{methods});
|
|
124
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { profileAuthPath, withProfileLock } from './profile.mjs';
|
|
3
|
+
|
|
4
|
+
function claims(token) {
|
|
5
|
+
try { return JSON.parse(Buffer.from(token.split('.')[1], 'base64url')); }
|
|
6
|
+
catch { return {}; }
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
function loginParams(auth) {
|
|
10
|
+
if ((auth.auth_mode == null || auth.auth_mode === 'apikey') && typeof auth.OPENAI_API_KEY === 'string' && auth.OPENAI_API_KEY) {
|
|
11
|
+
return {type:'apiKey', apiKey:auth.OPENAI_API_KEY};
|
|
12
|
+
}
|
|
13
|
+
const tokens = auth.tokens;
|
|
14
|
+
if ((auth.auth_mode != null && auth.auth_mode !== 'chatgpt') || typeof tokens?.access_token !== 'string' ||
|
|
15
|
+
typeof tokens.refresh_token !== 'string' || !tokens.refresh_token) throw Error('Invalid subscription credentials');
|
|
16
|
+
const access = claims(tokens.access_token)['https://api.openai.com/auth'] ?? {};
|
|
17
|
+
const id = claims(tokens.id_token)['https://api.openai.com/auth'] ?? {};
|
|
18
|
+
const account = tokens.account_id ?? access.chatgpt_account_id ?? id.chatgpt_account_id;
|
|
19
|
+
if (typeof account !== 'string' || !account || (access.chatgpt_account_id && access.chatgpt_account_id !== account)) {
|
|
20
|
+
throw Error('Invalid subscription account');
|
|
21
|
+
}
|
|
22
|
+
return {type:'chatgptAuthTokens', accessToken:tokens.access_token, chatgptAccountId:account,
|
|
23
|
+
chatgptPlanType:access.chatgpt_plan_type ?? id.chatgpt_plan_type ?? null};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function sessionAuth(config, profileId, rotate) {
|
|
27
|
+
const read = async () => {
|
|
28
|
+
const path = await profileAuthPath(config, profileId);
|
|
29
|
+
return {path, login:loginParams(JSON.parse(await readFile(path, 'utf8')))};
|
|
30
|
+
};
|
|
31
|
+
const {login:initial} = await withProfileLock(config, profileId, read);
|
|
32
|
+
const {type,chatgptAccountId} = initial;
|
|
33
|
+
let lastToken;
|
|
34
|
+
|
|
35
|
+
function check(login) {
|
|
36
|
+
if (login.type !== type || login.chatgptAccountId !== chatgptAccountId) throw Error('Profile account changed');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function latest(expectToken, proactive) {
|
|
40
|
+
return withProfileLock(config, profileId, async () => {
|
|
41
|
+
let {path,login} = await read();
|
|
42
|
+
check(login);
|
|
43
|
+
if (type === 'apiKey') return login;
|
|
44
|
+
const exp = claims(login.accessToken).exp;
|
|
45
|
+
const expired = Number.isFinite(exp) && exp * 1000 <= Date.now() + 30_000;
|
|
46
|
+
if ((proactive && expired) || (!proactive && expectToken === login.accessToken)) {
|
|
47
|
+
const before = login.accessToken;
|
|
48
|
+
// Codex can persist a successful rotation and subsequently reject account/read
|
|
49
|
+
// during workspace discovery. The atomically stored token is authoritative.
|
|
50
|
+
try { await rotate(config, path); } catch { /* verify the persisted result below */ }
|
|
51
|
+
({login} = await read());
|
|
52
|
+
check(login);
|
|
53
|
+
if (login.accessToken === before) throw Error('Subscription credentials could not be renewed');
|
|
54
|
+
}
|
|
55
|
+
lastToken = login.accessToken;
|
|
56
|
+
return login;
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
getTokens: () => latest(null, true),
|
|
62
|
+
async refreshTokens(params) {
|
|
63
|
+
if (type !== 'chatgptAuthTokens' || params.reason !== 'unauthorized' || !lastToken ||
|
|
64
|
+
(params.previousAccountId != null && params.previousAccountId !== chatgptAccountId)) {
|
|
65
|
+
throw Error('Invalid subscription refresh request');
|
|
66
|
+
}
|
|
67
|
+
const {type:_, ...tokens} = await latest(lastToken, false);
|
|
68
|
+
return tokens;
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
package/src/tools.mjs
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const string = {type:'string'}
|
|
2
|
+
const filter = {anyOf:[string,{type:'array',items:string}]}
|
|
3
|
+
const timeoutMs = {type:'integer',minimum:1,maximum:86400000}
|
|
4
|
+
const definitions = [
|
|
5
|
+
['dir','List workspace nodes visible to this APP.',{},[]],
|
|
6
|
+
['help','Read the public contract of a visible node.',{node:string,features:filter,schemas:filter,docs:filter},['node']],
|
|
7
|
+
['call','Call a permitted method on a pappai node.',{node:string,method:string,data:{},version:string,timeoutMs},['node','method']],
|
|
8
|
+
['publish','Publish a declared event as this APP.',{event:string,data:{},version:string,to:filter,
|
|
9
|
+
delivery:{enum:['none','status']},timeoutMs},['event']],
|
|
10
|
+
]
|
|
11
|
+
|
|
12
|
+
export const dynamicTools = definitions.map(([name,description,properties,required]) => ({
|
|
13
|
+
type:'function',name:'pappai_' + name,description,inputSchema:{type:'object',properties,required,additionalProperties:false},
|
|
14
|
+
}))
|
|
15
|
+
export const toolMethods = new Map(definitions.map(([name]) => ['pappai_' + name,name]))
|