@centlu/agent-core 0.1.0 → 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/src/manage.ts CHANGED
@@ -1,10 +1,18 @@
1
1
  import type {AgentEventListener, AgentLife, AgentOptions, Submission} from "./model.ts"
2
- import type {HistoryStore} from "./agent/store.ts"
2
+ import type {HistoryStore, PendingMessage, SessionCloseRequest} from "./agent"
3
3
  import type {AgentCore} from "./agent/core.ts"
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
4
10
 
5
11
  type SessionState = {
12
+ ownerId: string
6
13
  closing: boolean
7
14
  pendingWait?: AbortController
15
+ closeRequests: SessionCloseRequest[]
8
16
  }
9
17
 
10
18
  type ManagedSession = {
@@ -24,6 +32,7 @@ export class SessionManager {
24
32
  ) {}
25
33
 
26
34
  async submit(submission: Submission): Promise<void> {
35
+ this.validateSessionId(submission.session)
27
36
  await this.store.submit_pending_messages(submission)
28
37
 
29
38
  const {session: id, options} = submission
@@ -49,23 +58,82 @@ export class SessionManager {
49
58
  }
50
59
 
51
60
  async close(id: string): Promise<void> {
52
- const session = this.sessions.get(id)
53
- if (!session) return
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
+ }
54
71
 
55
- session.state.closing = true
56
- session.state.pendingWait?.abort()
72
+ this.beginClose(session.state)
57
73
  await session.done
58
74
  }
59
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
+
60
114
  private startSession(id: string, options: AgentOptions): ManagedSession {
61
- const ready = Promise.resolve().then(() => this.getCoreAgent(id, options))
62
- const state: SessionState = {closing: false}
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: []}
63
121
  const session: ManagedSession = {
64
122
  state,
65
123
  ready,
66
- done: this.runSession(id, ready, state).finally(() => {
67
- this.sessions.delete(id)
68
- }),
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)),
69
137
  }
70
138
 
71
139
  this.sessions.set(id, session)
@@ -73,27 +141,45 @@ export class SessionManager {
73
141
  return session
74
142
  }
75
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
+
76
153
  private async runSession(id: string, ready: Promise<AgentCore>, state: SessionState): Promise<void> {
77
154
  const agent = await ready
78
- let events = Promise.resolve()
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()
79
164
  let unsubscribe: (() => void) | undefined
80
165
 
81
166
  try {
82
167
  unsubscribe = agent.subscribe(event => {
83
- events = events.then(async () => {
84
- await this.store.append_history_to_store(event)
85
- await this.listener?.onEvent(event)
86
- }).catch(error => console.error("事件处理失败", id, event.type, error))
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)
87
173
  })
88
174
 
89
- agent.startHeartbeat(() => this.life.report(id))
175
+ agent.startHeartbeat(() => this.life.report(id, state.ownerId))
90
176
  await this.consumePending(id, agent, state)
91
177
  } finally {
92
178
  try {
93
179
  await agent.dispose()
94
180
  } finally {
95
181
  unsubscribe?.()
96
- await events
182
+ await Promise.all([historyWrites, delivery?.end()])
97
183
  }
98
184
  }
99
185
  }
