@flinbein/pappai-runner-codex 0.2.10 → 0.2.12
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 +12 -2
- package/examples/settings-schema.json +3 -1
- package/package.json +1 -1
- package/src/client.mjs +18 -5
- package/src/history.mjs +76 -0
- package/src/host.mjs +82 -29
- package/src/index.mjs +20 -2
- package/src/policy.mjs +25 -0
- package/src/run-configuration.mjs +17 -6
- package/src/templates.mjs +150 -0
package/README.md
CHANGED
|
@@ -57,11 +57,21 @@ 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
|
-
A persistent variant
|
|
64
|
+
A persistent variant resumes its stored conversation. Call `agent.sendMessage({"input":"Summarize the latest event."})` to submit a message. It returns `{"accepted":true,"messageId":"�"}` when the controller accepts the message. Follow-ups from the same sender can steer their active turn. Other messages wait in the APP queue. The executor receives a `$.session.message` event with the caller ID in `data.sender`, the text in `data.input`, and the work item ID in the stored record's `messageId`.
|
|
65
|
+
|
|
66
|
+
`agent.getHistory({})` returns the latest 20 visible messages in chronological order, including input accepted by the active turn. Each message has a stable `id`, `role` (`user`, `assistant` or `event`), `text`, and an optional `sender`. Text over 8192 UTF-8 bytes carries `truncated:true`. To paginate, pass the first ID as `before` or the last ID as `after`. Both bounds are exclusive. The optional `limit` accepts 1 through 20. The response includes `hasMoreBefore` and `hasMoreAfter`. An unknown ID returns an error. Tool activity and intermediate model commentary stay private.
|
|
67
|
+
|
|
68
|
+
`agent.status.get({})` returns `{"status":"idle"}` or `{"status":"working"}` with the current message sender when available. Both history and status can be read during a turn. Subscribe to `agent.status.updated` for status changes and `agent.historyChanged` to refresh history. Call `agent.interrupt({})` during an active turn to interrupt it. The runner supplies these methods and events for persistent configurations.
|
|
69
|
+
|
|
70
|
+
## Manifest templates
|
|
71
|
+
|
|
72
|
+
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.
|
|
73
|
+
|
|
74
|
+
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.
|
|
65
75
|
|
|
66
76
|
## Executor permissions
|
|
67
77
|
|
package/package.json
CHANGED
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
|
-
|
|
41
|
-
|
|
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) => {
|
|
@@ -88,7 +87,7 @@ export class AppServer {
|
|
|
88
87
|
const request = this.#requests.get(message.id)
|
|
89
88
|
if (!request) return
|
|
90
89
|
this.#requests.delete(message.id)
|
|
91
|
-
if (message.error) request.reject(Error('Codex rejected ' + request.method))
|
|
90
|
+
if (message.error) request.reject(Object.assign(Error('Codex rejected ' + request.method),{rpcRejected:true}))
|
|
92
91
|
else request.resolve(message.result)
|
|
93
92
|
return
|
|
94
93
|
}
|
|
@@ -179,6 +178,20 @@ export class AppServer {
|
|
|
179
178
|
}
|
|
180
179
|
}
|
|
181
180
|
|
|
181
|
+
async steer(input) {
|
|
182
|
+
const active = this.#turn
|
|
183
|
+
if (!active || !await active.ready.promise || active !== this.#turn || active.records.get(active.id)?.status)
|
|
184
|
+
return false
|
|
185
|
+
try {
|
|
186
|
+
const response = await this.rpc('turn/steer',{threadId:active.threadId,expectedTurnId:active.id,input})
|
|
187
|
+
if (response.turnId !== active.id) throw Error('Invalid Codex steer acknowledgement')
|
|
188
|
+
return true
|
|
189
|
+
} catch (error) {
|
|
190
|
+
if (error.rpcRejected) return false
|
|
191
|
+
throw error
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
182
195
|
async interrupt() {
|
|
183
196
|
const active = this.#turn
|
|
184
197
|
if (!active || !await active.ready.promise || active !== this.#turn || active.records.get(active.id)?.status)
|
package/src/history.mjs
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
const pageSize = 32
|
|
2
|
+
const textLimit = 8192
|
|
3
|
+
|
|
4
|
+
export function sessionSender(record) {
|
|
5
|
+
if (record?.event === '$.session.message' && typeof record.data?.input === 'string' &&
|
|
6
|
+
typeof record.data.sender === 'string') return record.data.sender
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function inputMessage(record,id) {
|
|
10
|
+
const sender = sessionSender(record)
|
|
11
|
+
if (sender !== undefined)
|
|
12
|
+
return {id,role:'user',text:record.data.input,sender}
|
|
13
|
+
if (record?.event || record?.method) {
|
|
14
|
+
const data = typeof record.data === 'string' ? record.data : JSON.stringify(record.data)
|
|
15
|
+
return {id,role:'event',text:[record.event ?? record.method,data].filter(Boolean).join('\n'),
|
|
16
|
+
...(typeof record.from === 'string' && {sender:record.from})}
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function messageFrom({turnId,item}) {
|
|
21
|
+
const nativeId = 'codex:' + JSON.stringify([turnId,item.id])
|
|
22
|
+
if (item.type === 'agentMessage' && (item.phase == null || item.phase === 'final_answer'))
|
|
23
|
+
return {id:nativeId,role:'assistant',text:item.text}
|
|
24
|
+
if (item.type !== 'userMessage') return
|
|
25
|
+
const text = item.content?.[0]?.text
|
|
26
|
+
if (typeof text !== 'string') return
|
|
27
|
+
let record
|
|
28
|
+
try { record = JSON.parse(text) } catch { /* Legacy plain-text input. */ }
|
|
29
|
+
return inputMessage(record,typeof record?.messageId === 'string' ? record.messageId : nativeId) ??
|
|
30
|
+
{id:nativeId,role:'user',text}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function bounded(message) {
|
|
34
|
+
const bytes = Buffer.from(message.text)
|
|
35
|
+
if (bytes.length <= textLimit) return message
|
|
36
|
+
return {...message,text:new TextDecoder().decode(bytes.subarray(0,textLimit),{stream:true}),truncated:true}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function* newestFirst(client,threadId,hasTurns,pending) {
|
|
40
|
+
// A turn can accept input before the app-server persists a readable item.
|
|
41
|
+
const pendingIds = new Set(pending.map(message => message.id))
|
|
42
|
+
yield* pending.toReversed()
|
|
43
|
+
if (!hasTurns) return
|
|
44
|
+
let cursor
|
|
45
|
+
do {
|
|
46
|
+
const page = await client.rpc('thread/items/list',{threadId,limit:pageSize,sortDirection:'desc',...(cursor && {cursor})})
|
|
47
|
+
for (const entry of page.data) {
|
|
48
|
+
const message = messageFrom(entry)
|
|
49
|
+
if (message && !pendingIds.has(message.id)) yield message
|
|
50
|
+
}
|
|
51
|
+
if (cursor && cursor === page.nextCursor) throw Error('Codex returned a repeated history cursor')
|
|
52
|
+
cursor = page.nextCursor
|
|
53
|
+
} while (cursor)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function history(client,threadId,data,hasTurns,pending) {
|
|
57
|
+
const {limit=20,before,after} = data ?? {}
|
|
58
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > 20 || (before !== undefined && after !== undefined) ||
|
|
59
|
+
[before,after].some(id => id !== undefined && (typeof id !== 'string' || !id || id.length > 4096)))
|
|
60
|
+
throw Error('Invalid history page')
|
|
61
|
+
const messages = []
|
|
62
|
+
let found = before === undefined && after === undefined
|
|
63
|
+
let hasMoreBefore = false, hasMoreAfter = false
|
|
64
|
+
for await (const message of newestFirst(client,threadId,hasTurns,pending)) {
|
|
65
|
+
if (after !== undefined) {
|
|
66
|
+
if (message.id === after) { found = true; hasMoreBefore = true; break }
|
|
67
|
+
if (messages.length === limit) { messages.shift(); hasMoreAfter = true }
|
|
68
|
+
} else if (!found) {
|
|
69
|
+
if (message.id === before) { found = true; hasMoreAfter = true }
|
|
70
|
+
continue
|
|
71
|
+
} else if (messages.length === limit) { hasMoreBefore = true; break }
|
|
72
|
+
messages.push(bounded(message))
|
|
73
|
+
}
|
|
74
|
+
if (!found) throw Error('Unknown history message ID')
|
|
75
|
+
return {messages:messages.reverse(),hasMoreBefore,hasMoreAfter}
|
|
76
|
+
}
|
package/src/host.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'
|
|
|
2
2
|
import { readFile, rename, unlink, writeFile } from 'node:fs/promises'
|
|
3
3
|
import Ajv2020 from 'ajv/dist/2020.js'
|
|
4
4
|
import addFormats from 'ajv-formats'
|
|
5
|
+
import { history, inputMessage, sessionSender } from './history.mjs'
|
|
5
6
|
import { AppServer } from './client.mjs'
|
|
6
7
|
import { dynamicTools, toolMethods } from './tools.mjs'
|
|
7
8
|
|
|
@@ -39,11 +40,12 @@ function schemaInstructions(schema) {
|
|
|
39
40
|
return 'Return only a JSON object with a result property matching this JSON Schema: ' + JSON.stringify(schema)
|
|
40
41
|
}
|
|
41
42
|
|
|
42
|
-
function turnRequest(threadId,item,settings,effort) {
|
|
43
|
+
function turnRequest(threadId,item,settings,effort,persistent) {
|
|
43
44
|
const record = {from:item.from,...(item.method ? {method:item.method} : {event:item.event,subscription:item.subscription}),data:item.data}
|
|
44
45
|
const named = item.method && settings.methods && Object.hasOwn(settings.methods,item.method)
|
|
45
46
|
if (item.method && (settings.eventSession || (settings.methods || settings.events) && !named))
|
|
46
47
|
throw Error('Unknown Codex method')
|
|
48
|
+
if (persistent) record.messageId = item.id
|
|
47
49
|
const input = [{type:'text',text:JSON.stringify(named ? item.data ?? null : record)}]
|
|
48
50
|
const params = {threadId,input,environments:[],...(effort && {effort})}
|
|
49
51
|
let validate
|
|
@@ -73,27 +75,6 @@ function resultOf(text,validate) {
|
|
|
73
75
|
return value.result
|
|
74
76
|
}
|
|
75
77
|
|
|
76
|
-
async function history(client,threadId,data,hasTurns) {
|
|
77
|
-
const {limit=20,cursor}=data ?? {}
|
|
78
|
-
if (!Number.isInteger(limit) || limit < 1 || limit > 20 || (cursor != null &&
|
|
79
|
-
(typeof cursor !== 'string' || cursor.length > 4096))) throw Error('Invalid history page')
|
|
80
|
-
if (!hasTurns) return {messages:[],nextCursor:null}
|
|
81
|
-
const page = await client.rpc('thread/items/list',{threadId,limit,cursor,sortDirection:'asc'})
|
|
82
|
-
const messages = []
|
|
83
|
-
for (const {item} of page.data) {
|
|
84
|
-
const user = item.type === 'userMessage'
|
|
85
|
-
// The runner writes the pappai record as the first text block. Subsequent
|
|
86
|
-
// blocks can contain runner instructions for models with structured output.
|
|
87
|
-
let text = user && item.content[0]?.type === 'text' ? item.content[0].text : undefined
|
|
88
|
-
if (item.type === 'agentMessage' && (item.phase == null || item.phase === 'final_answer')) text = item.text
|
|
89
|
-
if (typeof text !== 'string') continue
|
|
90
|
-
const bytes = Buffer.from(text), truncated = bytes.length > 8192
|
|
91
|
-
messages.push({role:user ? 'user' : 'assistant',text:truncated ? bytes.subarray(0,8192).toString('utf8') : text,
|
|
92
|
-
...(truncated && {truncated:true})})
|
|
93
|
-
}
|
|
94
|
-
return {messages,nextCursor:page.nextCursor ?? null}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
78
|
class Worker {
|
|
98
79
|
#incoming = Promise.withResolvers()
|
|
99
80
|
#queued = false
|
|
@@ -103,6 +84,10 @@ class Worker {
|
|
|
103
84
|
#client
|
|
104
85
|
#stopping = false
|
|
105
86
|
#issue
|
|
87
|
+
#threadId
|
|
88
|
+
#hasTurns = false
|
|
89
|
+
#turnItem
|
|
90
|
+
#pendingChat = []
|
|
106
91
|
#started = false
|
|
107
92
|
#outgoing = new Map()
|
|
108
93
|
|
|
@@ -152,6 +137,58 @@ class Worker {
|
|
|
152
137
|
this.#outgoing.get(id)?.resolve(response)
|
|
153
138
|
}
|
|
154
139
|
|
|
140
|
+
status() {
|
|
141
|
+
const sender = sessionSender(this.#turnItem)
|
|
142
|
+
return this.#turnItem ? {status:'working',...(sender !== undefined && {sender})} : {status:'idle'}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
publish(event,data) {
|
|
146
|
+
if (this.persistent && !this.#stopping)
|
|
147
|
+
this.emit('request',{workerId:this.job.id,id:randomUUID(),method:'publish',params:{event,data,to:['!.',true]}})
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
accepted(item) {
|
|
151
|
+
const message = inputMessage(item,item.id)
|
|
152
|
+
if (message) this.#pendingChat.push(message)
|
|
153
|
+
this.publish('agent.historyChanged',{})
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async steer(item,expectedWorkId) {
|
|
157
|
+
let result = false
|
|
158
|
+
const sender = sessionSender(item)
|
|
159
|
+
try {
|
|
160
|
+
if (this.persistent && !this.#stopping && this.#turnItem?.id === expectedWorkId &&
|
|
161
|
+
sender !== undefined && sender === sessionSender(this.#turnItem)) {
|
|
162
|
+
const {params} = turnRequest(this.#threadId,item,this.job.settings,undefined,true)
|
|
163
|
+
result = await this.#client.steer(params.input)
|
|
164
|
+
if (result) {
|
|
165
|
+
if (this.#turnItem?.id === expectedWorkId) this.accepted(item)
|
|
166
|
+
else this.publish('agent.historyChanged',{})
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
} catch {
|
|
170
|
+
// A lost acknowledgement may already have changed the model input.
|
|
171
|
+
// Worker exit tells the controller to retire this ambiguous delivery.
|
|
172
|
+
this.stop('Could not confirm Codex steering')
|
|
173
|
+
return
|
|
174
|
+
}
|
|
175
|
+
this.emit('steered',{id:item.id,workerId:this.job.id,result})
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async read(item) {
|
|
179
|
+
if (!this.persistent || !this.#started) throw Error('Chat requires a persistent Codex APP')
|
|
180
|
+
if (item.method === 'agent.status.get') return this.status()
|
|
181
|
+
if (item.method === 'agent.getHistory')
|
|
182
|
+
return history(this.#client,this.#threadId,item.data,this.#hasTurns,[...this.#pendingChat])
|
|
183
|
+
throw Error('Unknown chat query')
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async query(item) {
|
|
187
|
+
const fields = {id:item.id,workerId:this.job.id}
|
|
188
|
+
try { this.emit('reply',{...fields,result:await this.read(item)}) }
|
|
189
|
+
catch (error) { this.emit('reply',{...fields,error:{message:error.message}}) }
|
|
190
|
+
}
|
|
191
|
+
|
|
155
192
|
async interrupt(id) {
|
|
156
193
|
const fields = {id,workerId:this.job.id}
|
|
157
194
|
try {
|
|
@@ -194,7 +231,8 @@ class Worker {
|
|
|
194
231
|
}
|
|
195
232
|
spec = await prepare(config,this.job)
|
|
196
233
|
if (this.#stopping) return
|
|
197
|
-
const client = this.#client = new AppServer(spec,error => this.stop(error.message),params => this.#tool(params)
|
|
234
|
+
const client = this.#client = new AppServer(spec,error => this.stop(error.message),params => this.#tool(params),
|
|
235
|
+
bytes => this.emit('stderr',{data:bytes.toString('base64')}))
|
|
198
236
|
await client.initialize()
|
|
199
237
|
if (this.#stopping) return
|
|
200
238
|
const handler = this.persistent ? undefined : this.job.method
|
|
@@ -218,7 +256,9 @@ class Worker {
|
|
|
218
256
|
if (!threadId || typeof threadId !== 'string' || (stored && threadId !== stored)) throw Error('Invalid Codex thread identity')
|
|
219
257
|
if (this.#stopping) return
|
|
220
258
|
this.#started = true
|
|
221
|
-
this
|
|
259
|
+
this.#threadId = threadId
|
|
260
|
+
this.#hasTurns = !!stored
|
|
261
|
+
this.emit('started',this.persistent ? {chatControls:true} : {})
|
|
222
262
|
if (!this.job.holdFirst) this.deliver(this.job)
|
|
223
263
|
while (!this.#stopping) {
|
|
224
264
|
const item = await this.#incoming.promise
|
|
@@ -228,28 +268,33 @@ class Worker {
|
|
|
228
268
|
this.#active = item
|
|
229
269
|
const fields = {id:item.id,workerId:this.job.id}
|
|
230
270
|
try {
|
|
231
|
-
if (item.method === 'agent.getHistory') {
|
|
232
|
-
|
|
233
|
-
const result = await history(client,threadId,item.data,stored)
|
|
271
|
+
if (item.method === 'agent.getHistory' || this.persistent && item.method === 'agent.status.get') {
|
|
272
|
+
const result = await this.read(item)
|
|
234
273
|
if (!this.#stopping && this.#cancelled !== item.id) this.emit('reply',{...fields,result})
|
|
235
274
|
} else if (item.method === 'agent.interrupt') {
|
|
236
275
|
throw Error('No active Codex turn')
|
|
237
276
|
} else if (this.#cancelled !== item.id) {
|
|
238
|
-
const {params:request,validate} = turnRequest(threadId,item,settings,effort)
|
|
277
|
+
const {params:request,validate} = turnRequest(threadId,item,settings,effort,this.persistent)
|
|
278
|
+
this.#turnItem = item
|
|
279
|
+
this.publish('agent.status.updated',this.status())
|
|
239
280
|
const record = await client.turn(request,async () => {
|
|
240
281
|
if (this.#cancelled === item.id) this.#interrupt()
|
|
241
282
|
if (this.persistent && !stored) {
|
|
242
283
|
await saveThread(spec.stateFile,threadId)
|
|
243
284
|
stored = threadId
|
|
244
285
|
}
|
|
286
|
+
if (this.persistent) this.accepted(item)
|
|
245
287
|
}).catch(error => {
|
|
246
288
|
// An absent acknowledgement leaves the remote turn's state unknown.
|
|
247
289
|
// Retiring the worker prevents a second turn entering that thread.
|
|
248
290
|
this.stop(error.message)
|
|
249
291
|
throw error
|
|
250
292
|
})
|
|
293
|
+
// A fresh Codex thread has no native item history until its first
|
|
294
|
+
// turn finishes. Accepted chat is available from the active inputs.
|
|
295
|
+
if (this.persistent) this.#hasTurns = true
|
|
251
296
|
if (this.#cancelled !== item.id && !this.#stopping) {
|
|
252
|
-
if (record.status !== 'completed') throw Error('Codex turn did not complete (' + record.status + ')')
|
|
297
|
+
if (record.status !== 'completed' && !(this.persistent && !item.method && record.status === 'interrupted')) throw Error('Codex turn did not complete (' + record.status + ')')
|
|
253
298
|
if (item.method) this.emit('reply',{...fields,result:resultOf(record.text,validate)})
|
|
254
299
|
}
|
|
255
300
|
}
|
|
@@ -259,6 +304,12 @@ class Worker {
|
|
|
259
304
|
this.emit('reply',{...fields,error:{message:error.message}})
|
|
260
305
|
}
|
|
261
306
|
} finally {
|
|
307
|
+
if (this.#turnItem) {
|
|
308
|
+
this.#turnItem = undefined
|
|
309
|
+
this.#pendingChat = []
|
|
310
|
+
this.publish('agent.historyChanged',{})
|
|
311
|
+
this.publish('agent.status.updated',this.status())
|
|
312
|
+
}
|
|
262
313
|
clearTimeout(this.#cancelTimer)
|
|
263
314
|
this.#cancelTimer = undefined
|
|
264
315
|
this.#active = undefined
|
|
@@ -315,6 +366,8 @@ export class RunnerHost {
|
|
|
315
366
|
if (type === 'response') worker.respond(message.requestId,message.response)
|
|
316
367
|
if (type === 'notify' && typeof message.notification?.cancelled === 'string') worker.cancel(message.notification.cancelled)
|
|
317
368
|
if (type === 'notify' && typeof message.notification?.interrupt === 'string') void worker.interrupt(message.notification.interrupt)
|
|
369
|
+
if (type === 'notify' && message.notification?.chat) void worker.query(message.notification.chat)
|
|
370
|
+
if (type === 'notify' && message.notification?.steer) void worker.steer(message.notification.steer,message.notification.expectedWorkId)
|
|
318
371
|
if (type === 'reject' && message.message !== 'Call closed') {
|
|
319
372
|
worker.emit('reply',{workerId:id,id:message.callId,error:{message:message.message}})
|
|
320
373
|
}
|
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
|
-
}
|
|
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}
|
|
@@ -36,10 +36,21 @@ export const runConfigurationSchema = {
|
|
|
36
36
|
maxRestarts:{type:'integer',minimum:0,maximum:10}},['mode'])),
|
|
37
37
|
],
|
|
38
38
|
}
|
|
39
|
+
const messageId = {type:'string',minLength:1,maxLength:4096}
|
|
40
|
+
const status = object({status:{enum:['idle','working']},sender:string},['status'])
|
|
41
|
+
const message = object({id:messageId,role:{enum:['user','assistant','event']},text:string,
|
|
42
|
+
sender:string,truncated:{const:true}},['id','role','text'])
|
|
39
43
|
export const persistentFeatures = {
|
|
40
|
-
'agent.sendMessage':{type:'method',version:'1',description:'
|
|
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
|
|
43
|
-
schema:{input:object({
|
|
44
|
-
|
|
44
|
+
'agent.sendMessage':{type:'method',version:'1',description:'Send a message to this agent.',
|
|
45
|
+
schema:{input:object({input:string},['input']),output:object({accepted:{const:true},messageId},['accepted','messageId'])}},
|
|
46
|
+
'agent.getHistory':{type:'method',version:'1',description:'Read a chronological page of chat history.',
|
|
47
|
+
schema:{input:{...object({before:messageId,after:messageId,limit:{type:'integer',minimum:1,maximum:20}}),
|
|
48
|
+
not:{properties:{before:{},after:{}},required:['before','after']}},
|
|
49
|
+
output:object({messages:{type:'array',items:message},hasMoreBefore:{type:'boolean'},hasMoreAfter:{type:'boolean'}},
|
|
50
|
+
['messages','hasMoreBefore','hasMoreAfter'])}},
|
|
51
|
+
'agent.interrupt':{type:'method',version:'1',description:'Interrupt the current turn.',
|
|
52
|
+
schema:{input:object({}),output:object({interrupted:{const:true}},['interrupted'])}},
|
|
53
|
+
'agent.status.get':{type:'method',version:'1',description:'Read the current chat status.',schema:{input:object({}),output:status}},
|
|
54
|
+
'agent.status.updated':{type:'event',version:'1',description:'The chat status changed.',schema:{data:status}},
|
|
55
|
+
'agent.historyChanged':{type:'event',version:'1',description:'New chat history is available.',schema:{data:object({})}},
|
|
45
56
|
}
|
|
@@ -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
|
+
}
|