@chatcode/cco-llm-chatcode-config-test
v0.1.6-rc.12.022-rc1
Published
ChatCode CLI plugin for ChatCode models, shared account access, and operations reporting
Readme
description: "Provide ChatCode models, shared account access, and operations reporting in a ChatCode CLI profile." kind: "package-bundle"
@chatcode/cco-llm-chatcode-config
English | 中文
Summary
To investigate first-content latency, launch the CLI with CHATCODE_CLI_LATENCY_LOG=/tmp/chatcode-latency.jsonl (an absolute path is required). Tracing is off by default. It asynchronously records prompt assembly, step admission, request configuration, stream start, the first nonempty reasoning/text/tool fragment, and retry boundaries. It does not record prompts, response content, credentials, or error bodies. stream/first-content.durationMs measures from LLM stream entry and includes adapter, network, and server time; sinceTurnMs measures from turn start. request/header is a persisted configuration boundary, not an HTTP-send timestamp, and is omitted when unchanged. Compare adjacent phases rather than treating header intervals as network time. Unset the variable and restart to disable tracing. Model selection, permissions, memory, and retry behavior stay governed by their existing policies.
The bundle also provides shared CLI/Web long-conversation compression through billion-context: model-directed history folding, compressed-block search, and original retrieval. See long-conversation compression for behavior, configuration, and validation.
This plugin publishes CodingPlan, Yuanjing, and user-defined model catalogs, provides shared ChatCode account access, and reports committed ChatCode CLI Session activity to ChatCode. Runtime model credentials stay in the Host process, while the account grant stays in ChatCode CLI credential storage and never reaches Web or TUI clients. Reporting is enabled by default and can be disabled with reporting.enabled: false.
Table of Contents
- Use this package
- Understand the implementation
- Further Exploration
- Model Experience
- Known Limitations and Deferred Work
Use this package
Before issuing a launch cookie, the Web Runtime checks X-ChatCode-App-Id and X-ChatCode-App-Secret against the CVP key chatcode.runtime.appCredentials. Set its value to a JSON array of application credential pairs.
[
{ "appId": "desktop-a", "secret": "<desktop-a secret>" },
{ "appId": "desktop-b", "secret": "<desktop-b secret>" }
]The list is authoritative when configured. Include existing applications that should retain access. If CVP returns an empty string for the list key, the Runtime loads the legacy appId and secret pair. Each list entry requires these two fields, with a unique application ID and a nonempty secret. The Runtime ignores the legacy appName field. The Runtime reads the settings before Web readiness using the existing CVP token and startupGate.timeoutMs, including when startup admission is bypassed. Invalid settings or unavailable CVP block Web readiness. The verifier keeps a secret digest per application. Restrict access to the CVP key and restart the Runtime after editing the list or rotating credentials. Ordinary browser launches without these headers remain supported unless Connection requires authorization. Application credential settings are loaded by the Web startup plugin.
The shared Host reports one successful authenticated cco or cco web startup without requiring a conversation. First login releases the original startup record; page refreshes and configuration reloads do not create another launch. Startup records enter a persistent account-partitioned outbox before delivery. Set reporting.launch.enabled: false to disable this sink; operations reporting defines fields, retry bounds, and backend idempotency requirements.
The sibling-checkout development environment mounts this plugin through the main ChatCode CLI launcher:
Keep this repository and the host on dev_v2alpha_022_rc1 for the 0.2.2-rc.1 runtime. Development overrides link Host services to ../chatcode-cli-harness, including the fork's local dsh-invariants compatibility module. Build the host first; this plugin then supports pnpm install --frozen-lockfile and pnpm build from its own directory without requesting unpublished Host versions from npm.
cd /absolute/path/to/chatcode-cli-harness
pnpm install
pnpm cco web
pnpm cco cliThese source commands require no chatcode-cli plugin --profile ... add ...; their automatic patches do not modify profile manifests. Published profiles install the package with chatcode-cli plugin --profile <name> add @chatcode/cco-llm-chatcode-config. The Host uses the CVP_CHATCODE_API_TOKEN value retained from yuanjing-wanma-cli by default; startupGate.token in a private patch or CHATCODE_CVP_CONFIG_TOKEN in the Host environment overrides it. The independent CVP credential is never sent to Web or TUI clients. The local credential provider serializes updates to one ChatCode grant, so both clients see the same account at their next status query (normally about 2 seconds in Web). In Web, cco-better-sidebar displays the sign-in/out entry. In the integrated CLI, the TUI checks launch availability before account sign-in and Agent/Session creation. /login shows the account later, while /logout removes its tokens and invalidates pending sign-ins. Published installations can use cordis.patch.yml for the Host service and additionally apply cordis.web.patch.yml to make Web startup depend on that service.
Each CLI launch reads chatcode.cli.isEnabled from the CVP system-config endpoint before account authentication. A disabled response reads chatcode.cli.disabled.reason; malformed responses, authentication failures, and network failures stop startup. TUI offers Retry and Exit. Web prints the corresponding admission message and exits with status 0 before listening or opening a browser. CHATCODE_CLI_DEGRADE_STARTUP_GATE=1 or CHATCODE_CLI_NEED_AUTH_YZQ=false in the legacy settingsPath file bypasses this request; the legacy WANMA_CLI_NEED_AUTH_YZQ=false key also applies when the ChatCode key is absent. The bypass is evaluated at each launch, independently of auth.requireLogin. The default credential is embedded in Host source and can be read by anyone with access to the repository or published Host package. Legacy settingsPath reads use the explicit path first, then CHATCODE_CLI_HOME, then DSH_HOME, then ~/.chatcode-cli; selecting a separate home does not read the default home’s legacy settings. The Web admission overlay preserves the native host, port, and TLS settings, including paired --tls-cert and --tls-key flags; admission does not downgrade HTTPS to HTTP.
The default browser URL is https://testchatcode.chinaunicom.cn/unicode/#/unicode/sso?sessionId=…. The generated sessionId is part of the hash-route query and the plugin polls the matching legacy session endpoint until the account completes login. Every status query validates the stored account again; expired or revoked tokens attempt a refresh through the legacy long/login endpoint under the ChatCode CLI credential record lock. Temporary network failures preserve the grant and report unavailable verification for that call only. Detection results are not persisted, and legacy validation / checkedAtMs fields are ignored. The .credentials.yaml.lock file contains only the writer PID and is released after the transaction, including network failures.
See the shared sign-in guide (中文) for operation and validation. Account sign-in does not replace custom-model API keys or ChatCode CLI's own browser access authentication.
0.1.4-rc.8 merges the SSO default sign-in URL with the existing login-page recovery flow. Explicit auth.loginUrl overrides remain supported; model configuration, shared credentials and retry policies are unchanged.
Sign-in validation bounds the entire credential-queue, file-lock and network wait to min(20000, auth.requestTimeoutMs * 3) milliseconds (15 seconds by default). A timeout reports unavailable verification without deleting the stored grant or allowing model access; an expired queued callback cannot start validation later. Set CHATCODE_CLI_STARTUP_TRACE=1 to log credential-lock, account-request and validation durations to stderr without credential values. Startup version admission uses the launcher's process-layer CHATCODE_CLI_PRODUCT_VERSION when supplied, avoiding an additional global npm version probe.
With reporting.enabled and reporting.sessionEnabled, the Host submits original messages and per-response reports together through /wanma/api/v2/conversations/sync. The backend commits the database transaction before creating or reusing a persistent ChatCode chatId and appending an operations record. Settled tools contribute complete results, commands, paths, and recognized mutation code to their originating response; tools do not add separate zero-token reports. Tool-only responses retain usage under their original message UUID. Generated code uses its independent durable outbox. See ChatCode operations reporting for fields, recovery, and failure handling.
Unified submissions carry the owning login account's email as database metadata; the backend continues to authorize Session access with the authenticated account identity.
Subagent Session delivery is enabled by default. Each in-process spawn or fork child retains its own messages, usage, and ChatCode chatId; inherited fork history is excluded. The backend stores independent sessions without parent-child relationships. Set reporting.includeSubagentConversationSync: false to exclude child sessions from unified persistence and reporting. Untracked historical messages are not automatically backfilled. See the reporting guide for configuration and accounting limits.
ChatCode pluginVersion comes from the launcher's process-layer CHATCODE_CLI_PRODUCT_VERSION, as startup appVersion does. A missing or blank version prevents unified reporting installation; project and user .env cannot supply it. Either legacy conversationSync: false or chatCodeSession: false disables the entire unified Session chain; new configurations use sessionEnabled.
CLI /model-config and the native Web Models page store custom models as llm-pi-ai.providers in <CHATCODE_CLI_HOME>/cordis.patch.yml. They resolve apiKeyEnv references through the same credential service and .credentials.yaml; file watching publishes changes without restarting. settings.json.customModels is no longer loaded or automatically migrated. Explicit customModels on this plugin's mount remain supported for existing compositions, but the product configuration UI uses native provider settings. Other mount options can still be supplied through a separate patch:
- id: llm-chatcode-config
config:
gatewayBaseUrl: https://testchatcode.chinaunicom.cn/gateway
auth:
loginUrl: https://testchatcode.chinaunicom.cn/unicode/#/unicode/sso
apiBaseUrl: https://testchatcode.chinaunicom.cn
cvpChatCodeApiUrl: https://testchatcode.chinaunicom.cn/cvp
reporting:
enabled: true
codeSave: true
sessionEnabled: true
sessionRequestTimeoutMs: 120000
sessionRetryDelayMs: 5000
clientType: auto
tongtongAppIds: ["GtgO9XK1oe"]Set input: [text, image] on a custom model that accepts images; the former inputModalities spelling remains compatible. Models without a declaration remain text-only, avoiding image requests to gateways that do not accept them.
The Host uses the current ChatCode JWT to fetch the managed model groups from GET /v1/models/grouped and stream requests through POST /v1/chat/completions at gatewayBaseUrl. Group kind 1 uses the Yuanjing adapter. Other kinds use the CodingPlan adapter. The Web picker uses each group's name and position in the response. Conversation storage and ChatCode reports use the catalog model's name, upstream URL, and supported kind. Inference sends the catalog model's id. cvpChatCodeApiUrl serves session and code reporting independently.
The selector uses gateway IDs by default. Set gatewayModelAliases to map a gateway ID to a previously saved selection for the same model. Use catalogTimeoutMs to bound discovery. Temporary discovery outages retain the last catalog for the same login and deployment. Signing out, losing access, or receiving an empty catalog removes the affected models. Explicit codingPlanEndpoint or maasEndpoint settings select legacy compatibility mode.
Gateway entries with supportsImages: true accept inline image_url attachments. The Host projects images to text handles for text-only models. All gateway streams request usage so committed assistant messages retain token counts. DeepSeek routes use DeepSeekChatCompletionsAdapter for reasoning and tool history. Legacy endpoints declare image support with input or inputModalities.
For ChatCode history, the x-chatcode-session header uses ses_ plus 28 hexadecimal characters derived from the Harness session ID. Calls in the same session reuse this header. CVP uses this derived ID for new records and retains the original Harness ID for sessions already saved under it. The local reporting queue records the CVP ID before sending the first batch, so retries and restarts use the same record. Gateway calls send the launcher's CLI product version in x-chatcode-plugin-version when available, using the same version source as CVP reporting.
For ordinary ChatCode gateway requests, workspace instructions, runtime context, skill catalogs, time context, and model selection notices immediately following a user input are sent before that input so ChatCode history selects the original question.
The package retains a no-op browser client entry for installed-profile compatibility. The Web and terminal model pickers display the gateway groups containing available models, followed by user-defined models. Legacy endpoint mode uses the built-in and Yuanjing provider labels for managed models.
For a first installation without a saved model choice, the bundle supplies the first runnable CodingPlan model in server order as the shared CLI/Web default. If CodingPlan has no runnable entry, it falls back to Yuanjing and then custom models; if all three catalogs are empty, the selection stays empty instead of naming an unconfigured official DeepSeek model. Catalog loading finishes before the default becomes available. Saved model preferences and later explicit profile patches retain precedence, and selecting this startup default does not write a model preference.
Agent requests for CodingPlan, Yuanjing, and custom models default to seven retries after the initial attempt for transient failures, including HTTP 429 with no response body. Exponential backoff waits 4, 8, 16, 32, 64, 128, and 256 seconds, without random jitter and with a 256-second cap. The Host waits for the longer of local backoff and a provider-supplied Retry-After within that cap; longer rate-limit waits are capped rather than ending recovery. Retries retain the selected model and durable history, are recorded by the Host's llm-retry plugin, and stop on cancellation or budget exhaustion. MISSING_CREDENTIAL uses the same seven-retry budget, allowing temporarily unavailable credentials to become available between requests; if they remain missing, the final error retains that code. Other authentication failures and exhausted account quota are not retried. Override the budget and backoff through this entry's retryPolicy; an explicit maxRetries: 0 remains respected. Direct adapter or ctx.llm.stream() calls remain single-attempt, and each retry can incur provider charges.
Understand the implementation
Unacknowledged submissions and original response metadata persist in a local Session outbox partitioned by backend and account. TUI /resume, Web recovery, and Host restarts retain original UUIDs, reconcile managed history, and reuse the backend chatId. An ambiguous ChatCode result remains UNKNOWN and pauses subsequent appends for that Session while original messages continue to persist. An unavailable v2 endpoint never triggers fallback to the old dual submission paths; see reporting configuration and failure behavior.
src/managed.ts separates managed model metadata from request credentials and derives stable private connection routes. src/adapter.ts selects the native @deepseek-ai/dsh-llm-deepseek adapter for actual model IDs containing deepseek, case-insensitively, across custom, CodingPlan, and Yuanjing groups. OpenAI routes use DeepSeekChatCompletionsAdapter; Anthropic routes keep DeepSeekAdapter. Other IDs use the modified pi-ai adapter in vendor/dsh-llm-pi-ai/, whose reachable modules are bundled into lib/index.js. Display names do not select a transport.
The Host emits an Info log beginning chatcode-config: llm dispatch when each model attempt starts streaming. These records are exported to standard error (stderr) only when stderr is redirected to a file or pipe; an attached terminal receives no dispatch output. No dispatch log file is created automatically. The JSON fields identify the public provider, selected selection ID, actual wireModel, wire api, and selected adapter (DeepSeekChatCompletionsAdapter, DeepSeekAdapter, or PiAiAdapter). Direct calls, prepared calls, Host retries, and GLM corrective requests use this record. Catalog queries, capability inspection, unused prepared calls, and requests cancelled before consumption emit no dispatch record. Records describe adapter dispatch; authentication, image preparation, or transport errors can still prevent an HTTP request. For example:
chatcode-config: llm dispatch {"provider":"chatcode-custom","selection":"Vendor-DEEPSEEK-chat","wireModel":"Vendor-DEEPSEEK-chat","api":"openai-completions","adapter":"DeepSeekChatCompletionsAdapter"}DeepSeek routes use the entry protocol, base URL, and API key. Native OpenAI requests send Authorization: Bearer, default to High reasoning with thinking enabled, preserve raw reasoning_content and tool arguments, and support Files or inline images. An explicit effort, including Off, overrides this default. Native Anthropic requests send x-api-key. Both retain runtime identity headers and the stable anonymous DeepSeek user-id header; imported routes do not install official account request extensions. Non-DeepSeek Anthropic routes send Authorization: Bearer through pi-ai. MiniMax M2 OpenAI requests carry reasoning_split: true. Provider-owned attribution headers remain reserved, and pi-ai uses an isolated in-memory credential store.
Gateway requests use gatewaySourceType and gatewayAssistantId for attribution, with CLI defaults 5 and 1026. They reuse the Session ID and maintain a separate request ID per model step, including steps after tool results. A transport retry reuses the step's request ID. Legacy built-in model routes still send ai-user-id and ai-user-type: 11 using the stored account identity.
src/reporting/ projects committed Session events through per-Session queues into original messages, response drafts, and finalized reports, then durably submits them through the unified endpoint. The reporter reuses ChatCodeAuthService; it adds no client-visible service or second Cordis entry.
Managed OpenAI streaming requests explicitly send Accept: text/event-stream. This supports forwarding gateways that enforce content negotiation and prevents an HTTP 200 JSON business error from being misreported by the stream parser as a missing finish_reason.
Context capacity and output limits are independent: custom models resolve contextWindow, then legacy maxInputTokens, then defaultContextWindow; managed models use their explicit contextWindow or that default. maxTokens and managed maxToken set the output budget only. Compression reduces input history; a length response still ends the current generation at its output cap, including reasoning tokens when the provider bills them as output. The received text is retained and a new user message can continue it.
For Yuanjing glm-5.3-flash with tools available, a response that stops after reasoning about tool work or a short announcement of that work receives one corrective request with tool_choice: required and the same messages and tools. Normal answers, actual tool calls, request errors, and cancellation do not trigger this correction. Both requests' usage is counted; streamed preambles remain visible. If the correction also returns only a plan, the request reports YUANJING_TOOL_CALL_MISSING rather than completing silently. This workaround does not change other models or custom GLM routes.
Web and CLI share DSML recovery in the model adapter. All routes with tools available detect leaked DSML, ordinary XML tool tags (tool_calls, invoke, parameter), and <rpoot> wrappers when no structured tool call was returned, including empty wrappers and parameter fragments after a normal-text preamble. Leaked protocol text is filtered from streamed text and completed text blocks while the preamble, code examples, and ordinary HTML remain visible. Reasoning-only DSML also triggers recovery. A completed response receives one new request through the same captured adapter, with the same model, messages, tools, and thinking settings. DSML/XML text is never executed as a tool. The retry does not force tool choice, because DeepSeek thinking mode rejects required. Existing structured calls, complete answers, documentation examples, cancellation, provider errors, and output-length limits keep their behavior. Usage from both requests is retained. If the retry still returns malformed DSML, or only reasoning without an answer or tool call, the adapter appends a visible notice that this call was not executed and ends normally. Both clients can accept the next message in the same conversation. DSML and GLM recovery share one corrective-request budget.
With a sibling chatcode-cli-harness checkout on the same branch, pnpm verify:dsml typechecks and builds the plugin, runs protocol and recovery tests, and checks the real headless CLI plus the Web host's public Session API. Both fixtures load the complete built plugin in disposable profiles; model and configuration endpoints use local HTTP fixtures. They cover successful execution, repeated malformed output without execution, continued conversation, and durable completed turns. node tests/fixtures/dsml-web-smoke.mjs also starts an isolated WebUI for manual checks: send dsml-persistent, dsml-continue, then dsml-recover in one conversation, and stop the fixture with Ctrl-C to validate its Session log and remove test data. These checks do not change user profiles.
For the managed Yuanjing OpenAI route at https://maas-api.ai-yuanjing.com/openapi/compatible-mode/v1, a plain 404 page not found is classified as SERVER: this gateway can return that response intermittently on an otherwise working route, including after HTTP 429 rate limits. Host recovery uses the existing retry budget, backoff, and cancellation; the adapter adds no retries and never switches models. Exhausted retries report the actual model and a gateway diagnostic without credentials. Other 404s (including structured model_not_found and custom endpoints) retain their original classification. A persistent gateway failure still requires service-side investigation.
Further Exploration
- Plugin marketplace guide: Web and
/pluginsshare project/user installations, the default official market, and ChatCode authentication. docs/chatcode-models.mddescribes the user workflow and source fields.guides/chatcode-reporting.mddefines reporting fields, durability, and failure behavior.docs/decisions/2026-08-31-chatcode-model-source.mdrecords credential ownership and route identity.docs/decisions/2026-09-16-actual-model-adapter-routing.mdrecords adapter selection and authentication consequences.vendor/README.mdrecords the copied adapter source and update rule.
Model Experience
The model receives the normal ChatCode CLI system prompt, messages, and tools through the selected imported endpoint. CodingPlan entries appear under the 内置模型 group in both the Web selector and the CLI /model picker. Configuration paths, labels, and credentials do not enter model messages. The imported context capacity sizes the request context, and the imported output limit becomes the request default and ceiling. DeepSeek-named models expose the native DeepSeek reasoning choices; other imported models retain pi-ai capabilities.
Known Limitations and Deferred Work
- Managed catalog reads are activation snapshots; remount or restart after changing a central catalog.
- Imported models declare text input. Non-DeepSeek routes do not expose selectable reasoning effort.
- One invalid entry, including a duplicate model ID, suppresses the complete imported catalog; the bundle does not publish a partially valid source.
- The published browser client entry is intentionally a compatibility no-op; model groups come from the Host registry and the native model selector remains authoritative.
- The package tracks the copied pi-ai adapter source and the native DeepSeek adapter peer; upgrade either through an explicit compatibility test, and refresh
vendor/when pi-ai changes. - An ambiguous ChatCode append result requires remote reconciliation before further appends for that Session.
Dev Note
None.