@@ -102,7 +188,7 @@ export class SessionManager {
102
188
  const running = new Set<Promise<void>>()
103
189
 
104
190
  while (true) {
105
- let batch: Submission[]
191
+ let batch: PendingMessage[]
106
192
  if (state.closing && running.size === 0) {
107
193
  batch = await this.store.recall_pending_messages(id)
108
194
  if (batch.length === 0) break
@@ -116,7 +202,17 @@ export class SessionManager {
116
202
  }
117
203
  }
118
204
 
119
- for (const {operation, options} of batch) {
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
120
216
  const task = agent.handleInput(operation, options)
121
217
  .catch(error => console.error("处理操作失败", id, operation.kind, error))
122
218
  running.add(task)
@@ -137,7 +233,6 @@ export function createManager(
137
233
  listener?: AgentEventListener,
138
234
  ): SessionManager {
139
235
  return new SessionManager(store, life, async (id, options) => {
140
- const {CreateOhMyPiAgent} = await import("./agent/omp.ts")
141
236
  return CreateOhMyPiAgent(id, options)
142
237
  }, listener)
143
- }
238
+ }
package/src/model.ts CHANGED
@@ -1,78 +1,86 @@
1
- export type UserInput = {
2
- kind: "user-input"
3
-
4
- mode: 'steer' | 'followup'
5
- prompt: string
6
-
7
- skills: {
8
- name: string
9
- path: string
10
- }
11
-
12
- attachments: {
13
- index: number,
14
- path: string,
15
- detail: string
16
- }[]
17
-
18
- mentions: {
19
- name: string,
20
- path: string
21
- }[]
22
- }
23
-
24
- export type UserInterrupt = {
25
- kind: "user-interrupt"
26
- }
27
-
28
- export type UserResume = {
29
- kind: "user-resume"
30
- }
31
-
32
- export type UserCompact = {
33
- kind: "user-compact"
34
- }
35
-
36
- export type UserSettingOverride = {
37
- kind: "user-setting-override"
38
- setting: TurnConfig
39
- }
40
-
41
- export type AgentOptions = {
42
- cwd: string,
43
- setting: TurnConfig
44
- }
45
-
46
- export type TurnConfig = {
47
- revision: number
48
- provider: 'openai' | 'anthropic' | 'google' | 'grok' | 'kimi' | 'deepseek'
49
- baseurl?: string
50
- model: string
51
- apiKey: string
52
- contextWindow: number
53
- thinkingLevel: 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',
54
- }
55
-
56
- export type UserOperation = UserInput | UserInterrupt | UserCompact | UserResume
57
-
58
- export type Submission = {
59
- session: string,
60
- options: AgentOptions,
61
- operation: UserOperation
62
- }
63
-
64
- // agent-task[turn1, turn2, turn3.. ...turnN]
65
-
66
- export type AgentEvent = {
67
- type: string
68
- }
69
-
70
- export interface AgentEventListener {
71
- onEvent(evt: AgentEvent): Promise<void>
72
- }
73
-
74
- export interface AgentLife {
75
- alive(id: string): Promise<boolean>
76
-
77
- report(id: string): Promise<void>
78
- }
1
+ import type {AgentEventDelivery} from "./event.ts"
2
+
3
+ export type {AgentEvent} from "./event.ts"
4
+
5
+ export type UserInput = {
6
+ kind: "user-input"
7
+
8
+ mode: 'steer' | 'followup'
9
+ prompt: string
10
+
11
+ skills: {
12
+ name: string
13
+ path: string
14
+ }[]
15
+
16
+ attachments: {
17
+ index: number,
18
+ path: string,
19
+ detail: string
20
+ }[]
21
+
22
+ mentions: {
23
+ name: string,
24
+ path: string
25
+ }[]
26
+ }
27
+
28
+ export type UserInterrupt = {
29
+ kind: "user-interrupt"
30
+ }
31
+
32
+ export type UserResume = {
33
+ kind: "user-resume"
34
+ }
35
+
36
+ export type UserCompact = {
37
+ kind: "user-compact"
38
+ }
39
+
40
+ export type UserSettingOverride = {
41
+ kind: "user-setting-override"
42
+ setting: TurnConfig
43
+ }
44
+
45
+ export type AgentOptions = {
46
+ cwd: string,
47
+ setting: TurnConfig
48
+ }
49
+
50
+ export type TurnProtocol =
51
+ | 'openai-responses'
52
+ | 'openai-completions'
53
+ | 'anthropic-messages'
54
+ | 'google-generative-ai'
55
+ | 'azure-openai-responses'
56
+
57
+ export type TurnConfig = {
58
+ revision: number
59
+ protocol: TurnProtocol
60
+ baseurl?: string
61
+ model: string
62
+ apiKey: string
63
+ contextWindow: number,
64
+ maxTokens: number,
65
+ thinkingLevel: 'none' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'ultra',
66
+ }
67
+
68
+ export type UserOperation = UserInput | UserInterrupt | UserCompact | UserResume
69
+
70
+ export type Submission = {
71
+ session: string,
72
+ options: AgentOptions,
73
+ operation: UserOperation
74
+ }
75
+
76
+ export interface AgentEventListener {
77
+ onEvent(evt: AgentEventDelivery): Promise<void>
78
+ }
79
+
80
+ export interface AgentLife {
81
+ alive(id: string): Promise<boolean | string>
82
+
83
+ report(id: string, ownerId: string): Promise<void>
84
+
85
+ release?(id: string, ownerId: string): Promise<void>
86
+ }