@flinbein/pappai-runner-codex 0.2.10 → 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
@@ -57,12 +57,18 @@ 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
- 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.
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
61
 
62
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
63
 
64
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
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.
71
+
66
72
  ## Executor permissions
67
73
 
68
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.
@@ -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.2.10",
3
+ "version": "0.2.11",
4
4
  "description": "Codex app-server runner for pappai",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
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
@@ -194,7 +194,8 @@ class Worker {
194
194
  }
195
195
  spec = await prepare(config,this.job)
196
196
  if (this.#stopping) return
197
- 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')}))
198
199
  await client.initialize()
199
200
  if (this.#stopping) return
200
201
  const handler = this.persistent ? undefined : this.job.method
package/src/index.mjs CHANGED
@@ -1,10 +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
4
  import { prepareProfileCli, profileTerminalMethods } from './profile-cli.mjs'
5
5
  import { join } from 'node:path'
6
6
  import { CodexInstallation, runnerMethods } from './installation.mjs'
7
7
  import { runConfigurationSchema, persistentFeatures } from './run-configuration.mjs'
8
+ import { templates, templateForm, generateTemplate } from './templates.mjs'
8
9
  import settingsSchema from '../examples/settings-schema.json' with {type:'json'}
9
10
 
10
11
  if (typeof process.send !== 'function') throw Error('Start the Codex runner through the pappai runner registry')
@@ -24,8 +25,24 @@ const host = new RunnerHost(config,async (config,job) => {
24
25
  const codexExecutablePath=await installation.executable()
25
26
  return prepareWorker({...config,codexExecutablePath},job)
26
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
+ }
27
38
  async function runnerCall({id,method,data}) {
28
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
+ }
29
46
  if (method==='@cli.prepare') {
30
47
  const result=await prepareProfileCli(data,installation,config.runnerName)
31
48
  return send('runnerReply',{id,result})
@@ -49,6 +66,7 @@ process.on('message', message => {
49
66
  process.on('disconnect',close)
50
67
  process.on('SIGTERM',close)
51
68
  process.on('SIGINT',close)
52
- send('runnerReady',{kind:'codex',settingsSchema,runConfigurationSchema,persistentFeatures,methods:runnerMethods,profileTerminalMethods})
69
+ send('runnerReady',{kind:'codex',settingsSchema,runConfigurationSchema,persistentFeatures,methods:runnerMethods,profileTerminalMethods,
70
+ templates:templates.map(t=>({...t,readManifest:true}))})
53
71
  attachProfileMethods(config)
54
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 ||
@@ -22,7 +22,7 @@ const method = object({
22
22
  ...modelSettings,
23
23
  description:{type:'string',maxLength:255},version:{type:'string',minLength:1},doc:string,
24
24
  inputSchema:schema,outputSchema:schema,
25
- },['inputSchema','outputSchema'])
25
+ })
26
26
  const methods = {type:'object',minProperties:1,maxProperties:512,propertyNames:{
27
27
  pattern:'^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)*$',not:{enum:['agent.getHistory','agent.interrupt','agent.sendMessage']},
28
28
  },additionalProperties:method}
@@ -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
+ }