@flinbein/pappai-runner-codex 0.1.7 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,11 +4,22 @@ This external runner delivers [pappai](https://github.com/flinbein/pappai) event
4
4
 
5
5
  ## Installation
6
6
 
7
- The runner requires a pappai controller that supports PROFILE nodes and administrator-supplied runner configuration, Linux x86_64 with working bubblewrap, Node.js 24.2+, and the native musl distribution of the Codex CLI. Compatibility tests use Codex `0.170.0`. Install the CLI separately on a persistent volume. Set `codexExecutablePath` to the executable itself.
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
- 1. Mount a persistent private volume at `/run/pappai/private`. Create `profiles` and `state` directories there, owned by the pappai process user with mode `0700`. Only the administrator should have write access to the runner code and CLI installation.
10
- 2. Install the package, for example with `npm install --prefix /run/pappai/private/runners --omit=dev @flinbein/pappai-runner-codex`.
11
- 3. Use `call` to invoke `$.runners.add` on the workspace (`node: "~"`) with the following arguments. To have the controller validate APP settings, supply the [settings schema](examples/settings-schema.json) in the `settingsSchema` field when registering the runner.
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,7 +35,9 @@ The runner requires a pappai controller that supports PROFILE nodes and administ
24
35
 
25
36
  ## Updating an existing registration
26
37
 
27
- Find the installed entry point with `$.runners.get({})` on the workspace. Wait for active Codex turns to finish, then use the administrator terminal to install the desired package version under the same npm prefix as the registered entry point. For example, for an entry point under `/run/pappai/private/runners/node_modules/`, use `npm install --prefix /run/pappai/private/runners --omit=dev --ignore-scripts --save-exact @flinbein/pappai-runner-codex@VERSION`. Replace `VERSION` with the release number.
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
 
@@ -33,14 +46,16 @@ When upgrading a persistent session from the `pappai_dir` tool on Codex CLI 0.17
33
46
  ## First call
34
47
 
35
48
  1. Call `$.profile.create` on the workspace or a TEAM with a name and permissions. Save the returned ID.
36
- 2. Sign in with the Codex CLI and place the resulting `auth.json` in a directory the caller can read. Call `codex.setup` on the PROFILE with `{"authFile":"/tmp/codex-auth.json"}`. The controller reads the regular file as the caller. After import, `codex.status({})` returns `{"configured":true}`. Use `codex.remove({})` to remove the stored connection.
49
+ 2. In the USER web terminal, run `pappai cli PROFILE_ID codex.authorize '{}'`. Open the verification URL and enter the device code in your browser. The selected Codex CLI runs in a temporary home. After sign-in, the helper calls `codex.setup` with the path to the new credentials and displays the result of `codex.status`. The USER needs network access and permission to run the command and call both methods. If you cancel during login, the PROFILE keeps its existing connection. Substitute the registration name for `codex` if needed.
37
50
  3. Call `$.app.create` on the workspace or a TEAM with `name`, `profile`, `permissions` and `source.manifest`. Use the [one-shot](examples/oneShot.json) or [persistent](examples/persistent.json) manifest.
38
51
  4. Call `$.profile.scope.set({"scope":["APP_ID"]})` on the PROFILE using the new APP's ID, then call `$.profile.enable({})`. Call `$.app.start({})` on the APP.
39
52
  5. Call `agent.execute` on the APP with `{"input":"Translate into Russian: the build passed"}`. The example method declares a string result. You can declare a different output JSON Schema for your own method. The runner validates the result before replying.
40
53
 
41
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.
42
55
 
43
- The runner supports API keys and imported ChatGPT subscription credentials. A single runner host owns the profiles directory and coordinates token refresh across its APPs. Each subscription worker receives only short-lived credentials. Give each runner host exclusive use of its profile storage. The rotation test uses the native Codex CLI and a local OAuth test server.
56
+ For a manual import, place a Codex `auth.json` in a directory the caller can read and call `codex.setup` on the PROFILE with `{"authFile":"/tmp/codex-auth.json"}`. The controller reads the regular file as the caller. Use `codex.status({})` to check the connection and `codex.remove({})` to remove it.
57
+
58
+ 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.
44
59
 
45
60
  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.
46
61
 
@@ -50,7 +65,7 @@ The executor runs in an isolated directory. Its connection to the model is a ser
50
65
 
51
66
  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.
52
67
 
53
- Shell, native Codex file tools and user configuration from the working directory are disabled. Use `run.settings` to select the model, reasoning effort and developer instructions. The administrator sets the CLI and storage paths when registering the runner.
68
+ 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.
54
69
 
55
70
  ## HTTP MCP
56
71
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flinbein/pappai-runner-codex",
3
- "version": "0.1.7",
3
+ "version": "0.1.9",
4
4
  "description": "Codex app-server runner for pappai",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -0,0 +1,59 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { lstat, mkdir, mkdtemp, realpath, rm } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ // This file is mounted by itself in the USER terminal sandbox.
7
+ export async function authorize(codex, node, runner, pappai = '/usr/local/bin/pappai') {
8
+ const root = process.env.PAPPAI_CLI_TMP;
9
+ if (!root?.startsWith('/tmp/') || await realpath(root) !== root || !(await lstat(root)).isDirectory()) {
10
+ throw Error('Missing private CLI temporary directory');
11
+ }
12
+ const home = await mkdtemp(join(root,'codex-'));
13
+ let child, cancelled = false;
14
+ const cancel = () => {
15
+ cancelled = true;
16
+ child?.kill('SIGTERM');
17
+ };
18
+ function run(command, args, env, stdio, failure) {
19
+ if (cancelled) throw Error('Authorization cancelled');
20
+ return new Promise((resolve,reject) => {
21
+ child = spawn(command,args,{cwd:home,env,stdio});
22
+ child.once('error',() => reject(Error(failure)));
23
+ child.once('close',(code) => {
24
+ child = undefined;
25
+ if (cancelled) reject(Error('Authorization cancelled'));
26
+ else if (code !== 0) reject(Error(failure));
27
+ else resolve();
28
+ });
29
+ });
30
+ }
31
+ process.on('SIGINT',cancel);
32
+ process.on('SIGTERM',cancel);
33
+ try {
34
+ const tmp = join(home,'tmp');
35
+ await mkdir(tmp,{mode:0o700});
36
+ const env = {HOME:home,CODEX_HOME:home,TMPDIR:tmp,PATH:'/usr/local/bin:/usr/bin:/bin',RUST_LOG:'off'};
37
+ await run(codex,['--no-daemon','-c','cli_auth_credentials_store="file"','login','--device-auth'],
38
+ env,'inherit','Codex device login failed');
39
+ const authFile = join(home,'auth.json');
40
+ if (!(await lstat(authFile)).isFile()) throw Error('Codex did not save credentials');
41
+ await run(pappai,['call',node,runner+'.setup',JSON.stringify({authFile})],
42
+ process.env,['ignore','ignore','inherit'],'Could not import Codex credentials');
43
+ await run(pappai,['call',node,runner+'.status','{}'],
44
+ process.env,'inherit','Could not read Codex connection status');
45
+ } finally {
46
+ try { await rm(home,{recursive:true,force:true}); }
47
+ finally {
48
+ process.off('SIGTERM',cancel);
49
+ process.off('SIGINT',cancel);
50
+ }
51
+ }
52
+ }
53
+
54
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
55
+ authorize(...process.argv.slice(2,5)).catch(error => {
56
+ console.error(error.code ? 'Codex authorization file unavailable' : error.message);
57
+ process.exitCode = 1;
58
+ });
59
+ }
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' || !/\/0\.170\.0(?:\s|$)/.test(userAgent)) throw Error('Codex CLI 0.170.0 is required')
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,53 @@
1
1
  import { RunnerHost } from './host.mjs'
