750B Weights, 3T Brain? GLM-5.4 Seven Days Later: Loop Transformer, Generalized Coding, Marathon Thinking Timeouts & 3-OS Auto-Config Scripts
First a reality check, then the playbook: when Z.ai (Zhipu AI) dropped GLM-5.4 on November 23, 2026, it delivered arguably the most counter-intuitive flagship architecture of the season. Instead of inflating parameter count into the multi-trillions, Z.ai took its 750B GLM-5 base model and looped 28 middle layers through two iterations per forward pass—claiming 2T–3T-class reasoning without expanding weight memory. Seven days in, however, developer channels are split down the middle: half of the room is raving about GLM-5.4 rendering music videos purely from frontend code, sculpting 6-axis robotic arms in FreeCAD, and chewing through 1M-context refactors; the other half is tearing their hair out over 404 Model Not Found errors, two-minute “marathon thinking” stalls on single-line CSS edits, and surprise account-balance charges despite holding an active Coding Plan subscription.
After cross-checking the official launch blog (z.ai/blog/glm-5.4), BigModel / Z.ai developer docs, the ZCode v4.0.0 changelog, and live billing telemetry rules, the reason for that split becomes crystal clear: both camps are reacting to the exact same design choices. GLM-5.4 genuinely pushes computational depth forward with Loop Transformer, per-token Damp Gates, and Two-Bank Sparse MLA; yet it launched without a full 750B public benchmark leaderboard, with standard API access and open weights still queued behind safety hardening, right on top of Z.ai’s October 16 API Key isolation, an invisible default max reasoning effort trap in Claude Code, and a 2× weekday peak-hour credit window (14:00–18:00 UTC+8).
Below, we unpack the entire architecture with 15 real screenshots and original Huashu-style diagrams, plain-English everyday analogies an elementary student can follow, and zero-dependency automation scripts for Windows 11, Ubuntu 26.04, and macOS 27 (supporting both human interactive setup and unattended AI Agent execution).

Figure 1: Original panoramic overview. Core specs (750B base -> 2T–3T reasoning ceiling, 1M context / 128K output, 200 tok/s off-peak, 1.5× weekly quota boost) alongside the four real-world setup traps.
1. Background: The November 23 Bet on Depth Over Parameter Bloat
On November 23, 2026, Z.ai (z.ai globally and bigmodel.cn in mainland China) rolled out GLM-5.4 alongside ZCode v4.0.0, its official multi-agent coding workspace built specifically around the new model.

Figure 2: Live browser capture of z.ai/blog/glm-5.4 published on November 23, 2026: GLM-5.4: Toward Generalized Coding with Our First Loop Transformer.
On paper, the headline spec sheet already checks several major boxes:
- Multimodal Input: Native video, image, text, and file ingestion (powered by projected 24-layer ViT visual features), producing text/code output;
- Context & Generation: 1M-token context window and 128K maximum output tokens;
- Serving Throughput: Up to 200 tokens/s during off-peak hours and a steady 70–80 tokens/s at peak load;
- 1.5× Weekly Coding Quota: Immediately live for all GLM Coding Plan tiers (Lite, Pro, Max, and Team), where lower per-token credit multipliers give weekly subscribers 1.5× more usable tokens than GLM-5.3.

