@centlu/agent-core 0.2.0 → 1.0.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 CHANGED
@@ -0,0 +1,25 @@
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
+ When `createManager` opens or reopens a session, it loads that session's events in append order and uses completed messages and tool results to seed the in-memory Pi context before processing input. Restoration does not emit historical events. Compaction summaries and provider-native metadata are unavailable in the stored event format.
20
+
21
+ ## Session Close
22
+
23
+ `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.
24
+
25
+ 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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@centlu/agent-core",
3
- "version": "0.2.0",
3
+ "version": "1.0.0",
4
4
  "description": "Core TypeScript types for Bun-based agents.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -0,0 +1,113 @@
1
+ import type {AssistantMessage, ImageContent, TextContent, ToolResultMessage} from "@oh-my-pi/pi-ai"
2
+ import type {SessionManager} from "@oh-my-pi/pi-coding-agent/session/session-manager"
3
+ import type {AgentEvent, JsonValue, Outcome} from "../../event.ts"
4
+
5
+ type ToolResultEvent = Extract<AgentEvent, {type: "tool.execution.ended"}>
6
+ type ToolReady = Extract<AgentEvent, {type: "tool.call.ready"}>["payload"]
7
+
8
+ function isObject(value: JsonValue | undefined): value is Record<string, JsonValue> {
9
+ return value != null && typeof value === "object" && !Array.isArray(value)
10
+ }
11
+
12
+ function toolKey(event: AgentEvent, toolCallId: string): string {
13
+ return JSON.stringify([event.runId, event.turnId, toolCallId])
14
+ }
15
+
16
+ function restoreToolResult(
17
+ toolCallId: string, toolName: string, timestamp: number, event?: ToolResultEvent,
18
+ ): ToolResultMessage {
19
+ const result = event?.payload.result
20
+ const content: (TextContent | ImageContent)[] = []
21
+ if (isObject(result) && Array.isArray(result.content)) {
22
+ for (const part of result.content) {
23
+ if (!isObject(part)) continue
24
+ if (part.type === "text" && typeof part.text === "string") {
25
+ content.push({type: "text", text: part.text})
26
+ } else if (part.type === "image" && typeof part.data === "string" && typeof part.mimeType === "string") {
27
+ content.push({type: "image", data: part.data, mimeType: part.mimeType})
28
+ }
29
+ }
30
+ } else if (result !== undefined) {
31
+ content.push({type: "text", text: typeof result === "string" ? result : JSON.stringify(result)})
32
+ }
33
+ if (content.length === 0) {
34
+ const text = event?.payload.error?.message ?? (event ? "" : "No result was recorded for this tool call.")
35
+ content.push({type: "text", text})
36
+ }
37
+ return {
38
+ role: "toolResult", toolCallId, toolName, content,
39
+ isError: event?.payload.status !== "succeeded",
40
+ timestamp: event?.timestamp ?? timestamp,
41
+ }
42
+ }
43
+
44
+ export function restoreHistory(sessionManager: SessionManager, history: readonly AgentEvent[]): void {
45
+ const calls = new Map<string, Map<string, ToolReady>>()
46
+ const results = new Map<string, ToolResultEvent>()
47
+ const turns = new Map<string, Outcome>()
48
+ for (const event of history) {
49
+ switch (event.type) {
50
+ case "tool.call.ready": {
51
+ const {messageId, toolCallId} = event.payload
52
+ const messageCalls = calls.get(messageId) ?? new Map<string, ToolReady>()
53
+ messageCalls.set(toolCallId, event.payload)
54
+ calls.set(messageId, messageCalls)
55
+ break
56
+ }
57
+ case "tool.execution.ended":
58
+ results.set(toolKey(event, event.payload.toolCallId), event)
59
+ break
60
+ case "turn.ended":
61
+ turns.set(event.payload.turnId, event.payload.status)
62
+ break
63
+ }
64
+ }
65
+
66
+ for (const event of history) {
67
+ if (event.type !== "message.ended") continue
68
+ const {role, messageId} = event.payload
69
+ const content: AssistantMessage["content"] = []
70
+ const toolResults: ToolResultMessage[] = []
71
+ for (const part of [...event.payload.content].sort((left, right) => left.partIndex - right.partIndex)) {
72
+ if (part.kind === "text") content.push({type: "text", text: part.text})
73
+ if (part.kind === "image") content.push({type: "image", data: part.data, mimeType: part.mimeType})
74
+ if (role !== "assistant") continue
75
+ if (part.kind === "thinking_summary") {
76
+ content.push({type: "thinking", thinking: part.text, summary: true})
77
+ }
78
+ if (part.kind === "tool_call") {
79
+ const {toolCallId} = part
80
+ const call = calls.get(messageId)?.get(toolCallId)
81
+ if (!call) continue
82
+ const {toolName, args} = call
83
+ content.push({type: "toolCall", id: toolCallId, name: toolName, arguments: isObject(args) ? args : {}})
84
+ const result = results.get(toolKey(event, toolCallId))
85
+ toolResults.push(restoreToolResult(toolCallId, toolName, event.timestamp, result))
86
+ }
87
+ }
88
+
89
+ const {timestamp} = event
90
+ if (role !== "assistant") {
91
+ sessionManager.appendMessage({
92
+ role: role === "system" ? "developer" : "user",
93
+ content: content.filter(part => part.type === "image" || part.type === "text"),
94
+ timestamp,
95
+ })
96
+ continue
97
+ }
98
+
99
+ const status = event.turnId === undefined ? undefined : turns.get(event.turnId)
100
+ if (content.length === 0 && status !== "failed" && status !== "cancelled") continue
101
+ sessionManager.appendMessage({
102
+ role, content, timestamp,
103
+ api: "openai-completions", provider: "agent-core-history", model: "<synthetic>",
104
+ usage: {
105
+ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,
106
+ cost: {input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0},
107
+ },
108
+ stopReason: status === "failed" ? "error" : status === "cancelled" ? "aborted"
109
+ : toolResults.length > 0 ? "toolUse" : "stop",
110
+ })
111
+ for (const result of toolResults) sessionManager.appendMessage(result)
112
+ }
113
+ }
@@ -6,11 +6,16 @@ import type {AgentEvent, AgentOptions, UserOperation} from "../../model.ts"
6
6
  import {AbstractAgent, type AgentCore} from "../core.ts"
7
7
  import {applyTurnConfig} from "./config.ts";
8
8
  import {toEvents} from "./events.ts"
9
+ import {restoreHistory} from "./history.ts"
9
10
 
10
- export async function CreateOhMyPiAgent(id: string, options: AgentOptions): Promise<AgentCore> {
11
+ export async function CreateOhMyPiAgent(
12
+ id: string, options: AgentOptions, history: readonly AgentEvent[] = [],
13
+ ): Promise<AgentCore> {
14
+ const sessionManager = SessionManager.inMemory()
15
+ restoreHistory(sessionManager, history)
11
16
  const {session} = await createAgentSession({
12
17
  cwd: options.cwd,
13
- sessionManager: SessionManager.inMemory(),
18
+ sessionManager,
14
19
  })
15
20
  await applyTurnConfig(session, options.setting)
16
21
 
@@ -19,6 +19,7 @@ export type SessionCloseResult = {
19
19
  export type PendingMessage = Submission | SessionCloseRequest | SessionCloseResult
20
20
 
21
21
  export interface HistoryStore {
22
+ /** Load stored events for this session in append order. */
22
23
  load_history_from_store(id: string): Promise<Array<AgentEvent>>
23
24
  append_history_to_store(event: AgentEvent): Promise<void>
24
25
 
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
- function validatePacing(intervalMs: number, charsPerTick: number, bufferMs: number) {
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
- buffer += chunk;
97
- if (buffer.length >= reserveChars * charsPerTick) releaseBuffer?.()
98
- void drain();
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, charsPerTick = 3, bufferMs = 200} = {},
15
+ {intervalMs = 16} = {},
115
16
  ) {
116
- validatePacing(intervalMs, charsPerTick, bufferMs)
117
- type Delta = Extract<AgentEvent, {type: "message.delta"}>
118
- let pending: Promise<void> | undefined
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 enqueue(completion: Promise<void>) {
126
- pending = completion
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
- void active.smoother.end()
144
- active = undefined
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.ended" || event.type === "turn.ended" || event.type === "run.ended") {
152
- seal()
153
- let delivery: AgentEventDelivery
154
- if (event.type === "message.ended") {
155
- const {id, sessionId, runId, turnId, timestamp, seq, payload} = event
156
- delivery = {
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 !== "message.delta") {
170
- void send(event)
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 (!event.payload.delta) return
175
- const source = active?.source
176
- if (!active || source?.sessionId !== event.sessionId || source.runId !== event.runId ||
177
- source.turnId !== event.turnId || source.payload.messageId !== event.payload.messageId ||
178
- source.payload.partIndex !== event.payload.partIndex || source.payload.kind !== event.payload.kind) {
179
- seal()
180
- const previous = pending
181
- const smoother = createEventSmoother(async delta => {
182
- await previous
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
- async end(): Promise<void> {
74
+ end(): Promise<void> {
194
75
  ended = true
195
- seal()
196
- await pending
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
- delivery?.push(event)
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, delivery?.end()])
211
+ await Promise.all([historyWrites, this.listeners.get(id)?.flush()])
183
212
  }
184
213
  }
185
214
  }
@@ -230,9 +259,9 @@ 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
- return CreateOhMyPiAgent(id, options)
237
- }, listener)
264
+ const history = await store.load_history_from_store(id)
265
+ return CreateOhMyPiAgent(id, options, history)
266
+ })
238
267
  }