2
2
  import { prepareWorker } from './policy.mjs'
3
3
  import { attachProfileMethods } from './profile.mjs'
4
+ import { prepareProfileCli, profileCli } from './profile-cli.mjs'
5
+ import { join } from 'node:path'
6
+ import { CodexInstallation, runnerMethods } from './installation.mjs'
7
+ import settingsSchema from '../examples/settings-schema.json' with {type:'json'}
4
8
 
5
9
  if (typeof process.send !== 'function') throw Error('Start the Codex runner through the pappai runner registry')
6
10
  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},() => {})
11
+ config.runnerName = process.env.PAPPAI_RUNNER_NAME || 'codex'
12
+ if (!/^[a-z][a-z0-9_-]{0,63}$/.test(config.runnerName)) throw Error('Invalid runner name')
13
+ config.stateDir ??= '/run/pappai/private/state'
14
+ if (config.runnerName !== 'codex') config.stateDir=join(config.stateDir,'instances',config.runnerName)
15
+ const installation = new CodexInstallation({
16
+ toolsDir:process.env.PAPPAI_RUNNER_DIR ? join(process.env.PAPPAI_RUNNER_DIR,'tools') : undefined,
17
+ configuredPath:config.codexExecutablePath,
10
18
  })
19
+ function send(type,payload) {
20
+ if (process.connected) process.send({type,payload},() => {})
21
+ }
22
+ const host = new RunnerHost(config,async (config,job) => {
23
+ const codexExecutablePath=await installation.executable()
24
+ return prepareWorker({...config,codexExecutablePath},job)
25
+ },send)
26
+ async function runnerCall({id,method,data}) {
27
+ try {
28
+ if (method==='@cli.prepare') {
29
+ const result=await prepareProfileCli(data,installation,config.runnerName)
30
+ return send('runnerReply',{id,result})
31
+ }
32
+ if (!Object.hasOwn(runnerMethods,method)) throw Error('Unknown runner method')
33
+ if (!data || typeof data!=='object' || Array.isArray(data) ||
34
+ Object.keys(data).some(key=>method!=='installCodex' || key!=='version')) throw Error('Invalid runner method arguments')
35
+ const result=method==='getVersion' ? installation.status() : await installation.install(data.version)
36
+ send('runnerReply',{id,result})
37
+ } catch (error) { send('runnerReply',{id,error:error.message}) }
38
+ }
11
39
  async function close() {
12
- await host.close()
40
+ await Promise.all([installation.close(),host.close()])
13
41
  if (process.connected) process.disconnect()
14
42
  }
