nemo-fabric-adapters-droid 0.0.0 → 0.5.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 CHANGED
@@ -1,194 +1,8 @@
1
- Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
-
3
1
  Apache License
4
2
  Version 2.0, January 2004
5
3
  http://www.apache.org/licenses/
6
4
 
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]
5
+ Copyright 2026 NVIDIA CORPORATION & AFFILIATES
192
6
 
193
7
  Licensed under the Apache License, Version 2.0 (the "License");
194
8
  you may not use this file except in compliance with the License.
package/README.md CHANGED
@@ -1,3 +1,111 @@
1
- # NVIDIA NeMo Fabric Droid Adapter
1
+ <!--
2
+ SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
3
+ SPDX-License-Identifier: Apache-2.0
4
+ -->
2
5
 
3
- Version 0.0.0 is an inert registry bootstrap used to configure npm trusted publishing. It contains no adapter implementation. Supported versions are published by NVIDIA NeMo Fabric release workflows.
6
+ # NVIDIA NeMo Fabric Factory Droid Adapter
7
+
8
+ This package provides the bundled `nvidia.fabric.droid` process adapter. It
9
+ uses Factory's supported TypeScript SDK and retains one Droid session for the
10
+ lifetime of each NeMo Fabric runtime.
11
+
12
+ Install the supported SDK and caller-owned Droid CLI separately, then install
13
+ the adapter in the same Node.js project:
14
+
15
+ ```bash
16
+ npm install --global droid@0.233.0
17
+ npm install --save-exact @factory/droid-sdk@0.9.1
18
+ npm install nemo-fabric-adapters-droid
19
+ ```
20
+
21
+ The adapter never installs the Droid CLI at runtime. A missing SDK returns
22
+ `droid_harness_unavailable`; a missing CLI returns `droid_cli_unavailable`.
23
+ Set the Factory API key referenced by the Fabric model configuration before
24
+ starting a runtime.
25
+
26
+ For source development, install and build the focused workspace from the
27
+ repository root:
28
+
29
+ ```bash
30
+ just install-typescript-droid
31
+ npm run build --prefix adapter-contract/typescript
32
+ npm run build --prefix adapters/typescript --workspace nemo-fabric-adapters-common
33
+ npm run build --prefix adapters/typescript --workspace nemo-fabric-adapters-droid
34
+ ```
35
+
36
+ Point `DiscoveryConfig.local_paths` at the installed descriptor:
37
+
38
+ ```python
39
+ from nemo_fabric import DiscoveryConfig, FabricConfig, HarnessConfig
40
+ from nemo_fabric import InstructionConfig, InstructionsConfig
41
+ from nemo_fabric import MetadataConfig, ModelConfig, ToolsConfig
42
+
43
+ config = FabricConfig(
44
+ metadata=MetadataConfig(name="droid-agent"),
45
+ discovery=DiscoveryConfig(
46
+ local_paths=[
47
+ "./node_modules/nemo-fabric-adapters-droid/droid.fabric-adapter.json"
48
+ ]
49
+ ),
50
+ harness=HarnessConfig(adapter_id="nvidia.fabric.droid"),
51
+ models={
52
+ "default": ModelConfig(
53
+ provider="factory",
54
+ model="auto",
55
+ api_key_env="FACTORY_API_KEY",
56
+ )
57
+ },
58
+ instructions=InstructionsConfig(
59
+ system=InstructionConfig(
60
+ content="Review code for correctness risks.",
61
+ mode="append",
62
+ )
63
+ ),
64
+ tools=ToolsConfig(enabled=["Read", "Grep", "Glob"]),
65
+ )
66
+ config.add_skill_path("./skills/code-review")
67
+ ```
68
+
69
+ For a source build, use
70
+ `adapters/typescript/droid/droid.fabric-adapter.json`.
71
+
72
+ The initial adapter supports model IDs resolved by Droid, a Factory API-key
73
+ environment reference, replacement or appended system instructions, exact
74
+ Droid built-in tool enable/block policy, normalized skill paths, and
75
+ unauthenticated stdio, SSE, and streamable HTTP MCP servers. Tool values are
76
+ Droid tool IDs; inspect the IDs
77
+ available to a model with `droid exec --model MODEL_ID --list-tools
78
+ --output-format json`.
79
+
80
+ Each NeMo Fabric runtime owns one SDK session. Ordered invocations call
81
+ `session.stream()` on that retained session, so the caller does not replay
82
+ history. `stop()` closes the session and its CLI subprocess. Independent
83
+ runtimes create separate sessions.
84
+
85
+ Configured skill directories are copied into a runtime-scoped temporary home
86
+ using Droid's compatible personal `.agents/skills` layout. The adapter verifies
87
+ them with `listSkills()` and removes the temporary home during shutdown. This
88
+ keeps Fabric-provided skills isolated without modifying the workspace.
89
+ The isolated profile preserves Factory `settings.json` and
90
+ `settings.local.json` for custom model definitions but does not copy ambient
91
+ MCP configuration or authentication state.
92
+
93
+ ## Optional: Configure a Custom BYOK Model
94
+
95
+ The default configuration above uses Droid's `auto` model selection and a
96
+ Factory API key. Use the following optional configuration only when Droid must
97
+ call a custom model endpoint through BYOK. The integration guide uses an
98
+ NVIDIA-hosted model as one example.
99
+
100
+ To use a custom BYOK model, define the unprefixed model ID in either Factory
101
+ settings file and set `apiKey` to an exact reference to the provider's existing
102
+ credential variable, such as `${NVIDIA_API_KEY}`. The adapter forwards only the
103
+ variable referenced by the selected custom model. Refer to the
104
+ [Droid integration guide](../../../docs/integrations/harness/droid.mdx#optional-use-a-custom-byok-model)
105
+ for the complete optional setup.
106
+
107
+ The adapter intentionally does not accept normalized custom model endpoints.
108
+ Droid custom endpoints are configured outside a session in Droid settings. It
109
+ also does not advertise streaming, telemetry, or Relay integration. Unsupported
110
+ normalized fields, MCP authentication and per-server tool filters, unknown
111
+ settings, and unknown built-in tool IDs fail instead of being ignored.
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 [{ DroidSdkSessionFactory }, { DroidAdapterRuntime }] = await Promise.all([
7
+ import("./droid-sdk.js"),
8
+ import("./runtime.js"),
9
+ ]);
10
+ return new DroidAdapterRuntime(new DroidSdkSessionFactory());
11
+ });
@@ -0,0 +1,39 @@
1
+ import { type AdapterStartInput } from "nemo-fabric-adapters-common";
2
+ import type { DroidSessionFactory, DroidSessionHandle } from "./runtime.js";
3
+ interface DroidToolInfo {
4
+ id?: unknown;
5
+ }
6
+ interface DroidMcpToolInfo {
7
+ serverName?: unknown;
8
+ name?: unknown;
9
+ }
10
+ interface DroidSkillInfo {
11
+ name?: unknown;
12
+ filePath?: unknown;
13
+ enabled?: unknown;
14
+ }
15
+ interface DroidSdkSession {
16
+ readonly id: string;
17
+ stream(prompt: string): AsyncGenerator<unknown, void, undefined>;
18
+ close(): Promise<void>;
19
+ listTools(): Promise<DroidToolInfo[]>;
20
+ updateSettings(settings: {
21
+ disabledToolIds: string[];
22
+ }): Promise<unknown>;
23
+ listMcpTools(): Promise<DroidMcpToolInfo[]>;
24
+ listSkills(): Promise<{
25
+ skills: DroidSkillInfo[];
26
+ }>;
27
+ }
28
+ interface DroidSdkModule {
29
+ createSession(options: Record<string, unknown>): Promise<DroidSdkSession>;
30
+ }
31
+ export type DroidSdkLoader = () => Promise<DroidSdkModule>;
32
+ export declare class DroidSdkSessionFactory implements DroidSessionFactory {
33
+ private readonly loader;
34
+ private readonly mcpStartupTimeoutMs;
35
+ private readonly parentEnvironment;
36
+ constructor(loader?: DroidSdkLoader, mcpStartupTimeoutMs?: number, parentEnvironment?: NodeJS.ProcessEnv);
37
+ create(input: AdapterStartInput): Promise<DroidSessionHandle>;
38
+ }
39
+ export {};
@@ -0,0 +1,636 @@
1
+ // SPDX-FileCopyrightText: Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { cp, mkdir, mkdtemp, readFile, realpath, rm, stat } 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 DROID_SDK_INSTALL_COMMAND = "npm install @factory/droid-sdk@0.9.1";
8
+ const MCP_STARTUP_TIMEOUT_MS = 10_000;
9
+ const MCP_STATUS_POLL_INTERVAL_MS = 50;
10
+ const INHERITED_ENVIRONMENT_NAMES = new Set([
11
+ "APPDATA",
12
+ "BUN_INSTALL",
13
+ "COMSPEC",
14
+ "ComSpec",
15
+ "DBUS_SESSION_BUS_ADDRESS",
16
+ "HOME",
17
+ "HTTP_PROXY",
18
+ "HTTPS_PROXY",
19
+ "LANG",
20
+ "LC_ALL",
21
+ "LC_CTYPE",
22
+ "LOCALAPPDATA",
23
+ "NO_PROXY",
24
+ "PATH",
25
+ "PATHEXT",
26
+ "Path",
27
+ "PathExt",
28
+ "SHELL",
29
+ "SSL_CERT_DIR",
30
+ "SSL_CERT_FILE",
31
+ "SYSTEMROOT",
32
+ "SystemRoot",
33
+ "TEMP",
34
+ "TERM",
35
+ "TERM_PROGRAM",
36
+ "TMP",
37
+ "TMPDIR",
38
+ "USER",
39
+ "USERPROFILE",
40
+ "XDG_CACHE_HOME",
41
+ "XDG_CONFIG_HOME",
42
+ "XDG_DATA_HOME",
43
+ "XDG_RUNTIME_DIR",
44
+ "http_proxy",
45
+ "https_proxy",
46
+ "no_proxy",
47
+ ]);
48
+ function isMissingModuleError(error) {
49
+ return (typeof error === "object" &&
50
+ error !== null &&
51
+ "code" in error &&
52
+ (error.code === "ERR_MODULE_NOT_FOUND" || error.code === "MODULE_NOT_FOUND"));
53
+ }
54
+ async function loadDroidSdk() {
55
+ try {
56
+ const moduleName = "@factory/droid-sdk/node";
57
+ const sdk = (await import(moduleName));
58
+ if (typeof sdk.createSession !== "function") {
59
+ throw new LifecycleError("droid_harness_incompatible", "The installed Factory Droid SDK does not expose createSession");
60
+ }
61
+ return sdk;
62
+ }
63
+ catch (error) {
64
+ if (error instanceof LifecycleError)
65
+ throw error;
66
+ if (isMissingModuleError(error)) {
67
+ throw new LifecycleError("droid_harness_unavailable", `The Factory Droid SDK is not installed. Install the supported SDK with: ${DROID_SDK_INSTALL_COMMAND}`);
68
+ }
69
+ throw new LifecycleError("droid_harness_load_failed", "The installed Factory Droid SDK could not be loaded");
70
+ }
71
+ }
72
+ function selectModel(config) {
73
+ const entries = Object.entries(config.models ?? {});
74
+ if (entries.length === 0) {
75
+ throw new LifecycleError("droid_model_required", "The Droid adapter requires one configured model");
76
+ }
77
+ const selected = config.models?.default ?? (entries.length === 1 ? entries[0]?.[1] : undefined);
78
+ if (selected === undefined) {
79
+ throw new LifecycleError("droid_model_ambiguous", "Configure a default model role when the Droid adapter receives multiple models");
80
+ }
81
+ if (selected.provider !== "factory") {
82
+ throw new LifecycleError("droid_provider_unsupported", "The Droid adapter requires models to use provider='factory'");
83
+ }
84
+ return selected;
85
+ }
86
+ function credentialValue(input, name, parentEnvironment) {
87
+ return input.runtimeContext.environment.env?.[name] ?? parentEnvironment[name];
88
+ }
89
+ function replaceEnvironment(values) {
90
+ for (const name of Object.keys(process.env)) {
91
+ delete process.env[name];
92
+ }
93
+ for (const [name, value] of Object.entries(values)) {
94
+ if (value !== undefined)
95
+ process.env[name] = value;
96
+ }
97
+ }
98
+ function leaseEnvironment(configured, credentialName, credential, parentEnvironment) {
99
+ const original = { ...process.env };
100
+ const values = Object.create(null);
101
+ for (const name of INHERITED_ENVIRONMENT_NAMES) {
102
+ const value = parentEnvironment[name];
103
+ if (value !== undefined)
104
+ values[name] = value;
105
+ }
106
+ Object.assign(values, configured);
107
+ values[credentialName] = credential;
108
+ replaceEnvironment(values);
109
+ return { release: () => replaceEnvironment(original) };
110
+ }
111
+ async function resolveWorkspace(input) {
112
+ try {
113
+ const workspace = await realpath(resolve(input.runtimeContext.environment.workspace ?? input.baseDir));
114
+ if (!(await stat(workspace)).isDirectory())
115
+ throw new Error("not a directory");
116
+ return workspace;
117
+ }
118
+ catch {
119
+ throw new LifecycleError("droid_workspace_invalid", "The NeMo Fabric runtime workspace must be a directory");
120
+ }
121
+ }
122
+ function rejectMcpExtensions(name, server) {
123
+ if (server.extensions !== undefined && Object.keys(server.extensions).length > 0) {
124
+ throw new LifecycleError("droid_mcp_extensions_unsupported", "Droid does not support MCP extensions", {
125
+ metadata: { server: name },
126
+ });
127
+ }
128
+ if (server.authentication !== undefined && server.authentication !== null) {
129
+ throw new LifecycleError("droid_mcp_authentication_unsupported", "Droid MCP authentication is not supported by this adapter", { metadata: { server: name } });
130
+ }
131
+ if (server.allowed_tools !== undefined && server.allowed_tools !== null) {
132
+ throw new LifecycleError("droid_mcp_allowlist_unsupported", "Droid MCP allowed_tools filtering is not supported by this adapter", { metadata: { server: name } });
133
+ }
134
+ if (server.blocked_tools !== undefined && server.blocked_tools.length > 0) {
135
+ throw new LifecycleError("droid_mcp_blocklist_unsupported", "Droid MCP blocked_tools filtering is not supported by this adapter", { metadata: { server: name } });
136
+ }
137
+ }
138
+ function validateRemoteUrl(name, value) {
139
+ let parsed;
140
+ try {
141
+ parsed = new URL(value);
142
+ }
143
+ catch {
144
+ throw new LifecycleError("droid_mcp_url_invalid", "Droid network MCP servers require an absolute URL", {
145
+ metadata: { server: name },
146
+ });
147
+ }
148
+ const loopback = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1" || parsed.hostname === "[::1]";
149
+ if (parsed.protocol !== "https:" && !(parsed.protocol === "http:" && loopback)) {
150
+ throw new LifecycleError("droid_mcp_url_insecure", "Droid network MCP servers require HTTPS except for loopback development endpoints", { metadata: { server: name } });
151
+ }
152
+ }
153
+ function normalizedMcpServer(name, server) {
154
+ rejectMcpExtensions(name, server);
155
+ if (server.transport === "stdio") {
156
+ if (server.custom_headers !== undefined && Object.keys(server.custom_headers).length > 0) {
157
+ throw new LifecycleError("droid_mcp_headers_unsupported", "Droid stdio MCP servers do not support custom_headers", {
158
+ metadata: { server: name },
159
+ });
160
+ }
161
+ return {
162
+ name,
163
+ command: server.url,
164
+ args: server.args ?? [],
165
+ env: server.env ?? {},
166
+ };
167
+ }
168
+ if (server.transport === "streamable-http" || server.transport === "sse") {
169
+ if ((server.args?.length ?? 0) > 0 || Object.keys(server.env ?? {}).length > 0) {
170
+ throw new LifecycleError("droid_mcp_process_fields_unsupported", "Droid network MCP servers do not support args or env", { metadata: { server: name } });
171
+ }
172
+ validateRemoteUrl(name, server.url);
173
+ return {
174
+ name,
175
+ type: server.transport === "sse" ? "sse" : "http",
176
+ url: server.url,
177
+ headers: Object.entries(server.custom_headers ?? {}).map(([headerName, value]) => ({
178
+ name: headerName,
179
+ value,
180
+ })),
181
+ };
182
+ }
183
+ throw new LifecycleError("droid_mcp_transport_unsupported", "Droid does not support the configured MCP transport", {
184
+ metadata: { server: name, transport: server.transport },
185
+ });
186
+ }
187
+ function normalizedMcp(input) {
188
+ if (input.config.mcp?.extensions !== undefined && Object.keys(input.config.mcp.extensions).length > 0) {
189
+ throw new LifecycleError("droid_mcp_extensions_unsupported", "Droid does not support top-level MCP extensions");
190
+ }
191
+ return Object.entries(input.config.mcp?.servers ?? {}).map(([name, server]) => normalizedMcpServer(name, server));
192
+ }
193
+ function settingsHome(input, parentEnvironment) {
194
+ const runtimeEnvironment = input.runtimeContext.environment.env ?? {};
195
+ return (runtimeEnvironment.FACTORY_HOME_OVERRIDE ||
196
+ runtimeEnvironment.HOME ||
197
+ runtimeEnvironment.USERPROFILE ||
198
+ parentEnvironment.FACTORY_HOME_OVERRIDE ||
199
+ parentEnvironment.HOME ||
200
+ parentEnvironment.USERPROFILE);
201
+ }
202
+ async function customModelSettingsEnvironment(input, model, sourceHome, parentEnvironment) {
203
+ if (!model.startsWith("custom:") || sourceHome === undefined)
204
+ return {};
205
+ const modelId = model.slice("custom:".length);
206
+ let apiKey;
207
+ for (const filename of ["settings.json", "settings.local.json"]) {
208
+ try {
209
+ const settings = JSON.parse(await readFile(join(sourceHome, ".factory", filename), "utf8"));
210
+ if (typeof settings !== "object" || settings === null || !("customModels" in settings))
211
+ continue;
212
+ const customModels = settings.customModels;
213
+ if (!Array.isArray(customModels))
214
+ continue;
215
+ const configured = customModels.find((candidate) => typeof candidate === "object" &&
216
+ candidate !== null &&
217
+ "model" in candidate &&
218
+ candidate.model === modelId);
219
+ if (configured !== undefined && "apiKey" in configured)
220
+ apiKey = configured.apiKey;
221
+ }
222
+ catch (error) {
223
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
224
+ continue;
225
+ if (error instanceof SyntaxError)
226
+ continue; // Droid reports malformed settings during session creation.
227
+ throw new LifecycleError("droid_settings_unavailable", "Droid settings could not be read by NeMo Fabric");
228
+ }
229
+ }
230
+ if (typeof apiKey !== "string")
231
+ return {};
232
+ const match = /^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(apiKey);
233
+ if (match === null)
234
+ return {};
235
+ const name = match[1];
236
+ if (name === undefined)
237
+ return {};
238
+ const value = credentialValue(input, name, parentEnvironment);
239
+ if (value === undefined || value.length === 0) {
240
+ throw new LifecycleError("droid_credential_missing", `Credential environment variable ${name} is not set`);
241
+ }
242
+ return { [name]: value };
243
+ }
244
+ async function prepareRuntimeProfile(input, hasMcpServers, parentEnvironment, model) {
245
+ if (input.config.skills?.extensions !== undefined) {
246
+ throw new LifecycleError("droid_skill_extensions_unsupported", "Droid does not support skill extensions");
247
+ }
248
+ const configured = input.config.skills?.paths ?? [];
249
+ const sourceHome = settingsHome(input, parentEnvironment);
250
+ const settingsEnvironment = await customModelSettingsEnvironment(input, model, sourceHome, parentEnvironment);
251
+ if (configured.length === 0 && !hasMcpServers)
252
+ return { entrypoints: [], settingsEnvironment };
253
+ const root = await mkdtemp(join(tmpdir(), "nemo-fabric-droid-"));
254
+ const home = join(root, "home");
255
+ const factoryRoot = join(home, ".factory");
256
+ const skillsRoot = join(home, ".agents", "skills");
257
+ try {
258
+ if (sourceHome !== undefined) {
259
+ for (const filename of ["settings.json", "settings.local.json"]) {
260
+ const sourceSettings = join(sourceHome, ".factory", filename);
261
+ try {
262
+ if ((await stat(sourceSettings)).isFile()) {
263
+ await mkdir(factoryRoot, { recursive: true });
264
+ await cp(sourceSettings, join(factoryRoot, filename), { errorOnExist: true });
265
+ }
266
+ }
267
+ catch (error) {
268
+ if (!(typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")) {
269
+ throw new LifecycleError("droid_settings_unavailable", "Droid settings could not be copied into the isolated NeMo Fabric runtime");
270
+ }
271
+ }
272
+ }
273
+ }
274
+ if (configured.length > 0)
275
+ await mkdir(skillsRoot, { recursive: true });
276
+ const names = new Set();
277
+ const entrypoints = [];
278
+ for (const configuredPath of configured) {
279
+ let source;
280
+ try {
281
+ source = await realpath(resolve(input.baseDir, configuredPath));
282
+ if (!(await stat(source)).isDirectory() || !(await stat(join(source, "SKILL.md"))).isFile()) {
283
+ throw new Error("invalid skill directory");
284
+ }
285
+ }
286
+ catch {
287
+ throw new LifecycleError("droid_skill_invalid", "Droid skill paths must be directories containing a SKILL.md file", { metadata: { path: configuredPath } });
288
+ }
289
+ const name = basename(source);
290
+ if (name.length === 0 || names.has(name)) {
291
+ throw new LifecycleError("droid_skill_collision", "Configured Droid skills must use distinct directory names", {
292
+ metadata: { skill: name },
293
+ });
294
+ }
295
+ names.add(name);
296
+ const destination = join(skillsRoot, name);
297
+ await cp(source, destination, { recursive: true, errorOnExist: true });
298
+ entrypoints.push(await realpath(join(destination, "SKILL.md")));
299
+ }
300
+ return { root, home, entrypoints, settingsEnvironment };
301
+ }
302
+ catch (error) {
303
+ await rm(root, { recursive: true, force: true });
304
+ throw error;
305
+ }
306
+ }
307
+ async function validateSkills(session, expectedEntrypoints) {
308
+ if (expectedEntrypoints.length === 0)
309
+ return;
310
+ const report = await session.listSkills();
311
+ if (!Array.isArray(report.skills)) {
312
+ throw new LifecycleError("droid_skill_status_unavailable", "Droid could not determine configured skill status");
313
+ }
314
+ const loaded = new Map();
315
+ for (const skill of report.skills) {
316
+ if (typeof skill.filePath !== "string")
317
+ continue;
318
+ try {
319
+ loaded.set(await realpath(skill.filePath), skill);
320
+ }
321
+ catch {
322
+ // A malformed or stale ambient skill cannot satisfy a configured path.
323
+ }
324
+ }
325
+ const missing = expectedEntrypoints.filter((entrypoint) => !loaded.has(entrypoint));
326
+ const disabled = expectedEntrypoints.filter((entrypoint) => loaded.get(entrypoint)?.enabled === false);
327
+ if (missing.length > 0 || disabled.length > 0) {
328
+ throw new LifecycleError("droid_skill_load_failed", "Droid did not load every configured NeMo Fabric skill", {
329
+ metadata: { missing, disabled },
330
+ });
331
+ }
332
+ }
333
+ function validNonNegativeNumber(value) {
334
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
335
+ }
336
+ function validTokenCount(value) {
337
+ return Number.isSafeInteger(value) && Number(value) >= 0;
338
+ }
339
+ function normalizeUsage(value) {
340
+ if (value === null || value === undefined)
341
+ return undefined;
342
+ if (typeof value !== "object") {
343
+ throw new LifecycleError("droid_malformed_result", "Droid returned malformed usage metadata");
344
+ }
345
+ const usage = value;
346
+ const counts = [
347
+ usage.inputTokens,
348
+ usage.outputTokens,
349
+ usage.cacheCreationTokens,
350
+ usage.cacheReadTokens,
351
+ usage.thinkingTokens,
352
+ ];
353
+ if (!counts.every(validTokenCount) || (usage.factoryCredits !== undefined && !validNonNegativeNumber(usage.factoryCredits))) {
354
+ throw new LifecycleError("droid_malformed_result", "Droid returned malformed usage metadata");
355
+ }
356
+ const total = usage.inputTokens + usage.outputTokens;
357
+ if (!Number.isSafeInteger(total)) {
358
+ throw new LifecycleError("droid_malformed_result", "Droid returned malformed usage metadata");
359
+ }
360
+ return {
361
+ input_tokens: usage.inputTokens,
362
+ output_tokens: usage.outputTokens,
363
+ total_tokens: total,
364
+ extensions: {
365
+ cache_read_tokens: usage.cacheReadTokens,
366
+ cache_write_tokens: usage.cacheCreationTokens,
367
+ thinking_tokens: usage.thinkingTokens,
368
+ ...(usage.factoryCredits === undefined ? {} : { factory_credits: usage.factoryCredits }),
369
+ },
370
+ };
371
+ }
372
+ function normalizeResult(value) {
373
+ if (typeof value !== "object" || value === null) {
374
+ throw new LifecycleError("droid_malformed_result", "Droid did not return a terminal result");
375
+ }
376
+ const result = value;
377
+ if (result.type !== "result" ||
378
+ typeof result.sessionId !== "string" ||
379
+ result.sessionId.length === 0 ||
380
+ !validTokenCount(result.durationMs) ||
381
+ !validTokenCount(result.turnCount) ||
382
+ typeof result.text !== "string" ||
383
+ typeof result.success !== "boolean" ||
384
+ typeof result.interrupted !== "boolean" ||
385
+ !["success", "interrupted", "error_during_execution", "error_structured_output"].includes(String(result.subtype))) {
386
+ throw new LifecycleError("droid_malformed_result", "Droid returned a malformed terminal result");
387
+ }
388
+ const usage = normalizeUsage(result.tokenUsage);
389
+ const extensions = {
390
+ session_id: result.sessionId,
391
+ finish_reason: String(result.subtype),
392
+ duration_ms: Number(result.durationMs),
393
+ turn_count: Number(result.turnCount),
394
+ };
395
+ if (result.success && result.subtype === "success" && !result.interrupted) {
396
+ return { status: "completed", text: result.text, ...(usage === undefined ? {} : { usage }), extensions };
397
+ }
398
+ if (result.interrupted && result.subtype === "interrupted" && !result.success) {
399
+ return { status: "interrupted", text: result.text, ...(usage === undefined ? {} : { usage }), extensions };
400
+ }
401
+ if (!result.success && !result.interrupted && String(result.subtype).startsWith("error_")) {
402
+ const error = result.error;
403
+ const errorMessage = error !== null && typeof error === "object" && typeof error.message === "string"
404
+ ? error.message
405
+ : result.text;
406
+ return {
407
+ status: "failed",
408
+ text: result.text,
409
+ errorMessage: errorMessage.length === 0 ? "The Droid invocation failed" : errorMessage,
410
+ ...(usage === undefined ? {} : { usage }),
411
+ extensions,
412
+ };
413
+ }
414
+ throw new LifecycleError("droid_malformed_result", "Droid returned inconsistent terminal result fields");
415
+ }
416
+ function sdkErrorMessage(error) {
417
+ if (error instanceof Error && error.message.trim().length > 0)
418
+ return error.message;
419
+ if (typeof error === "string" && error.trim().length > 0)
420
+ return error;
421
+ return "Droid session communication failed";
422
+ }
423
+ async function applyToolPolicy(session, config, mcpServers) {
424
+ const enabled = config.tools?.enabled;
425
+ const blocked = config.tools?.blocked ?? [];
426
+ if (enabled === undefined && blocked.length === 0)
427
+ return;
428
+ const listed = await session.listTools();
429
+ const mcpPrefixes = mcpServers.map((server) => `${server.name}___`);
430
+ const available = listed
431
+ .map((tool) => tool.id)
432
+ .filter((id) => typeof id === "string" && id.length > 0 && !mcpPrefixes.some((prefix) => id.startsWith(prefix)));
433
+ const malformed = listed.some((tool) => typeof tool.id !== "string" || tool.id.length === 0);
434
+ if (malformed || new Set(available).size !== available.length) {
435
+ throw new LifecycleError("droid_tool_status_invalid", "Droid returned malformed built-in tool metadata");
436
+ }
437
+ const known = new Set(available);
438
+ const requested = [...(enabled ?? []), ...blocked];
439
+ const unknown = [...new Set(requested.filter((name) => !known.has(name)))].sort();
440
+ if (unknown.length > 0) {
441
+ throw new LifecycleError("droid_tool_unknown", "One or more configured tools are not Droid built-in tool IDs", {
442
+ metadata: { tools: unknown },
443
+ });
444
+ }
445
+ const disabled = new Set(blocked);
446
+ if (enabled !== undefined && enabled !== null) {
447
+ const selected = new Set(enabled);
448
+ for (const name of available) {
449
+ if (!selected.has(name))
450
+ disabled.add(name);
451
+ }
452
+ }
453
+ await session.updateSettings({ disabledToolIds: [...disabled].sort() });
454
+ }
455
+ async function validateMcpTools(session, configured, timeoutMs) {
456
+ const expected = new Set(configured.map((server) => server.name));
457
+ if (expected.size === 0)
458
+ return;
459
+ const deadline = Date.now() + timeoutMs;
460
+ let missing = [...expected];
461
+ while (true) {
462
+ const remainingBeforeRequestMs = deadline - Date.now();
463
+ if (remainingBeforeRequestMs <= 0) {
464
+ throw new LifecycleError("droid_mcp_load_failed", "Droid did not load tools from every configured MCP server", {
465
+ metadata: { missing },
466
+ });
467
+ }
468
+ let cancelTimer = () => undefined;
469
+ let tools;
470
+ try {
471
+ tools = await Promise.race([
472
+ session.listMcpTools(),
473
+ new Promise((resolve) => {
474
+ const timer = setTimeout(resolve, remainingBeforeRequestMs);
475
+ cancelTimer = () => clearTimeout(timer);
476
+ }),
477
+ ]);
478
+ }
479
+ catch {
480
+ throw new LifecycleError("droid_mcp_status_unavailable", "Droid could not determine configured MCP tool status");
481
+ }
482
+ finally {
483
+ cancelTimer();
484
+ }
485
+ if (tools === undefined) {
486
+ throw new LifecycleError("droid_mcp_load_failed", "Droid did not load tools from every configured MCP server", {
487
+ metadata: { missing },
488
+ });
489
+ }
490
+ if (!Array.isArray(tools) ||
491
+ tools.some((tool) => typeof tool.serverName !== "string" ||
492
+ tool.serverName.length === 0 ||
493
+ typeof tool.name !== "string" ||
494
+ tool.name.length === 0)) {
495
+ throw new LifecycleError("droid_mcp_status_unavailable", "Droid returned malformed MCP tool metadata");
496
+ }
497
+ const discovered = new Set(tools.map((tool) => tool.serverName));
498
+ missing = [...expected].filter((name) => !discovered.has(name));
499
+ if (missing.length === 0)
500
+ return;
501
+ const remainingMs = deadline - Date.now();
502
+ if (remainingMs <= 0) {
503
+ throw new LifecycleError("droid_mcp_load_failed", "Droid did not load tools from every configured MCP server", {
504
+ metadata: { missing },
505
+ });
506
+ }
507
+ await new Promise((resolve) => setTimeout(resolve, Math.min(MCP_STATUS_POLL_INTERVAL_MS, remainingMs)));
508
+ }
509
+ }
510
+ class DroidSdkSessionHandle {
511
+ session;
512
+ runtimeRoot;
513
+ stopped = false;
514
+ constructor(session, runtimeRoot) {
515
+ this.session = session;
516
+ this.runtimeRoot = runtimeRoot;
517
+ }
518
+ async prompt(text) {
519
+ if (this.stopped) {
520
+ throw new LifecycleError("droid_session_stopped", "The Droid session is already stopped");
521
+ }
522
+ let terminal;
523
+ try {
524
+ for await (const message of this.session.stream(text)) {
525
+ if (typeof message === "object" && message !== null && "type" in message && message.type === "result") {
526
+ terminal = message;
527
+ }
528
+ }
529
+ }
530
+ catch (error) {
531
+ throw new LifecycleError("droid_session_failed", sdkErrorMessage(error), { retryable: true });
532
+ }
533
+ if (terminal === undefined) {
534
+ throw new LifecycleError("droid_session_failed", "Droid session ended without a terminal result", {
535
+ retryable: true,
536
+ });
537
+ }
538
+ return normalizeResult(terminal);
539
+ }
540
+ async stop() {
541
+ if (this.stopped)
542
+ return;
543
+ this.stopped = true;
544
+ try {
545
+ await this.session.close();
546
+ }
547
+ finally {
548
+ if (this.runtimeRoot !== undefined) {
549
+ await rm(this.runtimeRoot, { recursive: true, force: true });
550
+ }
551
+ }
552
+ }
553
+ }
554
+ export class DroidSdkSessionFactory {
555
+ loader;
556
+ mcpStartupTimeoutMs;
557
+ parentEnvironment;
558
+ constructor(loader = loadDroidSdk, mcpStartupTimeoutMs = MCP_STARTUP_TIMEOUT_MS, parentEnvironment = process.env) {
559
+ this.loader = loader;
560
+ this.mcpStartupTimeoutMs = mcpStartupTimeoutMs;
561
+ this.parentEnvironment = parentEnvironment;
562
+ }
563
+ async create(input) {
564
+ const selected = selectModel(input.config);
565
+ const apiKeyEnv = selected.api_key_env;
566
+ if (apiKeyEnv === undefined || apiKeyEnv === null || apiKeyEnv.length === 0) {
567
+ throw new LifecycleError("droid_api_key_env_required", "The selected Factory model requires api_key_env");
568
+ }
569
+ const apiKey = credentialValue(input, apiKeyEnv, this.parentEnvironment);
570
+ if (apiKey === undefined || apiKey.length === 0) {
571
+ throw new LifecycleError("droid_credential_missing", `Credential environment variable ${apiKeyEnv} is not set`);
572
+ }
573
+ const workspace = await resolveWorkspace(input);
574
+ const mcpServers = normalizedMcp(input);
575
+ const instruction = input.config.instructions?.system;
576
+ if (instruction?.extensions !== undefined && Object.keys(instruction.extensions).length > 0) {
577
+ throw new LifecycleError("droid_instruction_extensions_unsupported", "Droid does not support instruction extensions");
578
+ }
579
+ if (instruction?.mode !== undefined && instruction.mode !== "replace" && instruction.mode !== "append") {
580
+ throw new LifecycleError("unsupported_system_instruction_mode", `Droid does not support instructions.system.mode='${instruction.mode}'; supported modes: replace, append`);
581
+ }
582
+ const runtimeProfile = await prepareRuntimeProfile(input, mcpServers.length > 0, this.parentEnvironment, selected.model);
583
+ const runtimeEnvironment = input.runtimeContext.environment.env ?? {};
584
+ const sessionEnvironment = runtimeProfile.home === undefined
585
+ ? { ...runtimeEnvironment, ...runtimeProfile.settingsEnvironment }
586
+ : {
587
+ ...runtimeEnvironment,
588
+ ...runtimeProfile.settingsEnvironment,
589
+ HOME: runtimeProfile.home,
590
+ USERPROFILE: runtimeProfile.home,
591
+ FACTORY_HOME_OVERRIDE: runtimeProfile.home,
592
+ };
593
+ let session;
594
+ try {
595
+ const environment = leaseEnvironment(sessionEnvironment, apiKeyEnv, apiKey, this.parentEnvironment);
596
+ try {
597
+ const sdk = await this.loader();
598
+ session = await sdk.createSession({
599
+ cwd: workspace,
600
+ modelId: selected.model,
601
+ apiKey,
602
+ autonomyLevel: "high",
603
+ ...(mcpServers.length === 0 ? {} : { mcpServers }),
604
+ env: sessionEnvironment,
605
+ ...(instruction === undefined || instruction === null
606
+ ? {}
607
+ : {
608
+ systemPrompt: instruction.mode === "append"
609
+ ? { type: "preset", preset: "droid", append: instruction.content }
610
+ : instruction.content,
611
+ }),
612
+ });
613
+ }
614
+ finally {
615
+ environment.release();
616
+ }
617
+ await applyToolPolicy(session, input.config, mcpServers);
618
+ await validateMcpTools(session, mcpServers, this.mcpStartupTimeoutMs);
619
+ await validateSkills(session, runtimeProfile.entrypoints);
620
+ return new DroidSdkSessionHandle(session, runtimeProfile.root);
621
+ }
622
+ catch (error) {
623
+ await session?.close().catch(() => undefined);
624
+ if (runtimeProfile.root !== undefined) {
625
+ await rm(runtimeProfile.root, { recursive: true, force: true });
626
+ }
627
+ if (error instanceof LifecycleError)
628
+ throw error;
629
+ const message = sdkErrorMessage(error);
630
+ if (/\b(?:ENOENT|not found|spawn droid)\b/i.test(message)) {
631
+ throw new LifecycleError("droid_cli_unavailable", "The Factory Droid CLI is not installed or is not available on PATH");
632
+ }
633
+ throw new LifecycleError("droid_start_failed", "Factory Droid SDK initialization failed");
634
+ }
635
+ }
636
+ }
@@ -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 DroidPromptOutcome {
4
+ status: "completed" | "interrupted" | "failed";
5
+ text?: string;
6
+ errorMessage?: string;
7
+ usage?: AgentUsage;
8
+ extensions?: JsonObject;
9
+ }
10
+ export interface DroidSessionHandle {
11
+ prompt(text: string): Promise<DroidPromptOutcome>;
12
+ stop(): Promise<void>;
13
+ }
14
+ export interface DroidSessionFactory {
15
+ create(input: AdapterStartInput): Promise<DroidSessionHandle>;
16
+ }
17
+ export declare class DroidAdapterRuntime implements AdapterRuntime {
18
+ private readonly factory;
19
+ private session?;
20
+ constructor(factory: DroidSessionFactory);
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,86 @@
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 DroidAdapterRuntime {
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("droid_already_started", "Droid 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
+ this.session = undefined;
29
+ try {
30
+ await session.stop();
31
+ }
32
+ catch {
33
+ // Preserve the invocation failure after invalidating the unusable session.
34
+ }
35
+ }
36
+ async invoke(request, _context) {
37
+ if (this.session === undefined) {
38
+ throw new LifecycleError("droid_not_started", "Droid adapter runtime is not started");
39
+ }
40
+ if (typeof request.input !== "string") {
41
+ return failed("droid_unsupported_input", "The Droid adapter accepts only plain-text input");
42
+ }
43
+ const session = this.session;
44
+ let outcome;
45
+ try {
46
+ outcome = await session.prompt(request.input);
47
+ }
48
+ catch (error) {
49
+ await this.invalidate(session);
50
+ if (error instanceof LifecycleError)
51
+ throw error;
52
+ throw new LifecycleError("droid_session_failed", "Droid session communication failed", { retryable: true });
53
+ }
54
+ if (outcome.status === "interrupted") {
55
+ return {
56
+ status: "cancelled",
57
+ output: null,
58
+ error: {
59
+ code: "droid_interrupted",
60
+ message: outcome.errorMessage ?? "The Droid invocation was interrupted",
61
+ retryable: false,
62
+ },
63
+ ...(outcome.usage === undefined ? {} : { usage: outcome.usage }),
64
+ ...(outcome.extensions === undefined ? {} : { extensions: outcome.extensions }),
65
+ };
66
+ }
67
+ if (outcome.status === "failed") {
68
+ return failed("droid_invocation_failed", outcome.errorMessage ?? "The Droid invocation failed", outcome.usage, outcome.extensions);
69
+ }
70
+ if (outcome.text === undefined || outcome.text.length === 0) {
71
+ return failed("droid_no_assistant_response", "Droid completed without a final assistant text response", outcome.usage, outcome.extensions);
72
+ }
73
+ return {
74
+ status: "succeeded",
75
+ output: { response: outcome.text },
76
+ ...(outcome.usage === undefined ? {} : { usage: outcome.usage }),
77
+ ...(outcome.extensions === undefined ? {} : { extensions: outcome.extensions }),
78
+ };
79
+ }
80
+ async stop() {
81
+ const session = this.session;
82
+ this.session = undefined;
83
+ if (session !== undefined)
84
+ await session.stop();
85
+ }
86
+ }
@@ -0,0 +1,72 @@
1
+ {
2
+ "contract_version": "fabric.adapter/v1alpha2",
3
+ "adapter_id": "nvidia.fabric.droid",
4
+ "adapter_kind": "process",
5
+ "runner": {
6
+ "command": "node",
7
+ "script": "dist/cli.js"
8
+ },
9
+ "requirements": {
10
+ "binaries": ["node", "droid"]
11
+ },
12
+ "config": {
13
+ "accepts": [
14
+ "models",
15
+ "instructions.system",
16
+ "tools.enabled",
17
+ "tools.blocked",
18
+ "mcp",
19
+ "skills"
20
+ ],
21
+ "system_instruction_modes": ["replace", "append"]
22
+ },
23
+ "settings_schema": {
24
+ "type": "object",
25
+ "properties": {},
26
+ "additionalProperties": false
27
+ },
28
+ "model_schema": {
29
+ "type": "object",
30
+ "properties": {
31
+ "provider": {"const": "factory"},
32
+ "model": {"type": "string", "minLength": 1},
33
+ "api_key_env": {"type": "string", "minLength": 1}
34
+ },
35
+ "required": ["provider", "model", "api_key_env"],
36
+ "additionalProperties": false
37
+ },
38
+ "extension_schemas": {
39
+ "run_result": {
40
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
41
+ "type": "object",
42
+ "properties": {
43
+ "session_id": {"type": "string", "minLength": 1},
44
+ "finish_reason": {
45
+ "type": "string",
46
+ "enum": ["success", "interrupted", "error_during_execution", "error_structured_output"]
47
+ },
48
+ "duration_ms": {"type": "integer", "minimum": 0},
49
+ "turn_count": {"type": "integer", "minimum": 0}
50
+ },
51
+ "required": ["session_id", "finish_reason", "duration_ms", "turn_count"],
52
+ "additionalProperties": false
53
+ },
54
+ "usage": {
55
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
56
+ "type": "object",
57
+ "properties": {
58
+ "cache_read_tokens": {"type": "integer", "minimum": 0},
59
+ "cache_write_tokens": {"type": "integer", "minimum": 0},
60
+ "thinking_tokens": {"type": "integer", "minimum": 0},
61
+ "factory_credits": {"type": "number", "minimum": 0}
62
+ },
63
+ "additionalProperties": false
64
+ }
65
+ },
66
+ "capabilities": {
67
+ "streaming": false,
68
+ "cancellation": false,
69
+ "updates": false,
70
+ "service": false
71
+ }
72
+ }
package/package.json CHANGED
@@ -1,19 +1,61 @@
1
1
  {
2
2
  "name": "nemo-fabric-adapters-droid",
3
- "version": "0.0.0",
4
- "description": "Inert bootstrap for NVIDIA NeMo Fabric trusted publishing. This version contains no adapter implementation.",
3
+ "version": "0.5.0",
4
+ "description": "Factory Droid SDK harness adapter for NVIDIA NeMo Fabric.",
5
5
  "license": "Apache-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "exports": {
9
+ "./descriptor": "./droid.fabric-adapter.json",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "bin": {
13
+ "nemo-fabric-adapters-droid": "dist/cli.js"
14
+ },
6
15
  "files": [
16
+ "dist",
17
+ "droid.fabric-adapter.json",
7
18
  "README.md",
8
19
  "LICENSE"
9
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
+ },
10
32
  "repository": {
11
33
  "type": "git",
12
34
  "url": "git+https://github.com/NVIDIA/NeMo-Fabric.git",
13
35
  "directory": "adapters/typescript/droid"
14
36
  },
15
- "publishConfig": {
16
- "access": "public",
17
- "registry": "https://registry.npmjs.org"
37
+ "bugs": {
38
+ "url": "https://github.com/NVIDIA/NeMo-Fabric/issues"
39
+ },
40
+ "homepage": "https://github.com/NVIDIA/NeMo-Fabric/tree/main/adapters/typescript/droid#readme",
41
+ "engines": {
42
+ "node": ">=22.19.0"
43
+ },
44
+ "dependencies": {
45
+ "nemo-fabric-adapter-contract": "0.5.0",
46
+ "nemo-fabric-adapters-common": "0.5.0"
47
+ },
48
+ "peerDependencies": {
49
+ "@factory/droid-sdk": "^0.9.1"
50
+ },
51
+ "peerDependenciesMeta": {
52
+ "@factory/droid-sdk": {
53
+ "optional": true
54
+ }
55
+ },
56
+ "devDependencies": {
57
+ "@factory/droid-sdk": "0.9.1",
58
+ "@types/node": "24.12.4",
59
+ "typescript": "5.9.3"
18
60
  }
19
61
  }