@centlu/agent-core 0.1.1 → 0.2.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/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 +130 -8
- package/src/event.ts +81 -0
- package/src/index.ts +5 -2
- package/src/manage.ts +115 -20
- package/src/model.ts +20 -11
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@centlu/agent-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.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,17 +1,35 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
import type {AgentEvent, AgentEventDelivery} from "./event.ts"
|
|
2
|
+
|
|
3
|
+
const maxTimerMs = 2_147_483_647
|
|
4
|
+
|
|
5
|
+
function validatePacing(intervalMs: number, charsPerTick: number, bufferMs: number) {
|
|
5
6
|
if (!Number.isInteger(charsPerTick) || charsPerTick < 1) {
|
|
6
7
|
throw new RangeError("charsPerTick must be a positive integer");
|
|
7
8
|
}
|
|
8
|
-
if (!Number.isInteger(intervalMs) || intervalMs < 1 || intervalMs >
|
|
9
|
+
if (!Number.isInteger(intervalMs) || intervalMs < 1 || intervalMs > maxTimerMs) {
|
|
9
10
|
throw new RangeError("intervalMs is outside the supported timer range");
|
|
10
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)
|
|
11
26
|
|
|
12
27
|
let buffer = "";
|
|
13
28
|
let ended = false;
|
|
14
29
|
let running = false;
|
|
30
|
+
let started = bufferMs === 0
|
|
31
|
+
const reserveChars = Math.ceil(bufferMs / intervalMs)
|
|
32
|
+
let releaseBuffer: (() => void) | undefined
|
|
15
33
|
let resolveDone!: () => void;
|
|
16
34
|
let rejectDone!: (error: unknown) => void;
|
|
17
35
|
|
|
@@ -25,11 +43,23 @@ export function createEventSmoother(
|
|
|
25
43
|
running = true;
|
|
26
44
|
|
|
27
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
|
|
28
57
|
while (buffer) {
|
|
29
|
-
await
|
|
58
|
+
await wait(intervalMs);
|
|
30
59
|
|
|
31
60
|
let end = 0;
|
|
32
61
|
let count = 0;
|
|
62
|
+
const limit = !ended && buffer.length <= reserveChars ? 1 : charsPerTick
|
|
33
63
|
for (const char of buffer) {
|
|
34
64
|
// 保留末尾单独的高代理项,等待下一段补齐 emoji 等字符。
|
|
35
65
|
if (!ended && end + 1 === buffer.length && /[\uD800-\uDBFF]/.test(char)) {
|
|
@@ -38,7 +68,7 @@ export function createEventSmoother(
|
|
|
38
68
|
|
|
39
69
|
end += char.length;
|
|
40
70
|
count += 1;
|
|
41
|
-
if (count ===
|
|
71
|
+
if (count === limit) break;
|
|
42
72
|
}
|
|
43
73
|
|
|
44
74
|
if (end === 0) break;
|
|
@@ -64,15 +94,107 @@ export function createEventSmoother(
|
|
|
64
94
|
if (!chunk) return;
|
|
65
95
|
|
|
66
96
|
buffer += chunk;
|
|
97
|
+
if (buffer.length >= reserveChars * charsPerTick) releaseBuffer?.()
|
|
67
98
|
void drain();
|
|
68
99
|
},
|
|
69
100
|
|
|
70
101
|
end() {
|
|
71
102
|
ended = true;
|
|
103
|
+
releaseBuffer?.()
|
|
72
104
|
void drain();
|
|
73
105
|
return done;
|
|
74
106
|
},
|
|
75
107
|
|
|
76
108
|
done,
|
|
77
109
|
};
|
|
78
|
-
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export function createAgentEventSmoother(
|
|
113
|
+
write: (event: AgentEventDelivery) => void | Promise<void>,
|
|
114
|
+
{intervalMs = 16, charsPerTick = 3, bufferMs = 200} = {},
|
|
115
|
+
) {
|
|
116
|
+
validatePacing(intervalMs, charsPerTick, bufferMs)
|
|
117
|
+
type Delta = Extract<AgentEvent, {type: "message.delta"}>
|
|
118
|
+
let pending: Promise<void> | undefined
|
|
119
|
+
let writes = Promise.resolve()
|
|
120
|
+
let ended = false
|
|
121
|
+
let seq = 0
|
|
122
|
+
let nextDeltaAt = 0
|
|
123
|
+
let active: {source: Delta; smoother: ReturnType<typeof createEventSmoother>} | undefined
|
|
124
|
+
|
|
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
|
+
})
|
|
137
|
+
void writes.catch(() => undefined)
|
|
138
|
+
return writes
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function seal() {
|
|
142
|
+
if (!active) return
|
|
143
|
+
void active.smoother.end()
|
|
144
|
+
active = undefined
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
return {
|
|
148
|
+
push(event: AgentEvent): void {
|
|
149
|
+
if (ended) throw new Error("The event input is closed")
|
|
150
|
+
|
|
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)
|
|
166
|
+
return
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (event.type !== "message.delta") {
|
|
170
|
+
void send(event)
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
|
|
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)
|
|
189
|
+
}
|
|
190
|
+
active.smoother.push(event.payload.delta)
|
|
191
|
+
},
|
|
192
|
+
|
|
193
|
+
async end(): Promise<void> {
|
|
194
|
+
ended = true
|
|
195
|
+
seal()
|
|
196
|
+
await pending
|
|
197
|
+
await writes
|
|
198
|
+
},
|
|
199
|
+
}
|
|
200
|
+
}
|
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,18 @@
|
|
|
1
1
|
import type {AgentEventListener, AgentLife, AgentOptions, Submission} from "./model.ts"
|
|
2
|
-
import type {HistoryStore} from "./agent"
|
|
2
|
+
import type {HistoryStore, PendingMessage, SessionCloseRequest} from "./agent"
|
|
3
3
|
import type {AgentCore} from "./agent/core.ts"
|
|
4
|
-
import {CreateOhMyPiAgent} from "./agent/
|
|
4
|
+
import {CreateOhMyPiAgent} from "./agent/oh-my-pi";
|
|
5
|
+
import {createAgentEventSmoother} from "./buffer.ts"
|
|
6
|
+
|
|
7
|
+
const closeReplyPrefix = "@agent-core/close/"
|
|
8
|
+
const remoteCloseTimeout = 30_000
|
|
9
|
+
const ownerCheckInterval = 500
|
|
5
10
|
|
|
6
11
|
type SessionState = {
|
|
12
|
+
ownerId: string
|
|
7
13
|
closing: boolean
|
|
8
14
|
pendingWait?: AbortController
|
|
15
|
+
closeRequests: SessionCloseRequest[]
|
|
9
16
|
}
|
|
10
17
|
|
|
11
18
|
type ManagedSession = {
|
|
@@ -25,6 +32,7 @@ export class SessionManager {
|
|
|
25
32
|
) {}
|
|
26
33
|
|
|
27
34
|
async submit(submission: Submission): Promise<void> {
|
|
35
|
+
this.validateSessionId(submission.session)
|
|
28
36
|
await this.store.submit_pending_messages(submission)
|
|
29
37
|
|
|
30
38
|
const {session: id, options} = submission
|
|
@@ -50,23 +58,82 @@ export class SessionManager {
|
|
|
50
58
|
}
|
|
51
59
|
|
|
52
60
|
async close(id: string): Promise<void> {
|
|
53
|
-
|
|
54
|
-
|
|
61
|
+
this.validateSessionId(id)
|
|
62
|
+
let session = this.sessions.get(id)
|
|
63
|
+
if (!session) {
|
|
64
|
+
const owner = await this.life.alive(id)
|
|
65
|
+
session = this.sessions.get(id)
|
|
66
|
+
if (!session) {
|
|
67
|
+
if (owner) await this.closeRemoteSession(id, owner)
|
|
68
|
+
return
|
|
69
|
+
}
|
|
70
|
+
}
|
|
55
71
|
|
|
56
|
-
session.state
|
|
57
|
-
session.state.pendingWait?.abort()
|
|
72
|
+
this.beginClose(session.state)
|
|
58
73
|
await session.done
|
|
59
74
|
}
|
|
60
75
|
|
|
76
|
+
private validateSessionId(id: string): void {
|
|
77
|
+
if (id.startsWith(closeReplyPrefix)) throw new Error(`Reserved session id: ${id}`)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private beginClose(state: SessionState): void {
|
|
81
|
+
state.closing = true
|
|
82
|
+
state.pendingWait?.abort()
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
private async closeRemoteSession(id: string, owner: string | true): Promise<void> {
|
|
86
|
+
const replyTo = `${closeReplyPrefix}${crypto.randomUUID()}`
|
|
87
|
+
const expiresAt = Date.now() + remoteCloseTimeout
|
|
88
|
+
const ownerId = typeof owner === "string" ? owner : undefined
|
|
89
|
+
const signal = AbortSignal.timeout(remoteCloseTimeout)
|
|
90
|
+
await this.store.submit_pending_messages({kind: "session-close", session: id, replyTo, expiresAt, ownerId})
|
|
91
|
+
|
|
92
|
+
while (!signal.aborted) {
|
|
93
|
+
const wait = ownerId === undefined ? signal : AbortSignal.any([signal, AbortSignal.timeout(ownerCheckInterval)])
|
|
94
|
+
const batch = await this.store.wait_and_recall_pending_messages(replyTo, wait)
|
|
95
|
+
if (this.readCloseResult(batch)) return
|
|
96
|
+
if (ownerId !== undefined && await this.life.alive(id) !== ownerId) {
|
|
97
|
+
this.readCloseResult(await this.store.recall_pending_messages(replyTo))
|
|
98
|
+
return
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
throw new Error(`Timed out waiting for session ${id} to close`)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private readCloseResult(batch: PendingMessage[]): boolean {
|
|
106
|
+
for (const message of batch) {
|
|
107
|
+
if (!("kind" in message) || message.kind !== "session-close-result") continue
|
|
108
|
+
if (message.error !== undefined) throw new Error(message.error)
|
|
109
|
+
return true
|
|
110
|
+
}
|
|
111
|
+
return false
|
|
112
|
+
}
|
|
113
|
+
|
|
61
114
|
private startSession(id: string, options: AgentOptions): ManagedSession {
|
|
62
|
-
const
|
|
63
|
-
const
|
|
115
|
+
const ownerId = crypto.randomUUID()
|
|
116
|
+
const ready = Promise.resolve().then(async () => {
|
|
117
|
+
await this.life.report(id, ownerId)
|
|
118
|
+
return this.getCoreAgent(id, options)
|
|
119
|
+
})
|
|
120
|
+
const state: SessionState = {ownerId, closing: false, closeRequests: []}
|
|
64
121
|
const session: ManagedSession = {
|
|
65
122
|
state,
|
|
66
123
|
ready,
|
|
67
|
-
done: this.runSession(id, ready, state)
|
|
68
|
-
|
|
69
|
-
|
|
124
|
+
done: this.runSession(id, ready, state)
|
|
125
|
+
.catch(async error => {
|
|
126
|
+
await this.replyToCloseRequests(state.closeRequests.splice(0), String(error))
|
|
127
|
+
throw error
|
|
128
|
+
})
|
|
129
|
+
.finally(async () => {
|
|
130
|
+
try {
|
|
131
|
+
await this.life.release?.(id, ownerId)
|
|
132
|
+
} finally {
|
|
133
|
+
this.sessions.delete(id)
|
|
134
|
+
}
|
|
135
|
+
})
|
|
136
|
+
.then(() => this.replyToCloseRequests(state.closeRequests)),
|
|
70
137
|
}
|
|
71
138
|
|
|
72
139
|
this.sessions.set(id, session)
|
|
@@ -74,27 +141,45 @@ export class SessionManager {
|
|
|
74
141
|
return session
|
|
75
142
|
}
|
|
76
143
|
|
|
144
|
+
private async replyToCloseRequests(requests: SessionCloseRequest[], error?: string): Promise<void> {
|
|
145
|
+
await Promise.all(requests.map(async ({replyTo, expiresAt}) => {
|
|
146
|
+
if (expiresAt <= Date.now()) return
|
|
147
|
+
await this.store.submit_pending_messages({
|
|
148
|
+
kind: "session-close-result", session: replyTo, expiresAt, error,
|
|
149
|
+
})
|
|
150
|
+
}))
|
|
151
|
+
}
|
|
152
|
+
|
|
77
153
|
private async runSession(id: string, ready: Promise<AgentCore>, state: SessionState): Promise<void> {
|
|
78
154
|
const agent = await ready
|
|
79
|
-
|
|
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
|
+
let historyWrites = Promise.resolve()
|
|
80
164
|
let unsubscribe: (() => void) | undefined
|
|
81
165
|
|
|
82
166
|
try {
|
|
83
167
|
unsubscribe = agent.subscribe(event => {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
}
|
|
168
|
+
if (event.type !== "message.delta") {
|
|
169
|
+
historyWrites = historyWrites.then(() => this.store.append_history_to_store(event))
|
|
170
|
+
.catch(error => console.error("事件写入历史失败", id, event.type, error))
|
|
171
|
+
}
|
|
172
|
+
delivery?.push(event)
|
|
88
173
|
})
|
|
89
174
|
|
|
90
|
-
agent.startHeartbeat(() => this.life.report(id))
|
|
175
|
+
agent.startHeartbeat(() => this.life.report(id, state.ownerId))
|
|
91
176
|
await this.consumePending(id, agent, state)
|
|
92
177
|
} finally {
|
|
93
178
|
try {
|
|
94
179
|
await agent.dispose()
|
|
95
180
|
} finally {
|
|
96
181
|
unsubscribe?.()
|
|
97
|
-
await
|
|
182
|
+
await Promise.all([historyWrites, delivery?.end()])
|
|
98
183
|
}
|
|
99
184
|
}
|
|
100
185
|
}
|
|
@@ -103,7 +188,7 @@ export class SessionManager {
|
|
|
103
188
|
const running = new Set<Promise<void>>()
|
|
104
189
|
|
|
105
190
|
while (true) {
|
|
106
|
-
let batch:
|
|
191
|
+
let batch: PendingMessage[]
|
|
107
192
|
if (state.closing && running.size === 0) {
|
|
108
193
|
batch = await this.store.recall_pending_messages(id)
|
|
109
194
|
if (batch.length === 0) break
|
|
@@ -117,7 +202,17 @@ export class SessionManager {
|
|
|
117
202
|
}
|
|
118
203
|
}
|
|
119
204
|
|
|
120
|
-
for (const
|
|
205
|
+
for (const message of batch) {
|
|
206
|
+
if ("kind" in message) {
|
|
207
|
+
if (message.kind === "session-close" && message.expiresAt > Date.now() &&
|
|
208
|
+
(message.ownerId === undefined || message.ownerId === state.ownerId)) {
|
|
209
|
+
state.closeRequests.push(message)
|
|
210
|
+
this.beginClose(state)
|
|
211
|
+
}
|
|
212
|
+
continue
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const {operation, options} = message
|
|
121
216
|
const task = agent.handleInput(operation, options)
|
|
122
217
|
.catch(error => console.error("处理操作失败", id, operation.kind, error))
|
|
123
218
|
running.add(task)
|
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
|
}
|