Skip to content

Architecture

Christian Trey Rowell edited this page Dec 3, 2026 · 1 revision

Architecture

English | 简体中文

This page explains how the plugin is built: the two packages, what each module owns, how one model call flows through them, and how failures are handled. It is for readers who want to review the code or change it.

Two packages

This section introduces the split between the DSH integration shell and the portable engine.

The repository is an npm workspace with two packages:

  • dsh-chatgpt-siwc (the repository root, published to npm) is the DSH integration shell. It owns the Cordis plugin entry, the provider adapter, the request mapper from DSH messages, OAuth and the accounts file, the settings card, the discovery tool, and the CLI.
  • siwc-core (packages/siwc-core, private, never published on its own) is the engine. It owns the request model, the Responses request builder, the stream translator, catalog merging and filtering, the account session, the error vocabulary in both languages, and shared types.

siwc-core ships inside the npm tarball under node_modules/siwc-core through bundleDependencies. It has no imports from DSH packages, React, or Cordis, and no node:* imports; tests/architecture.test.ts enforces this with an empty allowlist. Where the engine needs platform behavior (the accounts store, OAuth functions, DSH's error predicates, hashing), the shell passes the real implementation in. The engine's own SHA-256 is pure TypeScript and byte-identical to node:crypto (tests/core-hasher.test.ts), so prompt_cache_key and replay keys come out the same on any runtime; the Node shell injects node:crypto anyway.

How the parts connect

This section gives the module map as a diagram, with the same information in the table after it.

flowchart TB
  subgraph DSH["DeepSeek Harness"]
    Loop["Agent loop"]
    Picker["Model picker"]
    Card["Settings card (web client)"]
    Tools["Tool service"]
  end
  subgraph Plugin["dsh-chatgpt-siwc (src/)"]
    Entry["index.ts: Cordis entry"]
    Adapter["adapter.ts: ChatGptSiwcAdapter"]
    Mapper["serialize.ts: DSH messages to request model"]
    OAuth["oauth.ts, jwt.ts: sign-in, refresh, catalog fetch"]
    Store["store.ts: accounts file and lock"]
    Ctl["account-controller.ts: card remote calls"]
    Disc["discover.ts: siwc_discover"]
    CLI["bin.ts, doctor.ts: CLI"]
  end
  subgraph Core["siwc-core (bundled)"]
    Client["engine/client.ts: SiwcClient"]
    Wire["wire/request.ts: request builder"]
    Trans["stream/translator.ts"]
    Cat["catalog.ts"]
    Sess["account/session.ts"]
  end
  OpenAI["auth.openai.com and api.openai.com"]
  Loop --> Adapter
  Picker --> Entry
  Entry --> Adapter
  Card --> Ctl
  Tools --> Disc
  Adapter --> Mapper --> Wire
  Adapter --> Client
  Adapter --> Trans
  Client --> Cat
  Client --> OAuth
  Ctl --> Sess --> OAuth
  Disc --> OAuth
  CLI --> OAuth
  OAuth --> Store
  OAuth --> OpenAI
  Adapter --> OpenAI
Loading
Module Owns
src/index.ts Config schema and validation; registers the provider route and its directory entry, the model-discovery hook, the card's account controller, the siwc_discover tool, and the settings section. The plugin loads only when DSH's llm service is present; the tool, settings, and remote-call services are optional.
src/adapter.ts The DSH LlmAdapter: authentication, effort and tier resolution, the request with its admission deadline, 401 and 400 handling, usage-window capture, stream mapping to DSH chunks, and error mapping.
src/images.ts Reads one image request version per attachment from DSH (readImageRequest, fallback readImage), checks PNG/JPEG/WEBP/GIF by reference and magic number, caps 20 MiB per image, and withholds store error text. No DSH package imports.
src/serialize.ts, src/modalities.ts Turns DSH's request into the engine's request model, keeps leading versus later system messages apart, attaches replay records, sends surface images in user messages as input_image data: URLs for image-capable models, and projects files, tool-result attachments, offloaded images, and non-image-model attachments to DSH's placeholder text.
src/oauth.ts, src/jwt.ts, src/pages.ts Discovery, sign-in with the loopback listener and its pages, token exchange and refresh, ID-token verification, sign-out, and the catalog request.
src/store.ts, src/platform-dsh.ts The accounts and host files, atomic writes, and the cross-process lock, through DSH's dsh-atomic-write and dsh-home-paths when present, with a stand-alone fallback.
src/api-origin.ts The rule that the plan token goes only to https://api.openai.com or a loopback host.
src/account-controller.ts The card's remote calls: getStatus, refreshCatalog, startSignIn, cancelSignIn, signOut, diagnose.
src/discover.ts The siwc_discover tool and the CLI discover report. No DSH package imports.
src/bin.ts, src/doctor.ts, src/locales/ The CLI and its English and Simplified Chinese text.
src/client/ The settings card, built into lib/client.js by scripts/build-client.mjs.
packages/siwc-core/src/core/wire/request.ts Builds the POST /v1/responses body; anything the plan route does not accept is absent by construction.
packages/siwc-core/src/core/stream/translator.ts Turns Responses server-sent events into a small, stable event set: block start and end, text, reasoning, tool-call deltas, usage, finish, and diagnostics for unknown events.
packages/siwc-core/src/core/engine/client.ts SiwcClient: request headers, admission-failure classification, catalog caching and merge, and per-model data (efforts, context window).
packages/siwc-core/src/catalog.ts Merge by slug, visibility filtering, effective context window.
packages/siwc-core/src/core/account/session.ts The account state behind the card, including the safe catalog projection and the usage window.

One model call, step by step

This section follows a single request from DSH to OpenAI and back.

  1. Authenticate. Load the active account and make sure its access token is fresh (refresh if needed). Refuse locally with AUTH if plan usage was not granted.
  2. Resolve the model. Look up the model in the stored catalog. An effort chosen for this call must be in the catalog's list or the call fails with UNSUPPORTED_REASONING_EFFORT; a default effort that the model does not list is dropped. Decide whether service_tier: "priority" applies.
  3. Build the body. Map DSH messages to the request model and build the Responses body (Route and compliance lists every field).
  4. Send with a deadline. Post with the bearer token and the session-id header. Waiting for response headers is bounded by streamIdleTimeoutMs.
  5. Handle refusals. A 401 triggers one forced token refresh and one retry. A 400 that names service_tier records the tier as unsupported for that model and retries once without it. Any other non-success status is classified in this order: plan-usage errors, context-window overflow, quota, 401, 429, then generic.
  6. Read headers. Store the allowlisted usage-window headers.
  7. Stream. Parse server-sent events, translate them into engine events, and emit DSH chunks: text, reasoning, tool calls, usage. A byte-idle watchdog ends a silent stream with TIMEOUT.
  8. Finish. Report usage to DSH with cached tokens split out, add it to the local spend meter, and attach encrypted reasoning to the message for replay on the next turn.

Failure behavior

This section records the choices the adapter makes when something goes wrong, and why.

  • No retry before headers. If the connection fails or times out before any response header arrives, the plugin does not retry. It cannot know whether OpenAI received the POST, and a second send could spend plan usage twice. The error is TIMEOUT (naming the budget) or TRANSPORT. tests/admission-deadline.test.ts covers this.
  • At most one retry for 401 and one for 400 service_tier. Neither loops.
  • Stream ended without a terminal event is TRANSPORT. A response with no body is MALFORMED_RESPONSE.
  • Plan-usage refusals from OpenAI become QUOTA (usage limit reached) or AUTH (not entitled, not granted, or unavailable), with a message that points to Manage usage.
  • Unknown stream events are reported as diagnostics and skipped, so a new event type from OpenAI does not break a stream.

Codes and fixes are listed in Troubleshooting.

What is tested and what is not

This section separates what automated tests prove from what only a live run can show.

The suite is 672 tests in 37 files (release qualification on Node 24.22.1, recorded in CONTEXT.md), run in CI on Node 22 and 24. Tests use injected fakes, never live endpoints: the request contract and its byte stability, per-model image carriage and offload budgets, catalog merge, the service_tier fallback and its ordering after 401, stream translation, ID-token verification, OAuth end to end against a real loopback listener, standalone CLI execution without @deepseek-ai/* on disk, plugin registration, the settings card, and English and Chinese parity. Forty golden fixtures pin request bytes and stream chunks.

A real sign-in, a real revocation, and real inference are never part of the test suite; they are operator steps. Live results are in Prompt cache.

Parts that exist but are not wired into DSH

This section names exported code that a reader may find and wonder about.

  • ThinkingSmoother (siwc-core/thinking): a presentation engine that paces reasoning text for display. It is exported but the card does not use it.
  • Prefix fingerprint (src/prefix-fingerprint.ts): a diagnostic that fingerprints each request's cache-relevant prefix next to the reported cached tokens. The adapter accepts it as an option; the DSH entry does not turn it on.
  • Dev probes (src/probe.ts, scripts/probe-wire.mjs, scripts/probe-v220.mjs): live measurement scripts, excluded from the npm package.

Clone this wiki locally