@flinbein/pappai-runner-codex 0.2.11 → 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 +5 -1
- package/package.json +1 -1
- package/src/client.mjs +15 -1
- package/src/history.mjs +76 -0
- package/src/host.mjs +80 -28
- package/src/run-configuration.mjs +16 -5
package/README.md
CHANGED
|
@@ -61,7 +61,11 @@ Each key in `run` names a complete variant with `settings` and `executors`. In a
|
|
|
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.
|
|
65
69
|
|
|
66
70
|
## Manifest templates
|
|
67
71
|
|
package/package.json
CHANGED
package/src/client.mjs
CHANGED
|
@@ -87,7 +87,7 @@ export class AppServer {
|
|
|
87
87
|
const request = this.#requests.get(message.id)
|
|
88
88
|
if (!request) return
|
|
89
89
|
this.#requests.delete(message.id)
|
|
90
|
-
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}))
|
|
91
91
|
else request.resolve(message.result)
|
|
92
92
|
return
|
|
93
93
|
}
|
|
@@ -178,6 +178,20 @@ export class AppServer {
|
|
|
178
178
|
}
|
|
179
179
|
}
|
|
180
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
|
+
|
|
181
195
|
async interrupt() {
|
|
182
196
|
const active = this.#turn
|
|
183
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 {
|
|
@@ -219,7 +256,9 @@ class Worker {
|
|
|
219
256
|
if (!threadId || typeof threadId !== 'string' || (stored && threadId !== stored)) throw Error('Invalid Codex thread identity')
|
|
220
257
|
if (this.#stopping) return
|
|
221
258
|
this.#started = true
|
|
222
|
-
this
|
|
259
|
+
this.#threadId = threadId
|
|
260
|
+
this.#hasTurns = !!stored
|
|
261
|
+
this.emit('started',this.persistent ? {chatControls:true} : {})
|
|
223
262
|
if (!this.job.holdFirst) this.deliver(this.job)
|
|
224
263
|
while (!this.#stopping) {
|
|
225
264
|
const item = await this.#incoming.promise
|
|
@@ -229,28 +268,33 @@ class Worker {
|
|
|
229
268
|
this.#active = item
|
|
230
269
|
const fields = {id:item.id,workerId:this.job.id}
|
|
231
270
|
try {
|
|
232
|
-
if (item.method === 'agent.getHistory') {
|
|
233
|
-
|
|
234
|
-
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)
|
|
235
273
|
if (!this.#stopping && this.#cancelled !== item.id) this.emit('reply',{...fields,result})
|
|
236
274
|
} else if (item.method === 'agent.interrupt') {
|
|
237
275
|
throw Error('No active Codex turn')
|
|
238
276
|
} else if (this.#cancelled !== item.id) {
|
|
239
|
-
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())
|
|
240
280
|
const record = await client.turn(request,async () => {
|
|
241
281
|
if (this.#cancelled === item.id) this.#interrupt()
|
|
242
282
|
if (this.persistent && !stored) {
|
|
243
283
|
await saveThread(spec.stateFile,threadId)
|
|
244
284
|
stored = threadId
|
|
245
285
|
}
|
|
286
|
+
if (this.persistent) this.accepted(item)
|
|
246
287
|
}).catch(error => {
|
|
247
288
|
// An absent acknowledgement leaves the remote turn's state unknown.
|
|
248
289
|
// Retiring the worker prevents a second turn entering that thread.
|
|
249
290
|
this.stop(error.message)
|
|
250
291
|
throw error
|
|
251
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
|
|
252
296
|
if (this.#cancelled !== item.id && !this.#stopping) {
|
|
253
|
-
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 + ')')
|
|
254
298
|
if (item.method) this.emit('reply',{...fields,result:resultOf(record.text,validate)})
|
|
255
299
|
}
|
|
256
300
|
}
|
|
@@ -260,6 +304,12 @@ class Worker {
|
|
|
260
304
|
this.emit('reply',{...fields,error:{message:error.message}})
|
|
261
305
|
}
|
|
262
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
|
+
}
|
|
263
313
|
clearTimeout(this.#cancelTimer)
|
|
264
314
|
this.#cancelTimer = undefined
|
|
265
315
|
this.#active = undefined
|
|
@@ -316,6 +366,8 @@ export class RunnerHost {
|
|
|
316
366
|
if (type === 'response') worker.respond(message.requestId,message.response)
|
|
317
367
|
if (type === 'notify' && typeof message.notification?.cancelled === 'string') worker.cancel(message.notification.cancelled)
|
|
318
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)
|
|
319
371
|
if (type === 'reject' && message.message !== 'Call closed') {
|
|
320
372
|
worker.emit('reply',{workerId:id,id:message.callId,error:{message:message.message}})
|
|
321
373
|
}
|
|
@@ -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
|
}
|