Figure 3: Official model documentation page (docs.bigmodel.cn/cn/guide/models/glm-5.4), noting 2T–3T-equivalent intelligence, 1M context, 128K max output, the tendency to enter prolonged thinking loops, and pending API safety evaluation.
What actually shook up engineering teams, however, was the convergence of three structural shifts:
- Loop Transformer at Flagship Scale: Instead of training an even heavier multi-trillion-parameter monolith from scratch, Z.ai validated Scaling Loop—running shared middle layers twice on a 750B base model;
- Generalized Coding: Coding expands from software engineering into a universal control plane for real-time frontend video rendering, custom 3D GLSL shaders, complete playable games, and FreeCAD mechanical engineering;
- Subscription-First Rollout Friction: Because pay-as-you-go public APIs (
z.ai/model-api) and open weights are still awaiting safety hardening, almost every developer hit GLM-5.4 through GLM Coding Plan inside ZCode, Claude Code, Codex, Cline, and Cursor—where legacy endpoints and hidden defaults cause immediate breakage.
2. Symptoms in the Wild: Four Ways Developers Trip on Day One
Looking across community threads and developer troubleshooting reports from the past seven days, nearly every painful migration failure falls into one of four predictable symptoms:
- Symptom 1: Two-minute freezes and client timeouts on tiny edits
You swap Claude Code over toglm-5.4[1m], ask it to rename a helper or tweak CSS padding, and watch the spinner sit frozen for 90+ seconds until your IDE or CLI drops the socket. Z.ai openly acknowledges this behavior in its release notes as "marathon thinking" loops. - Symptom 2: Following an older guide still throws
404 Model Not Found
Either a Standard pay-as-you-go API Key was pasted instead of a Coding Plan Key, the request hit the standard/api/paas/v4route (where GLM-5.4 isn't live yet), or an older Claude Code build omitted the mandatory[1m]suffix. - Symptom 3: Subscribed to GLM Coding Plan, yet account cash balance keeps dropping
The nastiest billing surprise. On October 16, 2026, Z.ai permanently separated Standard API Keys, Personal Coding Plan Keys, and Team Plan Keys. Using a post-Oct-16 Standard Key—even against a Coding endpoint—bills your cash balance, and pre-Oct-16 Compatible Keys pointed at/api/paas/v4do the exact same thing. - Symptom 4: "1.5× more quota" vanishes in two afternoons
Mapping every single Claude Code alias (OPUS,SONNET,HAIKU) toglm-5.4[1m]forces a 750B Loop Transformer to handle trivial file searches—especially lethal if you leave auto-compaction at 1M tokens and work inside the Mon–Fri 14:00–18:00 (UTC+8) 2× peak window.
Before blaming the model, let’s crack open what GLM-5.4 actually does inside a forward pass—because every single symptom above traces straight back to the architecture and billing mechanics.
3. Architecture Under the Hood: Loop Transformer Explained Simply
Research blogs love phrases like “iterative residual refinement over Two-Bank Sparse MLA.” Let’s strip away the jargon using an everyday scenario an elementary student immediately gets: taking a tough math exam.

Figure 4: Original everyday-analogy blueprint translating GLM-5.4’s Loop Core, Damp Gates, Hybrid KV Cache, and Sparse Index Reuse into plain intuitions.
3.1 Buying a 3× Larger Backpack vs. Double-Checking the Middle 28 Steps
A traditional Transformer is a strictly one-way exam assembly line. A 78-layer model gives every token exactly one chance to pass through Layers 1 to 78. Want deeper multi-step reasoning? Normally you have to buy a 3× bigger backpack—bloating weights from 750B up to 2T–3T parameters and blowing up VRAM and serving bills.
As Z.ai noted in its earlier GLM-5.3 blog: memory-heavy trivia benefits from more parameters, but long-horizon reasoning (large codebases, cybersecurity, 3D geometry) benefits from more effective compute per token.
So instead of pre-training from scratch, Z.ai took its pre-trained 750B GLM-5 base (78 layers) and applied continued training to turn the middle into a loop:
- Prelude (
L1–26, 26 layers): Text embeddings plus projected 24-layer ViT visual features enter here. These first 26 layers read the problem statement and organize the facts. - Loop Core (
L27–54, 28 layers × 2 passes): Instead of moving straight on after Layer 54, the model feeds intermediate statex₁right back into Layer 27 and runs the exact same 28 layers a second time! Physically it still stores only 78 layers of weights, yet every token experiences26 + 28 × 2 + 24 = 106effective layer-passes of compute. - Coda (
L55–78, 24 layers): Takes the double-checked hidden statex₂through the final 24 layers, Final RMSNorm, and the LM Head to write out a clean final answer.

Figure 5: Real browser capture from z.ai/blog/glm-5.4 detailing Prelude (L1–26), Loop Pass 1 (L27–54), Damp Gate 1 & 2, Per-Layer Cache (k = 2048), Loop Pass 2 (Two-Bank Sparse MLA + 128-tok SWA), and Coda (L55–78).
3.2 Why Naive Loops Blow Up—and the 3 Surgical Fixes at 750B
Looping an already-trained 750B model is notoriously dangerous: activation magnitudes explode, memory doubles at 1M context, and sparse attention has to re-scan indices twice. Z.ai solved those three failure modes with surgical precision:
- Fix 1: Damp Gates (
x₁ = x₀ + β₁(h₁ - x₀)) — Like a Carpenter's Depth-Adjusting Chisel
Blindly overwriting hidden states on Pass 2 breaks downstream LayerNorm expectations in Layers 55–78. GLM-5.4 inserts a per-token sigmoid gateβ = σ(Linear(RMSNorm(x)))at each loop pass. Remarkably, training naturally taught the two passes a clean division of labor: Pass 1 opens the gate only slightly to sketch stable global context without blowing up norms; Pass 2 opens the gate wide to carve fine details—and dynamically pushes harder on Pass 1 whenever a token is unusually unpredictable. - Fix 2: Hybrid KV Cache (Two-Bank Sparse MLA) — Like Bringing One Sticky Note to an Open-Book Exam
Storing two complete 1M-token KV caches would double serving memory. Instead, Pass 2's Two-Bank Sparse MLA computes a single Softmax across two lightweight banks: it reuses the sparse KV latent prefix already cached in Pass 1, and allocates fresh Pass-2 KV storage only inside a tiny128-tokenlocal sliding window (SWA). Double the reasoning depth at 1M context, for virtually one sticky note of extra KV memory. - Fix 3: Sparse Attention Index Reuse — Bookmarking the Dictionary Once
Look closely at the official diagram for Pass 2: "No indexer in Pass 2." Every DSA group in Pass 1 picks the topk = 2048relevant tokens; Pass 2 simply reuses those exact indices with zero indexing overhead. Paired with custom fused kernels that eliminate intermediate memory round-trips, GLM-5.4 achieves up to 200 tokens/s off-peak and 70–80 tokens/s peak.
3.3 The 30B Iso-Parameter Ablation: Higher Intelligence, 10–14% Fewer Tokens
Z.ai verified “Scaling Correctness” progressively across 1B, 4B, 30B, and 750B scales. On a controlled 30B iso-parameter benchmark (identical weights, 200K long-context SFT, ~10% extra training compute, thinking mode on), looping revealed two striking patterns:

Figure 6: Official 30B controlled ablation table from z.ai/blog/glm-5.4 comparing Baseline vs. + Loop scores and average output length deltas.

Figure 7: Original breakdown contrasting the 30B ablation wins against the three caveats every engineering lead should keep in mind.
- Longer reasoning chains profit most: Knowledge/instruction benchmarks ticked up modestly (
MMLU-Pro +3.4to 75.05,IFBench +3.3to 53.47), while multi-step reasoning jumped sharply:AA-LCR +7.3(47.67),GPQA-Diamond +8.7(56.26), and competition mathAIME25 +11.3(19.17 → 30.42). - Implicit compute trims explicit verbosity: Average output length dropped 11.7% on GPQA-Diamond (-2,473 tokens) and 14.9% on MMLU-Pro—meaning the loop resolves dead ends silently inside hidden states rather than rambling aloud.
To stay intellectually honest, keep the caveats front and center: seven days post-launch, Z.ai still has not published a full 750B third-party benchmark table (relying on the 30B ablation and an internal 200-scenario coding evaluation), public APIs and open weights are still gated behind safety hardening, and multi-turn agent loops can still trigger prolonged “marathon thinking.”
4. Generalized Coding & ZCode v4.0.0: Beyond Text Buffers
Pair the 24-layer ViT vision encoder with two-pass loop reasoning and Z.ai’s push toward Generalized Coding makes immediate sense:
- Video Generation via Frontend Code: Creator Mike Luan produced GLM-5.4's self-narrated music video "Hello world" end-to-end—rendering every visual frame purely via live frontend code (zero image assets) while letting the model orchestrate music prompts across chapters;
- Pure-Math 3D & Shaders: Without importing a single external 3D mesh or texture, creator Yeshenbushuohua prompted GLM-5.4 to write pure mathematical geometry and custom GLSL shaders rendering an interactive macro long-tailed tit bird that breathes and blinks;
- Mechanical CAD & Simulation: Driving FreeCAD via code to construct a 6-axis robotic arm, then scripting Blender motion choreography and audio synthesis;
- ZCode v4.0.0: Released November 23, 2026 with pre-configured GLM-5.4 support, region-aware plugins, batched archive checks, and fixes for startup hangs and lost context when switching providers.

Figure 8: Live capture of zcode.z.ai/en/changelog showing ZCode 4.0.0 shipped November 23, 2026 with native GLM-5.4 support and session-recovery fixes.

Figure 9: Official z.ai/subscribe landing page showing single-subscription support across ZCode, AutoClaw, Claude Code, Codex, WorkBuddy, TraeWork, CodeBuddy, TraeCode, OpenCode, Cursor, and OpenClaw.
5. Root Causes: Why Your Setup Fails, Stalls, or Drains Cash
Now let’s trace the exact backend rules responsible for those four Day-1 failures.

Figure 10: Original triage decision matrix covering 404 Model Not Found, accidental balance billing, Marathon Thinking timeouts, context bloat, and China/Global endpoints.
Root Cause 1: The Hidden effort Default-to-max Trap + Short Client Timeouts
Think of hiring a national math Olympiad champion to fix a typo in a two-sentence homework note—except you forgot to tell him “take it easy,” and his house rule says “whenever nobody specifies how hard to think, default to 100% championship proof mode."
Look at Z.ai’s official How to Switch Models spec:

Figure 11: Official model-switching documentation showing 512000 auto-compact guidance, endpoint paths, and Claude Code’s /effort priority chain.
Whenever thinking isn’t explicitly turned off and reasoning_effort is omitted, blank, or unrecognized, GLM-5.4 automatically falls back to max effort! Combine that with default 60s HTTP timeouts in unconfigured clients, and long Loop Transformer passes get severed mid-thought and retried over and over unless you explicitly set “API_TIMEOUT_MS”: “3000000”.
Root Cause 2: October 16 Key Isolation & Standard Endpoint Billing Leak
Think of a university dining hall after an October 16 card-reader upgrade: previously one campus card worked at both the meal-plan counter and the snack shop; now a cash-card swiped at the meal-plan window still pulls real cash or gets rejected outright.
Per the October 16, 2026 API Key Management Guide:
- Post-Oct 16 Keys Are Strictly Scoped: A
Standard API Keyalways bills cash balance (and cannot call GLM-5.4 while public API safety evals are pending). Personal Coding Plan Keys must be generated under Personal Coding Plan → Plan Overview, and Team keys under Team Coding Plan → My Plan. Changing Base URLs does NOT change how a post-Oct 16 key bills. - Pre-Oct 16 "Compatible Keys" Follow the Base URL: Pointing a legacy Compatible Key at standard
/api/paas/v4bypasses your Coding Plan quota and bills your cash balance immediately. - Exact Endpoints by Region:
- Global (Z.ai): Anthropic →
https://api.z.ai/api/anthropic· OpenAI Coding →https://api.z.ai/api/coding/paas/v4· Codex →https://api.z.ai/api/v1 - China (BigModel): Anthropic →
https://open.bigmodel.cn/api/anthropic· OpenAI Coding →https://open.bigmodel.cn/api/coding/paas/v4· Codex →https://open.bigmodel.cn/api/v1
- Global (Z.ai): Anthropic →
Root Cause 3: The Official Credit Math Behind the 8× Quota Spread
Think of residential electricity tariffs: weekday afternoon peak hours (14:00–18:00 UTC+8) charge full commercial rates, off-peak hours and all weekends cost half price, and the smaller inverter AC unit (GLM-5.3-Flash) is running a 50%-off seasonal discount from November 24 to December 24.

Figure 12: Official credit deduction multipliers per 10,000 tokens (GLM-5.4: 4.6 / 1.1 / 16 vs. GLM-5.3: 6.9 / 1.7 / 24 vs. GLM-5.3-Flash promo: 1.15 / 0.28 / 4) and the Mon–Fri 14:00–18:00 (UTC+8) peak rule.

Figure 13: Original credit economics chart showing why 100K output tokens spans from 160 credits (Peak GLM-5.4) down to 20 credits (Off-Peak 5.3-Flash)—an 8× difference.
And notice the context-window nuance too: BigModel’s Chinese docs recommend setting CLAUDE_CODE_AUTO_COMPACT_WINDOW to 512000 (instead of letting threads bloat all the way to 1M before compacting), which preserves responsiveness and drastically cuts redundant token burn. Also note that OpenClaw runs under secondary best-effort scheduling on Coding Plans, yielding priority to active IDE Coding Agents during peak contention.
6. The Fix: OpusPlan Hybrid Routing + 3-OS Zero-Dependency Scripts
Z.ai’s own best-practice guide recommends pairing a Michelin head chef (GLM-5.4) with a lightning-fast prep cook (GLM-5.3-Flash):

Figure 14: Official workflow guide detailing how to pair GLM-5.4 (planning, cross-module decisions, pre-commit review) with GLM-5.3-Flash (2× quota promo Nov 24–Dec 24 for routine coding, tests, and read-only subagent search).

Figure 15: Production OpusPlan three-stage routing architecture plus our Windows 11, Ubuntu 26.04, and macOS 27 zero-dependency automation toolkit.
Below are two drop-in deployment paths—Method 1 (Human Interactive Scripts) and Method 2 (Unattended AI Agent Prompt). All three scripts use strictly built-in OS shells (no Python/Node packages required), redact full IPs, hostnames, and raw tokens, preserve unrelated fields in ~/.claude/settings.json after creating a timestamped backup, check whether your clock is currently inside the UTC+8 14:00–18:00 2× peak window, and optionally scaffold .claude/agents/flash-worker.md.
Method 1: Human Interactive Execution (Windows 11 / Ubuntu 26.04 / macOS 27)
1. Windows 11 (PowerShell 5.1 / 7+: glm54_toolkit_windows11.ps1)
<#
.SYNOPSIS
GLM-5.4 Diagnostic, Peak-Hour Guard & Claude Code Auto-Config - Windows 11
Zero third-party dependencies (PowerShell 5.1 / 7+ built-in cmdlets only).
Privacy Guard: Never emits full IP addresses, computer hostnames, or raw API keys.
.EXAMPLE
Human Interactive: .\glm54_toolkit_windows11.ps1
Agent Automated: .\glm54_toolkit_windows11.ps1 -Auto -Json -Region global -Profile opusplan -Apply -ScaffoldWorker -Target .
#>
[CmdletBinding()]
param(
[string]$Target = ".",
[string]$HomeOverride = "",
[ValidateSet("china", "global")]
[string]$Region = "global",
[ValidateSet("opusplan", "full")]
[string]$Profile = "opusplan",
[string]$ApiKey = "",
[switch]$Apply,
[switch]$ScaffoldWorker,
[switch]$Auto,
[switch]$Json,
[switch]$Help
)
$ErrorActionPreference = "Stop"
if ($Help) {
Write-Output "Usage: .\glm54_toolkit_windows11.ps1 [-Target <dir>] [-Region china|global] [-Profile opusplan|full] [-ApiKey <key>] [-Apply] [-ScaffoldWorker] [-Auto] [-Json]"
exit 0
}
if ($Json) { $Auto = $true }
if (-not (Test-Path -Path $Target -PathType Container)) {
Write-Error "Target directory not found: $Target"
exit 2
}
$TargetAbs = (Resolve-Path -Path $Target).Path
$SettingsRoot = if ($HomeOverride -and $HomeOverride.Trim() -ne "") { $HomeOverride } else { $HOME }
if (-not $Auto) {
Write-Host "=====================================================================" -ForegroundColor Cyan
Write-Host " GLM-5.4 Loop Transformer Toolkit & Triage - Windows 11 (PowerShell)" -ForegroundColor Blue
Write-Host "=====================================================================" -ForegroundColor Cyan
$inDir = Read-Host "Workspace directory to inspect [$TargetAbs] (Enter to keep)"
if ($inDir -and $inDir.Trim() -ne "") {
if (-not (Test-Path -Path $inDir -PathType Container)) { Write-Error "Directory not found: $inDir"; exit 2 }
$TargetAbs = (Resolve-Path -Path $inDir).Path
}
$inReg = Read-Host "Region [china=open.bigmodel.cn / global=api.z.ai] ($Region)"
if ($inReg -eq "china" -or $inReg -eq "global") { $Region = $inReg }
$inProf = Read-Host "Routing profile [opusplan (recommended) / full] ($Profile)"
if ($inProf -eq "opusplan" -or $inProf -eq "full") { $Profile = $inProf }
$inApply = Read-Host "Backup and update ~/.claude/settings.json? [y/N]"
if ($inApply -match "^[Yy]") {
$Apply = $true
$secKey = Read-Host "Paste Coding Plan API Key (leave blank to keep existing)" -AsSecureString
$ptr = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secKey)
try { $plain = [Runtime.InteropServices.Marshal]::PtrToStringAuto($ptr) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ptr) }
if ($plain -and $plain.Trim() -ne "") { $ApiKey = $plain.Trim() }
}
$inWorker = Read-Host "Scaffold .claude/agents/flash-worker.md in workspace? [y/N]"
if ($inWorker -match "^[Yy]") { $ScaffoldWorker = $true }
}
$utcNow = [DateTime]::UtcNow
$cstNow = $utcNow.AddHours(8)
$cstStr = $cstNow.ToString("yyyy-MM-dd HH:mm")
$inPeak = ($cstNow.DayOfWeek -ge [DayOfWeek]::Monday -and $cstNow.DayOfWeek -le [DayOfWeek]::Friday -and $cstNow.Hour -ge 14 -and $cstNow.Hour -lt 18)
$creditRate = if ($inPeak) { "1.0x_base_2x_vs_offpeak" } else { "0.5x_off_peak" }
function Get-CmdVersion([string]$cmdName, [string]$arg) {
$cmd = Get-Command $cmdName -ErrorAction SilentlyContinue
if (-not $cmd) { return "not-installed" }
try {
$out = & $cmd.Source $arg 2>$null | Select-Object -First 1
if ($out) { return "$out".Trim() }
} catch {}
return "installed"
}
$nodeVer = Get-CmdVersion "node" "-v"
$claudeVer = Get-CmdVersion "claude" "--version"
$codexVer = Get-CmdVersion "codex" "--version"
if ($Region -eq "china") {
$expAnthropic = "https://open.bigmodel.cn/api/anthropic"
$expOpenai = "https://open.bigmodel.cn/api/coding/paas/v4"
$expCodex = "https://open.bigmodel.cn/api/v1"
} else {
$expAnthropic = "https://api.z.ai/api/anthropic"
$expOpenai = "https://api.z.ai/api/coding/paas/v4"
$expCodex = "https://api.z.ai/api/v1"
}
$tOpus = "glm-5.4[1m]"
$tFable = "glm-5.4[1m]"
if ($Profile -eq "opusplan") {
$tSonnet = "glm-5.3-flash"
$tHaiku = "glm-5.3-flash"
} else {
$tSonnet = "glm-5.4[1m]"
$tHaiku = "glm-5.4[1m]"
}
$claudeDir = Join-Path $SettingsRoot ".claude"
$settingsFile = Join-Path $claudeDir "settings.json"
$curObj = $null
if (Test-Path -Path $settingsFile -PathType Leaf) {
try { $curObj = Get-Content -Path $settingsFile -Raw -Encoding UTF8 | ConvertFrom-Json } catch { $curObj = $null }
}
function Get-EnvProp([object]$obj, [string]$name) {
if ($null -eq $obj) { return "" }
$envProp = $obj.PSObject.Properties["env"]
if ($null -eq $envProp -or $null -eq $envProp.Value) { return "" }
$prop = $envProp.Value.PSObject.Properties[$name]
if ($null -ne $prop -and $null -ne $prop.Value) { return "$($prop.Value)" }
return ""
}
$curBaseUrl = Get-EnvProp $curObj "ANTHROPIC_BASE_URL"
$curOpus = Get-EnvProp $curObj "ANTHROPIC_DEFAULT_OPUS_MODEL"
$curSonnet = Get-EnvProp $curObj "ANTHROPIC_DEFAULT_SONNET_MODEL"
$curTimeout = Get-EnvProp $curObj "API_TIMEOUT_MS"
$curCompact = Get-EnvProp $curObj "CLAUDE_CODE_AUTO_COMPACT_WINDOW"
$curTokenRaw = Get-EnvProp $curObj "ANTHROPIC_AUTH_TOKEN"
$tokenState = "missing"
if ($curTokenRaw -and -not $curTokenRaw.StartsWith("YOUR_")) {
$tokenState = "configured(len=$($curTokenRaw.Length))"
}
$standardTrap = ($curBaseUrl -like "*/api/paas/v4*" -and $curBaseUrl -notlike "*/api/coding/paas/v4*")
$timeoutNum = 0
$timeoutRisk = (-not [int]::TryParse($curTimeout, [ref]$timeoutNum)) -or ($timeoutNum -lt 3000000)
$legacyHits = 0
$sampleFiles = @()
$scanExts = @("*.json", "*.yaml", "*.yml", "*.toml", "*.env*", "*.md")
$files = Get-ChildItem -Path $TargetAbs -Recurse -File -Include $scanExts -ErrorAction SilentlyContinue |
Where-Object { $_.FullName -notmatch "\\(\.git|node_modules|\.venv|dist|build)\\" }
foreach ($f in $files) {
$lineHits = Select-String -Path $f.FullName -Pattern '/api/paas/v4|glm-4\.7|glm-5\.2|glm-5\.3"|ANTHROPIC_BASE_URL' -ErrorAction SilentlyContinue
if ($lineHits) {
$legacyHits += @($lineHits).Count
if ($sampleFiles.Count -lt 3) {
$rel = $f.FullName.Substring($TargetAbs.Length).TrimStart('\', '/')
$sampleFiles += $rel
}
}
}
$settingsUpdated = $false
$backupFile = ""
if ($Apply) {
if (-not (Test-Path -Path $claudeDir)) { New-Item -Path $claudeDir -ItemType Directory -Force | Out-Null }
$tokWrite = if ($ApiKey -and $ApiKey.Trim() -ne "") { $ApiKey.Trim() } elseif ($curTokenRaw) { $curTokenRaw } else { "YOUR_GLM_CODING_PLAN_API_KEY" }
if (Test-Path -Path $settingsFile -PathType Leaf) {
$ts = (Get-Date).ToString("yyyyMMddHHmmss")
$backupFile = "settings.json.bak.$ts"
Copy-Item -Path $settingsFile -Destination (Join-Path $claudeDir $backupFile) -Force
}
if ($null -eq $curObj) { $curObj = [PSCustomObject]@{} }
if ($null -eq $curObj.env) { $curObj | Add-Member -MemberType NoteProperty -Name "env" -Value ([PSCustomObject]@{}) -Force }
$newEnv = [ordered]@{
ANTHROPIC_BASE_URL = $expAnthropic
ANTHROPIC_AUTH_TOKEN = $tokWrite
API_TIMEOUT_MS = "3000000"
CLAUDE_CODE_AUTO_COMPACT_WINDOW = "512000"
CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS = "1"
ANTHROPIC_DEFAULT_OPUS_MODEL = $tOpus
ANTHROPIC_DEFAULT_SONNET_MODEL = $tSonnet
ANTHROPIC_DEFAULT_HAIKU_MODEL = $tHaiku
ANTHROPIC_DEFAULT_FABLE_MODEL = $tFable
}
foreach ($k in $newEnv.Keys) {
$curObj.env | Add-Member -MemberType NoteProperty -Name $k -Value $newEnv[$k] -Force
}
$jsonOut = $curObj | ConvertTo-Json -Depth 10
[System.IO.File]::WriteAllText($settingsFile, $jsonOut, (New-Object System.Text.UTF8Encoding($false)))
$settingsUpdated = $true
$curBaseUrl = $expAnthropic
$curOpus = $tOpus
$curSonnet = $tSonnet
$curTimeout = "3000000"
$curCompact = "512000"
if (-not $tokWrite.StartsWith("YOUR_")) { $tokenState = "configured(len=$($tokWrite.Length))" }
$standardTrap = $false
$timeoutRisk = $false
}
$workerCreated = $false
if ($ScaffoldWorker) {
$agentDir = Join-Path $TargetAbs ".claude\agents"
New-Item -Path $agentDir -ItemType Directory -Force | Out-Null
$workerMd = @"
---
name: flash-worker
description: Fast read-only codebase investigator for call sites, tests, and config files using GLM-5.3-Flash.
model: glm-5.3-flash
tools: Read, Grep, Glob
---
Search the workspace within the scope assigned by the main GLM-5.4 session.
List exact file paths, symbol names, and existing test coverage, and flag ambiguities for the main planner to decide.
"@
[System.IO.File]::WriteAllText((Join-Path $agentDir "flash-worker.md"), $workerMd, (New-Object System.Text.UTF8Encoding($false)))
$workerCreated = $true
}
$summary = [ordered]@{
platform = "Windows 11"
region = $Region
profile = $Profile
cst_time = $cstStr
in_peak_window_2x = $inPeak
credit_rate = $creditRate
node_version = $nodeVer
claude_version = $claudeVer
codex_version = $codexVer
expected_anthropic_url = $expAnthropic
expected_openai_coding_url = $expOpenai
expected_codex_url = $expCodex
configured_base_url = if ($curBaseUrl) { $curBaseUrl } else { "unset" }
configured_opus_model = if ($curOpus) { $curOpus } else { "unset" }
configured_sonnet_model = if ($curSonnet) { $curSonnet } else { "unset" }
configured_timeout_ms = if ($curTimeout) { $curTimeout } else { "unset" }
configured_compact_window = if ($curCompact) { $curCompact } else { "unset" }
token_state = $tokenState
standard_endpoint_balance_trap = $standardTrap
marathon_timeout_risk = $timeoutRisk
workspace_legacy_hits = $legacyHits
workspace_sample_files = ($sampleFiles -join ",")
settings_updated = $settingsUpdated
backup_file = $backupFile
flash_worker_scaffolded = $workerCreated
}
if ($Json) {
$summary | ConvertTo-Json -Depth 4
} else {
Write-Host ""
Write-Host "=== GLM-5.4 Diagnostic Summary (Windows 11 · Sanitized) ===" -ForegroundColor Cyan
foreach ($k in $summary.Keys) {
Write-Host ("{0,-32} : {1}" -f $k, $summary[$k])
}
}
Run in PowerShell:
powershell -ExecutionPolicy Bypass -File .\glm54_toolkit_windows11.ps1
2. Ubuntu 26.04 (GNU Bash: glm54_toolkit_ubuntu2604.sh)
#!/usr/bin/env bash
# ==============================================================================
# GLM-5.4 Diagnostic, Peak-Hour Guard & Claude Code Auto-Config — Ubuntu 26.04
# Zero third-party dependencies (GNU bash, awk, grep, sed, date, curl)
# Privacy Guard: Never emits full IP addresses, hostnames, or raw API keys.
#
# Modes:
# Human Interactive: bash ./glm54_toolkit_ubuntu2604.sh
# Agent Automated: bash ./glm54_toolkit_ubuntu2604.sh --auto --json --region global --profile opusplan --apply --scaffold-worker --target .
# ==============================================================================
set -euo pipefail
TARGET_DIR="."
REGION="global"
PROFILE="opusplan"
AUTO_MODE=0
JSON_MODE=0
APPLY_CONFIG=0
SCAFFOLD_WORKER=0
API_KEY_INPUT=""
SETTINGS_ROOT="${HOME}"
print_usage() {
cat <<'USAGE'
Usage: bash glm54_toolkit_ubuntu2604.sh [options]
--target <dir> Workspace directory to scan / scaffold agent (default: .)
--home <dir> Override HOME for ~/.claude/settings.json (sandbox testing)
--region <val> china (open.bigmodel.cn) or global (api.z.ai) (default: global)
--profile <val> opusplan (5.4 planner + 5.3-flash worker) or full (all 5.4[1m]) (default: opusplan)
--api-key <key> Optional Coding Plan API key to write into settings.json
--apply Backup ~/.claude/settings.json and apply GLM-5.4 optimized env settings
--scaffold-worker Create .claude/agents/flash-worker.md in --target workspace
--auto Non-interactive mode (no prompts; ideal for CI / AI Agents)
--json Emit machine-readable sanitized JSON summary to stdout
-h, --help Show help
USAGE
}
while (( $# > 0 )); do
case "$1" in
--target) shift; [[ $# -gt 0 ]] || { echo "Error: --target requires a dir" >&2; exit 2; }; TARGET_DIR="$1" ;;
--home) shift; [[ $# -gt 0 ]] || { echo "Error: --home requires a dir" >&2; exit 2; }; SETTINGS_ROOT="$1" ;;
--region) shift; [[ $# -gt 0 ]] || { echo "Error: --region requires china|global" >&2; exit 2; }; REGION="$1" ;;
--profile) shift; [[ $# -gt 0 ]] || { echo "Error: --profile requires opusplan|full" >&2; exit 2; }; PROFILE="$1" ;;
--api-key) shift; [[ $# -gt 0 ]] || { echo "Error: --api-key requires a value" >&2; exit 2; }; API_KEY_INPUT="$1" ;;
--apply) APPLY_CONFIG=1 ;;
--scaffold-worker) SCAFFOLD_WORKER=1 ;;
--auto) AUTO_MODE=1 ;;
--json) JSON_MODE=1; AUTO_MODE=1 ;;
-h|--help) print_usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; print_usage >&2; exit 2 ;;
esac
shift
done
[[ "$REGION" == "china" || "$REGION" == "global" ]] || { echo "Error: --region must be china or global" >&2; exit 2; }
[[ "$PROFILE" == "opusplan" || "$PROFILE" == "full" ]] || { echo "Error: --profile must be opusplan or full" >&2; exit 2; }
[[ -d "$TARGET_DIR" ]] || { echo "Error: Target directory not found: $TARGET_DIR" >&2; exit 2; }
TARGET_ABS="$(cd "$TARGET_DIR" && pwd)"
if (( AUTO_MODE == 0 )); then
echo "====================================================================="
echo " GLM-5.4 Loop Transformer Toolkit & Triage — Ubuntu 26.04 (Bash)"
echo "====================================================================="
printf "Workspace directory to inspect [%s] (Enter to keep): " "$TARGET_ABS"
read -r in_dir || true
if [[ -n "${in_dir:-}" ]]; then
[[ -d "$in_dir" ]] || { echo "Directory not found: $in_dir" >&2; exit 2; }
TARGET_ABS="$(cd "$in_dir" && pwd)"
fi
printf "Region [china=open.bigmodel.cn / global=api.z.ai] (%s): " "$REGION"
read -r in_reg || true
[[ "${in_reg:-}" == "global" || "${in_reg:-}" == "china" ]] && REGION="$in_reg"
printf "Routing profile [opusplan (recommended) / full] (%s): " "$PROFILE"
read -r in_prof || true
[[ "${in_prof:-}" == "full" || "${in_prof:-}" == "opusplan" ]] && PROFILE="$in_prof"
printf "Backup & update ~/.claude/settings.json? [y/N]: "
read -r in_apply || true
[[ "${in_apply:-n}" == [Yy]* ]] && APPLY_CONFIG=1
if (( APPLY_CONFIG == 1 )); then
printf "Paste Coding Plan API Key (leave blank to keep existing): "
read -rs in_key || true
echo ""
[[ -n "${in_key:-}" ]] && API_KEY_INPUT="$in_key"
fi
printf "Scaffold .claude/agents/flash-worker.md in workspace? [y/N]: "
read -r in_worker || true
[[ "${in_worker:-n}" == [Yy]* ]] && SCAFFOLD_WORKER=1
fi
CST_STR="$(TZ=Asia/Shanghai date '+%Y-%m-%d %H:%M %u')"
CST_DOW="$(TZ=Asia/Shanghai date '+%u')"
CST_HHMM="$(TZ=Asia/Shanghai date '+%H%M')"
IN_PEAK_WINDOW=false
CREDIT_RATE="0.5x_off_peak"
if (( CST_DOW >= 1 && CST_DOW <= 5 && 10#$CST_HHMM >= 1400 && 10#$CST_HHMM < 1800 )); then
IN_PEAK_WINDOW=true
CREDIT_RATE="1.0x_base_2x_vs_offpeak"
fi
NODE_VER="not-installed"
if command -v node >/dev/null 2>&1; then
NODE_VER="$(node -v 2>/dev/null | tr -d '\r' || echo unknown)"
fi
CLAUDE_VER="not-installed"
if command -v claude >/dev/null 2>&1; then
CLAUDE_VER="$(claude --version 2>/dev/null | head -n 1 | tr -d '\r' || echo unknown)"
fi
CODEX_VER="not-installed"
if command -v codex >/dev/null 2>&1; then
CODEX_VER="$(codex --version 2>/dev/null | head -n 1 | tr -d '\r' || echo unknown)"
fi
if [[ "$REGION" == "china" ]]; then
EXPECTED_ANTHROPIC_URL="https://open.bigmodel.cn/api/anthropic"
EXPECTED_OPENAI_URL="https://open.bigmodel.cn/api/coding/paas/v4"
EXPECTED_CODEX_URL="https://open.bigmodel.cn/api/v1"
else
EXPECTED_ANTHROPIC_URL="https://api.z.ai/api/anthropic"
EXPECTED_OPENAI_URL="https://api.z.ai/api/coding/paas/v4"
EXPECTED_CODEX_URL="https://api.z.ai/api/v1"
fi
if [[ "$PROFILE" == "opusplan" ]]; then
TARGET_OPUS="glm-5.4[1m]"
TARGET_SONNET="glm-5.3-flash"
TARGET_HAIKU="glm-5.3-flash"
TARGET_FABLE="glm-5.4[1m]"
else
TARGET_OPUS="glm-5.4[1m]"
TARGET_SONNET="glm-5.4[1m]"
TARGET_HAIKU="glm-5.4[1m]"
TARGET_FABLE="glm-5.4[1m]"
fi
CLAUDE_DIR="${SETTINGS_ROOT}/.claude"
SETTINGS_FILE="${CLAUDE_DIR}/settings.json"
extract_json_val() {
local key="$1" file="$2"
[[ -f "$file" ]] || return 0
awk -v k="$key" -F'"' '{
for (i=2; i<=NF; i+=2) {
if ($i == k && $(i+1) ~ /^[[:space:]]*:[[:space:]]*$/ && (i+2)<=NF) {
print $(i+2); exit
}
}
}' "$file" 2>/dev/null || true
}
CUR_BASE_URL="$(extract_json_val "ANTHROPIC_BASE_URL" "$SETTINGS_FILE")"
CUR_OPUS="$(extract_json_val "ANTHROPIC_DEFAULT_OPUS_MODEL" "$SETTINGS_FILE")"
CUR_SONNET="$(extract_json_val "ANTHROPIC_DEFAULT_SONNET_MODEL" "$SETTINGS_FILE")"
CUR_TIMEOUT="$(extract_json_val "API_TIMEOUT_MS" "$SETTINGS_FILE")"
CUR_COMPACT="$(extract_json_val "CLAUDE_CODE_AUTO_COMPACT_WINDOW" "$SETTINGS_FILE")"
CUR_TOKEN_RAW="$(extract_json_val "ANTHROPIC_AUTH_TOKEN" "$SETTINGS_FILE")"
TOKEN_STATE="missing"
if [[ -n "$CUR_TOKEN_RAW" && "$CUR_TOKEN_RAW" != "YOUR_"* ]]; then
TOKEN_STATE="configured(len=${#CUR_TOKEN_RAW})"
fi
STANDARD_ENDPOINT_TRAP=false
if [[ "$CUR_BASE_URL" == *"/api/paas/v4"* && "$CUR_BASE_URL" != *"/api/coding/paas/v4"* ]]; then
STANDARD_ENDPOINT_TRAP=true
fi
TIMEOUT_RISK=false
if [[ -z "$CUR_TIMEOUT" ]] || ! [[ "$CUR_TIMEOUT" =~ ^[0-9]+$ ]] || (( CUR_TIMEOUT < 3000000 )); then
TIMEOUT_RISK=true
fi
WORKSPACE_HITS=0
SAMPLE_FILES=""
raw_hits="$(grep -rnE \
--exclude-dir=.git --exclude-dir=node_modules --exclude-dir=.venv --exclude-dir=dist --exclude-dir=build \
--include='*.json' --include='*.yaml' --include='*.yml' --include='*.toml' --include='*.env*' --include='*.md' \
'/api/paas/v4|glm-4\.7|glm-5\.2|glm-5\.3"|ANTHROPIC_BASE_URL' "$TARGET_ABS" 2>/dev/null || true)"
if [[ -n "$raw_hits" ]]; then
WORKSPACE_HITS="$(printf '%s\n' "$raw_hits" | wc -l | tr -d ' ')"
SAMPLE_FILES="$(printf '%s\n' "$raw_hits" | head -n 3 | sed "s|$TARGET_ABS/||g" | cut -d: -f1 | paste -sd ',' -)"
fi
SETTINGS_UPDATED=false
BACKUP_NAME=""
if (( APPLY_CONFIG == 1 )); then
mkdir -p "$CLAUDE_DIR"
TOKEN_TO_WRITE="${API_KEY_INPUT:-${CUR_TOKEN_RAW:-YOUR_GLM_CODING_PLAN_API_KEY}}"
if [[ -f "$SETTINGS_FILE" ]] && grep -q '[^[:space:]]' "$SETTINGS_FILE"; then
ts="$(date +%Y%m%d%H%M%S)"
cp "$SETTINGS_FILE" "${SETTINGS_FILE}.bak.${ts}"
BACKUP_NAME="settings.json.bak.${ts}"
fi
if [[ -f "$SETTINGS_FILE" ]] && grep -q '"env"[[:space:]]*:' "$SETTINGS_FILE"; then
awk -v base="$EXPECTED_ANTHROPIC_URL" \
-v tok="$TOKEN_TO_WRITE" \
-v opus="$TARGET_OPUS" \
-v sonnet="$TARGET_SONNET" \
-v haiku="$TARGET_HAIKU" \
-v fable="$TARGET_FABLE" '
BEGIN { in_env=0; brace=0; done_env=0 }
{
if (!in_env && !done_env && $0 ~ /"env"[[:space:]]*:/) {
in_env=1
brace=1
print " \"env\": {"
print " \"ANTHROPIC_BASE_URL\": \"" base "\","
print " \"ANTHROPIC_AUTH_TOKEN\": \"" tok "\","
print " \"API_TIMEOUT_MS\": \"3000000\","
print " \"CLAUDE_CODE_AUTO_COMPACT_WINDOW\": \"512000\","
print " \"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS\": \"1\","
print " \"ANTHROPIC_DEFAULT_OPUS_MODEL\": \"" opus "\","
print " \"ANTHROPIC_DEFAULT_SONNET_MODEL\": \"" sonnet "\","
print " \"ANTHROPIC_DEFAULT_HAIKU_MODEL\": \"" haiku "\","
print " \"ANTHROPIC_DEFAULT_FABLE_MODEL\": \"" fable "\""
next
}
if (in_env) {
for (i=1; i<=length($0); i++) {
c=substr($0,i,1)
if (c=="{") brace++
else if (c=="}") brace--
}
if (brace <= 0) {
in_env=0
done_env=1
print $0
}
next
}
print $0
}
' "$SETTINGS_FILE" > "${SETTINGS_FILE}.tmp" && mv "${SETTINGS_FILE}.tmp" "$SETTINGS_FILE"
else
cat > "$SETTINGS_FILE" <<EOF
{
"env": {
"ANTHROPIC_BASE_URL": "${EXPECTED_ANTHROPIC_URL}",
"ANTHROPIC_AUTH_TOKEN": "${TOKEN_TO_WRITE}",
"API_TIMEOUT_MS": "3000000",
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "512000",
"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "${TARGET_OPUS}",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "${TARGET_SONNET}",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "${TARGET_HAIKU}",
"ANTHROPIC_DEFAULT_FABLE_MODEL": "${TARGET_FABLE}"
}
}
EOF
fi
chmod 600 "$SETTINGS_FILE" 2>/dev/null || true
SETTINGS_UPDATED=true
CUR_BASE_URL="$EXPECTED_ANTHROPIC_URL"
CUR_OPUS="$TARGET_OPUS"
CUR_SONNET="$TARGET_SONNET"
CUR_TIMEOUT="3000000"
CUR_COMPACT="512000"
if [[ "$TOKEN_TO_WRITE" != "YOUR_"* ]]; then
TOKEN_STATE="configured(len=${#TOKEN_TO_WRITE})"
fi
STANDARD_ENDPOINT_TRAP=false
TIMEOUT_RISK=false
fi
WORKER_CREATED=false
if (( SCAFFOLD_WORKER == 1 )); then
mkdir -p "${TARGET_ABS}/.claude/agents"
cat > "${TARGET_ABS}/.claude/agents/flash-worker.md" <<'EOF'
---
name: flash-worker
description: Fast read-only codebase investigator for call sites, tests, and config files using GLM-5.3-Flash.
model: glm-5.3-flash
tools: Read, Grep, Glob
---
Search the workspace within the scope assigned by the main GLM-5.4 session.
List exact file paths, symbol names, and existing test coverage, and flag ambiguities for the main planner to decide.
EOF
WORKER_CREATED=true
fi
if (( JSON_MODE == 1 )); then
cat <<EOF
{
"platform": "Ubuntu 26.04",
"region": "${REGION}",
"profile": "${PROFILE}",
"cst_time": "${CST_STR}",
"in_peak_window_2x": ${IN_PEAK_WINDOW},
"credit_rate": "${CREDIT_RATE}",
"node_version": "${NODE_VER}",
"claude_version": "${CLAUDE_VER}",
"codex_version": "${CODEX_VER}",
"expected_anthropic_url": "${EXPECTED_ANTHROPIC_URL}",
"expected_openai_coding_url": "${EXPECTED_OPENAI_URL}",
"expected_codex_url": "${EXPECTED_CODEX_URL}",
"configured_base_url": "${CUR_BASE_URL:-unset}",
"configured_opus_model": "${CUR_OPUS:-unset}",
"configured_sonnet_model": "${CUR_SONNET:-unset}",
"configured_timeout_ms": "${CUR_TIMEOUT:-unset}",
"configured_compact_window": "${CUR_COMPACT:-unset}",
"token_state": "${TOKEN_STATE}",
"standard_endpoint_balance_trap": ${STANDARD_ENDPOINT_TRAP},
"marathon_timeout_risk": ${TIMEOUT_RISK},
"workspace_legacy_hits": ${WORKSPACE_HITS},
"workspace_sample_files": "${SAMPLE_FILES}",
"settings_updated": ${SETTINGS_UPDATED},
"backup_file": "${BACKUP_NAME}",
"flash_worker_scaffolded": ${WORKER_CREATED}
}
EOF
else
echo ""
echo "=== GLM-5.4 Diagnostic Summary (Ubuntu 26.04 · Sanitized) ==="
echo "UTC+8 Clock / Window: ${CST_STR} (peak_2x=${IN_PEAK_WINDOW}, rate=${CREDIT_RATE})"
echo "Toolchain: node=${NODE_VER} | claude=${CLAUDE_VER} | codex=${CODEX_VER}"
echo "Region / Profile: ${REGION} / ${PROFILE}"
echo "Anthropic Base URL: ${CUR_BASE_URL:-unset} (expected: ${EXPECTED_ANTHROPIC_URL})"
echo "OPUS / SONNET Routing: ${CUR_OPUS:-unset} / ${CUR_SONNET:-unset}"
echo "Timeout / Compact Win: ${CUR_TIMEOUT:-unset} ms / ${CUR_COMPACT:-unset} tokens"
echo "Token State: ${TOKEN_STATE}"
echo "Endpoint Balance Trap: ${STANDARD_ENDPOINT_TRAP} | Timeout Risk: ${TIMEOUT_RISK}"
echo "Workspace Legacy Hits: ${WORKSPACE_HITS} ${SAMPLE_FILES:+(${SAMPLE_FILES})}"
echo "Applied / Worker File: updated=${SETTINGS_UPDATED} (backup=${BACKUP_NAME:-none}) | worker=${WORKER_CREATED}"
fi
Run in Bash:
chmod +x ./glm54_toolkit_ubuntu2604.sh && ./glm54_toolkit_ubuntu2604.sh
3. macOS 27 (Built-in Zsh: glm54_toolkit_macos27.zsh)
#!/usr/bin/env zsh
# ==============================================================================
# GLM-5.4 Diagnostic, Peak-Hour Guard & Claude Code Auto-Config — macOS 27
# Zero third-party dependencies (macOS 27 built-in zsh, awk, grep, sed, date, curl)
# Privacy Guard: Never emits full IP addresses, hostnames, or raw API keys.
#
# Modes:
# Human Interactive: zsh ./glm54_toolkit_macos27.zsh
# Agent Automated: zsh ./glm54_toolkit_macos27.zsh --auto --json --region global --profile opusplan --apply --scaffold-worker --target .
# ==============================================================================
emulate -L zsh
setopt PIPE_FAIL NO_UNSET
TARGET_DIR="."
REGION="global"
PROFILE="opusplan"
AUTO_MODE=0
JSON_MODE=0
APPLY_CONFIG=0
SCAFFOLD_WORKER=0
API_KEY_INPUT=""
SETTINGS_ROOT="${HOME}"
print_usage() {
cat <<'USAGE'
Usage: zsh glm54_toolkit_macos27.zsh [options]
--target <dir> Workspace directory to scan / scaffold agent (default: .)
--home <dir> Override HOME for ~/.claude/settings.json (useful for sandbox tests)
--region <val> china (open.bigmodel.cn) or global (api.z.ai) (default: global)
--profile <val> opusplan (5.4 planner + 5.3-flash worker) or full (all 5.4[1m]) (default: opusplan)
--api-key <key> Optional Coding Plan API key to write into settings.json
--apply Backup ~/.claude/settings.json and apply GLM-5.4 optimized env settings
--scaffold-worker Create .claude/agents/flash-worker.md in --target workspace
--auto Non-interactive mode (no prompts; ideal for CI / AI Agents)
--json Emit machine-readable sanitized JSON summary to stdout
-h, --help Show help
USAGE
}
while (( $# > 0 )); do
case "$1" in
--target) shift; [[ $# -gt 0 ]] || { echo "Error: --target requires a dir" >&2; exit 2; }; TARGET_DIR="$1" ;;
--home) shift; [[ $# -gt 0 ]] || { echo "Error: --home requires a dir" >&2; exit 2; }; SETTINGS_ROOT="$1" ;;
--region) shift; [[ $# -gt 0 ]] || { echo "Error: --region requires china|global" >&2; exit 2; }; REGION="$1" ;;
--profile) shift; [[ $# -gt 0 ]] || { echo "Error: --profile requires opusplan|full" >&2; exit 2; }; PROFILE="$1" ;;
--api-key) shift; [[ $# -gt 0 ]] || { echo "Error: --api-key requires a value" >&2; exit 2; }; API_KEY_INPUT="$1" ;;
--apply) APPLY_CONFIG=1 ;;
--scaffold-worker) SCAFFOLD_WORKER=1 ;;
--auto) AUTO_MODE=1 ;;
--json) JSON_MODE=1; AUTO_MODE=1 ;;
-h|--help) print_usage; exit 0 ;;
*) echo "Unknown option: $1" >&2; print_usage >&2; exit 2 ;;
esac
shift
done
[[ "$REGION" == "china" || "$REGION" == "global" ]] || { echo "Error: --region must be china or global" >&2; exit 2; }
[[ "$PROFILE" == "opusplan" || "$PROFILE" == "full" ]] || { echo "Error: --profile must be opusplan or full" >&2; exit 2; }
[[ -d "$TARGET_DIR" ]] || { echo "Error: Target directory not found: $TARGET_DIR" >&2; exit 2; }
TARGET_ABS="$(cd "$TARGET_DIR" && pwd)"
if (( AUTO_MODE == 0 )); then
print -P "%F{cyan}=====================================================================%f"
print -P "%B%F{blue} GLM-5.4 Loop Transformer Toolkit & Triage — macOS 27 (Zsh)%f%b"
print -P "%F{cyan}=====================================================================%f"
printf "Workspace directory to inspect [%s] (Enter to keep): " "$TARGET_ABS"
read -r in_dir || true
if [[ -n "${in_dir:-}" ]]; then
[[ -d "$in_dir" ]] || { echo "Directory not found: $in_dir" >&2; exit 2; }
TARGET_ABS="$(cd "$in_dir" && pwd)"
fi
printf "Region [china=open.bigmodel.cn / global=api.z.ai] (%s): " "$REGION"
read -r in_reg || true
[[ "${in_reg:-}" == "global" || "${in_reg:-}" == "china" ]] && REGION="$in_reg"
printf "Routing profile [opusplan (recommended) / full] (%s): " "$PROFILE"
read -r in_prof || true
[[ "${in_prof:-}" == "full" || "${in_prof:-}" == "opusplan" ]] && PROFILE="$in_prof"
printf "Backup & update ~/.claude/settings.json? [y/N]: "
read -r in_apply || true
[[ "${in_apply:-n}" == [Yy]* ]] && APPLY_CONFIG=1
if (( APPLY_CONFIG == 1 )); then
printf "Paste Coding Plan API Key (leave blank to keep existing): "
read -rs in_key || true
print ""
[[ -n "${in_key:-}" ]] && API_KEY_INPUT="$in_key"
fi
printf "Scaffold .claude/agents/flash-worker.md in workspace? [y/N]: "
read -r in_worker || true
[[ "${in_worker:-n}" == [Yy]* ]] && SCAFFOLD_WORKER=1
fi
CST_STR="$(TZ=Asia/Shanghai date '+%Y-%m-%d %H:%M %u')"
CST_DOW="$(TZ=Asia/Shanghai date '+%u')"
CST_HHMM="$(TZ=Asia/Shanghai date '+%H%M')"
IN_PEAK_WINDOW=false
CREDIT_RATE="0.5x_off_peak"
if (( CST_DOW >= 1 && CST_DOW <= 5 && 10#$CST_HHMM >= 1400 && 10#$CST_HHMM < 1800 )); then
IN_PEAK_WINDOW=true
CREDIT_RATE="1.0x_base_2x_vs_offpeak"
fi
NODE_VER="not-installed"
if command -v node >/dev/null 2>&1; then
NODE_VER="$(node -v 2>/dev/null | tr -d '\r' || echo unknown)"
fi
CLAUDE_VER="not-installed"
if command -v claude >/dev/null 2>&1; then
CLAUDE_VER="$(claude --version 2>/dev/null | head -n 1 | tr -d '\r' || echo unknown)"
fi
CODEX_VER="not-installed"
if command -v codex >/dev/null 2>&1; then
CODEX_VER="$(codex --version 2>/dev/null | head -n 1 | tr -d '\r' || echo unknown)"
fi
if [[ "$REGION" == "china" ]]; then
EXPECTED_ANTHROPIC_URL="https://open.bigmodel.cn/api/anthropic"
EXPECTED_OPENAI_URL="https://open.bigmodel.cn/api/coding/paas/v4"
EXPECTED_CODEX_URL="https://open.bigmodel.cn/api/v1"
else
EXPECTED_ANTHROPIC_URL="https://api.z.ai/api/anthropic"
EXPECTED_OPENAI_URL="https://api.z.ai/api/coding/paas/v4"
EXPECTED_CODEX_URL="https://api.z.ai/api/v1"
fi
if [[ "$PROFILE" == "opusplan" ]]; then
TARGET_OPUS="glm-5.4[1m]"
TARGET_SONNET="glm-5.3-flash"
TARGET_HAIKU="glm-5.3-flash"
TARGET_FABLE="glm-5.4[1m]"
else
TARGET_OPUS="glm-5.4[1m]"
TARGET_SONNET="glm-5.4[1m]"
TARGET_HAIKU="glm-5.4[1m]"
TARGET_FABLE="glm-5.4[1m]"
fi
CLAUDE_DIR="${SETTINGS_ROOT}/.claude"
SETTINGS_FILE="${CLAUDE_DIR}/settings.json"
extract_json_val() {
local key="$1" file="$2"
[[ -f "$file" ]] || return 0
awk -v k="$key" -F'"' '{
for (i=2; i<=NF; i+=2) {
if ($i == k && $(i+1) ~ /^[[:space:]]*:[[:space:]]*$/ && (i+2)<=NF) {
print $(i+2); exit
}
}
}' "$file" 2>/dev/null || true
}
CUR_BASE_URL="$(extract_json_val "ANTHROPIC_BASE_URL" "$SETTINGS_FILE")"
CUR_OPUS="$(extract_json_val "ANTHROPIC_DEFAULT_OPUS_MODEL" "$SETTINGS_FILE")"
CUR_SONNET="$(extract_json_val "ANTHROPIC_DEFAULT_SONNET_MODEL" "$SETTINGS_FILE")"
CUR_TIMEOUT="$(extract_json_val "API_TIMEOUT_MS" "$SETTINGS_FILE")"
CUR_COMPACT="$(extract_json_val "CLAUDE_CODE_AUTO_COMPACT_WINDOW" "$SETTINGS_FILE")"
CUR_TOKEN_RAW="$(extract_json_val "ANTHROPIC_AUTH_TOKEN" "$SETTINGS_FILE")"
TOKEN_STATE="missing"
if [[ -n "$CUR_TOKEN_RAW" && "$CUR_TOKEN_RAW" != "YOUR_"* ]]; then
TOKEN_STATE="configured(len=${#CUR_TOKEN_RAW})"
fi
STANDARD_ENDPOINT_TRAP=false
if [[ "$CUR_BASE_URL" == *"/api/paas/v4"* && "$CUR_BASE_URL" != *"/api/coding/paas/v4"* ]]; then
STANDARD_ENDPOINT_TRAP=true
fi
TIMEOUT_RISK=false
if [[ -z "$CUR_TIMEOUT" ]] || ! [[ "$CUR_TIMEOUT" =~ ^[0-9]+$ ]] || (( CUR_TIMEOUT < 3000000 )); then
TIMEOUT_RISK=true
fi
WORKSPACE_HITS=0
SAMPLE_FILES=""
raw_hits="$(grep -rnE \
--exclude-dir=.git --exclude-dir=node_modules --exclude-dir=.venv --exclude-dir=dist --exclude-dir=build \
--include='*.json' --include='*.yaml' --include='*.yml' --include='*.toml' --include='*.env*' --include='*.md' \
'/api/paas/v4|glm-4\.7|glm-5\.2|glm-5\.3"|ANTHROPIC_BASE_URL' "$TARGET_ABS" 2>/dev/null || true)"
if [[ -n "$raw_hits" ]]; then
WORKSPACE_HITS="$(printf '%s\n' "$raw_hits" | wc -l | tr -d ' ')"
SAMPLE_FILES="$(printf '%s\n' "$raw_hits" | head -n 3 | sed "s|$TARGET_ABS/||g" | cut -d: -f1 | paste -sd ',' -)"
fi
SETTINGS_UPDATED=false
BACKUP_NAME=""
if (( APPLY_CONFIG == 1 )); then
mkdir -p "$CLAUDE_DIR"
TOKEN_TO_WRITE="${API_KEY_INPUT:-${CUR_TOKEN_RAW:-YOUR_GLM_CODING_PLAN_API_KEY}}"
if [[ -f "$SETTINGS_FILE" ]] && grep -q '[^[:space:]]' "$SETTINGS_FILE"; then
ts="$(date +%Y%m%d%H%M%S)"
cp "$SETTINGS_FILE" "${SETTINGS_FILE}.bak.${ts}"
BACKUP_NAME="settings.json.bak.${ts}"
fi
if [[ -f "$SETTINGS_FILE" ]] && grep -q '"env"[[:space:]]*:' "$SETTINGS_FILE"; then
awk -v base="$EXPECTED_ANTHROPIC_URL" \
-v tok="$TOKEN_TO_WRITE" \
-v opus="$TARGET_OPUS" \
-v sonnet="$TARGET_SONNET" \
-v haiku="$TARGET_HAIKU" \
-v fable="$TARGET_FABLE" '
BEGIN { in_env=0; brace=0; done_env=0 }
{
if (!in_env && !done_env && $0 ~ /"env"[[:space:]]*:/) {
in_env=1
brace=1
print " \"env\": {"
print " \"ANTHROPIC_BASE_URL\": \"" base "\","
print " \"ANTHROPIC_AUTH_TOKEN\": \"" tok "\","
print " \"API_TIMEOUT_MS\": \"3000000\","
print " \"CLAUDE_CODE_AUTO_COMPACT_WINDOW\": \"512000\","
print " \"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS\": \"1\","
print " \"ANTHROPIC_DEFAULT_OPUS_MODEL\": \"" opus "\","
print " \"ANTHROPIC_DEFAULT_SONNET_MODEL\": \"" sonnet "\","
print " \"ANTHROPIC_DEFAULT_HAIKU_MODEL\": \"" haiku "\","
print " \"ANTHROPIC_DEFAULT_FABLE_MODEL\": \"" fable "\""
next
}
if (in_env) {
for (i=1; i<=length($0); i++) {
c=substr($0,i,1)
if (c=="{") brace++
else if (c=="}") brace--
}
if (brace <= 0) {
in_env=0
done_env=1
print $0
}
next
}
print $0
}
' "$SETTINGS_FILE" > "${SETTINGS_FILE}.tmp" && mv "${SETTINGS_FILE}.tmp" "$SETTINGS_FILE"
else
cat > "$SETTINGS_FILE" <<EOF
{
"env": {
"ANTHROPIC_BASE_URL": "${EXPECTED_ANTHROPIC_URL}",
"ANTHROPIC_AUTH_TOKEN": "${TOKEN_TO_WRITE}",
"API_TIMEOUT_MS": "3000000",
"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "512000",
"CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS": "1",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "${TARGET_OPUS}",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "${TARGET_SONNET}",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "${TARGET_HAIKU}",
"ANTHROPIC_DEFAULT_FABLE_MODEL": "${TARGET_FABLE}"
}
}
EOF
fi
chmod 600 "$SETTINGS_FILE" 2>/dev/null || true
SETTINGS_UPDATED=true
CUR_BASE_URL="$EXPECTED_ANTHROPIC_URL"
CUR_OPUS="$TARGET_OPUS"
CUR_SONNET="$TARGET_SONNET"
CUR_TIMEOUT="3000000"
CUR_COMPACT="512000"
if [[ "$TOKEN_TO_WRITE" != "YOUR_"* ]]; then
TOKEN_STATE="configured(len=${#TOKEN_TO_WRITE})"
fi
STANDARD_ENDPOINT_TRAP=false
TIMEOUT_RISK=false
fi
WORKER_CREATED=false
if (( SCAFFOLD_WORKER == 1 )); then
mkdir -p "${TARGET_ABS}/.claude/agents"
cat > "${TARGET_ABS}/.claude/agents/flash-worker.md" <<'EOF'
---
name: flash-worker
description: Fast read-only codebase investigator for call sites, tests, and config files using GLM-5.3-Flash.
model: glm-5.3-flash
tools: Read, Grep, Glob
---
Search the workspace within the scope assigned by the main GLM-5.4 session.
List exact file paths, symbol names, and existing test coverage, and flag ambiguities for the main planner to decide.
EOF
WORKER_CREATED=true
fi
if (( JSON_MODE == 1 )); then
cat <<EOF
{
"platform": "macOS 27",
"region": "${REGION}",
"profile": "${PROFILE}",
"cst_time": "${CST_STR}",
"in_peak_window_2x": ${IN_PEAK_WINDOW},
"credit_rate": "${CREDIT_RATE}",
"node_version": "${NODE_VER}",
"claude_version": "${CLAUDE_VER}",
"codex_version": "${CODEX_VER}",
"expected_anthropic_url": "${EXPECTED_ANTHROPIC_URL}",
"expected_openai_coding_url": "${EXPECTED_OPENAI_URL}",
"expected_codex_url": "${EXPECTED_CODEX_URL}",
"configured_base_url": "${CUR_BASE_URL:-unset}",
"configured_opus_model": "${CUR_OPUS:-unset}",
"configured_sonnet_model": "${CUR_SONNET:-unset}",
"configured_timeout_ms": "${CUR_TIMEOUT:-unset}",
"configured_compact_window": "${CUR_COMPACT:-unset}",
"token_state": "${TOKEN_STATE}",
"standard_endpoint_balance_trap": ${STANDARD_ENDPOINT_TRAP},
"marathon_timeout_risk": ${TIMEOUT_RISK},
"workspace_legacy_hits": ${WORKSPACE_HITS},
"workspace_sample_files": "${SAMPLE_FILES}",
"settings_updated": ${SETTINGS_UPDATED},
"backup_file": "${BACKUP_NAME}",
"flash_worker_scaffolded": ${WORKER_CREATED}
}
EOF
else
print -r -- ""
print -P "%B=== GLM-5.4 Diagnostic Summary (macOS 27 · Sanitized) ===%b"
print -r -- "UTC+8 Clock / Window: ${CST_STR} (peak_2x=${IN_PEAK_WINDOW}, rate=${CREDIT_RATE})"
print -r -- "Toolchain: node=${NODE_VER} | claude=${CLAUDE_VER} | codex=${CODEX_VER}"
print -r -- "Region / Profile: ${REGION} / ${PROFILE}"
print -r -- "Anthropic Base URL: ${CUR_BASE_URL:-unset} (expected: ${EXPECTED_ANTHROPIC_URL})"
print -r -- "OPUS / SONNET Routing: ${CUR_OPUS:-unset} / ${CUR_SONNET:-unset}"
print -r -- "Timeout / Compact Win: ${CUR_TIMEOUT:-unset} ms / ${CUR_COMPACT:-unset} tokens"
print -r -- "Token State: ${TOKEN_STATE}"
print -r -- "Endpoint Balance Trap: ${STANDARD_ENDPOINT_TRAP} | Timeout Risk: ${TIMEOUT_RISK}"
print -r -- "Workspace Legacy Hits: ${WORKSPACE_HITS} ${SAMPLE_FILES:+(${SAMPLE_FILES})}"
print -r -- "Applied / Worker File: updated=${SETTINGS_UPDATED} (backup=${BACKUP_NAME:-none}) | worker=${WORKER_CREATED}"
fi
Run in Zsh:
chmod +x ./glm54_toolkit_macos27.zsh && zsh ./glm54_toolkit_macos27.zsh
Method 2: Let Your AI Agent Configure Everything Automatically
Paste this prompt directly into Claude Code, ZCode, Codex, or Antigravity:
Detect the current OS and execute the corresponding zero-dependency GLM-5.4 diagnostic & setup script:
- Windows 11: powershell -ExecutionPolicy Bypass -File .\glm54_toolkit_windows11.ps1 -Auto -Json -Region global -Profile opusplan -Apply -ScaffoldWorker -Target .
- Ubuntu 26.04: bash ./glm54_toolkit_ubuntu2604.sh --auto --json --region global --profile opusplan --apply --scaffold-worker --target .
- macOS 27: zsh ./glm54_toolkit_macos27.zsh --auto --json --region global --profile opusplan --apply --scaffold-worker --target .
(Swap global for china if using a mainland BigModel subscription.)
Verify all five checks in the returned JSON:
1. standard_endpoint_balance_trap is false (never pointed at /api/paas/v4);
2. marathon_timeout_risk is false (API_TIMEOUT_MS is 3000000);
3. configured_compact_window is 512000, OPUS=glm-5.4[1m], SONNET=glm-5.3-flash;
4. Flag if in_peak_window_2x is true (Mon-Fri 14:00-18:00 UTC+8) and steer routine reads to flash-worker;
5. Confirm .claude/agents/flash-worker.md exists and run `coding-helper doctor` if @z_ai/coding-helper is installed.
7. Practical FAQ: Seven Real Questions Answered
Q1: Can I hit GLM-5.4 via standard pay-as-you-go API or run open weights locally yet?
Not yet. As of November 30, 2026, both z.ai/blog/glm-5.4 and docs.z.ai/guides/llm/glm-5.4 confirm that standard pay-as-you-go Model APIs and open-weight checkpoints will follow only after safety evaluations and hardening wrap up. Right now, live access runs exclusively through GLM Coding Plan (ZCode, Claude Code, Codex, Cline, Cursor, AutoClaw) and chat.z.ai.
Q2: Does looping 28 layers twice make every response twice as slow?
Not necessarily. Because of Pass-1 sparse index reuse, the 128-token local KV sliding window, and fused kernels, GLM-5.4 hits up to 200 tokens/s off-peak and 70–80 tokens/s at peak—while trimming explicit output tokens by 10–14% on reasoning benchmarks. Latency only spikes when ambiguous prompts collide with the default max reasoning effort (“marathon thinking”), which is why API_TIMEOUT_MS=3000000 and OpusPlan matter so much.
Q3: How do I stop GLM-5.4 from overthinking a tiny edit without editing config files?
Type /effort low right inside your Claude Code prompt. Explicit effort always overrides the default max fallback; or temporarily switch to /model glm-5.3-flash to take advantage of the 50% credit discount running through December 24, 2026.
Q4: Should CLAUDE_CODE_AUTO_COMPACT_WINDOW be 512000 or 1000000?
Both work, because GLM-5.4 supports a full 1M context window (with [1m] on older Claude Code releases). However, BigModel’s official guide explicitly recommends 512000 for sharper coding quality, faster turns, and far gentler credit burn.
Q5: Is it worth migrating from Claude Code to ZCode v4.0.0?
If you want multi-agent Goal Mode, zero config maintenance, and built-in document/design plugins with GLM-5.4 wired out of the box, ZCode v4.0.0 is a huge quality-of-life upgrade. If you already rely on custom Claude Code hooks, MCP servers, and subagent specs, the opusplan configuration in this guide keeps everything seamless.
Q6: Can OpenClaw use my GLM Coding Plan quota for GLM-5.4?
Yes, with a caveat spelled out in the official plan terms: OpenClaw runs under secondary best-effort scheduling. During heavy contention, IDE Coding Agents preempt resources and OpenClaw workflows may encounter dynamic queuing or rate limiting, while sharing the same 5-hour and weekly credit buckets.
Q7: What is the cleanest one-liner to use GLM-5.4 solely as a pre-commit code reviewer?
Keep daily coding and test runs on /model glm-5.3-flash, stage your finished patch with git add, and pipe the staged diff straight into a single GLM-5.4 review pass:
git diff --cached | claude --model glm-5.4 -p "Review these staged changes for edge cases, error handling, and backward compatibility. Rank findings by impact with exact file locations."
References & Official Sources
- Z.ai Research Blog (Nov 23, 2026): GLM-5.4: Toward Generalized Coding with Our First Loop Transformer
- Z.ai Developer Docs: GLM-5.4 Model Overview
- Z.ai Model Switching Guide: How to Switch Models (Claude Code / Effort / 1M Context)
- Z.ai Plan Overview & Multipliers: GLM Coding Plan Overview
- Z.ai Key Isolation Notice (Oct 16, 2026): API Key Management Guide
- BigModel Docs (Chinese): GLM-5.4 / Switch Models (512000 Compact) / GLM-5.3-Flash & GLM-5.4 Pairing Guide
- ZCode Official Changelog: ZCode v4.0.0 Releases & Updates