nemo-fabric-adapters-cline 0.0.0 → 0.4.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/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+ Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [yyyy] [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,90 @@
1
+ <!--
2
+ SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
+ SPDX-License-Identifier: Apache-2.0
4
+ -->
5
+
6
+ # NVIDIA NeMo Fabric Cline Adapter
7
+
8
+ This package provides the bundled `nvidia.fabric.cline` process adapter. It
9
+ uses Cline's supported TypeScript SDK and keeps one Cline session alive for the
10
+ lifetime of each NeMo Fabric runtime.
11
+
12
+ Install Cline's supported SDK harness separately, then install the NeMo Fabric
13
+ adapter in the same Node.js project:
14
+
15
+ ```bash
16
+ npm install --save-exact @cline/sdk@0.0.83
17
+ npm install nemo-fabric-adapters-cline
18
+ ```
19
+
20
+ The SDK is not an adapter package dependency, so installing the NeMo Fabric
21
+ adapter does not pull Cline or its dependency graph into the project. Starting
22
+ the adapter without the supported SDK returns `cline_harness_unavailable` with
23
+ the Cline installation command.
24
+
25
+ For source development, install and build the focused workspace from the
26
+ repository root:
27
+
28
+ ```bash
29
+ just install-typescript-cline
30
+ npm install --prefix adapters/typescript \
31
+ --workspace nemo-fabric-adapters-cline \
32
+ --include-workspace-root \
33
+ --no-save \
34
+ --package-lock=false \
35
+ --ignore-scripts \
36
+ --no-audit \
37
+ --no-fund \
38
+ @cline/sdk@0.0.83
39
+ npm run build --prefix adapter-contract/typescript
40
+ npm run build --prefix adapters/typescript --workspace nemo-fabric-adapters-common
41
+ npm run build --prefix adapters/typescript --workspace nemo-fabric-adapters-cline
42
+ ```
43
+
44
+ Point `DiscoveryConfig.local_paths` at the installed descriptor:
45
+
46
+ ```python
47
+ from nemo_fabric import DiscoveryConfig, FabricConfig, HarnessConfig
48
+ from nemo_fabric import MetadataConfig, ModelConfig, ToolsConfig
49
+
50
+ config = FabricConfig(
51
+ metadata=MetadataConfig(name="cline-agent"),
52
+ discovery=DiscoveryConfig(
53
+ local_paths=[
54
+ "./node_modules/nemo-fabric-adapters-cline/cline.fabric-adapter.json"
55
+ ]
56
+ ),
57
+ harness=HarnessConfig(adapter_id="nvidia.fabric.cline"),
58
+ models={
59
+ "default": ModelConfig(
60
+ provider="nvidia",
61
+ model="nvidia/nemotron-3-nano-omni-30b-a3b-reasoning",
62
+ api_key_env="NVIDIA_API_KEY",
63
+ base_url="https://integrate.api.nvidia.com/v1",
64
+ )
65
+ },
66
+ tools=ToolsConfig(enabled=["read_files", "skills"]),
67
+ )
68
+ config.add_skill_path("./skills/code-review")
69
+ ```
70
+
71
+ For a source build, use
72
+ `adapters/typescript/cline/cline.fabric-adapter.json`. Relative skill paths
73
+ resolve from the `base_dir` passed to `plan()`, `doctor()`, or `run()`.
74
+
75
+ The initial adapter supports a configured model, an API-key environment
76
+ reference, an optional model base URL, replacement system instructions, Cline
77
+ built-in tool enable/block policy, runtime-scoped native skills, and
78
+ unauthenticated stdio, SSE, and streamable HTTP MCP servers. It does not
79
+ advertise streaming, telemetry, or Relay integration.
80
+
81
+ Each NeMo Fabric runtime owns one local Cline core and one interactive Cline
82
+ session. The first invocation calls `ClineCore.start()`. Later invocations call
83
+ `ClineCore.send()` with the retained session ID, and `stop()` closes the
84
+ session, disposes the core, and removes runtime-scoped state. Independent
85
+ NeMo Fabric runtimes do not share Cline state.
86
+
87
+ The adapter accepts no Cline-specific `harness.settings`. Unsupported
88
+ normalized fields, unknown settings, unknown built-in tool names, authenticated
89
+ MCP configuration, and MCP tool allowlists or blocklists fail instead of being
90
+ ignored.
@@ -0,0 +1,80 @@
1
+ {
2
+ "contract_version": "fabric.adapter/v1alpha2",
3
+ "adapter_id": "nvidia.fabric.cline",
4
+ "adapter_kind": "process",
5
+ "runner": {
6
+ "command": "node",
7
+ "script": "dist/cli.js"
8
+ },
9
+ "requirements": {
10
+ "binaries": ["node"]
11
+ },
12
+ "config": {
13
+ "accepts": [
14
+ "models",
15
+ "models.base_url",
16
+ "instructions.system",
17
+ "tools.enabled",
18
+ "tools.blocked",
19
+ "mcp",
20
+ "skills"
21
+ ],
22
+ "system_instruction_modes": ["replace"]
23
+ },
24
+ "settings_schema": {
25
+ "type": "object",
26
+ "properties": {},
27
+ "additionalProperties": false
28
+ },
29
+ "model_schema": {
30
+ "type": "object",
31
+ "properties": {
32
+ "provider": {"type": "string", "minLength": 1},
33
+ "model": {"type": "string", "minLength": 1},
34
+ "api_key_env": {"type": "string", "minLength": 1},
35
+ "base_url": {"type": ["string", "null"], "format": "uri"}
36
+ },
37
+ "required": ["provider", "model", "api_key_env"],
38
+ "additionalProperties": false
39
+ },
40
+ "extension_schemas": {
41
+ "run_result": {
42
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
43
+ "type": "object",
44
+ "properties": {
45
+ "session_id": {"type": "string", "minLength": 1},
46
+ "finish_reason": {
47
+ "type": "string",
48
+ "enum": ["completed", "aborted", "error", "mistake_limit", "max_iterations"]
49
+ },
50
+ "iterations": {"type": "integer", "minimum": 0},
51
+ "model": {
52
+ "type": "object",
53
+ "properties": {
54
+ "id": {"type": "string"},
55
+ "provider": {"type": "string"}
56
+ },
57
+ "required": ["id", "provider"],
58
+ "additionalProperties": false
59
+ }
60
+ },
61
+ "required": ["session_id", "finish_reason"],
62
+ "additionalProperties": false
63
+ },
64
+ "usage": {
65
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
66
+ "type": "object",
67
+ "properties": {
68
+ "cache_read_tokens": {"type": "integer", "minimum": 0},
69
+ "cache_write_tokens": {"type": "integer", "minimum": 0}
70
+ },
71
+ "additionalProperties": false
72
+ }
73
+ },
74
+ "capabilities": {
75
+ "streaming": false,
76
+ "cancellation": false,
77
+ "updates": false,
78
+ "service": false
79
+ }
80
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { serve } from "nemo-fabric-adapters-common";
5
+ await serve(async () => {
6
+ const [{ ClineSdkSessionFactory }, { ClineAdapterRuntime }] = await Promise.all([
7
+ import("./cline-sdk.js"),
8
+ import("./runtime.js"),
9
+ ]);
10
+ return new ClineAdapterRuntime(new ClineSdkSessionFactory());
11
+ });
@@ -0,0 +1,60 @@
1
+ import { type AdapterStartInput } from "nemo-fabric-adapters-common";
2
+ import type { ClineSessionFactory, ClineSessionHandle } from "./runtime.js";
3
+ interface ClineUsage {
4
+ inputTokens?: number;
5
+ outputTokens?: number;
6
+ cacheReadTokens?: number;
7
+ cacheWriteTokens?: number;
8
+ totalCost?: number;
9
+ }
10
+ interface ClineResult {
11
+ text?: unknown;
12
+ finishReason?: unknown;
13
+ iterations?: unknown;
14
+ model?: unknown;
15
+ usage?: ClineUsage;
16
+ }
17
+ interface ClineStartResult {
18
+ sessionId: string;
19
+ result?: ClineResult;
20
+ }
21
+ interface ClineCoreInstance {
22
+ start(input: Record<string, unknown>): Promise<ClineStartResult>;
23
+ send(input: {
24
+ sessionId: string;
25
+ prompt: string;
26
+ }): Promise<ClineResult | undefined>;
27
+ stop(sessionId: string): Promise<void>;
28
+ dispose(reason?: string): Promise<void>;
29
+ }
30
+ interface ClineSdkModule {
31
+ ALL_DEFAULT_TOOL_NAMES: readonly string[];
32
+ ClineCore: {
33
+ create(options: Record<string, unknown>): Promise<ClineCoreInstance>;
34
+ };
35
+ getClineDefaultSystemPrompt(options: {
36
+ workspaceRoot: string;
37
+ overridePrompt?: string;
38
+ providerId: string;
39
+ }): string;
40
+ loadAgentPluginPackages(options: {
41
+ pluginPaths: readonly string[];
42
+ cwd: string;
43
+ searchPaths: readonly string[];
44
+ pluginDataRoot: string;
45
+ }): Promise<{
46
+ skills: readonly unknown[];
47
+ mcpServers: readonly unknown[];
48
+ diagnostics: readonly {
49
+ level: "warning" | "error";
50
+ message: string;
51
+ }[];
52
+ }>;
53
+ }
54
+ export type ClineSdkLoader = () => Promise<ClineSdkModule>;
55
+ export declare class ClineSdkSessionFactory implements ClineSessionFactory {
56
+ private readonly loader;
57
+ constructor(loader?: ClineSdkLoader);
58
+ create(input: AdapterStartInput): Promise<ClineSessionHandle>;
59
+ }
60
+ export {};
@@ -0,0 +1,458 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { cp, mkdir, mkdtemp, realpath, rm, stat, writeFile } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, join, resolve } from "node:path";
6
+ import { LifecycleError } from "nemo-fabric-adapters-common";
7
+ const CLINE_HARNESS_INSTALL_COMMAND = "npm install @cline/sdk@0.0.83";
8
+ const CLINE_PLUGIN_NAME = "nvidia.fabric.cline";
9
+ const AGENT_PLUGIN_MANIFEST_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json";
10
+ const AGENT_PLUGIN_MCP_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json";
11
+ let clineDataDirTail = Promise.resolve();
12
+ async function withClineDataDir(dataDir, operation) {
13
+ const predecessor = clineDataDirTail;
14
+ let release = () => undefined;
15
+ clineDataDirTail = new Promise((resolveLease) => {
16
+ release = resolveLease;
17
+ });
18
+ await predecessor;
19
+ const previousDataDir = process.env.CLINE_DATA_DIR;
20
+ process.env.CLINE_DATA_DIR = dataDir;
21
+ try {
22
+ return await operation();
23
+ }
24
+ finally {
25
+ if (previousDataDir === undefined) {
26
+ delete process.env.CLINE_DATA_DIR;
27
+ }
28
+ else {
29
+ process.env.CLINE_DATA_DIR = previousDataDir;
30
+ }
31
+ release();
32
+ }
33
+ }
34
+ function isMissingModuleError(error) {
35
+ return (typeof error === "object" &&
36
+ error !== null &&
37
+ "code" in error &&
38
+ (error.code === "ERR_MODULE_NOT_FOUND" || error.code === "MODULE_NOT_FOUND"));
39
+ }
40
+ async function loadClineSdk() {
41
+ let sdk;
42
+ try {
43
+ const moduleName = "@cline/sdk";
44
+ sdk = (await import(moduleName));
45
+ }
46
+ catch (error) {
47
+ if (isMissingModuleError(error)) {
48
+ throw new LifecycleError("cline_harness_unavailable", `The Cline SDK harness is not installed. Install the supported harness with: ${CLINE_HARNESS_INSTALL_COMMAND}`);
49
+ }
50
+ throw new LifecycleError("cline_harness_load_failed", "The installed Cline SDK harness could not be loaded");
51
+ }
52
+ if (typeof sdk.ClineCore?.create !== "function" ||
53
+ typeof sdk.getClineDefaultSystemPrompt !== "function" ||
54
+ typeof sdk.loadAgentPluginPackages !== "function" ||
55
+ !Array.isArray(sdk.ALL_DEFAULT_TOOL_NAMES)) {
56
+ throw new LifecycleError("cline_harness_incompatible", "The installed Cline SDK harness does not expose the APIs required by this adapter");
57
+ }
58
+ return sdk;
59
+ }
60
+ function selectModel(config) {
61
+ const entries = Object.entries(config.models ?? {});
62
+ if (entries.length === 0) {
63
+ throw new LifecycleError("cline_model_required", "The Cline adapter requires one configured model");
64
+ }
65
+ const selected = config.models?.default ?? (entries.length === 1 ? entries[0]?.[1] : undefined);
66
+ if (selected === undefined) {
67
+ throw new LifecycleError("cline_model_ambiguous", "Configure a default model role when the Cline adapter receives multiple models");
68
+ }
69
+ return selected;
70
+ }
71
+ function credentialValue(input, name) {
72
+ return input.runtimeContext.environment.env?.[name] ?? process.env[name];
73
+ }
74
+ async function resolveWorkspace(input) {
75
+ try {
76
+ const workspace = await realpath(resolve(input.runtimeContext.environment.workspace ?? input.baseDir));
77
+ if (!(await stat(workspace)).isDirectory()) {
78
+ throw new Error("not a directory");
79
+ }
80
+ return workspace;
81
+ }
82
+ catch {
83
+ throw new LifecycleError("cline_workspace_invalid", "The NeMo Fabric runtime workspace must be a directory");
84
+ }
85
+ }
86
+ function toolPolicies(config, availableNames) {
87
+ const available = new Set(availableNames);
88
+ const enabled = config.tools?.enabled;
89
+ const blocked = config.tools?.blocked ?? [];
90
+ const requested = [...(enabled ?? []), ...blocked];
91
+ const unknown = requested.filter((name) => !available.has(name));
92
+ if (unknown.length > 0) {
93
+ throw new LifecycleError("cline_tool_unknown", "One or more configured tools are not Cline built-in tools", {
94
+ metadata: { tools: [...new Set(unknown)].sort() },
95
+ });
96
+ }
97
+ const policies = Object.fromEntries(availableNames.map((name) => [name, { autoApprove: true }]));
98
+ if (enabled !== undefined && enabled !== null) {
99
+ const selected = new Set(enabled);
100
+ for (const name of available) {
101
+ policies[name] = { enabled: selected.has(name), autoApprove: true };
102
+ }
103
+ }
104
+ for (const name of blocked) {
105
+ policies[name] = { enabled: false, autoApprove: true };
106
+ }
107
+ return policies;
108
+ }
109
+ function normalizedMcpServer(name, server) {
110
+ if (server.authentication !== undefined && server.authentication !== null) {
111
+ throw new LifecycleError("cline_mcp_authentication_unsupported", "Cline MCP authentication is not supported by this adapter", { metadata: { server: name } });
112
+ }
113
+ if (server.allowed_tools !== undefined && server.allowed_tools !== null) {
114
+ throw new LifecycleError("cline_mcp_allowlist_unsupported", "Cline MCP allowed_tools filtering is not supported by this adapter", { metadata: { server: name } });
115
+ }
116
+ if (server.blocked_tools !== undefined && server.blocked_tools.length > 0) {
117
+ throw new LifecycleError("cline_mcp_blocklist_unsupported", "Cline MCP blocked_tools filtering is not supported by this adapter", { metadata: { server: name } });
118
+ }
119
+ if (server.transport === "stdio") {
120
+ if (server.custom_headers !== undefined && Object.keys(server.custom_headers).length > 0) {
121
+ throw new LifecycleError("cline_mcp_headers_unsupported", "Cline stdio MCP servers do not support custom_headers", { metadata: { server: name } });
122
+ }
123
+ return {
124
+ type: "stdio",
125
+ command: server.url,
126
+ ...(server.args === undefined || server.args.length === 0 ? {} : { args: server.args }),
127
+ ...(server.env === undefined || Object.keys(server.env).length === 0 ? {} : { env: server.env }),
128
+ };
129
+ }
130
+ if (server.transport === "sse" || server.transport === "streamable-http") {
131
+ if ((server.args?.length ?? 0) > 0 || Object.keys(server.env ?? {}).length > 0) {
132
+ throw new LifecycleError("cline_mcp_process_fields_unsupported", "Cline network MCP servers do not support args or env", { metadata: { server: name } });
133
+ }
134
+ return {
135
+ type: server.transport === "sse" ? "sse" : "streamable-http",
136
+ url: server.url,
137
+ ...(server.custom_headers === undefined || Object.keys(server.custom_headers).length === 0
138
+ ? {}
139
+ : { headers: server.custom_headers }),
140
+ };
141
+ }
142
+ throw new LifecycleError("cline_mcp_transport_unsupported", "Cline does not support the configured MCP transport", {
143
+ metadata: { server: name, transport: server.transport },
144
+ });
145
+ }
146
+ async function prepareRuntimeFiles(input) {
147
+ const root = await mkdtemp(join(tmpdir(), "nemo-fabric-cline-"));
148
+ const dataDir = join(root, "data");
149
+ const skillPaths = input.config.skills?.paths ?? [];
150
+ const mcpServers = input.config.mcp?.servers ?? {};
151
+ if (skillPaths.length === 0 && Object.keys(mcpServers).length === 0) {
152
+ return { root, dataDir, skillCount: 0, mcpServerCount: 0 };
153
+ }
154
+ const pluginRoot = join(root, "plugin");
155
+ try {
156
+ await mkdir(pluginRoot, { recursive: true });
157
+ await writeFile(join(pluginRoot, "plugin.json"), `${JSON.stringify({
158
+ $schema: AGENT_PLUGIN_MANIFEST_SCHEMA,
159
+ name: CLINE_PLUGIN_NAME,
160
+ version: "1.0.0",
161
+ description: "Runtime-scoped NeMo Fabric skills and MCP servers.",
162
+ }, null, 2)}\n`, "utf8");
163
+ if (skillPaths.length > 0) {
164
+ const skillsRoot = join(pluginRoot, "skills");
165
+ await mkdir(skillsRoot);
166
+ const names = new Set();
167
+ for (const configured of skillPaths) {
168
+ let source;
169
+ try {
170
+ source = await realpath(resolve(input.baseDir, configured));
171
+ if (!(await stat(source)).isDirectory() || !(await stat(join(source, "SKILL.md"))).isFile()) {
172
+ throw new Error("invalid skill directory");
173
+ }
174
+ }
175
+ catch {
176
+ throw new LifecycleError("cline_skill_invalid", "Cline skill paths must be directories containing a SKILL.md file", { metadata: { path: configured } });
177
+ }
178
+ const name = basename(source);
179
+ if (names.has(name)) {
180
+ throw new LifecycleError("cline_skill_collision", "Two configured Cline skills use the same directory name", {
181
+ metadata: { skill: name },
182
+ });
183
+ }
184
+ names.add(name);
185
+ await cp(source, join(skillsRoot, name), { recursive: true, errorOnExist: true });
186
+ }
187
+ }
188
+ if (Object.keys(mcpServers).length > 0) {
189
+ const servers = Object.fromEntries(Object.entries(mcpServers).map(([name, server]) => [name, normalizedMcpServer(name, server)]));
190
+ await writeFile(join(pluginRoot, "mcp.json"), `${JSON.stringify({ $schema: AGENT_PLUGIN_MCP_SCHEMA, mcpServers: servers }, null, 2)}\n`, "utf8");
191
+ }
192
+ return {
193
+ root,
194
+ dataDir,
195
+ pluginRoot,
196
+ skillCount: skillPaths.length,
197
+ mcpServerCount: Object.keys(mcpServers).length,
198
+ };
199
+ }
200
+ catch (error) {
201
+ await rm(root, { recursive: true, force: true });
202
+ throw error;
203
+ }
204
+ }
205
+ async function validateRuntimePlugin(sdk, files, workspace) {
206
+ if (files.pluginRoot === undefined) {
207
+ return;
208
+ }
209
+ const report = await sdk.loadAgentPluginPackages({
210
+ pluginPaths: [files.pluginRoot],
211
+ cwd: workspace,
212
+ searchPaths: [],
213
+ pluginDataRoot: join(files.root, "plugin-data"),
214
+ });
215
+ const errors = report.diagnostics.filter((diagnostic) => diagnostic.level === "error");
216
+ if (errors.length > 0 ||
217
+ report.skills.length !== files.skillCount ||
218
+ report.mcpServers.length !== files.mcpServerCount) {
219
+ throw new LifecycleError("cline_plugin_invalid", "Cline rejected configured skills or MCP servers", {
220
+ metadata: {
221
+ errors: errors.map((diagnostic) => diagnostic.message),
222
+ expected_skills: files.skillCount,
223
+ loaded_skills: report.skills.length,
224
+ expected_mcp_servers: files.mcpServerCount,
225
+ loaded_mcp_servers: report.mcpServers.length,
226
+ },
227
+ });
228
+ }
229
+ }
230
+ function normalizeUsage(usage) {
231
+ if (usage === undefined) {
232
+ return undefined;
233
+ }
234
+ if (typeof usage !== "object" || usage === null) {
235
+ throw new LifecycleError("cline_malformed_result", "Cline returned malformed usage metadata");
236
+ }
237
+ for (const value of [usage.inputTokens, usage.outputTokens, usage.cacheReadTokens, usage.cacheWriteTokens]) {
238
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < 0)) {
239
+ throw new LifecycleError("cline_malformed_result", "Cline returned malformed usage metadata");
240
+ }
241
+ }
242
+ if (usage.totalCost !== undefined && (!Number.isFinite(usage.totalCost) || usage.totalCost < 0)) {
243
+ throw new LifecycleError("cline_malformed_result", "Cline returned malformed usage metadata");
244
+ }
245
+ const input = usage.inputTokens;
246
+ const output = usage.outputTokens;
247
+ if (input !== undefined && output !== undefined && !Number.isSafeInteger(input + output)) {
248
+ throw new LifecycleError("cline_malformed_result", "Cline returned malformed usage metadata");
249
+ }
250
+ const extensions = {
251
+ ...(usage.cacheReadTokens === undefined ? {} : { cache_read_tokens: usage.cacheReadTokens }),
252
+ ...(usage.cacheWriteTokens === undefined ? {} : { cache_write_tokens: usage.cacheWriteTokens }),
253
+ };
254
+ return {
255
+ ...(input === undefined ? {} : { input_tokens: input }),
256
+ ...(output === undefined ? {} : { output_tokens: output }),
257
+ ...(input === undefined || output === undefined ? {} : { total_tokens: input + output }),
258
+ ...(usage.totalCost === undefined ? {} : { cost_usd: usage.totalCost }),
259
+ ...(Object.keys(extensions).length === 0 ? {} : { extensions }),
260
+ };
261
+ }
262
+ function sdkErrorMessage(error) {
263
+ if (error instanceof Error && error.message.trim().length > 0) {
264
+ return error.message;
265
+ }
266
+ if (typeof error === "string" && error.trim().length > 0) {
267
+ return error;
268
+ }
269
+ return "Cline session communication failed";
270
+ }
271
+ function normalizeResult(result, sessionId) {
272
+ if (result === undefined ||
273
+ !["completed", "aborted", "error", "mistake_limit", "max_iterations"].includes(String(result.finishReason))) {
274
+ throw new LifecycleError("cline_malformed_result", "Cline returned a malformed result");
275
+ }
276
+ if (typeof result.text !== "string") {
277
+ throw new LifecycleError("cline_malformed_result", "Cline returned a malformed assistant response");
278
+ }
279
+ if (result.iterations !== undefined && (!Number.isInteger(result.iterations) || Number(result.iterations) < 0)) {
280
+ throw new LifecycleError("cline_malformed_result", "Cline returned malformed iteration metadata");
281
+ }
282
+ let model;
283
+ if (result.model !== undefined) {
284
+ if (typeof result.model !== "object" ||
285
+ result.model === null ||
286
+ !("id" in result.model) ||
287
+ !("provider" in result.model) ||
288
+ typeof result.model.id !== "string" ||
289
+ typeof result.model.provider !== "string") {
290
+ throw new LifecycleError("cline_malformed_result", "Cline returned malformed model metadata");
291
+ }
292
+ model = { id: result.model.id, provider: result.model.provider };
293
+ }
294
+ const usage = normalizeUsage(result.usage);
295
+ const finishReason = String(result.finishReason);
296
+ const status = finishReason === "completed" ? "completed" : finishReason === "aborted" ? "aborted" : "failed";
297
+ return {
298
+ status,
299
+ text: result.text,
300
+ ...(status === "failed" && result.text.length > 0 ? { errorMessage: result.text } : {}),
301
+ ...(usage === undefined ? {} : { usage }),
302
+ extensions: {
303
+ session_id: sessionId,
304
+ finish_reason: finishReason,
305
+ ...(result.iterations === undefined ? {} : { iterations: Number(result.iterations) }),
306
+ ...(model === undefined ? {} : { model }),
307
+ },
308
+ };
309
+ }
310
+ class ClineSdkSessionHandle {
311
+ core;
312
+ startInput;
313
+ sessionId;
314
+ stopped = false;
315
+ cleanup;
316
+ constructor(core, startInput, cleanup) {
317
+ this.core = core;
318
+ this.startInput = startInput;
319
+ this.cleanup = cleanup;
320
+ }
321
+ async prompt(text) {
322
+ if (this.stopped) {
323
+ throw new LifecycleError("cline_session_stopped", "The Cline session is already stopped");
324
+ }
325
+ try {
326
+ if (this.sessionId === undefined) {
327
+ const started = await this.core.start({ ...this.startInput, prompt: text });
328
+ if (typeof started.sessionId !== "string" || started.sessionId.length === 0) {
329
+ throw new LifecycleError("cline_malformed_result", "Cline did not return a session identifier");
330
+ }
331
+ this.sessionId = started.sessionId;
332
+ return normalizeResult(started.result, this.sessionId);
333
+ }
334
+ return normalizeResult(await this.core.send({ sessionId: this.sessionId, prompt: text }), this.sessionId);
335
+ }
336
+ catch (error) {
337
+ if (error instanceof LifecycleError) {
338
+ throw error;
339
+ }
340
+ throw new LifecycleError("cline_session_failed", sdkErrorMessage(error), {
341
+ retryable: true,
342
+ });
343
+ }
344
+ }
345
+ async stop() {
346
+ if (this.stopped) {
347
+ return;
348
+ }
349
+ this.stopped = true;
350
+ let failure;
351
+ if (this.sessionId !== undefined) {
352
+ try {
353
+ await this.core.stop(this.sessionId);
354
+ }
355
+ catch (error) {
356
+ failure = error;
357
+ }
358
+ }
359
+ try {
360
+ await this.core.dispose("NeMo Fabric runtime stopped");
361
+ }
362
+ catch (error) {
363
+ failure ??= error;
364
+ }
365
+ try {
366
+ await this.cleanup();
367
+ }
368
+ catch (error) {
369
+ failure ??= error;
370
+ }
371
+ if (failure !== undefined) {
372
+ throw failure;
373
+ }
374
+ }
375
+ }
376
+ export class ClineSdkSessionFactory {
377
+ loader;
378
+ constructor(loader = loadClineSdk) {
379
+ this.loader = loader;
380
+ }
381
+ async create(input) {
382
+ const systemInstruction = input.config.instructions?.system;
383
+ if (systemInstruction?.mode === "append") {
384
+ throw new LifecycleError("unsupported_system_instruction_mode", "Cline does not support instructions.system.mode='append'; supported modes: replace", {
385
+ metadata: {
386
+ field: "instructions.system.mode",
387
+ mode: systemInstruction.mode,
388
+ supported_modes: ["replace"],
389
+ },
390
+ });
391
+ }
392
+ const selected = selectModel(input.config);
393
+ const apiKeyEnv = selected.api_key_env;
394
+ if (apiKeyEnv === undefined || apiKeyEnv === null || apiKeyEnv.length === 0) {
395
+ throw new LifecycleError("cline_api_key_env_required", "The selected Cline model requires api_key_env");
396
+ }
397
+ const apiKey = credentialValue(input, apiKeyEnv);
398
+ if (apiKey === undefined || apiKey.length === 0) {
399
+ throw new LifecycleError("cline_credential_missing", `Credential environment variable ${apiKeyEnv} is not set`);
400
+ }
401
+ const workspace = await resolveWorkspace(input);
402
+ const files = await prepareRuntimeFiles(input);
403
+ let core;
404
+ try {
405
+ const sdk = await this.loader();
406
+ await validateRuntimePlugin(sdk, files, workspace);
407
+ const policies = {
408
+ ...toolPolicies(input.config, sdk.ALL_DEFAULT_TOOL_NAMES),
409
+ };
410
+ core = await withClineDataDir(files.dataDir, () => sdk.ClineCore.create({
411
+ clientName: "nemo-fabric",
412
+ backendMode: "local",
413
+ toolPolicies: policies,
414
+ }));
415
+ const systemPrompt = systemInstruction === undefined || systemInstruction === null
416
+ ? sdk.getClineDefaultSystemPrompt({
417
+ workspaceRoot: workspace,
418
+ providerId: selected.provider,
419
+ })
420
+ : systemInstruction.content;
421
+ return new ClineSdkSessionHandle(core, {
422
+ config: {
423
+ providerId: selected.provider,
424
+ modelId: selected.model,
425
+ apiKey,
426
+ ...(selected.base_url === undefined || selected.base_url === null
427
+ ? {}
428
+ : { baseUrl: selected.base_url }),
429
+ cwd: workspace,
430
+ workspaceRoot: workspace,
431
+ mode: "act",
432
+ enableTools: input.config.tools?.enabled?.length !== 0,
433
+ enableSpawnAgent: false,
434
+ enableAgentTeams: false,
435
+ systemPrompt,
436
+ ...(files.pluginRoot === undefined ? {} : { agentPluginPaths: [files.pluginRoot] }),
437
+ },
438
+ // Cline removes non-interactive sessions after their initial turn. NeMo
439
+ // Fabric owns a persistent runtime, so keep this SDK session interactive
440
+ // and drive every turn through the lifecycle protocol instead.
441
+ interactive: true,
442
+ source: "sdk",
443
+ toolPolicies: policies,
444
+ localRuntime: { configExtensions: [] },
445
+ }, async () => {
446
+ await rm(files.root, { recursive: true, force: true });
447
+ });
448
+ }
449
+ catch (error) {
450
+ await core?.dispose("NeMo Fabric startup failed").catch(() => undefined);
451
+ await rm(files.root, { recursive: true, force: true });
452
+ if (error instanceof LifecycleError) {
453
+ throw error;
454
+ }
455
+ throw new LifecycleError("cline_start_failed", "Cline SDK initialization failed");
456
+ }
457
+ }
458
+ }
@@ -0,0 +1,25 @@
1
+ import type { AgentRunRequest, AgentRunResult, AgentUsage, JsonObject, RuntimeContext } from "nemo-fabric-adapter-contract";
2
+ import { type AdapterRuntime, type AdapterStartInput } from "nemo-fabric-adapters-common";
3
+ export interface ClinePromptOutcome {
4
+ status: "completed" | "aborted" | "failed";
5
+ text?: string;
6
+ errorMessage?: string;
7
+ usage?: AgentUsage;
8
+ extensions?: JsonObject;
9
+ }
10
+ export interface ClineSessionHandle {
11
+ prompt(text: string): Promise<ClinePromptOutcome>;
12
+ stop(): Promise<void>;
13
+ }
14
+ export interface ClineSessionFactory {
15
+ create(input: AdapterStartInput): Promise<ClineSessionHandle>;
16
+ }
17
+ export declare class ClineAdapterRuntime implements AdapterRuntime {
18
+ private readonly factory;
19
+ private session?;
20
+ constructor(factory: ClineSessionFactory);
21
+ start(input: AdapterStartInput): Promise<void>;
22
+ private invalidate;
23
+ invoke(request: AgentRunRequest, _context: RuntimeContext): Promise<AgentRunResult>;
24
+ stop(): Promise<void>;
25
+ }
@@ -0,0 +1,91 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { LifecycleError } from "nemo-fabric-adapters-common";
4
+ function failed(code, message, usage, extensions) {
5
+ return {
6
+ status: "failed",
7
+ output: null,
8
+ error: { code, message, retryable: false },
9
+ ...(usage === undefined ? {} : { usage }),
10
+ ...(extensions === undefined ? {} : { extensions }),
11
+ };
12
+ }
13
+ export class ClineAdapterRuntime {
14
+ factory;
15
+ session;
16
+ constructor(factory) {
17
+ this.factory = factory;
18
+ }
19
+ async start(input) {
20
+ if (this.session !== undefined) {
21
+ throw new LifecycleError("cline_already_started", "Cline adapter runtime is already started");
22
+ }
23
+ this.session = await this.factory.create(input);
24
+ }
25
+ async invalidate(session) {
26
+ if (this.session !== session) {
27
+ return;
28
+ }
29
+ this.session = undefined;
30
+ try {
31
+ await session.stop();
32
+ }
33
+ catch {
34
+ // The failed session is unusable; preserve the invocation failure.
35
+ }
36
+ }
37
+ async invoke(request, _context) {
38
+ if (this.session === undefined) {
39
+ throw new LifecycleError("cline_not_started", "Cline adapter runtime is not started");
40
+ }
41
+ if (typeof request.input !== "string") {
42
+ return failed("cline_unsupported_input", "The Cline adapter accepts only plain-text input");
43
+ }
44
+ const session = this.session;
45
+ let outcome;
46
+ try {
47
+ outcome = await session.prompt(request.input);
48
+ }
49
+ catch (error) {
50
+ await this.invalidate(session);
51
+ if (error instanceof LifecycleError) {
52
+ throw error;
53
+ }
54
+ throw new LifecycleError("cline_session_failed", "Cline session communication failed", {
55
+ retryable: true,
56
+ });
57
+ }
58
+ if (outcome.status === "aborted") {
59
+ return {
60
+ status: "cancelled",
61
+ output: null,
62
+ error: {
63
+ code: "cline_aborted",
64
+ message: outcome.errorMessage ?? "The Cline invocation was aborted",
65
+ retryable: false,
66
+ },
67
+ ...(outcome.usage === undefined ? {} : { usage: outcome.usage }),
68
+ ...(outcome.extensions === undefined ? {} : { extensions: outcome.extensions }),
69
+ };
70
+ }
71
+ if (outcome.status === "failed") {
72
+ return failed("cline_model_error", outcome.errorMessage ?? "The Cline invocation failed", outcome.usage, outcome.extensions);
73
+ }
74
+ if (outcome.text === undefined || outcome.text.length === 0) {
75
+ return failed("cline_no_assistant_response", "Cline completed without a final assistant text response", outcome.usage, outcome.extensions);
76
+ }
77
+ return {
78
+ status: "succeeded",
79
+ output: { response: outcome.text },
80
+ ...(outcome.usage === undefined ? {} : { usage: outcome.usage }),
81
+ ...(outcome.extensions === undefined ? {} : { extensions: outcome.extensions }),
82
+ };
83
+ }
84
+ async stop() {
85
+ const session = this.session;
86
+ this.session = undefined;
87
+ if (session !== undefined) {
88
+ await session.stop();
89
+ }
90
+ }
91
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
1
1
  {
2
2
  "name": "nemo-fabric-adapters-cline",
3
- "version": "0.0.0",
4
- "description": "Inert bootstrap for the NVIDIA NeMo Fabric Cline adapter.",
5
- "license": "Apache-2.0"
3
+ "version": "0.4.0",
4
+ "description": "Cline SDK harness adapter for NVIDIA NeMo Fabric.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ "./descriptor": "./cline.fabric-adapter.json",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "bin": {
13
+ "nemo-fabric-adapters-cline": "dist/cli.js"
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "cline.fabric-adapter.json",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "scripts": {
22
+ "build": "tsc -p tsconfig.build.json",
23
+ "clean": "rm -rf dist",
24
+ "pack:check": "npm run build && node ../scripts/check-package.mjs",
25
+ "prepack": "npm run build",
26
+ "test": "npm run clean && npm run build && node --test test/*.test.mjs"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public",
30
+ "registry": "https://registry.npmjs.org"
31
+ },
32
+ "repository": {
33
+ "type": "git",
34
+ "url": "git+https://github.com/NVIDIA/NeMo-Fabric.git",
35
+ "directory": "adapters/typescript/cline"
36
+ },
37
+ "bugs": {
38
+ "url": "https://github.com/NVIDIA/NeMo-Fabric/issues"
39
+ },
40
+ "homepage": "https://github.com/NVIDIA/NeMo-Fabric/tree/main/adapters/typescript/cline#readme",
41
+ "engines": {
42
+ "node": ">=22.19.0"
43
+ },
44
+ "dependencies": {
45
+ "nemo-fabric-adapter-contract": "0.4.0",
46
+ "nemo-fabric-adapters-common": "0.4.0"
47
+ },
48
+ "devDependencies": {
49
+ "@types/node": "24.12.4",
50
+ "typescript": "5.9.3"
51
+ }
6
52
  }