@flinbein/pappai-runner-codex 0.1.9 → 0.2.11

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,15 +41,15 @@ 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. 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.
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
 
@@ -57,11 +57,23 @@ For a manual import, place a Codex `auth.json` in a directory the caller can rea
57
57
 
58
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.
59
59
 
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.
60
+ Each key in `run` names a complete variant with `settings` and `executors`. In a one-shot variant, define methods under `settings.methods` with optional `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.
65
+
66
+ ## Manifest templates
67
+
68
+ In the APP manifest menu, **Persistent agent** edits instructions, model and reasoning effort. **Agent tasks** configures independent methods, their optional JSON schemas and an optional incoming-event handler. The runner obtains models and supported efforts from the installed CLI's `model/list` response and caches the catalog for one minute. **Default** omits the setting. If the catalog is unavailable, only Default is offered.
69
+
70
+ The form reads the manifest with the initiator's permissions. Applying saves inline JSON. A compatible named variant retains its executor settings and MCP configuration. The form warns when converting Pattern instructions to plain text. To inspect a running worker's live diagnostics, use the APP's `$.app.executors.stderr` pipe method.
61
71
 
62
72
  ## Executor permissions
63
73
 
64
- 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.
74
+ 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.
75
+
76
+ 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.
65
77
 
66
78
  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.
67
79
 
@@ -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
  }
@@ -14,7 +14,9 @@
14
14
  "low",
15
15
  "medium",
16
16
  "high",
17
- "xhigh"
17
+ "xhigh",
18
+ "max",
19
+ "ultra"
18
20
  ]
19
21
  },
20
22
  "developerInstructions": { "type": "string" },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flinbein/pappai-runner-codex",
3
- "version": "0.1.9",
3
+ "version": "0.2.11",
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')
package/src/client.mjs CHANGED
@@ -23,7 +23,7 @@ export class AppServer {
23
23
  #serverRequests = new Set()
24
24
  #fail
25
25
 
26
- constructor({executable,args,cwd,env,sessionAuth},onLoss,onTool) {
26
+ constructor({executable,args,cwd,env,sessionAuth},onLoss,onTool,onStderr) {
27
27
  this.#auth = sessionAuth
28
28
  this.#tool = onTool
29
29
  const child = this.#child = spawn(executable,args,{cwd,env,stdio:'pipe',windowsHide:true})
@@ -37,9 +37,8 @@ export class AppServer {
37
37
  if (!this.#closing) onLoss(error)
38
38
  }
39
39
  this.#fail = fail
40
- // stderr may contain provider data. Drain it without exposing credentials,
41
- // prompts or installation paths through a user-visible executor error.
42
- child.stderr.resume()
40
+ if (onStderr) child.stderr.on('data',onStderr)
41
+ else child.stderr.resume()
43
42
  child.stdin.on('error',() => fail(Error('Codex input closed')))
44
43
  child.once('error',() => fail(Error('Could not launch Codex app-server')))
45
44
  child.once('exit',(code,signal) => {
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,31 @@ 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
- const client = this.#client = new AppServer(spec,error => this.stop(error.message),params => this.#tool(params))
197
+ const client = this.#client = new AppServer(spec,error => this.stop(error.message),params => this.#tool(params),
198
+ bytes => this.emit('stderr',{data:bytes.toString('base64')}))
179
199
  await client.initialize()
180
200
  if (this.#stopping) return
181
- const settings = this.job.settings
201
+ const handler = this.persistent ? undefined : this.job.method
202
+ ? settings.methods?.[this.job.method] : settings.events
203
+ const model = handler?.model ?? settings.model
204
+ const effort = handler?.effort ?? settings.effort
205
+ let instructions = handler?.instructions ?? settings.instructions ?? settings.developerInstructions
206
+ if (handler && hasSchemaReferences(handler.outputSchema)) {
207
+ instructions = [instructions,schemaInstructions(handler.outputSchema)].filter(Boolean).join('\n')
208
+ }
182
209
  const params = {
183
- ...(settings.model && {model:settings.model}),
184
- ...(settings.developerInstructions && {developerInstructions:settings.developerInstructions}),
210
+ ...(model && {model}),
211
+ ...(instructions !== undefined && {developerInstructions:instructions}),
185
212
  ...spec.threadParams,
186
213
  }
187
214
  let stored = this.persistent && await savedThread(spec.stateFile)
@@ -209,7 +236,7 @@ class Worker {
209
236
  } else if (item.method === 'agent.interrupt') {
210
237
  throw Error('No active Codex turn')
211
238
  } else if (this.#cancelled !== item.id) {
212
- const {params:request,validate} = turnRequest(threadId,item,settings.effort)
239
+ const {params:request,validate} = turnRequest(threadId,item,settings,effort)
213
240
  const record = await client.turn(request,async () => {
214
241
  if (this.#cancelled === item.id) this.#interrupt()
215
242
  if (this.persistent && !stored) {
package/src/index.mjs CHANGED
@@ -1,9 +1,11 @@
1
1
  import { RunnerHost } from './host.mjs'
2
- import { prepareWorker } from './policy.mjs'
2
+ import { catalogModels, prepareWorker } from './policy.mjs'
3
3
  import { attachProfileMethods } from './profile.mjs'
4
- import { prepareProfileCli, profileCli } from './profile-cli.mjs'
4
+ import { prepareProfileCli, profileTerminalMethods } from './profile-cli.mjs'
5
5
  import { join } from 'node:path'
6
6
  import { CodexInstallation, runnerMethods } from './installation.mjs'
7
+ import { runConfigurationSchema, persistentFeatures } from './run-configuration.mjs'
8
+ import { templates, templateForm, generateTemplate } from './templates.mjs'
7
9
  import settingsSchema from '../examples/settings-schema.json' with {type:'json'}
8
10
 
9
11
  if (typeof process.send !== 'function') throw Error('Start the Codex runner through the pappai runner registry')
@@ -23,8 +25,24 @@ const host = new RunnerHost(config,async (config,job) => {
23
25
  const codexExecutablePath=await installation.executable()
24
26
  return prepareWorker({...config,codexExecutablePath},job)
25
27
  },send)
28
+ let cachedModels
29
+ async function modelChoices() {
30
+ if (installation.status().status!=='ready') return []
31
+ const path=await installation.executable()
32
+ if (!cachedModels || cachedModels.path!==path || cachedModels.until<Date.now()) {
33
+ const request=catalogModels({...config,codexExecutablePath:path}).catch(()=>[])
34
+ cachedModels={path,until:Date.now()+60_000,request}
35
+ }
36
+ return cachedModels.request
37
+ }
26
38
  async function runnerCall({id,method,data}) {
27
39
  try {
40
+ if (method==='@template.createForm' || method==='@template.generate') {
41
+ const models=await modelChoices()
42
+ const result=method==='@template.createForm' ? templateForm(data.template,data.context,models) :
43
+ generateTemplate(data.template,data.formData,data.context,models)
44
+ return send('runnerReply',{id,result})
45
+ }
28
46
  if (method==='@cli.prepare') {
29
47
  const result=await prepareProfileCli(data,installation,config.runnerName)
30
48
  return send('runnerReply',{id,result})
@@ -48,6 +66,7 @@ process.on('message', message => {
48
66
  process.on('disconnect',close)
49
67
  process.on('SIGTERM',close)
50
68
  process.on('SIGINT',close)
51
- send('runnerReady',{kind:'codex',settingsSchema,methods:runnerMethods,profileCli})
69
+ send('runnerReady',{kind:'codex',settingsSchema,runConfigurationSchema,persistentFeatures,methods:runnerMethods,profileTerminalMethods,
70
+ templates:templates.map(t=>({...t,readManifest:true}))})
52
71
  attachProfileMethods(config)
53
72
  void installation.start().catch(()=>{}) // getVersion and waiting workers expose the issue
package/src/policy.mjs CHANGED
@@ -148,6 +148,31 @@ export async function rotateProfile(config, authPath, endpoint = 'https://auth.o
148
148
  }
149
149
  }
150
150
 
151
+ export async function catalogModels(config) {
152
+ const spec = await namespace(config,null);
153
+ const client = new AppServer(spec,()=>{});
154
+ const deadline=setTimeout(()=>client.close(),10_000);
155
+ try {
156
+ await client.initialize({readAccount:false});
157
+ const models = [];
158
+ let cursor;
159
+ const cursors=new Set();
160
+ do {
161
+ const page = await client.rpc('model/list',{limit:100,...(cursor && {cursor})});
162
+ models.push(...page.data.filter(model=>!model.hidden));
163
+ cursor = page.nextCursor;
164
+ if (models.length > 1000 || cursors.size>=16 || cursor && cursors.has(cursor))
165
+ throw Error('Codex model catalog exceeds the runner limit');
166
+ cursors.add(cursor);
167
+ } while (cursor);
168
+ return models;
169
+ } finally {
170
+ clearTimeout(deadline);
171
+ await client.close();
172
+ await spec.cleanup();
173
+ }
174
+ }
175
+
151
176
  export async function prepareWorker(config, job) {
152
177
  if (process.platform !== 'linux') throw new Error('Codex workers require Linux bubblewrap');
153
178
  if (!job.profileId || typeof job.appId !== 'string' || !job.appId ||
@@ -1,7 +1,8 @@
1
1
  import { fileURLToPath } from 'node:url';
2
2
 
3
- export const profileCli = {
3
+ export const profileTerminalMethods = {
4
4
  authorize: {
5
+ type:'method', terminal:true,
5
6
  description: 'Connect this PROFILE to ChatGPT using a device code.',
6
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.',
7
8
  version: '1',
@@ -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
+ })
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
+ }
@@ -0,0 +1,150 @@
1
+ import Ajv2020 from 'ajv/dist/2020.js'
2
+ import addFormats from 'ajv-formats'
3
+ import {runConfigurationSchema} from './run-configuration.mjs'
4
+ import settingsSchema from '../examples/settings-schema.json' with {type:'json'}
5
+
6
+ export const templates=[
7
+ {template:'persistentAgent',name:'Persistent agent',type:'form',description:'Keep a conversation across incoming messages.'},
8
+ {template:'agentTasks',name:'Agent tasks',type:'form',description:'Run methods and incoming events in independent agent sessions.'},
9
+ ]
10
+ const ajv=new Ajv2020({strict:true,addUsedSchema:false,ownProperties:true})
11
+ addFormats(ajv)
12
+ const matches=ajv.compile(runConfigurationSchema)
13
+ const object=(properties,required=[])=>({type:'object',properties,required,additionalProperties:false})
14
+ const field=(type,key,label,required=false)=>({type,key,label,required})
15
+ const warning=text=>({type:'paragraph',level:'warning',text})
16
+ const empty={instructions:'',model:'',effort:''}
17
+ const dialect='https://json-schema.org/draft/2020-12/schema'
18
+ const methodName={type:'string',pattern:'^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*$',
19
+ not:{enum:['agent.sendMessage','agent.getHistory','agent.interrupt']}}
20
+
21
+ function target(template,context) {
22
+ if (!templates.some(t=>t.template===template)) throw Error('Unknown Codex template')
23
+ const raw=context.readDenied ? undefined : context.manifest
24
+ const named=raw?.run && typeof raw.run.type!=='string'
25
+ const base=named ? structuredClone(raw) : {run:{}}
26
+ const mode=template==='persistentAgent' ? 'persistent' : 'oneShot'
27
+ const keys=Object.keys(base.run).filter(key=>{
28
+ const {templateData,...variant}=base.run[key]
29
+ return variant.executors?.mode===mode && matches(variant)
30
+ })
31
+ let key=keys.includes(context.configuration) ? context.configuration :
32
+ keys.includes(template) ? template : keys.length===1 ? keys[0] : ''
33
+ const old=key ? base.run[key] : undefined
34
+ if (!key) {
35
+ key=template
36
+ for (let i=2;Object.hasOwn(base.run,key);i++) key=template+i
37
+ }
38
+ return {base,key,old,mode,legacy:!!raw && !named}
39
+ }
40
+
41
+ function modelFields(models) {
42
+ const catalog=new Map()
43
+ for (const model of models) {
44
+ if (typeof model.model!=='string' || !model.model || model.hidden) continue
45
+ const efforts=model.supportedReasoningEfforts?.map(e=>e.reasoningEffort)
46
+ .filter(e=>settingsSchema.properties.effort.enum.includes(e)) ?? []
47
+ catalog.set(model.model,{label:model.displayName || model.model,efforts,isDefault:model.isDefault})
48
+ }
49
+ const defaultEfforts=[...catalog.values()].find(m=>m.isDefault)?.efforts ?? []
50
+ const allowed=new Map([['',defaultEfforts],...[...catalog].map(([key,m])=>[key,m.efforts])])
51
+ const choices=[{value:'',label:'Default'},...[...catalog].map(([value,m])=>({value,label:m.label}))]
52
+ const efforts=[...new Set([...allowed.values()].flat())]
53
+ const elements=[field('textarea','instructions','Instructions'),{...field('select','model','Model'),choices},
54
+ {...field('select','effort','Reasoning effort'),choices:[{value:'',label:'Default'},...efforts.map(value=>({
55
+ value,label:value,visibleWhen:{select:'/model',in:[...allowed].filter(([,list])=>list.includes(value)).map(([key])=>key)}}))]}]
56
+ const properties={instructions:{type:'string'},model:{enum:[...allowed.keys()]},effort:{enum:['',...efforts]}}
57
+ const allOf=[...allowed].map(([key,list])=>({if:key==='' ? {properties:{model:{const:''}}} :
58
+ {properties:{model:{const:key}},required:['model']},then:{properties:{effort:{enum:['',...list]}}}}))
59
+ return {elements,properties,allOf}
60
+ }
61
+
62
+ function descriptor(template,context,models) {
63
+ const {old,legacy}=target(template,context)
64
+ const {elements:fields,properties,allOf}=modelFields(models)
65
+ const elements=[]
66
+ if (context.readDenied) elements.push(warning('The current manifest is unavailable. Applying replaces it using only this form.'))
67
+ if (legacy) elements.push(warning('Applying replaces the existing legacy manifest.'))
68
+ if (context.file) elements.push(warning('Applying saves inline JSON and stops tracking the manifest file.'))
69
+ if (!models.length) elements.push(warning('The Codex model catalog is unavailable. Default uses the runtime settings.'))
70
+ const settings=old?.settings ?? {}
71
+ function handler(value={}) {
72
+ const data={...empty}
73
+ for (const key of Object.keys(data)) {
74
+ if (typeof value[key]==='string') data[key]=value[key]
75
+ else if (key==='instructions' && typeof value.instructions?.value==='string') data.instructions=value.instructions.value
76
+ }
77
+ return data
78
+ }
79
+ const patternWarning=warning('Applying this form replaces Pattern instructions with plain text and removes substitutions.')
80
+ const isPattern=handler=>handler && typeof handler.instructions==='object'
81
+ const handlers=[settings,...Object.values(settings.methods ?? {}),settings.events].filter(Boolean)
82
+ if (handlers.some(h=>['model','effort'].some(k=>typeof h[k]==='object')))
83
+ elements.push(warning('Applying replaces model and reasoning effort Patterns in the edited fields.'))
84
+ const handlerSchema={...object(properties),allOf}
85
+ if (template==='persistentAgent') {
86
+ elements.push(fields[0],...(isPattern(settings) ? [patternWarning] : []),...fields.slice(1))
87
+ return {elements,formData:handler(settings),schema:handlerSchema}
88
+ }
89
+ const schemaValue={anyOf:[{type:'object'},{type:'boolean'}]}
90
+ const rowSchema={...object({name:methodName,description:{type:'string',maxLength:255},...properties,
91
+ inputSchema:schemaValue,outputSchema:schemaValue},['name']),allOf}
92
+ const methods=Object.entries(settings.methods ?? {}).map(([name,m])=>({name,description:m.description ?? '',...handler(m),
93
+ ...(m.inputSchema!==undefined && {inputSchema:m.inputSchema}),...(m.outputSchema!==undefined && {outputSchema:m.outputSchema})}))
94
+ const newItem={name:'',description:'',...empty}
95
+ elements.push({type:'array',key:'methods',label:'Methods',required:true,addLabel:'Add method',newItem,item:{type:'object',
96
+ elements:[field('text','name','Method name',true),field('text','description','Description'),fields[0],
97
+ ...(Object.values(settings.methods ?? {}).some(isPattern) ? [patternWarning] : []),...fields.slice(1),
98
+ {...field('json','inputSchema','Input schema'),schema:dialect},{...field('json','outputSchema','Output schema'),schema:dialect}]}},
99
+ field('checkbox','handleIncomingEvents','Handle incoming events'),{type:'block',key:'events',label:'Incoming events',
100
+ visibleWhen:{select:'/handleIncomingEvents',in:[true]},elements:[fields[0],...(isPattern(settings.events) ? [patternWarning] : []),...fields.slice(1)]})
101
+ const formData={methods:old ? methods : [{...newItem,name:'run'}],handleIncomingEvents:!!settings.events,events:handler(settings.events)}
102
+ const schema={...object({methods:{type:'array',items:rowSchema,maxItems:512},handleIncomingEvents:{type:'boolean'},events:{}},['methods','handleIncomingEvents']),
103
+ if:{properties:{handleIncomingEvents:{const:true}}},then:{properties:{events:handlerSchema}},
104
+ else:{properties:{methods:{type:'array',minItems:1}}}}
105
+ return {elements,formData,schema}
106
+ }
107
+
108
+ export function templateForm(template,context={},models=[]) { return descriptor(template,context,models) }
109
+ export function generateTemplate(template,data,context={},models=[]) {
110
+ const {base,key,old,mode}=target(template,context)
111
+ const schema=descriptor(template,context,models).schema
112
+ const validate=ajv.compile(schema)
113
+ ajv.removeSchema(schema)
114
+ if (!validate(data)) throw Error((validate.errors[0].instancePath || '/')+' '+validate.errors[0].message)
115
+ const settings={...old?.settings}
116
+ function handler(row={}) { return Object.fromEntries(Object.keys(empty).filter(k=>row[k]).map(k=>[k,row[k]])) }
117
+ if (mode==='persistent') {
118
+ for (const key of Object.keys(empty)) delete settings[key]
119
+ Object.assign(settings,handler(data))
120
+ } else {
121
+ const previous=settings.methods ?? {}
122
+ const methods=Object.create(null)
123
+ for (const [index,row] of data.methods.entries()) {
124
+ const path='/methods/'+index
125
+ if (Object.hasOwn(methods,row.name)) throw Error(path+'/name duplicates another method')
126
+ const method={...handler(row)}
127
+ if (row.description) method.description=row.description
128
+ if (Object.hasOwn(previous,row.name)) {
129
+ for (const key of ['version','doc']) if (Object.hasOwn(previous[row.name],key)) method[key]=previous[row.name][key]
130
+ }
131
+ for (const key of ['inputSchema','outputSchema']) if (Object.hasOwn(row,key)) {
132
+ try {
133
+ if (row[key]?.$async) throw Error('Async schemas are unsupported')
134
+ ajv.compile(row[key])
135
+ if (typeof row[key]==='object') ajv.removeSchema(row[key])
136
+ } catch { throw Error(path+'/'+key+' must be a valid supported JSON Schema') }
137
+ method[key]=row[key]
138
+ }
139
+ methods[row.name]=method
140
+ }
141
+ delete settings.methods
142
+ if (data.methods.length) settings.methods={...methods}
143
+ delete settings.events
144
+ if (data.handleIncomingEvents) settings.events=handler(data.events)
145
+ }
146
+ const variant={settings,executors:old?.executors ?? {mode}}
147
+ if (!matches(variant)) throw Error('Generated Codex configuration exceeds runner limits')
148
+ base.run[key]={...old,...variant}
149
+ return base
150
+ }
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]))