Feature Overview
The language services exist in two implementations — the TypeScript face and the Rust core (kode-server). kbengine.core.backend (ts | rust | shadow, default rust) picks who serves the interactive faces and how; the per-face matrix and selection guidance live in TS or Rust: choosing the backend.
Language Features
.defsyntax highlighting (built-in XML grammar delegation + engine semantic coloring)- Completion for types, Flags, DetailLevel
- Hover for tags, values, custom symbols
- Navigation between
entities.xmland.def - Manifest ordinal on
entities.xmlregistration hover (batch 147, the**Utype**line: the engine assigns utype inentities.xmllist order, so the ordinal is the first-occurrence position) - Merged def-chain hover (batch 148, closing source-analysis D5): hovering the root-level
<Parent>element in a.defpresents the def's inheritance closure in three facets — the recursive Parent chain, the flattenedinterfaces/list, and thecomponents/hookup — aligned with the engine's merge semantics; missing def files for parents/interfaces/components are stated as such, and cycles are truncated by a visited set and marked (the engine's loadParentClass has no cycle guard; kode does not copy that) - Entity reference navigation inside
.def - Types.xml symbol references (Shift+F12, IDE-NAV-017): custom type symbols in types.xml list every workspace use site (
.defproperty types,ARRAY of X/FIXED_DICTelement types,<Arg>values, other types.xml references); built-in types have no reference face; empty results show none rather than fabricating - Bidirectional Python ↔
.defnavigation - RPC method markers (functions in Python implementation scripts that hit def method declarations get a one-line clickable CodeLens jumping back to the def declaration)
- Per-feature switches for language features (batch 154): each of the four CodeLens kinds (RPC markers, event callbacks, property markers, the
types.xmlstorage lens chain) and the six hover kinds (custom-type storage,implementedBybacklink, entity registration, def chain, event stats, server config fields) gets its ownkbengine.*switch, all default on with no master switch; CodeLens toggles take effect immediately - Python property type inlay hints (batch 154):
self.<property>access sites inline thetypes.xmldata type declared in the def, resolved through the same index as property F12;self.base/cell/clientRPC call sites inline the declared parameter types (: type, type-only —.def<Arg>carries no parameter names; declared args only, section-gated), controlled bykbengine.inlayHints.typeData(inlay hints have no change event, so a toggle takes effect on the next render); array<of>element types inline afterfor item in self.<property>:targets andx = self.<property>[i]subscript-assignment locals (same resolution chain) - Python def-declared property type hover: hovering
self.<def 属性>shows the def-declared type (types.xml alias resolved down to the builtin, e.g. EQUIP_TRACK_LIST → FixedArray[EQUIP_INFO]); hovering afor-target or a subscript-assignment local infers the<of>element type (one level of local-variable indirection; empty<of>/ alias cycle / missing type give an honestAnywith the reason surfaced), gated bykbengine.entity.builtinProperties - FIXED_DICT sub-key type / completion / jump (KSEM-STRUCT-02): for a def property typed as a
types.xmlFIXED_DICT,self.<property>["key"](and.get("key")) resolves each layer's key against the<Properties>field names — completion offers every field of that layer's container (with its value annotation and thetypes.xmldeclaration line), F12 jumps to the field declaration line, and hover shows**key: <annotation>**with the declaration site; nesting and alias receivers work (self.info["pos"]["x"]→POSITION.x: float), and an ARRAY element that is itself a FIXED_DICT reaches the same face throughself.bag[0]["x"]; the access forms are the engine's real ones (string subscript and dict methods —FixedDicthas no attribute passthrough), so attribute-stylefd.<field>, an integer index on a dict, and a string key on an array field all decline honestly instead of inventing a type; a missing<Type>on the field leaves the annotation as an honestAny(hover shows no type rather than a fabricated one), and chains are bounded at 8 segments so a cyclic type graph stops instead of looping; the hover face sits insidekbengine.entity.builtinPropertieslike the sibling def-property type hover, while the completion and jump faces have no such gate (same as the cellData key faces) - FIXED_DICT element receivers (KSEM-STRUCT-03): the STRUCT-02 key faces now also work through receivers holding an array element — an iteration target (
for pos in self.bag:thenpos["x"]) and a subscript-RHS alias (d = self.bag[0]thend["x"]) both inherit the element structure (POSITION), so completion, F12 and key hover light up through them; a slice RHS (d = self.bag[0:2]) keeps the array shape, and a rawFixedArray[POSITION]annotation root enters the same chain; receiver typing is a bounded upward scan (200 lines, alias depth ≤ 2, nearest binding wins); illegal subscripts and dynamic forms decline honestly — an integer index on a FIXED_DICT, a string key on an array, call/arithmetic RHS,.values(), andenumeratetuple targets produce no keys instead of invented ones - FIXED_DICT construction-site check (KSEM-STRUCT-04): a whole dict literal assigned to a FIXED_DICT-typed target (
self.<prop> = {…}/ nestedself.<prop>["<key>"]… = {…}) is checked against the types.xml declared field set — missing declared fields, unknown literal keys and builtin-scalar field value structure mismatches are flagged askbengine.fixedDictConstructWarnings; plain dicts (bare-name targets, non-FD/scalar/array targets, augmented assignment, comparisons, call RHS) are never constrained;{**spread}/dynamic keys open the key universe (missing unreported, unknown literal keys still report); scalar ranges stay with the range lane and nested dict literals are not descended - def-property scalar assignment check (KSEM-STRUCT-05): a whole-line literal assigned to a target resolving to an engine scalar (
self.<prop> = <literal>root face including alias chains,self.<prop>["<key>"]… = <literal>FD-field face,self.<prop>[<int>] = <literal>array-element face) is judged for structure mismatch (string/bytes/vector/None) and integer out-of-range (BigInt-exact bounds) against the same CELL-08 engine scalar truth, flagged askbengine.scalarAssignWarnings citing the declaration source; the engine scalar name is resolved at the registry level (never from Python type names),boolcounts asint, dict literals stay with the construction face; name/call RHS, unresolvable targets, FD containers, array FD elements and mixed chains decline honestly - implementedBy binding resolution (KSEM-STRUCT-06): the types.xml custom-type hover resolves
implementedByto its real Python binding — engine truthloadImplModule(exactly two segments, class/def/assignment all legal), real-import resolution with package__init__.pywinning over a same-named.py(CPython package precedence, verified locally), symbol form classified as class/function/object (alias one hop to a single same-file class/def binds as object); duplicates (same-symbol multi-definition, same-module across user_type roots), dynamic assignment RHS and missing module/symbol all stay unknown with the engine-evidenced reason in the hover - Object vs transport representation (KSEM-STRUCT-07):
implementedByredefines a FIXED_DICT's in-memory form (impl-defined access — the official example is alistsubclass); FIXED_DICTPropertieskeys only describe the transport/storage form the engine restores atgetDictFromObjboundaries — dict-key faces (subscript completion/hover/definition, scalar-assign chain, dict-literal construct check) no longer resolve through an implementedBy container, an implementedBy receiver's string-subscript hover shows a mechanism note, and the custom-type hover frames Properties as “transport/storage form” (plain types unchanged); non-FD custom types were already outside the aliasType gates — pinned - Type stubs aligned with editor results (KSEM-STRUCT-08): the custom-type registry is deduplicated once at extraction with the engine rule (
datatypes.cpp addDataTyperejects duplicate registration —types.xmlfirst,alias.xmllater, first occurrence wins), and that single dedup feeds the pyi stub emission plan, the interactive annotation-resolution chain, and the entity-stub annotation map alike, so a name declared in both files (or twice in one) resolves to the same entry in generated stubs and in completion/hover/definition; cycles, unknown types, and cross-mirror-dir same names keep their existing consistent behavior (shared resolver / Any both ways / separatekbe_typesmodules) — pinned - Def property read-only view inlay (C-22): a whole-line comment containing the anchor
# kode:props-from-defrenders, at the end of that line, the def-declared root-level property overview of the file's entity (name: typeper part, one hint per anchor; per-part hover gives the def declaration line, visibility domains, and persistence; an unresolvable type shows the bare name — honest, no fabricated annotation). Pure rendering that writes no code: the single source of truth stays the.def, property F12 still jumps straight to the declaration line, and FIXED_DICT sub-keys / component-slot members stay out of the overview (they have their own access-site hints); nothing renders for files with no owning entity or no properties; controlled bykbengine.inlayHints.defProps(toggle applies on the next render) .defproperty/method F2 rename (same-file declaration + descendant def restatements, see the boundary note on the language page)
Diagnostics
- Unknown type check
- Unknown Flags check
- Unknown DetailLevel check
- Duplicate definition check
- Missing
Type/Flagscheck - Duplicate entity registration check in
entities.xml(batch 147): the engine silently merges same-name entries, keeping the first one, so later entries never take effect; kode flags them with a warning, gated by thekbengine.enableDiagnosticsmaster switch - Behavior-knowledge lints (C-23): three knowledge-grounded Python diagnostics delivered from the traps-index entries — FIXED_DICT sub-key assignment never syncs (
kbengine.fixedDictNestedMutation, with a whole-reassign quick fix),selfregistered into a module-level container without per-container removal inonDestroy(kbengine.destroyedEntityReference), and a class-bodyKBEngine.addTimer(…, repeat≠0, self.callback)with noKBEngine.delTimerinonDestroy(kbengine.timerLeakOnDestroy; entity-levelself.addTimeris never flagged); each behind its ownkbengine.*Diagnosticstoggle (default on), see the lint-rule guide for boundaries
Tool Panels
- Entity explorer
- Server control panel
- Log viewer
- Monitoring panel
- Entity dependency graph
- Entity architecture flow diagram
Notes: the log viewer has not completed the official logger watcher protocol adaptation. When the watcher does not respond, the monitoring panel keeps only the base status returned by machine.
Explorer sidebar layout (UX-REVIEW-011)
- Entities sits at the top of the KBEngine explorer (first view in the sidebar). Its title carries a count badge (total of the four root groups) once the tree has rendered at least once — the tooltip breaks the count down to Entities / Types / Interfaces / Components, and an empty project shows no badge at all
- Get Started right below drives project identification; it reports honestly through scanning / not-found / failed states and offers the real retry/report commands
- Component Status is hidden until the engine is ready (
kbengine.engineReadycontext key, set by the Get Started state machine) — before that its machined-discovery poll would just show noise - Config view title buttons:
Show Final Server ConfigandConfig Merge Visualization(the merge-resolution webview panel) are one click on the Config view title — they are also on the command palette
Raw Log ERROR Scan (inventory G6)
- The
Scan Raw Log Errorscommand picks raw log files or a folder (a folder scans one level of.log/.txt/.out, sorted by name and deduped); the same parser the log panel uses picks out theERROR/CRITICALlines - Aggregation is by "component + normalized signature" (numbers folded to
N, whitespace collapsed, signature truncated to 160 characters); the panel shows count / level / component / signature / most recent time, clicking a row opens that line in the source file, and "Rescan" reruns over the same file set - Does not depend on the logger watcher protocol: this path keeps working when the logger channel is not connected; 64MB cap per file, and an oversize or unreadable file is recorded as a readError without interrupting the rest
Telnet Probing and Session Integration
- Telnet-related content shows only when telnet is explicitly enabled (an explicit port in the settings, or a
<telnet_service>section in kbengine.xml); with neither configured there is no probing and no display — the status light, the standalone tree view, and the panel command entries are all hidden. The engine defaults do contain a<telnet_service>section, but defaults only provide value fallbacks and do not switch telnet on by themselves - Status bar and server control panel status light: connected / enabled·no password / password rejected / not enabled / not configured
- Target resolution chain: kode settings (
kbengine.telnet.host/port/password) → the componentkbengine.xml<telnet_service>section (specified viakbengine.telnet.configXmlPath; when unspecified,kbengine.assetsRoot/kbengine.xmlfirst, then convention paths probed at the workspace root:kbengine.xml,res/server/kbengine.xml,assets/res/server/kbengine.xml) → the enginekbengine_defaults.xml(inferred viakbengine.binPath). Port and password each take the first non-empty value in this order;.kbengine/debug.jsondoes not participate in telnet probing - Probing defaults to one round per 5 seconds, 1.5s timeout per port, sockets destroyed after each probe
- When the port is up, handshake login happens automatically; the password goes over the socket only and never into logs
- Panel command input goes through a whitelist plus built-in read-only shortcuts;
:quitis always rejected - A disconnected status can flip back and reconnect; a dropped session does not crash the panel
Debugging Support
The debug config reads only the workspace
.kbengine/debug.json:telnetHost/telnetPort/telnetEnableCommandsserve only theStart Debuggingprompt wording,pathMappingsis used to generate launch.json; telnet probing/panel/status light follow the three-layer chain above and do not read this fileThe generated launch config is a
debugpyattach form; local attach has the extension list local processes (matches on component names pinned and marked ✓), and selecting one assembles the config by PID — no more hand-typing PIDsRemote attach (
kbengine.debug.attachRemote) targets come from the settingkbengine.debug.remoteTargets, connecting in debugpyconnectmode straight to the remote debugpy listening portDebug model: first send the enable-debugging command into the component via telnet, then attach to the target process
Two attach modes (IDE-PDBG-001): a component with a configured
debugpyPort(> 0, optional companiondebugpyHost) in.kbengine/debug.jsonalways attaches in port mode —Start Debuggingskips the telnet briefing and dialsdebugpyHost:debugpyPort(default host127.0.0.1) in debugpyconnectform, andAttach to Componentfollows the same dispatch; a component without a configured port asks once which mode to use — port mode (connect; with no explicit port the per-component table applies: baseapp 5678 / cellapp 5679 / loginapp 5680 / dbmgr 5681 / logger 5682, otherwise 5678) or process attach mode (the local process picker assembling the config by PID) — and the choice is remembered in workspace state so later attaches go straight through; the first-time prompt's "清除记住的选择" aborts this attach without remembering, andkbengine.debug.resetAttachMode(palette:Reset Debug Attach Mode Choice) clears the memory so the next attach asks againPort mode expects a listener: engine processes never start a debugpy listener on their own — the embedded Python must reach a
debugpy.listen(port)(or equivalent bootstrap) before the IDE can connect. kode ships three ready-made paths there:kbengine.debug.autoDebugpyinjectsdebugpy.listenthrough the component's telnet after start-up, the opt-inkbengine.debug.waitAtStartupinserts alisten+wait_for_clientbootstrap at the earliest Python point, andkbengine.python.debugpySynccopies the debugpy package into<assets>/scripts/common/debugpysoimport debugpyresolves inside the enginePort-mode pre-probe (IDE-PDBG-002): before connecting, kode probes the debugpy port over TCP (1.5 s, same pace as telnet probing); an open port attaches straight away with zero extra dialogs, while a closed port names the cause — nobody listening / network timeout / host unresolvable — and, when the local interpreter chain lacks debugpy (or its version is too old), offers a one-click install (
<interpreter> -m pip install -U debugpy) or a manual guide; an install failure reports the pip exit code and output tail honestly, and after a successful install the port is re-probed — installing the package alone never opens the port, so a still-closed port moves on to the "next step" guidance instead of stopping there: the notice carries the current not-listening cause, the three listening paths and the launch.json landing spot, with three controls —起监听并附加(make sure debugpy is synced into<assets>/scripts/common/debugpyfirst, wait for the component's telnet to be ready, senddebugpy.listenthrough its:pythonlayer, then re-probe the port and attach right away; failures are reported as they are) /重试附加(re-probe directly — if the listener came up elsewhere it just connects) /起监听指引(the three paths plus a copyablepython -m debugpy --listen 127.0.0.1:<port> --wait-for-client <entry script>). Every port-mode attach also idempotently writes that component'shost:portconnect entry into.vscode/launch.json(type/request/connect; user entries and hand-edited fields kept as-is, superseded same-component port entries recycled; a file with comments or broken syntax is refused with the reason stated) so Run and Debug can F5 straight into it; kode never attaches into a voidpy-spy profiling entry (IDE-PDBG-003): the Servers tree carries a
$(pulse)icon right after the debug attach icon; picking a component (tree node or picker) and a process (the existing picker, component matches pinned ✓) runspy-spy dump --pid <pid> --nonblockingand writes the Python call stacks to theKBEngine py-spyoutput channel — nonblocking never pauses the target process. py-spy missing locally asks once and installs via<interpreter> -m pip install -U py-spy(failures honest, no retry loop); permission failures carry the ptrace guidance: py-spy reads the target stack via ptrace, so Linux needskernel.yama.ptrace_scope=0(or sudo/cap), containers need--cap-add=SYS_PTRACE, Windows needs an elevated or same-user sessionRemote servers view and dispatch (IDE-PDBG-004): the
Remote Serversview (KBEngine explorer) lists the hosts from~/.ssh/config— HostName/User/Port/ProxyJump parsed per Host block, wildcard and negated aliases hidden — plus manually added hosts, with本地(直接执行)always first and selected by default; picking a node (or the paletteSelect Remote Server) stores the choice in workspace state and every debug / py-spy dispatch follows the precedence componentsshHost>debug.defaultSshHost> view selection > local. On a remote target, port-mode attach opens anssh -N -Ltunnel (BatchMode, jump chain and port from the config) and connects to127.0.0.1:<localPort>, keeping the tunnel up until the debug session it started terminates (a failed/cancelled start and the extension unload still close it); py-spy probe/install/dump all run overssh <host> -- …. Aliases absent from the config connect by their bare name (ssh semantics);Includedirectives are not expanded — hosts living in included files don't show up in the view. A tunnel or host that never comes up fails honestly (exit / not-ready reason naming BatchMode password-free login), never a fake attachRemote process picker alignment (IDE-PDBG-005): on a remote target the process list comes from
ssh <host> -- ps -axo pid=,comm=and the picker is the same face as local — component-name matches pinned ✓ on top, description carrying the PID; a listing that cannot be fetched (ssh exit / timeout / unreachable) reports the host and cause honestly and opens no picker — it never falls back to the local list pretending it is the remote oneIn-editor validation (batch 136 G3): kode ships a JSON Schema for
.kbengine/debug.json(contributes.jsonValidationmatching**/.kbengine/debug.json), so the VS Code JSON extension flags wrong types,telnetPortwritten as a string, apathMappingsentry missinglocalRoot/remoteRoot, or amethodoutside the whitelist before you save; validation is a hint only — the parser still drops bad entries and falls back per field as beforeScaffolded when missing (batch 143): when
.kbengine/debug.jsonis absent from the workspace, activation creates.kbengine/in the effective working directory and writes an annotated skeleton; the skeleton is written as JSONC (//and block comments allowed, same convention astsconfig.json) and kode strips comments before parsing, so your own comments never break config loading. An existing file is never overwritten; if the directory is not writable it only reports that plainly on the "KBEngine 配置" output channel, leaving every other capability intact
Notes: KBEngine components are C++ processes with embedded Python runtimes; debugging is attach-based — there is no "extension launches a Python script" form.
Final Config View
- Synthesizes the final effective configuration per the engine's loading rules: load the engine default
kbengine_defaults.xmlfirst, then override with the componentkbengine.xml(child keys aligned by name); a read-only virtual documentkbengine-final.xml, never written to disk - Three entries: the "Final Config" node in the sidebar Config view, the
Show Final Server Configcommand, and an automatic background open after activation (kbengine.showFinalConfigOnOpen, default on) - Auto-recomputed after defaults or the component
kbengine.xmlis saved (kbengine.autoRefreshFinalConfig, default on); hovering a field shows what it does - Layering rules and a before/after comparison: the "server config three layers" section in the configuration reference
Property → Database Hints and the Schema View
- Persistent property hovers append a "database storage" line: the full
`db`.`table`.`column`name + the engine DDL fragment (column type,not null,DEFAULT) + concrete value constraints (integers per MySQL ranges, varchar per the parsed length; default 255 when<DatabaseLength>is absent,entity_table_mysql.cpp:1829-1833); same-DDL columns merge into one line (a vector's three columns as one) - ARRAY / component properties are not in the main table: the hover explains which child table the data lives in and the
parentIDrelation, and F12 lands on the child table row in the schema (child tables carry a父表:note) - Connection details are read straight from the engine's own config (nothing hand-filled): the synthesized
<dbmgr><databaseInterfaces><default>(engine defaults + componentkbengine.xmlsame-key override), port0falls to the MySQL default 3306 (db_interface_mysql.cpp:166-167); the password is read only when<encrypt>false</encrypt>(plaintext config) and never displayed;encrypt=trueRSA ciphertext is not deciphered. Read values are cached per "workspace + binPath" and re-read wheneverkbengine*.xmlor the config changes - Schema view (
kbengine.database.open): Chinese-label rendering (batch 133). The header gives the entity name,存储引擎,定义文件, and a表: N 张 · 列: M(其中 .def 声明 K)overview, plus数据库: 库名@host:端口when the config is readable, then a "how to read this" legend (tbl_/sm_prefixes, engine columns not from def,parentIDrelation, flag meanings, SQL paste usage); each table is tagged with表类型(entity table / component table / array child table),定义来源(workspace-relative path), and父表:; fields split into "engine columns (created automatically by the engine, no.defdeclaration needed)" (id/autoLoad/parentID/ the six position-and-orientation columns, each with fixed semantic annotations) and "property columns (declared in.def)"; property column row ends carry← 文件:行 <属性>pointing at the def origin; a table with only engine columns honestly notes属性列: 无(本表只有引擎列,没有 .def 声明的数据列); each table ends with three pasteable SQL lines (full SELECT, aSQL(属性列)with only def property columns, and a child table'sSQL(子表 JOIN)joining the parent viaparentIDwith aLEFT JOINpreserving empty-element property rows); all carry the database/table prefix and backtick escaping; when the database name is unreadable it degrades to table-level full names, still valid - The table prefix is overridable: the setting
kbengine.db.tablePrefix(default empty = engine defaulttbl_), substituted in the same source for table names and the three SQL templates; ARRAY child table hovers likewise give a pasteable JOIN - types.xml type forms and reference back-scan (batch 134): type declaration name hovers append the "database form" (builtin lands as a main-table single column with its type, FIXED_DICT flattens into columns without a table, ARRAY becomes a
tbl_<Entity>_<Property>child table with one recursive level of element columns, unresolved types state plainly that engine loading will fail); above each declaration line a CodeLens back-scans the real reference sites (Hero.itemId → tbl_Hero.sm_itemId), clicking opens that entity's schema view at the matching column, folding into a count lens beyond 10 sites, invalidated and rescanned when.def/types.xml/entities.xmlchange; back-scan sites come from the schema snapshot (same engine semantics as the rendering), no separate persistence rules invented - Database drift check (
kbengine.database.checkDrift/checkAllDrift): compares missing tables / columns, extra columns, type / nullability / default / index differences, and residual tables; checks one or all workspace entities. Connection info comes from engine config (encrypt=falseplaintext password); queries and sessions remain read-only; connect and each query run underkbengine.databaseQueryTimeoutMswith a cancellable progress notification — timeout or cancel returns with that reason and releases the connection (the table preview and schema impact preview commands run under the same deadline and cancel). Schema impact preview (kbengine.database.previewSchemaImpact) diffs one entity's real table structure against the def-derived virtual schema and prints the added / removed / type-changed list a sync by the current def would cause — read-only, no DDL anywhere. Real drift runs save evidence keyed by engine version (kbengine.database.showDriftEvidencere-views it; an undetectable version stays unknown — no compatibility claim). See Database Drift Check
Database Simulation
- Simulates table creation and row data on top of a database schema snapshot: a
.dbsimvirtual document shows DDL, simulated row JSON, INSERT statements, and the engine difference list together - DDL aligns item by item with the engine's MySQL persistence implementation (
tbl_prefix,parentIDchild column,sm_autoLoad, per-type column types,(@DATALEN@)empty-width stripping,ENGINE=InnoDB); sources in Database Simulation - Row validation follows strict engine semantics: any failed check rejects the whole statement; DELETE cascades child tables recursively; the UNIQUE pre-check is something the simulator does beyond the engine and is registered honestly
- Entries:
Simulate Entity Database(entity inferred from the active.defwhen no name is passed) andExport Entity Database Simulation(export as Markdown)
Config Auto-Discovery
- A clean workspace needs zero configuration for core features (open a
.def→ entity explorer / dependency graph / flow diagram / property panel / database schema / hovers) - Discovery chain: explicit config → convention layouts → bounded deep scan (depth 7 / 20k entries, pruning node_modules/.git etc.) → a unique hit is used; multiple candidates pop a quick pick once during activation and remember per workspace
- The server assets root
kbengine.assetsRootfollows the same chain (batch 128): the original value is validated with the engine-loading proberes/server/kbengine.xml; on failure it goes through the convention chain (workspace root, assets/, server_assets/) → remembered choice → deep-scan unique hit fallback; telnet probing and the final config view benefit in sync - Index scan root (2026-11-23): the Python/def index scans only
{assetsRoot}/scripts; when thatscriptsdirectory is missing the scan-root list is empty (no fallback to the assets root itself or the workspace top level, which used to pull engine repos, dependency trees and build output into the index); a configured-but-invalid assets root is an empty scan root too (explicit configuration is an intent, not a guess); only a genuinely non-KBEngine workspace keeps the legacy per-folder scan, still narrowed to ascriptssubdirectory when present - Pure discovery, no settings:
types.xml,messages_fixed(_defaults).xml, and the engine defaults' source-root fallback; sub-paths derived from the def root (interfaces/components/user_type) do not enter the settings - Location failures are no longer silent: the
kbengine.discovery.reportcommand lays out the discovery result key by key in the OUTPUT panel (final chosen value and source, explicit-config existence, convention-chain hits/misses, deep-scan hits, remembered choices, deep-scan truncation markers), with per-item remediation advice; the whole report can be copied back to maintainers - See the "path-like config auto-discovery" section and the full comparison table in the configuration reference
Python Ecosystem Wiring (inventory G1 / G2)
- extraPaths wiring (batch 136 G1): writes the KBEngine scripts roots discovered in the workspace into
python.analysis.extraPaths(workspace-folder level) in${workspaceFolder}/...variable form — legacy absolute paths with the workspace-root prefix migrate automatically, paths you typed yourself are otherwise never touched; the same sync setspython.analysis.stubPathto${workspaceFolder}/.kbengine/stubs(Pylance priority: same-name .pyi → stubPath → extraPaths); nothing is written when nothing changed, and a workspace with no discoverable root is skipped silently. TheSync Python Extra Pathscommand reruns it manually; activation syncs once with zero prompts (kbengine.python.extraPathsSyncon by default, disableable) .pyistub export (batch 136 G2): exports the built-in KBEngine Python API symbol index (same source as completion/hover/navigation) as a realKBEngine.pyifile — virtual stub documents are invisible to the Python extension, and only a real file plus the extraPaths wiring resolvesimport KBEngine; identical content is a zero-write, a stale stub is rewritten, activation does it once silently, and theExport KBEngine Python Stubsmanual entry chains one extraPaths sync after a successful export- Configurable stub directory (batch 142):
kbengine.python.stubDirresolves in three tiers — setting >KBENGINE_STUB_DIRenvironment variable > the default convention.kbengine/stubs. The default directory is managed by kode (refreshed by content comparison); a directory you specify is scan-only: any.pyialready in it counts as your asset and is never overwritten, kode only generates when there is none, and an unreadable directory is reported plainly instead of being written blindly - types.xml type stubs (def-pyi-stubs §6): exports the
entity_defs/types.xmlcustom types into a real.pymodulekbe_types.py(FIXED_DICT→TypedDict,ARRAY→List[element], aliases → type names; aliases in dependency topological order, cycles/empty directives skipped with a stated reason) — a real module is both a Pylance type source and runtime-importable viaimport kbe_types; it shares the directory and switch withKBEngine.pyi(kbengine.python.stubExport), its deterministic content upholds the zero-write discipline, and theExport KBEngine Python Type Stubsmanual entry chains one extraPaths sync after a successful export, and aftertypes.xmllands on disk (save/create/delete) the watcher silently regenerates it - Entity stub auto-regeneration on def change (C-22): creating/changing/deleting any
.defregeneratesentity_types.pyiafter a 400 ms trailing debounce (collapsed across bursts) and refreshes theentity_types.pyisource-mirror CodeLens plan in place — previously the generated stub went stale until a window reload; the regeneration shares thekbengine.python.stubExportmaster gate and the content-compare zero-write discipline, and a failed regeneration does not refresh the lens plan. Scope:.deffiles only (types.xml already has its own regen path; entities.xml is not wired yet)
Variable Substitution (batch 141)
- Path-like settings, the
quickActionsandworkspaceRootof.kbengine/debug.json, andkbengine.python.stubDirall go through one set of official VS Code variable substitution instead of each writing its own - Supported:
${workspaceFolder},${workspaceFolderBasename},${file},${fileBasename},${fileBasenameNoExtension},${fileDirname},${fileExtname},${relativeFile},${relativeFileDirname},${cwd},${userHome},${pathSeparator},${env:NAME} - The relative-path family only yields the relative form when the file sits under some workspace root, falling back to an absolute path otherwise; unknown variables follow two policies by semantics — quick action execution fails and names the variable (a silent empty string would run the script as a fake success with an empty path), while path-like settings fall back to an empty string per the existing convention
HTTP Quick Requests
- The
kbengine.httpRequestslist holds: name / URL template / method / headers / body / enable flag / keybinding display string - Template variables
${module}/${file}/${line}/${sel}, replaced literally without URL encoding;${module}is the workspace-relative module path (entities/fight/FightAI.py→entities.fight.FightAI) - Two trigger paths: a command-palette quick pick; a keybinding for
kbengine.httpRequest.runwithargs.namein keybindings.json fires directly - Execution logs go to the OUTPUT panel "KBEngine HTTP 快捷请求"; failures are marked with
✗plus an error popup
Field and variable tables in the configuration reference; command details in Commands and Panels.
Quick Actions
- The action list lives in the workspace
.kbengine/debug.jsontop-levelquickActionsarray (travels with the KBEngine project, not in VS Code settings, not inlaunch.json) - Three whitelisted backend kinds:
command(a VS Code command),script(a script explicitly declared in the config),http(a local hot-update URL written into the config); no arbitrary shell entry - Two trigger paths: the Servers view title bar button + top-right buttons in
.def/ Python / XML editors + the command paletteRun Quick Actions - Actions pop a modal confirm by default; logs go to the OUTPUT panel "KBEngine 快速执行动作"; a failure pops once and keeps the exit/status code
- First-time config creation scans
.bat/.ps1files in the effective config root andassetsRoot; scanned actions run with the script's containing directory ascwd.Rescan Scripts for Quick Actionsrefreshes scanned entries while preserving manual actions .ps1runs through PowerShell; script actions can optionally enable a Python venv and choose its path, or auto-discover.venv/venv- First install scans one level of workspace-root
.batand.ps1files; all of them appear in a multi-select registration prompt (keyword lists only assign a category); canceling stops the auto-prompt for that workspace
Command details in Commands and Panels; config keys and variable tables in the configuration reference.
Auto Hot Reload (inventory G5)
- A file save / watcher event triggers the
quickActionsaction named above. The gatekbengine.hotReload.enabledis on by default (user order 2026-11-06): a fresh workspace watches**/*.pyout of the box, and with noactionNamea save posts the default hot-reload request tohttp://127.0.0.1:8090/hotfix?module_name=<module>(module_name=<module>in both the query and the body), reporting an unreachable engine as failed. One-key off = clicking the 「热更」 status bar item orkbengine.hotReload.toggle; the first activation shows one dismissible non-modal notice. Toggling takes effect immediately, no window restart needed - Change, create, and delete all count as save events and are merged into one execution by debounce; the trigger path skips the execution confirm, while action failures and unexpected async errors are caught and reported without an unhandled Promise rejection
- When
actionNameis empty or matches no action, the event still fires but only writes one line to the OUTPUT channel "KBEngine 快速执行动作" — no popup, no execution - For
httpactions the real response feeds the per-target ledger: 2xx lands as delivered-unverified (or upgraded to accepted only when the body echoes the sent file verbatim under the documented receipt protocol), non-2xx lands failed naming the status; unknown bodies stay unverified. Anappliedclaim needs double evidence — the receipt's sha256 digest must match the sent file content — and anything less (missing runtime protocol, unreadable content, digest mismatch, verification timeout) stays unverified with the blocking reason recorded - A
.deffile in the batch goes through a structural gate first: serialization/RPC-parameter changes (property or method add/remove, type/flags/signature change) block the whole batch from the plain reload with a restart-required warning; comment/whitespace-only def edits and pure-Python batches send normally kbengine.hotReload.showBatchSummaryrolls the whole per-target ledger up into the log channel: mixed batches show partial with every failed target named, and each target's per-file reasons stay viewablekbengine.hotReload.retryFailedre-sends only the failed targets through the real quick-action entry (confirmed-successful targets are never re-sent); it runs under a cancellable progress notification — after cancellation nothing further is sent — and a successful retry turns the ledger page through the same receipt/verification faces as the fire pathkbengine.hotReload.showRevisionEvidenceshows per-file revision evidence with source labels: locally recomputed fileHash,.defstructural semanticHash, and the runtime-reported engineDigest (attributed only to the file the receipt echoes); kinds are never compared across classes and missing kinds stay missingkbengine.hotReload.configureChannelis the per-profile deploy-level channel panel (IDE-HOT-102): pick a channel (unset / KBEngine official / custom HTTP) with a connectivity test button (probe never saves); with a channel configured on the active profile the whole reload batch goes throughtransport.send— receipts (sent/accepted/applied/failed) feed the per-target ledger directly — while an unconfigured profile keeps the existing actionName path unchanged- Every reload action is audited with five elements (who / when / which files / channel / outcome) in the 「KBEngine 热更新」 OUTPUT channel, shared by all three faces: the deployment channel (channel kind), the actionName fallback (
actionName:<name>), and the structural-def gate hold (channel = 拦截:需重启); ledger records carry the trigger source and channel alongside
Dependency Graph
- Mermaid visualization
- Inheritance and
ENTITYCALLrelations - Click-through to entity definitions from the graph
- SVG export
- PNG export
Flow Diagram
- Method calls from the client to baseapp/cellapp and automatic property synchronization, as a Mermaid visualization
- Edge semantics annotated per property
Flagsbits, each edge listing the engine source (file:line) and the member declaration site - Clicking a member row jumps back to its
.defdeclaration - Unexposed BaseMethods listed separately as "methods the client cannot call"
- Refresh re-reads the
def/entities.xmlon disk - Exports Markdown, SVG, PNG
Code Generation
- Entity creation wizard
- Preset templates (10: account, role, NPC, item, monster, scene, guild, team, mail, empty entity)
- Automatic
.defgeneration - Automatic Python generation
- Automatic registration into
entities.xml - Client entity SDK generation (generates client skeletons for entities registered in
entities.xml; TypeScript / C# / Python multi-select) - Definition form wizard (batch 139, inventory G7): beyond the entity wizard, generates one form per run — proxy (a Proxy def under
proxy_defs/whoseParentpoints at the proxied entity; the engine loads defs fromentity_defs/only, so the header and the outcome note say the file has to move there and intoentities.xml), space (registershasBase+hasCellinentities.xml), component (a def undercomponents/, optionally mounting aCOMPONENTproperty at the end of the entity's<Properties>block), fixed-dict type (written intotypes.xml). Existing files are not overwritten by default; duplicate registrations and malformed structures are reported plainly rather than force-inserted
Notes: the generator is affected by the kbengine.generator.* settings and writes entities.xml to the fixed {assetsRoot}/scripts/entities.xml location; the client entity SDK by kbengine.clientSdk.outputDir.
Performance Analysis
- Full-workspace
.defstatic checks (theAnalyze Def Performancecommand) - Optimization suggestions written to the output panel and dropped into the problems list as diagnostics
Snippet Generation
- Generate custom snippets from a selection (the
Generate Snippet from Selectioncommand) - Snippet grammar escaping and common-indent stripping (per the editor's
tabSizecolumn semantics, mixed tabs/spaces keep relative levels), merged into.vscode/kbengine-custom.code-snippets