@gatemux/dsh-gatemux-login-core 1.0.0 → 1.1.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.
Files changed (4) hide show
  1. package/account.js +85 -17
  2. package/llm.js +4 -0
  3. package/package.json +11 -5
  4. package/search.js +226 -0
package/account.js CHANGED
@@ -25,11 +25,10 @@ import { promises as streamPromises } from 'node:stream'
25
25
 
26
26
  import { Service } from '@deepseek-ai/cordis'
27
27
  import { credentialKey } from '@deepseek-ai/dsh-credentials'
28
- import {
29
- DeepSeekAccount,
30
- installAccountTaskCancellation,
31
- } from '@deepseek-ai/dsh-deepseek-account'
28
+ import { DeepSeekAccount } from '@deepseek-ai/dsh-deepseek-account'
29
+ import { LlmError } from '@deepseek-ai/dsh-llm'
32
30
  import { launchEnvironmentOf } from '@deepseek-ai/dsh-launch-environment'
31
+ import Schema from '@deepseek-ai/schemastery'
33
32
 
34
33
  /**
35
34
  * Deployment defaults. Every one of these is overridable through the row's
@@ -64,6 +63,22 @@ const REFRESH_MARGIN_MS = 60_000
64
63
  const ATTEMPT_TIMEOUT_MS = 600_000
65
64
  const REQUEST_TIMEOUT_MS = 30_000
66
65
  const DEFAULT_SCOPES = ['models:read', 'responses:create', 'media:create', 'account:read', 'openid', 'email']
66
+ /** Route this provider authenticates; the same id the model row registers. */
67
+ const PROVIDER = 'gatemux-account'
68
+
69
+ /**
70
+ * Row configuration surface, validated at activation rather than on first use.
71
+ *
72
+ * `clientId` stays optional because a launch environment may supply it; the
73
+ * constructor still rejects an empty value with the message that names both
74
+ * sources.
75
+ */
76
+ export const Config = Schema.object({
77
+ clientId: Schema.string().min(1),
78
+ authorizeOrigin: Schema.string().default(DEFAULT_ISSUER),
79
+ consoleOrigin: Schema.string().default(DEFAULT_CONSOLE_ORIGIN),
80
+ scopes: Schema.array(Schema.string()).default(DEFAULT_SCOPES),
81
+ })
67
82
 
68
83
  /** Local attempt failure taxonomy; the abstract contract renders these through locale copy. */
