@myrialabs/clopen 0.3.8 → 0.3.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -19
- package/backend/auth/auth-service.ts +56 -1
- package/backend/auth/permissions.ts +66 -2
- package/backend/auth/session-cleanup.ts +58 -0
- package/backend/chat/stream-manager.ts +143 -13
- package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
- package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
- package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
- package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
- package/backend/database/migrations/index.ts +29 -1
- package/backend/database/queries/db-client-connection-queries.ts +160 -54
- package/backend/database/queries/engine-queries.ts +12 -0
- package/backend/database/queries/project-queries.ts +10 -5
- package/backend/db-client/connection-manager.ts +9 -3
- package/backend/engine/README.md +1702 -0
- package/backend/engine/adapters/claude/models.ts +141 -0
- package/backend/engine/adapters/claude/stream.ts +1 -1
- package/backend/engine/adapters/codex/credential.ts +179 -0
- package/backend/engine/adapters/codex/error-handler.ts +65 -0
- package/backend/engine/adapters/codex/index.ts +1 -0
- package/backend/engine/adapters/codex/message-converter.ts +646 -0
- package/backend/engine/adapters/codex/models.ts +105 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
- package/backend/engine/adapters/codex/session-fork.ts +149 -0
- package/backend/engine/adapters/codex/stream.ts +310 -0
- package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
- package/backend/engine/adapters/copilot/error-handler.ts +94 -0
- package/backend/engine/adapters/copilot/index.ts +1 -0
- package/backend/engine/adapters/copilot/message-converter.ts +973 -0
- package/backend/engine/adapters/copilot/models.ts +92 -0
- package/backend/engine/adapters/copilot/session-fork.ts +111 -0
- package/backend/engine/adapters/copilot/stream.ts +570 -0
- package/backend/engine/adapters/opencode/config.ts +56 -104
- package/backend/engine/adapters/opencode/error-handler.ts +71 -0
- package/backend/engine/adapters/opencode/models.ts +79 -0
- package/backend/engine/adapters/opencode/presets.ts +91 -0
- package/backend/engine/adapters/opencode/stream.ts +8 -114
- package/backend/engine/adapters/qwen/credential.ts +78 -0
- package/backend/engine/adapters/qwen/environment.ts +84 -0
- package/backend/engine/adapters/qwen/error-handler.ts +71 -0
- package/backend/engine/adapters/qwen/index.ts +1 -0
- package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
- package/backend/engine/adapters/qwen/models.ts +81 -0
- package/backend/engine/adapters/qwen/presets.ts +51 -0
- package/backend/engine/adapters/qwen/session-fork.ts +97 -0
- package/backend/engine/adapters/qwen/stream.ts +379 -0
- package/backend/engine/index.ts +35 -0
- package/backend/engine/install-recipes.ts +80 -1
- package/backend/engine/install-runner.ts +4 -0
- package/backend/files/path-browsing.ts +20 -0
- package/backend/git/git-service.ts +81 -11
- package/backend/git/git-spawn-validation.test.ts +75 -0
- package/backend/git/git-spawn-validation.ts +77 -0
- package/backend/index.ts +5 -0
- package/backend/mcp/README.md +84 -14
- package/backend/mcp/config.ts +218 -17
- package/backend/mcp/index.ts +2 -0
- package/backend/mcp/project-context.ts +55 -0
- package/backend/mcp/servers/browser-automation/actions.ts +6 -1
- package/backend/mcp/servers/helper.ts +13 -0
- package/backend/middleware/error-handler.ts +16 -2
- package/backend/preview/browser/browser-preview-service.ts +4 -4
- package/backend/preview/browser/browser-tab-manager.ts +23 -3
- package/backend/snapshot/gitignore.ts +4 -9
- package/backend/tunnel/cloudflared/binary.ts +2 -2
- package/backend/tunnel/global-tunnel-manager.ts +9 -3
- package/backend/utils/ws.ts +5 -1
- package/backend/ws/README.md +128 -3
- package/backend/ws/access.ts +56 -0
- package/backend/ws/auth/index.ts +14 -0
- package/backend/ws/auth/login.ts +3 -0
- package/backend/ws/auth/users.ts +61 -1
- package/backend/ws/chat/stream.ts +139 -22
- package/backend/ws/db-client/access.ts +19 -0
- package/backend/ws/db-client/connections.ts +31 -17
- package/backend/ws/db-client/io.ts +7 -9
- package/backend/ws/db-client/query.ts +86 -32
- package/backend/ws/db-client/schema.ts +9 -4
- package/backend/ws/db-client/structure.ts +22 -10
- package/backend/ws/engine/access.ts +39 -0
- package/backend/ws/engine/claude/accounts.ts +15 -10
- package/backend/ws/engine/codex/accounts.ts +516 -0
- package/backend/ws/engine/codex/index.ts +14 -0
- package/backend/ws/engine/codex/status.ts +87 -0
- package/backend/ws/engine/copilot/accounts.ts +122 -0
- package/backend/ws/engine/copilot/index.ts +13 -0
- package/backend/ws/engine/copilot/status.ts +54 -0
- package/backend/ws/engine/index.ts +7 -1
- package/backend/ws/engine/opencode/providers.ts +1 -1
- package/backend/ws/engine/qwen/accounts.ts +137 -0
- package/backend/ws/engine/qwen/index.ts +15 -0
- package/backend/ws/engine/qwen/presets.ts +40 -0
- package/backend/ws/engine/qwen/status.ts +54 -0
- package/backend/ws/files/path-access.ts +101 -0
- package/backend/ws/files/read.ts +26 -11
- package/backend/ws/files/search.ts +10 -6
- package/backend/ws/files/state.ts +3 -0
- package/backend/ws/files/watch.ts +7 -1
- package/backend/ws/files/write.ts +109 -15
- package/backend/ws/git/branch.ts +13 -19
- package/backend/ws/git/commit-message.ts +3 -4
- package/backend/ws/git/commit.ts +5 -7
- package/backend/ws/git/conflict.ts +7 -10
- package/backend/ws/git/diff.ts +7 -10
- package/backend/ws/git/log.ts +3 -4
- package/backend/ws/git/remote.ts +30 -43
- package/backend/ws/git/staging.ts +13 -19
- package/backend/ws/git/status.ts +7 -11
- package/backend/ws/messages/crud.ts +7 -13
- package/backend/ws/preview/access.ts +45 -0
- package/backend/ws/preview/browser/cleanup.ts +3 -11
- package/backend/ws/preview/browser/console.ts +7 -42
- package/backend/ws/preview/browser/interact.ts +2 -6
- package/backend/ws/preview/browser/native-ui.ts +5 -18
- package/backend/ws/preview/browser/stats.ts +2 -12
- package/backend/ws/preview/browser/tab-info.ts +4 -20
- package/backend/ws/preview/browser/tab.ts +4 -27
- package/backend/ws/preview/browser/webcodecs.ts +6 -47
- package/backend/ws/projects/crud.ts +15 -16
- package/backend/ws/projects/status.ts +5 -1
- package/backend/ws/sessions/crud.ts +31 -36
- package/backend/ws/settings/crud.ts +13 -13
- package/backend/ws/snapshot/restore.ts +5 -2
- package/backend/ws/snapshot/timeline.ts +3 -1
- package/backend/ws/system-tools/access.ts +28 -0
- package/backend/ws/system-tools/install.ts +13 -4
- package/backend/ws/system-tools/status.ts +5 -2
- package/backend/ws/terminal/access.ts +56 -0
- package/backend/ws/terminal/persistence.ts +13 -7
- package/backend/ws/terminal/session.ts +35 -14
- package/backend/ws/terminal/stream.ts +4 -1
- package/dist/assets/{index-DqAGCTFT.js → index-C1afGwHY.js} +2 -2
- package/dist/assets/main-CZb3Y_Z_.js +315 -0
- package/dist/assets/main-Cn8cX2DY.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +5 -1
- package/shared/constants/engines.ts +45 -140
- package/shared/types/database/schema.ts +1 -0
- package/shared/types/unified/common.ts +1 -1
- package/shared/types/unified/engine.ts +29 -1
- package/shared/types/unified/index.ts +2 -0
- package/shared/types/unified/message.ts +1 -1
- package/shared/types/unified/tool.ts +17 -2
- package/shared/utils/ws-server.ts +14 -0
- package/dist/assets/main-DsED0rLr.js +0 -304
- package/dist/assets/main-eWY9R8g9.css +0 -1
|
@@ -0,0 +1,1055 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Qwen Code SDK → Unified Type Converters
|
|
3
|
+
*
|
|
4
|
+
* Translates `@qwen-code/sdk` messages (whose shape closely mirrors the
|
|
5
|
+
* Anthropic content-block model) into `EngineOutput` (unified types).
|
|
6
|
+
*
|
|
7
|
+
* Mirrors `claude/message-converter.ts` — the message envelope is identical
|
|
8
|
+
* (SDKAssistantMessage / SDKUserMessage / SDKPartialAssistantMessage with
|
|
9
|
+
* text / thinking / tool_use / tool_result blocks). Differences from Claude:
|
|
10
|
+
*
|
|
11
|
+
* 1. **Tool names are gemini-cli style snake_case** (`read_file`, `write_file`,
|
|
12
|
+
* `replace`, `run_shell_command`, …). We map them to the canonical
|
|
13
|
+
* PascalCase names so the existing tool UI components render correctly,
|
|
14
|
+
* then normalise input shapes (`file_path` → `filePath`, etc.).
|
|
15
|
+
* 2. **Stop reasons are free-form strings** (the Anthropic-style values aren't
|
|
16
|
+
* guaranteed). We keep the strict union via best-effort mapping.
|
|
17
|
+
* 3. **Provider/account on every emitted message** is filled from per-stream
|
|
18
|
+
* state — there is no SDK-level "provider" hint.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type {
|
|
22
|
+
SDKMessage,
|
|
23
|
+
SDKAssistantMessage,
|
|
24
|
+
SDKUserMessage,
|
|
25
|
+
SDKPartialAssistantMessage,
|
|
26
|
+
SDKResultMessage,
|
|
27
|
+
SDKResultMessageSuccess,
|
|
28
|
+
SDKResultMessageError,
|
|
29
|
+
SDKSystemMessage,
|
|
30
|
+
ContentBlock as QwenContentBlock,
|
|
31
|
+
Usage as QwenUsage,
|
|
32
|
+
ExtendedUsage as QwenExtendedUsage,
|
|
33
|
+
} from '@qwen-code/sdk';
|
|
34
|
+
import type {
|
|
35
|
+
MessageEngine,
|
|
36
|
+
EngineOutput,
|
|
37
|
+
UserMessage,
|
|
38
|
+
AssistantMessage,
|
|
39
|
+
ReasoningMessage,
|
|
40
|
+
UserContentBlock,
|
|
41
|
+
AssistantContentBlock,
|
|
42
|
+
ToolUseBlock,
|
|
43
|
+
ToolResult,
|
|
44
|
+
TextDeltaEvent,
|
|
45
|
+
StreamLifecycleEvent,
|
|
46
|
+
SuccessResultEvent,
|
|
47
|
+
ErrorResultEvent,
|
|
48
|
+
SystemInitEvent,
|
|
49
|
+
TokenUsage,
|
|
50
|
+
StopReason,
|
|
51
|
+
AskUserQuestion,
|
|
52
|
+
} from '$shared/types/unified';
|
|
53
|
+
import { toCanonicalToolName } from '$shared/types/unified';
|
|
54
|
+
import { resolveOpenCodeToolName } from '../../../mcp/config';
|
|
55
|
+
|
|
56
|
+
// ============================================================
|
|
57
|
+
// Qwen-specific tool-result content markers
|
|
58
|
+
//
|
|
59
|
+
// Two strings come back from `agent` tool execution that mean "the sub-agent
|
|
60
|
+
// has only just been spawned — its real output is still pending":
|
|
61
|
+
//
|
|
62
|
+
// 1. FORK_PLACEHOLDER_RESULT — fire-and-forget fork (no `subagent_type`,
|
|
63
|
+
// no `run_in_background`). Source: `node_modules/@qwen-code/sdk/dist/cli/cli.js:277525`.
|
|
64
|
+
// 2. The "Background agent launched successfully…" multiline blob —
|
|
65
|
+
// `run_in_background: true` mode that emits a `task_notification` later.
|
|
66
|
+
// Source: same file around line 281616.
|
|
67
|
+
//
|
|
68
|
+
// We intercept these so the Agent block stays in the "pending" state in the
|
|
69
|
+
// UI while sub-activities accumulate, then emit a synthetic tool_result with
|
|
70
|
+
// the actual sub-agent output when we can.
|
|
71
|
+
// ============================================================
|
|
72
|
+
const QWEN_FORK_PLACEHOLDER_RESULT = 'Fork started — processing in background';
|
|
73
|
+
const QWEN_BACKGROUND_LAUNCH_PREFIX = 'Background agent launched successfully.';
|
|
74
|
+
|
|
75
|
+
function isQwenAgentPlaceholderResult(content: string): boolean {
|
|
76
|
+
const trimmed = content.trim();
|
|
77
|
+
return trimmed === QWEN_FORK_PLACEHOLDER_RESULT
|
|
78
|
+
|| trimmed.startsWith(QWEN_BACKGROUND_LAUNCH_PREFIX);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Format the user's answers to AskUserQuestion in OpenCode's wording so the
|
|
83
|
+
* downstream model sees a consistent payload regardless of which engine ran.
|
|
84
|
+
* Mirrors the OpenCode adapter's output:
|
|
85
|
+
* `User has answered your questions: "Q1"="A1", "Q2"="A2". You can now continue with the user's answers in mind.`
|
|
86
|
+
*
|
|
87
|
+
* Qwen's `answers` map is keyed by question INDEX (string number), not by
|
|
88
|
+
* question text — see `node_modules/@qwen-code/sdk/dist/cli/cli.js:284219-284222`.
|
|
89
|
+
* We dereference each index against the original questions array.
|
|
90
|
+
*/
|
|
91
|
+
function formatAskUserQuestionResult(questions: AskUserQuestion[], answers: Record<string, string>): string {
|
|
92
|
+
const pairs: string[] = [];
|
|
93
|
+
for (const [key, value] of Object.entries(answers)) {
|
|
94
|
+
const idx = Number.parseInt(key, 10);
|
|
95
|
+
const q = Number.isFinite(idx) ? questions[idx] : undefined;
|
|
96
|
+
const label = q?.question ?? q?.header ?? `Question ${key}`;
|
|
97
|
+
pairs.push(`"${label}"="${value}"`);
|
|
98
|
+
}
|
|
99
|
+
if (pairs.length === 0) {
|
|
100
|
+
return 'User did not provide any answers.';
|
|
101
|
+
}
|
|
102
|
+
return `User has answered your questions: ${pairs.join(', ')}. You can now continue with the user's answers in mind.`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ============================================================
|
|
106
|
+
// Engine identity
|
|
107
|
+
// ============================================================
|
|
108
|
+
|
|
109
|
+
export function buildEngine(modelId: string): MessageEngine {
|
|
110
|
+
return {
|
|
111
|
+
type: 'qwen',
|
|
112
|
+
provider: 'qwen',
|
|
113
|
+
model: { id: modelId, name: '' },
|
|
114
|
+
account: { id: 0, name: '' },
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// ============================================================
|
|
119
|
+
// Helper mappers
|
|
120
|
+
// ============================================================
|
|
121
|
+
|
|
122
|
+
function mapStopReason(raw: string | null | undefined): StopReason | null {
|
|
123
|
+
switch (raw) {
|
|
124
|
+
case 'end_turn':
|
|
125
|
+
case 'stop':
|
|
126
|
+
case 'finish':
|
|
127
|
+
return 'end_turn';
|
|
128
|
+
case 'tool_use':
|
|
129
|
+
case 'tool_calls':
|
|
130
|
+
return 'tool_use';
|
|
131
|
+
case 'max_tokens':
|
|
132
|
+
case 'length':
|
|
133
|
+
return 'max_tokens';
|
|
134
|
+
case 'interrupted':
|
|
135
|
+
case 'cancelled':
|
|
136
|
+
return 'interrupted';
|
|
137
|
+
default:
|
|
138
|
+
return raw ? 'end_turn' : null;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function mapUsage(raw: QwenUsage | QwenExtendedUsage | null | undefined): TokenUsage | null {
|
|
143
|
+
if (!raw) return null;
|
|
144
|
+
return {
|
|
145
|
+
inputTokens: raw.input_tokens || 0,
|
|
146
|
+
outputTokens: raw.output_tokens || 0,
|
|
147
|
+
cacheCreationInputTokens: raw.cache_creation_input_tokens || 0,
|
|
148
|
+
cacheReadInputTokens: raw.cache_read_input_tokens || 0,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function mapUsageRequired(raw: QwenUsage | QwenExtendedUsage | null | undefined): TokenUsage {
|
|
153
|
+
const usage = mapUsage(raw);
|
|
154
|
+
if (usage) return usage;
|
|
155
|
+
return { inputTokens: 0, outputTokens: 0, cacheCreationInputTokens: 0, cacheReadInputTokens: 0 };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// ============================================================
|
|
159
|
+
// Tool name + input normalisation
|
|
160
|
+
//
|
|
161
|
+
// Qwen Code is built on gemini-cli, so its tool surface uses snake_case
|
|
162
|
+
// names. We canonicalise both the name and the input fields so the existing
|
|
163
|
+
// tool UI components render the same way they do for Claude / Codex.
|
|
164
|
+
// ============================================================
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Map Qwen Code's snake_case tool names to the canonical PascalCase names
|
|
168
|
+
* the unified UI components render. Sourced from the bundled CLI's
|
|
169
|
+
* `ToolNames` table — `agent` (not `task`) is the dispatch tool, and
|
|
170
|
+
* `grep_search` is the active grep variant in v0.1.7+.
|
|
171
|
+
*/
|
|
172
|
+
const QWEN_TOOL_NAME_MAP: Record<string, string> = {
|
|
173
|
+
// File I/O
|
|
174
|
+
'read_file': 'Read',
|
|
175
|
+
'write_file': 'Write',
|
|
176
|
+
'replace': 'Edit',
|
|
177
|
+
'edit': 'Edit',
|
|
178
|
+
// Listing / search
|
|
179
|
+
'list_directory': 'List',
|
|
180
|
+
'ls': 'List',
|
|
181
|
+
'glob': 'Glob',
|
|
182
|
+
'grep_search': 'Grep',
|
|
183
|
+
'search_file_content': 'Grep',
|
|
184
|
+
'grep': 'Grep',
|
|
185
|
+
// Shell
|
|
186
|
+
'run_shell_command': 'Bash',
|
|
187
|
+
'shell': 'Bash',
|
|
188
|
+
'execute': 'Bash',
|
|
189
|
+
// Web
|
|
190
|
+
'web_fetch': 'WebFetch',
|
|
191
|
+
'google_web_search': 'WebSearch',
|
|
192
|
+
'web_search': 'WebSearch',
|
|
193
|
+
// Memory / planning
|
|
194
|
+
'todo_write': 'TodoWrite',
|
|
195
|
+
'save_memory': 'TodoWrite',
|
|
196
|
+
'exit_plan_mode': 'ExitPlanMode',
|
|
197
|
+
// Sub-agent dispatch
|
|
198
|
+
'agent': 'Agent',
|
|
199
|
+
'task': 'Agent',
|
|
200
|
+
'dispatch_agent': 'Agent',
|
|
201
|
+
'task_stop': 'TaskStop',
|
|
202
|
+
// Question / harness
|
|
203
|
+
'ask_user_question': 'AskUserQuestion',
|
|
204
|
+
'skill': 'Skill',
|
|
205
|
+
'lsp': 'Lsp',
|
|
206
|
+
// Cron
|
|
207
|
+
'cron_create': 'CronCreate',
|
|
208
|
+
'cron_list': 'CronList',
|
|
209
|
+
'cron_delete': 'CronDelete',
|
|
210
|
+
// `send_message` is the Qwen-specific channel the parent uses to push a
|
|
211
|
+
// follow-up prompt into a backgrounded sub-agent. There's no canonical
|
|
212
|
+
// equivalent — keep its raw name so the UI renders it as Unknown:* rather
|
|
213
|
+
// than silently swallowing the call.
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
function canonicaliseToolName(rawName: string): string {
|
|
217
|
+
// MCP tools come through as `clopen-mcp_<tool>` or `clopen-mcp-<tool>` —
|
|
218
|
+
// route through the shared resolver so they collapse to the canonical
|
|
219
|
+
// `mcp__<server>__<tool>` form (README §9.12).
|
|
220
|
+
const resolved = resolveOpenCodeToolName(rawName);
|
|
221
|
+
if (resolved) return resolved;
|
|
222
|
+
|
|
223
|
+
const mapped = QWEN_TOOL_NAME_MAP[rawName];
|
|
224
|
+
if (mapped) return mapped;
|
|
225
|
+
// Already canonical (PascalCase) — let toCanonicalToolName decide.
|
|
226
|
+
return rawName;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function snakeToCamel(str: string): string {
|
|
230
|
+
return str.replace(/_([a-z])/g, (_, c: string) => c.toUpperCase());
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Per-tool input normalisers — Qwen exposes gemini-cli's snake_case fields
|
|
235
|
+
* which the unified UI types expect in camelCase.
|
|
236
|
+
*/
|
|
237
|
+
function normaliseToolInput(canonical: string, raw: Record<string, unknown>): Record<string, unknown> {
|
|
238
|
+
switch (canonical) {
|
|
239
|
+
case 'Read': {
|
|
240
|
+
const path = (raw.absolute_path ?? raw.file_path ?? raw.path ?? raw.filePath) as string | undefined;
|
|
241
|
+
const offset = raw.offset as number | undefined;
|
|
242
|
+
const limit = raw.limit as number | undefined;
|
|
243
|
+
return {
|
|
244
|
+
...(path !== undefined ? { filePath: path } : {}),
|
|
245
|
+
...(offset !== undefined ? { offset } : {}),
|
|
246
|
+
...(limit !== undefined ? { limit } : {}),
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
case 'Write': {
|
|
250
|
+
const path = (raw.file_path ?? raw.path ?? raw.filePath ?? raw.absolute_path) as string | undefined;
|
|
251
|
+
const content = (raw.content ?? raw.text ?? raw.contents) as string | undefined;
|
|
252
|
+
return {
|
|
253
|
+
...(path !== undefined ? { filePath: path } : {}),
|
|
254
|
+
...(content !== undefined ? { content } : {}),
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
case 'Edit': {
|
|
258
|
+
const path = (raw.file_path ?? raw.path ?? raw.filePath ?? raw.absolute_path) as string | undefined;
|
|
259
|
+
const oldString = (raw.old_string ?? raw.oldString ?? raw.search) as string | undefined;
|
|
260
|
+
const newString = (raw.new_string ?? raw.newString ?? raw.replace) as string | undefined;
|
|
261
|
+
const replaceAll = (raw.expected_replacements ?? raw.replaceAll) as number | boolean | undefined;
|
|
262
|
+
return {
|
|
263
|
+
...(path !== undefined ? { filePath: path } : {}),
|
|
264
|
+
...(oldString !== undefined ? { oldString } : {}),
|
|
265
|
+
...(newString !== undefined ? { newString } : {}),
|
|
266
|
+
...(replaceAll !== undefined ? { replaceAll: typeof replaceAll === 'number' ? replaceAll > 1 : !!replaceAll } : {}),
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
case 'Bash': {
|
|
270
|
+
const command = (raw.command ?? raw.cmd ?? raw.script) as string | undefined;
|
|
271
|
+
const description = (raw.description ?? raw.reason) as string | undefined;
|
|
272
|
+
return {
|
|
273
|
+
...(command !== undefined ? { command } : {}),
|
|
274
|
+
...(description !== undefined ? { description } : {}),
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
case 'List': {
|
|
278
|
+
const path = (raw.path ?? raw.directory ?? raw.absolute_path ?? raw.filePath) as string | undefined;
|
|
279
|
+
return { ...(path !== undefined ? { path } : {}) };
|
|
280
|
+
}
|
|
281
|
+
case 'Glob': {
|
|
282
|
+
const pattern = (raw.pattern ?? raw.glob) as string | undefined;
|
|
283
|
+
const path = (raw.path ?? raw.directory) as string | undefined;
|
|
284
|
+
return {
|
|
285
|
+
...(pattern !== undefined ? { pattern } : {}),
|
|
286
|
+
...(path !== undefined ? { path } : {}),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
case 'Grep': {
|
|
290
|
+
const pattern = (raw.pattern ?? raw.regex ?? raw.query) as string | undefined;
|
|
291
|
+
const path = (raw.path ?? raw.directory) as string | undefined;
|
|
292
|
+
const include = (raw.include ?? raw.glob) as string | undefined;
|
|
293
|
+
return {
|
|
294
|
+
...(pattern !== undefined ? { pattern } : {}),
|
|
295
|
+
...(path !== undefined ? { path } : {}),
|
|
296
|
+
...(include !== undefined ? { glob: include } : {}),
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
case 'WebFetch': {
|
|
300
|
+
const url = raw.url as string | undefined;
|
|
301
|
+
const prompt = (raw.prompt ?? raw.query ?? raw.task) as string | undefined;
|
|
302
|
+
return {
|
|
303
|
+
...(url !== undefined ? { url } : {}),
|
|
304
|
+
...(prompt !== undefined ? { prompt } : {}),
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
case 'WebSearch': {
|
|
308
|
+
const query = (raw.query ?? raw.q) as string | undefined;
|
|
309
|
+
return { ...(query !== undefined ? { query } : {}) };
|
|
310
|
+
}
|
|
311
|
+
case 'TodoWrite': {
|
|
312
|
+
const todos = raw.todos ?? raw.items;
|
|
313
|
+
if (Array.isArray(todos)) {
|
|
314
|
+
const normalised = todos.map((t: unknown) => {
|
|
315
|
+
const todo = t as Record<string, unknown>;
|
|
316
|
+
return {
|
|
317
|
+
content: (todo.content ?? todo.text ?? todo.description ?? '') as string,
|
|
318
|
+
status: (todo.status ?? (todo.completed ? 'completed' : 'pending')) as string,
|
|
319
|
+
activeForm: (todo.activeForm ?? todo.active_form ?? todo.content ?? '') as string,
|
|
320
|
+
};
|
|
321
|
+
});
|
|
322
|
+
return { todos: normalised };
|
|
323
|
+
}
|
|
324
|
+
return { todos: [] };
|
|
325
|
+
}
|
|
326
|
+
case 'Agent': {
|
|
327
|
+
const subagentType = (raw.subagent_type ?? raw.agent_type ?? raw.agent ?? raw.name) as string | undefined;
|
|
328
|
+
const description = (raw.description ?? raw.task) as string | undefined;
|
|
329
|
+
const prompt = (raw.prompt ?? raw.instruction ?? raw.task) as string | undefined;
|
|
330
|
+
return {
|
|
331
|
+
...(prompt !== undefined ? { prompt } : {}),
|
|
332
|
+
...(description !== undefined ? { description } : {}),
|
|
333
|
+
subagentType: subagentType ?? 'general-purpose',
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
case 'AskUserQuestion': {
|
|
337
|
+
// Qwen's schema matches the unified shape closely — just pass `questions`
|
|
338
|
+
// through, defaulting to [] if absent so the UI renders an empty prompt
|
|
339
|
+
// instead of crashing.
|
|
340
|
+
const questions = Array.isArray(raw.questions) ? raw.questions : [];
|
|
341
|
+
return { questions };
|
|
342
|
+
}
|
|
343
|
+
case 'ExitPlanMode': {
|
|
344
|
+
// Qwen ships only `{ plan: string }`; the unified type's optional
|
|
345
|
+
// `allowedPrompts` field is unused. Pass `plan` through verbatim — the
|
|
346
|
+
// UI variants read it via `(input as Record<string,unknown>).plan`.
|
|
347
|
+
const plan = (raw.plan ?? raw.summary ?? raw.text) as string | undefined;
|
|
348
|
+
return plan !== undefined ? { plan } : {};
|
|
349
|
+
}
|
|
350
|
+
case 'Skill': {
|
|
351
|
+
const skill = (raw.skill ?? raw.name ?? raw.id) as string | undefined;
|
|
352
|
+
const args = (raw.args ?? raw.arguments ?? raw.input) as string | undefined;
|
|
353
|
+
return {
|
|
354
|
+
skill: skill ?? '',
|
|
355
|
+
...(args !== undefined ? { args } : {}),
|
|
356
|
+
};
|
|
357
|
+
}
|
|
358
|
+
case 'Lsp': {
|
|
359
|
+
const operation = (raw.operation ?? raw.action ?? raw.method) as string | undefined;
|
|
360
|
+
const filePath = (raw.file_path ?? raw.filePath ?? raw.path) as string | undefined;
|
|
361
|
+
const line = (raw.line ?? raw.lineNumber) as number | undefined;
|
|
362
|
+
const column = (raw.column ?? raw.col) as number | undefined;
|
|
363
|
+
const symbol = (raw.symbol ?? raw.name ?? raw.identifier) as string | undefined;
|
|
364
|
+
return {
|
|
365
|
+
operation: operation ?? '',
|
|
366
|
+
...(filePath !== undefined ? { filePath } : {}),
|
|
367
|
+
...(line !== undefined ? { line } : {}),
|
|
368
|
+
...(column !== undefined ? { column } : {}),
|
|
369
|
+
...(symbol !== undefined ? { symbol } : {}),
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
case 'CronCreate': {
|
|
373
|
+
const name = (raw.name ?? raw.title) as string | undefined;
|
|
374
|
+
const schedule = (raw.schedule ?? raw.cron ?? raw.expression) as string | undefined;
|
|
375
|
+
const prompt = (raw.prompt ?? raw.instruction ?? raw.task) as string | undefined;
|
|
376
|
+
const description = (raw.description ?? raw.summary) as string | undefined;
|
|
377
|
+
return {
|
|
378
|
+
name: name ?? '',
|
|
379
|
+
schedule: schedule ?? '',
|
|
380
|
+
prompt: prompt ?? '',
|
|
381
|
+
...(description !== undefined ? { description } : {}),
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
case 'CronList': {
|
|
385
|
+
const filter = (raw.filter ?? raw.query) as string | undefined;
|
|
386
|
+
return filter !== undefined ? { filter } : {};
|
|
387
|
+
}
|
|
388
|
+
case 'CronDelete': {
|
|
389
|
+
const id = (raw.id ?? raw.cron_id ?? raw.cronId ?? raw.name) as string | undefined;
|
|
390
|
+
return { id: id ?? '' };
|
|
391
|
+
}
|
|
392
|
+
case 'TaskStop': {
|
|
393
|
+
const taskId = (raw.task_id ?? raw.taskId ?? raw.id) as string | undefined;
|
|
394
|
+
return { taskId: taskId ?? '' };
|
|
395
|
+
}
|
|
396
|
+
default: {
|
|
397
|
+
// Generic snake → camel passthrough so unknown fields still render.
|
|
398
|
+
const out: Record<string, unknown> = {};
|
|
399
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
400
|
+
out[snakeToCamel(k)] = v;
|
|
401
|
+
}
|
|
402
|
+
return out;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// ============================================================
|
|
408
|
+
// Content block converters
|
|
409
|
+
// ============================================================
|
|
410
|
+
|
|
411
|
+
function mapAssistantContent(content: QwenContentBlock[], state?: QwenConverterState, sessionId?: string): AssistantContentBlock[] {
|
|
412
|
+
const blocks: AssistantContentBlock[] = [];
|
|
413
|
+
for (const block of content) {
|
|
414
|
+
switch (block.type) {
|
|
415
|
+
case 'text':
|
|
416
|
+
blocks.push({ type: 'text', text: block.text });
|
|
417
|
+
break;
|
|
418
|
+
case 'tool_use': {
|
|
419
|
+
const canonical = canonicaliseToolName(block.name);
|
|
420
|
+
const rawInput = (block.input && typeof block.input === 'object' ? block.input : {}) as Record<string, unknown>;
|
|
421
|
+
const normalisedInput = normaliseToolInput(canonical, rawInput);
|
|
422
|
+
const finalName = toCanonicalToolName(canonical);
|
|
423
|
+
if (finalName === 'AskUserQuestion') {
|
|
424
|
+
state?.onAskUserQuestionEmitted?.(block.id);
|
|
425
|
+
if (state) {
|
|
426
|
+
const questions = (normalisedInput.questions as AskUserQuestion[] | undefined) ?? [];
|
|
427
|
+
state.askUserQuestions.set(block.id, {
|
|
428
|
+
questions,
|
|
429
|
+
answered: false,
|
|
430
|
+
answers: null,
|
|
431
|
+
sessionId: sessionId ?? null,
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
} else if (finalName === 'Agent' && state) {
|
|
435
|
+
const description = (normalisedInput.description as string | undefined) ?? '';
|
|
436
|
+
state.pendingAgents.set(block.id, {
|
|
437
|
+
accumulatedText: '',
|
|
438
|
+
description,
|
|
439
|
+
sessionId: sessionId ?? null,
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
blocks.push({
|
|
443
|
+
type: 'tool_use',
|
|
444
|
+
id: block.id,
|
|
445
|
+
name: finalName,
|
|
446
|
+
input: normalisedInput,
|
|
447
|
+
result: null,
|
|
448
|
+
subActivities: [],
|
|
449
|
+
skillPrompt: null,
|
|
450
|
+
interrupted: false,
|
|
451
|
+
} as ToolUseBlock);
|
|
452
|
+
break;
|
|
453
|
+
}
|
|
454
|
+
// thinking/tool_result do not appear on assistant content here.
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
return blocks;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function mapUserContent(raw: string | QwenContentBlock[]): UserContentBlock[] {
|
|
461
|
+
if (typeof raw === 'string') {
|
|
462
|
+
return [{ type: 'text', text: raw }];
|
|
463
|
+
}
|
|
464
|
+
const blocks: UserContentBlock[] = [];
|
|
465
|
+
for (const block of raw) {
|
|
466
|
+
switch (block.type) {
|
|
467
|
+
case 'text':
|
|
468
|
+
blocks.push({ type: 'text', text: block.text });
|
|
469
|
+
break;
|
|
470
|
+
case 'tool_result': {
|
|
471
|
+
const inner = block.content;
|
|
472
|
+
let text = '';
|
|
473
|
+
if (typeof inner === 'string') {
|
|
474
|
+
text = inner;
|
|
475
|
+
} else if (Array.isArray(inner)) {
|
|
476
|
+
text = inner
|
|
477
|
+
.map(b => (b.type === 'text' ? b.text : ''))
|
|
478
|
+
.filter(Boolean)
|
|
479
|
+
.join('\n');
|
|
480
|
+
}
|
|
481
|
+
blocks.push({
|
|
482
|
+
type: 'tool_result',
|
|
483
|
+
toolUseId: block.tool_use_id,
|
|
484
|
+
content: text,
|
|
485
|
+
isError: !!block.is_error,
|
|
486
|
+
});
|
|
487
|
+
break;
|
|
488
|
+
}
|
|
489
|
+
// Qwen's content-block type does NOT include image/document on the
|
|
490
|
+
// inbound side — we only emit them on the outbound prompt.
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
if (blocks.length === 0) blocks.push({ type: 'text', text: '' });
|
|
494
|
+
return blocks;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// ============================================================
|
|
498
|
+
// Per-stream state — needed because the Qwen SDK emits
|
|
499
|
+
// `content_block_stop` without the block payload, mirroring Anthropic.
|
|
500
|
+
// ============================================================
|
|
501
|
+
|
|
502
|
+
export interface PendingAskUserQuestion {
|
|
503
|
+
questions: AskUserQuestion[];
|
|
504
|
+
answered: boolean;
|
|
505
|
+
answers: Record<string, string> | null;
|
|
506
|
+
/** Last session id we saw the AUQ on — used to stamp the synthetic tool_result. */
|
|
507
|
+
sessionId: string | null;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
export interface PendingAgent {
|
|
511
|
+
/**
|
|
512
|
+
* Accumulated text from sub-agent assistant messages whose
|
|
513
|
+
* `parent_tool_use_id` matches this Agent's call id. Used as the body of
|
|
514
|
+
* the synthetic tool_result we emit once we can finalize the Agent.
|
|
515
|
+
*/
|
|
516
|
+
accumulatedText: string;
|
|
517
|
+
/** Description from the original `agent` tool input, for status text. */
|
|
518
|
+
description: string;
|
|
519
|
+
/** Last session id we saw the Agent on — used to stamp the synthetic tool_result. */
|
|
520
|
+
sessionId: string | null;
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
export interface QwenConverterState {
|
|
524
|
+
modelId: string;
|
|
525
|
+
/** index → true when the block at that index is a thinking block. */
|
|
526
|
+
reasoningBlocks: Map<number, boolean>;
|
|
527
|
+
/**
|
|
528
|
+
* Optional callback fired the moment the converter sees a tool_use block
|
|
529
|
+
* whose canonical name is `AskUserQuestion`. The engine wires this to the
|
|
530
|
+
* pending-answer slot so `resolveUserAnswer(toolUseId, …)` can verify the
|
|
531
|
+
* inbound id matches the one the frontend was shown — Qwen's `canUseTool`
|
|
532
|
+
* callback intentionally does NOT pass the tool_use_id (line 486179 of the
|
|
533
|
+
* bundled CLI), so the converter is the only place we can recover it.
|
|
534
|
+
*/
|
|
535
|
+
onAskUserQuestionEmitted?: (toolUseId: string) => void;
|
|
536
|
+
/**
|
|
537
|
+
* Open AskUserQuestion calls keyed by tool_use_id. Populated when the
|
|
538
|
+
* assistant message containing the AUQ tool_use is converted. The engine
|
|
539
|
+
* pushes the user's answers in via `recordUserAnswer` as soon as
|
|
540
|
+
* `resolveUserAnswer` fires; the entry stays around until the SDK emits
|
|
541
|
+
* the AUQ tool_result, at which point we replace its content.
|
|
542
|
+
*/
|
|
543
|
+
askUserQuestions: Map<string, PendingAskUserQuestion>;
|
|
544
|
+
/**
|
|
545
|
+
* Open Agent calls keyed by tool_use_id. Qwen's built-in `agent` tool
|
|
546
|
+
* returns immediately with a placeholder ("Fork started …") regardless of
|
|
547
|
+
* whether the sub-agent actually finished — we track each Agent here so
|
|
548
|
+
* we can suppress the placeholder, accumulate the sub-agent's output, and
|
|
549
|
+
* emit a synthetic completion tool_result later (via `task_notification`
|
|
550
|
+
* for run_in_background mode, or the SDK's final result event for forks).
|
|
551
|
+
*/
|
|
552
|
+
pendingAgents: Map<string, PendingAgent>;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
export function createConverterState(modelId: string): QwenConverterState {
|
|
556
|
+
return {
|
|
557
|
+
modelId,
|
|
558
|
+
reasoningBlocks: new Map(),
|
|
559
|
+
askUserQuestions: new Map(),
|
|
560
|
+
pendingAgents: new Map(),
|
|
561
|
+
};
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
// ============================================================
|
|
565
|
+
// Top-level dispatchers
|
|
566
|
+
// ============================================================
|
|
567
|
+
|
|
568
|
+
export function convertAssistantMessage(msg: SDKAssistantMessage, state: QwenConverterState): EngineOutput[] {
|
|
569
|
+
const sessionId = msg.session_id;
|
|
570
|
+
const inner = msg.message;
|
|
571
|
+
const content = inner.content;
|
|
572
|
+
const outputs: EngineOutput[] = [];
|
|
573
|
+
|
|
574
|
+
const thinkingBlocks = content.filter(b => b.type === 'thinking');
|
|
575
|
+
if (thinkingBlocks.length > 0) {
|
|
576
|
+
const text = thinkingBlocks
|
|
577
|
+
.map(b => (b.type === 'thinking' ? b.thinking : ''))
|
|
578
|
+
.join('\n')
|
|
579
|
+
.trim();
|
|
580
|
+
if (text) {
|
|
581
|
+
const reasoning: ReasoningMessage = {
|
|
582
|
+
type: 'reasoning',
|
|
583
|
+
createdAt: new Date().toISOString(),
|
|
584
|
+
messageId: crypto.randomUUID(),
|
|
585
|
+
sessionId,
|
|
586
|
+
parent: { messageId: null, sessionId: null, toolUseId: msg.parent_tool_use_id || null },
|
|
587
|
+
engine: buildEngine(state.modelId),
|
|
588
|
+
text,
|
|
589
|
+
};
|
|
590
|
+
outputs.push(reasoning);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
const otherBlocks = content.filter(b => b.type !== 'thinking');
|
|
595
|
+
const blocks = mapAssistantContent(
|
|
596
|
+
otherBlocks.length > 0 ? otherBlocks : [{ type: 'text', text: '' } as QwenContentBlock],
|
|
597
|
+
state,
|
|
598
|
+
sessionId,
|
|
599
|
+
);
|
|
600
|
+
|
|
601
|
+
// If this assistant message belongs to a sub-agent (parent_tool_use_id
|
|
602
|
+
// matches a tracked Agent), accumulate its text into the parent Agent's
|
|
603
|
+
// buffer so we can use it as the final tool_result content when we
|
|
604
|
+
// finalize the Agent (via task_notification or the SDK's result event).
|
|
605
|
+
const parentToolUseId = msg.parent_tool_use_id || null;
|
|
606
|
+
if (parentToolUseId && state.pendingAgents.has(parentToolUseId)) {
|
|
607
|
+
const entry = state.pendingAgents.get(parentToolUseId)!;
|
|
608
|
+
const subText = blocks
|
|
609
|
+
.filter(b => b.type === 'text')
|
|
610
|
+
.map(b => (b.type === 'text' ? b.text : ''))
|
|
611
|
+
.filter(Boolean)
|
|
612
|
+
.join('\n');
|
|
613
|
+
if (subText) {
|
|
614
|
+
entry.accumulatedText = entry.accumulatedText
|
|
615
|
+
? `${entry.accumulatedText}\n${subText}`
|
|
616
|
+
: subText;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const baseId = msg.uuid || crypto.randomUUID();
|
|
621
|
+
if (blocks.length <= 1) {
|
|
622
|
+
const assistant: AssistantMessage = {
|
|
623
|
+
type: 'assistant',
|
|
624
|
+
createdAt: new Date().toISOString(),
|
|
625
|
+
messageId: baseId,
|
|
626
|
+
sessionId,
|
|
627
|
+
parent: { messageId: null, sessionId: null, toolUseId: msg.parent_tool_use_id || null },
|
|
628
|
+
engine: buildEngine(state.modelId),
|
|
629
|
+
content: blocks,
|
|
630
|
+
stopReason: mapStopReason(inner.stop_reason),
|
|
631
|
+
usage: mapUsage(inner.usage),
|
|
632
|
+
};
|
|
633
|
+
outputs.push(assistant);
|
|
634
|
+
} else {
|
|
635
|
+
// One tool_use per AssistantMessage (README §9.3).
|
|
636
|
+
blocks.forEach((block, idx) => {
|
|
637
|
+
const assistant: AssistantMessage = {
|
|
638
|
+
type: 'assistant',
|
|
639
|
+
createdAt: new Date().toISOString(),
|
|
640
|
+
messageId: `${baseId}:${idx}`,
|
|
641
|
+
sessionId,
|
|
642
|
+
parent: { messageId: null, sessionId: null, toolUseId: msg.parent_tool_use_id || null },
|
|
643
|
+
engine: buildEngine(state.modelId),
|
|
644
|
+
content: [block],
|
|
645
|
+
stopReason: block.type === 'tool_use' ? 'tool_use' : mapStopReason(inner.stop_reason),
|
|
646
|
+
usage: idx === blocks.length - 1 ? mapUsage(inner.usage) : null,
|
|
647
|
+
};
|
|
648
|
+
outputs.push(assistant);
|
|
649
|
+
});
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
return outputs;
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/**
|
|
656
|
+
* Convert an SDK user message into a unified `UserMessage`, intercepting
|
|
657
|
+
* tool_result blocks for AskUserQuestion and the Agent fork placeholder.
|
|
658
|
+
*
|
|
659
|
+
* Returns `null` when every content block was intercepted/dropped — the
|
|
660
|
+
* dispatcher then emits nothing (we'll synthesize the real result later from
|
|
661
|
+
* `task_notification` or the SDK's final result event).
|
|
662
|
+
*/
|
|
663
|
+
export function convertUserMessage(msg: SDKUserMessage, state: QwenConverterState): UserMessage | null {
|
|
664
|
+
const rawBlocks = mapUserContent(msg.message.content);
|
|
665
|
+
const outBlocks: UserContentBlock[] = [];
|
|
666
|
+
|
|
667
|
+
for (const block of rawBlocks) {
|
|
668
|
+
if (block.type !== 'tool_result') {
|
|
669
|
+
outBlocks.push(block);
|
|
670
|
+
continue;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// 1. AskUserQuestion: replace the SDK's broken empty-answer body with
|
|
674
|
+
// the real answers. The Qwen SDK's stream-json `handleOutgoingPermissionRequest`
|
|
675
|
+
// calls `onConfirm(ProceedOnce)` without a payload, dropping the
|
|
676
|
+
// `answers` we passed via `updatedInput`. See the analysis in
|
|
677
|
+
// `qwen/stream.ts::resolveUserAnswer` and `cli.js:486478-486485`.
|
|
678
|
+
const auq = state.askUserQuestions.get(block.toolUseId);
|
|
679
|
+
if (auq) {
|
|
680
|
+
const content = auq.answered && auq.answers
|
|
681
|
+
? formatAskUserQuestionResult(auq.questions, auq.answers)
|
|
682
|
+
: 'User did not provide an answer to the questions.';
|
|
683
|
+
outBlocks.push({
|
|
684
|
+
type: 'tool_result',
|
|
685
|
+
toolUseId: block.toolUseId,
|
|
686
|
+
content,
|
|
687
|
+
isError: false,
|
|
688
|
+
});
|
|
689
|
+
state.askUserQuestions.delete(block.toolUseId);
|
|
690
|
+
continue;
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// 2. Agent fork placeholder: drop entirely. The Agent block stays in
|
|
694
|
+
// the "pending" state in the UI; the real tool_result is emitted
|
|
695
|
+
// later from `task_notification` or the SDK's result event.
|
|
696
|
+
if (state.pendingAgents.has(block.toolUseId) && isQwenAgentPlaceholderResult(block.content)) {
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
outBlocks.push(block);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (outBlocks.length === 0) return null;
|
|
704
|
+
|
|
705
|
+
return {
|
|
706
|
+
type: 'user',
|
|
707
|
+
createdAt: new Date().toISOString(),
|
|
708
|
+
messageId: msg.uuid || crypto.randomUUID(),
|
|
709
|
+
sessionId: msg.session_id,
|
|
710
|
+
// Top-level tool_result UserMessage MUST keep parent.toolUseId = null
|
|
711
|
+
// (README §9.5). Sub-agent messages are an explicit exception.
|
|
712
|
+
parent: { messageId: null, sessionId: null, toolUseId: msg.parent_tool_use_id || null },
|
|
713
|
+
engine: buildEngine(state.modelId),
|
|
714
|
+
sender: { id: '', name: '' },
|
|
715
|
+
content: outBlocks,
|
|
716
|
+
synthetic: true,
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Build a synthetic UserMessage carrying a single tool_result block.
|
|
722
|
+
* Used to finalize Agent calls from `task_notification` or the SDK's final
|
|
723
|
+
* result event when the SDK never sent a real tool_result for the Agent.
|
|
724
|
+
*/
|
|
725
|
+
function buildSyntheticToolResult(
|
|
726
|
+
state: QwenConverterState,
|
|
727
|
+
toolUseId: string,
|
|
728
|
+
sessionId: string | null,
|
|
729
|
+
result: ToolResult,
|
|
730
|
+
): UserMessage {
|
|
731
|
+
return {
|
|
732
|
+
type: 'user',
|
|
733
|
+
createdAt: new Date().toISOString(),
|
|
734
|
+
messageId: crypto.randomUUID(),
|
|
735
|
+
sessionId: sessionId ?? '',
|
|
736
|
+
parent: { messageId: null, sessionId: null, toolUseId: null },
|
|
737
|
+
engine: buildEngine(state.modelId),
|
|
738
|
+
sender: { id: '', name: '' },
|
|
739
|
+
content: [result],
|
|
740
|
+
synthetic: true,
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
export function convertStreamEvent(msg: SDKPartialAssistantMessage, state: QwenConverterState): EngineOutput[] {
|
|
745
|
+
const sessionId = msg.session_id;
|
|
746
|
+
const event = msg.event;
|
|
747
|
+
const outputs: EngineOutput[] = [];
|
|
748
|
+
|
|
749
|
+
// Suppress streaming deltas that belong to a backgrounded sub-agent —
|
|
750
|
+
// they double-emit alongside the eventual non-streaming `assistant`
|
|
751
|
+
// message scoped to the sub-agent (which carries `parent_tool_use_id` and
|
|
752
|
+
// is routed into the parent Agent block's subActivities by the frontend
|
|
753
|
+
// grouper). Without this drop, the deltas leak into the main turn's text
|
|
754
|
+
// bubble. See README §9.15 fix #3.
|
|
755
|
+
if (msg.parent_tool_use_id) return outputs;
|
|
756
|
+
|
|
757
|
+
switch (event.type) {
|
|
758
|
+
case 'message_start':
|
|
759
|
+
case 'message_stop': {
|
|
760
|
+
outputs.push({
|
|
761
|
+
type: 'stream_event',
|
|
762
|
+
event: event.type === 'message_start' ? 'start' : 'stop',
|
|
763
|
+
sessionId,
|
|
764
|
+
reasoning: false,
|
|
765
|
+
} as StreamLifecycleEvent);
|
|
766
|
+
break;
|
|
767
|
+
}
|
|
768
|
+
case 'content_block_start': {
|
|
769
|
+
const blockType = event.content_block.type;
|
|
770
|
+
const isReasoning = blockType === 'thinking';
|
|
771
|
+
state.reasoningBlocks.set(event.index, isReasoning);
|
|
772
|
+
if (isReasoning) {
|
|
773
|
+
outputs.push({ type: 'stream_event', event: 'start', sessionId, reasoning: true } as StreamLifecycleEvent);
|
|
774
|
+
} else if (blockType === 'text') {
|
|
775
|
+
outputs.push({ type: 'stream_event', event: 'start', sessionId, reasoning: false } as StreamLifecycleEvent);
|
|
776
|
+
}
|
|
777
|
+
break;
|
|
778
|
+
}
|
|
779
|
+
case 'content_block_delta': {
|
|
780
|
+
const delta = event.delta;
|
|
781
|
+
if (delta.type === 'thinking_delta') {
|
|
782
|
+
outputs.push({
|
|
783
|
+
type: 'stream_event',
|
|
784
|
+
event: 'delta',
|
|
785
|
+
sessionId,
|
|
786
|
+
text: delta.thinking || '',
|
|
787
|
+
reasoning: true,
|
|
788
|
+
} as TextDeltaEvent);
|
|
789
|
+
} else if (delta.type === 'text_delta') {
|
|
790
|
+
outputs.push({
|
|
791
|
+
type: 'stream_event',
|
|
792
|
+
event: 'delta',
|
|
793
|
+
sessionId,
|
|
794
|
+
text: delta.text || '',
|
|
795
|
+
reasoning: false,
|
|
796
|
+
} as TextDeltaEvent);
|
|
797
|
+
}
|
|
798
|
+
// input_json_delta: tool argument streaming — the UI doesn't render
|
|
799
|
+
// partial tool inputs, so we drop these and wait for the final
|
|
800
|
+
// assistant.message that carries the full input object.
|
|
801
|
+
break;
|
|
802
|
+
}
|
|
803
|
+
case 'content_block_stop': {
|
|
804
|
+
const isReasoning = state.reasoningBlocks.get(event.index) === true;
|
|
805
|
+
state.reasoningBlocks.delete(event.index);
|
|
806
|
+
outputs.push({ type: 'stream_event', event: 'stop', sessionId, reasoning: isReasoning } as StreamLifecycleEvent);
|
|
807
|
+
break;
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
return outputs;
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
export function convertResultSuccess(msg: SDKResultMessageSuccess): SuccessResultEvent {
|
|
815
|
+
return {
|
|
816
|
+
type: 'result',
|
|
817
|
+
subtype: 'success',
|
|
818
|
+
sessionId: msg.session_id,
|
|
819
|
+
numTurns: msg.num_turns || 0,
|
|
820
|
+
totalCostUsd: 0,
|
|
821
|
+
usage: mapUsageRequired(msg.usage),
|
|
822
|
+
stopReason: null,
|
|
823
|
+
};
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
export function convertResultError(msg: SDKResultMessageError): ErrorResultEvent {
|
|
827
|
+
return {
|
|
828
|
+
type: 'result',
|
|
829
|
+
subtype: msg.subtype === 'error_max_turns' ? 'error_max_turns' : 'error_during_execution',
|
|
830
|
+
sessionId: msg.session_id,
|
|
831
|
+
errors: msg.error?.message ? [msg.error.message] : [],
|
|
832
|
+
};
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
export function convertSystemInit(msg: SDKSystemMessage, state: QwenConverterState): SystemInitEvent {
|
|
836
|
+
return {
|
|
837
|
+
type: 'system_init',
|
|
838
|
+
sessionId: msg.session_id,
|
|
839
|
+
model: msg.model || state.modelId,
|
|
840
|
+
engine: 'qwen',
|
|
841
|
+
tools: msg.tools || [],
|
|
842
|
+
mcpServers: (msg.mcp_servers || []).map(s => ({
|
|
843
|
+
name: s.name || '',
|
|
844
|
+
status: (s.status as 'connected' | 'disconnected' | 'error') || 'disconnected',
|
|
845
|
+
})),
|
|
846
|
+
};
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
/**
|
|
850
|
+
* Handle a `task_notification` system message — emitted by the Qwen SDK when
|
|
851
|
+
* a `run_in_background: true` Agent reaches a terminal status. Source:
|
|
852
|
+
* `node_modules/@qwen-code/sdk/dist/cli/cli.js:485345-485353` and 227829.
|
|
853
|
+
*
|
|
854
|
+
* `data` shape (per `cli.js:485240-485249`):
|
|
855
|
+
* `{ task_id, tool_use_id, status: 'completed'|'failed'|'cancelled'|'running', usage? }`
|
|
856
|
+
*
|
|
857
|
+
* The full sub-agent text is NOT in `data` — it's only in the SDK-internal
|
|
858
|
+
* `modelText` (XML with `<result>`) which is fed to the model on the next
|
|
859
|
+
* turn but never emitted to us. We use the text we accumulated from the
|
|
860
|
+
* sub-agent's assistant messages (via `parent_tool_use_id` routing) instead.
|
|
861
|
+
*
|
|
862
|
+
* Returns the synthetic tool_result UserMessage to emit, or null when the
|
|
863
|
+
* notification doesn't match a tracked Agent (e.g. `status: 'running'`, or
|
|
864
|
+
* the toolUseId belongs to a different stream).
|
|
865
|
+
*/
|
|
866
|
+
function convertTaskNotification(msg: SDKSystemMessage, state: QwenConverterState): UserMessage | null {
|
|
867
|
+
const data = (msg.data ?? {}) as { tool_use_id?: string; status?: string; task_id?: string };
|
|
868
|
+
const toolUseId = data.tool_use_id;
|
|
869
|
+
if (!toolUseId) return null;
|
|
870
|
+
|
|
871
|
+
const entry = state.pendingAgents.get(toolUseId);
|
|
872
|
+
if (!entry) return null;
|
|
873
|
+
|
|
874
|
+
// Only finalize on terminal statuses; "running" is intermediate.
|
|
875
|
+
const status = data.status ?? '';
|
|
876
|
+
if (status !== 'completed' && status !== 'failed' && status !== 'cancelled') {
|
|
877
|
+
return null;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
const isError = status === 'failed' || status === 'cancelled';
|
|
881
|
+
const body = entry.accumulatedText.trim();
|
|
882
|
+
const fallbackByStatus: Record<string, string> = {
|
|
883
|
+
completed: entry.description
|
|
884
|
+
? `Agent task "${entry.description}" completed.`
|
|
885
|
+
: 'Agent task completed.',
|
|
886
|
+
failed: entry.description
|
|
887
|
+
? `Agent task "${entry.description}" failed.`
|
|
888
|
+
: 'Agent task failed.',
|
|
889
|
+
cancelled: entry.description
|
|
890
|
+
? `Agent task "${entry.description}" was cancelled.`
|
|
891
|
+
: 'Agent task was cancelled.',
|
|
892
|
+
};
|
|
893
|
+
const content = body || fallbackByStatus[status];
|
|
894
|
+
|
|
895
|
+
state.pendingAgents.delete(toolUseId);
|
|
896
|
+
|
|
897
|
+
return buildSyntheticToolResult(state, toolUseId, entry.sessionId ?? msg.session_id, {
|
|
898
|
+
type: 'tool_result',
|
|
899
|
+
toolUseId,
|
|
900
|
+
content,
|
|
901
|
+
isError,
|
|
902
|
+
});
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
/**
|
|
906
|
+
* Finalize any AskUserQuestion / Agent calls that are still open when the
|
|
907
|
+
* SDK ends the query. Without this, the UI would leave Agent blocks spinning
|
|
908
|
+
* forever (Qwen forks have no completion notification — README §9.15) and
|
|
909
|
+
* AUQ blocks would stay pending if the user closed the dialog without
|
|
910
|
+
* answering.
|
|
911
|
+
*/
|
|
912
|
+
function* flushPendingOnResult(state: QwenConverterState, sessionId: string): Generator<UserMessage> {
|
|
913
|
+
for (const [toolUseId, entry] of state.askUserQuestions) {
|
|
914
|
+
yield buildSyntheticToolResult(state, toolUseId, entry.sessionId ?? sessionId, {
|
|
915
|
+
type: 'tool_result',
|
|
916
|
+
toolUseId,
|
|
917
|
+
content: 'User did not provide an answer to the questions.',
|
|
918
|
+
isError: false,
|
|
919
|
+
});
|
|
920
|
+
}
|
|
921
|
+
state.askUserQuestions.clear();
|
|
922
|
+
|
|
923
|
+
for (const [toolUseId, entry] of state.pendingAgents) {
|
|
924
|
+
const body = entry.accumulatedText.trim();
|
|
925
|
+
const fallback = entry.description
|
|
926
|
+
? `Agent task "${entry.description}" completed.`
|
|
927
|
+
: 'Agent task completed.';
|
|
928
|
+
yield buildSyntheticToolResult(state, toolUseId, entry.sessionId ?? sessionId, {
|
|
929
|
+
type: 'tool_result',
|
|
930
|
+
toolUseId,
|
|
931
|
+
content: body || fallback,
|
|
932
|
+
isError: false,
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
state.pendingAgents.clear();
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
// ============================================================
|
|
939
|
+
// Top-level dispatcher
|
|
940
|
+
// ============================================================
|
|
941
|
+
|
|
942
|
+
export interface SdkMessageConverterOptions {
|
|
943
|
+
/** Forwarded to converter state — see `QwenConverterState.onAskUserQuestionEmitted`. */
|
|
944
|
+
onAskUserQuestionEmitted?: (toolUseId: string) => void;
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
export interface SdkMessageConverter {
|
|
948
|
+
convert(msg: SDKMessage): Generator<EngineOutput>;
|
|
949
|
+
/**
|
|
950
|
+
* Push the user's answers into the converter state so the next AUQ
|
|
951
|
+
* tool_result we see can be rewritten with the proper `User has answered
|
|
952
|
+
* your questions: …` payload. Idempotent — if no AUQ matches the toolUseId,
|
|
953
|
+
* the call is a no-op (harmless if the SDK already auto-completed it).
|
|
954
|
+
*/
|
|
955
|
+
recordUserAnswer(toolUseId: string, answers: Record<string, string>): void;
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
export function createSdkMessageConverter(
|
|
959
|
+
modelId: string,
|
|
960
|
+
options: SdkMessageConverterOptions = {},
|
|
961
|
+
): SdkMessageConverter {
|
|
962
|
+
const state = createConverterState(modelId);
|
|
963
|
+
state.onAskUserQuestionEmitted = options.onAskUserQuestionEmitted;
|
|
964
|
+
|
|
965
|
+
function* convert(msg: SDKMessage): Generator<EngineOutput> {
|
|
966
|
+
switch (msg.type) {
|
|
967
|
+
case 'assistant':
|
|
968
|
+
for (const out of convertAssistantMessage(msg, state)) yield out;
|
|
969
|
+
return;
|
|
970
|
+
case 'user': {
|
|
971
|
+
const userMsg = convertUserMessage(msg, state);
|
|
972
|
+
if (userMsg) yield userMsg;
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
case 'stream_event':
|
|
976
|
+
for (const out of convertStreamEvent(msg, state)) yield out;
|
|
977
|
+
return;
|
|
978
|
+
case 'system': {
|
|
979
|
+
if (msg.subtype === 'init') {
|
|
980
|
+
yield convertSystemInit(msg, state);
|
|
981
|
+
} else if (msg.subtype === 'task_notification') {
|
|
982
|
+
const synth = convertTaskNotification(msg, state);
|
|
983
|
+
if (synth) yield synth;
|
|
984
|
+
}
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
case 'result': {
|
|
988
|
+
const result = msg as SDKResultMessage;
|
|
989
|
+
// Flush any still-open AUQ / Agent calls BEFORE the result event
|
|
990
|
+
// so the UI sees their tool_result land in the right order
|
|
991
|
+
// (tool_use → tool_result → result).
|
|
992
|
+
yield* flushPendingOnResult(state, result.session_id);
|
|
993
|
+
if (result.subtype === 'success') {
|
|
994
|
+
yield convertResultSuccess(result);
|
|
995
|
+
} else {
|
|
996
|
+
yield convertResultError(result);
|
|
997
|
+
}
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
return {
|
|
1004
|
+
convert,
|
|
1005
|
+
recordUserAnswer(toolUseId, answers) {
|
|
1006
|
+
const entry = state.askUserQuestions.get(toolUseId);
|
|
1007
|
+
if (!entry) return;
|
|
1008
|
+
entry.answers = answers;
|
|
1009
|
+
entry.answered = true;
|
|
1010
|
+
},
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
// ============================================================
|
|
1015
|
+
// Outbound prompt converter
|
|
1016
|
+
// ============================================================
|
|
1017
|
+
|
|
1018
|
+
export function toSdkUserMessage(msg: UserMessage): SDKUserMessage {
|
|
1019
|
+
const sdkContent: QwenContentBlock[] = [];
|
|
1020
|
+
|
|
1021
|
+
for (const block of msg.content) {
|
|
1022
|
+
switch (block.type) {
|
|
1023
|
+
case 'text':
|
|
1024
|
+
sdkContent.push({ type: 'text', text: block.text });
|
|
1025
|
+
break;
|
|
1026
|
+
case 'tool_result':
|
|
1027
|
+
sdkContent.push({
|
|
1028
|
+
type: 'tool_result',
|
|
1029
|
+
tool_use_id: block.toolUseId,
|
|
1030
|
+
content: block.content,
|
|
1031
|
+
is_error: block.isError,
|
|
1032
|
+
});
|
|
1033
|
+
break;
|
|
1034
|
+
// Qwen's SDK content-block type does not include image/document
|
|
1035
|
+
// blocks for inbound user messages — image/PDF attachments are
|
|
1036
|
+
// dropped here. The CLI accepts text-only prompts.
|
|
1037
|
+
case 'image':
|
|
1038
|
+
case 'document':
|
|
1039
|
+
break;
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
|
|
1043
|
+
const content: string | QwenContentBlock[] =
|
|
1044
|
+
sdkContent.length === 1 && sdkContent[0].type === 'text'
|
|
1045
|
+
? sdkContent[0].text
|
|
1046
|
+
: sdkContent;
|
|
1047
|
+
|
|
1048
|
+
return {
|
|
1049
|
+
type: 'user',
|
|
1050
|
+
uuid: msg.messageId,
|
|
1051
|
+
session_id: msg.sessionId ?? '',
|
|
1052
|
+
parent_tool_use_id: msg.parent.toolUseId,
|
|
1053
|
+
message: { role: 'user', content },
|
|
1054
|
+
};
|
|
1055
|
+
}
|