15
43
  process.on('message', message => {
16
44
  if (message?.type === 'close') void close()
45
+ else if (message?.type === 'runnerCall') void runnerCall(message)
17
46
  else if (message) host.receive(message)
18
47
  })
19
- process.on('disconnect',() => { void host.close() })
48
+ process.on('disconnect',close)
20
49
  process.on('SIGTERM',close)
21
50
  process.on('SIGINT',close)
51
+ send('runnerReady',{kind:'codex',settingsSchema,methods:runnerMethods,profileCli})
52
+ attachProfileMethods(config)
53
+ 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 namespace(config, state, profileOwner, mcp) {
70
- const binary = await canonicalFile(config.codexExecutablePath, 'Codex executable');
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 = profileOwner ? null : await canonicalFile(join(dirname(binary), 'codex-code-mode-host'), 'bundled Codex Code Mode host');
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,...(codeModeHost ? [codeModeHost] : [])].every(path => protectedBinary(path,mounts))) {
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
  }
@@ -0,0 +1,22 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ export const profileCli = {
4
+ authorize: {
5
+ description: 'Connect this PROFILE to ChatGPT using a device code.',
6
+ doc: 'Open the verification URL in your browser and enter the code shown in this terminal. After sign-in, this command calls setup and status on the selected PROFILE as the current USER. The USER needs network access and permission for both methods.',
7
+ version: '1',
8
+ schema: {input:{type:'object', properties:{}, additionalProperties:false}},
9
+ },
10
+ };
11
+
12
+ export async function prepareProfileCli(data, installation, runnerName) {
13
+ if (data?.feature !== 'authorize' || typeof data.node !== 'string' || !data.node ||
14
+ !data.input || typeof data.input !== 'object' || Array.isArray(data.input) ||
15
+ Object.keys(data.input).length || Object.keys(data).some(key => !['feature','node','input'].includes(key))) {
16
+ throw Error('Invalid PROFILE authorization command');
17
+ }
18
+ return {
19
+ files:[fileURLToPath(new URL('./authorize.mjs',import.meta.url)), await installation.executable()],
20
+ argv:['/usr/local/bin/node','/run/pappai/cli/0','/run/pappai/cli/1',data.node,runnerName],
21
+ };
22
+ }
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
- // The operator provisions the canonical root. Never follow a tenant-chosen link.
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
- for (const part of [id,'codex']) {
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,'..','codex-removed-'+randomUUID());
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) {