69
84
  class GateMuxAuthError extends Error {
@@ -134,9 +149,37 @@ function apiErrorCode(body) {
134
149
  return typeof error.code === 'string' ? error.code : undefined
135
150
  }
136
151
 
152
+ /**
153
+ * Cancel running work on this route when the account signs out.
154
+ *
155
+ * The shared `installAccountTaskCancellation` helper is keyed to the shipped
156
+ * `deepseek-account` route, so reusing it here would leave a `gatemux-account`
157
+ * stream running with a credential the person just removed. The sign-in
158
+ * guidance half is provider-agnostic and kept verbatim.
159
+ *
160
+ * @param ctx - the account provider's lifetime.
161
+ */
162
+ function installGateMuxTaskCancellation(ctx) {
163
+ ctx.inject(['agents'], (scope) => {
164
+ scope.on('agent/error', ({ error }) => {
165
+ if (error instanceof LlmError && error.code === 'ACCOUNT_SIGN_IN_REQUIRED') {
166
+ scope.emit('deepseek-account/model-sign-in-required')
167
+ }
168
+ })
169
+ scope.on('deepseek-account/signed-out', () => {
170
+ for (const agent of scope.agents.list()) {
171
+ if (agent.status === 'running' && agent.session.requestContext()?.provider === PROVIDER) {
172
+ agent.cancel({ kind: 'hook', reason: 'deepseek-account/signed-out' }, { keepInbox: true })
173
+ }
174
+ }
175
+ })
176
+ })
177
+ }
178
+
137
179
  /** GateMux login state, stored grant, and refresh rotation. */
138
180
  export class GateMuxAccount extends DeepSeekAccount {
139
181
  static inject = ['credentials', 'authorization']
182
+ static Config = Config
140
183
 
141
184
  clientId
142
185
  issuer
@@ -162,7 +205,7 @@ export class GateMuxAccount extends DeepSeekAccount {
162
205
  */
163
206
  constructor(ctx, config = {}) {
164
207
  super(ctx)
165
- installAccountTaskCancellation(ctx)
208
+ installGateMuxTaskCancellation(ctx)
166
209
  const clientId = config.clientId ?? launchEnvironmentOf(ctx).get(CLIENT_ID_ENV)?.value
167
210
  if (typeof clientId !== 'string' || clientId.length === 0) {
168
211
  throw new GateMuxAuthError(
@@ -265,7 +308,7 @@ export class GateMuxAccount extends DeepSeekAccount {
265
308
  if (grant === null || lifetime.signal.aborted) return null
266
309
  const body = await this.callApi(this.accountEndpoint, grant, lifetime, client)
267
310
  if (this.detailsLifetime !== lifetime) return null
268
- if (body === null) return { status: 'failed' }
311
+ if (body === null || typeof body !== 'object') return { status: 'failed' }
269
312
  const wallet = body.wallet
270
313
  if (typeof wallet !== 'object' || wallet === null) return { status: 'failed' }
271
314
  const { currency, balance } = wallet
@@ -313,9 +356,7 @@ export class GateMuxAccount extends DeepSeekAccount {
313
356
  interaction: { notify: () => undefined, prompt: () => Promise.reject(new GateMuxAuthError('no prompt', 'protocol')) },
314
357
  }).then((outcome) => {
315
358
  this.update(attempt, { phase: outcome.status === 'authorized' ? 'succeeded' : 'cancelled' })
316
- if (outcome.status === 'authorized' && attempt.completionUrl !== undefined) {
317
- attempt.callback?.writeHead(302, { location: attempt.completionUrl, 'cache-control': 'no-store' }).end()
318
- } else if (outcome.status === 'authorized') {
359
+ if (outcome.status === 'authorized') {
319
360
  // GateMux serves no hosted completion page, so this tab is the only place
320
361
  // the result is visible; answering 204 would leave it blank.
321
362
  this.writeCallbackPage(attempt, 'Signed in', attempt.loginSource === 'web'
@@ -363,10 +404,15 @@ export class GateMuxAccount extends DeepSeekAccount {
363
404
  const record = await this.ctx.credentials.readRecord(KEY)
364
405
  if (record !== undefined) {
365
406
  const grant = record.kind === 'grant' ? parseGrant(record.payload, this.issuer) : null
366
- if (grant === null) throw new GateMuxAuthError('stored grant is unreadable', 'storage')
407
+ // A record this deployment cannot read still has to be removable:
408
+ // refusing here would strand a corrupt grant with no way to clear it
409
+ // from the settings page.
410
+ if (grant === null) {
411
+ this.logger.warn('stored grant discarded on sign-out', { reason: 'unreadable-or-foreign-issuer' })
412
+ }
367
413
  await this.ctx.credentials.deleteRecord(KEY)
368
414
  // Revoking the refresh token cascades to every access token it issued.
369
- this.revoke(grant.refreshToken)
415
+ if (grant !== null) this.revoke(grant.refreshToken)
370
416
  }
371
417
  this.attempt = undefined
372
418
  this.ctx.emit('deepseek-account/signed-out')
@@ -553,6 +599,9 @@ export class GateMuxAccount extends DeepSeekAccount {
553
599
  try {
554
600
  return await this.refreshInFlight
555
601
  } catch {
602
+ // The seam can only report "no token", so a transient refresh failure
603
+ // reads as sign-in-required at the model route; the grant is kept so the
604
+ // next request can retry.
556
605
  return null
557
606
  }
558
607
  }
@@ -574,10 +623,18 @@ export class GateMuxAccount extends DeepSeekAccount {
574
623
  }, lifetime.signal)
575
624
  if (!response.ok) {
576
625
  const code = tokenErrorCode(response.body)
577
- // An unknown or expired refresh token means the authorization is gone.
578
- this.logger.warn('refresh rejected', { errorCode: code ?? 'unknown' })
579
- await this.expireCredential(grant.accessToken, lifetime)
580
- throw new GateMuxAuthError('refresh token rejected', 'expired')
626
+ // Only a rejected grant means this authorization is gone. A 5xx, a 429,
627
+ // or a client-configuration error leaves the stored grant in place:
628
+ // discarding it would sign the person out for an outage they cannot fix
629
+ // by signing in again.
630
+ if (code === 'invalid_grant' || code === 'invalid_token') {
631
+ this.logger.warn('refresh token rejected', { errorCode: code })
632
+ await this.expireCredential(grant.accessToken, lifetime)
633
+ throw new GateMuxAuthError('refresh token rejected', 'expired')
634
+ }
635
+ this.logger.warn('refresh temporarily failed', { status: response.status, errorCode: code ?? 'unknown' })
636
+ throw new GateMuxAuthError(
637
+ `token endpoint rejected refresh (${response.status} ${code ?? 'unknown'})`, 'network')
581
638
  }
582
639
  const next = this.grantFrom(response.body)
583
640
  // Persist the rotated token before any other request can read the old one.
@@ -599,7 +656,13 @@ export class GateMuxAccount extends DeepSeekAccount {
599
656
  return { version: 1, accessToken, refreshToken, expiresAt: Date.now() + seconds * 1000, issuer: this.issuer }
600
657
  }
601
658
 
602
- /** Post one token-endpoint request and decode its RFC 6749 §5.2 envelope. */
659
+ /**
660
+ * Post one token-endpoint request and decode its RFC 6749 §5.2 envelope.
661
+ *
662
+ * GateMux accepts the parameters as a JSON object; a stock RFC 6749 token
663
+ * endpoint expects `application/x-www-form-urlencoded`, so this is a
664
+ * GateMux-specific contract rather than a generic one.
665
+ */
603
666
  async postToken(fields, signal) {
604
667
  const response = await fetch(this.tokenEndpoint, {
605
668
  method: 'POST',
@@ -689,7 +752,12 @@ export class GateMuxAccount extends DeepSeekAccount {
689
752
  await this.removing
690
753
  }
691
754
 
692
- /** Revoke a refresh token, cascading to its access tokens; failures are not fatal. */
755
+ /**
756
+ * Revoke a refresh token, cascading to its access tokens; failures are not fatal.
757
+ *
758
+ * RFC 7009 normally expects form encoding; GateMux accepts JSON, like its
759
+ * token endpoint.
760
+ */
693
761
  revoke(refreshToken) {
694
762
  if (this.closed) return
695
763
  void fetch(this.revokeEndpoint, {
package/llm.js CHANGED
@@ -35,6 +35,9 @@ const MESSAGES_PROTOCOL = 'anthropic-messages'
35
35
  /** Protocol version this transport sends on every request, the model listing included. */
36
36
  const ANTHROPIC_VERSION = '2023-06-01'
37
37
 
38
+ /** Deadline for one model-listing read; discovery must not hang the selector. */
39
+ const LISTING_TIMEOUT_MS = 30_000
40
+
38
41
  /**
39
42
  * Anthropic's listing path, read from a Messages base URL.
40
43
  *
@@ -164,6 +167,7 @@ export function apply(ctx, config) {
164
167
  const response = await fetch(url, {
165
168
  method: 'GET',
166
169
  headers: { ...headers, 'accept': 'application/json', 'anthropic-version': ANTHROPIC_VERSION },
170
+ signal: AbortSignal.timeout(LISTING_TIMEOUT_MS),
167
171
  })
168
172
  if (!response.ok) throw new Error(`${url} answered ${response.status}`)
169
173
  const body = await response.json()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gatemux/dsh-gatemux-login-core",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "description": "GateMux account provider and model route for DeepSeek Harness. Shared code; install a region bundle instead of this package.",
6
6
  "publishConfig": {
@@ -9,11 +9,13 @@
9
9
  "license": "MIT",
10
10
  "files": [
11
11
  "account.js",
12
- "llm.js"
12
+ "llm.js",
13
+ "search.js"
13
14
  ],
14
15
  "exports": {
15
16
  "./account": "./account.js",
16
17
  "./llm": "./llm.js",
18
+ "./search": "./search.js",
17
19
  "./package.json": "./package.json"
18
20
  },
19
21
  "meta": {
@@ -28,7 +30,9 @@
28
30
  "@deepseek-ai/dsh-host-webserver": "^0.1.7-rc.2 || ^0.2.0-rc.2",
29
31
  "@deepseek-ai/dsh-launch-environment": "^0.1.7-rc.2 || ^0.2.0-rc.2",
30
32
  "@deepseek-ai/dsh-llm": "^0.1.7-rc.2 || ^0.2.0-rc.2",
31
- "@deepseek-ai/dsh-llm-deepseek": "^0.1.7-rc.2 || ^0.2.0-rc.2"
33
+ "@deepseek-ai/dsh-llm-deepseek": "^0.1.7-rc.2 || ^0.2.0-rc.2",
34
+ "@deepseek-ai/dsh-web": "^0.1.7-rc.2 || ^0.2.0-rc.2",
35
+ "@deepseek-ai/schemastery": "^3.18.4"
32
36
  },
33
37
  "devDependencies": {
34
38
  "@deepseek-ai/cordis": "^4.0.4",
@@ -38,6 +42,8 @@
38
42
  "@deepseek-ai/dsh-host-webserver": "^0.1.7-rc.2 || ^0.2.0-rc.2",
39
43
  "@deepseek-ai/dsh-launch-environment": "^0.1.7-rc.2 || ^0.2.0-rc.2",
40
44
  "@deepseek-ai/dsh-llm": "^0.1.7-rc.2 || ^0.2.0-rc.2",
41
- "@deepseek-ai/dsh-llm-deepseek": "^0.1.7-rc.2 || ^0.2.0-rc.2"
45
+ "@deepseek-ai/dsh-llm-deepseek": "^0.1.7-rc.2 || ^0.2.0-rc.2",
46
+ "@deepseek-ai/dsh-web": "^0.1.7-rc.2 || ^0.2.0-rc.2",
47
+ "@deepseek-ai/schemastery": "^3.18.4"
42
48
  }
43
- }
49
+ }
package/search.js ADDED
@@ -0,0 +1,226 @@
1
+ /**
2
+ * GateMux native web search provider.
3
+ *
4
+ * GateMux exposes Anthropic's `web_search_20250305` server tool on
5
+ * `/v1/messages`, but only enables it for requests that carry GateMux's
6
+ * Claude Code client marker in `system`. Without the marker the model answers
7
+ * directly and returns no `web_search_tool_result`, so the marker is part of
8
+ * the protocol this provider speaks rather than an optional prompt.
9
+ *
10
+ * The search is one non-streaming Messages request authenticated with the
11
+ * signed-in GateMux account. It does not use the conversation's model route:
12
+ * the conversation model calls the host `web_search` tool, and this provider
13
+ * performs the retrieval. Both the conversation and the search bill to the
14
+ * same GateMux balance.
15
+ *
16
+ * @module @gatemux/dsh-gatemux-login-core/search
17
+ */
18
+
19
+ import Schema from '@deepseek-ai/schemastery'
20
+ import { WebError } from '@deepseek-ai/dsh-web'
21
+
22
+ /** Provider id selected by the `web` row in `cordis.patch.yml`. */
23
+ const PROVIDER = 'gatemux'
24
+
25
+ /** Route this search is billed to; only the account's own issuer serves it. */
26
+ const DEFAULT_BASE_URL = 'https://rest.gatemux.ai/v1'
27
+ const DEFAULT_MODEL = 'gatemux/deepseek-v4-flash'
28
+ const DEFAULT_MAX_TOKENS = 2048
29
+ const DEFAULT_MAX_USES = 8
30
+ const DEFAULT_TIMEOUT_MS = 60_000
31
+ const ANTHROPIC_VERSION = '2023-06-01'
32
+
33
+ /**
34
+ * GateMux enables its native search server tool only for requests carrying
35
+ * this client marker. It identifies the caller to the gateway; it is not a
36
+ * credential and is the only value the plugin shares with GateMux's example.
37
+ */
38
+ const SYSTEM_MARKER = 'x-anthropic-billing-header: cc_entrypoint=cli;'
39
+
40
+ /**
41
+ * Row configuration surface, validated at activation rather than first use.
42
+ * `baseURL` and `model` come from the region patch; the rest have defaults.
43
+ */
44
+ export const Config = Schema.object({
45
+ baseURL: Schema.string().default(DEFAULT_BASE_URL),
46
+ model: Schema.string().default(DEFAULT_MODEL),
47
+ maxTokens: Schema.natural().default(DEFAULT_MAX_TOKENS),
48
+ maxUses: Schema.natural().default(DEFAULT_MAX_USES),
49
+ timeoutMs: Schema.natural().default(DEFAULT_TIMEOUT_MS),
50
+ })
51
+
52
+ /** Stable provider name used by loader diagnostics. */
53
+ export const name = 'gatemux-search'
54
+
55
+ /** The web seam this provider registers into. */
56
+ export const inject = ['web']
57
+
58
+ /** One normalized result item, kept before the seam applies its own bounds. */
59
+ function sourceOf(item, seen) {
60
+ if (typeof item !== 'object' || item === null) return undefined
61
+ const url = typeof item.url === 'string' ? item.url : undefined
62
+ if (url === undefined || url.length === 0 || seen.has(url)) return undefined
63
+ seen.add(url)
64
+ return {
65
+ url,
66
+ ...typeof item.title === 'string' && item.title.length > 0 ? { title: item.title } : {},
67
+ ...typeof item.page_age === 'string' && item.page_age.length > 0 ? { publishedAt: item.page_age } : {},
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Map one Anthropic Messages response to the web seam's result shape.
73
+ * @param payload - the decoded response body.
74
+ * @returns the answer text and citeable sources, or undefined when the response carried neither.
75
+ */
76
+ function mapResponse(payload) {
77
+ const blocks = Array.isArray(payload?.content) ? payload.content : []
78
+ const seen = new Set()
79
+ const sources = []
80
+ let content = ''
81
+ for (const block of blocks) {
82
+ if (block?.type === 'web_search_tool_result') {
83
+ for (const item of Array.isArray(block.content) ? block.content : []) {
84
+ const source = sourceOf(item, seen)
85
+ if (source !== undefined) sources.push(source)
86
+ }
87
+ } else if (block?.type === 'text') {
88
+ if (typeof block.text === 'string') content += block.text
89
+ for (const citation of Array.isArray(block.citations) ? block.citations : []) {
90
+ if (typeof citation?.url !== 'string' || seen.has(citation.url)) continue
91
+ seen.add(citation.url)
92
+ sources.push({
93
+ url: citation.url,
94
+ ...typeof citation.cited_text === 'string' && citation.cited_text.length > 0 ? { snippet: citation.cited_text } : {},
95
+ })
96
+ }
97
+ }
98
+ }
99
+ if (content.length === 0 && sources.length === 0) return undefined
100
+ return {
101
+ ...content.length === 0 ? {} : { content },
102
+ sources,
103
+ truncated: false,
104
+ }
105
+ }
106
+
107
+ /** The GateMux-backed search provider. */
108
+ export class GateMuxSearchProvider {
109
+ /** Stable id selected by the `web` row. */
110
+ id = PROVIDER
111
+
112
+ /**
113
+ * @param ctx - Host with the optional GateMux account service.
114
+ * @param config - this row's resolved endpoint, model, and bounds.
115
+ */
116
+ constructor(ctx, config) {
117
+ this.ctx = ctx
118
+ this.config = config
119
+ this.endpoint = `${config.baseURL.replace(/\/+$/u, '')}/messages`
120
+ }
121
+
122
+ /** Cheap local usability check; the account service is present in this composition. */
123
+ available() {
124
+ return this.ctx.get('deepseekAccount') !== undefined
125
+ }
126
+
127
+ /**
128
+ * Run one native search through GateMux.
129
+ * @param request - the query the conversation model asked for.
130
+ * @param signal - the tool's cooperative timeout/cancellation signal.
131
+ * @returns the answer text and citeable sources.
132
+ */
133
+ async search(request, signal) {
134
+ if (signal?.aborted === true) throw new WebError('GateMux web search was cancelled', 'WEB_ABORTED')
135
+ const account = this.ctx.get('deepseekAccount')
136
+ const token = await account?.resolveToken(this.endpoint)
137
+ if (token === undefined || token.length === 0) {
138
+ throw new WebError(
139
+ 'Sign in with GateMux to use web search. The search is billed to your own GateMux balance.',
140
+ 'ACCOUNT_SIGN_IN_REQUIRED',
141
+ )
142
+ }
143
+
144
+ const body = {
145
+ model: this.config.model,
146
+ max_tokens: this.config.maxTokens,
147
+ // GateMux's native search is only enabled for requests carrying this
148
+ // client marker; it is a protocol detail, not user-visible prompt text.
149
+ system: [{ type: 'text', text: SYSTEM_MARKER }],
150
+ messages: [{ role: 'user', content: request.query }],
151
+ tools: [{ type: 'web_search_20250305', name: 'web_search', max_uses: this.config.maxUses }],
152
+ }
153
+ const timeout = AbortSignal.timeout(this.config.timeoutMs)
154
+ const fused = signal === undefined ? timeout : AbortSignal.any([signal, timeout])
155
+ let response
156
+ try {
157
+ response = await fetch(this.endpoint, {
158
+ method: 'POST',
159
+ redirect: 'error',
160
+ headers: {
161
+ // GateMux accepts the account's Bearer credential; the DeepSeek-only
162
+ // `x-dsh-auth-token` header is not used here.
163
+ authorization: `Bearer ${token}`,
164
+ 'anthropic-version': ANTHROPIC_VERSION,
165
+ 'content-type': 'application/json',
166
+ accept: 'application/json',
167
+ },
168
+ body: JSON.stringify(body),
169
+ signal: fused,
170
+ })
171
+ } catch (error) {
172
+ if (signal?.aborted === true) throw new WebError('GateMux web search was cancelled', 'WEB_ABORTED')
173
+ throw new WebError(`GateMux web search request failed: ${String(error)}`, 'WEB_PROVIDER_ERROR', { cause: error })
174
+ }
175
+
176
+ if (!response.ok) {
177
+ let detail
178
+ try {
179
+ const payload = await response.json()
180
+ const error = payload?.error
181
+ detail = typeof error === 'string' ? error : error?.message
182
+ } catch {
183
+ // The HTTP status is the contract; a non-JSON error body adds no detail.
184
+ }
185
+ if (response.status === 401) {
186
+ try {
187
+ await account?.rejectToken(token)
188
+ } catch {
189
+ // The inference failure is the answer; a storage failure cannot replace it.
190
+ }
191
+ throw new WebError('GateMux web search credential was rejected; sign in again.', 'ACCOUNT_TOKEN_INVALID')
192
+ }
193
+ throw new WebError(
194
+ `GateMux web search failed (HTTP ${response.status})${typeof detail === 'string' && detail.length > 0 ? `: ${detail}` : ''}`,
195
+ 'WEB_PROVIDER_ERROR',
196
+ )
197
+ }
198
+
199
+ let payload
200
+ try {
201
+ payload = await response.json()
202
+ } catch (error) {
203
+ if (signal?.aborted === true) throw new WebError('GateMux web search was cancelled', 'WEB_ABORTED')
204
+ throw new WebError('GateMux web search returned an unreadable response body', 'WEB_PROVIDER_ERROR', { cause: error })
205
+ }
206
+ const result = mapResponse(payload)
207
+ if (result === undefined) {
208
+ throw new WebError('GateMux web search returned no answer or sources', 'WEB_PROVIDER_ERROR')
209
+ }
210
+ return result
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Register the provider with the web seam.
216
+ * @param ctx - Host context with the `web` service injected.
217
+ * @param config - this row's resolved configuration.
218
+ */
219
+ export function apply(ctx, config) {
220
+ ctx.effect(
221
+ () => ctx.web.registerSearchProvider(new GateMuxSearchProvider(ctx, config)),
222
+ 'gatemux-search: register provider',
223
+ )
224
+ }
225
+
226
+ export default { name, inject, Config, apply }