@flinbein/pappai-runner-codex 0.1.8 → 0.2.10

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
@@ -6,7 +6,7 @@ This external runner delivers [pappai](https://github.com/flinbein/pappai) event
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
- 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.
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. At startup the runner publishes the [schema for a complete named run variant](src/run-configuration.mjs), its persistent methods and the PROFILE terminal method.
10
10
 
11
11
  Administrators can call these methods on the workspace (`~`). Substitute the installation name for `codex`.
12
12
 
@@ -41,25 +41,33 @@ For a manually installed runner, find its entry point with `$.runners.get({})` o
41
41
 
42
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.
43
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.
44
+ When upgrading the workspace tools of a persistent session 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 installs the current tool catalog 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
45
 
46
46
  ## First call
47
47
 
48
- 1. Call `$.profile.create` on the workspace or a TEAM with a name and permissions. Save the returned ID.
49
- 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.
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.
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.
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.
48
+ 1. Call `$.children.createProfile` on the workspace or a TEAM with a name and permissions. Save the returned ID.
49
+ 2. In the USER web terminal, run `pappai cli --terminal 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.
50
+ 3. Call `$.children.createApp` 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.
51
+ 4. Call `$.profile.scope.set({"scope":["APP_ID"]})` on the PROFILE using the new APP's ID, then call `$.lifecycle.start({})`. Call `$.lifecycle.start({})` on the APP.
52
+ 5. On the one-shot example, call `agent.execute` 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.
53
53
 
54
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.
55
55
 
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
+
56
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.
57
59
 
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.
60
+ Each key in `run` names a complete variant with `settings` and `executors`. In a one-shot variant, define methods under `settings.methods` with `inputSchema` and `outputSchema`. The model receives the JSON input as its user message. Each invocation uses its own temporary thread. To process subscribed events, add `settings.events`, for example `{"instructions":"Summarize each incident."}`. This one handler receives the event name, source, subscription and data. Without it the runner acknowledges events without starting a model turn.
61
+
62
+ Set `model`, `effort` and `instructions` in settings for APP defaults. Each method or event handler can override individual fields. For example, a method can set `"instructions":{"select":"/prompt","from":"options"}`. An explicitly empty instructions string clears the default for that handler. The controller resolves Patterns in the context of the assignment.
63
+
64
+ A persistent variant processes events sequentially and resumes its stored conversation. Call `agent.sendMessage({"input":"Summarize the latest event."})` to queue a message. The method returns `{"accepted":true}` after queueing a `$.session.message` event. Its data contains the caller ID in `sender` and the original text in `input`. Read replies using `agent.getHistory` with an optional cursor and limit. Use `agent.interrupt` during an active turn. The runner supplies the persistent methods automatically.
59
65
 
60
66
  ## Executor permissions
61
67
 
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.
68
+ The executor runs in an isolated directory. Its connection to the model is a service channel. For workspace operations, the model receives the `pappai_me`, `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.
69
+
70
+ To use a terminal or pipe method, call `pappai_stream_open({node,method,input,mode})` with a mode advertised by help. Pass the returned `id` to `pappai_stream_write` and `pappai_stream_read`. Chunks contain base64 data, and reads identify the output channel. For a pipe, call `pappai_stream_close_input` after writing stdin. Read until the exit code arrives. Use `pappai_stream_resize` for terminal dimensions and `pappai_stream_cancel` to end an unfinished call.
63
71
 
64
72
  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.
65
73
 
@@ -1,15 +1,13 @@
1
1
  {
2
2
  "run": {
3
- "type": "codex",
4
- "settings": {
5
- "developerInstructions": "Complete the task in data.input. Reply in the user's language.",
6
- "features": {
7
- "agent.execute": {
8
- "type": "method",
9
- "description": "Complete a text assignment",
10
- "version": "1",
11
- "schema": {
12
- "input": {
3
+ "asAgent": {
4
+ "settings": {
5
+ "instructions": "Complete the assignment in the input field. Reply in the user's language.",
6
+ "methods": {
7
+ "agent.execute": {
8
+ "description": "Complete a text assignment",
9
+ "version": "1",
10
+ "inputSchema": {
13
11
  "type": "object",
14
12
  "properties": {
15
13
  "input": {
@@ -22,17 +20,17 @@
22
20
  ],
23
21
  "additionalProperties": false
24
22
  },
25
- "output": {
23
+ "outputSchema": {
26
24
  "type": "string"
27
25
  }
28
26
  }
29
27
  }
28
+ },
29
+ "executors": {
30
+ "mode": "oneShot",
31
+ "poolSize": 2,
32
+ "maxLifetimeMs": 120000
30
33
  }
31
34
  }
32
- },
33
- "executors": {
34
- "mode": "oneShot",
35
- "poolSize": 2,
36
- "maxLifetimeMs": 120000
37
35
  }
38
36
  }
@@ -1,69 +1,19 @@
1
1
  {
2
2
  "run": {
3
- "type": "codex",
4
- "settings": {
5
- "developerInstructions": "Complete the task in data.input. Reply in the user's language.",
6
- "features": {
7
- "agent.execute": {
8
- "type": "method",
9
- "description": "Complete a text assignment",
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": "Return a page of conversation history",
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": "Interrupt the active turn",
55
- "schema": {
56
- "input": {
57
- "type": "object",
58
- "additionalProperties": false
59
- }
60
- }
61
- }
3
+ "asAgent": {
4
+ "settings": {
5
+ "instructions": "Read each workspace event and summarize the change."
6
+ },
7
+ "executors": {
8
+ "mode": "persistent",
9
+ "idleTimeoutMs": 300000
62
10
  }
63
11
  }
64
12
  },
65
- "executors": {
66
- "mode": "persistent",
67
- "idleTimeoutMs": 300000
68
- }
13
+ "subscriptions": [
14
+ {
15
+ "node": ".",
16
+ "events": "$.app.restarted"
17
+ }
18
+ ]
69
19
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flinbein/pappai-runner-codex",
3
- "version": "0.1.8",
3
+ "version": "0.2.10",
4
4
  "description": "Codex app-server runner for pappai",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -8,9 +8,19 @@ import { DatabaseSync } from 'node:sqlite'
8
8
  import { pathToFileURL } from 'node:url'
9
9
  import { dynamicTools } from '../src/tools.mjs'
10
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
- ]))
11
+ const workspaceNames = new Set(['pappai_dir',...dynamicTools.map(tool => tool.name)])
12
+
13
+ function updatedCatalog(tools) {
14
+ const base = tools?.find(tool => !tool.namespace && ['pappai_dir','pappai_discover'].includes(tool.name))
15
+ if (!base) return
16
+ const keep = tools.filter(tool => tool.namespace || !workspaceNames.has(tool.name))
17
+ const updated = dynamicTools.map(({name,description,inputSchema}) => {
18
+ const original = tools.find(tool => !tool.namespace && tool.name === name) ?? base
19
+ return {...original,name,description,...(Object.hasOwn(original,'input_schema') ? {input_schema:inputSchema} : {inputSchema})}
20
+ })
21
+ const result = [...keep,...updated]
22
+ return JSON.stringify(result) === JSON.stringify(tools) ? undefined : result
23
+ }
14
24
 
15
25
  async function upgradeRollout(file) {
16
26
  // Preserve the conversation byte for byte after the session metadata line.
@@ -28,12 +38,9 @@ async function upgradeRollout(file) {
28
38
  const record = JSON.parse(header.subarray(0,end))
29
39
  const tools = record.payload?.dynamic_tools
30
40
  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
- }
41
+ const catalog = updatedCatalog(tools)
42
+ if (!catalog) return 0
43
+ record.payload.dynamic_tools = catalog
37
44
  const temporary = join(dirname(file),'.upgrade-' + randomUUID())
38
45
  const target = await open(temporary,'wx',0o600)
39
46
  try {
@@ -56,12 +63,25 @@ export async function upgradeThreadTools(state) {
56
63
  const db = new DatabaseSync(file)
57
64
  try {
58
65
  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')
66
+ const existing = db.prepare("SELECT * FROM thread_dynamic_tools WHERE name IN ('pappai_dir','pappai_discover') AND namespace IS NULL").all()
67
+ const rowsFor = db.prepare('SELECT * FROM thread_dynamic_tools WHERE thread_id=? ORDER BY position')
68
+ const update = db.prepare('UPDATE thread_dynamic_tools SET name=?,description=?,input_schema=? WHERE thread_id=? AND position=?')
69
+ for (const row of existing) {
70
+ const rows = rowsFor.all(row.thread_id)
71
+ let position = rows.at(-1).position
72
+ const columns = Object.keys(row)
73
+ const insert = db.prepare('INSERT INTO thread_dynamic_tools (' + columns.join(',') + ') VALUES (' + columns.map(() => '?').join(',') + ')')
74
+ for (const tool of dynamicTools) {
75
+ const old = rows.find(entry => !entry.namespace && (entry.name === tool.name ||
76
+ (entry.name === 'pappai_dir' && tool.name === 'pappai_discover')))
77
+ const schema = JSON.stringify(tool.inputSchema)
78
+ if (old) {
79
+ if (old.name !== tool.name || old.description !== tool.description || JSON.stringify(JSON.parse(old.input_schema)) !== schema)
80
+ update.run(tool.name,tool.description,schema,row.thread_id,old.position)
81
+ } else {
82
+ const entry = {...row,position:++position,name:tool.name,description:tool.description,input_schema:schema}
83
+ insert.run(...columns.map(key => entry[key]))
84
+ }
65
85
  }
66
86
  }
67
87
  db.exec('COMMIT')
@@ -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/host.mjs CHANGED
@@ -31,19 +31,30 @@ async function saveThread(file,threadId) {
31
31
  }
32
32
  }
33
33
 
34
- function turnRequest(threadId,item,effort) {
34
+ function hasSchemaReferences(schema) {
35
+ return /"\$(?:ref|dynamicRef|id|schema)"\s*:/.test(JSON.stringify(schema))
36
+ }
37
+
38
+ function schemaInstructions(schema) {
39
+ return 'Return only a JSON object with a result property matching this JSON Schema: ' + JSON.stringify(schema)
40
+ }
41
+
42
+ function turnRequest(threadId,item,settings,effort) {
35
43
  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)}]
44
+ const named = item.method && settings.methods && Object.hasOwn(settings.methods,item.method)
45
+ if (item.method && (settings.eventSession || (settings.methods || settings.events) && !named))
46
+ throw Error('Unknown Codex method')
47
+ const input = [{type:'text',text:JSON.stringify(named ? item.data ?? null : record)}]
37
48
  const params = {threadId,input,environments:[],...(effort && {effort})}
38
49
  let validate
39
- if (item.method && item.outputSchema !== undefined) {
40
- const schema = item.outputSchema
50
+ const schema = named ? settings.methods[item.method].outputSchema : item.outputSchema
51
+ if (item.method && schema !== undefined) {
41
52
  validate = ajv.compile(schema)
42
53
  if (typeof schema === 'object') ajv.removeSchema(schema)
43
54
  // A root-relative reference must keep its original schema resource. Give
44
55
  // 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)})
56
+ if (hasSchemaReferences(schema)) {
57
+ if (!named) input.push({type:'text',text:schemaInstructions(schema)})
47
58
  } else {
48
59
  params.outputSchema = {type:'object',properties:{result:schema},required:['result'],additionalProperties:false}
49
60
  }
@@ -173,15 +184,30 @@ class Worker {
173
184
  const lifetime = this.job.maxLifetimeMs && setTimeout(() => this.stop('Codex executor lifetime exceeded'),this.job.maxLifetimeMs)
174
185
  try {
175
186
  if (!this.job.profileId) throw Error('Codex requires an assigned profile')
187
+ const settings = this.job.settings
188
+ if (!this.persistent && !this.job.method && settings.methods && !settings.events) {
189
+ this.#started = true
190
+ this.emit('started')
191
+ if (this.job.holdFirst) await this.#incoming.promise
192
+ if (!this.#stopping) this.emit('written',{workerId:this.job.id})
193
+ return
194
+ }
176
195
  spec = await prepare(config,this.job)
177
196
  if (this.#stopping) return
178
197
  const client = this.#client = new AppServer(spec,error => this.stop(error.message),params => this.#tool(params))
179
198
  await client.initialize()
180
199
  if (this.#stopping) return
181
- const settings = this.job.settings
200
+ const handler = this.persistent ? undefined : this.job.method
201
+ ? settings.methods?.[this.job.method] : settings.events
202
+ const model = handler?.model ?? settings.model
203
+ const effort = handler?.effort ?? settings.effort
204
+ let instructions = handler?.instructions ?? settings.instructions ?? settings.developerInstructions
205
+ if (handler && hasSchemaReferences(handler.outputSchema)) {
206
+ instructions = [instructions,schemaInstructions(handler.outputSchema)].filter(Boolean).join('\n')
207
+ }
182
208
  const params = {
183
- ...(settings.model && {model:settings.model}),
184
- ...(settings.developerInstructions && {developerInstructions:settings.developerInstructions}),
209
+ ...(model && {model}),
210
+ ...(instructions !== undefined && {developerInstructions:instructions}),
185
211
  ...spec.threadParams,
186
212
  }
187
213
  let stored = this.persistent && await savedThread(spec.stateFile)
@@ -209,7 +235,7 @@ class Worker {
209
235
  } else if (item.method === 'agent.interrupt') {
210
236
  throw Error('No active Codex turn')
211
237
  } else if (this.#cancelled !== item.id) {
212
- const {params:request,validate} = turnRequest(threadId,item,settings.effort)
238
+ const {params:request,validate} = turnRequest(threadId,item,settings,effort)
213
239
  const record = await client.turn(request,async () => {
214
240
  if (this.#cancelled === item.id) this.#interrupt()
215
241
  if (this.persistent && !stored) {
package/src/index.mjs CHANGED
@@ -1,8 +1,10 @@
1
1
  import { RunnerHost } from './host.mjs'
2
2
  import { prepareWorker } from './policy.mjs'
3
3
  import { attachProfileMethods } from './profile.mjs'
4
+ import { prepareProfileCli, profileTerminalMethods } from './profile-cli.mjs'
4
5
  import { join } from 'node:path'
5
6
  import { CodexInstallation, runnerMethods } from './installation.mjs'
7
+ import { runConfigurationSchema, persistentFeatures } from './run-configuration.mjs'
6
8
  import settingsSchema from '../examples/settings-schema.json' with {type:'json'}
7
9
 
8
10
  if (typeof process.send !== 'function') throw Error('Start the Codex runner through the pappai runner registry')
@@ -24,6 +26,10 @@ const host = new RunnerHost(config,async (config,job) => {
24
26
  },send)
25
27
  async function runnerCall({id,method,data}) {
26
28
  try {
29
+ if (method==='@cli.prepare') {
30
+ const result=await prepareProfileCli(data,installation,config.runnerName)
31
+ return send('runnerReply',{id,result})
32
+ }
27
33
  if (!Object.hasOwn(runnerMethods,method)) throw Error('Unknown runner method')
28
34
  if (!data || typeof data!=='object' || Array.isArray(data) ||
29
35
  Object.keys(data).some(key=>method!=='installCodex' || key!=='version')) throw Error('Invalid runner method arguments')
@@ -43,6 +49,6 @@ process.on('message', message => {
43
49
  process.on('disconnect',close)
44
50
  process.on('SIGTERM',close)
45
51
  process.on('SIGINT',close)
46
- send('runnerReady',{kind:'codex',settingsSchema,methods:runnerMethods})
52
+ send('runnerReady',{kind:'codex',settingsSchema,runConfigurationSchema,persistentFeatures,methods:runnerMethods,profileTerminalMethods})
47
53
  attachProfileMethods(config)
48
54
  void installation.start().catch(()=>{}) // getVersion and waiting workers expose the issue
@@ -0,0 +1,23 @@
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ export const profileTerminalMethods = {
4
+ authorize: {
5
+ type:'method', terminal:true,
6
+ description: 'Connect this PROFILE to ChatGPT using a device code.',
7
+ 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.',
8
+ version: '1',
9
+ schema: {input:{type:'object', properties:{}, additionalProperties:false}},
10
+ },
11
+ };
12
+
13
+ export async function prepareProfileCli(data, installation, runnerName) {
14
+ if (data?.feature !== 'authorize' || typeof data.node !== 'string' || !data.node ||
15
+ !data.input || typeof data.input !== 'object' || Array.isArray(data.input) ||
16
+ Object.keys(data.input).length || Object.keys(data).some(key => !['feature','node','input'].includes(key))) {
17
+ throw Error('Invalid PROFILE authorization command');
18
+ }
19
+ return {
20
+ files:[fileURLToPath(new URL('./authorize.mjs',import.meta.url)), await installation.executable()],
21
+ argv:['/usr/local/bin/node','/run/pappai/cli/0','/run/pappai/cli/1',data.node,runnerName],
22
+ };
23
+ }
@@ -0,0 +1,45 @@
1
+ import settingsSchema from '../examples/settings-schema.json' with {type:'json'}
2
+
3
+ const object = (properties,required=[]) => ({type:'object',properties,required,additionalProperties:false})
4
+ const string = {type:'string'}
5
+ const schema = {anyOf:[{type:'object'},{type:'boolean'}]}
6
+ const duration = {type:'integer',minimum:1,maximum:2147483647}
7
+ const patternRef = {$ref:'#/$defs/pattern'}
8
+ const pointer = {type:'string',pattern:'^(?:/(?:[^~/]|~[01])*)*$'}
9
+ const pattern = {anyOf:[string,
10
+ object({value:patternRef,replace:{type:'object',additionalProperties:patternRef}},['value','replace']),
11
+ object({select:pointer,from:{enum:['options','parameters']}},['select','from']),
12
+ object({select:pointer,from:{const:'configuration'},resolve:{const:true}},['select','from']),
13
+ ]}
14
+ const patterned = literal => ({anyOf:[literal,{type:'object',allOf:[patternRef]}]})
15
+ const modelSettings = {
16
+ model:patterned(settingsSchema.properties.model),
17
+ effort:patterned(settingsSchema.properties.effort),
18
+ instructions:patternRef,
19
+ }
20
+ const common = {...modelSettings,mcp:settingsSchema.properties.mcp}
21
+ const method = object({
22
+ ...modelSettings,
23
+ description:{type:'string',maxLength:255},version:{type:'string',minLength:1},doc:string,
24
+ inputSchema:schema,outputSchema:schema,
25
+ },['inputSchema','outputSchema'])
26
+ const methods = {type:'object',minProperties:1,maxProperties:512,propertyNames:{
27
+ pattern:'^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*$',not:{enum:['agent.getHistory','agent.interrupt','agent.sendMessage']},
28
+ },additionalProperties:method}
29
+ const oneShotSettings = {...object({...common,methods,events:object(modelSettings)}),
30
+ anyOf:[{properties:{methods:{}},required:['methods']},{properties:{events:{}},required:['events']}]}
31
+ const variant = (settings,executors) => object({settings,executors},['settings','executors'])
32
+ export const runConfigurationSchema = {
33
+ type:'object',$defs:{pattern},oneOf:[
34
+ variant(oneShotSettings,object({mode:{const:'oneShot'},poolSize:{type:'integer',minimum:1,maximum:20},maxLifetimeMs:duration},['mode'])),
35
+ variant(object(common),object({mode:{const:'persistent'},idleTimeoutMs:{anyOf:[duration,{type:'null'}]},
36
+ maxRestarts:{type:'integer',minimum:0,maximum:10}},['mode'])),
37
+ ],
38
+ }
39
+ export const persistentFeatures = {
40
+ 'agent.sendMessage':{type:'method',version:'1',description:'Queue a message for this agent.',
41
+ schema:{input:object({input:string},['input']),output:object({accepted:{const:true}},['accepted'])}},
42
+ 'agent.getHistory':{type:'method',version:'1',description:'Read a page of user messages and final replies.',
43
+ schema:{input:object({cursor:{type:'string',maxLength:4096},limit:{type:'integer',minimum:1,maximum:20}})}},
44
+ 'agent.interrupt':{type:'method',version:'1',description:'Interrupt the current turn.',schema:{input:object({})}},
45
+ }
package/src/tools.mjs CHANGED
@@ -1,16 +1,25 @@
1
1
  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
+ const size = {type:'integer',minimum:1,maximum:1000}
5
+ const streamId = {id:string}
4
6
  const definitions = [
5
- ['discover','List workspace nodes visible to this APP.',{},[]],
6
- ['help','Read the public contract of a visible node.',{node:string,
7
+ ['me','Return the id, parentId, type and name of the APP making this request.',{},[]],
8
+ ['discover','List workspace nodes that this APP can discover. Use their IDs with pappai_help.',{},[]],
9
+ ['help','Read the public contract of a visible node. Set features to true for all names, or select names and request their schema and documentation.',{node:string,
7
10
  features:{anyOf:[...filter.anyOf,{const:true}]}, description:{type:'boolean'}, schema:{type:'boolean'}, doc:{type:'boolean'}},['node']],
8
- ['call','Call a permitted method on a pappai node.',{node:string,method:string,data:{},version:string,timeoutMs},['node','method']],
9
- ['publish','Publish a declared event as this APP.',{event:string,data:{},version:string,to:filter,
11
+ ['call','Invoke a permitted JSON method on a workspace node as this APP. Use pappai_stream_open for terminal or pipe methods.',{node:string,method:string,data:{},version:string,timeoutMs},['node','method']],
12
+ ['publish','Publish an application event declared by this APP. Only event names that do not start with "$." can be published.',{event:string,data:{},version:string,to:filter,
10
13
  delivery:{enum:['none','status']},timeoutMs},['event']],
14
+ ['stream_open','Start a permitted method in an advertised stream mode. Returns the call id.',{node:string,method:string,input:{},mode:{enum:['pipe','terminal']},cols:size,rows:size},['node','method','mode'],'stream.open'],
15
+ ['stream_read','Wait for an output chunk {channel,data} in base64, or {exitCode} when the call finishes.',streamId,['id'],'stream.read'],
16
+ ['stream_write','Write a base64-encoded chunk to the call input.',{...streamId,data:{type:'string',maxLength:48*1024}},['id','data'],'stream.write'],
17
+ ['stream_close_input','Finish writing stdin to a pipe call. Output can still be read.',streamId,['id'],'stream.closeInput'],
18
+ ['stream_resize','Set the terminal size in character cells.',{...streamId,cols:size,rows:size},['id','cols','rows'],'stream.resize'],
19
+ ['stream_cancel','Cancel the active call and release its resources.',streamId,['id'],'stream.cancel'],
11
20
  ]
12
21
 
13
22
  export const dynamicTools = definitions.map(([name,description,properties,required]) => ({
14
23
  type:'function',name:'pappai_' + name,description,inputSchema:{type:'object',properties,required,additionalProperties:false},
15
24
  }))
16
- export const toolMethods = new Map(definitions.map(([name]) => ['pappai_' + name,name]))
25
+ export const toolMethods = new Map(definitions.map(([name,,,,request]) => ['pappai_' + name,request ?? name]))