@dot-agent/language-server 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md ADDED
@@ -0,0 +1,156 @@
1
+ # Agent DSL Language Server — Agent Guidelines
2
+
3
+ AI collaboration guide for maintaining and evolving the LSP server for `.agent DSL` files.
4
+
5
+ ---
6
+
7
+ ## What this package is
8
+
9
+ A standalone [Language Server Protocol](https://microsoft.github.io/language-server-protocol/) server that provides all IDE intelligence for the .agent DSL. It speaks LSP over `stdio` and is shared by the VS Code extension, Zed, Neovim, Helix, and any other LSP-capable editor. The server is intentionally editor-agnostic — no VS Code APIs, no Electron, no DOM.
10
+
11
+ All structural analysis is performed on **tree-sitter ASTs** (not regex). `parser.js` owns the WASM parser lifecycle, document cache, and the helper functions that feature modules use to traverse parse trees.
12
+
13
+ ---
14
+
15
+ ## Module responsibilities
16
+
17
+ | File | Responsibility |
18
+ |------|---------------|
19
+ | `server.js` | LSP wiring — creates the connection, awaits `initParsers()` in `onInitialize`, registers all `connection.onXxx()` handlers, delegates to `features/` |
20
+ | `parser.js` | Tree-sitter engine — WASM initialization, per-document AST cache, and shared traversal helpers |
21
+ | `features/hover.js` | Hover documentation for all DSL keywords (static lookup, no tree traversal) |
22
+ | `features/completions.js` | Context-aware completions using `getContextNode` and `nodesOfType` for name lookups |
23
+ | `features/diagnostics.js` | Linting — dangling transitions, dead-end interact (AST), deprecated keywords (line scan), undeclared types (AST) |
24
+ | `features/definition.js` | Go-to-definition via `state_decl` / `type_decl` node lookup |
25
+ | `features/references.js` | Find all references via `transition_stmt`, `intent_trigger`, `type_ref` traversal |
26
+ | `features/rename.js` | Rename symbol — same traversal as references, produces `TextEdit[]` |
27
+ | `features/symbols.js` | Document symbol index from `state_decl`, `trigger_decl`, `agent_decl`, `type_decl` nodes |
28
+ | `features/formatting.js` | Indentation normalization (text-based, no tree traversal needed) |
29
+ | `features/links.js` | Document links from `behavior_block`, `schema_prop`, `merge_decl`, `run_stmt` nodes |
30
+
31
+ **Invariant:** `server.js` contains only LSP wiring. All analysis logic lives in `features/` or `parser.js`.
32
+
33
+ ---
34
+
35
+ ## Adding a new LSP capability
36
+
37
+ 1. Create `features/my-feature.js` exporting a `provideXxx(langId, tree, text, ...)` function.
38
+ 2. Import it in `server.js`.
39
+ 3. Wire it: `connection.onXxx((params) => { ... return provideXxx(langId, getTree(doc), doc.getText(), ...); })`.
40
+ 4. Add the capability to the `capabilities` object in the `initialize` response in `server.js`.
41
+
42
+ Never put analysis logic directly in `server.js` handlers — always delegate to a feature module.
43
+
44
+ ---
45
+
46
+ ## `parser.js` — tree-sitter API
47
+
48
+ | Export | Signature | Description |
49
+ |--------|-----------|-------------|
50
+ | `initParsers()` | `async () => void` | Initializes WASM parsers for both grammars. **Must** be awaited in `onInitialize` before any handler runs. |
51
+ | `parse(uri, langId, text, version)` | `→ Tree \| null` | Returns a cached `Tree`, reparsing incrementally when the version changes. Returns `null` if parsers are not yet initialized. |
52
+ | `evict(uri)` | `(uri) → void` | Removes a document's cached tree (call in `onDidClose`). |
53
+ | `nodesOfType(tree, type)` | `→ SyntaxNode[]` | All descendants of the given node type string. |
54
+ | `nodeAtOffset(tree, offset)` | `→ SyntaxNode \| null` | Deepest node at a byte offset. |
55
+ | `nodeToRange(node)` | `→ Range` | Converts a `SyntaxNode` to an LSP `Range` using `startPosition`/`endPosition`. |
56
+ | `positionToOffset(text, line, character)` | `→ number` | Converts an LSP `{line, character}` to a byte offset. |
57
+ | `wordAtPosition(text, line, character)` | `→ {word, start, end}` | Extracts the identifier (including dots) around a cursor position. |
58
+ | `getContextNode(tree, offset)` | `→ SyntaxNode` | Walks up past `ERROR`/`MISSING` nodes to find a clean context ancestor. Use in completions and hover to handle partially-typed input. |
59
+
60
+ Add shared helpers here — never duplicate tree traversal logic across feature files.
61
+
62
+ ---
63
+
64
+ ## Key node types
65
+
66
+ ### `.behavior` grammar
67
+
68
+ | Node type | Represents | Useful fields |
69
+ |-----------|-----------|---------------|
70
+ | `state_decl` | `state name block` | `name` (path) |
71
+ | `trigger_decl` | `on event "name" block` | `event` (quoted_string) |
72
+ | `merge_decl` | `merge "file"` | `path` (quoted_string) |
73
+ | `transition_stmt` | `transition to stateName` | `state` (path) |
74
+ | `intent_trigger` | `on intent "text" (transition to state \| block)` | `intent`, `state` (inline only), `block` |
75
+ | `offtopic_stmt` | `on offtopic block` | `block` |
76
+ | `run_stmt` | `run type "target" …` | `run_type`, `target` |
77
+ | `interact_stmt` | `interact [requiring "text"]` | — |
78
+
79
+ ### `.agent` grammar
80
+
81
+ | Node type | Represents | Useful fields |
82
+ |-----------|-----------|---------------|
83
+ | `agent_decl` | `agent Name …` | `name` (agent_name) |
84
+ | `type_decl` | `type Name …` | `name` (identifier) |
85
+ | `behavior_block` | `behavior file.behavior` | `file` (bare_string) |
86
+ | `schema_prop` | `schema file.json` | `file` (filename) |
87
+ | `type_ref` | `TypeName` or `ns.TypeName` | first named child = identifier |
88
+ | `input_block` / `output_block` / `requires_block` / `capabilities_block` | strict blocks | contain `typed_item`, `type_reference`, `cap_item` |
89
+
90
+ > **Known limitation:** `on offtopic transition to X` and `on fallback transition to X` in inline form (no block indent) parse as ERROR nodes in the current grammar. Those transitions are not captured by references/rename/diagnostics. Fix requires updating `offtopic_stmt` and `fallback_stmt` in `behavior/grammar.js` to support the inline form.
91
+
92
+ ---
93
+
94
+ ## Dependency constraints
95
+
96
+ Production dependencies:
97
+ - `vscode-languageserver` and `vscode-languageserver-textdocument` — LSP protocol implementation
98
+ - `web-tree-sitter` — WASM-based tree-sitter runtime
99
+ - `@dot-agent/tree-sitter` — Agent and Flow grammar WASM binaries
100
+
101
+ Do not add framework dependencies, bundlers, or anything that requires a build step on the language-server side. The server must start with a bare `node server.js --stdio` once the WASM binaries are in `@dot-agent/tree-sitter/dist/`.
102
+
103
+ The grammar WASM binaries are built by running `npm run build` in the `tree-sitter-agent` package (requires Emscripten). When published to npm, `dist/` is included in the package and no build is needed.
104
+
105
+ ---
106
+
107
+ ## Async lifecycle rule
108
+
109
+ `web-tree-sitter` initializes asynchronously. The `onInitialize` handler is the only safe place to call `await initParsers()`:
110
+
111
+ ```js
112
+ connection.onInitialize(async () => {
113
+ await initParsers(); // blocks until both WASMs are loaded
114
+ return { capabilities: { ... } };
115
+ });
116
+ ```
117
+
118
+ No feature handler will fire before `initialize` completes, so this guarantees parsers are ready before any `onHover`, `onCompletion`, etc. request arrives. Never call `initParsers()` outside `onInitialize`.
119
+
120
+ ---
121
+
122
+ ## License rules
123
+
124
+ - **Every new `.js` file** must carry the Apache 2.0 header using `/* */` block comment style at the top.
125
+ - No NOTICE file — npm dependencies are not distributed as source.
126
+
127
+ The Apache 2.0 header:
128
+ ```
129
+ /*
130
+ * Copyright (c) 2026 Danilo Borges (https://github.com/daniloborges)
131
+ *
132
+ * Licensed under the Apache License, Version 2.0 (the "License");
133
+ * you may not use this file except in compliance with the License.
134
+ * You may obtain a copy of the License at
135
+ *
136
+ * http://www.apache.org/licenses/LICENSE-2.0
137
+ *
138
+ * Unless required by applicable law or agreed to in writing, software
139
+ * distributed under the License is distributed on an "AS IS" BASIS,
140
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
141
+ * See the License for the specific language governing permissions and
142
+ * limitations under the License.
143
+ */
144
+ ```
145
+
146
+ ---
147
+
148
+ ## Key references
149
+
150
+ | Resource | Link |
151
+ |----------|------|
152
+ | Language specification | [language.md](https://github.com/daniloborges/dot-agent/blob/main/dsl/language.md) |
153
+ | Agent grammar (canonical) | [tree-sitter-agent/grammar.js](https://github.com/daniloborges/tree-sitter-agent/blob/main/grammar.js) |
154
+ | Flow grammar (canonical) | [tree-sitter-agent/flow/grammar.js](https://github.com/daniloborges/tree-sitter-agent/blob/main/flow/grammar.js) |
155
+ | VS Code extension | [vscode-dot-agent](https://github.com/daniloborges/vscode-dot-agent) |
156
+ | WASM execution engine | [dot-agent-kernel](https://github.com/daniloborges/dot-agent-kernel) |
package/LICENSE ADDED
@@ -0,0 +1,185 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contributions
78
+ with the Work to which such Contributions were submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any
81
+ Contribution embodied within the Work constitutes direct or
82
+ contributory patent infringement, then any patent licenses granted to
83
+ You under this License for that Work shall terminate as of the date
84
+ such litigation is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or as an addendum to
115
+ the NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the License.
117
+
118
+ You may add Your own license statement for Your modifications and
119
+ may provide additional grant of rights to use, copy, modify, merge,
120
+ publish, distribute, sublicense, and/or sell copies of the
121
+ Contribution, either in combined form with the Work or separate from
122
+ the Work. If You choose to provide additional grant of rights, You
123
+ must do so in a manner consistent with the terms of this License.
124
+
125
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
126
+ any Contribution intentionally submitted for inclusion in the Work
127
+ by You to the Licensor shall be under the terms and conditions of
128
+ this License, without any additional terms or conditions.
129
+ Notwithstanding the above, nothing herein shall supersede or modify
130
+ the terms of any separate license agreement you may have executed
131
+ with Licensor regarding such Contributions.
132
+
133
+ 6. Trademarks. This License does not grant permission to use the trade
134
+ names, trademarks, service marks, or product names of the Licensor,
135
+ except as required for reasonable and customary use in describing the
136
+ origin of the Work and reproducing the content of the NOTICE file.
137
+
138
+ 7. Disclaimer of Warranty. Unless required by applicable law or
139
+ agreed to in writing, Licensor provides the Work (and each
140
+ Contributor provides its Contributions) on an "AS IS" BASIS,
141
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
142
+ implied, including, without limitation, any warranties or conditions
143
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
144
+ PARTICULAR PURPOSE. You are solely responsible for determining the
145
+ appropriateness of using or reproducing the Work and assume any
146
+ risks associated with Your exercise of permissions under this License.
147
+
148
+ 8. Limitation of Liability. In no event and under no legal theory,
149
+ whether in tort (including negligence), contract, or otherwise,
150
+ unless required by applicable law (such as deliberate and grossly
151
+ negligent acts) or agreed to in writing, shall any Contributor be
152
+ liable to You for damages, including any direct, indirect, special,
153
+ incidental, or exemplary damages of any character arising as a
154
+ result of this License or out of the use or inability to use the
155
+ Work (including but not limited to damages for loss of goodwill,
156
+ work stoppage, computer failure or malfunction, or all other
157
+ commercial damages or losses), even if such Contributor has been
158
+ advised of the possibility of such damages.
159
+
160
+ 9. Accepting Warranty or Additional Liability. While redistributing
161
+ the Work or Derivative Works thereof, You may choose to offer,
162
+ and charge a fee for, acceptance of support, warranty, indemnity,
163
+ or other liability obligations and/or rights consistent with this
164
+ License. However, in accepting such obligations, You may act only
165
+ on Your own behalf and on Your sole responsibility, not on behalf
166
+ of any other Contributor, and only if You agree to indemnify,
167
+ defend, and hold each Contributor harmless for any liability
168
+ incurred by, or claims asserted against, such Contributor by reason
169
+ of your accepting any such warranty or additional liability.
170
+
171
+ END OF TERMS AND CONDITIONS
172
+
173
+ Copyright (c) 2026 Danilo Borges (https://github.com/daniloborges)
174
+
175
+ Licensed under the Apache License, Version 2.0 (the "License");
176
+ you may not use this file except in compliance with the License.
177
+ You may obtain a copy of the License at
178
+
179
+ http://www.apache.org/licenses/LICENSE-2.0
180
+
181
+ Unless required by applicable law or agreed to in writing, software
182
+ distributed under the License is distributed on an "AS IS" BASIS,
183
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
184
+ See the License for the specific language governing permissions and
185
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,186 @@
1
+ # Agent DSL Language Server
2
+
3
+ A standalone [Language Server Protocol (LSP)](https://microsoft.github.io/language-server-protocol/) server for the **.agent DSL** (`.description`, `.type`, `.behavior`) files. Shared by the VS Code and Zed extensions.
4
+
5
+ ## Features
6
+
7
+ | Capability | `.agent` | `.behavior` |
8
+ |---|---|---|
9
+ | **Hover** | Keyword documentation | Keyword documentation |
10
+ | **Completion** | Manifest keywords, custom types | Keywords, state names, memory domains (`context.`, `session.`, …) |
11
+ | **Diagnostics** | Deprecated keywords, strict block lint, undeclared types | Dangling `transition` targets, dead-end `interact` |
12
+ | **Go-to-Definition** | Type name → `type` declaration | `transition to stateName` → `state` declaration |
13
+ | **Find References** | All uses of a type | All `transition` references to a state |
14
+ | **Rename** | Type and its references | State and all `transition` references |
15
+ | **Document Symbols** | Agents, types | States, `on event` observers |
16
+ | **Formatting** | 0 / 2-space indentation | 0 / 2 / 4-space indentation by block depth |
17
+
18
+ > The VS Code extension adds two capabilities on top: **Behavior Graph** (Mermaid state diagram WebView) and **status bar** (current state indicator). Those are VS Code-specific and live in [`extension.js`](https://github.com/daniloborges/vscode-dot-agent/blob/main/extension.js).
19
+
20
+ ## Architecture
21
+
22
+ ```
23
+ ┌──────────────┐ LSP/stdio ┌─────────────────────────────────┐
24
+ │ VS Code │ ←──────────── │ server.js │
25
+ │ Zed │ │ ├── features/hover.js │
26
+ │ Neovim/etc │ │ ├── features/completions.js │
27
+ └──────────────┘ │ ├── features/diagnostics.js │
28
+ │ ├── features/definition.js │
29
+ │ ├── features/references.js │
30
+ │ ├── features/rename.js │
31
+ │ ├── features/symbols.js │
32
+ │ └── features/formatting.js │
33
+ │ parser.js (tree-sitter engine)│
34
+ └─────────────────────────────────┘
35
+ ```
36
+
37
+ The server speaks LSP over `stdio`. Each editor starts it as a subprocess and communicates via JSON-RPC messages.
38
+
39
+ All structural analysis uses the **tree-sitter** parse trees from [`@dot-agent/tree-sitter-agent`](https://github.com/daniloborges/tree-sitter-agent). `parser.js` initializes the WASM-based parsers during `initialize` and maintains a per-document AST cache with incremental reparse.
40
+
41
+ ## Prerequisites
42
+
43
+ The grammar package must have its WASM binaries built before first use:
44
+
45
+ ```bash
46
+ cd dsl/tree-sitter-agent
47
+ npm run build # requires Emscripten; generates dist/*.wasm
48
+ ```
49
+
50
+ When consuming the package from npm (published), `dist/` is already included — no build step needed.
51
+
52
+ ## Installation
53
+
54
+ **Standalone (Neovim, Helix, or any LSP-capable editor):**
55
+
56
+ ```bash
57
+ git clone git@github.com:daniloborges/language-server.git
58
+ cd language-server
59
+ # Build the grammar WASMs first (see Prerequisites above)
60
+ npm install
61
+ ```
62
+
63
+ **As a git submodule:**
64
+
65
+ ```bash
66
+ git submodule add git@github.com:daniloborges/language-server.git dsl/language-server
67
+ ```
68
+
69
+ ## Usage
70
+
71
+ Run directly over stdio:
72
+
73
+ ```bash
74
+ node server.js --stdio
75
+ ```
76
+
77
+ ### Neovim (nvim-lspconfig)
78
+
79
+ ```lua
80
+ local lspconfig = require('lspconfig')
81
+ local configs = require('lspconfig.configs')
82
+
83
+ if not configs.agent_dsl then
84
+ configs.agent_dsl = {
85
+ default_config = {
86
+ cmd = { 'node', '/path/to/language-server/server.js', '--stdio' },
87
+ filetypes = { 'agent', 'behavior' },
88
+ root_dir = lspconfig.util.root_pattern('.git'),
89
+ },
90
+ }
91
+ end
92
+
93
+ lspconfig.agent_dsl.setup {}
94
+ ```
95
+
96
+ ### Helix (`~/.config/helix/languages.toml`)
97
+
98
+ ```toml
99
+ [[language]]
100
+ name = "agent"
101
+ language-servers = ["agent-dsl-lsp"]
102
+
103
+ [[language]]
104
+ name = "behavior"
105
+ language-servers = ["agent-dsl-lsp"]
106
+
107
+ [language-server.agent-dsl-lsp]
108
+ command = "node"
109
+ args = ["/path/to/language-server/server.js", "--stdio"]
110
+ ```
111
+
112
+ ## VS Code Integration
113
+
114
+ The [VS Code extension](https://github.com/daniloborges/vscode-dot-agent) installs the server as an npm dependency and starts it automatically via `vscode-languageclient`. No manual setup needed — install the `.vsix` and the server starts with the editor.
115
+
116
+ ## Zed Integration
117
+
118
+ Configured in `zed-agent/extension.toml` under `[language_servers.agent-dsl-lsp]`. Note: Zed extensions with full LSP support may require Rust bindings depending on the Zed version.
119
+
120
+ ## Development
121
+
122
+ ### Adding a new LSP capability
123
+
124
+ 1. Create `features/my-feature.js` exporting a `provideXxx(langId, tree, text, ...)` function.
125
+ 2. Import and wire it in `server.js` via `connection.onXxx(...)`, passing `getTree(doc)` and `doc.getText()`.
126
+
127
+ ### Shared parsing helpers (`parser.js`)
128
+
129
+ | Export | Description |
130
+ |---|---|
131
+ | `initParsers()` | Async — initializes both WASM parsers. Called once inside `onInitialize`. |
132
+ | `parse(uri, langId, text, version)` | Returns a cached `Tree` for the document, reparsing incrementally on version change. |
133
+ | `evict(uri)` | Removes a document's cached tree on close. |
134
+ | `nodesOfType(tree, type)` | `SyntaxNode[]` — all descendants of the given node type. |
135
+ | `nodeAtOffset(tree, offset)` | The deepest node at a byte offset. |
136
+ | `nodeToRange(node)` | Converts a `SyntaxNode` to an LSP `Range` via `startPosition`/`endPosition`. |
137
+ | `positionToOffset(text, line, character)` | Converts an LSP `{line, character}` to a byte offset. |
138
+ | `wordAtPosition(text, line, character)` | Extracts the identifier (including dots) around a cursor position. |
139
+ | `getContextNode(tree, offset)` | Walks up past `ERROR`/`MISSING` nodes to find a clean context ancestor. |
140
+
141
+ ### Testing features manually
142
+
143
+ ```bash
144
+ # Parse a real file and inspect the AST
145
+ node -e "
146
+ const { initParsers, parse, nodesOfType } = require('./parser');
147
+ (async () => {
148
+ await initParsers();
149
+ const text = require('fs').readFileSync('../examples/doctor/doctor.behavior', 'utf8');
150
+ const tree = parse('f', 'behavior', text, 1);
151
+ console.log(nodesOfType(tree, 'state_decl').map(n => n.childForFieldName('name').text));
152
+ })();
153
+ "
154
+
155
+ # Run a diagnostic check
156
+ node -e "
157
+ const { initParsers, parse } = require('./parser');
158
+ const { diagnose } = require('./features/diagnostics');
159
+ (async () => {
160
+ await initParsers();
161
+ const text = 'state greeting\n interact\n transition to missing\n';
162
+ const tree = parse('f', 'behavior', text, 1);
163
+ console.log(diagnose('behavior', tree, text));
164
+ })();
165
+ "
166
+ ```
167
+
168
+ ### Testing the full LSP protocol
169
+
170
+ ```bash
171
+ node -e "
172
+ const { spawn } = require('child_process');
173
+ const p = spawn('node', ['server.js', '--stdio']);
174
+ const msg = JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'initialize', params: { processId: null, rootUri: null, capabilities: {} } });
175
+ p.stdin.write('Content-Length: ' + Buffer.byteLength(msg) + '\r\n\r\n' + msg);
176
+ p.stdout.on('data', d => { console.log(d.toString()); p.kill(); });
177
+ "
178
+ ```
179
+
180
+ ---
181
+
182
+ ## License
183
+
184
+ Copyright (c) 2026 Danilo Borges (https://github.com/daniloborges)
185
+
186
+ Licensed under the **Apache License, Version 2.0** — see [`LICENSE`](LICENSE).
@@ -0,0 +1,112 @@
1
+ /*
2
+ * Copyright (c) 2026 Danilo Borges (https://github.com/daniloborges)
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+
17
+ 'use strict';
18
+
19
+ const { CompletionItemKind } = require('vscode-languageserver');
20
+ const { nodesOfType, positionToOffset, getContextNode } = require('../parser');
21
+
22
+ const BEHAVIOR_TOP_KW = ['state', 'merge', 'on event', 'on intent', 'on offtopic', 'on fallback'];
23
+ const BEHAVIOR_BLOCK_KW = ['guide', 'teach', 'goal', 'interact', 'run', 'transition', 'set', 'if', 'else', 'after', 'parallel', 'apply', 'remove', 'on intent', 'on offtopic', 'on fallback', 'on complete', 'on failed'];
24
+ const AGENT_TOP_KW = ['agent', 'domain', 'license', 'terms', 'privacy', 'description', 'behavior', 'requires', 'input', 'capabilities', 'output', 'type', 'concept', 'schema'];
25
+ const STRICT_BLOCKS = new Set(['input_block', 'output_block', 'requires_block', 'capabilities_block']);
26
+
27
+ function kw(label) {
28
+ return { label, kind: CompletionItemKind.Keyword };
29
+ }
30
+
31
+ // Find the deepest non-error ancestor of a given type
32
+ function nearestAncestor(node, types) {
33
+ let n = node;
34
+ while (n) {
35
+ if (types.includes(n.type)) return n;
36
+ n = n.parent;
37
+ }
38
+ return null;
39
+ }
40
+
41
+ function provideCompletions(langId, tree, text, position) {
42
+ const lines = text.split('\n');
43
+ const line = lines[position.line] || '';
44
+ const before = line.slice(0, position.character);
45
+
46
+ if (langId === 'behavior') {
47
+ // Keyword-specific completions: use prefix regex (reliable while typing)
48
+ if (/\btransition\s+to\s+\S*$/.test(before)) {
49
+ return nodesOfType(tree, 'state_decl')
50
+ .map(n => n.childForFieldName('name')?.text)
51
+ .filter(Boolean)
52
+ .map(name => ({ label: name, kind: CompletionItemKind.Module, detail: 'state' }));
53
+ }
54
+ if (/\bset\s+\S*$/.test(before)) {
55
+ return ['context.', 'session.', 'worksession.', 'user.']
56
+ .map(d => ({ label: d, kind: CompletionItemKind.Variable, detail: 'memory domain' }));
57
+ }
58
+ if (/\brun\s+\S*$/.test(before)) {
59
+ return ['script', 'subagent', 'tool'].map(kw);
60
+ }
61
+ if (/\bon\s+\S*$/.test(before)) {
62
+ return ['event', 'intent', 'offtopic', 'fallback', 'complete', 'failed'].map(kw);
63
+ }
64
+
65
+ // Context-aware: top-level vs. inside a block
66
+ if (tree) {
67
+ const offset = positionToOffset(text, position.line, position.character);
68
+ const ctx = getContextNode(tree, offset);
69
+ const inBlock = !!nearestAncestor(ctx, ['block']);
70
+ return (inBlock ? BEHAVIOR_BLOCK_KW : BEHAVIOR_TOP_KW).map(kw);
71
+ }
72
+ return (/^\s/.test(line) ? BEHAVIOR_BLOCK_KW : BEHAVIOR_TOP_KW).map(kw);
73
+ }
74
+
75
+ if (langId === 'agent') {
76
+ if (!/^\s/.test(line)) {
77
+ return AGENT_TOP_KW.map(kw);
78
+ }
79
+
80
+ // Inside a strict block → suggest declared types
81
+ if (tree) {
82
+ const offset = positionToOffset(text, position.line, position.character);
83
+ const ctx = getContextNode(tree, offset);
84
+ const strictBlock = nearestAncestor(ctx, [...STRICT_BLOCKS]);
85
+ if (strictBlock) {
86
+ return nodesOfType(tree, 'type_decl')
87
+ .map(n => n.childForFieldName('name')?.text)
88
+ .filter(Boolean)
89
+ .map(name => ({ label: name, kind: CompletionItemKind.Class, detail: 'type' }));
90
+ }
91
+ } else {
92
+ // Fallback: text-based block detection
93
+ for (let i = position.line - 1; i >= 0; i--) {
94
+ const prev = lines[i];
95
+ if (/^\s/.test(prev)) continue;
96
+ const blockKw = (prev.trim().split(/\s+/)[0] || '');
97
+ if (['input', 'output', 'requires', 'capabilities'].includes(blockKw)) {
98
+ return nodesOfType(tree, 'type_decl')
99
+ .map(n => n.childForFieldName('name')?.text)
100
+ .filter(Boolean)
101
+ .map(name => ({ label: name, kind: CompletionItemKind.Class, detail: 'type' }));
102
+ }
103
+ break;
104
+ }
105
+ }
106
+ return [];
107
+ }
108
+
109
+ return [];
110
+ }
111
+
112
+ module.exports = { provideCompletions };