@centlu/agent-core 0.2.0 → 0.3.0
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 +23 -0
- package/package.json +1 -1
- package/src/buffer.ts +44 -164
- package/src/manage.ts +41 -13
package/README.md
CHANGED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# Agent Core
|
|
2
|
+
|
|
3
|
+
## Agent Events
|
|
4
|
+
|
|
5
|
+
See the [frontend event integration guide](FRONTEND_EVENTS.md) for JSON shapes, rendering rules, and a multi-turn example.
|
|
6
|
+
|
|
7
|
+
`AgentEvent` is a hand-written contract shared by adapters, history stores, and listeners. Event IDs identify individual events. `seq` increases for the lifetime of an adapter instance, and `timestamp` records conversion time in Unix milliseconds.
|
|
8
|
+
|
|
9
|
+
Oh My Pi keeps the same `runId` across `run.paused` and `run.resumed`. A new Pi run after a terminal event gets a new ID. Disposing the adapter ends any still-open run as cancelled. Automatic retry events report scheduled attempts and their overall outcome. Manual and automatic context compaction report start and end, including skips and cancellations. Idle compaction has no `runId`.
|
|
10
|
+
|
|
11
|
+
Apply live `message.delta` by `messageId` and `partIndex`. Live `message.ended` marks completion with `messageId` and `role`. Read complete content, including thinking summaries, from the stored `message.ended` event. Tool updates carry replaceable snapshots and use `toolCallId` to correlate concurrent calls.
|
|
12
|
+
|
|
13
|
+
`AgentEventListener` batches text and thinking deltas for up to 16 ms by default, with no character limit per batch. Switching message parts or receiving `message.ended`, `turn.ended`, or `run.ended` queues the pending text immediately. Tool calls, progress, and results go straight to the listener's send queue and can arrive while a text batch is still collecting.
|
|
14
|
+
|
|
15
|
+
Create the manager with `createManager(store, life)` and bind one listener per session with `manager.bindListener(sessionId, listener)`. A duplicate bind throws and leaves the current listener active. Call the returned function when the connection closes. The binding lasts until explicitly removed, including across submissions and session restarts. In a multi-Pod deployment, bind on the manager running the session or forward events from that Pod through the application.
|
|
16
|
+
|
|
17
|
+
History stores receive the original non-delta events. Live delivery proceeds independently of history writes. The listener's `seq` orders live delivery within each binding and running session. Load the stored events for historical playback or to recover complete messages after reconnecting.
|
|
18
|
+
|
|
19
|
+
## Session Close
|
|
20
|
+
|
|
21
|
+
`SessionManager.close(id)` gracefully drains the session. A close from another Pod uses the shared `HistoryStore` pending queue and waits up to 30 seconds for disposal to finish or for the targeted owner to leave. It throws on timeout or if the owner reports a disposal failure.
|
|
22
|
+
|
|
23
|
+
For multi-Pod deployments, all managers must use the same pending queues and shared `AgentLife` liveness records. Store the `ownerId` passed to `AgentLife.report`, return it from `alive`, and implement `release` to clear the record when its owner matches. This scopes a close to the running instance even if the session is later reopened. A `HistoryStore` adapter must round-trip each `PendingMessage` variant under its `session` key, including the reply queues under the reserved `@agent-core/close/` prefix. Adapters can expire close requests and replies using their `expiresAt` timestamps. Update all Pod versions and store adapters before routing cross-Pod close requests.
|
package/package.json
CHANGED
package/src/buffer.ts
CHANGED
|
@@ -2,199 +2,79 @@ import type {AgentEvent, AgentEventDelivery} from "./event.ts"
|
|
|
2
2
|
|
|
3
3
|
const maxTimerMs = 2_147_483_647
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
if (!Number.isInteger(charsPerTick) || charsPerTick < 1) {
|
|
7
|
-
throw new RangeError("charsPerTick must be a positive integer");
|
|
8
|
-
}
|
|
9
|
-
if (!Number.isInteger(intervalMs) || intervalMs < 1 || intervalMs > maxTimerMs) {
|
|
10
|
-
throw new RangeError("intervalMs is outside the supported timer range");
|
|
11
|
-
}
|
|
12
|
-
if (!Number.isInteger(bufferMs) || bufferMs < 0 || bufferMs > maxTimerMs) {
|
|
13
|
-
throw new RangeError("bufferMs is outside the supported timer range")
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function wait(intervalMs: number): Promise<void> {
|
|
18
|
-
return new Promise(resolve => setTimeout(resolve, intervalMs))
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export function createEventSmoother(
|
|
22
|
-
write: (chunk: string) => void | Promise<void>,
|
|
23
|
-
{intervalMs = 16, charsPerTick = 2, bufferMs = 200} = {},
|
|
24
|
-
) {
|
|
25
|
-
validatePacing(intervalMs, charsPerTick, bufferMs)
|
|
26
|
-
|
|
27
|
-
let buffer = "";
|
|
28
|
-
let ended = false;
|
|
29
|
-
let running = false;
|
|
30
|
-
let started = bufferMs === 0
|
|
31
|
-
const reserveChars = Math.ceil(bufferMs / intervalMs)
|
|
32
|
-
let releaseBuffer: (() => void) | undefined
|
|
33
|
-
let resolveDone!: () => void;
|
|
34
|
-
let rejectDone!: (error: unknown) => void;
|
|
35
|
-
|
|
36
|
-
const done = new Promise<void>((resolve, reject) => {
|
|
37
|
-
resolveDone = resolve;
|
|
38
|
-
rejectDone = reject;
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
async function drain(): Promise<void> {
|
|
42
|
-
if (running) return;
|
|
43
|
-
running = true;
|
|
44
|
-
|
|
45
|
-
try {
|
|
46
|
-
if (!started && !ended && buffer.length < reserveChars * charsPerTick) {
|
|
47
|
-
await new Promise<void>(resolve => {
|
|
48
|
-
const timer = setTimeout(() => releaseBuffer?.(), bufferMs)
|
|
49
|
-
releaseBuffer = () => {
|
|
50
|
-
clearTimeout(timer)
|
|
51
|
-
releaseBuffer = undefined
|
|
52
|
-
resolve()
|
|
53
|
-
}
|
|
54
|
-
})
|
|
55
|
-
}
|
|
56
|
-
started = true
|
|
57
|
-
while (buffer) {
|
|
58
|
-
await wait(intervalMs);
|
|
59
|
-
|
|
60
|
-
let end = 0;
|
|
61
|
-
let count = 0;
|
|
62
|
-
const limit = !ended && buffer.length <= reserveChars ? 1 : charsPerTick
|
|
63
|
-
for (const char of buffer) {
|
|
64
|
-
// 保留末尾单独的高代理项,等待下一段补齐 emoji 等字符。
|
|
65
|
-
if (!ended && end + 1 === buffer.length && /[\uD800-\uDBFF]/.test(char)) {
|
|
66
|
-
break;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
end += char.length;
|
|
70
|
-
count += 1;
|
|
71
|
-
if (count === limit) break;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
if (end === 0) break;
|
|
75
|
-
|
|
76
|
-
const chunk = buffer.slice(0, end);
|
|
77
|
-
buffer = buffer.slice(end);
|
|
78
|
-
await write(chunk);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
if (ended) resolveDone();
|
|
82
|
-
} catch (error) {
|
|
83
|
-
ended = true;
|
|
84
|
-
buffer = "";
|
|
85
|
-
rejectDone(error);
|
|
86
|
-
} finally {
|
|
87
|
-
running = false;
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
return {
|
|
92
|
-
push(chunk: string) {
|
|
93
|
-
if (ended) throw new Error("The text input is closed");
|
|
94
|
-
if (!chunk) return;
|
|
5
|
+
type Delta = Extract<AgentEvent, {type: "message.delta"}>
|
|
95
6
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
end() {
|
|
102
|
-
ended = true;
|
|
103
|
-
releaseBuffer?.()
|
|
104
|
-
void drain();
|
|
105
|
-
return done;
|
|
106
|
-
},
|
|
107
|
-
|
|
108
|
-
done,
|
|
109
|
-
};
|
|
7
|
+
function isSamePart(first: Delta, next: Delta): boolean {
|
|
8
|
+
return first.sessionId === next.sessionId && first.runId === next.runId && first.turnId === next.turnId &&
|
|
9
|
+
first.payload.messageId === next.payload.messageId && first.payload.partIndex === next.payload.partIndex &&
|
|
10
|
+
first.payload.kind === next.payload.kind
|
|
110
11
|
}
|
|
111
12
|
|
|
112
13
|
export function createAgentEventSmoother(
|
|
113
14
|
write: (event: AgentEventDelivery) => void | Promise<void>,
|
|
114
|
-
{intervalMs = 16
|
|
15
|
+
{intervalMs = 16} = {},
|
|
115
16
|
) {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
17
|
+
if (!Number.isInteger(intervalMs) || intervalMs < 1 || intervalMs > maxTimerMs) {
|
|
18
|
+
throw new RangeError("intervalMs is outside the supported timer range")
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let active: {source: Delta; text: string} | undefined
|
|
22
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
119
23
|
let writes = Promise.resolve()
|
|
120
24
|
let ended = false
|
|
121
25
|
let seq = 0
|
|
122
|
-
let nextDeltaAt = 0
|
|
123
|
-
let active: {source: Delta; smoother: ReturnType<typeof createEventSmoother>} | undefined
|
|
124
26
|
|
|
125
|
-
function
|
|
126
|
-
|
|
127
|
-
void completion.then(() => {
|
|
128
|
-
if (pending === completion) pending = undefined
|
|
129
|
-
}, () => undefined)
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
function send(event: AgentEventDelivery): Promise<void> {
|
|
133
|
-
writes = writes.then(async () => {
|
|
134
|
-
if (event.type === "message.delta") nextDeltaAt = performance.now() + intervalMs
|
|
135
|
-
await write({...event, seq: ++seq})
|
|
136
|
-
})
|
|
27
|
+
function send(event: AgentEventDelivery): void {
|
|
28
|
+
writes = writes.then(() => write({...event, seq: ++seq}))
|
|
137
29
|
void writes.catch(() => undefined)
|
|
138
|
-
return writes
|
|
139
30
|
}
|
|
140
31
|
|
|
141
|
-
function seal
|
|
32
|
+
function flush(seal: boolean): void {
|
|
33
|
+
clearTimeout(timer)
|
|
34
|
+
timer = undefined
|
|
142
35
|
if (!active) return
|
|
143
|
-
|
|
144
|
-
|
|
36
|
+
|
|
37
|
+
const {source, text} = active
|
|
38
|
+
const lastCodeUnit = text.charCodeAt(text.length - 1)
|
|
39
|
+
const keepTail = !seal && lastCodeUnit >= 0xD800 && lastCodeUnit <= 0xDBFF
|
|
40
|
+
const delta = keepTail ? text.slice(0, -1) : text
|
|
41
|
+
active = keepTail ? {source, text: text.slice(-1)} : undefined
|
|
42
|
+
if (delta) send({...source, id: crypto.randomUUID(), payload: {...source.payload, delta}})
|
|
145
43
|
}
|
|
146
44
|
|
|
147
45
|
return {
|
|
148
46
|
push(event: AgentEvent): void {
|
|
149
47
|
if (ended) throw new Error("The event input is closed")
|
|
150
48
|
|
|
151
|
-
if (event.type === "message.
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
if (
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
type: "message.ended", id, sessionId, runId, timestamp, seq,
|
|
158
|
-
...(turnId === undefined ? {} : {turnId}),
|
|
159
|
-
payload: {messageId: payload.messageId, role: payload.role},
|
|
160
|
-
}
|
|
161
|
-
} else {
|
|
162
|
-
delivery = event
|
|
163
|
-
}
|
|
164
|
-
if (pending) enqueue(pending.then(() => send(delivery)))
|
|
165
|
-
else void send(delivery)
|
|
49
|
+
if (event.type === "message.delta") {
|
|
50
|
+
if (!event.payload.delta) return
|
|
51
|
+
if (active && !isSamePart(active.source, event)) flush(true)
|
|
52
|
+
if (active) active.text += event.payload.delta
|
|
53
|
+
else active = {source: event, text: event.payload.delta}
|
|
54
|
+
timer ??= setTimeout(() => flush(false), intervalMs)
|
|
166
55
|
return
|
|
167
56
|
}
|
|
168
57
|
|
|
169
|
-
if (event.type
|
|
170
|
-
|
|
171
|
-
return
|
|
58
|
+
if (event.type === "message.ended" || event.type === "turn.ended" || event.type === "run.ended") {
|
|
59
|
+
flush(true)
|
|
172
60
|
}
|
|
173
61
|
|
|
174
|
-
if (
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
const delay = Math.ceil(nextDeltaAt - performance.now())
|
|
184
|
-
if (delay > 0) await wait(delay)
|
|
185
|
-
await send({...event, id: crypto.randomUUID(), payload: {...event.payload, delta}})
|
|
186
|
-
}, {intervalMs, charsPerTick, bufferMs})
|
|
187
|
-
active = {source: event, smoother}
|
|
188
|
-
enqueue(smoother.done)
|
|
62
|
+
if (event.type === "message.ended") {
|
|
63
|
+
const {id, sessionId, runId, turnId, timestamp, seq, payload} = event
|
|
64
|
+
send({
|
|
65
|
+
type: "message.ended", id, sessionId, runId, timestamp, seq,
|
|
66
|
+
...(turnId === undefined ? {} : {turnId}),
|
|
67
|
+
payload: {messageId: payload.messageId, role: payload.role},
|
|
68
|
+
})
|
|
69
|
+
} else {
|
|
70
|
+
send(event)
|
|
189
71
|
}
|
|
190
|
-
active.smoother.push(event.payload.delta)
|
|
191
72
|
},
|
|
192
73
|
|
|
193
|
-
|
|
74
|
+
end(): Promise<void> {
|
|
194
75
|
ended = true
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
await writes
|
|
76
|
+
flush(true)
|
|
77
|
+
return writes
|
|
198
78
|
},
|
|
199
79
|
}
|
|
200
80
|
}
|
package/src/manage.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type {AgentEventListener, AgentLife, AgentOptions, Submission} from "./model.ts"
|
|
2
|
+
import type {AgentEvent} from "./event.ts"
|
|
2
3
|
import type {HistoryStore, PendingMessage, SessionCloseRequest} from "./agent"
|
|
3
4
|
import type {AgentCore} from "./agent/core.ts"
|
|
4
5
|
import {CreateOhMyPiAgent} from "./agent/oh-my-pi";
|
|
@@ -21,16 +22,52 @@ type ManagedSession = {
|
|
|
21
22
|
done: Promise<void>
|
|
22
23
|
}
|
|
23
24
|
|
|
25
|
+
type SessionListener = {
|
|
26
|
+
push(event: AgentEvent): void
|
|
27
|
+
flush(): Promise<void> | undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
24
30
|
export class SessionManager {
|
|
25
31
|
private readonly sessions = new Map<string, ManagedSession>()
|
|
32
|
+
private readonly listeners = new Map<string, SessionListener>()
|
|
26
33
|
|
|
27
34
|
constructor(
|
|
28
35
|
private readonly store: HistoryStore,
|
|
29
36
|
private readonly life: AgentLife,
|
|
30
37
|
private readonly getCoreAgent: (id: string, options: AgentOptions) => Promise<AgentCore>,
|
|
31
|
-
private readonly listener?: AgentEventListener,
|
|
32
38
|
) {}
|
|
33
39
|
|
|
40
|
+
bindListener(id: string, listener: AgentEventListener): () => void {
|
|
41
|
+
this.validateSessionId(id)
|
|
42
|
+
if (this.listeners.has(id)) throw new Error(`Session ${id} already has a listener`)
|
|
43
|
+
|
|
44
|
+
let delivery: ReturnType<typeof createAgentEventSmoother> | undefined
|
|
45
|
+
const binding: SessionListener = {
|
|
46
|
+
push: event => {
|
|
47
|
+
delivery ??= createAgentEventSmoother(async event => {
|
|
48
|
+
if (this.listeners.get(id) !== binding) return
|
|
49
|
+
try {
|
|
50
|
+
await listener.onEvent(event)
|
|
51
|
+
} catch (error) {
|
|
52
|
+
console.error("事件发送失败", id, event.type, error)
|
|
53
|
+
}
|
|
54
|
+
})
|
|
55
|
+
delivery.push(event)
|
|
56
|
+
},
|
|
57
|
+
flush: () => {
|
|
58
|
+
const pending = delivery
|
|
59
|
+
delivery = undefined
|
|
60
|
+
return pending?.end()
|
|
61
|
+
},
|
|
62
|
+
}
|
|
63
|
+
this.listeners.set(id, binding)
|
|
64
|
+
return () => {
|
|
65
|
+
if (this.listeners.get(id) !== binding) return
|
|
66
|
+
this.listeners.delete(id)
|
|
67
|
+
void binding.flush()
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
34
71
|
async submit(submission: Submission): Promise<void> {
|
|
35
72
|
this.validateSessionId(submission.session)
|
|
36
73
|
await this.store.submit_pending_messages(submission)
|
|
@@ -152,14 +189,6 @@ export class SessionManager {
|
|
|
152
189
|
|
|
153
190
|
private async runSession(id: string, ready: Promise<AgentCore>, state: SessionState): Promise<void> {
|
|
154
191
|
const agent = await ready
|
|
155
|
-
const listener = this.listener
|
|
156
|
-
const delivery = listener && createAgentEventSmoother(async event => {
|
|
157
|
-
try {
|
|
158
|
-
await listener.onEvent(event)
|
|
159
|
-
} catch (error) {
|
|
160
|
-
console.error("事件发送失败", id, event.type, error)
|
|
161
|
-
}
|
|
162
|
-
})
|
|
163
192
|
let historyWrites = Promise.resolve()
|
|
164
193
|
let unsubscribe: (() => void) | undefined
|
|
165
194
|
|
|
@@ -169,7 +198,7 @@ export class SessionManager {
|
|
|
169
198
|
historyWrites = historyWrites.then(() => this.store.append_history_to_store(event))
|
|
170
199
|
.catch(error => console.error("事件写入历史失败", id, event.type, error))
|
|
171
200
|
}
|
|
172
|
-
|
|
201
|
+
this.listeners.get(id)?.push(event)
|
|
173
202
|
})
|
|
174
203
|
|
|
175
204
|
agent.startHeartbeat(() => this.life.report(id, state.ownerId))
|
|
@@ -179,7 +208,7 @@ export class SessionManager {
|
|
|
179
208
|
await agent.dispose()
|
|
180
209
|
} finally {
|
|
181
210
|
unsubscribe?.()
|
|
182
|
-
await Promise.all([historyWrites,
|
|
211
|
+
await Promise.all([historyWrites, this.listeners.get(id)?.flush()])
|
|
183
212
|
}
|
|
184
213
|
}
|
|
185
214
|
}
|
|
@@ -230,9 +259,8 @@ export class SessionManager {
|
|
|
230
259
|
export function createManager(
|
|
231
260
|
store: HistoryStore,
|
|
232
261
|
life: AgentLife,
|
|
233
|
-
listener?: AgentEventListener,
|
|
234
262
|
): SessionManager {
|
|
235
263
|
return new SessionManager(store, life, async (id, options) => {
|
|
236
264
|
return CreateOhMyPiAgent(id, options)
|
|
237
|
-
}
|
|
265
|
+
})
|
|
238
266
|
}
|