@flinbein/pappai-runner-codex 0.1.6 → 0.1.8
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 +24 -9
- package/package.json +2 -1
- package/scripts/upgrade-thread-tools.mjs +73 -0
- package/src/client.mjs +1 -1
- package/src/index.mjs +32 -5
- package/src/installation.mjs +158 -0
- package/src/policy.mjs +10 -4
- package/src/profile.mjs +7 -6
- package/src/tools.mjs +3 -2
package/README.md
CHANGED
|
@@ -4,11 +4,22 @@ This external runner delivers [pappai](https://github.com/flinbein/pappai) event
|
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
In the pappai workspace, choose **Add runner → npm**, enter `@flinbein/pappai-runner-codex`, and give the installation a name, such as `codex`. The host requires Linux x86_64, bubblewrap, npm, Node.js 24.2+ and a persistent private volume at `/run/pappai/private`.
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
On first start the runner downloads the latest stable native Linux musl distribution from the public npm registry and verifies its executable version. It keeps each CLI release and the selected version in `/run/pappai/private/runners/<name>/tools/`. A restart uses the selected version offline. The runner publishes its [APP settings schema](examples/settings-schema.json) when it starts.
|
|
10
|
+
|
|
11
|
+
Administrators can call these methods on the workspace (`~`). Substitute the installation name for `codex`.
|
|
12
|
+
|
|
13
|
+
| Method | Arguments | Result |
|
|
14
|
+
| --- | --- | --- |
|
|
15
|
+
| `runners.codex.getVersion` | `{}` | Active CLI version, installation status and source |
|
|
16
|
+
| `runners.codex.installCodex` | `{}` or `{"version":"0.172.0"}` | Resolve the latest stable version or select the exact stable version, then return its status |
|
|
17
|
+
|
|
18
|
+
For example, `{"source":"managed","version":"0.172.0","status":"ready"}` means new executors will use that release. During the first installation, the status is `installing` and the version is `null`. New workers wait for the CLI. Existing executors keep using their launch version after an update. A failed update preserves the active release and exposes an `error` through `getVersion`. To roll back, select a previously installed version.
|
|
19
|
+
|
|
20
|
+
### Existing installations
|
|
21
|
+
|
|
22
|
+
Controllers with an existing manual registration continue to use its saved paths. For example, the following registration was supported by earlier controllers. Its externally installed CLI reports `"source":"configured"` in workspace settings on controllers that support runner methods.
|
|
12
23
|
|
|
13
24
|
```json
|
|
14
25
|
{
|
|
@@ -24,10 +35,14 @@ The runner requires a pappai controller that supports PROFILE nodes and administ
|
|
|
24
35
|
|
|
25
36
|
## Updating an existing registration
|
|
26
37
|
|
|
27
|
-
|
|
38
|
+
Updating the runner package and updating the Codex CLI are separate operations. In a managed installation, select the new runner release through workspace settings. The controller activates its entry point with `$.runners.restart({name,entrypoint})`. CLI selection, stored profile connections, and APP history persist across runner package updates.
|
|
39
|
+
|
|
40
|
+
For a manually installed runner, find its 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.
|
|
28
41
|
|
|
29
42
|
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.
|
|
30
43
|
|
|
44
|
+
When upgrading a persistent session from the `pappai_dir` tool on Codex CLI 0.170.0, stop the controller, back up the runner state directory and run `node <installed-package>/scripts/upgrade-thread-tools.mjs <app-state>` for each persistent APP state directory before starting the new controller. Codex stores dynamic tool definitions at thread creation. The script updates the discovery name and help signature in stored rollout metadata and the SQLite index. It replaces each rollout atomically, preserving all conversation records after the header. A repeated invocation reports zero updates. Restore the backup if rolling back both packages. Fresh installations and one-shot APPs can skip this step.
|
|
45
|
+
|
|
31
46
|
## First call
|
|
32
47
|
|
|
33
48
|
1. Call `$.profile.create` on the workspace or a TEAM with a name and permissions. Save the returned ID.
|
|
@@ -38,17 +53,17 @@ Call `$.runners.restart({"name":"codex"})` on the workspace to load the installe
|
|
|
38
53
|
|
|
39
54
|
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
55
|
|
|
41
|
-
The runner supports API keys and imported ChatGPT subscription credentials.
|
|
56
|
+
The runner supports API keys and imported ChatGPT subscription credentials. Each installation stores its connection at `profiles/<profileId>/<runnerName>/` and coordinates token refresh across its APPs. The default installation named `codex` keeps its existing history under `state/`. Other installations keep their history under `state/instances/<runnerName>/`. Each subscription worker receives only short-lived credentials. The rotation test uses the native Codex CLI and a local OAuth test server.
|
|
42
57
|
|
|
43
58
|
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
59
|
|
|
45
60
|
## Executor permissions
|
|
46
61
|
|
|
47
|
-
The executor runs in an isolated directory. Its connection to the model is a service channel. For workspace operations, the model receives the `
|
|
62
|
+
The executor runs in an isolated directory. Its connection to the model is a service channel. For workspace operations, the model receives the `pappai_discover`, `pappai_help`, `pappai_call` and `pappai_publish` tools. Use `pappai_help({node, features:true})` to list the full catalog. Omit `features` for the top level, or select names and request `doc:true` and `schema:true` for details. Each entry has a type and version. 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
63
|
|
|
49
|
-
Workers support Code Mode. For example, `functions.exec` can run `text(await tools.
|
|
64
|
+
Workers support Code Mode. For example, `functions.exec` can run `text(await tools.pappai_discover({}))`. 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
65
|
|
|
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.
|
|
66
|
+
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.
|
|
52
67
|
|
|
53
68
|
## HTTP MCP
|
|
54
69
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@flinbein/pappai-runner-codex",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
4
4
|
"description": "Codex app-server runner for pappai",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.mjs",
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
11
11
|
"src/",
|
|
12
|
+
"scripts/upgrade-thread-tools.mjs",
|
|
12
13
|
"examples/",
|
|
13
14
|
"README.md"
|
|
14
15
|
],
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Offline upgrade for the rollout headers and optional tool index of Codex CLI 0.170.0.
|
|
2
|
+
import { createReadStream } from 'node:fs'
|
|
3
|
+
import { lstat, open, readdir, rename, rm } from 'node:fs/promises'
|
|
4
|
+
import { randomUUID } from 'node:crypto'
|
|
5
|
+
import { dirname, join, resolve } from 'node:path'
|
|
6
|
+
import { pipeline } from 'node:stream/promises'
|
|
7
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
8
|
+
import { pathToFileURL } from 'node:url'
|
|
9
|
+
import { dynamicTools } from '../src/tools.mjs'
|
|
10
|
+
|
|
11
|
+
const replacements = new Map(['pappai_discover','pappai_help'].map(name => [
|
|
12
|
+
name === 'pappai_discover' ? 'pappai_dir' : name, dynamicTools.find(tool => tool.name === name),
|
|
13
|
+
]))
|
|
14
|
+
|
|
15
|
+
async function upgradeRollout(file) {
|
|
16
|
+
// Preserve the conversation byte for byte after the session metadata line.
|
|
17
|
+
let header = Buffer.alloc(0)
|
|
18
|
+
const chunk = Buffer.alloc(16384)
|
|
19
|
+
const input = await open(file,'r')
|
|
20
|
+
let end
|
|
21
|
+
try {
|
|
22
|
+
while ((end = header.indexOf(10)) < 0) {
|
|
23
|
+
const {bytesRead} = await input.read(chunk)
|
|
24
|
+
if (!bytesRead || header.length > 4 * 1024 * 1024) throw Error('Invalid rollout metadata')
|
|
25
|
+
header = Buffer.concat([header,chunk.subarray(0,bytesRead)])
|
|
26
|
+
}
|
|
27
|
+
} finally { await input.close() }
|
|
28
|
+
const record = JSON.parse(header.subarray(0,end))
|
|
29
|
+
const tools = record.payload?.dynamic_tools
|
|
30
|
+
if (record.type !== 'session_meta') throw Error('Expected session metadata')
|
|
31
|
+
if (!tools?.some(tool => tool.name === 'pappai_dir' && !tool.namespace)) return 0
|
|
32
|
+
for (const [name, replacement] of replacements) {
|
|
33
|
+
const tool = tools.find(tool => tool.name === name && !tool.namespace)
|
|
34
|
+
if (!tool) throw Error('Incomplete thread tool catalog')
|
|
35
|
+
Object.assign(tool,replacement)
|
|
36
|
+
}
|
|
37
|
+
const temporary = join(dirname(file),'.upgrade-' + randomUUID())
|
|
38
|
+
const target = await open(temporary,'wx',0o600)
|
|
39
|
+
try {
|
|
40
|
+
await target.writeFile(JSON.stringify(record) + '\n')
|
|
41
|
+
await pipeline(createReadStream(file,{start:end+1}),target.createWriteStream())
|
|
42
|
+
await rename(temporary,file)
|
|
43
|
+
} finally { await target.close(); await rm(temporary,{force:true}) }
|
|
44
|
+
return 1
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function upgradeThreadTools(state) {
|
|
48
|
+
const sessions = join(state,'sessions')
|
|
49
|
+
let updated = 0
|
|
50
|
+
for (const item of await readdir(sessions,{recursive:true,withFileTypes:true})) {
|
|
51
|
+
if (item.isFile() && /^rollout-.*\.jsonl$/.test(item.name))
|
|
52
|
+
updated += await upgradeRollout(join(item.parentPath,item.name))
|
|
53
|
+
}
|
|
54
|
+
const file = join(state,'sqlite','state_5.sqlite')
|
|
55
|
+
if (!(await lstat(file)).isFile()) throw Error('Expected an existing Codex state database')
|
|
56
|
+
const db = new DatabaseSync(file)
|
|
57
|
+
try {
|
|
58
|
+
db.exec('BEGIN IMMEDIATE')
|
|
59
|
+
const legacy = db.prepare("SELECT thread_id FROM thread_dynamic_tools WHERE name='pappai_dir' AND namespace IS NULL").all()
|
|
60
|
+
const update = db.prepare('UPDATE thread_dynamic_tools SET name=?, description=?, input_schema=? WHERE thread_id=? AND name=? AND namespace IS NULL')
|
|
61
|
+
for (const {thread_id} of legacy) {
|
|
62
|
+
for (const [oldName, tool] of replacements) {
|
|
63
|
+
if (update.run(tool.name,tool.description,JSON.stringify(tool.inputSchema),thread_id,oldName).changes !== 1)
|
|
64
|
+
throw Error('Unexpected persistent thread tool catalog')
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
db.exec('COMMIT')
|
|
68
|
+
return updated
|
|
69
|
+
} finally { db.close() }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href)
|
|
73
|
+
console.log('Updated persistent tool catalogs:', await upgradeThreadTools(process.argv[2]))
|
package/src/client.mjs
CHANGED
|
@@ -149,7 +149,7 @@ export class AppServer {
|
|
|
149
149
|
const {userAgent} = await this.rpc('initialize',{
|
|
150
150
|
clientInfo:{name:'pappai_runner_codex',version:'1'},capabilities:{experimentalApi:true},
|
|
151
151
|
})
|
|
152
|
-
if (typeof userAgent !== 'string' ||
|
|
152
|
+
if (typeof userAgent !== 'string' || !userAgent) throw Error('Invalid Codex app-server initialization')
|
|
153
153
|
this.#send({method:'initialized'})
|
|
154
154
|
if (!readAccount) return
|
|
155
155
|
if (this.#auth) {
|
package/src/index.mjs
CHANGED
|
@@ -1,21 +1,48 @@
|
|
|
1
1
|
import { RunnerHost } from './host.mjs'
|
|
2
2
|
import { prepareWorker } from './policy.mjs'
|
|
3
3
|
import { attachProfileMethods } from './profile.mjs'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { CodexInstallation, runnerMethods } from './installation.mjs'
|
|
6
|
+
import settingsSchema from '../examples/settings-schema.json' with {type:'json'}
|
|
4
7
|
|
|
5
8
|
if (typeof process.send !== 'function') throw Error('Start the Codex runner through the pappai runner registry')
|
|
6
9
|
const config = JSON.parse(process.env.PAPPAI_RUNNER_CONFIG ?? '{}')
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
+
config.runnerName = process.env.PAPPAI_RUNNER_NAME || 'codex'
|
|
11
|
+
if (!/^[a-z][a-z0-9_-]{0,63}$/.test(config.runnerName)) throw Error('Invalid runner name')
|
|
12
|
+
config.stateDir ??= '/run/pappai/private/state'
|
|
13
|
+
if (config.runnerName !== 'codex') config.stateDir=join(config.stateDir,'instances',config.runnerName)
|
|
14
|
+
const installation = new CodexInstallation({
|
|
15
|
+
toolsDir:process.env.PAPPAI_RUNNER_DIR ? join(process.env.PAPPAI_RUNNER_DIR,'tools') : undefined,
|
|
16
|
+
configuredPath:config.codexExecutablePath,
|
|
10
17
|
})
|
|
18
|
+
function send(type,payload) {
|
|
19
|
+
if (process.connected) process.send({type,payload},() => {})
|
|
20
|
+
}
|
|
21
|
+
const host = new RunnerHost(config,async (config,job) => {
|
|
22
|
+
const codexExecutablePath=await installation.executable()
|
|
23
|
+
return prepareWorker({...config,codexExecutablePath},job)
|
|
24
|
+
},send)
|
|
25
|
+
async function runnerCall({id,method,data}) {
|
|
26
|
+
try {
|
|
27
|
+
if (!Object.hasOwn(runnerMethods,method)) throw Error('Unknown runner method')
|
|
28
|
+
if (!data || typeof data!=='object' || Array.isArray(data) ||
|
|
29
|
+
Object.keys(data).some(key=>method!=='installCodex' || key!=='version')) throw Error('Invalid runner method arguments')
|
|
30
|
+
const result=method==='getVersion' ? installation.status() : await installation.install(data.version)
|
|
31
|
+
send('runnerReply',{id,result})
|
|
32
|
+
} catch (error) { send('runnerReply',{id,error:error.message}) }
|
|
33
|
+
}
|
|
11
34
|
async function close() {
|
|
12
|
-
await host.close()
|
|
35
|
+
await Promise.all([installation.close(),host.close()])
|
|
13
36
|
if (process.connected) process.disconnect()
|
|
14
37
|
}
|
|
15
38
|
process.on('message', message => {
|
|
16
39
|
if (message?.type === 'close') void close()
|
|
40
|
+
else if (message?.type === 'runnerCall') void runnerCall(message)
|
|
17
41
|
else if (message) host.receive(message)
|
|
18
42
|
})
|
|
19
|
-
process.on('disconnect',
|
|
43
|
+
process.on('disconnect',close)
|
|
20
44
|
process.on('SIGTERM',close)
|
|
21
45
|
process.on('SIGINT',close)
|
|
46
|
+
send('runnerReady',{kind:'codex',settingsSchema,methods:runnerMethods})
|
|
47
|
+
attachProfileMethods(config)
|
|
48
|
+
void installation.start().catch(()=>{}) // getVersion and waiting workers expose the issue
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import {execFile} from 'node:child_process';
|
|
2
|
+
import {mkdir, mkdtemp, readFile, rename, rm, writeFile} from 'node:fs/promises';
|
|
3
|
+
import {join} from 'node:path';
|
|
4
|
+
import {promisify} from 'node:util';
|
|
5
|
+
import {trustedDistribution} from './policy.mjs';
|
|
6
|
+
|
|
7
|
+
const run = promisify(execFile);
|
|
8
|
+
const stable = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
|
|
9
|
+
const registry = 'https://registry.npmjs.org/';
|
|
10
|
+
const statusSchema = {type:'object', required:['version','status','source'], additionalProperties:false,
|
|
11
|
+
properties:{version:{type:['string','null']}, status:{enum:['installing','ready','error']},
|
|
12
|
+
source:{enum:['managed','configured']}, error:{type:'string'}}};
|
|
13
|
+
const input = properties => ({type:'object',properties,additionalProperties:false});
|
|
14
|
+
export const runnerMethods = {
|
|
15
|
+
getVersion:{description:'Read the active Codex CLI version and installation status.',
|
|
16
|
+
schema:{input:input({}),output:statusSchema}},
|
|
17
|
+
installCodex:{description:'Install an exact stable Codex CLI version, or use the latest stable version.',
|
|
18
|
+
schema:{input:input({version:{type:'string',pattern:stable.source,maxLength:64}}),output:statusSchema}},
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
function exact(version) {
|
|
22
|
+
if (typeof version !== 'string' || version.length > 64 || !stable.test(version)) throw Error('Expected a stable Codex version (x.y.z)');
|
|
23
|
+
return version;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function latest(signal) {
|
|
27
|
+
const response = await fetch(registry + '@openai%2fcodex/latest',{signal:AbortSignal.any([signal,AbortSignal.timeout(30000)])});
|
|
28
|
+
if (!response.ok) throw Error('Could not resolve the latest stable Codex CLI (HTTP ' + response.status + ')');
|
|
29
|
+
return exact((await response.json()).version);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function download(stage,version,signal) {
|
|
33
|
+
if (process.platform !== 'linux' || process.arch !== 'x64') throw Error('Managed Codex installation requires Linux x86_64');
|
|
34
|
+
const prefix=join(stage,'npm');
|
|
35
|
+
try {
|
|
36
|
+
await run('npm',['install','--prefix',prefix,'--cache',join(stage,'cache'),'--registry',registry,
|
|
37
|
+
'--no-save','--package-lock=false','--ignore-scripts','--no-audit','--no-fund',
|
|
38
|
+
'@openai/codex@'+version+'-linux-x64'],{cwd:stage,signal,timeout:600000});
|
|
39
|
+
} catch {
|
|
40
|
+
throw Error('npm could not install the native Linux x64 Codex CLI '+version);
|
|
41
|
+
}
|
|
42
|
+
await rename(join(prefix,'node_modules','@openai','codex','vendor','x86_64-unknown-linux-musl'),join(stage,'distribution'));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function inspect(path,signal) {
|
|
46
|
+
await trustedDistribution(path);
|
|
47
|
+
const {stdout} = await run(path,['--version'],{signal,timeout:10000,maxBuffer:16384,env:{PATH:'/usr/bin:/bin'}});
|
|
48
|
+
const match=/^codex-cli (\S+)$/.exec(stdout.trim());
|
|
49
|
+
if (!match) throw Error('Unrecognized Codex CLI version');
|
|
50
|
+
return match[1];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Each registration has a single host. A worker pins its version-specific path for
|
|
54
|
+
// its lifetime, including token refreshes after an administrator changes the selection.
|
|
55
|
+
export class CodexInstallation {
|
|
56
|
+
#active;
|
|
57
|
+
#issue;
|
|
58
|
+
#pending = Promise.resolve();
|
|
59
|
+
#busy = 0;
|
|
60
|
+
#stop = new AbortController();
|
|
61
|
+
|
|
62
|
+
constructor({toolsDir,configuredPath,latest:resolveLatest=latest,download:fetchNative=download,inspect:probe=inspect}) {
|
|
63
|
+
Object.assign(this,{toolsDir,configuredPath,resolveLatest,fetchNative,probe});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
status() {
|
|
67
|
+
return {source:this.#active?.source ?? (this.configuredPath ? 'configured' : 'managed'),
|
|
68
|
+
version:this.#active?.version ?? null, status:this.#busy ? 'installing' : this.#active ? 'ready' : 'error',
|
|
69
|
+
...(this.#issue && {error:this.#issue})};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
#operation(work) {
|
|
73
|
+
this.#busy++;
|
|
74
|
+
const result = this.#pending.then(async () => {
|
|
75
|
+
try {
|
|
76
|
+
this.#stop.signal.throwIfAborted();
|
|
77
|
+
this.#issue=undefined;
|
|
78
|
+
await work();
|
|
79
|
+
} catch (error) {
|
|
80
|
+
this.#issue = error.code ? 'Codex CLI storage or executable unavailable (' + error.code + ')' : error.message;
|
|
81
|
+
throw Error(this.#issue);
|
|
82
|
+
} finally { this.#busy--; }
|
|
83
|
+
return this.status();
|
|
84
|
+
});
|
|
85
|
+
this.#pending=result.catch(()=>{});
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
start() {
|
|
90
|
+
return this.#operation(async () => {
|
|
91
|
+
let selected;
|
|
92
|
+
if (this.toolsDir) {
|
|
93
|
+
try { selected=JSON.parse(await readFile(join(this.toolsDir,'selected.json'),'utf8')); }
|
|
94
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
95
|
+
}
|
|
96
|
+
if (selected !== undefined) {
|
|
97
|
+
await this.#select(exact(selected?.version),false);
|
|
98
|
+
} else if (this.configuredPath) {
|
|
99
|
+
const version=await this.probe(this.configuredPath,this.#stop.signal);
|
|
100
|
+
this.#active={source:'configured',version,path:this.configuredPath};
|
|
101
|
+
} else {
|
|
102
|
+
await this.#install();
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async executable() {
|
|
108
|
+
if (!this.#active) await this.#pending;
|
|
109
|
+
if (!this.#active) throw Error(this.#issue ?? 'Codex CLI unavailable');
|
|
110
|
+
return this.#active.path;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
install(version) {
|
|
114
|
+
return this.#operation(()=>this.#install(version));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async #install(requested) {
|
|
118
|
+
if (!this.toolsDir) throw Error('Installing Codex requires a managed runner directory');
|
|
119
|
+
const version=exact(requested === undefined ? await this.resolveLatest(this.#stop.signal) : requested);
|
|
120
|
+
await this.#select(version,true);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async #select(version,install) {
|
|
124
|
+
const dest=join(this.toolsDir,version), path=join(dest,'bin','codex');
|
|
125
|
+
const active={source:'managed',version,path};
|
|
126
|
+
const verify = async file => {
|
|
127
|
+
if (await this.probe(file,this.#stop.signal) !== version) throw Error('Codex executable version does not match the selected release');
|
|
128
|
+
};
|
|
129
|
+
let missing = false;
|
|
130
|
+
try { await verify(path); }
|
|
131
|
+
catch (error) {
|
|
132
|
+
if (!install || error.code!=='ENOENT') throw error;
|
|
133
|
+
missing = true;
|
|
134
|
+
}
|
|
135
|
+
if (!install) {
|
|
136
|
+
this.#active=active;
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
await mkdir(this.toolsDir,{recursive:true,mode:0o700});
|
|
140
|
+
const stage=await mkdtemp(join(this.toolsDir,'.install-'));
|
|
141
|
+
try {
|
|
142
|
+
if (missing) {
|
|
143
|
+
await this.fetchNative(stage,version,this.#stop.signal);
|
|
144
|
+
const dir=join(stage,'distribution');
|
|
145
|
+
await verify(join(dir,'bin','codex'));
|
|
146
|
+
await rename(dir,dest);
|
|
147
|
+
}
|
|
148
|
+
await writeFile(join(stage,'selected.json'),JSON.stringify({version})+'\n',{flag:'wx',mode:0o600});
|
|
149
|
+
await rename(join(stage,'selected.json'),join(this.toolsDir,'selected.json'));
|
|
150
|
+
this.#active=active;
|
|
151
|
+
} finally { await rm(stage,{recursive:true,force:true}); }
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
async close() {
|
|
155
|
+
this.#stop.abort();
|
|
156
|
+
await this.#pending;
|
|
157
|
+
}
|
|
158
|
+
}
|
package/src/policy.mjs
CHANGED
|
@@ -66,18 +66,24 @@ function configToml(modelBaseUrl, codeMode) {
|
|
|
66
66
|
|
|
67
67
|
// Only the administrator supplies config. The APP cannot add mounts, a cwd, environment,
|
|
68
68
|
// config layers, or executable arguments. Personal state and installer files are never mounted.
|
|
69
|
-
async function
|
|
70
|
-
const binary = await canonicalFile(
|
|
69
|
+
export async function trustedDistribution(path) {
|
|
70
|
+
const binary = await canonicalFile(path, 'Codex executable');
|
|
71
71
|
const bwrap = await canonicalFile(join(dirname(dirname(binary)), 'codex-resources', 'bwrap'), 'bundled Codex bubblewrap');
|
|
72
|
-
const codeModeHost =
|
|
72
|
+
const codeModeHost = await canonicalFile(join(dirname(binary), 'codex-code-mode-host'), 'bundled Codex Code Mode host');
|
|
73
73
|
const mounts = (await readFile('/proc/self/mountinfo', 'utf8')).trim().split('\n').map(line => {
|
|
74
74
|
const fields = line.split(' ');
|
|
75
75
|
const target = fields[4].replace(/\\([0-7]{3})/g, (_, octal) => String.fromCharCode(parseInt(octal, 8)));
|
|
76
76
|
return {target, readonly:fields[5].split(',').includes('ro')};
|
|
77
77
|
});
|
|
78
|
-
if (![binary,bwrap
|
|
78
|
+
if (![binary,bwrap,codeModeHost].every(path => protectedBinary(path,mounts))) {
|
|
79
79
|
throw Error('Codex distribution must be on a read-only mount or below /run/pappai/private');
|
|
80
80
|
}
|
|
81
|
+
return {binary,bwrap,codeModeHost};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
async function namespace(config, state, profileOwner, mcp) {
|
|
85
|
+
const {binary,bwrap,codeModeHost:helper} = await trustedDistribution(config.codexExecutablePath);
|
|
86
|
+
const codeModeHost = profileOwner ? null : helper;
|
|
81
87
|
if (typeof config.stateDir !== 'string' || !config.stateDir.startsWith('/run/pappai/private/')) {
|
|
82
88
|
throw new Error('Runner state must be below /run/pappai/private');
|
|
83
89
|
}
|
package/src/profile.mjs
CHANGED
|
@@ -11,7 +11,7 @@ const profileOperations = new Map();
|
|
|
11
11
|
// The controller gives one runner host ownership of its profile storage. Configure,
|
|
12
12
|
// remove, and native token rotation share the same queue, including errors.
|
|
13
13
|
export function withProfileLock(config, id, work) {
|
|
14
|
-
const key = JSON.stringify([config.profilesDir ?? process.env.PAPPAI_PROFILES_DIR, id]);
|
|
14
|
+
const key = JSON.stringify([config.profilesDir ?? process.env.PAPPAI_PROFILES_DIR, id, config.runnerName ?? 'codex']);
|
|
15
15
|
const previous = profileOperations.get(key) ?? Promise.resolve();
|
|
16
16
|
const operation = previous.then(work);
|
|
17
17
|
const settled = operation.catch(() => {});
|
|
@@ -25,10 +25,12 @@ async function directory(config, id, create) {
|
|
|
25
25
|
if (typeof root !== 'string' || !isAbsolute(root) || root !== resolve(root)) throw Error('Invalid profiles directory');
|
|
26
26
|
if (process.platform === 'linux' && !root.startsWith('/run/pappai/private/')) throw Error('Profiles must use the private mount');
|
|
27
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
|
-
|
|
28
|
+
if (create) await mkdir(root,{recursive:true,mode:0o700});
|
|
29
29
|
if (await realpath(root) !== root) throw Error('Invalid profiles directory');
|
|
30
30
|
let dir = root;
|
|
31
|
-
|
|
31
|
+
const name = config.runnerName ?? 'codex';
|
|
32
|
+
if (!/^[a-z][a-z0-9_-]{0,63}$/.test(name)) throw Error('Invalid runner name');
|
|
33
|
+
for (const part of [id,name]) {
|
|
32
34
|
dir = join(dir,part);
|
|
33
35
|
if (create) {
|
|
34
36
|
try { await mkdir(dir,{mode:0o700}); }
|
|
@@ -69,7 +71,7 @@ async function runProfileMethod(config, id, method, data, reader) {
|
|
|
69
71
|
if (method==='remove') {
|
|
70
72
|
try {
|
|
71
73
|
const dir=await directory(config,id,false);
|
|
72
|
-
const retired=join(dir,'..','
|
|
74
|
+
const retired=join(dir,'..','.removed-'+randomUUID());
|
|
73
75
|
await rename(dir,retired);
|
|
74
76
|
await rm(retired,{recursive:true,force:true});
|
|
75
77
|
}
|
|
@@ -91,8 +93,7 @@ async function runProfileMethod(config, id, method, data, reader) {
|
|
|
91
93
|
return {configured:true};
|
|
92
94
|
}
|
|
93
95
|
|
|
94
|
-
export function attachProfileMethods() {
|
|
95
|
-
const config=JSON.parse(process.env.PAPPAI_RUNNER_CONFIG || '{}');
|
|
96
|
+
export function attachProfileMethods(config) {
|
|
96
97
|
const requests=new Map();
|
|
97
98
|
const send=(type,payload)=>{ if (process.connected) process.send({type,payload},()=>{}); };
|
|
98
99
|
function read(id,path) {
|
package/src/tools.mjs
CHANGED
|
@@ -2,8 +2,9 @@ const string = {type:'string'}
|
|
|
2
2
|
const filter = {anyOf:[string,{type:'array',items:string}]}
|
|
3
3
|
const timeoutMs = {type:'integer',minimum:1,maximum:86400000}
|
|
4
4
|
const definitions = [
|
|
5
|
-
['
|
|
6
|
-
['help','Read the public contract of a visible node.',{node:string,
|
|
5
|
+
['discover','List workspace nodes visible to this APP.',{},[]],
|
|
6
|
+
['help','Read the public contract of a visible node.',{node:string,
|
|
7
|
+
features:{anyOf:[...filter.anyOf,{const:true}]}, description:{type:'boolean'}, schema:{type:'boolean'}, doc:{type:'boolean'}},['node']],
|
|
7
8
|
['call','Call a permitted method on a pappai node.',{node:string,method:string,data:{},version:string,timeoutMs},['node','method']],
|
|
8
9
|
['publish','Publish a declared event as this APP.',{event:string,data:{},version:string,to:filter,
|
|
9
10
|
delivery:{enum:['none','status']},timeoutMs},['event']],
|