@herbertgao/pi-extensions 2026.11.2 → 2026.11.3
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/CHANGELOG.md +10 -0
- package/README.md +11 -11
- package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
- package/node_modules/@herbertgao/pi-cc-extensions/README.en.md +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/README.md +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/compact-mode.ts +109 -16
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/renderer/tool/diff/write-execution.ts +5 -1
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +4 -4
- package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +6 -0
- package/node_modules/@herbertgao/pi-subagents/README.md +12 -10
- package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +1 -1
- package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
- package/node_modules/@herbertgao/pi-subagents/src/agent-record-entry.ts +22 -6
- package/node_modules/@herbertgao/pi-subagents/src/index.ts +9 -4
- package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +167 -7
- package/node_modules/@herbertgao/pi-subagents/src/ui/viewer-keys.ts +8 -4
- package/node_modules/@narumitw/pi-btw/CHANGELOG.md +259 -0
- package/node_modules/@narumitw/pi-btw/package.json +6 -5
- package/node_modules/@narumitw/pi-caffeinate/CHANGELOG.md +70 -0
- package/node_modules/@narumitw/pi-caffeinate/package.json +5 -4
- package/node_modules/pi-commandcode-provider/CHANGELOG.md +21 -0
- package/node_modules/pi-commandcode-provider/README.md +18 -6
- package/node_modules/pi-commandcode-provider/index.ts +11 -5
- package/node_modules/pi-commandcode-provider/package.json +1 -1
- package/node_modules/pi-commandcode-provider/src/api-key.ts +26 -10
- package/node_modules/pi-commandcode-provider/src/auth-server.ts +33 -24
- package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +2 -2
- package/node_modules/pi-commandcode-provider/src/converters.ts +3 -61
- package/node_modules/pi-commandcode-provider/src/core.ts +29 -4
- package/node_modules/pi-commandcode-provider/src/cost.ts +32 -12
- package/node_modules/pi-commandcode-provider/src/oauth.ts +40 -6
- package/node_modules/pi-commandcode-provider/src/pricing.ts +5 -3
- package/node_modules/pi-commandcode-provider/src/runtime.ts +14 -7
- package/node_modules/pi-commandcode-provider/src/transport.ts +6 -3
- package/node_modules/pi-web-access/CHANGELOG.md +22 -0
- package/node_modules/pi-web-access/README.md +31 -12
- package/node_modules/pi-web-access/curator-page.ts +5 -1
- package/node_modules/pi-web-access/curator-server.ts +2 -0
- package/node_modules/pi-web-access/dist/index.js +673 -308
- package/node_modules/pi-web-access/dist/mcp-cli.js +666 -309
- package/node_modules/pi-web-access/gemini-search.ts +12 -4
- package/node_modules/pi-web-access/github-api.ts +1 -1
- package/node_modules/pi-web-access/github-extract.ts +3 -2
- package/node_modules/pi-web-access/index.ts +7 -3
- package/node_modules/pi-web-access/mcp-tool-definitions.ts +1 -1
- package/node_modules/pi-web-access/outcrawl.ts +204 -0
- package/node_modules/pi-web-access/package.json +2 -2
- package/node_modules/pi-web-access/sofya.ts +201 -0
- package/node_modules/pi-web-access/utils.ts +16 -6
- package/node_modules/pi-web-access/web-tool-core.ts +4 -0
- package/package.json +9 -9
|
@@ -2,6 +2,27 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 0.7.12 - 2026-11-04
|
|
6
|
+
|
|
7
|
+
- Reuse the shared credential redactor for `/commandcode-status` diagnostic text while preserving URL query, fragment, and userinfo removal. Defensive hardening with synthetic regression coverage, not a confirmed production leak. Carries the shared-redactor fix from #165 by @patlux ([#195](https://github.com/patlux/pi-commandcode-provider/pull/195)).
|
|
8
|
+
- Clear the `/commandcode-status` stream-warning slot when the next Responses HTTP request starts, rather than keeping a one-off malformed-reasoning warning until restart. Other transports do not clear the slot; concurrent Responses requests still share it. Carries the warning-reset fix from #165 by @patlux, with precise reset semantics and a real Pi RPC regression ([#194](https://github.com/patlux/pi-commandcode-provider/pull/194)).
|
|
9
|
+
- Preserve and double context-tier rates alongside base rates during DeepSeek V4 peak windows on the Provider API path. Copy the readonly catalog into an independent mutable cost table at the native-host boundary. The adapter's mutable return shape is guarded by the project typecheck and mutation tests; this does not extend typecheck coverage to the host entrypoint. This is a synthetic future-proofing case: no current time-priced model has context tiers. Carries the peak-tier fix from #165 by @patlux, with the native-host contract adapted during integration ([#193](https://github.com/patlux/pi-commandcode-provider/pull/193)).
|
|
10
|
+
- Reset the transport probe on `/commandcode-refresh` so an upgraded Go account retries the Provider API with the same key. Prevent requests started before a reset or key change from overwriting the new probe result. Carries the refresh fix from #165 by @patlux, with same-key race coverage and a real Pi RPC wiring test ([#192](https://github.com/patlux/pi-commandcode-provider/pull/192)).
|
|
11
|
+
- Make server-side taste learning opt-in on the legacy generate transport via `COMMANDCODE_TASTE_LEARNING=1`, always disabled under `CMD_ZDR=1` or `COMMANDCODE_ZDR=1`. Caller headers cannot override this policy, regardless of casing. Document the working-directory, project-slug, and session metadata. Carries the taste-learning fix from #165 by @patlux, with the header-override review concern addressed ([#191](https://github.com/patlux/pi-commandcode-provider/pull/191)).
|
|
12
|
+
- Validate pasted `/login` API keys against the configured `COMMANDCODE_API_BASE` instead of always calling production, with a 15-second deadline even when fetch ignores cancellation. An explicitly empty base is preserved instead of silently sending the key to production. Carries the login-validation fix from #165 by @patlux ([#190](https://github.com/patlux/pi-commandcode-provider/pull/190)).
|
|
13
|
+
- Read ambient credentials through one shared reader for the Provider API, generate fallback, and quota commands. The generate fallback now follows the documented `.commandcode` → pi → `.omp` file order and accepts the `"command-code": "user_..."` string form. `PI_CODING_AGENT_DIR` redirects the pi slot without falling back to the default pi profile; `.commandcode` and `.omp` still resolve from `HOME`. Carries the credential-reader fix from #165 by @patlux ([#189](https://github.com/patlux/pi-commandcode-provider/pull/189)).
|
|
14
|
+
- Require the matching login state token before honoring OAuth callback errors, and reject the local development browser origin `http://localhost:3000`. Invalid callbacks leave the server waiting for the legitimate login. Carried forward from @patlux's #165 (`a918138`); callbacks that omit the state on cancellation now wait for the existing timeout and manual-key fallback instead of cancelling immediately ([#186](https://github.com/patlux/pi-commandcode-provider/pull/186)).
|
|
15
|
+
- Add reviewed zero display pricing for `stealth/crouton-alpha`, free up to 1,000 requests per day while the stealth preview lasts, with no fixed expiry published. Refresh the API/pricing snapshots to 96 models, verified on 2026-11-04. CLI capability metadata remains unchanged at `command-code@1.88.2`; Crouton keeps conservative text-only, non-reasoning defaults with a 65,536-token output limit and uses its advertised Chat Completions endpoint ([#188](https://github.com/patlux/pi-commandcode-provider/pull/188)).
|
|
16
|
+
- Report generate response-body stalls as timeouts instead of user cancellations, retrying only while no visible content has been emitted and the retry budget remains. Real user cancellations still abort without retry. Carried forward from @patlux's #165 (`cef7402`); the native Provider API transports are unchanged ([#187](https://github.com/patlux/pi-commandcode-provider/pull/187)).
|
|
17
|
+
- Add reviewed display pricing for `inclusionai/ling-3.1-flash-1019` after its free preview ended on 2026-11-03 at 16:00 UTC: $0.30 input / $0.90 output / $0.06 cache read per million tokens, with no cache-write charge. Remove the retired `:free` entry and its dated pricing guard, and refresh the 95-model snapshot against the Provider API. The existing `inclusionai/ling-3.1-flash` keeps its own list rates. The CLI still publishes no capability metadata for the 1019 model, so it retains conservative text-only, non-reasoning defaults with a 65,536-token output limit ([#185](https://github.com/patlux/pi-commandcode-provider/pull/185)).
|
|
18
|
+
- Refresh the capability snapshot pin to `command-code@1.88.2`; upstream reports no capability or output-limit changes ([#178](https://github.com/patlux/pi-commandcode-provider/pull/178)).
|
|
19
|
+
- Stabilize the abort regression test by cancelling after the first observed text delta, verifying iterator completion and upstream closure, and bounding failed-test teardown. Cover immediate and delayed mock responses; no runtime behavior change ([#196](https://github.com/patlux/pi-commandcode-provider/pull/196)).
|
|
20
|
+
|
|
21
|
+
### Contributors
|
|
22
|
+
|
|
23
|
+
- @patlux (Patrick Wozniak) — authored the nine auth, credential, privacy, transport, pricing-tier and diagnostic-redaction lots carried forward from #165 through #186, #187 and #189–#195.
|
|
24
|
+
- @pierreraby — reviewed and adapted the carries, contributed integration guards and tests, maintained model pricing, stabilized the abort test, and prepared this release.
|
|
25
|
+
|
|
5
26
|
## 0.7.11 - 2026-10-28
|
|
6
27
|
|
|
7
28
|
- Refresh the static capability snapshot to `command-code@1.88.1`, which publishes metadata for two models the CLI previously did not describe: `moonshotai/Kimi-K3.1-Pro` finally gains image input, reasoning, and selectable `low`/`high`/`max` efforts instead of the conservative text-only defaults it carried since 0.7.10, and the newly advertised `gpt-6.1-terra` arrives with image input, reasoning, and `low`/`medium`/`high`/`xhigh`/`max` efforts. Neither model publishes a model-specific output limit, so both keep the 65,536-token default. No other model metadata changed ([#175](https://github.com/patlux/pi-commandcode-provider/pull/175)).
|
|
@@ -51,12 +51,14 @@ export COMMAND_CODE_API_KEY="user_..."
|
|
|
51
51
|
|
|
52
52
|
### Auth file
|
|
53
53
|
|
|
54
|
-
The provider also reads existing credentials from:
|
|
54
|
+
The provider also reads existing credentials from, in this order:
|
|
55
55
|
|
|
56
56
|
- `~/.commandcode/auth.json`
|
|
57
|
-
- `~/.pi/agent/auth.json`
|
|
57
|
+
- `~/.pi/agent/auth.json` (or `$PI_CODING_AGENT_DIR/auth.json` when pi runs with that variable)
|
|
58
58
|
- `~/.omp/agent/auth.json`
|
|
59
59
|
|
|
60
|
+
Both transports and the quota commands use the same ambient lookup, after any credentials supplied by the host. `PI_CODING_AGENT_DIR` redirects only the pi auth-file slot; the `.commandcode` and `.omp` paths still use `HOME`. Isolate `HOME` as well when a sandbox must not read those credentials.
|
|
61
|
+
|
|
60
62
|
Supported examples:
|
|
61
63
|
|
|
62
64
|
```json
|
|
@@ -132,8 +134,8 @@ When a valid cache exists, the provider registers the cached catalog immediately
|
|
|
132
134
|
|
|
133
135
|
While pi is running, use these provider commands without restarting:
|
|
134
136
|
|
|
135
|
-
- `/commandcode-refresh` fetches and re-registers the current model catalog. Overlapping refreshes are coalesced, and a failed refresh keeps the last valid catalog active.
|
|
136
|
-
- `/commandcode-status` shows redacted discovery diagnostics, including the source, model count, timestamps, cache path, endpoint, and warning. If a Responses reasoning event has an unsupported shape, a separate stream warning
|
|
137
|
+
- `/commandcode-refresh` fetches and re-registers the current model catalog, and forgets the probed transport so the next request tries the Provider API again (for example after upgrading a Go account). Overlapping refreshes are coalesced, and a failed refresh keeps the last valid catalog active.
|
|
138
|
+
- `/commandcode-status` shows redacted discovery diagnostics, including the source, model count, timestamps, cache path, endpoint, and warning. If a Responses reasoning event has an unsupported shape, a separate stream warning is cleared when the next Responses HTTP request starts, before its outcome is known. Requests on Chat Completions, Messages, or generate do not clear it. The slot is shared by concurrent Responses requests, so a late warning from an older in-flight response can still replace it. The event is preserved unchanged; no reasoning text is included in the warning.
|
|
137
139
|
- `/commandcode-quota` shows your Command Code account usage and quota in a dashboard-style layout: credits remaining and used with a percentage, monthly/purchased/free sources, the current plan, available usage totals, the API key name, and the 5-hour and weekly usage windows.
|
|
138
140
|
|
|
139
141
|
The `commandcode-quota` command reads from the Command Code alpha usage endpoints (the same ones the `cmd` CLI `/usage` command uses): `whoami`, `billing/credits`, `billing/subscriptions`, and `usage/summary`. It authenticates with the same API key the provider already uses. If the command cannot reach those endpoints or an endpoint schema changes, unavailable sections are reported explicitly instead of being displayed as zero usage. Output is plain text (via `ui.notify`) so it works across pi and compatible hosts such as OMP.
|
|
@@ -142,16 +144,26 @@ On Oh My Pi the provider also registers an OMP usage provider through the `usage
|
|
|
142
144
|
|
|
143
145
|
Set `CMD_ZDR=1` to send Command Code's documented `x-cmd-zdr: 1` zero-data-retention header. The legacy `COMMANDCODE_ZDR=1` alias remains supported.
|
|
144
146
|
|
|
147
|
+
### Request metadata on the generate transport
|
|
148
|
+
|
|
149
|
+
The legacy `/alpha/generate` fallback used by Go accounts mirrors the official CLI's request shape, which includes metadata the Provider API path does not send:
|
|
150
|
+
|
|
151
|
+
- the absolute working directory (`config.workingDir`) and a slug derived from it (`x-project-slug`);
|
|
152
|
+
- the host session id (`x-session-id`) and, when it is a UUID, the same value as `threadId`;
|
|
153
|
+
- `x-taste-learning`, the CLI's opt-in for Command Code's server-side taste learning. The CLI sends its `tasteLearning` setting (default on); this extension never reads the learned profile back, so it sends `false` unless `COMMANDCODE_TASTE_LEARNING=1` is set, and always `false` under `CMD_ZDR=1` or `COMMANDCODE_ZDR=1`. Caller headers cannot override this policy.
|
|
154
|
+
|
|
155
|
+
The dedicated local-files, git-state, memory, and skills request fields stay empty. Conversation messages, tool results, system prompts, and tool definitions are still sent as required for inference.
|
|
156
|
+
|
|
145
157
|
The following environment variables are intended for tests, local mocks, and compatible API endpoints:
|
|
146
158
|
|
|
147
|
-
- `COMMANDCODE_API_BASE`
|
|
159
|
+
- `COMMANDCODE_API_BASE` (Provider API base; the alpha endpoints used by `/login` key validation and `/commandcode-quota` are derived from it without the `/provider/v1` suffix; an explicitly empty value does not fall back to production)
|
|
148
160
|
- `COMMANDCODE_MODELS_URL`
|
|
149
161
|
- `COMMANDCODE_MODELS_CACHE`
|
|
150
162
|
- `COMMANDCODE_MODELS_TIMEOUT_MS` (defaults to 10 seconds; invalid or non-positive values use the default)
|
|
151
163
|
|
|
152
164
|
## Image input
|
|
153
165
|
|
|
154
|
-
The provider advertises image input only for models marked with the `image` input modality in the official Command Code CLI model catalog. The capability snapshot currently follows `command-code@1.88.
|
|
166
|
+
The provider advertises image input only for models marked with the `image` input modality in the official Command Code CLI model catalog. The capability snapshot currently follows `command-code@1.88.2`; unknown models default to text-only until their upstream metadata is reviewed. A daily GitHub Actions job synchronizes the CLI version, image capabilities, reasoning flags, reasoning efforts, and model-specific output limits with the latest published CLI package, also dropping manual effort overrides that upstream has published itself, and opens or updates a reviewable pull request when they change. Pricing remains manually reviewed because temporary promotions and long-context tiers require explicit review.
|
|
155
167
|
|
|
156
168
|
For vision-capable models, Pi's native provider adapters forward image blocks from user messages and tool results using the documented OpenAI or Anthropic message schema. Unknown and text-only models remain marked text-only in Pi.
|
|
157
169
|
|
|
@@ -19,7 +19,7 @@ import { join } from "node:path"
|
|
|
19
19
|
import { getConfiguredApiKey } from "./src/api-key.ts"
|
|
20
20
|
import { pickCommandCodeApiKey, withResolvedCommandCodeApiKey } from "./src/converters.ts"
|
|
21
21
|
import { createStreamCommandCode } from "./src/core.ts"
|
|
22
|
-
import { calculateCommandCodeCost,
|
|
22
|
+
import { calculateCommandCodeCost, commandCodeNativeCostRatesAt } from "./src/cost.ts"
|
|
23
23
|
import {
|
|
24
24
|
apiForModelId,
|
|
25
25
|
baseUrlForModel,
|
|
@@ -221,6 +221,8 @@ export default async function (pi: ExtensionAPI) {
|
|
|
221
221
|
const modelApis = new Map<string, CommandCodeApi>()
|
|
222
222
|
const resolveModelApi = (modelId: string): CommandCodeApi =>
|
|
223
223
|
modelApis.get(modelId) ?? apiForModelId(modelId)
|
|
224
|
+
// Diagnostic for /commandcode-status: reflects the most recent Responses
|
|
225
|
+
// request, so a one-off malformed stream does not stick until restart.
|
|
224
226
|
let streamWarning: string | undefined
|
|
225
227
|
const transport = createCommandCodeTransportRouter({
|
|
226
228
|
createStream: () => new AssistantMessageEventStream(),
|
|
@@ -232,20 +234,23 @@ export default async function (pi: ExtensionAPI) {
|
|
|
232
234
|
wire === "openai-responses"
|
|
233
235
|
? {
|
|
234
236
|
...resolvedOptions,
|
|
235
|
-
fetch: async (...args: Parameters<typeof fetch>) =>
|
|
236
|
-
|
|
237
|
+
fetch: async (...args: Parameters<typeof fetch>) => {
|
|
238
|
+
streamWarning = undefined
|
|
239
|
+
return normalizeCommandCodeResponsesResponse(
|
|
237
240
|
await (resolvedOptions?.fetch ?? fetch)(...args),
|
|
238
241
|
(warning) => {
|
|
239
242
|
streamWarning = warning
|
|
240
243
|
},
|
|
241
|
-
)
|
|
244
|
+
)
|
|
245
|
+
},
|
|
242
246
|
}
|
|
243
247
|
: resolvedOptions
|
|
244
248
|
return streamNativeProvider(
|
|
245
249
|
{
|
|
246
250
|
...model,
|
|
247
251
|
api: wire,
|
|
248
|
-
|
|
252
|
+
// Native hosts receive mutable tiers without owning the readonly catalog.
|
|
253
|
+
cost: commandCodeNativeCostRatesAt(model.id, model.cost),
|
|
249
254
|
compat: model.compatConfig ?? model.compat,
|
|
250
255
|
},
|
|
251
256
|
context,
|
|
@@ -298,6 +303,7 @@ export default async function (pi: ExtensionAPI) {
|
|
|
298
303
|
return createProviderConfig(models, apiBase, transport.stream)
|
|
299
304
|
},
|
|
300
305
|
getTransport: transport.getTransport,
|
|
306
|
+
resetTransport: transport.reset,
|
|
301
307
|
getStreamWarning: () => streamWarning,
|
|
302
308
|
})
|
|
303
309
|
|
|
@@ -10,10 +10,17 @@ function stringValue(value: unknown): string | undefined {
|
|
|
10
10
|
return typeof value === "string" ? value : undefined
|
|
11
11
|
}
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
/**
|
|
14
|
+
* Credential files consulted after the environment, in precedence order (also
|
|
15
|
+
* documented in README.md). pi honors `PI_CODING_AGENT_DIR` for its agent
|
|
16
|
+
* directory, so a profile started with that variable must not fall back to the
|
|
17
|
+
* default `~/.pi/agent/auth.json` of another profile.
|
|
18
|
+
*/
|
|
19
|
+
export function defaultAuthPaths(home: string, env: NodeJS.ProcessEnv = process.env): string[] {
|
|
20
|
+
const piAgentDir = env.PI_CODING_AGENT_DIR || join(home, ".pi", "agent")
|
|
14
21
|
return [
|
|
15
22
|
join(home, ".commandcode", "auth.json"),
|
|
16
|
-
join(
|
|
23
|
+
join(piAgentDir, "auth.json"),
|
|
17
24
|
join(home, ".omp", "agent", "auth.json"),
|
|
18
25
|
]
|
|
19
26
|
}
|
|
@@ -26,19 +33,25 @@ function apiKeyFromCredential(value: unknown): string | undefined {
|
|
|
26
33
|
return stringValue(value.access) ?? stringValue(value.key)
|
|
27
34
|
}
|
|
28
35
|
|
|
29
|
-
export
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
+
export interface ApiKeyLookupOptions {
|
|
37
|
+
env?: NodeJS.ProcessEnv
|
|
38
|
+
authPaths?: readonly string[]
|
|
39
|
+
homeDir?: () => string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The single credential reader shared by the Provider API path, the generate
|
|
44
|
+
* fallback, and the quota/usage commands: environment first, then the auth
|
|
45
|
+
* files above. Hosts resolve their own stored credentials before this runs;
|
|
46
|
+
* this is the ambient fallback for keys they do not know about.
|
|
47
|
+
*/
|
|
48
|
+
export function getConfiguredApiKey(options: ApiKeyLookupOptions = {}): string | undefined {
|
|
36
49
|
const env = options.env ?? process.env
|
|
37
50
|
if (env.COMMAND_CODE_API_KEY) return env.COMMAND_CODE_API_KEY
|
|
38
51
|
if (env.COMMANDCODE_API_KEY) return env.COMMANDCODE_API_KEY
|
|
39
52
|
|
|
40
53
|
const home = options.homeDir?.() ?? homedir()
|
|
41
|
-
const authPaths = options.authPaths ?? defaultAuthPaths(home)
|
|
54
|
+
const authPaths = options.authPaths ?? defaultAuthPaths(home, env)
|
|
42
55
|
|
|
43
56
|
for (const authPath of authPaths) {
|
|
44
57
|
try {
|
|
@@ -46,9 +59,12 @@ export function getConfiguredApiKey(
|
|
|
46
59
|
const parsed: unknown = JSON.parse(readFileSync(authPath, "utf-8"))
|
|
47
60
|
if (!isRecord(parsed)) continue
|
|
48
61
|
|
|
62
|
+
// Legacy: direct apiKey or commandcode field.
|
|
49
63
|
const apiKey = stringValue(parsed.apiKey)
|
|
50
64
|
if (apiKey) return apiKey
|
|
51
65
|
|
|
66
|
+
// pi stores OAuth credentials as {"commandcode": {"type":"oauth","access":"..."}}.
|
|
67
|
+
// The official Command Code CLI stores API credentials under "command-code".
|
|
52
68
|
const commandcode = stringValue(parsed.commandcode)
|
|
53
69
|
if (commandcode) return commandcode
|
|
54
70
|
|
|
@@ -11,6 +11,10 @@ import type { AddressInfo } from "node:net"
|
|
|
11
11
|
const DEFAULT_PORT = 5959
|
|
12
12
|
const DEFAULT_PORT_RANGE = 10
|
|
13
13
|
|
|
14
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
15
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
16
|
+
}
|
|
17
|
+
|
|
14
18
|
export interface AuthCallback {
|
|
15
19
|
apiKey: string
|
|
16
20
|
state: string
|
|
@@ -92,13 +96,10 @@ export async function startAuthServer(options: AuthServerOptions = {}): Promise<
|
|
|
92
96
|
})
|
|
93
97
|
|
|
94
98
|
const server = createServer((req, res) => {
|
|
95
|
-
// CORS: allow requests from Command Code
|
|
99
|
+
// CORS: allow requests from the Command Code Studio origins only. A local
|
|
100
|
+
// development origin would let any page on that port reach the callback.
|
|
96
101
|
const origin = req.headers.origin || ""
|
|
97
|
-
const allowedOrigins = [
|
|
98
|
-
"http://localhost:3000",
|
|
99
|
-
"https://staging.commandcode.ai",
|
|
100
|
-
"https://commandcode.ai",
|
|
101
|
-
]
|
|
102
|
+
const allowedOrigins = ["https://commandcode.ai", "https://staging.commandcode.ai"]
|
|
102
103
|
// CORS response headers do not prevent cross-origin POST side effects.
|
|
103
104
|
// Reject untrusted browser origins before handling the callback.
|
|
104
105
|
if (origin && !allowedOrigins.includes(origin)) {
|
|
@@ -155,29 +156,43 @@ export async function startAuthServer(options: AuthServerOptions = {}): Promise<
|
|
|
155
156
|
|
|
156
157
|
req.on("end", () => {
|
|
157
158
|
try {
|
|
158
|
-
const
|
|
159
|
+
const payload: unknown = JSON.parse(body)
|
|
160
|
+
if (!isRecord(payload)) {
|
|
161
|
+
res.writeHead(400)
|
|
162
|
+
res.end(JSON.stringify({ success: false, error: "Invalid JSON" }))
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
const state = typeof payload.state === "string" ? payload.state : ""
|
|
159
166
|
|
|
160
|
-
|
|
167
|
+
// Only the page that received the state token may settle this login,
|
|
168
|
+
// including by reporting an error. Anything else keeps the server
|
|
169
|
+
// waiting for the legitimate callback.
|
|
170
|
+
if (options.expectedState !== undefined && state !== options.expectedState) {
|
|
171
|
+
res.writeHead(403)
|
|
172
|
+
res.end(JSON.stringify({ success: false, error: "Invalid state token" }))
|
|
173
|
+
return
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (payload.error) {
|
|
161
177
|
res.writeHead(200)
|
|
162
178
|
res.end(JSON.stringify({ success: true }))
|
|
163
179
|
const description =
|
|
164
|
-
typeof
|
|
165
|
-
?
|
|
166
|
-
: String(
|
|
167
|
-
if (
|
|
180
|
+
typeof payload.error_description === "string"
|
|
181
|
+
? payload.error_description
|
|
182
|
+
: String(payload.error)
|
|
183
|
+
if (payload.error === "access_denied") {
|
|
168
184
|
rejectCallback(new Error(description || "Authorization was denied by the user"))
|
|
169
185
|
} else {
|
|
170
|
-
rejectCallback(new Error(description || String(
|
|
186
|
+
rejectCallback(new Error(description || String(payload.error)))
|
|
171
187
|
}
|
|
172
188
|
closeServer(server)
|
|
173
189
|
return
|
|
174
190
|
}
|
|
175
191
|
|
|
176
|
-
const apiKey = typeof
|
|
177
|
-
const
|
|
178
|
-
const
|
|
179
|
-
const
|
|
180
|
-
const keyName = typeof parsed.keyName === "string" ? parsed.keyName : ""
|
|
192
|
+
const apiKey = typeof payload.apiKey === "string" ? payload.apiKey : ""
|
|
193
|
+
const userId = typeof payload.userId === "string" ? payload.userId : ""
|
|
194
|
+
const userName = typeof payload.userName === "string" ? payload.userName : ""
|
|
195
|
+
const keyName = typeof payload.keyName === "string" ? payload.keyName : ""
|
|
181
196
|
|
|
182
197
|
if (!apiKey || !state || !userId || !userName || !keyName) {
|
|
183
198
|
res.writeHead(400)
|
|
@@ -190,12 +205,6 @@ export async function startAuthServer(options: AuthServerOptions = {}): Promise<
|
|
|
190
205
|
return
|
|
191
206
|
}
|
|
192
207
|
|
|
193
|
-
if (options.expectedState !== undefined && state !== options.expectedState) {
|
|
194
|
-
res.writeHead(403)
|
|
195
|
-
res.end(JSON.stringify({ success: false, error: "Invalid state token" }))
|
|
196
|
-
return
|
|
197
|
-
}
|
|
198
|
-
|
|
199
208
|
res.writeHead(200)
|
|
200
209
|
res.end(JSON.stringify({ success: true }))
|
|
201
210
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export const COMMAND_CODE_CLI_VERSION = "1.88.
|
|
1
|
+
export const COMMAND_CODE_CLI_VERSION = "1.88.2"
|
|
2
2
|
|
|
3
3
|
export type CommandCodeInputType = "text" | "image"
|
|
4
4
|
export type CommandCodeReasoningEffort =
|
|
@@ -11,7 +11,7 @@ export type CommandCodeReasoningEffort =
|
|
|
11
11
|
| "max"
|
|
12
12
|
|
|
13
13
|
/**
|
|
14
|
-
* Generated from command-code@1.88.
|
|
14
|
+
* Generated from command-code@1.88.2 by `npm run sync:commandcode-catalog`.
|
|
15
15
|
* Do not edit manually.
|
|
16
16
|
*/
|
|
17
17
|
export const MODEL_INPUT_MODALITIES: Readonly<Record<string, readonly CommandCodeInputType[]>> = {
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { createHash } from "node:crypto"
|
|
2
|
-
import { existsSync, readFileSync } from "node:fs"
|
|
3
|
-
import { homedir } from "node:os"
|
|
4
|
-
import { join } from "node:path"
|
|
5
2
|
|
|
6
3
|
import type { MessageLike, StopReason, ToolLike } from "./types.ts"
|
|
7
4
|
import { geminiSafeJsonSchema, toJsonSchema } from "./json-schema.ts"
|
|
8
5
|
|
|
9
6
|
export { toJsonSchema } from "./json-schema.ts"
|
|
7
|
+
// The generate transport reads ambient credentials through the same reader
|
|
8
|
+
// as the Provider API path and the quota commands (README "Auth file" order).
|
|
9
|
+
export { getConfiguredApiKey as getApiKey } from "./api-key.ts"
|
|
10
10
|
|
|
11
11
|
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
12
12
|
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
@@ -38,24 +38,6 @@ export function numberValue(value: unknown): number | undefined {
|
|
|
38
38
|
return typeof value === "number" && Number.isFinite(value) ? value : undefined
|
|
39
39
|
}
|
|
40
40
|
|
|
41
|
-
function defaultAuthPaths(home: string): string[] {
|
|
42
|
-
return [
|
|
43
|
-
join(home, ".commandcode", "auth.json"),
|
|
44
|
-
join(home, ".omp", "agent", "auth.json"),
|
|
45
|
-
join(home, ".pi", "agent", "auth.json"),
|
|
46
|
-
]
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
function apiKeyFromCredentialRecord(value: unknown): string | undefined {
|
|
50
|
-
if (!isRecord(value)) return undefined
|
|
51
|
-
|
|
52
|
-
const type = stringValue(value.type)
|
|
53
|
-
if (type === "api") return stringValue(value.key)
|
|
54
|
-
if (type === "oauth") return stringValue(value.access)
|
|
55
|
-
|
|
56
|
-
return stringValue(value.key) ?? stringValue(value.access)
|
|
57
|
-
}
|
|
58
|
-
|
|
59
41
|
function imageParts(value: unknown): readonly Record<string, unknown>[] {
|
|
60
42
|
if (isRecord(value)) return value.type === "image" ? [value] : []
|
|
61
43
|
return recordArray(value).filter((part) => part.type === "image")
|
|
@@ -99,46 +81,6 @@ function userContentToCommandCode(content: unknown, allowImages: boolean): unkno
|
|
|
99
81
|
})
|
|
100
82
|
}
|
|
101
83
|
|
|
102
|
-
export function getApiKey(
|
|
103
|
-
options: {
|
|
104
|
-
env?: NodeJS.ProcessEnv
|
|
105
|
-
authPaths?: readonly string[]
|
|
106
|
-
homeDir?: () => string
|
|
107
|
-
} = {},
|
|
108
|
-
): string | undefined {
|
|
109
|
-
const env = options.env ?? process.env
|
|
110
|
-
if (env.COMMAND_CODE_API_KEY) return env.COMMAND_CODE_API_KEY
|
|
111
|
-
if (env.COMMANDCODE_API_KEY) return env.COMMANDCODE_API_KEY
|
|
112
|
-
|
|
113
|
-
const home = options.homeDir?.() ?? homedir()
|
|
114
|
-
const authPaths = options.authPaths ?? defaultAuthPaths(home)
|
|
115
|
-
|
|
116
|
-
for (const authPath of authPaths) {
|
|
117
|
-
try {
|
|
118
|
-
if (!existsSync(authPath)) continue
|
|
119
|
-
const parsed: unknown = JSON.parse(readFileSync(authPath, "utf-8"))
|
|
120
|
-
if (!isRecord(parsed)) continue
|
|
121
|
-
|
|
122
|
-
// Legacy: direct apiKey or commandcode field.
|
|
123
|
-
const apiKey = stringValue(parsed.apiKey)
|
|
124
|
-
if (apiKey) return apiKey
|
|
125
|
-
const commandcode = stringValue(parsed.commandcode)
|
|
126
|
-
if (commandcode) return commandcode
|
|
127
|
-
|
|
128
|
-
// pi stores OAuth credentials as {"commandcode": {"type":"oauth","access":"..."}}.
|
|
129
|
-
// The official Command Code CLI stores API credentials under "command-code".
|
|
130
|
-
const providerKey =
|
|
131
|
-
apiKeyFromCredentialRecord(parsed.commandcode) ??
|
|
132
|
-
apiKeyFromCredentialRecord(parsed["command-code"])
|
|
133
|
-
if (providerKey) return providerKey
|
|
134
|
-
} catch {
|
|
135
|
-
// Ignore malformed or unreadable auth files.
|
|
136
|
-
}
|
|
137
|
-
}
|
|
138
|
-
|
|
139
|
-
return undefined
|
|
140
|
-
}
|
|
141
|
-
|
|
142
84
|
// Hosts such as OMP may pass a literal env-var name as the "resolved" registry
|
|
143
85
|
// key instead of the actual credential. Treat those as unresolved.
|
|
144
86
|
export const COMMAND_CODE_PLACEHOLDER_KEYS = new Set([
|
|
@@ -149,6 +149,18 @@ function mappedReasoningEffort(model: ModelLike, options?: StreamOptions): strin
|
|
|
149
149
|
return typeof mapped === "string" && mapped !== "off" ? mapped : undefined
|
|
150
150
|
}
|
|
151
151
|
|
|
152
|
+
/**
|
|
153
|
+
* Whether the generate request opts the account into Command Code's
|
|
154
|
+
* server-side taste learning. The official CLI sends its `tasteLearning`
|
|
155
|
+
* setting on every request (default on). This extension never reads the
|
|
156
|
+
* learned profile back, so learning is off unless the user enables it, and
|
|
157
|
+
* always off under the zero-data-retention flag.
|
|
158
|
+
*/
|
|
159
|
+
export function tasteLearningEnabled(env: NodeJS.ProcessEnv): boolean {
|
|
160
|
+
if (env.CMD_ZDR === "1" || env.COMMANDCODE_ZDR === "1") return false
|
|
161
|
+
return env.COMMANDCODE_TASTE_LEARNING === "1"
|
|
162
|
+
}
|
|
163
|
+
|
|
152
164
|
function isUuid(value: string): boolean {
|
|
153
165
|
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
|
|
154
166
|
}
|
|
@@ -165,6 +177,7 @@ export function projectSlugFromPath(pathName: string): string {
|
|
|
165
177
|
export function createStreamCommandCode(deps: CoreDependencies) {
|
|
166
178
|
const apiBase = deps.apiBase ?? DEFAULT_API_BASE
|
|
167
179
|
const fetchImpl = deps.fetchImpl ?? fetch
|
|
180
|
+
const env = () => deps.env ?? process.env
|
|
168
181
|
const cwd = deps.cwd ?? (() => process.cwd())
|
|
169
182
|
const now = deps.now ?? (() => Date.now())
|
|
170
183
|
const uuid = deps.uuid ?? (() => randomUUID())
|
|
@@ -588,16 +601,22 @@ export function createStreamCommandCode(deps: CoreDependencies) {
|
|
|
588
601
|
|
|
589
602
|
const maxRetries = options?.maxRetries ?? DEFAULT_MAX_RETRIES
|
|
590
603
|
const maxRetryDelayMs = effectiveMaxRetryDelayMs(options?.maxRetryDelayMs)
|
|
604
|
+
// The privacy policy is authoritative even for differently cased caller headers.
|
|
605
|
+
const callerHeaders = Object.fromEntries(
|
|
606
|
+
Object.entries(options?.headers ?? {}).filter(
|
|
607
|
+
([name]) => name.toLowerCase() !== "x-taste-learning",
|
|
608
|
+
),
|
|
609
|
+
)
|
|
591
610
|
const requestHeaders = {
|
|
592
611
|
"Content-Type": "application/json",
|
|
593
612
|
Authorization: `Bearer ${apiKey}`,
|
|
594
613
|
"x-command-code-version": COMMAND_CODE_CLI_VERSION,
|
|
595
614
|
"x-cli-environment": "production",
|
|
596
615
|
"x-project-slug": projectSlugFromPath(workingDir),
|
|
597
|
-
"x-taste-learning":
|
|
616
|
+
"x-taste-learning": String(tasteLearningEnabled(env())),
|
|
598
617
|
...(options?.sessionId ? { "x-session-id": options.sessionId } : {}),
|
|
599
618
|
"User-Agent": "cli",
|
|
600
|
-
...
|
|
619
|
+
...callerHeaders,
|
|
601
620
|
}
|
|
602
621
|
const bodyStr = JSON.stringify(body)
|
|
603
622
|
|
|
@@ -745,9 +764,15 @@ export function createStreamCommandCode(deps: CoreDependencies) {
|
|
|
745
764
|
} catch {}
|
|
746
765
|
reader = undefined
|
|
747
766
|
|
|
767
|
+
// The per-attempt timer aborts `attemptController`, so a stalled
|
|
768
|
+
// body surfaces as an AbortError here. Classify it as a timeout
|
|
769
|
+
// before the user-abort check, or it would be reported as a
|
|
770
|
+
// cancellation and never retried.
|
|
771
|
+
if (controller.signal.aborted) throw streamError
|
|
748
772
|
if (
|
|
749
|
-
|
|
750
|
-
|
|
773
|
+
!attemptTimedOut &&
|
|
774
|
+
streamError instanceof Error &&
|
|
775
|
+
streamError.name === "AbortError"
|
|
751
776
|
) {
|
|
752
777
|
throw streamError
|
|
753
778
|
}
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* `tests/test-cost.ts` locks this implementation to the pi-ai original.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import type { ModelCostRates, ModelLike, Usage } from "./types.ts"
|
|
10
|
+
import type { ModelCost, ModelCostRates, ModelCostTier, ModelLike, Usage } from "./types.ts"
|
|
11
11
|
|
|
12
12
|
const DEEPSEEK_V4_TIME_PRICED_MODELS = new Set([
|
|
13
13
|
"deepseek/deepseek-v4-pro",
|
|
@@ -30,18 +30,9 @@ export function isDeepSeekV4Peak(atMs: number): boolean {
|
|
|
30
30
|
return (hour >= 1 && hour < 4) || (hour >= 6 && hour < 10)
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
|
|
34
|
-
* Select request-time rates for both the native provider transport and the
|
|
35
|
-
* local generate fallback. DeepSeek V4 peak rates are exactly 2x off-peak.
|
|
36
|
-
*/
|
|
37
|
-
export function commandCodeCostRatesAt(
|
|
38
|
-
modelId: string,
|
|
39
|
-
rates: ModelCostRates,
|
|
40
|
-
atMs: number = Date.now(),
|
|
41
|
-
): ModelCostRates {
|
|
42
|
-
if (!DEEPSEEK_V4_TIME_PRICED_MODELS.has(modelId) || !isDeepSeekV4Peak(atMs)) return rates
|
|
43
|
-
|
|
33
|
+
function doubledRates<T extends ModelCostRates>(rates: T): T {
|
|
44
34
|
return {
|
|
35
|
+
...rates,
|
|
45
36
|
input: rates.input * 2,
|
|
46
37
|
output: rates.output * 2,
|
|
47
38
|
cacheRead: rates.cacheRead * 2,
|
|
@@ -49,6 +40,35 @@ export function commandCodeCostRatesAt(
|
|
|
49
40
|
}
|
|
50
41
|
}
|
|
51
42
|
|
|
43
|
+
/**
|
|
44
|
+
* Select request-time rates for both the native provider transport and the
|
|
45
|
+
* local generate fallback. DeepSeek V4 peak rates are exactly 2x off-peak.
|
|
46
|
+
* Context tiers on a full model cost table are kept and doubled alongside
|
|
47
|
+
* the base rates so the host's tier selection still applies during peak.
|
|
48
|
+
*/
|
|
49
|
+
export function commandCodeCostRatesAt<
|
|
50
|
+
T extends ModelCostRates & { tiers?: readonly ModelCostTier[] },
|
|
51
|
+
>(modelId: string, rates: T, atMs: number = Date.now()): T {
|
|
52
|
+
if (!DEEPSEEK_V4_TIME_PRICED_MODELS.has(modelId) || !isDeepSeekV4Peak(atMs)) return rates
|
|
53
|
+
|
|
54
|
+
const doubled = doubledRates(rates)
|
|
55
|
+
if (!rates.tiers) return doubled
|
|
56
|
+
return { ...doubled, tiers: rates.tiers.map((tier) => doubledRates(tier)) }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Native hosts accept mutable cost tiers, while our catalog is readonly.
|
|
61
|
+
* Give the host its own table, array, and tier objects at that boundary.
|
|
62
|
+
*/
|
|
63
|
+
export function commandCodeNativeCostRatesAt(
|
|
64
|
+
modelId: string,
|
|
65
|
+
rates: ModelCost,
|
|
66
|
+
atMs: number = Date.now(),
|
|
67
|
+
): ModelCostRates & { tiers?: ModelCostTier[] } {
|
|
68
|
+
const selected = commandCodeCostRatesAt(modelId, rates, atMs)
|
|
69
|
+
return { ...selected, tiers: selected.tiers?.map((tier) => ({ ...tier })) }
|
|
70
|
+
}
|
|
71
|
+
|
|
52
72
|
export function calculateCommandCodeCost(
|
|
53
73
|
model: ModelLike,
|
|
54
74
|
usage: Usage,
|
|
@@ -20,6 +20,8 @@ const STUDIO_BASE_URL = "https://commandcode.ai"
|
|
|
20
20
|
const TEN_YEARS_MS = 10 * 365 * 24 * 60 * 60 * 1000 // API keys don't expire
|
|
21
21
|
const DEFAULT_AUTH_TIMEOUT_MS = 120_000
|
|
22
22
|
const DEFAULT_API_BASE = "https://api.commandcode.ai"
|
|
23
|
+
const DEFAULT_PROVIDER_API_BASE = `${DEFAULT_API_BASE}/provider/v1`
|
|
24
|
+
export const VALIDATE_API_KEY_TIMEOUT_MS = 15_000
|
|
23
25
|
|
|
24
26
|
export interface OAuthLoginCallbacks {
|
|
25
27
|
onAuth(params: { url: string }): void
|
|
@@ -96,22 +98,54 @@ export function sanitizeApiKey(input: string): string {
|
|
|
96
98
|
.trim()
|
|
97
99
|
}
|
|
98
100
|
|
|
101
|
+
/**
|
|
102
|
+
* Base of the alpha endpoints used for key validation. Mirrors index.ts: the
|
|
103
|
+
* configured `COMMANDCODE_API_BASE` is the Provider API base, and the alpha
|
|
104
|
+
* endpoints live next to it without the `/provider/v1` suffix.
|
|
105
|
+
*/
|
|
106
|
+
export function validationApiBase(env: NodeJS.ProcessEnv = process.env): string {
|
|
107
|
+
const providerApiBase = env.COMMANDCODE_API_BASE ?? DEFAULT_PROVIDER_API_BASE
|
|
108
|
+
return providerApiBase.replace(/\/provider\/v1\/?$/, "")
|
|
109
|
+
}
|
|
110
|
+
|
|
99
111
|
export async function validateApiKey(
|
|
100
112
|
apiKey: string,
|
|
101
|
-
options: { fetchImpl?: typeof fetch; apiBase?: string } = {},
|
|
113
|
+
options: { fetchImpl?: typeof fetch; apiBase?: string; timeoutMs?: number } = {},
|
|
102
114
|
): Promise<void> {
|
|
115
|
+
const timeoutMs = options.timeoutMs ?? VALIDATE_API_KEY_TIMEOUT_MS
|
|
116
|
+
// AbortSignal is cooperative: a custom fetch may ignore it, so the deadline
|
|
117
|
+
// also races the request. /login must never hang on a stalled whoami.
|
|
118
|
+
const controller = new AbortController()
|
|
119
|
+
let rejectDeadline: ((error: Error) => void) | undefined
|
|
120
|
+
const deadline = new Promise<never>((_resolve, reject) => {
|
|
121
|
+
rejectDeadline = reject
|
|
122
|
+
})
|
|
123
|
+
const timer = setTimeout(() => {
|
|
124
|
+
const error = new Error(
|
|
125
|
+
`Could not validate the Command Code API key: request timed out after ${timeoutMs}ms`,
|
|
126
|
+
)
|
|
127
|
+
controller.abort(error)
|
|
128
|
+
rejectDeadline?.(error)
|
|
129
|
+
}, timeoutMs)
|
|
130
|
+
|
|
103
131
|
let response: Response
|
|
104
132
|
try {
|
|
105
|
-
response = await
|
|
106
|
-
`${options.apiBase ??
|
|
107
|
-
{
|
|
133
|
+
response = await Promise.race([
|
|
134
|
+
(options.fetchImpl ?? fetch)(`${options.apiBase ?? validationApiBase()}/alpha/whoami`, {
|
|
108
135
|
headers: { Authorization: `Bearer ${apiKey}` },
|
|
109
|
-
|
|
110
|
-
|
|
136
|
+
signal: controller.signal,
|
|
137
|
+
}),
|
|
138
|
+
deadline,
|
|
139
|
+
])
|
|
111
140
|
} catch (error) {
|
|
141
|
+
if (controller.signal.aborted && controller.signal.reason instanceof Error) {
|
|
142
|
+
throw controller.signal.reason
|
|
143
|
+
}
|
|
112
144
|
throw new Error(
|
|
113
145
|
`Could not validate the Command Code API key: ${error instanceof Error ? error.message : String(error)}`,
|
|
114
146
|
)
|
|
147
|
+
} finally {
|
|
148
|
+
clearTimeout(timer)
|
|
115
149
|
}
|
|
116
150
|
|
|
117
151
|
if (response.status === 401) throw new Error("Invalid Command Code API key")
|