dsh-agent-sdk-bridge 1.2.2 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/DEVELOPMENT.md +38 -5
- package/FAQ.md +78 -2
- package/lib/index.js +566 -114
- package/lib/types/adapter.d.ts +10 -0
- package/lib/types/codebuddy-state.d.ts +23 -0
- package/lib/types/codebuddy.d.ts +40 -6
- package/lib/types/mcp-naming.d.ts +43 -0
- package/lib/types/minimax.d.ts +8 -1
- package/lib/types/models.d.ts +37 -3
- package/lib/types/render.d.ts +11 -0
- package/lib/types/sdk.d.ts +16 -0
- package/lib/types/session.d.ts +143 -3
- package/lib/types/usage.d.ts +7 -1
- package/package.json +1 -1
- package/src/adapter.ts +22 -3
- package/src/api.ts +6 -6
- package/src/codebuddy-adapter.ts +5 -3
- package/src/codebuddy-state.ts +53 -0
- package/src/codebuddy.ts +148 -59
- package/src/mcp-naming.ts +68 -0
- package/src/minimax-adapter.ts +5 -3
- package/src/minimax.ts +2463 -2458
- package/src/models.ts +85 -8
- package/src/render.ts +51 -0
- package/src/sdk.ts +25 -0
- package/src/session.ts +232 -27
- package/src/usage.ts +24 -5
package/src/codebuddy-state.ts
CHANGED
|
@@ -28,6 +28,24 @@ export interface CodeBuddySavedUser {
|
|
|
28
28
|
userNickname: string
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
/**
|
|
32
|
+
* A stored account reading with its credential removed.
|
|
33
|
+
*
|
|
34
|
+
* The CLI's `accountInfo()` answer carries a bearer token, and older versions
|
|
35
|
+
* persisted that object whole — a second copy of the credential in a file that
|
|
36
|
+
* gets backed up and pasted into bug reports, one the plugin never read. A
|
|
37
|
+
* region holds exactly one credential, in `token`.
|
|
38
|
+
*/
|
|
39
|
+
export function withoutCredential(account: CodeBuddyAccount | undefined): CodeBuddyAccount | undefined {
|
|
40
|
+
if (account === undefined) return undefined
|
|
41
|
+
const clean: Record<string, unknown> = {}
|
|
42
|
+
for (const [key, value] of Object.entries(account as Record<string, unknown>)) {
|
|
43
|
+
if (/token|secret|credential|password|cookie/i.test(key)) continue
|
|
44
|
+
clean[key] = value
|
|
45
|
+
}
|
|
46
|
+
return clean as CodeBuddyAccount
|
|
47
|
+
}
|
|
48
|
+
|
|
31
49
|
/** Everything remembered for one login region. */
|
|
32
50
|
export interface CodeBuddySavedRegion {
|
|
33
51
|
/** Bearer credential from the SDK login, used to restore the login. */
|
|
@@ -93,6 +111,7 @@ export class CodeBuddyStateStore {
|
|
|
93
111
|
const parsed = JSON.parse(readFileSync(this.file, 'utf8')) as Partial<SavedFile>
|
|
94
112
|
if (parsed.version === 1 && parsed.regions !== null && typeof parsed.regions === 'object') {
|
|
95
113
|
this.state = { version: 1, regions: parsed.regions }
|
|
114
|
+
this.recoverLostTokens()
|
|
96
115
|
}
|
|
97
116
|
} catch {
|
|
98
117
|
// A missing or unreadable file is the normal first-run state.
|
|
@@ -100,6 +119,37 @@ export class CodeBuddyStateStore {
|
|
|
100
119
|
return this.state
|
|
101
120
|
}
|
|
102
121
|
|
|
122
|
+
/**
|
|
123
|
+
* Lift a credential the old layout hid inside the account object.
|
|
124
|
+
*
|
|
125
|
+
* The CLI's `accountInfo()` answer carries a bearer token of its own, and an
|
|
126
|
+
* earlier version persisted that whole object here. When the top-level
|
|
127
|
+
* `token` was later dropped — which any quota failure used to do, because
|
|
128
|
+
* expiry was *guessed* from the error text — the region read as signed out
|
|
129
|
+
* even though a working credential still sat in the file, and nothing could
|
|
130
|
+
* recover it without a fresh browser login. This picks the copy back up.
|
|
131
|
+
*
|
|
132
|
+
* {@link persist} no longer stores a token inside the account, so this runs
|
|
133
|
+
* only over files written by those older versions.
|
|
134
|
+
*/
|
|
135
|
+
private recoverLostTokens(): void {
|
|
136
|
+
let recovered = false
|
|
137
|
+
for (const [key, saved] of Object.entries(this.state.regions)) {
|
|
138
|
+
const region = key as CodeBuddyRegion
|
|
139
|
+
const hidden = (saved?.account as { token?: unknown } | undefined)?.token
|
|
140
|
+
if (saved === undefined || saved.token !== undefined) continue
|
|
141
|
+
if (typeof hidden !== 'string' || hidden.length === 0) continue
|
|
142
|
+
this.state.regions[region] = {
|
|
143
|
+
...saved,
|
|
144
|
+
token: hidden,
|
|
145
|
+
signedIn: true,
|
|
146
|
+
account: withoutCredential(saved.account),
|
|
147
|
+
}
|
|
148
|
+
recovered = true
|
|
149
|
+
}
|
|
150
|
+
if (recovered) this.persist()
|
|
151
|
+
}
|
|
152
|
+
|
|
103
153
|
region(region: CodeBuddyRegion): CodeBuddySavedRegion | undefined {
|
|
104
154
|
return this.ensureLoaded().regions[region]
|
|
105
155
|
}
|
|
@@ -138,6 +188,9 @@ export class CodeBuddyStateStore {
|
|
|
138
188
|
if (value === undefined) delete next[key as keyof CodeBuddySavedRegion]
|
|
139
189
|
else (next as Record<string, unknown>)[key] = value
|
|
140
190
|
}
|
|
191
|
+
// The account object arrives from the CLI carrying a bearer token of its
|
|
192
|
+
// own; keep exactly one credential per region on disk.
|
|
193
|
+
if (next.account !== undefined) next.account = withoutCredential(next.account)
|
|
141
194
|
state.regions[region] = next
|
|
142
195
|
this.persist()
|
|
143
196
|
}
|
package/src/codebuddy.ts
CHANGED
|
@@ -21,13 +21,13 @@ import type {
|
|
|
21
21
|
CanUseTool, Message, RawLanguageModel, UserMessage,
|
|
22
22
|
} from '@tencent-ai/agent-sdk'
|
|
23
23
|
import type { CodeBuddyRegion } from './brand.ts'
|
|
24
|
-
import { CodeBuddyStateStore, codeBuddyCliDir } from './codebuddy-state.ts'
|
|
24
|
+
import { CodeBuddyStateStore, codeBuddyCliDir, withoutCredential } from './codebuddy-state.ts'
|
|
25
25
|
import type { CodeBuddySavedUser } from './codebuddy-state.ts'
|
|
26
26
|
import { jsonSchemaToShape } from './jsonschema.ts'
|
|
27
27
|
import type { Live } from './live.ts'
|
|
28
28
|
import { readLive } from './live.ts'
|
|
29
|
+
import { stripMcpNamespace } from './mcp-naming.ts'
|
|
29
30
|
import { codeBuddyEnvironment, loadCodeBuddySdk } from './sdk.ts'
|
|
30
|
-
import type { ChannelContent, ToolResultPayload } from './session.ts'
|
|
31
31
|
|
|
32
32
|
/**
|
|
33
33
|
* Literal characters in a channel payload; images contribute pixels, not text.
|
|
@@ -58,7 +58,8 @@ function toCodeBuddyUserMessage(
|
|
|
58
58
|
parent_tool_use_id: null,
|
|
59
59
|
}
|
|
60
60
|
}
|
|
61
|
-
import { MCP_SERVER_NAME, ToolResultPairing, TurnQueue } from './session.ts'
|
|
61
|
+
import { MCP_SERVER_NAME, HostToolRegistry, ToolResultPairing, TurnQueue } from './session.ts'
|
|
62
|
+
import type { ChannelContent, ToolResultPayload, ToolRegistryHost } from './session.ts'
|
|
62
63
|
import { TurnOutputAccounting, estimateTextTokens } from './tokens.ts'
|
|
63
64
|
|
|
64
65
|
/** Default context capacity assumed for a CodeBuddy model that declares none. */
|
|
@@ -88,17 +89,26 @@ const MCP_TOOL_PREFIX = `mcp__${MCP_SERVER_NAME}__`
|
|
|
88
89
|
* `Bash`. The Qoder CLI keeps the hyphen, so both spellings are accepted.
|
|
89
90
|
*/
|
|
90
91
|
const MCP_TOOL_PREFIX_SANITIZED = `mcp__${MCP_SERVER_NAME.replace(/[^a-zA-Z0-9]/g, '_')}__`
|
|
92
|
+
/** Both spellings, in the order the shared stripper tries them. */
|
|
93
|
+
const HOST_TOOL_PREFIXES = [MCP_TOOL_PREFIX, MCP_TOOL_PREFIX_SANITIZED]
|
|
91
94
|
|
|
92
95
|
/** Whether a CLI tool name belongs to this plugin's MCP server. */
|
|
93
|
-
function isHostTool(toolName: string): boolean {
|
|
94
|
-
return toolName
|
|
96
|
+
export function isHostTool(toolName: string): boolean {
|
|
97
|
+
return stripMcpNamespace(toolName, HOST_TOOL_PREFIXES) !== null
|
|
95
98
|
}
|
|
96
99
|
|
|
97
|
-
/**
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
100
|
+
/**
|
|
101
|
+
* The host-side tool name, with every MCP namespace layer removed.
|
|
102
|
+
*
|
|
103
|
+
* CodeBuddy qualifies an already-qualified name again, so the handler can be
|
|
104
|
+
* handed `mcp__dsh_host__mcp__dsh_host__edit`. Stripping one layer produced
|
|
105
|
+
* `mcp__dsh_host__edit`, a name the host does not have (its tool is `edit`), and
|
|
106
|
+
* DSH answered `unknown tool "mcp__dsh_host__edit"`; the model retried the
|
|
107
|
+
* doubled spelling next round and the CLI rejected it with `does not exist in
|
|
108
|
+
* the current tool set`. See {@link stripMcpNamespace}.
|
|
109
|
+
*/
|
|
110
|
+
export function hostToolName(toolName: string): string {
|
|
111
|
+
return stripMcpNamespace(toolName, HOST_TOOL_PREFIXES) ?? toolName
|
|
102
112
|
}
|
|
103
113
|
|
|
104
114
|
/** One model as the settings page and the adapter see it. */
|
|
@@ -218,12 +228,26 @@ function tokenFor(region: CodeBuddyRegion): string | undefined {
|
|
|
218
228
|
* pins the environment, so a fresh process always reads the right catalog.
|
|
219
229
|
*/
|
|
220
230
|
function cliEnv(region: CodeBuddyRegion): { env: Record<string, string> } {
|
|
221
|
-
const env
|
|
231
|
+
const env = cliDirEnv(region)
|
|
222
232
|
const token = tokenFor(region)
|
|
223
233
|
if (token !== undefined) env.CODEBUDDY_AUTH_TOKEN = token
|
|
224
234
|
return { env }
|
|
225
235
|
}
|
|
226
236
|
|
|
237
|
+
/**
|
|
238
|
+
* The region's own CLI directory, with no credential attached.
|
|
239
|
+
*
|
|
240
|
+
* The login, logout and silent-token calls need this and nothing else: they
|
|
241
|
+
* must not carry a bearer token (login starts fresh, logout clears), but they
|
|
242
|
+
* absolutely must be scoped to one region. Without it they acted on the CLI's
|
|
243
|
+
* default `~/.codebuddy`, which both regions share — so signing in for one
|
|
244
|
+
* region overwrote the other's login, and `logout` for the region the page was
|
|
245
|
+
* showing left the credential of the other one standing.
|
|
246
|
+
*/
|
|
247
|
+
function cliDirEnv(region: CodeBuddyRegion): Record<string, string> {
|
|
248
|
+
return { CODEBUDDY_CONFIG_DIR: codeBuddyCliDir(region) }
|
|
249
|
+
}
|
|
250
|
+
|
|
227
251
|
/** Remember a bearer token in memory and on disk. */
|
|
228
252
|
function rememberBearerToken(region: CodeBuddyRegion, token: string, user?: CodeBuddySavedUser): void {
|
|
229
253
|
if (token.length === 0) return
|
|
@@ -448,12 +472,15 @@ export class CodeBuddyAccountReader {
|
|
|
448
472
|
|
|
449
473
|
private async fetch(region: CodeBuddyRegion): Promise<CodeBuddyUsageSnapshot> {
|
|
450
474
|
const at = Date.now()
|
|
451
|
-
//
|
|
452
|
-
//
|
|
453
|
-
//
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
475
|
+
// Ask the CLI even when this region holds no credential of ours.
|
|
476
|
+
//
|
|
477
|
+
// Refusing here used to be the guard against adopting the *other* region's
|
|
478
|
+
// login: the CLI's default directory is shared, so a probe could answer with
|
|
479
|
+
// whichever account logged in last. Every call now runs inside this region's
|
|
480
|
+
// own directory, so the answer can only be this region's — and the refusal
|
|
481
|
+
// had become pure damage: any accident that dropped the local copy of a
|
|
482
|
+
// working token left the card saying "not signed in" for an account the CLI
|
|
483
|
+
// still had, with no path back short of a fresh browser login.
|
|
457
484
|
try {
|
|
458
485
|
const account = await readAccount(region, readLive(this.timeoutMs, CODEBUDDY_FETCH_TIMEOUT_MS))
|
|
459
486
|
// An unauthenticated CLI answers with an empty object or an anonymous
|
|
@@ -470,7 +497,7 @@ export class CodeBuddyAccountReader {
|
|
|
470
497
|
return { at, account, quota }
|
|
471
498
|
} catch (quotaError) {
|
|
472
499
|
const message = quotaError instanceof Error ? quotaError.message : String(quotaError)
|
|
473
|
-
if (
|
|
500
|
+
if (isCredentialRejected(quotaError)) forgetToken(region)
|
|
474
501
|
else codeBuddyState.patch(region, { quota: undefined, quotaError: message })
|
|
475
502
|
return { at, account, quotaError: message }
|
|
476
503
|
}
|
|
@@ -500,7 +527,9 @@ async function readAccount(region: CodeBuddyRegion, timeoutMs: number): Promise<
|
|
|
500
527
|
})
|
|
501
528
|
try {
|
|
502
529
|
await withTimeout(q.connect(), timeoutMs)
|
|
503
|
-
|
|
530
|
+
// The CLI's answer carries a bearer token beside the identity; it goes on
|
|
531
|
+
// to the settings page through `/usage`, so the credential comes off here.
|
|
532
|
+
return withoutCredential(await withTimeout(q.accountInfo(), timeoutMs)) ?? {}
|
|
504
533
|
} finally {
|
|
505
534
|
await q.return().catch(() => undefined)
|
|
506
535
|
}
|
|
@@ -609,9 +638,14 @@ function formatLocalTime(date: Date): string {
|
|
|
609
638
|
/**
|
|
610
639
|
* A bearer token for the region, from a recent login or a silent SDK read.
|
|
611
640
|
*
|
|
612
|
-
*
|
|
613
|
-
*
|
|
614
|
-
*
|
|
641
|
+
* The silent read is the documented behaviour of `authenticate` — return the
|
|
642
|
+
* CLI's existing token instead of opening a browser when the region is signed
|
|
643
|
+
* in — but it did not work as measured: on a machine with a live CodeBuddy
|
|
644
|
+
* login it timed out for both regions, each in the shared default directory and
|
|
645
|
+
* in both per-region directories. So treat it as best effort, and never as a
|
|
646
|
+
* place to recover from: the copy this plugin saved is the only credential a
|
|
647
|
+
* session can count on, which is why dropping it used to read as "not signed
|
|
648
|
+
* in" even while the account still worked.
|
|
615
649
|
*/
|
|
616
650
|
async function readBearerToken(region: CodeBuddyRegion): Promise<string> {
|
|
617
651
|
const cached = tokenFor(region)
|
|
@@ -619,6 +653,10 @@ async function readBearerToken(region: CodeBuddyRegion): Promise<string> {
|
|
|
619
653
|
const sdk = await loadCodeBuddySdk()
|
|
620
654
|
const result = await withTimeout(sdk.unstable_v2_authenticate({
|
|
621
655
|
environment: codeBuddyEnvironment(region),
|
|
656
|
+
// Scoped to this region's directory. Left out, the CLI answered from its
|
|
657
|
+
// shared default directory — whichever region had signed in last — and
|
|
658
|
+
// `rememberBearerToken` below then recorded *that* account as this region's.
|
|
659
|
+
env: cliDirEnv(region),
|
|
622
660
|
timeout: 3000,
|
|
623
661
|
onAuthUrl: () => {
|
|
624
662
|
// A quota read must never pop a browser; the page owns login.
|
|
@@ -682,7 +720,7 @@ export async function fetchCodeBuddyQuota(
|
|
|
682
720
|
const text = await response.text()
|
|
683
721
|
if (!response.ok) {
|
|
684
722
|
if (response.status === 401 || response.status === 403) {
|
|
685
|
-
throw new
|
|
723
|
+
throw new CredentialRejectedError('CodeBuddy 登录已过期,请重新登录')
|
|
686
724
|
}
|
|
687
725
|
const detail = text.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 160)
|
|
688
726
|
throw new Error(`CodeBuddy 额度接口返回 HTTP ${response.status}${detail === '' ? '' : `:${detail}`}`)
|
|
@@ -696,9 +734,33 @@ export async function fetchCodeBuddyQuota(
|
|
|
696
734
|
return parseCodeBuddyQuota(payload)
|
|
697
735
|
}
|
|
698
736
|
|
|
699
|
-
/**
|
|
700
|
-
|
|
701
|
-
|
|
737
|
+
/**
|
|
738
|
+
* The credential this region holds was rejected by the endpoint.
|
|
739
|
+
*
|
|
740
|
+
* Thrown where the rejection is *known* — an explicit HTTP 401/403 — rather
|
|
741
|
+
* than inferred from the error text. Inferring it was the bug: the loose
|
|
742
|
+
* matcher below used to treat any failure whose message happened to contain
|
|
743
|
+
* "token", "401" inside a number, or an HTML body mentioning a token, as an
|
|
744
|
+
* expired login. It then dropped a working credential, and because a missing
|
|
745
|
+
* local token reads as "signed out", the page showed an account as not signed
|
|
746
|
+
* in while the CLI still had a usable login.
|
|
747
|
+
*/
|
|
748
|
+
class CredentialRejectedError extends Error {}
|
|
749
|
+
|
|
750
|
+
/**
|
|
751
|
+
* Whether a quota failure genuinely means the credential no longer works.
|
|
752
|
+
*
|
|
753
|
+
* The typed error carries the CLI's own expiry sentence, which is also matched
|
|
754
|
+
* here because the message is ours, fixed, and not derived from server text.
|
|
755
|
+
* Everything else — a 5xx, a bad payload, a timeout, an unreachable endpoint —
|
|
756
|
+
* leaves the credential alone.
|
|
757
|
+
*
|
|
758
|
+
* @param error - whatever quota reading threw.
|
|
759
|
+
*/
|
|
760
|
+
function isCredentialRejected(error: unknown): boolean {
|
|
761
|
+
if (error instanceof CredentialRejectedError) return true
|
|
762
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
763
|
+
return message === 'CodeBuddy 登录已过期,请重新登录'
|
|
702
764
|
}
|
|
703
765
|
|
|
704
766
|
/** Read quota, retrying once with a fresh token after an auth failure. */
|
|
@@ -709,8 +771,7 @@ async function readQuotaWithToken(region: CodeBuddyRegion): Promise<CodeBuddyQuo
|
|
|
709
771
|
try {
|
|
710
772
|
return await fetchCodeBuddyQuota(region, token)
|
|
711
773
|
} catch (error) {
|
|
712
|
-
|
|
713
|
-
if (!isExpiredToken(detail)) throw error
|
|
774
|
+
if (!isCredentialRejected(error)) throw error
|
|
714
775
|
forgetToken(region)
|
|
715
776
|
const renewed = await readBearerToken(region).catch((renewError: unknown) => {
|
|
716
777
|
throw new Error(authErrorText(region, renewError))
|
|
@@ -768,7 +829,7 @@ export class CodeBuddyAuth {
|
|
|
768
829
|
try {
|
|
769
830
|
const sdk = await loadCodeBuddySdk()
|
|
770
831
|
await withTimeout(
|
|
771
|
-
sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region) }),
|
|
832
|
+
sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region), env: cliDirEnv(region) }),
|
|
772
833
|
CODEBUDDY_FETCH_TIMEOUT_MS,
|
|
773
834
|
)
|
|
774
835
|
} catch (error) {
|
|
@@ -796,14 +857,18 @@ export class CodeBuddyAuth {
|
|
|
796
857
|
// it returns that token without ever calling `onAuthUrl`, so the click
|
|
797
858
|
// looks dead and an expired credential survives forever. A login click
|
|
798
859
|
// always means "open the browser", so drop the stored credential first.
|
|
860
|
+
// Both calls are scoped to this region's directory: the CLI's default
|
|
861
|
+
// directory is shared, so an unscoped logout here signed the *other*
|
|
862
|
+
// region out as a side effect of logging this one in.
|
|
799
863
|
await withTimeout(
|
|
800
|
-
sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region) }),
|
|
864
|
+
sdk.unstable_v2_logout({ environment: codeBuddyEnvironment(region), env: cliDirEnv(region) }),
|
|
801
865
|
LOGOUT_TIMEOUT_MS,
|
|
802
866
|
).catch(() => undefined)
|
|
803
867
|
if (!this.current(run)) return
|
|
804
868
|
bearerTokens.delete(region)
|
|
805
869
|
const result = await sdk.unstable_v2_authenticate({
|
|
806
870
|
environment: codeBuddyEnvironment(region),
|
|
871
|
+
env: cliDirEnv(region),
|
|
807
872
|
timeout: LOGIN_TIMEOUT_MS,
|
|
808
873
|
onAuthUrl: (state) => {
|
|
809
874
|
// The bundled CLI opens the browser itself as part of the login
|
|
@@ -890,8 +955,18 @@ export class CodeBuddySession {
|
|
|
890
955
|
private session: SessionImpl | null = null
|
|
891
956
|
private mcp: ReturnType<typeof import('@tencent-ai/agent-sdk').createSdkMcpServer> | null = null
|
|
892
957
|
private readonly pairing = new ToolResultPairing()
|
|
893
|
-
private readonly registered = new Map<string, string>()
|
|
894
958
|
private toolSchemas: readonly { name: string, description: string, parameters?: unknown }[] = []
|
|
959
|
+
/**
|
|
960
|
+
* Reconciles the live host tool list into {@link mcp}.
|
|
961
|
+
*
|
|
962
|
+
* Created with the MCP server, because that is what it installs into. Owned
|
|
963
|
+
* here rather than inline so a tool that the host adds or withdraws during a
|
|
964
|
+
* conversation is actually added or withdrawn: the MCP SDK refuses a second
|
|
965
|
+
* `registerTool` for a name it already holds, so the previous
|
|
966
|
+
* name→hash replay could never replace a changed schema, and `Tool "…" does
|
|
967
|
+
* not exist in the current tool set.` was what the model got for its trouble.
|
|
968
|
+
*/
|
|
969
|
+
private registry: HostToolRegistry | null = null
|
|
895
970
|
private queue: TurnQueue | null = null
|
|
896
971
|
private disposed = false
|
|
897
972
|
private abortPending = false
|
|
@@ -976,12 +1051,14 @@ export class CodeBuddySession {
|
|
|
976
1051
|
* compacts (and the gateway rejects) anything past 276K — while the host,
|
|
977
1052
|
* told 1M, keeps showing and feeding a larger history. Replaying that history
|
|
978
1053
|
* then collapses to a summary. Applying the same number the host divides by
|
|
979
|
-
* keeps the two in step;
|
|
980
|
-
*
|
|
1054
|
+
* keeps the two in step; the adapter therefore sends a window for every model
|
|
1055
|
+
* it knows about, not only the ones that advertise a choice — the mainland
|
|
1056
|
+
* catalog declares no lengths anywhere and its physical `maxInputTokens` is a
|
|
1057
|
+
* provider number the CLI is free to ignore when left to itself.
|
|
981
1058
|
*
|
|
982
|
-
*
|
|
983
|
-
*
|
|
984
|
-
*
|
|
1059
|
+
* A rejected value keeps the CLI on its own default, which is the one case
|
|
1060
|
+
* where the two denominators can still disagree; it is reported nowhere, so
|
|
1061
|
+
* the host's figure stays the visible contract.
|
|
985
1062
|
*/
|
|
986
1063
|
private async applyContextWindow(session: SessionImpl): Promise<void> {
|
|
987
1064
|
const window = this.contextWindow
|
|
@@ -992,7 +1069,8 @@ export class CodeBuddySession {
|
|
|
992
1069
|
try {
|
|
993
1070
|
await session.setConfig({ contextWindow: window })
|
|
994
1071
|
} catch {
|
|
995
|
-
//
|
|
1072
|
+
// Nothing selectable here, or the value was refused: the model's own
|
|
1073
|
+
// default stands rather than failing the turn over a budget hint.
|
|
996
1074
|
}
|
|
997
1075
|
}
|
|
998
1076
|
|
|
@@ -1011,28 +1089,18 @@ export class CodeBuddySession {
|
|
|
1011
1089
|
this.registerTools()
|
|
1012
1090
|
}
|
|
1013
1091
|
|
|
1092
|
+
/**
|
|
1093
|
+
* Reconcile this session's MCP tool set with the host's live list.
|
|
1094
|
+
*
|
|
1095
|
+
* Add, update in place, and remove: the host withdraws tools when a mode
|
|
1096
|
+
* changes and adds them when `ops_discover_tools` resolves a deferred one, and
|
|
1097
|
+
* a tool the model can still name but the server no longer holds is answered
|
|
1098
|
+
* with `Tool "…" does not exist in the current tool set.` — the CLI never
|
|
1099
|
+
* forwards it to the host, so no tool result ever comes back.
|
|
1100
|
+
*/
|
|
1014
1101
|
private registerTools(): void {
|
|
1015
|
-
if (this.
|
|
1016
|
-
|
|
1017
|
-
const hash = JSON.stringify(schema.parameters ?? {})
|
|
1018
|
-
if (this.registered.get(schema.name) === hash) continue
|
|
1019
|
-
const shape = jsonSchemaToShape((schema.parameters ?? {}) as Record<string, unknown>)
|
|
1020
|
-
try {
|
|
1021
|
-
this.mcp.instance.registerTool(schema.name, {
|
|
1022
|
-
description: schema.description.length > 0 ? schema.description : schema.name,
|
|
1023
|
-
inputSchema: shape,
|
|
1024
|
-
}, async () => {
|
|
1025
|
-
const result = await this.pairing.claim(this.toolResultTimeoutMs)
|
|
1026
|
-
return {
|
|
1027
|
-
content: result.content,
|
|
1028
|
-
...result.isError ? { isError: true } : {},
|
|
1029
|
-
}
|
|
1030
|
-
})
|
|
1031
|
-
} catch {
|
|
1032
|
-
continue
|
|
1033
|
-
}
|
|
1034
|
-
this.registered.set(schema.name, hash)
|
|
1035
|
-
}
|
|
1102
|
+
if (this.registry === null) return
|
|
1103
|
+
this.registry.reconcile(this.toolSchemas)
|
|
1036
1104
|
}
|
|
1037
1105
|
|
|
1038
1106
|
/** Hand the host's tool results to parked or buffered handlers. */
|
|
@@ -1115,7 +1183,28 @@ export class CodeBuddySession {
|
|
|
1115
1183
|
if (this.session !== null) return this.session
|
|
1116
1184
|
const sdk = await loadCodeBuddySdk()
|
|
1117
1185
|
this.mcp ??= sdk.createSdkMcpServer({ name: MCP_SERVER_NAME, tools: [] })
|
|
1118
|
-
// Host tools must exist in the MCP server before the CLI lists them.
|
|
1186
|
+
// Host tools must exist in the MCP server before the CLI lists them. The
|
|
1187
|
+
// registry is created here, with the server it installs into, and the
|
|
1188
|
+
// replay below is what puts the first turn's schemas in place.
|
|
1189
|
+
this.registry ??= new HostToolRegistry(
|
|
1190
|
+
this.mcp.instance as unknown as ToolRegistryHost,
|
|
1191
|
+
() => async () => {
|
|
1192
|
+
const result = await this.pairing.claim(this.toolResultTimeoutMs)
|
|
1193
|
+
return {
|
|
1194
|
+
content: result.content,
|
|
1195
|
+
...result.isError ? { isError: true } : {},
|
|
1196
|
+
}
|
|
1197
|
+
},
|
|
1198
|
+
// A tool the SDK refused is invisible to the model, which then calls it and
|
|
1199
|
+
// gets the CLI's `does not exist in the current tool set` instead of a host
|
|
1200
|
+
// result. Surface it instead of dropping it.
|
|
1201
|
+
message => console.warn(`[dsh-agent-sdk-bridge] ${message}`),
|
|
1202
|
+
)
|
|
1203
|
+
// Declare the tools capability before createSession connects this server. A
|
|
1204
|
+
// first turn that published no host tools would otherwise connect with no
|
|
1205
|
+
// tools capability at all, and the MCP SDK then rejects every later
|
|
1206
|
+
// registration — the tool silently never reaches `tools/list`.
|
|
1207
|
+
this.registry.prepare()
|
|
1119
1208
|
this.registerTools()
|
|
1120
1209
|
const session = sdk.unstable_v2_createSession({
|
|
1121
1210
|
environment: codeBuddyEnvironment(this.region),
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* MCP tool-name namespacing, shared by every CLI backend this bridge drives.
|
|
3
|
+
*
|
|
4
|
+
* Each backend reaches the host's tools over an in-process MCP server, so the
|
|
5
|
+
* name a model emits is namespaced (`mcp__dsh-host__ops_bash`) while the host
|
|
6
|
+
* dispatches on the bare name (`ops_bash`). Two things make that translation
|
|
7
|
+
* less trivial than it looks, and both are the same bug in different clothes:
|
|
8
|
+
*
|
|
9
|
+
* - **Spelling.** CodeBuddy rewrites a server name's non-alphanumeric characters
|
|
10
|
+
* to `_`, so `dsh-host` is exposed as `mcp__dsh_host__…`; the Qoder CLI keeps
|
|
11
|
+
* the hyphen. A handler must accept both.
|
|
12
|
+
* - **Depth.** A model occasionally emits an already-qualified name, and the CLI
|
|
13
|
+
* then qualifies it again. Peeling exactly one layer handed the host
|
|
14
|
+
* `mcp__dsh_host__edit` — a name it does not have — so DSH answered
|
|
15
|
+
* `unknown tool "mcp__dsh_host__edit"`; the model then retried the doubled
|
|
16
|
+
* spelling and the CLI refused it with its own
|
|
17
|
+
* `does not exist in the current tool set.` Two error messages, one cause:
|
|
18
|
+
* a prefix peeled once instead of exhaustively.
|
|
19
|
+
*
|
|
20
|
+
* This module exists so all three backends peel the same way, rather than each
|
|
21
|
+
* carrying its own one-layer `slice`.
|
|
22
|
+
*
|
|
23
|
+
* @module dsh-agent-sdk-bridge/mcp-naming
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** How many prefix layers a single name may carry before the walk gives up. */
|
|
27
|
+
const MAX_NAMESPACE_LAYERS = 8
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Peel every matching namespace layer off a tool name.
|
|
31
|
+
*
|
|
32
|
+
* @param name - the tool name as the CLI's `tool_use` block carried it.
|
|
33
|
+
* @param prefixes - the namespaced spellings that belong to one server, in
|
|
34
|
+
* either spelling the backends produce. Longest first is not required; the
|
|
35
|
+
* walk re-checks the whole list after each peel.
|
|
36
|
+
* @returns the bare host tool name, or null when no prefix matched at all (or
|
|
37
|
+
* the name was nothing but namespaces).
|
|
38
|
+
*/
|
|
39
|
+
export function stripMcpNamespace(name: string, prefixes: readonly string[]): string | null {
|
|
40
|
+
const usable = prefixes.filter(prefix => prefix.length > 0)
|
|
41
|
+
let current = name
|
|
42
|
+
let stripped = false
|
|
43
|
+
// Bounded, so a name made only of prefixes cannot spin here.
|
|
44
|
+
for (let layer = 0; layer < MAX_NAMESPACE_LAYERS; layer++) {
|
|
45
|
+
const found = usable.find(prefix => current.startsWith(prefix))
|
|
46
|
+
if (found === undefined) return stripped && current.length > 0 ? current : null
|
|
47
|
+
current = current.slice(found.length)
|
|
48
|
+
stripped = true
|
|
49
|
+
}
|
|
50
|
+
// Still a namespace after the cap: there is no tool name in here, and
|
|
51
|
+
// returning the remainder would hand the host a prefix as if it were a tool.
|
|
52
|
+
return usable.some(prefix => current.startsWith(prefix)) || current.length === 0
|
|
53
|
+
? null
|
|
54
|
+
: stripped ? current : null
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The two spellings one MCP server name is exposed under by the backends.
|
|
59
|
+
*
|
|
60
|
+
* @param serverName - the name the server was registered with, e.g. `dsh-host`.
|
|
61
|
+
* @returns the registered spelling followed by the CLI-sanitised one; the two
|
|
62
|
+
* collapse to a single entry when the name is already alphanumeric.
|
|
63
|
+
*/
|
|
64
|
+
export function mcpToolPrefixes(serverName: string): string[] {
|
|
65
|
+
const registered = `mcp__${serverName}__`
|
|
66
|
+
const sanitized = `mcp__${serverName.replace(/[^a-zA-Z0-9]/g, '_')}__`
|
|
67
|
+
return sanitized === registered ? [registered] : [registered, sanitized]
|
|
68
|
+
}
|
package/src/minimax-adapter.ts
CHANGED
|
@@ -30,7 +30,7 @@ import type { ImageRequestReader } from './adapter.ts'
|
|
|
30
30
|
import type { Live } from './live.ts'
|
|
31
31
|
import { readLive, readLiveOptional } from './live.ts'
|
|
32
32
|
import type { Feed, ImagePathResolver } from './render.ts'
|
|
33
|
-
import { feedImageRefs, feedToText, imageRefText, renderInitialFeed, resolvedFeedParts } from './render.ts'
|
|
33
|
+
import { feedImageRefs, feedToText, imageRefText, renderInitialFeed, renderSideChannelFeed, resolvedFeedParts } from './render.ts'
|
|
34
34
|
|
|
35
35
|
/** The MiniMax Code provider route. */
|
|
36
36
|
export const MINIMAX_PROVIDER = 'minimax-acp'
|
|
@@ -310,8 +310,10 @@ export class MinimaxAdapter extends LlmAdapter {
|
|
|
310
310
|
}
|
|
311
311
|
const model = resolveMinimaxModelId(options.model, this.aliases)
|
|
312
312
|
if (options.sessionId === undefined || options.purpose !== undefined) {
|
|
313
|
-
|
|
314
|
-
|
|
313
|
+
// A side-channel request (compaction, a session title) carries its
|
|
314
|
+
// instruction as the last user message, so it is rendered as the task to
|
|
315
|
+
// carry out rather than as a turn to continue. See renderSideChannelFeed.
|
|
316
|
+
const prompt = feedToText(renderSideChannelFeed(options.system, options.messages, this.options.imagePath), this.options.imagePath)
|
|
315
317
|
for (const chunk of await minimaxColdStream(region, prompt, model, options)) yield chunk
|
|
316
318
|
return
|
|
317
319
|
}
|