@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/package.json CHANGED
@@ -1,7 +1,11 @@
1
1
  {
2
2
  "name": "@centlu/agent-core",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Core TypeScript types for Bun-based agents.",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/ilovejavac/agent-core.git"
8
+ },
5
9
  "type": "module",
6
10
  "types": "./src/index.ts",
7
11
  "exports": {
@@ -21,6 +25,7 @@
21
25
  "access": "public"
22
26
  },
23
27
  "dependencies": {
28
+ "@oh-my-pi/pi-agent-core": "^19.1.0",
24
29
  "@oh-my-pi/pi-coding-agent": "^19.1.0"
25
30
  }
26
31
  }
package/src/agent/core.ts CHANGED
@@ -1,10 +1,15 @@
1
- import type {AgentEvent, AgentOptions, UserOperation} from "../model.ts"
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, 5000)
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 "../model.ts"
6
- import {type AgentCore, AbstractAgent} from "./core.ts"
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
- return this.core.subscribe(listener)
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
- return this.core.dispose()
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>