@centlu/agent-core 0.1.1 → 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 +2 -1
- package/src/agent/core.ts +12 -3
- package/src/agent/oh-my-pi/config.ts +110 -0
- package/src/agent/oh-my-pi/events.ts +235 -0
- package/src/agent/{omp.ts → oh-my-pi/index.ts} +28 -13
- package/src/agent/oh-my-pi/model-selection.ts +52 -0
- package/src/agent/oh-my-pi/thinking.ts +12 -0
- package/src/agent/store.ts +28 -10
- package/src/buffer.ts +65 -63
- package/src/event.ts +81 -0
- package/src/index.ts +5 -2
- package/src/manage.ts +146 -23
- package/src/model.ts +20 -11
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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@centlu/agent-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Core TypeScript types for Bun-based agents.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
"access": "public"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
+
"@oh-my-pi/pi-agent-core": "^19.1.0",
|
|
28
29
|
"@oh-my-pi/pi-coding-agent": "^19.1.0"
|
|
29
30
|
}
|
|
30
31
|
}
|
package/src/agent/core.ts
CHANGED
|
@@ -1,10 +1,15 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {AgentOptions, UserOperation} from "../model.ts"
|
|
2
|
+
import type {AgentEvent} from "../event.ts";
|
|
2
3
|
|
|
3
4
|
export interface AgentCore {
|
|
4
5
|
handleInput(input: UserOperation, options: AgentOptions): Promise<void>
|
|
6
|
+
|
|
5
7
|
waitForEnd(): Promise<void>
|
|
8
|
+
|
|
6
9
|
subscribe(listener: (event: AgentEvent) => void): () => void
|
|
10
|
+
|
|
7
11
|
startHeartbeat(report: () => Promise<void>): void
|
|
12
|
+
|
|
8
13
|
dispose(): Promise<void>
|
|
9
14
|
}
|
|
10
15
|
|
|
@@ -13,7 +18,8 @@ export abstract class AbstractAgent implements AgentCore {
|
|
|
13
18
|
private reporting?: Promise<void>
|
|
14
19
|
private disposal?: Promise<void>
|
|
15
20
|
|
|
16
|
-
protected constructor(protected readonly id: string) {
|
|
21
|
+
protected constructor(protected readonly id: string) {
|
|
22
|
+
}
|
|
17
23
|
|
|
18
24
|
startHeartbeat(report: () => Promise<void>): void {
|
|
19
25
|
if (this.heartbeat !== undefined || this.disposal) return
|
|
@@ -28,7 +34,7 @@ export abstract class AbstractAgent implements AgentCore {
|
|
|
28
34
|
})
|
|
29
35
|
}
|
|
30
36
|
|
|
31
|
-
this.heartbeat = setInterval(tick,
|
|
37
|
+
this.heartbeat = setInterval(tick, 15_000)
|
|
32
38
|
tick()
|
|
33
39
|
}
|
|
34
40
|
|
|
@@ -43,7 +49,10 @@ export abstract class AbstractAgent implements AgentCore {
|
|
|
43
49
|
}
|
|
44
50
|
|
|
45
51
|
abstract handleInput(input: UserOperation, options: AgentOptions): Promise<void>
|
|
52
|
+
|
|
46
53
|
abstract waitForEnd(): Promise<void>
|
|
54
|
+
|
|
47
55
|
abstract subscribe(listener: (event: AgentEvent) => void): () => void
|
|
56
|
+
|
|
48
57
|
protected abstract doDispose(): Promise<void>
|
|
49
58
|
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type {AgentSession} from "@oh-my-pi/pi-coding-agent/session/agent-session"
|
|
2
|
+
import type {ModelRegistry} from "@oh-my-pi/pi-coding-agent/config/model-registry"
|
|
3
|
+
import type {Model} from "@oh-my-pi/pi-ai"
|
|
4
|
+
import type {TurnConfig} from "../../model.ts"
|
|
5
|
+
import {GATEWAY_PROVIDER_PREFIX, narrowerLimit, pickCatalogModel, pickTurnModel} from "./model-selection.ts"
|
|
6
|
+
import {thinkingLevels} from "./thinking.ts"
|
|
7
|
+
|
|
8
|
+
type RuntimeKey = {provider: string, apiKey: string, previous?: string}
|
|
9
|
+
|
|
10
|
+
const runtimeKeys = new WeakMap<AgentSession, RuntimeKey>()
|
|
11
|
+
|
|
12
|
+
export async function applyTurnConfig(session: AgentSession, setting: TurnConfig): Promise<void> {
|
|
13
|
+
const registry = session.modelRegistry
|
|
14
|
+
const modelId = setting.model.trim()
|
|
15
|
+
const baseUrl = setting.baseurl?.trim()
|
|
16
|
+
const apiKey = setting.apiKey?.trim()
|
|
17
|
+
if (!modelId) throw new Error("模型名不能为空")
|
|
18
|
+
if (baseUrl && (!apiKey || apiKey.startsWith("!"))) {
|
|
19
|
+
throw new Error("自定义网关需要有效的 API Key")
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const candidates = registry.getAll().filter(model =>
|
|
23
|
+
model.id.toLowerCase() === modelId.toLowerCase()
|
|
24
|
+
&& !model.provider.startsWith(GATEWAY_PROVIDER_PREFIX)
|
|
25
|
+
)
|
|
26
|
+
const matching = candidates.filter(model => model.api === setting.protocol)
|
|
27
|
+
if (!baseUrl && matching.length === 0) {
|
|
28
|
+
throw new Error(`找不到与 ${setting.protocol}/${modelId} 匹配的模型`)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const keys = registry.authStorage.keys
|
|
32
|
+
const previous = runtimeKeys.get(session)
|
|
33
|
+
restoreRuntimeKey(registry, previous)
|
|
34
|
+
runtimeKeys.delete(session)
|
|
35
|
+
|
|
36
|
+
try {
|
|
37
|
+
let model = baseUrl
|
|
38
|
+
? registerGateway(registry, setting, modelId, baseUrl, apiKey!,
|
|
39
|
+
pickCatalogModel(matching.length ? matching : candidates, modelId))
|
|
40
|
+
: apiKey
|
|
41
|
+
? pickCatalogModel(matching, modelId)!
|
|
42
|
+
: pickTurnModel(matching, modelId, candidate => registry.hasConfiguredAuth(candidate))!
|
|
43
|
+
|
|
44
|
+
requireEndpoint(registry, model)
|
|
45
|
+
|
|
46
|
+
if (!baseUrl && apiKey) {
|
|
47
|
+
const priorKey = keys.source(model.provider)?.kind === "runtime"
|
|
48
|
+
? await keys.peek(model.provider) : undefined
|
|
49
|
+
keys.setRuntime(model.provider, apiKey)
|
|
50
|
+
runtimeKeys.set(session, {provider: model.provider, apiKey, previous: priorKey})
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (!baseUrl) {
|
|
54
|
+
model = {
|
|
55
|
+
...model,
|
|
56
|
+
contextWindow: narrowerLimit(setting.contextWindow, model.contextWindow),
|
|
57
|
+
maxTokens: narrowerLimit(setting.maxTokens, model.maxTokens),
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
await session.setModelTemporary(model, thinkingLevels[setting.thinkingLevel])
|
|
61
|
+
session.setSteeringMode("all", false)
|
|
62
|
+
} catch (error) {
|
|
63
|
+
restoreRuntimeKey(registry, runtimeKeys.get(session))
|
|
64
|
+
runtimeKeys.delete(session)
|
|
65
|
+
if (previous) {
|
|
66
|
+
keys.setRuntime(previous.provider, previous.apiKey)
|
|
67
|
+
runtimeKeys.set(session, previous)
|
|
68
|
+
}
|
|
69
|
+
throw error
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function requireEndpoint(registry: ModelRegistry, model: Model): void {
|
|
74
|
+
if (!model.baseUrl && !registry.getProviderBaseUrl(model.provider)) {
|
|
75
|
+
throw new Error(`${model.provider}/${model.id} 没有默认接口地址,请通过 baseurl 指定端点`)
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function registerGateway(
|
|
80
|
+
registry: ModelRegistry,
|
|
81
|
+
setting: TurnConfig,
|
|
82
|
+
modelId: string,
|
|
83
|
+
baseUrl: string,
|
|
84
|
+
apiKey: string,
|
|
85
|
+
catalog?: Model,
|
|
86
|
+
): Model {
|
|
87
|
+
const provider = `${GATEWAY_PROVIDER_PREFIX}${setting.protocol}`
|
|
88
|
+
registry.registerProvider(provider, {
|
|
89
|
+
api: setting.protocol,
|
|
90
|
+
baseUrl,
|
|
91
|
+
apiKey,
|
|
92
|
+
models: [{
|
|
93
|
+
id: modelId,
|
|
94
|
+
name: catalog?.name ?? modelId,
|
|
95
|
+
input: catalog ? [...catalog.input] : ["text"],
|
|
96
|
+
contextWindow: narrowerLimit(setting.contextWindow, catalog?.contextWindow),
|
|
97
|
+
maxTokens: narrowerLimit(setting.maxTokens, catalog?.maxTokens),
|
|
98
|
+
cost: catalog?.cost ?? {input: 0, output: 0, cacheRead: 0, cacheWrite: 0},
|
|
99
|
+
}],
|
|
100
|
+
})
|
|
101
|
+
const model = registry.find(provider, modelId)
|
|
102
|
+
if (!model) throw new Error(`找不到模型:${provider}/${modelId}`)
|
|
103
|
+
return model
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function restoreRuntimeKey(registry: ModelRegistry, key?: RuntimeKey): void {
|
|
107
|
+
if (!key) return
|
|
108
|
+
if (key.previous === undefined) registry.authStorage.keys.removeRuntime(key.provider)
|
|
109
|
+
else registry.authStorage.keys.setRuntime(key.provider, key.previous)
|
|
110
|
+
}
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
|
|
2
|
+
import type {AgentSessionEvent} from "@oh-my-pi/pi-coding-agent/session/agent-session-events"
|
|
3
|
+
import type {AgentEvent, AgentEventData, JsonValue, MessagePart, Outcome} from "../../event.ts"
|
|
4
|
+
|
|
5
|
+
type Message = Extract<AgentSessionEvent, {type: "message_end"}>["message"]
|
|
6
|
+
type AssistantMessage = Extract<Message, {role: "assistant"}>
|
|
7
|
+
type ToolCall = Extract<AssistantMessage["content"][number], {type: "toolCall"}>
|
|
8
|
+
type CompactionTrigger = "automatic" | "manual"
|
|
9
|
+
type Run = {
|
|
10
|
+
id: string
|
|
11
|
+
paused: boolean
|
|
12
|
+
turnId?: string
|
|
13
|
+
lastAssistant?: AssistantMessage
|
|
14
|
+
messages: Map<string, string>
|
|
15
|
+
toolCalls: Map<string, {turnId?: string; ready: boolean}>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function jsonValue(value: unknown): JsonValue | undefined {
|
|
19
|
+
try {
|
|
20
|
+
const serialized = JSON.stringify(value)
|
|
21
|
+
if (serialized !== undefined) return JSON.parse(serialized)
|
|
22
|
+
} catch {
|
|
23
|
+
return undefined
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function assistantOutcome(message?: AssistantMessage): Outcome {
|
|
28
|
+
switch (message?.stopReason) {
|
|
29
|
+
case "error": return "failed"
|
|
30
|
+
case "aborted": return "cancelled"
|
|
31
|
+
case "stop":
|
|
32
|
+
case "length":
|
|
33
|
+
case "toolUse": return "succeeded"
|
|
34
|
+
default: return "unknown"
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function messageContent(message: Extract<Message, {role: "user" | "developer" | "assistant"}>): MessagePart[] {
|
|
39
|
+
if (typeof message.content === "string") return [{partIndex: 0, kind: "text", text: message.content}]
|
|
40
|
+
return message.content.flatMap((part, partIndex): MessagePart[] => {
|
|
41
|
+
switch (part.type) {
|
|
42
|
+
case "text": return [{partIndex, kind: "text", text: part.text}]
|
|
43
|
+
case "image": return [{partIndex, kind: "image", data: part.data, mimeType: part.mimeType}]
|
|
44
|
+
case "toolCall": return [{partIndex, kind: "tool_call", toolCallId: part.id}]
|
|
45
|
+
case "thinking":
|
|
46
|
+
if (part.narration) return [{partIndex, kind: "text", text: part.thinking}]
|
|
47
|
+
if (part.summary) return [{partIndex, kind: "thinking_summary", text: part.thinking}]
|
|
48
|
+
return []
|
|
49
|
+
default: return []
|
|
50
|
+
}
|
|
51
|
+
})
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function toEvents(sessionId: string) {
|
|
55
|
+
let seq = 0
|
|
56
|
+
let run: Run | undefined
|
|
57
|
+
const compactions = new Map<CompactionTrigger, {id: string; runId?: string; strategy?: string}>()
|
|
58
|
+
|
|
59
|
+
function emit(data: AgentEventData, turnId?: string): AgentEvent {
|
|
60
|
+
return {
|
|
61
|
+
...data, id: crypto.randomUUID(), sessionId, seq: ++seq, timestamp: Date.now(),
|
|
62
|
+
...(turnId ? {turnId} : {}),
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function toolCallReady(current: Run, toolCall: ToolCall, messageId: string): AgentEvent[] {
|
|
67
|
+
if (current.toolCalls.get(toolCall.id)?.ready) return []
|
|
68
|
+
current.toolCalls.set(toolCall.id, {turnId: current.turnId, ready: true})
|
|
69
|
+
const args = jsonValue(toolCall.arguments)
|
|
70
|
+
return [emit({
|
|
71
|
+
type: "tool.call.ready", runId: current.id,
|
|
72
|
+
payload: {toolCallId: toolCall.id, messageId, toolName: toolCall.name, ...(args !== undefined ? {args} : {})},
|
|
73
|
+
}, current.turnId)]
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function dispose(): AgentEvent[] {
|
|
77
|
+
const runId = run?.id
|
|
78
|
+
run = undefined
|
|
79
|
+
compactions.clear()
|
|
80
|
+
if (runId === undefined) return []
|
|
81
|
+
return [emit({type: "run.ended", runId, payload: {status: "cancelled"}})]
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function convert(event: AgentSessionEvent): AgentEvent[] {
|
|
85
|
+
switch (event.type) {
|
|
86
|
+
case "agent_start": {
|
|
87
|
+
if (!run) {
|
|
88
|
+
run = {id: crypto.randomUUID(), paused: false, messages: new Map(), toolCalls: new Map()}
|
|
89
|
+
return [emit({type: "run.started", runId: run.id, payload: null})]
|
|
90
|
+
}
|
|
91
|
+
if (!run.paused) return []
|
|
92
|
+
run.paused = false
|
|
93
|
+
run.lastAssistant = undefined
|
|
94
|
+
return [emit({type: "run.resumed", runId: run.id, payload: null})]
|
|
95
|
+
}
|
|
96
|
+
case "auto_compaction_start":
|
|
97
|
+
case "manual_compaction_start": {
|
|
98
|
+
const trigger = event.type === "auto_compaction_start" ? "automatic" : "manual"
|
|
99
|
+
const strategy = event.type === "auto_compaction_start" ? event.action : event.mode
|
|
100
|
+
const compactionId = crypto.randomUUID()
|
|
101
|
+
compactions.set(trigger, {id: compactionId, runId: run?.id, strategy})
|
|
102
|
+
return [emit({
|
|
103
|
+
type: "context.compaction.started", ...(run ? {runId: run.id} : {}),
|
|
104
|
+
payload: {
|
|
105
|
+
compactionId, trigger, ...(strategy !== undefined ? {strategy} : {}),
|
|
106
|
+
...(event.type === "auto_compaction_start" ? {reason: event.reason} : {}),
|
|
107
|
+
},
|
|
108
|
+
})]
|
|
109
|
+
}
|
|
110
|
+
case "auto_compaction_end":
|
|
111
|
+
case "manual_compaction_end": {
|
|
112
|
+
const trigger = event.type === "auto_compaction_end" ? "automatic" : "manual"
|
|
113
|
+
const compaction = compactions.get(trigger)
|
|
114
|
+
compactions.delete(trigger)
|
|
115
|
+
const runId = compaction ? compaction.runId : run?.id
|
|
116
|
+
const strategy = event.type === "auto_compaction_end" ? event.action : compaction?.strategy
|
|
117
|
+
const status = event.aborted ? "cancelled" : event.skipped ? "skipped" : event.result ? "succeeded" : "failed"
|
|
118
|
+
return [emit({
|
|
119
|
+
type: "context.compaction.ended", ...(runId ? {runId} : {}),
|
|
120
|
+
payload: {
|
|
121
|
+
compactionId: compaction?.id ?? crypto.randomUUID(), trigger, status,
|
|
122
|
+
...(strategy !== undefined ? {strategy} : {}),
|
|
123
|
+
...(event.type === "auto_compaction_end" ? {willRetry: event.willRetry} : {}),
|
|
124
|
+
...(event.result ? {tokensBefore: event.result.tokensBefore} : {}),
|
|
125
|
+
...(event.errorMessage ? {error: {message: event.errorMessage}} : {}),
|
|
126
|
+
},
|
|
127
|
+
})]
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
if (!run) return []
|
|
132
|
+
const runId = run.id
|
|
133
|
+
switch (event.type) {
|
|
134
|
+
case "agent_pause":
|
|
135
|
+
if (run.paused) return []
|
|
136
|
+
run.paused = true
|
|
137
|
+
run.turnId = undefined
|
|
138
|
+
return [emit({type: "run.paused", runId, payload: {yielded: event.yielded, awaiting: event.awaiting}})]
|
|
139
|
+
case "agent_end": {
|
|
140
|
+
const last = event.messages.findLast((message): message is AssistantMessage => message.role === "assistant") ?? run.lastAssistant
|
|
141
|
+
run = undefined
|
|
142
|
+
return [emit({type: "run.ended", runId, payload: {
|
|
143
|
+
status: assistantOutcome(last),
|
|
144
|
+
...(last?.errorMessage ? {error: {message: last.errorMessage}} : {}),
|
|
145
|
+
}})]
|
|
146
|
+
}
|
|
147
|
+
case "turn_start": {
|
|
148
|
+
const turnId = run.turnId = crypto.randomUUID()
|
|
149
|
+
run.lastAssistant = undefined
|
|
150
|
+
return [emit({type: "turn.started", runId, payload: {turnId}}, turnId)]
|
|
151
|
+
}
|
|
152
|
+
case "turn_end": {
|
|
153
|
+
const turnId = run.turnId
|
|
154
|
+
run.turnId = undefined
|
|
155
|
+
if (event.message.role === "assistant") run.lastAssistant = event.message
|
|
156
|
+
if (!turnId) return []
|
|
157
|
+
const status = assistantOutcome(event.message.role === "assistant" ? event.message : undefined)
|
|
158
|
+
return [emit({type: "turn.ended", runId, payload: {turnId, status}}, turnId)]
|
|
159
|
+
}
|
|
160
|
+
case "message_start":
|
|
161
|
+
case "message_end": {
|
|
162
|
+
const message = event.message
|
|
163
|
+
if (message.role !== "user" && message.role !== "assistant" && message.role !== "developer") return []
|
|
164
|
+
const role = message.role === "developer" ? "system" : message.role
|
|
165
|
+
const messageId = run.messages.get(message.role) ?? crypto.randomUUID()
|
|
166
|
+
if (event.type === "message_start") {
|
|
167
|
+
run.messages.set(message.role, messageId)
|
|
168
|
+
return [emit({type: "message.started", runId, payload: {messageId, role}}, run.turnId)]
|
|
169
|
+
}
|
|
170
|
+
run.messages.delete(message.role)
|
|
171
|
+
const events: AgentEvent[] = []
|
|
172
|
+
if (message.role === "assistant") {
|
|
173
|
+
run.lastAssistant = message
|
|
174
|
+
if (assistantOutcome(message) === "succeeded") {
|
|
175
|
+
for (const part of message.content) {
|
|
176
|
+
if (part.type === "toolCall") events.push(...toolCallReady(run, part, messageId))
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
events.push(emit({
|
|
181
|
+
type: "message.ended", runId, payload: {messageId, role, content: messageContent(message)},
|
|
182
|
+
}, run.turnId))
|
|
183
|
+
return events
|
|
184
|
+
}
|
|
185
|
+
case "message_update": {
|
|
186
|
+
const update = event.assistantMessageEvent
|
|
187
|
+
if (update.type !== "text_delta" && update.type !== "thinking_delta" && update.type !== "toolcall_end") return []
|
|
188
|
+
const messageId = run.messages.get("assistant") ?? crypto.randomUUID()
|
|
189
|
+
run.messages.set("assistant", messageId)
|
|
190
|
+
if (update.type === "toolcall_end") return toolCallReady(run, update.toolCall, messageId)
|
|
191
|
+
let kind: "text" | "thinking_summary" = "text"
|
|
192
|
+
if (update.type === "thinking_delta") {
|
|
193
|
+
const part = update.partial.content[update.contentIndex]
|
|
194
|
+
if (part?.type !== "thinking" || (!part.narration && !part.summary)) return []
|
|
195
|
+
if (!part.narration) kind = "thinking_summary"
|
|
196
|
+
}
|
|
197
|
+
return [emit({type: "message.delta", runId, payload: {
|
|
198
|
+
messageId, partIndex: update.contentIndex, kind, delta: update.delta,
|
|
199
|
+
}}, run.turnId)]
|
|
200
|
+
}
|
|
201
|
+
case "tool_execution_start": {
|
|
202
|
+
const {toolCallId, toolName} = event
|
|
203
|
+
if (!run.toolCalls.has(toolCallId)) run.toolCalls.set(toolCallId, {turnId: run.turnId, ready: false})
|
|
204
|
+
return [emit({type: "tool.execution.started", runId, payload: {toolCallId, toolName}}, run.toolCalls.get(toolCallId)?.turnId)]
|
|
205
|
+
}
|
|
206
|
+
case "tool_execution_update": {
|
|
207
|
+
const snapshot = jsonValue(event.partialResult)
|
|
208
|
+
if (snapshot === undefined) return []
|
|
209
|
+
const {toolCallId} = event
|
|
210
|
+
return [emit({type: "tool.execution.updated", runId, payload: {toolCallId, snapshot}}, run.toolCalls.get(toolCallId)?.turnId)]
|
|
211
|
+
}
|
|
212
|
+
case "tool_execution_end": {
|
|
213
|
+
const {toolCallId} = event
|
|
214
|
+
const result = jsonValue(event.result)
|
|
215
|
+
return [emit({type: "tool.execution.ended", runId, payload: {
|
|
216
|
+
toolCallId, status: event.isError ? "failed" : "succeeded",
|
|
217
|
+
...(result !== undefined ? {result} : {}),
|
|
218
|
+
}}, run.toolCalls.get(toolCallId)?.turnId)]
|
|
219
|
+
}
|
|
220
|
+
case "auto_retry_start":
|
|
221
|
+
return [emit({type: "retry.started", runId, payload: {
|
|
222
|
+
attempt: event.attempt, maxAttempts: event.maxAttempts, delayMs: event.delayMs,
|
|
223
|
+
error: {message: event.errorMessage},
|
|
224
|
+
}})]
|
|
225
|
+
case "auto_retry_end":
|
|
226
|
+
return [emit({type: "retry.ended", runId, payload: {
|
|
227
|
+
attempt: event.attempt, success: event.success,
|
|
228
|
+
...(event.finalError ? {error: {message: event.finalError}} : {}),
|
|
229
|
+
}})]
|
|
230
|
+
default: return []
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
return {convert, dispose}
|
|
235
|
+
}
|
|
@@ -2,34 +2,56 @@ import type {AgentSession} from "@oh-my-pi/pi-coding-agent/session/agent-session
|
|
|
2
2
|
import {USER_INTERRUPT_LABEL} from "@oh-my-pi/pi-coding-agent/session/messages"
|
|
3
3
|
import {SessionManager} from "@oh-my-pi/pi-coding-agent/session/session-manager"
|
|
4
4
|
import {createAgentSession} from "@oh-my-pi/pi-coding-agent/sdk"
|
|
5
|
-
import type {AgentEvent, AgentOptions, UserOperation} from "
|
|
6
|
-
import {type AgentCore
|
|
5
|
+
import type {AgentEvent, AgentOptions, UserOperation} from "../../model.ts"
|
|
6
|
+
import {AbstractAgent, type AgentCore} from "../core.ts"
|
|
7
|
+
import {applyTurnConfig} from "./config.ts";
|
|
8
|
+
import {toEvents} from "./events.ts"
|
|
7
9
|
|
|
8
10
|
export async function CreateOhMyPiAgent(id: string, options: AgentOptions): Promise<AgentCore> {
|
|
9
11
|
const {session} = await createAgentSession({
|
|
10
12
|
cwd: options.cwd,
|
|
11
13
|
sessionManager: SessionManager.inMemory(),
|
|
12
14
|
})
|
|
15
|
+
await applyTurnConfig(session, options.setting)
|
|
13
16
|
|
|
14
|
-
session.setSteeringMode("all", false)
|
|
15
17
|
return new OhMyPiAgent(id, session)
|
|
16
18
|
}
|
|
17
19
|
|
|
18
20
|
class OhMyPiAgent extends AbstractAgent {
|
|
21
|
+
private readonly events: ReturnType<typeof toEvents>
|
|
22
|
+
private readonly listeners = new Set<(event: AgentEvent) => void>()
|
|
23
|
+
private unsubscribeCore?: () => void
|
|
24
|
+
|
|
19
25
|
constructor(id: string, private readonly core: AgentSession) {
|
|
20
26
|
super(id)
|
|
27
|
+
this.events = toEvents(id)
|
|
21
28
|
}
|
|
22
29
|
|
|
23
30
|
override subscribe(listener: (event: AgentEvent) => void): () => void {
|
|
24
|
-
|
|
31
|
+
this.listeners.add(listener)
|
|
32
|
+
this.unsubscribeCore ??= this.core.subscribe(event => this.publishEvents(this.events.convert(event)))
|
|
33
|
+
return () => { this.listeners.delete(listener) }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
private publishEvents(events: AgentEvent[]): void {
|
|
37
|
+
for (const event of events) {
|
|
38
|
+
for (const subscriber of this.listeners) subscriber(event)
|
|
39
|
+
}
|
|
25
40
|
}
|
|
26
41
|
|
|
27
42
|
override waitForEnd(): Promise<void> {
|
|
28
43
|
return this.core.waitForIdle()
|
|
29
44
|
}
|
|
30
45
|
|
|
31
|
-
protected override doDispose(): Promise<void> {
|
|
32
|
-
|
|
46
|
+
protected override async doDispose(): Promise<void> {
|
|
47
|
+
try {
|
|
48
|
+
await this.core.dispose()
|
|
49
|
+
this.publishEvents(this.events.dispose())
|
|
50
|
+
} finally {
|
|
51
|
+
this.unsubscribeCore?.()
|
|
52
|
+
this.unsubscribeCore = undefined
|
|
53
|
+
this.listeners.clear()
|
|
54
|
+
}
|
|
33
55
|
}
|
|
34
56
|
|
|
35
57
|
override async handleInput(input: UserOperation): Promise<void> {
|
|
@@ -52,13 +74,6 @@ class OhMyPiAgent extends AbstractAgent {
|
|
|
52
74
|
case "user-resume":
|
|
53
75
|
await this.core.resume()
|
|
54
76
|
return
|
|
55
|
-
|
|
56
|
-
default:
|
|
57
|
-
return assertNever(input)
|
|
58
77
|
}
|
|
59
78
|
}
|
|
60
79
|
}
|
|
61
|
-
|
|
62
|
-
function assertNever(_input: never): never {
|
|
63
|
-
throw new Error("Unsupported user operation")
|
|
64
|
-
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import {resolveModelFromString} from "@oh-my-pi/pi-coding-agent/config/model-resolver";
|
|
2
|
+
import type {Api, Model} from "@oh-my-pi/pi-ai";
|
|
3
|
+
|
|
4
|
+
export const GATEWAY_PROVIDER_PREFIX = "agent-gateway-"
|
|
5
|
+
|
|
6
|
+
const VENDOR_PROVIDERS: Record<string, readonly string[]> = {
|
|
7
|
+
gemini: ["google", "google-vertex"],
|
|
8
|
+
gemma: ["google", "google-vertex"],
|
|
9
|
+
xai: ["xai", "xai-oauth"],
|
|
10
|
+
kimi: ["kimi-code", "moonshot"],
|
|
11
|
+
glm: ["zai", "zhipu-coding-plan"],
|
|
12
|
+
minimax: ["minimax", "minimax-cn", "minimax-code", "minimax-code-cn"],
|
|
13
|
+
qwen: ["qwen-portal", "alibaba-token-plan"],
|
|
14
|
+
mimo: ["xiaomi", "xiaomi-token-plan-ams", "xiaomi-token-plan-cn", "xiaomi-token-plan-sgp"],
|
|
15
|
+
meta: ["meta", "muse-code"],
|
|
16
|
+
amazon: ["amazon-bedrock"],
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function pickTurnModel(
|
|
20
|
+
models: Model<Api>[],
|
|
21
|
+
modelId: string,
|
|
22
|
+
hasAuth: (model: Model<Api>) => boolean,
|
|
23
|
+
): Model<Api> | undefined {
|
|
24
|
+
if (models.length === 0) return undefined
|
|
25
|
+
|
|
26
|
+
const configured = models.filter(hasAuth)
|
|
27
|
+
const pool = configured.length > 0 ? configured : models
|
|
28
|
+
return pickCatalogModel(pool, modelId)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function pickCatalogModel(models: Model<Api>[], modelId: string): Model<Api> | undefined {
|
|
32
|
+
if (models.length === 0) return undefined
|
|
33
|
+
return pickVendorModel(models) ?? resolveModelFromString(modelId, models) ?? models[0]
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function pickVendorModel(models: Model<Api>[]): Model<Api> | undefined {
|
|
37
|
+
const vendor = models.find(model => model.identity.class !== "unknown")?.identity.class
|
|
38
|
+
if (!vendor) return undefined
|
|
39
|
+
|
|
40
|
+
for (const provider of VENDOR_PROVIDERS[vendor] ?? [vendor]) {
|
|
41
|
+
const match = models.find(model => model.provider === provider)
|
|
42
|
+
if (match) return match
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
return undefined
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function narrowerLimit(setting: number, catalog: number | null | undefined): number {
|
|
49
|
+
if (!catalog || catalog <= 0) return setting
|
|
50
|
+
if (!setting || setting <= 0) return catalog
|
|
51
|
+
return Math.min(setting, catalog)
|
|
52
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import {ThinkingLevel} from "@oh-my-pi/pi-agent-core/thinking";
|
|
2
|
+
import type {TurnConfig} from "../../model.ts";
|
|
3
|
+
|
|
4
|
+
export const thinkingLevels = {
|
|
5
|
+
none: ThinkingLevel.Off,
|
|
6
|
+
low: ThinkingLevel.Low,
|
|
7
|
+
medium: ThinkingLevel.Medium,
|
|
8
|
+
high: ThinkingLevel.High,
|
|
9
|
+
xhigh: ThinkingLevel.XHigh,
|
|
10
|
+
max: ThinkingLevel.Max,
|
|
11
|
+
ultra: ThinkingLevel.Max,
|
|
12
|
+
} satisfies Record<TurnConfig["thinkingLevel"], ThinkingLevel>
|
package/src/agent/store.ts
CHANGED
|
@@ -1,19 +1,37 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type {Submission} from "../model.ts";
|
|
2
|
+
import type {AgentEvent} from "../event.ts";
|
|
3
|
+
|
|
4
|
+
export type SessionCloseRequest = {
|
|
5
|
+
kind: "session-close"
|
|
6
|
+
session: string
|
|
7
|
+
replyTo: string
|
|
8
|
+
expiresAt: number
|
|
9
|
+
ownerId?: string
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type SessionCloseResult = {
|
|
13
|
+
kind: "session-close-result"
|
|
14
|
+
session: string
|
|
15
|
+
expiresAt: number
|
|
16
|
+
error?: string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export type PendingMessage = Submission | SessionCloseRequest | SessionCloseResult
|
|
2
20
|
|
|
3
21
|
export interface HistoryStore {
|
|
4
22
|
load_history_from_store(id: string): Promise<Array<AgentEvent>>
|
|
5
23
|
append_history_to_store(event: AgentEvent): Promise<void>
|
|
6
24
|
|
|
7
25
|
/** Take the currently queued batch without waiting for new messages. */
|
|
8
|
-
recall_pending_messages(id: string): Promise<
|
|
26
|
+
recall_pending_messages(id: string): Promise<PendingMessage[]>
|
|
9
27
|
|
|
10
28
|
/**
|
|
11
29
|
* Wait until messages are available and take a batch. On cancellation, return
|
|
12
30
|
* an empty batch if nothing was taken, or return the batch already taken.
|
|
13
31
|
*/
|
|
14
|
-
wait_and_recall_pending_messages(id: string, signal: AbortSignal): Promise<
|
|
32
|
+
wait_and_recall_pending_messages(id: string, signal: AbortSignal): Promise<PendingMessage[]>
|
|
15
33
|
|
|
16
|
-
submit_pending_messages(
|
|
34
|
+
submit_pending_messages(message: PendingMessage): Promise<void>
|
|
17
35
|
}
|
|
18
36
|
|
|
19
37
|
export function createMemoryPendingStore(): Pick<
|
|
@@ -22,10 +40,10 @@ export function createMemoryPendingStore(): Pick<
|
|
|
22
40
|
| "recall_pending_messages"
|
|
23
41
|
| "wait_and_recall_pending_messages"
|
|
24
42
|
> {
|
|
25
|
-
const queues = new Map<string,
|
|
26
|
-
const waiters = new Map<string, (batch:
|
|
43
|
+
const queues = new Map<string, PendingMessage[]>()
|
|
44
|
+
const waiters = new Map<string, (batch: PendingMessage[]) => void>()
|
|
27
45
|
|
|
28
|
-
function take(id: string):
|
|
46
|
+
function take(id: string): PendingMessage[] {
|
|
29
47
|
const batch = queues.get(id) ?? []
|
|
30
48
|
queues.delete(id)
|
|
31
49
|
return batch
|
|
@@ -59,10 +77,10 @@ export function createMemoryPendingStore(): Pick<
|
|
|
59
77
|
throw new Error(`Session ${id} already has a waiting consumer`)
|
|
60
78
|
}
|
|
61
79
|
|
|
62
|
-
return new Promise<
|
|
80
|
+
return new Promise<PendingMessage[]>(resolve => {
|
|
63
81
|
const cancel = () => finish([])
|
|
64
82
|
|
|
65
|
-
function finish(messages:
|
|
83
|
+
function finish(messages: PendingMessage[]) {
|
|
66
84
|
signal.removeEventListener("abort", cancel)
|
|
67
85
|
waiters.delete(id)
|
|
68
86
|
resolve(messages)
|
|
@@ -73,4 +91,4 @@ export function createMemoryPendingStore(): Pick<
|
|
|
73
91
|
})
|
|
74
92
|
},
|
|
75
93
|
}
|
|
76
|
-
}
|
|
94
|
+
}
|
package/src/buffer.ts
CHANGED
|
@@ -1,78 +1,80 @@
|
|
|
1
|
-
|
|
2
|
-
write: (chunk: string) => void | Promise<void>,
|
|
3
|
-
{ intervalMs = 30, charsPerTick = 4 } = {},
|
|
4
|
-
) {
|
|
5
|
-
if (!Number.isInteger(charsPerTick) || charsPerTick < 1) {
|
|
6
|
-
throw new RangeError("charsPerTick must be a positive integer");
|
|
7
|
-
}
|
|
8
|
-
if (!Number.isInteger(intervalMs) || intervalMs < 1 || intervalMs > 2_147_483_647) {
|
|
9
|
-
throw new RangeError("intervalMs is outside the supported timer range");
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
let buffer = "";
|
|
13
|
-
let ended = false;
|
|
14
|
-
let running = false;
|
|
15
|
-
let resolveDone!: () => void;
|
|
16
|
-
let rejectDone!: (error: unknown) => void;
|
|
1
|
+
import type {AgentEvent, AgentEventDelivery} from "./event.ts"
|
|
17
2
|
|
|
18
|
-
|
|
19
|
-
resolveDone = resolve;
|
|
20
|
-
rejectDone = reject;
|
|
21
|
-
});
|
|
3
|
+
const maxTimerMs = 2_147_483_647
|
|
22
4
|
|
|
23
|
-
|
|
24
|
-
if (running) return;
|
|
25
|
-
running = true;
|
|
5
|
+
type Delta = Extract<AgentEvent, {type: "message.delta"}>
|
|
26
6
|
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
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
|
|
11
|
+
}
|
|
30
12
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
13
|
+
export function createAgentEventSmoother(
|
|
14
|
+
write: (event: AgentEventDelivery) => void | Promise<void>,
|
|
15
|
+
{intervalMs = 16} = {},
|
|
16
|
+
) {
|
|
17
|
+
if (!Number.isInteger(intervalMs) || intervalMs < 1 || intervalMs > maxTimerMs) {
|
|
18
|
+
throw new RangeError("intervalMs is outside the supported timer range")
|
|
19
|
+
}
|
|
38
20
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
21
|
+
let active: {source: Delta; text: string} | undefined
|
|
22
|
+
let timer: ReturnType<typeof setTimeout> | undefined
|
|
23
|
+
let writes = Promise.resolve()
|
|
24
|
+
let ended = false
|
|
25
|
+
let seq = 0
|
|
43
26
|
|
|
44
|
-
|
|
27
|
+
function send(event: AgentEventDelivery): void {
|
|
28
|
+
writes = writes.then(() => write({...event, seq: ++seq}))
|
|
29
|
+
void writes.catch(() => undefined)
|
|
30
|
+
}
|
|
45
31
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
32
|
+
function flush(seal: boolean): void {
|
|
33
|
+
clearTimeout(timer)
|
|
34
|
+
timer = undefined
|
|
35
|
+
if (!active) return
|
|
50
36
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
running = false;
|
|
58
|
-
}
|
|
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}})
|
|
59
43
|
}
|
|
60
44
|
|
|
61
45
|
return {
|
|
62
|
-
push(
|
|
63
|
-
if (ended) throw new Error("The
|
|
64
|
-
if (!chunk) return;
|
|
46
|
+
push(event: AgentEvent): void {
|
|
47
|
+
if (ended) throw new Error("The event input is closed")
|
|
65
48
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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)
|
|
55
|
+
return
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (event.type === "message.ended" || event.type === "turn.ended" || event.type === "run.ended") {
|
|
59
|
+
flush(true)
|
|
60
|
+
}
|
|
69
61
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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)
|
|
71
|
+
}
|
|
74
72
|
},
|
|
75
73
|
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
74
|
+
end(): Promise<void> {
|
|
75
|
+
ended = true
|
|
76
|
+
flush(true)
|
|
77
|
+
return writes
|
|
78
|
+
},
|
|
79
|
+
}
|
|
80
|
+
}
|
package/src/event.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export type JsonValue =
|
|
2
|
+
| null | boolean | number | string
|
|
3
|
+
| JsonValue[]
|
|
4
|
+
| { [key: string]: JsonValue }
|
|
5
|
+
|
|
6
|
+
export type Outcome = "succeeded" | "failed" | "cancelled" | "unknown"
|
|
7
|
+
type EventError = { code?: string; message: string }
|
|
8
|
+
|
|
9
|
+
type MessageHeader = {
|
|
10
|
+
messageId: string
|
|
11
|
+
role: "user" | "assistant" | "system"
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type MessagePart = { partIndex: number } & (
|
|
15
|
+
| { kind: "text" | "thinking_summary"; text: string }
|
|
16
|
+
| { kind: "image"; data: string; mimeType: string }
|
|
17
|
+
| { kind: "tool_call"; toolCallId: string }
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
type Compaction = { compactionId: string; trigger: "automatic" | "manual"; strategy?: string }
|
|
21
|
+
|
|
22
|
+
type EventPayloads = {
|
|
23
|
+
"run.started": null
|
|
24
|
+
"run.paused": { yielded: boolean; awaiting: boolean }
|
|
25
|
+
"run.resumed": null
|
|
26
|
+
"run.ended": { status: Outcome; error?: EventError }
|
|
27
|
+
"turn.started": { turnId: string }
|
|
28
|
+
"turn.ended": { turnId: string; status: Outcome }
|
|
29
|
+
"message.started": MessageHeader
|
|
30
|
+
"message.delta": {
|
|
31
|
+
messageId: string
|
|
32
|
+
partIndex: number
|
|
33
|
+
kind: "text" | "thinking_summary"
|
|
34
|
+
delta: string
|
|
35
|
+
}
|
|
36
|
+
"message.ended": MessageHeader & { content: MessagePart[] }
|
|
37
|
+
"tool.call.ready": { toolCallId: string; messageId: string; toolName: string; args?: JsonValue }
|
|
38
|
+
"tool.execution.started": { toolCallId: string; toolName: string }
|
|
39
|
+
"tool.execution.updated": { toolCallId: string; snapshot: JsonValue }
|
|
40
|
+
"tool.execution.ended": {
|
|
41
|
+
toolCallId: string
|
|
42
|
+
status: Outcome
|
|
43
|
+
result?: JsonValue
|
|
44
|
+
error?: EventError
|
|
45
|
+
}
|
|
46
|
+
"retry.started": { attempt: number; maxAttempts: number; delayMs: number; error: EventError }
|
|
47
|
+
"retry.ended": { attempt: number; success: boolean; error?: EventError }
|
|
48
|
+
"context.compaction.started": Compaction & { reason?: string }
|
|
49
|
+
"context.compaction.ended": Compaction & {
|
|
50
|
+
status: Outcome | "skipped"
|
|
51
|
+
willRetry?: boolean
|
|
52
|
+
tokensBefore?: number
|
|
53
|
+
error?: EventError
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
type EventType = keyof EventPayloads
|
|
58
|
+
|
|
59
|
+
type EventData<Types extends EventType> = {
|
|
60
|
+
[Type in Types]: { type: Type; payload: EventPayloads[Type] } & (
|
|
61
|
+
Type extends "context.compaction.started" | "context.compaction.ended"
|
|
62
|
+
? { runId?: string }
|
|
63
|
+
: { runId: string }
|
|
64
|
+
)
|
|
65
|
+
}[Types]
|
|
66
|
+
|
|
67
|
+
type EventEnvelope = {
|
|
68
|
+
id: string
|
|
69
|
+
sessionId: string
|
|
70
|
+
turnId?: string
|
|
71
|
+
seq: number
|
|
72
|
+
timestamp: number
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export type AgentEventData = EventData<EventType>
|
|
76
|
+
export type AgentEvent = EventEnvelope & AgentEventData
|
|
77
|
+
|
|
78
|
+
export type AgentEventDelivery = EventEnvelope & (
|
|
79
|
+
| EventData<Exclude<EventType, "message.ended">>
|
|
80
|
+
| {type: "message.ended"; runId: string; payload: MessageHeader}
|
|
81
|
+
)
|
package/src/index.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
export * from './model'
|
|
2
2
|
export * from './manage'
|
|
3
|
-
export
|
|
4
|
-
export {
|
|
3
|
+
export * from './event'
|
|
4
|
+
export {createAgentEventSmoother} from './buffer.ts'
|
|
5
|
+
export type {HistoryStore, PendingMessage} from './agent/index.ts'
|
|
6
|
+
export {type AgentCore} from './agent/core.ts'
|
|
7
|
+
export {applyTurnConfig} from './agent/oh-my-pi/config.ts'
|
package/src/manage.ts
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
1
1
|
import type {AgentEventListener, AgentLife, AgentOptions, Submission} from "./model.ts"
|
|
2
|
-
import type {
|
|
2
|
+
import type {AgentEvent} from "./event.ts"
|
|
3
|
+
import type {HistoryStore, PendingMessage, SessionCloseRequest} from "./agent"
|
|
3
4
|
import type {AgentCore} from "./agent/core.ts"
|
|
4
|
-
import {CreateOhMyPiAgent} from "./agent/
|
|
5
|
+
import {CreateOhMyPiAgent} from "./agent/oh-my-pi";
|
|
6
|
+
import {createAgentEventSmoother} from "./buffer.ts"
|
|
7
|
+
|
|
8
|
+
const closeReplyPrefix = "@agent-core/close/"
|
|
9
|
+
const remoteCloseTimeout = 30_000
|
|
10
|
+
const ownerCheckInterval = 500
|
|
5
11
|
|
|
6
12
|
type SessionState = {
|
|
13
|
+
ownerId: string
|
|
7
14
|
closing: boolean
|
|
8
15
|
pendingWait?: AbortController
|
|
16
|
+
closeRequests: SessionCloseRequest[]
|
|
9
17
|
}
|
|
10
18
|
|
|
11
19
|
type ManagedSession = {
|
|
@@ -14,17 +22,54 @@ type ManagedSession = {
|
|
|
14
22
|
done: Promise<void>
|
|
15
23
|
}
|
|
16
24
|
|
|
25
|
+
type SessionListener = {
|
|
26
|
+
push(event: AgentEvent): void
|
|
27
|
+
flush(): Promise<void> | undefined
|
|
28
|
+
}
|
|
29
|
+
|
|
17
30
|
export class SessionManager {
|
|
18
31
|
private readonly sessions = new Map<string, ManagedSession>()
|
|
32
|
+
private readonly listeners = new Map<string, SessionListener>()
|
|
19
33
|
|
|
20
34
|
constructor(
|
|
21
35
|
private readonly store: HistoryStore,
|
|
22
36
|
private readonly life: AgentLife,
|
|
23
37
|
private readonly getCoreAgent: (id: string, options: AgentOptions) => Promise<AgentCore>,
|
|
24
|
-
private readonly listener?: AgentEventListener,
|
|
25
38
|
) {}
|
|
26
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
|
+
|
|
27
71
|
async submit(submission: Submission): Promise<void> {
|
|
72
|
+
this.validateSessionId(submission.session)
|
|
28
73
|
await this.store.submit_pending_messages(submission)
|
|
29
74
|
|
|
30
75
|
const {session: id, options} = submission
|
|
@@ -50,23 +95,82 @@ export class SessionManager {
|
|
|
50
95
|
}
|
|
51
96
|
|
|
52
97
|
async close(id: string): Promise<void> {
|
|
53
|
-
|
|
54
|
-
|
|
98
|
+
this.validateSessionId(id)
|
|
99
|
+
let session = this.sessions.get(id)
|
|
100
|
+
if (!session) {
|
|
101
|
+
const owner = await this.life.alive(id)
|
|
102
|
+
session = this.sessions.get(id)
|
|
103
|
+
if (!session) {
|
|
104
|
+
if (owner) await this.closeRemoteSession(id, owner)
|
|
105
|
+
return
|
|
106
|
+
}
|
|
107
|
+
}
|
|
55
108
|
|
|
56
|
-
session.state
|
|
57
|
-
session.state.pendingWait?.abort()
|
|
109
|
+
this.beginClose(session.state)
|
|
58
110
|
await session.done
|
|
59
111
|
}
|
|
60
112
|
|
|
113
|
+
private validateSessionId(id: string): void {
|
|
114
|
+
if (id.startsWith(closeReplyPrefix)) throw new Error(`Reserved session id: ${id}`)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
private beginClose(state: SessionState): void {
|
|
118
|
+
state.closing = true
|
|
119
|
+
state.pendingWait?.abort()
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private async closeRemoteSession(id: string, owner: string | true): Promise<void> {
|
|
123
|
+
const replyTo = `${closeReplyPrefix}${crypto.randomUUID()}`
|
|
124
|
+
const expiresAt = Date.now() + remoteCloseTimeout
|
|
125
|
+
const ownerId = typeof owner === "string" ? owner : undefined
|
|
126
|
+
const signal = AbortSignal.timeout(remoteCloseTimeout)
|
|
127
|
+
await this.store.submit_pending_messages({kind: "session-close", session: id, replyTo, expiresAt, ownerId})
|
|
128
|
+
|
|
129
|
+
while (!signal.aborted) {
|
|
130
|
+
const wait = ownerId === undefined ? signal : AbortSignal.any([signal, AbortSignal.timeout(ownerCheckInterval)])
|
|
131
|
+
const batch = await this.store.wait_and_recall_pending_messages(replyTo, wait)
|
|
132
|
+
if (this.readCloseResult(batch)) return
|
|
133
|
+
if (ownerId !== undefined && await this.life.alive(id) !== ownerId) {
|
|
134
|
+
this.readCloseResult(await this.store.recall_pending_messages(replyTo))
|
|
135
|
+
return
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
throw new Error(`Timed out waiting for session ${id} to close`)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
private readCloseResult(batch: PendingMessage[]): boolean {
|
|
143
|
+
for (const message of batch) {
|
|
144
|
+
if (!("kind" in message) || message.kind !== "session-close-result") continue
|
|
145
|
+
if (message.error !== undefined) throw new Error(message.error)
|
|
146
|
+
return true
|
|
147
|
+
}
|
|
148
|
+
return false
|
|
149
|
+
}
|
|
150
|
+
|
|
61
151
|
private startSession(id: string, options: AgentOptions): ManagedSession {
|
|
62
|
-
const
|
|
63
|
-
const
|
|
152
|
+
const ownerId = crypto.randomUUID()
|
|
153
|
+
const ready = Promise.resolve().then(async () => {
|
|
154
|
+
await this.life.report(id, ownerId)
|
|
155
|
+
return this.getCoreAgent(id, options)
|
|
156
|
+
})
|
|
157
|
+
const state: SessionState = {ownerId, closing: false, closeRequests: []}
|
|
64
158
|
const session: ManagedSession = {
|
|
65
159
|
state,
|
|
66
160
|
ready,
|
|
67
|
-
done: this.runSession(id, ready, state)
|
|
68
|
-
|
|
69
|
-
|
|
161
|
+
done: this.runSession(id, ready, state)
|
|
162
|
+
.catch(async error => {
|
|
163
|
+
await this.replyToCloseRequests(state.closeRequests.splice(0), String(error))
|
|
164
|
+
throw error
|
|
165
|
+
})
|
|
166
|
+
.finally(async () => {
|
|
167
|
+
try {
|
|
168
|
+
await this.life.release?.(id, ownerId)
|
|
169
|
+
} finally {
|
|
170
|
+
this.sessions.delete(id)
|
|
171
|
+
}
|
|
172
|
+
})
|
|
173
|
+
.then(() => this.replyToCloseRequests(state.closeRequests)),
|
|
70
174
|
}
|
|
71
175
|
|
|
72
176
|
this.sessions.set(id, session)
|
|
@@ -74,27 +178,37 @@ export class SessionManager {
|
|
|
74
178
|
return session
|
|
75
179
|
}
|
|
76
180
|
|
|
181
|
+
private async replyToCloseRequests(requests: SessionCloseRequest[], error?: string): Promise<void> {
|
|
182
|
+
await Promise.all(requests.map(async ({replyTo, expiresAt}) => {
|
|
183
|
+
if (expiresAt <= Date.now()) return
|
|
184
|
+
await this.store.submit_pending_messages({
|
|
185
|
+
kind: "session-close-result", session: replyTo, expiresAt, error,
|
|
186
|
+
})
|
|
187
|
+
}))
|
|
188
|
+
}
|
|
189
|
+
|
|
77
190
|
private async runSession(id: string, ready: Promise<AgentCore>, state: SessionState): Promise<void> {
|
|
78
191
|
const agent = await ready
|
|
79
|
-
let
|
|
192
|
+
let historyWrites = Promise.resolve()
|
|
80
193
|
let unsubscribe: (() => void) | undefined
|
|
81
194
|
|
|
82
195
|
try {
|
|
83
196
|
unsubscribe = agent.subscribe(event => {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
197
|
+
if (event.type !== "message.delta") {
|
|
198
|
+
historyWrites = historyWrites.then(() => this.store.append_history_to_store(event))
|
|
199
|
+
.catch(error => console.error("事件写入历史失败", id, event.type, error))
|
|
200
|
+
}
|
|
201
|
+
this.listeners.get(id)?.push(event)
|
|
88
202
|
})
|
|
89
203
|
|
|
90
|
-
agent.startHeartbeat(() => this.life.report(id))
|
|
204
|
+
agent.startHeartbeat(() => this.life.report(id, state.ownerId))
|
|
91
205
|
await this.consumePending(id, agent, state)
|
|
92
206
|
} finally {
|
|
93
207
|
try {
|
|
94
208
|
await agent.dispose()
|
|
95
209
|
} finally {
|
|
96
210
|
unsubscribe?.()
|
|
97
|
-
await
|
|
211
|
+
await Promise.all([historyWrites, this.listeners.get(id)?.flush()])
|
|
98
212
|
}
|
|
99
213
|
}
|
|
100
214
|
}
|
|
@@ -103,7 +217,7 @@ export class SessionManager {
|
|
|
103
217
|
const running = new Set<Promise<void>>()
|
|
104
218
|
|
|
105
219
|
while (true) {
|
|
106
|
-
let batch:
|
|
220
|
+
let batch: PendingMessage[]
|
|
107
221
|
if (state.closing && running.size === 0) {
|
|
108
222
|
batch = await this.store.recall_pending_messages(id)
|
|
109
223
|
if (batch.length === 0) break
|
|
@@ -117,7 +231,17 @@ export class SessionManager {
|
|
|
117
231
|
}
|
|
118
232
|
}
|
|
119
233
|
|
|
120
|
-
for (const
|
|
234
|
+
for (const message of batch) {
|
|
235
|
+
if ("kind" in message) {
|
|
236
|
+
if (message.kind === "session-close" && message.expiresAt > Date.now() &&
|
|
237
|
+
(message.ownerId === undefined || message.ownerId === state.ownerId)) {
|
|
238
|
+
state.closeRequests.push(message)
|
|
239
|
+
this.beginClose(state)
|
|
240
|
+
}
|
|
241
|
+
continue
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const {operation, options} = message
|
|
121
245
|
const task = agent.handleInput(operation, options)
|
|
122
246
|
.catch(error => console.error("处理操作失败", id, operation.kind, error))
|
|
123
247
|
running.add(task)
|
|
@@ -135,9 +259,8 @@ export class SessionManager {
|
|
|
135
259
|
export function createManager(
|
|
136
260
|
store: HistoryStore,
|
|
137
261
|
life: AgentLife,
|
|
138
|
-
listener?: AgentEventListener,
|
|
139
262
|
): SessionManager {
|
|
140
263
|
return new SessionManager(store, life, async (id, options) => {
|
|
141
264
|
return CreateOhMyPiAgent(id, options)
|
|
142
|
-
}
|
|
265
|
+
})
|
|
143
266
|
}
|
package/src/model.ts
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import type {AgentEventDelivery} from "./event.ts"
|
|
2
|
+
|
|
3
|
+
export type {AgentEvent} from "./event.ts"
|
|
4
|
+
|
|
1
5
|
export type UserInput = {
|
|
2
6
|
kind: "user-input"
|
|
3
7
|
|
|
@@ -7,7 +11,7 @@ export type UserInput = {
|
|
|
7
11
|
skills: {
|
|
8
12
|
name: string
|
|
9
13
|
path: string
|
|
10
|
-
}
|
|
14
|
+
}[]
|
|
11
15
|
|
|
12
16
|
attachments: {
|
|
13
17
|
index: number,
|
|
@@ -43,13 +47,21 @@ export type AgentOptions = {
|
|
|
43
47
|
setting: TurnConfig
|
|
44
48
|
}
|
|
45
49
|
|
|
50
|
+
export type TurnProtocol =
|
|
51
|
+
| 'openai-responses'
|
|
52
|
+
| 'openai-completions'
|
|
53
|
+
| 'anthropic-messages'
|
|
54
|
+
| 'google-generative-ai'
|
|
55
|
+
| 'azure-openai-responses'
|
|
56
|
+
|
|
46
57
|
export type TurnConfig = {
|
|
47
58
|
revision: number
|
|
48
|
-
|
|
59
|
+
protocol: TurnProtocol
|
|
49
60
|
baseurl?: string
|
|
50
61
|
model: string
|
|
51
62
|
apiKey: string
|
|
52
|
-
contextWindow: number
|
|
63
|
+
contextWindow: number,
|
|
64
|
+
maxTokens: number,
|
|
53
65
|
thinkingLevel: 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',
|
|
54
66
|
}
|
|
55
67
|
|
|
@@ -61,17 +73,14 @@ export type Submission = {
|
|
|
61
73
|
operation: UserOperation
|
|
62
74
|
}
|
|
63
75
|
|
|
64
|
-
export type AgentEvent = {
|
|
65
|
-
type: string
|
|
66
|
-
usage?: any
|
|
67
|
-
}
|
|
68
|
-
|
|
69
76
|
export interface AgentEventListener {
|
|
70
|
-
onEvent(evt:
|
|
77
|
+
onEvent(evt: AgentEventDelivery): Promise<void>
|
|
71
78
|
}
|
|
72
79
|
|
|
73
80
|
export interface AgentLife {
|
|
74
|
-
alive(id: string): Promise<boolean>
|
|
81
|
+
alive(id: string): Promise<boolean | string>
|
|
82
|
+
|
|
83
|
+
report(id: string, ownerId: string): Promise<void>
|
|
75
84
|
|
|
76
|
-
|
|
85
|
+
release?(id: string, ownerId: string): Promise<void>
|
|
77
86
|
}
|