@myrialabs/clopen 0.4.15 → 0.4.16
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/backend/artifacts/matrix.ts +8 -0
- package/backend/artifacts/types.ts +2 -2
- package/backend/auth/permissions.ts +14 -0
- package/backend/chat/stream-manager.ts +5 -5
- package/backend/commands/detect.ts +1 -1
- package/backend/commands/sync.ts +1 -1
- package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
- package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
- package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
- package/backend/database/migrations/index.ts +21 -0
- package/backend/engine/README.md +36 -13
- package/backend/engine/adapters/cline/agent-tool.ts +64 -0
- package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
- package/backend/engine/adapters/cline/credential.ts +166 -0
- package/backend/engine/adapters/cline/error-handler.ts +49 -0
- package/backend/engine/adapters/cline/index.ts +1 -0
- package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
- package/backend/engine/adapters/cline/message-converter.ts +396 -0
- package/backend/engine/adapters/cline/models.ts +73 -0
- package/backend/engine/adapters/cline/presets.ts +128 -0
- package/backend/engine/adapters/cline/stream.ts +413 -0
- package/backend/engine/adapters/codex/credential.ts +1 -1
- package/backend/engine/adapters/codex/message-converter.ts +4 -4
- package/backend/engine/adapters/codex/session-fork.ts +1 -1
- package/backend/engine/adapters/codex/stream.ts +3 -3
- package/backend/engine/adapters/copilot/stream.ts +1 -1
- package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
- package/backend/engine/adapters/cursor/credential.ts +68 -0
- package/backend/engine/adapters/cursor/environment.ts +32 -0
- package/backend/engine/adapters/cursor/error-handler.ts +60 -0
- package/backend/engine/adapters/cursor/index.ts +1 -0
- package/backend/engine/adapters/cursor/message-converter.ts +615 -0
- package/backend/engine/adapters/cursor/models.ts +68 -0
- package/backend/engine/adapters/cursor/session-fork.ts +68 -0
- package/backend/engine/adapters/cursor/stream.ts +341 -0
- package/backend/engine/adapters/pi/agent-tool.ts +62 -0
- package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
- package/backend/engine/adapters/pi/credential.ts +137 -0
- package/backend/engine/adapters/pi/environment.ts +33 -0
- package/backend/engine/adapters/pi/error-handler.ts +46 -0
- package/backend/engine/adapters/pi/index.ts +1 -0
- package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
- package/backend/engine/adapters/pi/message-converter.ts +446 -0
- package/backend/engine/adapters/pi/models.ts +53 -0
- package/backend/engine/adapters/pi/presets.ts +133 -0
- package/backend/engine/adapters/pi/session-fork.ts +46 -0
- package/backend/engine/adapters/pi/stream.ts +427 -0
- package/backend/engine/adapters/qwen/message-converter.ts +5 -5
- package/backend/engine/adapters/qwen/stream.ts +2 -2
- package/backend/engine/docs/adapter-contract.md +7 -2
- package/backend/engine/docs/adding-an-engine.md +70 -12
- package/backend/engine/docs/artifacts.md +124 -0
- package/backend/engine/docs/database.md +4 -4
- package/backend/engine/docs/frontend-and-chat.md +22 -4
- package/backend/engine/docs/lessons-learned.md +219 -32
- package/backend/engine/docs/quick-reference.md +18 -7
- package/backend/engine/docs/websocket-routes.md +2 -2
- package/backend/engine/index.ts +9 -0
- package/backend/mcp/README.md +3 -3
- package/backend/mcp/external/config.ts +11 -0
- package/backend/mcp/index.ts +8 -0
- package/backend/mcp/internal/config.ts +33 -1
- package/backend/permissions/service.ts +5 -2
- package/backend/skills/sync.ts +1 -1
- package/backend/subagents/detect.ts +1 -1
- package/backend/subagents/sync.ts +1 -1
- package/backend/ws/chat/stream.ts +1 -1
- package/backend/ws/engine/cline/accounts.ts +317 -0
- package/backend/ws/engine/cline/index.ts +15 -0
- package/backend/ws/engine/cline/presets.ts +36 -0
- package/backend/ws/engine/cline/status.ts +49 -0
- package/backend/ws/engine/codex/accounts.ts +1 -1
- package/backend/ws/engine/cursor/accounts.ts +162 -0
- package/backend/ws/engine/cursor/index.ts +13 -0
- package/backend/ws/engine/cursor/status.ts +55 -0
- package/backend/ws/engine/index.ts +6 -0
- package/backend/ws/engine/pi/accounts.ts +319 -0
- package/backend/ws/engine/pi/index.ts +15 -0
- package/backend/ws/engine/pi/presets.ts +34 -0
- package/backend/ws/engine/pi/status.ts +50 -0
- package/backend/ws/sessions/crud.ts +2 -2
- package/backend/ws/settings/crud.ts +2 -2
- package/dist/assets/{index-EunAFLxP.js → index-BPvctwJ2.js} +1 -1
- package/dist/assets/{index-ChF_jIXj.js → index-vLKZpWQH.js} +1 -1
- package/dist/assets/{main-CTs4NXwP.js → main-BtBZvCwv.js} +359 -357
- package/dist/assets/{main-moCAkEwm.css → main-D7ATW8pp.css} +1 -1
- package/dist/index.html +2 -2
- package/package.json +7 -1
- package/shared/constants/engine-tools.ts +16 -2
- package/shared/constants/engines.ts +27 -0
- package/shared/types/unified/common.ts +1 -1
- package/shared/types/unified/engine.ts +82 -1
- package/shared/types/unified/index.ts +6 -0
- package/shared/types/unified/message.ts +1 -1
|
@@ -0,0 +1,446 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi SDK → Unified Type Converter.
|
|
3
|
+
*
|
|
4
|
+
* Translates `AgentSessionEvent`s (pi-coding-agent's subscribe stream) into
|
|
5
|
+
* `EngineOutput`. Unlike the other adapters, Pi is push/subscribe rather than an
|
|
6
|
+
* async generator, so the engine bridges subscribe → generator and feeds each
|
|
7
|
+
* event through `convert()` here (see ./stream.ts).
|
|
8
|
+
*
|
|
9
|
+
* Event mapping:
|
|
10
|
+
* - `message_update` (text/thinking deltas) → live `stream_event`s
|
|
11
|
+
* - `message_end` (assistant) → ReasoningMessage + AssistantMessage(s)
|
|
12
|
+
* - `tool_execution_end` → tool_result UserMessage
|
|
13
|
+
* - `agent_end` → success ResultEvent
|
|
14
|
+
*
|
|
15
|
+
* Pi built-in tool names are lowercase (`read`, `bash`, …); we canonicalise them
|
|
16
|
+
* to the unified PascalCase names + normalise input field names so the shared
|
|
17
|
+
* tool UI renders identically to Claude/Codex. MCP tools already arrive as
|
|
18
|
+
* `mcp__<server>__<tool>` from the bridge (see ./mcp-tools.ts).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { AgentSessionEvent } from '@earendil-works/pi-coding-agent';
|
|
22
|
+
import type {
|
|
23
|
+
AssistantMessage as PiAssistantMessage,
|
|
24
|
+
ToolCall as PiToolCall,
|
|
25
|
+
Usage as PiUsage,
|
|
26
|
+
StopReason as PiStopReason,
|
|
27
|
+
} from '@earendil-works/pi-ai';
|
|
28
|
+
import type {
|
|
29
|
+
MessageEngine,
|
|
30
|
+
EngineOutput,
|
|
31
|
+
UserMessage,
|
|
32
|
+
AssistantMessage,
|
|
33
|
+
ReasoningMessage,
|
|
34
|
+
AssistantContentBlock,
|
|
35
|
+
ToolUseBlock,
|
|
36
|
+
TextDeltaEvent,
|
|
37
|
+
StreamLifecycleEvent,
|
|
38
|
+
SuccessResultEvent,
|
|
39
|
+
NotificationEvent,
|
|
40
|
+
TokenUsage,
|
|
41
|
+
StopReason,
|
|
42
|
+
} from '$shared/types/unified';
|
|
43
|
+
import { toCanonicalToolName } from '$shared/types/unified';
|
|
44
|
+
|
|
45
|
+
// ============================================================
|
|
46
|
+
// Tool name + input normalisation
|
|
47
|
+
// ============================================================
|
|
48
|
+
|
|
49
|
+
const PI_TOOL_NAME_MAP: Record<string, string> = {
|
|
50
|
+
read: 'Read',
|
|
51
|
+
bash: 'Bash',
|
|
52
|
+
edit: 'Edit',
|
|
53
|
+
write: 'Write',
|
|
54
|
+
grep: 'Grep',
|
|
55
|
+
glob: 'Glob',
|
|
56
|
+
find: 'Glob',
|
|
57
|
+
ls: 'List',
|
|
58
|
+
list: 'List',
|
|
59
|
+
ask_question: 'AskUserQuestion',
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
function canonicaliseToolName(rawName: string): string {
|
|
63
|
+
if (rawName.startsWith('mcp__')) return rawName;
|
|
64
|
+
return PI_TOOL_NAME_MAP[rawName] ?? rawName;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function snakeToCamel(str: string): string {
|
|
68
|
+
return str.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function normaliseToolInput(canonical: string, raw: Record<string, unknown>): Record<string, unknown> {
|
|
72
|
+
switch (canonical) {
|
|
73
|
+
case 'Read': {
|
|
74
|
+
const path = (raw.filePath ?? raw.file_path ?? raw.path ?? raw.absolute_path) as string | undefined;
|
|
75
|
+
return {
|
|
76
|
+
...(path !== undefined ? { filePath: path } : {}),
|
|
77
|
+
...(raw.offset !== undefined ? { offset: raw.offset } : {}),
|
|
78
|
+
...(raw.limit !== undefined ? { limit: raw.limit } : {}),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
case 'Write': {
|
|
82
|
+
const path = (raw.filePath ?? raw.file_path ?? raw.path) as string | undefined;
|
|
83
|
+
const content = (raw.content ?? raw.text) as string | undefined;
|
|
84
|
+
return {
|
|
85
|
+
...(path !== undefined ? { filePath: path } : {}),
|
|
86
|
+
...(content !== undefined ? { content } : {}),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
case 'Edit': {
|
|
90
|
+
const path = (raw.path ?? raw.filePath ?? raw.file_path) as string | undefined;
|
|
91
|
+
// Pi's edit tool is multi-edit: `{ path, edits: [{ oldText, newText }] }`.
|
|
92
|
+
// The unified UI renders a single old→new diff, so fold the hunks: one
|
|
93
|
+
// edit maps directly; several are joined so the content still shows.
|
|
94
|
+
let oldString: string | undefined;
|
|
95
|
+
let newString: string | undefined;
|
|
96
|
+
const edits = Array.isArray(raw.edits) ? (raw.edits as Array<{ oldText?: string; newText?: string }>) : null;
|
|
97
|
+
if (edits && edits.length > 0) {
|
|
98
|
+
oldString = edits.map(e => e.oldText ?? '').join('\n');
|
|
99
|
+
newString = edits.map(e => e.newText ?? '').join('\n');
|
|
100
|
+
} else {
|
|
101
|
+
oldString = (raw.oldString ?? raw.old_string ?? raw.oldText ?? raw.old_text) as string | undefined;
|
|
102
|
+
newString = (raw.newString ?? raw.new_string ?? raw.newText ?? raw.new_text) as string | undefined;
|
|
103
|
+
}
|
|
104
|
+
const replaceAll = (raw.replaceAll ?? raw.replace_all) as boolean | undefined;
|
|
105
|
+
return {
|
|
106
|
+
...(path !== undefined ? { filePath: path } : {}),
|
|
107
|
+
...(oldString !== undefined ? { oldString } : {}),
|
|
108
|
+
...(newString !== undefined ? { newString } : {}),
|
|
109
|
+
...(replaceAll !== undefined ? { replaceAll: !!replaceAll } : {}),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
case 'Bash': {
|
|
113
|
+
const command = (raw.command ?? raw.cmd ?? raw.script) as string | undefined;
|
|
114
|
+
const description = (raw.description ?? raw.reason) as string | undefined;
|
|
115
|
+
return {
|
|
116
|
+
...(command !== undefined ? { command } : {}),
|
|
117
|
+
...(description !== undefined ? { description } : {}),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
case 'Grep': {
|
|
121
|
+
const pattern = (raw.pattern ?? raw.regex ?? raw.query) as string | undefined;
|
|
122
|
+
const path = (raw.path ?? raw.directory) as string | undefined;
|
|
123
|
+
return {
|
|
124
|
+
...(pattern !== undefined ? { pattern } : {}),
|
|
125
|
+
...(path !== undefined ? { path } : {}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
case 'Glob': {
|
|
129
|
+
const pattern = (raw.pattern ?? raw.glob ?? raw.query) as string | undefined;
|
|
130
|
+
const path = (raw.path ?? raw.directory) as string | undefined;
|
|
131
|
+
return {
|
|
132
|
+
...(pattern !== undefined ? { pattern } : {}),
|
|
133
|
+
...(path !== undefined ? { path } : {}),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
case 'List': {
|
|
137
|
+
const path = (raw.path ?? raw.directory ?? raw.dir) as string | undefined;
|
|
138
|
+
return { ...(path !== undefined ? { path } : {}) };
|
|
139
|
+
}
|
|
140
|
+
case 'AskUserQuestion': {
|
|
141
|
+
return { questions: Array.isArray(raw.questions) ? raw.questions : [] };
|
|
142
|
+
}
|
|
143
|
+
default: {
|
|
144
|
+
const out: Record<string, unknown> = {};
|
|
145
|
+
for (const [k, v] of Object.entries(raw)) out[snakeToCamel(k)] = v;
|
|
146
|
+
return out;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// ============================================================
|
|
152
|
+
// Helper mappers
|
|
153
|
+
// ============================================================
|
|
154
|
+
|
|
155
|
+
function mapStopReason(raw: PiStopReason | null | undefined): StopReason | null {
|
|
156
|
+
switch (raw) {
|
|
157
|
+
case 'stop': return 'end_turn';
|
|
158
|
+
case 'toolUse': return 'tool_use';
|
|
159
|
+
case 'length': return 'max_tokens';
|
|
160
|
+
case 'aborted': return 'interrupted';
|
|
161
|
+
case 'error': return 'end_turn';
|
|
162
|
+
default: return null;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function mapUsage(raw: PiUsage | null | undefined): TokenUsage | null {
|
|
167
|
+
if (!raw) return null;
|
|
168
|
+
return {
|
|
169
|
+
inputTokens: raw.input || 0,
|
|
170
|
+
outputTokens: raw.output || 0,
|
|
171
|
+
cacheCreationInputTokens: raw.cacheWrite || 0,
|
|
172
|
+
cacheReadInputTokens: raw.cacheRead || 0,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// ============================================================
|
|
177
|
+
// Converter
|
|
178
|
+
// ============================================================
|
|
179
|
+
|
|
180
|
+
export interface PiConverterOptions {
|
|
181
|
+
engine: MessageEngine;
|
|
182
|
+
sessionId: string;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export interface PiMessageConverter {
|
|
186
|
+
convert(event: AgentSessionEvent): EngineOutput[];
|
|
187
|
+
/** Accumulated usage for the final result event. */
|
|
188
|
+
readonly totalUsage: TokenUsage;
|
|
189
|
+
readonly totalCostUsd: number;
|
|
190
|
+
readonly turns: number;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function createPiMessageConverter(options: PiConverterOptions): PiMessageConverter {
|
|
194
|
+
const { engine, sessionId } = options;
|
|
195
|
+
const totalUsage: TokenUsage = { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0 };
|
|
196
|
+
let totalCostUsd = 0;
|
|
197
|
+
let turns = 0;
|
|
198
|
+
// Tracks whether the run produced ANY visible output (reasoning, assistant
|
|
199
|
+
// text/tool_use, or a tool result). If a whole run ends with nothing — e.g.
|
|
200
|
+
// the model returns an empty end_turn — we surface a notification on
|
|
201
|
+
// `agent_end` instead of leaving the user staring at silence.
|
|
202
|
+
let emittedContent = false;
|
|
203
|
+
|
|
204
|
+
function mapAssistantContent(msg: PiAssistantMessage): { reasoning: string; blocks: AssistantContentBlock[] } {
|
|
205
|
+
let reasoning = '';
|
|
206
|
+
const blocks: AssistantContentBlock[] = [];
|
|
207
|
+
for (const block of msg.content) {
|
|
208
|
+
if (block.type === 'thinking') {
|
|
209
|
+
reasoning += (reasoning ? '\n' : '') + block.thinking;
|
|
210
|
+
} else if (block.type === 'text') {
|
|
211
|
+
// Skip empty/whitespace text blocks. Gemini (and others) routinely
|
|
212
|
+
// emit a trailing empty text part after a tool call; persisting it
|
|
213
|
+
// would render as a blank assistant bubble.
|
|
214
|
+
if (block.text.trim()) blocks.push({ type: 'text', text: block.text });
|
|
215
|
+
} else if (block.type === 'toolCall') {
|
|
216
|
+
const call = block as PiToolCall;
|
|
217
|
+
const canonical = canonicaliseToolName(call.name);
|
|
218
|
+
const finalName = toCanonicalToolName(canonical);
|
|
219
|
+
const rawInput = (call.arguments && typeof call.arguments === 'object' ? call.arguments : {}) as Record<string, unknown>;
|
|
220
|
+
blocks.push({
|
|
221
|
+
type: 'tool_use',
|
|
222
|
+
id: call.id,
|
|
223
|
+
name: finalName,
|
|
224
|
+
input: normaliseToolInput(canonical, rawInput),
|
|
225
|
+
result: null,
|
|
226
|
+
subActivities: [],
|
|
227
|
+
skillPrompt: null,
|
|
228
|
+
interrupted: false,
|
|
229
|
+
} as ToolUseBlock);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return { reasoning, blocks };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function convertAssistantMessage(msg: PiAssistantMessage): EngineOutput[] {
|
|
236
|
+
const outputs: EngineOutput[] = [];
|
|
237
|
+
const { reasoning, blocks } = mapAssistantContent(msg);
|
|
238
|
+
|
|
239
|
+
if (reasoning.trim()) {
|
|
240
|
+
emittedContent = true;
|
|
241
|
+
outputs.push({
|
|
242
|
+
type: 'reasoning',
|
|
243
|
+
createdAt: new Date().toISOString(),
|
|
244
|
+
messageId: crypto.randomUUID(),
|
|
245
|
+
sessionId,
|
|
246
|
+
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
247
|
+
engine,
|
|
248
|
+
text: reasoning,
|
|
249
|
+
} as ReasoningMessage);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const usage = mapUsage(msg.usage);
|
|
253
|
+
if (msg.usage) {
|
|
254
|
+
totalUsage.inputTokens += msg.usage.input || 0;
|
|
255
|
+
totalUsage.outputTokens += msg.usage.output || 0;
|
|
256
|
+
totalUsage.cacheCreationInputTokens += msg.usage.cacheWrite || 0;
|
|
257
|
+
totalUsage.cacheReadInputTokens += msg.usage.cacheRead || 0;
|
|
258
|
+
totalCostUsd += msg.usage.cost?.total || 0;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// Nothing substantive in this message. If the model genuinely errored
|
|
262
|
+
// (stopReason 'error' with a message), surface a CLEANED message as visible
|
|
263
|
+
// text; user-aborted turns and empty responses emit no bubble — an empty
|
|
264
|
+
// text placeholder just looks like a stuck turn.
|
|
265
|
+
if (blocks.length === 0) {
|
|
266
|
+
const errorMessage = (msg as { errorMessage?: string }).errorMessage;
|
|
267
|
+
if (msg.stopReason === 'error' && errorMessage && errorMessage.trim()) {
|
|
268
|
+
emittedContent = true;
|
|
269
|
+
outputs.push({
|
|
270
|
+
type: 'assistant',
|
|
271
|
+
createdAt: new Date().toISOString(),
|
|
272
|
+
messageId: crypto.randomUUID(),
|
|
273
|
+
sessionId,
|
|
274
|
+
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
275
|
+
engine,
|
|
276
|
+
content: [{ type: 'text', text: `⚠️ ${cleanProviderError(errorMessage)}` }],
|
|
277
|
+
stopReason: mapStopReason(msg.stopReason),
|
|
278
|
+
usage,
|
|
279
|
+
} as AssistantMessage);
|
|
280
|
+
}
|
|
281
|
+
return outputs;
|
|
282
|
+
}
|
|
283
|
+
emittedContent = true;
|
|
284
|
+
|
|
285
|
+
const emitBlocks = blocks;
|
|
286
|
+
const baseId = crypto.randomUUID();
|
|
287
|
+
if (emitBlocks.length === 1) {
|
|
288
|
+
outputs.push({
|
|
289
|
+
type: 'assistant',
|
|
290
|
+
createdAt: new Date().toISOString(),
|
|
291
|
+
messageId: baseId,
|
|
292
|
+
sessionId,
|
|
293
|
+
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
294
|
+
engine,
|
|
295
|
+
content: emitBlocks,
|
|
296
|
+
stopReason: emitBlocks[0].type === 'tool_use' ? 'tool_use' : mapStopReason(msg.stopReason),
|
|
297
|
+
usage,
|
|
298
|
+
} as AssistantMessage);
|
|
299
|
+
} else {
|
|
300
|
+
// One tool_use per AssistantMessage (README §10.3).
|
|
301
|
+
emitBlocks.forEach((block, idx) => {
|
|
302
|
+
outputs.push({
|
|
303
|
+
type: 'assistant',
|
|
304
|
+
createdAt: new Date().toISOString(),
|
|
305
|
+
messageId: `${baseId}:${idx}`,
|
|
306
|
+
sessionId,
|
|
307
|
+
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
308
|
+
engine,
|
|
309
|
+
content: [block],
|
|
310
|
+
stopReason: block.type === 'tool_use' ? 'tool_use' : mapStopReason(msg.stopReason),
|
|
311
|
+
usage: idx === emitBlocks.length - 1 ? usage : null,
|
|
312
|
+
} as AssistantMessage);
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
return outputs;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function convertToolResult(toolCallId: string, result: unknown, isError: boolean): UserMessage {
|
|
319
|
+
emittedContent = true;
|
|
320
|
+
const text = extractResultText(result);
|
|
321
|
+
return {
|
|
322
|
+
type: 'user',
|
|
323
|
+
createdAt: new Date().toISOString(),
|
|
324
|
+
messageId: crypto.randomUUID(),
|
|
325
|
+
sessionId,
|
|
326
|
+
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
327
|
+
engine,
|
|
328
|
+
sender: { id: '', name: '' },
|
|
329
|
+
content: [{ type: 'tool_result', toolUseId: toolCallId, content: text, isError }],
|
|
330
|
+
synthetic: true,
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function convert(event: AgentSessionEvent): EngineOutput[] {
|
|
335
|
+
switch (event.type) {
|
|
336
|
+
case 'message_update': {
|
|
337
|
+
const ev = event.assistantMessageEvent;
|
|
338
|
+
switch (ev.type) {
|
|
339
|
+
case 'text_start':
|
|
340
|
+
return [{ type: 'stream_event', event: 'start', sessionId, reasoning: false } as StreamLifecycleEvent];
|
|
341
|
+
case 'text_delta':
|
|
342
|
+
return [{ type: 'stream_event', event: 'delta', sessionId, text: ev.delta || '', reasoning: false } as TextDeltaEvent];
|
|
343
|
+
case 'text_end':
|
|
344
|
+
return [{ type: 'stream_event', event: 'stop', sessionId, reasoning: false } as StreamLifecycleEvent];
|
|
345
|
+
case 'thinking_start':
|
|
346
|
+
return [{ type: 'stream_event', event: 'start', sessionId, reasoning: true } as StreamLifecycleEvent];
|
|
347
|
+
case 'thinking_delta':
|
|
348
|
+
return [{ type: 'stream_event', event: 'delta', sessionId, text: ev.delta || '', reasoning: true } as TextDeltaEvent];
|
|
349
|
+
case 'thinking_end':
|
|
350
|
+
return [{ type: 'stream_event', event: 'stop', sessionId, reasoning: true } as StreamLifecycleEvent];
|
|
351
|
+
default:
|
|
352
|
+
return [];
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
case 'message_end': {
|
|
356
|
+
const msg = event.message;
|
|
357
|
+
if (msg && (msg as { role?: string }).role === 'assistant') {
|
|
358
|
+
turns += 1;
|
|
359
|
+
return convertAssistantMessage(msg as PiAssistantMessage);
|
|
360
|
+
}
|
|
361
|
+
return [];
|
|
362
|
+
}
|
|
363
|
+
case 'tool_execution_end':
|
|
364
|
+
return [convertToolResult(event.toolCallId, event.result, event.isError)];
|
|
365
|
+
case 'agent_end': {
|
|
366
|
+
const outputs: EngineOutput[] = [];
|
|
367
|
+
// Run produced no visible output at all → tell the user rather than
|
|
368
|
+
// finishing silently (looks like a stuck / dropped turn otherwise).
|
|
369
|
+
if (!emittedContent) {
|
|
370
|
+
outputs.push({
|
|
371
|
+
type: 'notification',
|
|
372
|
+
sessionId,
|
|
373
|
+
level: 'warning',
|
|
374
|
+
title: 'Empty response',
|
|
375
|
+
message: 'Pi returned an empty response. Try again or rephrase your prompt.',
|
|
376
|
+
} as NotificationEvent);
|
|
377
|
+
}
|
|
378
|
+
outputs.push({
|
|
379
|
+
type: 'result',
|
|
380
|
+
subtype: 'success',
|
|
381
|
+
sessionId,
|
|
382
|
+
numTurns: turns,
|
|
383
|
+
totalCostUsd,
|
|
384
|
+
usage: { ...totalUsage },
|
|
385
|
+
stopReason: null,
|
|
386
|
+
} as SuccessResultEvent);
|
|
387
|
+
return outputs;
|
|
388
|
+
}
|
|
389
|
+
default:
|
|
390
|
+
return [];
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
return {
|
|
395
|
+
convert,
|
|
396
|
+
get totalUsage() { return totalUsage; },
|
|
397
|
+
get totalCostUsd() { return totalCostUsd; },
|
|
398
|
+
get turns() { return turns; },
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Turn a provider error (often a doubly-encoded JSON envelope with literal
|
|
404
|
+
* `\n`s — e.g. Google's 429 quota blob) into a short human-readable line.
|
|
405
|
+
*/
|
|
406
|
+
function cleanProviderError(raw: string): string {
|
|
407
|
+
let msg = raw.trim();
|
|
408
|
+
// Peel nested `{ error: { message } }` / `{ message }` envelopes.
|
|
409
|
+
for (let i = 0; i < 3; i++) {
|
|
410
|
+
try {
|
|
411
|
+
const parsed = JSON.parse(msg) as { error?: { message?: string; code?: number; status?: string }; message?: string };
|
|
412
|
+
const inner = parsed?.error?.message ?? parsed?.message;
|
|
413
|
+
if (typeof inner === 'string' && inner.trim()) { msg = inner.trim(); continue; }
|
|
414
|
+
} catch {
|
|
415
|
+
break;
|
|
416
|
+
}
|
|
417
|
+
break;
|
|
418
|
+
}
|
|
419
|
+
// Collapse escaped/real whitespace and trim to one tidy line.
|
|
420
|
+
msg = msg.replace(/\\n/g, ' ').replace(/\\"/g, '"').replace(/\s+/g, ' ').trim();
|
|
421
|
+
if (/quota|rate limit|resource_exhausted|429/i.test(msg)) {
|
|
422
|
+
msg = `Rate limit / quota exceeded — ${msg}`;
|
|
423
|
+
}
|
|
424
|
+
return msg.length > 400 ? `${msg.slice(0, 400)}…` : msg;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** Extract plain text from a tool result (AgentToolResult or MCP-style content). */
|
|
428
|
+
function extractResultText(result: unknown): string {
|
|
429
|
+
if (result == null) return '';
|
|
430
|
+
if (typeof result === 'string') return result;
|
|
431
|
+
const r = result as { content?: unknown };
|
|
432
|
+
if (Array.isArray(r.content)) {
|
|
433
|
+
return r.content
|
|
434
|
+
.map((c: unknown) => {
|
|
435
|
+
const item = c as { type?: string; text?: string };
|
|
436
|
+
return item?.type === 'text' && typeof item.text === 'string' ? item.text : '';
|
|
437
|
+
})
|
|
438
|
+
.filter(Boolean)
|
|
439
|
+
.join('\n');
|
|
440
|
+
}
|
|
441
|
+
try {
|
|
442
|
+
return JSON.stringify(result);
|
|
443
|
+
} catch {
|
|
444
|
+
return String(result);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi dynamic model discovery.
|
|
3
|
+
*
|
|
4
|
+
* Pi resolves models from its built-in catalog (plus any custom providers in the
|
|
5
|
+
* isolated `models.json`). We build a `ModelRuntime` seeded with every stored Pi
|
|
6
|
+
* account's credential and ask it for the models that have valid auth
|
|
7
|
+
* (`getAvailable()`), then translate each into an `EngineModel`.
|
|
8
|
+
*
|
|
9
|
+
* `engine.provider` carries the pi-ai provider id (e.g. 'anthropic', 'openai')
|
|
10
|
+
* so the chat's send path can resolve the matching account by provider. Returns
|
|
11
|
+
* `[]` on any failure (mirrors the OpenCode/Qwen dynamic-catalog contract — the
|
|
12
|
+
* picker renders empty rather than a stale list).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { Api, Model } from '@earendil-works/pi-ai';
|
|
16
|
+
import type { EngineModel } from '$shared/types/unified';
|
|
17
|
+
import { debug } from '$shared/utils/logger';
|
|
18
|
+
import { DbCredentialStore, getPiAccounts } from './credential';
|
|
19
|
+
import { createPiRuntime } from './presets';
|
|
20
|
+
|
|
21
|
+
export async function fetchPiModels(): Promise<EngineModel[]> {
|
|
22
|
+
try {
|
|
23
|
+
const accounts = getPiAccounts();
|
|
24
|
+
const store = new DbCredentialStore(accounts);
|
|
25
|
+
const runtime = await createPiRuntime(store);
|
|
26
|
+
const available = await runtime.getAvailable();
|
|
27
|
+
const mapped = available.map(mapPiModel);
|
|
28
|
+
debug.log('engine', `Pi getAvailableModels: ${mapped.length} models across ${accounts.length} account(s)`);
|
|
29
|
+
return mapped;
|
|
30
|
+
} catch (error) {
|
|
31
|
+
debug.warn('engine', `Pi model discovery failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
32
|
+
return [];
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function mapPiModel(model: Model<Api>): EngineModel {
|
|
37
|
+
const image = model.input.includes('image');
|
|
38
|
+
return {
|
|
39
|
+
engine: {
|
|
40
|
+
type: 'pi',
|
|
41
|
+
provider: model.provider,
|
|
42
|
+
model: { id: model.id, name: model.name || model.id },
|
|
43
|
+
account: { id: 0, name: '' },
|
|
44
|
+
},
|
|
45
|
+
limit: { input: model.contextWindow ?? 0, output: model.maxTokens ?? 0 },
|
|
46
|
+
modalities: {
|
|
47
|
+
input: { text: true, image, audio: false, video: false, pdf: false },
|
|
48
|
+
output: { text: true, image: false, audio: false, video: false, pdf: false },
|
|
49
|
+
},
|
|
50
|
+
capabilities: { reasoning: !!model.reasoning, tools: true, structuredOutput: true },
|
|
51
|
+
cost: { input: model.cost?.input ?? 0, output: model.cost?.output ?? 0 },
|
|
52
|
+
};
|
|
53
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi provider catalog + `ModelRuntime` factory.
|
|
3
|
+
*
|
|
4
|
+
* Pi ships a large built-in provider catalog (Anthropic, OpenAI, Google,
|
|
5
|
+
* OpenRouter, xAI, …), each supporting API-key auth, OAuth (subscription) auth,
|
|
6
|
+
* or both. Rather than hardcode 30 providers, we enumerate them from a
|
|
7
|
+
* throwaway `ModelRuntime` (`getProviders()` exposes `provider.auth.apiKey` /
|
|
8
|
+
* `provider.auth.oauth`) and expose the result to the login picker via the
|
|
9
|
+
* `engine:pi-presets-list` WS endpoint.
|
|
10
|
+
*
|
|
11
|
+
* The wire types (`PiProviderPreset`, `PiAuthMode`) live in
|
|
12
|
+
* `shared/types/unified/engine.ts` so the frontend stays typed without importing
|
|
13
|
+
* `$backend`.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { ModelRuntime } from '@earendil-works/pi-coding-agent';
|
|
17
|
+
import type { CredentialStore } from '@earendil-works/pi-ai';
|
|
18
|
+
import type { PiAuthMode, PiCredentialField, PiProviderPreset } from '$shared/types/unified';
|
|
19
|
+
import { getPiModelsPath, getPiModelsStorePath } from './environment';
|
|
20
|
+
import { debug } from '$shared/utils/logger';
|
|
21
|
+
|
|
22
|
+
export type { PiAuthMode, PiCredentialField, PiProviderPreset };
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Per-provider API-key credential fields, shown all at once in the account form.
|
|
26
|
+
* Most providers need just a key; a few need extra provider-scoped config
|
|
27
|
+
* (Cloudflare account/gateway ids, Azure base URL) which pi-ai reads from the
|
|
28
|
+
* credential's `env` map (see providers.md). `role: 'key'` → `credential.key`,
|
|
29
|
+
* `role: 'env'` → `credential.env[key]`.
|
|
30
|
+
*/
|
|
31
|
+
const DEFAULT_FIELDS: PiCredentialField[] = [
|
|
32
|
+
{ key: 'apiKey', label: 'API key', secret: true, role: 'key', placeholder: 'sk-…' },
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
const PROVIDER_FIELDS: Record<string, PiCredentialField[]> = {
|
|
36
|
+
'cloudflare-workers-ai': [
|
|
37
|
+
{ key: 'apiKey', label: 'API token', secret: true, role: 'key' },
|
|
38
|
+
{ key: 'CLOUDFLARE_ACCOUNT_ID', label: 'Account ID', secret: false, role: 'env' },
|
|
39
|
+
],
|
|
40
|
+
'cloudflare-ai-gateway': [
|
|
41
|
+
{ key: 'apiKey', label: 'API token', secret: true, role: 'key' },
|
|
42
|
+
{ key: 'CLOUDFLARE_ACCOUNT_ID', label: 'Account ID', secret: false, role: 'env' },
|
|
43
|
+
{ key: 'CLOUDFLARE_GATEWAY_ID', label: 'Gateway ID', secret: false, role: 'env' },
|
|
44
|
+
],
|
|
45
|
+
'azure-openai-responses': [
|
|
46
|
+
{ key: 'apiKey', label: 'API key', secret: true, role: 'key' },
|
|
47
|
+
{ key: 'AZURE_OPENAI_BASE_URL', label: 'Base URL', secret: false, role: 'env', placeholder: 'https://your-resource.openai.azure.com' },
|
|
48
|
+
],
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
/** Credential field schema for an api-key provider (single key by default). */
|
|
52
|
+
export function getPiProviderFields(providerId: string): PiCredentialField[] {
|
|
53
|
+
return PROVIDER_FIELDS[providerId] ?? DEFAULT_FIELDS;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Build a `ModelRuntime` pointed at Clopen's isolated Pi dirs. When `credentials`
|
|
58
|
+
* is provided it becomes the auth source (DB-backed store); otherwise the runtime
|
|
59
|
+
* is credential-less (used only to enumerate provider metadata for the picker).
|
|
60
|
+
*
|
|
61
|
+
* We never pass `authPath`, so Pi never touches the user's real
|
|
62
|
+
* `~/.pi/agent/auth.json` — the DB store is the sole credential source.
|
|
63
|
+
*/
|
|
64
|
+
export async function createPiRuntime(credentials?: CredentialStore): Promise<ModelRuntime> {
|
|
65
|
+
return ModelRuntime.create({
|
|
66
|
+
...(credentials ? { credentials } : {}),
|
|
67
|
+
modelsPath: getPiModelsPath(),
|
|
68
|
+
modelsStorePath: getPiModelsStorePath(),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Where to obtain an API key, keyed by pi-ai provider id (best-effort hints). */
|
|
73
|
+
const API_KEY_URLS: Record<string, string> = {
|
|
74
|
+
anthropic: 'https://console.anthropic.com/settings/keys',
|
|
75
|
+
openai: 'https://platform.openai.com/api-keys',
|
|
76
|
+
google: 'https://aistudio.google.com/apikey',
|
|
77
|
+
openrouter: 'https://openrouter.ai/keys',
|
|
78
|
+
xai: 'https://console.x.ai',
|
|
79
|
+
groq: 'https://console.groq.com/keys',
|
|
80
|
+
deepseek: 'https://platform.deepseek.com/api_keys',
|
|
81
|
+
mistral: 'https://console.mistral.ai/api-keys',
|
|
82
|
+
together: 'https://api.together.ai/settings/api-keys',
|
|
83
|
+
fireworks: 'https://fireworks.ai/account/api-keys',
|
|
84
|
+
cerebras: 'https://cloud.cerebras.ai',
|
|
85
|
+
nvidia: 'https://build.nvidia.com',
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
/** Human labels for the OAuth (subscription) option, keyed by provider id. */
|
|
89
|
+
const OAUTH_LABELS: Record<string, string> = {
|
|
90
|
+
anthropic: 'Sign in with Claude Pro/Max',
|
|
91
|
+
'openai-codex': 'Sign in with ChatGPT (Plus/Pro)',
|
|
92
|
+
'github-copilot': 'Sign in with GitHub Copilot',
|
|
93
|
+
xai: 'Sign in with SuperGrok or X Premium',
|
|
94
|
+
radius: 'Sign in with Radius',
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
let presetsCache: PiProviderPreset[] | null = null;
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Enumerate Pi's providers and their supported auth modes. Cached — the catalog
|
|
101
|
+
* is static per process. Returns `[]` if the runtime can't be built (mirrors the
|
|
102
|
+
* dynamic-catalog `[]`-on-failure contract).
|
|
103
|
+
*/
|
|
104
|
+
export async function getPiProviderPresets(): Promise<PiProviderPreset[]> {
|
|
105
|
+
if (presetsCache) return presetsCache;
|
|
106
|
+
try {
|
|
107
|
+
const runtime = await createPiRuntime();
|
|
108
|
+
const presets: PiProviderPreset[] = [];
|
|
109
|
+
for (const provider of runtime.getProviders()) {
|
|
110
|
+
const authModes: PiAuthMode[] = [];
|
|
111
|
+
// An ambient-only api-key provider omits `login`; skip it as an
|
|
112
|
+
// interactive target (nothing for the user to paste) but still expose
|
|
113
|
+
// oauth when present.
|
|
114
|
+
if (provider.auth.apiKey?.login) authModes.push('api_key');
|
|
115
|
+
if (provider.auth.oauth) authModes.push('oauth');
|
|
116
|
+
if (authModes.length === 0) continue;
|
|
117
|
+
presets.push({
|
|
118
|
+
id: provider.id,
|
|
119
|
+
name: provider.name,
|
|
120
|
+
authModes,
|
|
121
|
+
...(authModes.includes('api_key') ? { fields: getPiProviderFields(provider.id) } : {}),
|
|
122
|
+
...(OAUTH_LABELS[provider.id] ? { oauthLabel: OAUTH_LABELS[provider.id] } : {}),
|
|
123
|
+
...(API_KEY_URLS[provider.id] ? { apiKeyUrl: API_KEY_URLS[provider.id] } : {}),
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
presets.sort((a, b) => a.name.localeCompare(b.name));
|
|
127
|
+
presetsCache = presets;
|
|
128
|
+
return presets;
|
|
129
|
+
} catch (error) {
|
|
130
|
+
debug.warn('engine', `Pi presets: failed to enumerate providers: ${error instanceof Error ? error.message : String(error)}`);
|
|
131
|
+
return [];
|
|
132
|
+
}
|
|
133
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pi session persistence + fork-on-resume.
|
|
3
|
+
*
|
|
4
|
+
* Pi persists each session as a JSONL tree. We keep those files in Clopen's
|
|
5
|
+
* ISOLATED sessions dir (never `~/.pi/agent/sessions`) by always passing an
|
|
6
|
+
* explicit `sessionDir` to `SessionManager`, encoded per project so concurrent
|
|
7
|
+
* projects don't collide.
|
|
8
|
+
*
|
|
9
|
+
* Every resume FORKS (README §10.10): Clopen's multi-branch checkpoints require
|
|
10
|
+
* each resumed turn to produce a brand-new session id so the source branch's
|
|
11
|
+
* history is never mutated. Pi exposes a native `SessionManager.forkFrom()`, so
|
|
12
|
+
* this is a first-class copy — no manual JSONL patching.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { SessionManager } from '@earendil-works/pi-coding-agent';
|
|
17
|
+
import { getPiSessionsDir } from './environment';
|
|
18
|
+
import { debug } from '$shared/utils/logger';
|
|
19
|
+
|
|
20
|
+
/** Per-project isolated session dir under Clopen's Pi config dir. */
|
|
21
|
+
export function getPiSessionDir(projectPath: string): string {
|
|
22
|
+
return join(getPiSessionsDir(), projectPath.replace(/[^a-zA-Z0-9]/g, '-'));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Build the `SessionManager` for a stream. When `resume` names an existing
|
|
27
|
+
* session, fork from it (new id, source untouched); otherwise start fresh.
|
|
28
|
+
*/
|
|
29
|
+
export async function resolvePiSessionManager(projectPath: string, resume?: string): Promise<SessionManager> {
|
|
30
|
+
const sessionDir = getPiSessionDir(projectPath);
|
|
31
|
+
if (resume) {
|
|
32
|
+
try {
|
|
33
|
+
const infos = await SessionManager.list(projectPath, sessionDir);
|
|
34
|
+
const match = infos.find(info => info.id === resume);
|
|
35
|
+
if (match) {
|
|
36
|
+
const forked = SessionManager.forkFrom(match.path, projectPath, sessionDir);
|
|
37
|
+
debug.log('engine', `Pi resumed session ${resume} → fork ${forked.getSessionId()}`);
|
|
38
|
+
return forked;
|
|
39
|
+
}
|
|
40
|
+
debug.warn('engine', `Pi resume: session ${resume} not found on disk, starting fresh`);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
debug.warn('engine', `Pi resume failed (${error instanceof Error ? error.message : String(error)}), starting fresh`);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return SessionManager.create(projectPath, sessionDir);
|
|
46
|
+
}
|