stemcode-sdk 1.1.23__py3-none-any.whl

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.
stemcode/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """Python wrapper for the StemCode .NET SDK."""
2
+
3
+ from .client import (
4
+ DotNetLoadError,
5
+ StemCodeClient,
6
+ StemCodeClientBuilder,
7
+ StemCodeResult,
8
+ StemCodeSession,
9
+ load_stemcode,
10
+ )
11
+
12
+ __all__ = [
13
+ "DotNetLoadError",
14
+ "StemCodeClient",
15
+ "StemCodeClientBuilder",
16
+ "StemCodeResult",
17
+ "StemCodeSession",
18
+ "load_stemcode",
19
+ ]
stemcode/client.py ADDED
@@ -0,0 +1,701 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import platform
5
+ import shutil
6
+ import sys
7
+ import tempfile
8
+ import urllib.error
9
+ import urllib.request
10
+ import zipfile
11
+ from dataclasses import dataclass
12
+ from importlib.metadata import PackageNotFoundError, version as package_version
13
+ from importlib.resources import files
14
+ from pathlib import Path
15
+ from typing import Any, Callable
16
+ from xml.etree import ElementTree
17
+
18
+ _loaded = False
19
+ _assembly_resolvers: list[Any] = []
20
+ _native_library_handles: list[Any] = []
21
+
22
+
23
+ class DotNetLoadError(RuntimeError):
24
+ """Raised when the StemCode .NET assembly cannot be loaded."""
25
+
26
+
27
+ def load_stemcode(runtime_path: str | os.PathLike[str] | None = None) -> None:
28
+ """Load the StemCode .NET assembly through pythonnet.
29
+
30
+ The runtime path may point either to a directory containing StemCode.dll or
31
+ directly to StemCode.dll. If omitted, STEMCODE_DOTNET_PATH is used.
32
+ """
33
+
34
+ global _loaded
35
+ if _loaded:
36
+ return
37
+
38
+ path_value = runtime_path or os.getenv("STEMCODE_DOTNET_PATH")
39
+ if path_value:
40
+ root = Path(path_value).expanduser().resolve()
41
+ else:
42
+ root = Path(str(files("stemcode").joinpath("_dotnet"))).resolve()
43
+
44
+ assembly_path = root if root.name.lower() == "stemcode.dll" else root / "StemCode.dll"
45
+ if not assembly_path.exists() and not path_value:
46
+ root = _ensure_dotnet_runtime_from_nuget()
47
+ assembly_path = root / "StemCode.dll"
48
+
49
+ if not assembly_path.exists():
50
+ raise DotNetLoadError(
51
+ f"StemCode.dll was not found at {assembly_path}. Reinstall the "
52
+ "package or set STEMCODE_DOTNET_PATH to a published StemCode SDK folder."
53
+ )
54
+
55
+ assembly_dir = str(assembly_path.parent)
56
+ if assembly_dir not in sys.path:
57
+ sys.path.insert(0, assembly_dir)
58
+
59
+ native_dirs = _register_native_library_paths(assembly_path.parent)
60
+
61
+ try:
62
+ from pythonnet import load
63
+
64
+ try:
65
+ load("coreclr")
66
+ except RuntimeError as exc:
67
+ if "already" not in str(exc).lower():
68
+ raise
69
+
70
+ import clr # type: ignore
71
+
72
+ _register_assembly_resolver(assembly_path.parent, native_dirs)
73
+ clr.AddReference(str(assembly_path))
74
+ except Exception as exc: # pragma: no cover - depends on local .NET runtime
75
+ raise DotNetLoadError(
76
+ "Failed to load StemCode through pythonnet. Verify that pythonnet "
77
+ "is installed and that a compatible .NET runtime is available."
78
+ ) from exc
79
+
80
+ _loaded = True
81
+
82
+
83
+ def _register_native_library_paths(assembly_dir: Path) -> tuple[Path, ...]:
84
+ native_dirs = [
85
+ assembly_dir,
86
+ *(path for path in _candidate_native_dirs(assembly_dir) if path.exists()),
87
+ ]
88
+
89
+ if sys.platform == "win32":
90
+ for directory in native_dirs:
91
+ if hasattr(os, "add_dll_directory"):
92
+ _native_library_handles.append(os.add_dll_directory(str(directory)))
93
+
94
+ path_value = os.environ.get("PATH", "")
95
+ paths = [str(directory) for directory in native_dirs]
96
+ os.environ["PATH"] = os.pathsep.join([*paths, path_value]) if path_value else os.pathsep.join(paths)
97
+ else:
98
+ variable = "DYLD_LIBRARY_PATH" if sys.platform == "darwin" else "LD_LIBRARY_PATH"
99
+ path_value = os.environ.get(variable, "")
100
+ paths = [str(directory) for directory in native_dirs]
101
+ os.environ[variable] = os.pathsep.join([*paths, path_value]) if path_value else os.pathsep.join(paths)
102
+
103
+ return tuple(native_dirs)
104
+
105
+
106
+ def _candidate_native_dirs(assembly_dir: Path) -> tuple[Path, ...]:
107
+ rid = _runtime_identifier()
108
+ paths = []
109
+ if rid:
110
+ paths.append(assembly_dir / "runtimes" / rid / "native")
111
+
112
+ if sys.platform == "win32":
113
+ paths.append(assembly_dir / "runtimes" / "win" / "native")
114
+
115
+ return tuple(paths)
116
+
117
+
118
+ def _runtime_identifier() -> str | None:
119
+ system = platform.system().lower()
120
+ machine = platform.machine().lower()
121
+
122
+ architecture = {
123
+ "amd64": "x64",
124
+ "x86_64": "x64",
125
+ "arm64": "arm64",
126
+ "aarch64": "arm64",
127
+ }.get(machine)
128
+ if architecture is None:
129
+ return None
130
+
131
+ if system == "windows":
132
+ return f"win-{architecture}"
133
+ if system == "linux":
134
+ return f"linux-{architecture}"
135
+ if system == "darwin":
136
+ return f"osx-{architecture}"
137
+
138
+ return None
139
+
140
+
141
+ def _ensure_dotnet_runtime_from_nuget() -> Path:
142
+ package_id = os.getenv("STEMCODE_NUGET_PACKAGE", "StemCode")
143
+ package_version_value = os.getenv("STEMCODE_NUGET_VERSION") or _python_package_version()
144
+ source_url = os.getenv("STEMCODE_NUGET_SOURCE", "https://api.nuget.org/v3-flatcontainer")
145
+ rid = _runtime_identifier() or "any"
146
+
147
+ target_dir = _nuget_cache_root() / package_id.lower() / package_version_value / rid
148
+ assembly_path = target_dir / "StemCode.dll"
149
+ if assembly_path.exists():
150
+ _trace_nuget(f"using cached runtime: {target_dir}")
151
+ return target_dir
152
+
153
+ target_dir.parent.mkdir(parents=True, exist_ok=True)
154
+
155
+ try:
156
+ _trace_nuget(f"downloading runtime package: {package_id} {package_version_value}")
157
+ with tempfile.TemporaryDirectory(prefix="stemcode-nuget-") as temp_dir_value:
158
+ temp_dir = Path(temp_dir_value)
159
+ package_path = temp_dir / f"{package_id}.{package_version_value}.nupkg"
160
+ _download_nuget_package(package_id, package_version_value, source_url, package_path)
161
+
162
+ extract_dir = temp_dir / "package"
163
+ _extract_zip_safe(package_path, extract_dir)
164
+
165
+ runtime_dir = _select_nuget_runtime_dir(extract_dir, rid)
166
+ if target_dir.exists():
167
+ shutil.rmtree(target_dir)
168
+
169
+ shutil.copytree(runtime_dir, target_dir)
170
+ _trace_nuget(f"hydrating dependencies into: {target_dir}")
171
+ _hydrate_nuget_dependencies(
172
+ extract_dir,
173
+ target_dir,
174
+ rid,
175
+ source_url,
176
+ visited={(package_id.lower(), package_version_value.lower())},
177
+ )
178
+ except Exception as exc:
179
+ raise DotNetLoadError(
180
+ "StemCode.dll was not bundled and could not be downloaded from NuGet. "
181
+ "Set STEMCODE_DOTNET_PATH to a published StemCode SDK folder, or set "
182
+ "STEMCODE_NUGET_PACKAGE/STEMCODE_NUGET_VERSION/STEMCODE_NUGET_SOURCE "
183
+ "to a NuGet package that contains StemCode.dll and its dependency DLLs."
184
+ ) from exc
185
+
186
+ if not assembly_path.exists():
187
+ raise DotNetLoadError(
188
+ f"The NuGet package {package_id} {package_version_value} did not provide "
189
+ "StemCode.dll in a supported layout."
190
+ )
191
+
192
+ return target_dir
193
+
194
+
195
+ def _python_package_version() -> str:
196
+ try:
197
+ return package_version("stemcode-sdk")
198
+ except PackageNotFoundError:
199
+ return "0.1.0"
200
+
201
+
202
+ def _nuget_cache_root() -> Path:
203
+ configured = os.getenv("STEMCODE_DOTNET_CACHE")
204
+ if configured:
205
+ return Path(configured).expanduser().resolve()
206
+
207
+ if sys.platform == "win32":
208
+ root = os.getenv("LOCALAPPDATA")
209
+ if root:
210
+ return Path(root) / "StemCode" / "python-dotnet"
211
+
212
+ if sys.platform == "darwin":
213
+ return Path.home() / "Library" / "Caches" / "StemCode" / "python-dotnet"
214
+
215
+ root = os.getenv("XDG_CACHE_HOME")
216
+ if root:
217
+ return Path(root) / "stemcode" / "python-dotnet"
218
+
219
+ return Path.home() / ".cache" / "stemcode" / "python-dotnet"
220
+
221
+
222
+ def _download_nuget_package(package_id: str, version: str, source_url: str, destination: Path) -> None:
223
+ normalized_source = source_url.rstrip("/")
224
+ lower_id = package_id.lower()
225
+ url = f"{normalized_source}/{lower_id}/{version.lower()}/{lower_id}.{version.lower()}.nupkg"
226
+ _trace_nuget(f"GET {package_id} {version}")
227
+
228
+ request = urllib.request.Request(url, headers={"User-Agent": "stemcode-sdk-python"})
229
+ try:
230
+ with urllib.request.urlopen(request, timeout=60) as response:
231
+ destination.write_bytes(response.read())
232
+ except urllib.error.HTTPError as exc:
233
+ raise DotNetLoadError(f"NuGet package download failed with HTTP {exc.code}: {url}") from exc
234
+
235
+
236
+ def _hydrate_nuget_dependencies(
237
+ extract_dir: Path,
238
+ target_dir: Path,
239
+ rid: str,
240
+ source_url: str,
241
+ visited: set[tuple[str, str]],
242
+ ) -> None:
243
+ for dependency_id, dependency_version in _read_nuget_dependencies(extract_dir):
244
+ normalized_version = _normalize_nuget_version(dependency_version)
245
+ key = (dependency_id.lower(), normalized_version.lower())
246
+ if key in visited:
247
+ continue
248
+
249
+ visited.add(key)
250
+ _trace_nuget(f"dependency: {dependency_id} {normalized_version}")
251
+
252
+ with tempfile.TemporaryDirectory(prefix="stemcode-nuget-dep-") as temp_dir_value:
253
+ temp_dir = Path(temp_dir_value)
254
+ package_path = temp_dir / f"{dependency_id}.{normalized_version}.nupkg"
255
+ _download_nuget_package(dependency_id, normalized_version, source_url, package_path)
256
+
257
+ dependency_extract_dir = temp_dir / "package"
258
+ _extract_zip_safe(package_path, dependency_extract_dir)
259
+
260
+ _copy_nuget_managed_assets(dependency_extract_dir, target_dir)
261
+ _copy_nuget_runtime_assets(dependency_extract_dir, target_dir, rid)
262
+ if _should_hydrate_dependency_dependencies(dependency_id):
263
+ _hydrate_nuget_dependencies(dependency_extract_dir, target_dir, rid, source_url, visited)
264
+
265
+
266
+ def _read_nuget_dependencies(extract_dir: Path) -> tuple[tuple[str, str], ...]:
267
+ nuspec_files = sorted(extract_dir.glob("*.nuspec"))
268
+ if not nuspec_files:
269
+ return ()
270
+
271
+ root = ElementTree.parse(nuspec_files[0]).getroot()
272
+ namespace = ""
273
+ if root.tag.startswith("{"):
274
+ namespace = root.tag.split("}", 1)[0] + "}"
275
+
276
+ dependencies = []
277
+ for dependency in root.findall(f".//{namespace}dependency"):
278
+ dependency_id = dependency.attrib.get("id")
279
+ dependency_version = dependency.attrib.get("version")
280
+ if dependency_id and dependency_version:
281
+ dependencies.append((dependency_id, dependency_version))
282
+
283
+ return tuple(dependencies)
284
+
285
+
286
+ def _normalize_nuget_version(version: str) -> str:
287
+ normalized = version.strip()
288
+ if "," in normalized:
289
+ normalized = normalized.strip("[]()").split(",", 1)[0].strip()
290
+ return normalized.strip("[]()")
291
+
292
+
293
+ def _copy_nuget_managed_assets(extract_dir: Path, target_dir: Path) -> None:
294
+ asset_dir = _select_framework_asset_dir(extract_dir)
295
+ if asset_dir is None:
296
+ return
297
+
298
+ for asset in asset_dir.iterdir():
299
+ if asset.is_file() and asset.suffix.lower() in {".dll", ".json"}:
300
+ shutil.copy2(asset, target_dir / asset.name)
301
+
302
+
303
+ def _select_framework_asset_dir(extract_dir: Path) -> Path | None:
304
+ candidates = (
305
+ extract_dir / "lib" / "net10.0",
306
+ extract_dir / "lib" / "net9.0",
307
+ extract_dir / "lib" / "net8.0",
308
+ extract_dir / "lib" / "net7.0",
309
+ extract_dir / "lib" / "net6.0",
310
+ extract_dir / "lib" / "netstandard2.1",
311
+ extract_dir / "lib" / "netstandard2.0",
312
+ )
313
+
314
+ for candidate in candidates:
315
+ if candidate.exists():
316
+ return candidate
317
+
318
+ lib_dir = extract_dir / "lib"
319
+ if not lib_dir.exists():
320
+ return None
321
+
322
+ framework_dirs = sorted(path for path in lib_dir.iterdir() if path.is_dir())
323
+ return framework_dirs[-1] if framework_dirs else None
324
+
325
+
326
+ def _copy_nuget_runtime_assets(extract_dir: Path, target_dir: Path, rid: str) -> None:
327
+ runtime_candidates = (
328
+ extract_dir / "runtimes" / rid / "native",
329
+ extract_dir / "runtimes" / _rid_family(rid) / "native",
330
+ )
331
+ for candidate in runtime_candidates:
332
+ if candidate.exists():
333
+ native_target = target_dir / "runtimes" / candidate.parent.name / "native"
334
+ native_target.mkdir(parents=True, exist_ok=True)
335
+ for asset in candidate.iterdir():
336
+ if asset.is_file():
337
+ shutil.copy2(asset, native_target / asset.name)
338
+
339
+ runtime_lib_candidates = (
340
+ extract_dir / "runtimes" / rid / "lib" / "net10.0",
341
+ extract_dir / "runtimes" / _rid_family(rid) / "lib" / "net10.0",
342
+ )
343
+ for candidate in runtime_lib_candidates:
344
+ if candidate.exists():
345
+ for asset in candidate.iterdir():
346
+ if asset.is_file() and asset.suffix.lower() in {".dll", ".json"}:
347
+ shutil.copy2(asset, target_dir / asset.name)
348
+
349
+
350
+ def _rid_family(rid: str) -> str:
351
+ if rid.startswith("win-"):
352
+ return "win"
353
+ if rid.startswith("linux-"):
354
+ return "linux"
355
+ if rid.startswith("osx-"):
356
+ return "osx"
357
+ return rid
358
+
359
+
360
+ def _should_hydrate_dependency_dependencies(package_id: str) -> bool:
361
+ normalized = package_id.lower()
362
+ return normalized.startswith("microsoft.extensions.") or normalized.startswith("microsoft.ml.onnxruntime")
363
+
364
+
365
+ def _trace_nuget(message: str) -> None:
366
+ if os.getenv("STEMCODE_NUGET_VERBOSE"):
367
+ print(f"[stemcode-nuget] {message}", file=sys.stderr, flush=True)
368
+
369
+
370
+ def _select_nuget_runtime_dir(extract_dir: Path, rid: str) -> Path:
371
+ candidates = (
372
+ extract_dir / "tools" / "stemcode" / rid,
373
+ extract_dir / "tools" / "stemcode" / "any",
374
+ extract_dir / "tools" / rid,
375
+ extract_dir / "tools",
376
+ extract_dir / "lib" / "net10.0",
377
+ )
378
+
379
+ for candidate in candidates:
380
+ if (candidate / "StemCode.dll").exists():
381
+ return candidate
382
+
383
+ matches = sorted(extract_dir.rglob("StemCode.dll"))
384
+ if matches:
385
+ return matches[0].parent
386
+
387
+ raise DotNetLoadError("StemCode.dll was not found inside the downloaded NuGet package.")
388
+
389
+
390
+ def _extract_zip_safe(package_path: Path, destination: Path) -> None:
391
+ destination.mkdir(parents=True, exist_ok=True)
392
+ destination_root = destination.resolve()
393
+
394
+ with zipfile.ZipFile(package_path) as package:
395
+ for member in package.infolist():
396
+ target = (destination / member.filename).resolve()
397
+ if destination_root != target and destination_root not in target.parents:
398
+ raise DotNetLoadError("NuGet package contains an unsafe archive path.")
399
+
400
+ package.extractall(destination)
401
+
402
+
403
+ def _register_assembly_resolver(assembly_dir: Path, native_dirs: tuple[Path, ...]) -> None:
404
+ from System import Func, IntPtr, String # type: ignore
405
+ from System.Reflection import Assembly, AssemblyName # type: ignore
406
+ from System.Runtime.Loader import AssemblyLoadContext # type: ignore
407
+ from System.Runtime.InteropServices import NativeLibrary # type: ignore
408
+
409
+ def resolve(context: Any, assembly_name: Any) -> Any:
410
+ candidate = assembly_dir / f"{assembly_name.Name}.dll"
411
+ if candidate.exists():
412
+ return Assembly.LoadFrom(str(candidate))
413
+ return None
414
+
415
+ def resolve_unmanaged(assembly: Any, library_name: str) -> Any:
416
+ for candidate in _native_library_candidates(native_dirs, str(library_name)):
417
+ if candidate.exists():
418
+ return NativeLibrary.Load(str(candidate))
419
+
420
+ return IntPtr.Zero
421
+
422
+ resolver = Func[AssemblyLoadContext, AssemblyName, Assembly](resolve)
423
+ unmanaged_resolver = Func[Assembly, String, IntPtr](resolve_unmanaged)
424
+ AssemblyLoadContext.Default.Resolving += resolver
425
+ AssemblyLoadContext.Default.ResolvingUnmanagedDll += unmanaged_resolver
426
+ _assembly_resolvers.append(resolver)
427
+ _assembly_resolvers.append(unmanaged_resolver)
428
+
429
+
430
+ def _native_library_candidates(native_dirs: tuple[Path, ...], library_name: str) -> tuple[Path, ...]:
431
+ names = {library_name}
432
+ suffixes = (".dll", ".so", ".dylib")
433
+
434
+ if not any(library_name.endswith(suffix) for suffix in suffixes):
435
+ names.update(
436
+ {
437
+ f"{library_name}.dll",
438
+ f"{library_name}.so",
439
+ f"lib{library_name}.so",
440
+ f"{library_name}.dylib",
441
+ f"lib{library_name}.dylib",
442
+ }
443
+ )
444
+
445
+ return tuple(directory / name for directory in native_dirs for name in names)
446
+
447
+
448
+ @dataclass(frozen=True)
449
+ class StemCodeSession:
450
+ session_id: str
451
+ provider_name: str
452
+ model_id: str
453
+ agent_profile_name: str
454
+ thinking_mode: str
455
+ reasoning_effort: str | None
456
+ show_thinking: bool
457
+ section_title: str
458
+ is_resumed_section: bool
459
+ available_model_ids: tuple[str, ...]
460
+
461
+ @classmethod
462
+ def from_dotnet(cls, session: Any) -> "StemCodeSession":
463
+ return cls(
464
+ session_id=str(session.SessionId),
465
+ provider_name=str(session.ProviderName),
466
+ model_id=str(session.ModelId),
467
+ agent_profile_name=str(session.AgentProfileName),
468
+ thinking_mode=str(session.ThinkingMode),
469
+ reasoning_effort=_none_or_str(session.ReasoningEffort),
470
+ show_thinking=bool(session.ShowThinking),
471
+ section_title=str(session.SectionTitle),
472
+ is_resumed_section=bool(session.IsResumedSection),
473
+ available_model_ids=tuple(str(item) for item in session.AvailableModelIds),
474
+ )
475
+
476
+
477
+ @dataclass(frozen=True)
478
+ class StemCodeResult:
479
+ kind: str
480
+ response_text: str
481
+ reasoning_text: str | None
482
+ dotnet_result: Any
483
+
484
+ @classmethod
485
+ def from_dotnet(cls, result: Any) -> "StemCodeResult":
486
+ return cls(
487
+ kind=str(result.Kind),
488
+ response_text=str(result.ResponseText),
489
+ reasoning_text=_none_or_str(result.ReasoningText),
490
+ dotnet_result=result,
491
+ )
492
+
493
+
494
+ class StemCodeClientBuilder:
495
+ """Pythonic facade over StemCode.Sdk.StemCodeClientBuilder."""
496
+
497
+ def __init__(self, runtime_path: str | os.PathLike[str] | None = None) -> None:
498
+ load_stemcode(runtime_path)
499
+ from StemCode.Sdk import StemCodeClient as DotNetStemCodeClient # type: ignore
500
+
501
+ self._builder = DotNetStemCodeClient.CreateBuilder()
502
+
503
+ def use_anthropic(self, api_key: str, model: str | None = None) -> "StemCodeClientBuilder":
504
+ self._builder.UseAnthropic(api_key, model)
505
+ return self
506
+
507
+ def use_openai(self, api_key: str, model: str | None = None) -> "StemCodeClientBuilder":
508
+ self._builder.UseOpenAi(api_key, model)
509
+ return self
510
+
511
+ def use_google_ai_studio(self, api_key: str, model: str | None = None) -> "StemCodeClientBuilder":
512
+ self._builder.UseGoogleAiStudio(api_key, model)
513
+ return self
514
+
515
+ def use_openrouter(self, api_key: str, model: str | None = None) -> "StemCodeClientBuilder":
516
+ self._builder.UseOpenRouter(api_key, model)
517
+ return self
518
+
519
+ def use_deepseek(self, api_key: str, model: str | None = None) -> "StemCodeClientBuilder":
520
+ self._builder.UseDeepSeek(api_key, model)
521
+ return self
522
+
523
+ def use_groq(self, api_key: str, model: str | None = None) -> "StemCodeClientBuilder":
524
+ self._builder.UseGroq(api_key, model)
525
+ return self
526
+
527
+ def use_cerebras(self, api_key: str, model: str | None = None) -> "StemCodeClientBuilder":
528
+ self._builder.UseCerebras(api_key, model)
529
+ return self
530
+
531
+ def use_ollama(self, base_url: str | None = None, model: str | None = None) -> "StemCodeClientBuilder":
532
+ self._builder.UseOllama(base_url, model)
533
+ return self
534
+
535
+ def use_lm_studio(self, base_url: str | None = None, model: str | None = None) -> "StemCodeClientBuilder":
536
+ self._builder.UseLmStudio(base_url, model)
537
+ return self
538
+
539
+ def use_openai_compatible(
540
+ self,
541
+ base_url: str,
542
+ api_key: str,
543
+ model: str | None = None,
544
+ ) -> "StemCodeClientBuilder":
545
+ self._builder.UseOpenAiCompatible(base_url, api_key, model)
546
+ return self
547
+
548
+ def with_model(self, model_id: str) -> "StemCodeClientBuilder":
549
+ self._builder.WithModel(model_id)
550
+ return self
551
+
552
+ def with_workspace(self, workspace_path: str | os.PathLike[str]) -> "StemCodeClientBuilder":
553
+ self._builder.WithWorkspace(str(workspace_path))
554
+ return self
555
+
556
+ def with_profile(self, profile_name: str) -> "StemCodeClientBuilder":
557
+ self._builder.WithProfile(profile_name)
558
+ return self
559
+
560
+ def use_build_tool(self) -> "StemCodeClientBuilder":
561
+ self._builder.UseBuildTool()
562
+ return self
563
+
564
+ def with_thinking_mode(self, thinking_mode: str) -> "StemCodeClientBuilder":
565
+ self._builder.WithThinkingMode(thinking_mode)
566
+ return self
567
+
568
+ def resume_session(self, section_id: str) -> "StemCodeClientBuilder":
569
+ self._builder.ResumeSession(section_id)
570
+ return self
571
+
572
+ def with_system_prompt(self, system_prompt: str) -> "StemCodeClientBuilder":
573
+ self._builder.WithSystemPrompt(system_prompt)
574
+ return self
575
+
576
+ def use_stemcode_system_prompt(self) -> "StemCodeClientBuilder":
577
+ self._builder.UseStemCodeSystemPrompt()
578
+ return self
579
+
580
+ def without_system_prompt(self) -> "StemCodeClientBuilder":
581
+ self._builder.WithoutSystemPrompt()
582
+ return self
583
+
584
+ def auto_approve_tools(self) -> "StemCodeClientBuilder":
585
+ self._builder.AutoApproveTools()
586
+ return self
587
+
588
+ def build(self) -> "StemCodeClient":
589
+ return StemCodeClient(self._builder.Build())
590
+
591
+
592
+ class StemCodeClient:
593
+ """Synchronous convenience wrapper around StemCode.Sdk.StemCodeClient."""
594
+
595
+ def __init__(self, dotnet_client: Any) -> None:
596
+ self._client = dotnet_client
597
+ self._event_handlers: list[Any] = []
598
+
599
+ @staticmethod
600
+ def builder(runtime_path: str | os.PathLike[str] | None = None) -> StemCodeClientBuilder:
601
+ return StemCodeClientBuilder(runtime_path)
602
+
603
+ def __enter__(self) -> "StemCodeClient":
604
+ return self
605
+
606
+ def __exit__(self, exc_type: Any, exc: Any, traceback: Any) -> None:
607
+ self.close()
608
+
609
+ def initialize(self) -> StemCodeSession:
610
+ return StemCodeSession.from_dotnet(_wait(self._client.InitializeAsync()))
611
+
612
+ def run_turn(self, prompt: str) -> StemCodeResult:
613
+ return StemCodeResult.from_dotnet(_wait(self._client.RunTurnAsync(prompt)))
614
+
615
+ def run_command(self, command_text: str) -> Any:
616
+ return _wait(self._client.RunCommandAsync(command_text))
617
+
618
+ def close(self) -> None:
619
+ value_task = self._client.DisposeAsync()
620
+ if hasattr(value_task, "AsTask"):
621
+ _wait(value_task.AsTask())
622
+ elif hasattr(value_task, "GetAwaiter"):
623
+ value_task.GetAwaiter().GetResult()
624
+
625
+ def on_reasoning(self, callback: Callable[[str], Any]) -> "StemCodeClient":
626
+ from StemCode.Sdk.Events import AssistantReasoningEventArgs # type: ignore
627
+
628
+ def handler(sender: Any, args: Any) -> None:
629
+ callback(str(args.ReasoningText))
630
+
631
+ return self._add_event_handler(
632
+ "ReasoningReceived",
633
+ AssistantReasoningEventArgs,
634
+ handler,
635
+ )
636
+
637
+ def on_assistant_message_chunk(
638
+ self,
639
+ callback: Callable[..., Any],
640
+ *callback_args: Any,
641
+ **callback_kwargs: Any,
642
+ ) -> "StemCodeClient":
643
+ from StemCode.Sdk.Events import AssistantMessageChunkEventArgs # type: ignore
644
+
645
+ def handler(sender: Any, args: Any) -> None:
646
+ callback(str(args.Text), *callback_args, **callback_kwargs)
647
+
648
+ return self._add_event_handler(
649
+ "AssistantMessageChunkReceived",
650
+ AssistantMessageChunkEventArgs,
651
+ handler,
652
+ )
653
+
654
+ def on_status(self, callback: Callable[[str, str], Any]) -> "StemCodeClient":
655
+ from StemCode.Sdk.Events import StatusMessageEventArgs # type: ignore
656
+
657
+ def handler(sender: Any, args: Any) -> None:
658
+ callback(str(args.Severity), str(args.Message))
659
+
660
+ return self._add_event_handler("StatusMessage", StatusMessageEventArgs, handler)
661
+
662
+ def on_tool_calls_started(self, callback: Callable[[Any], Any]) -> "StemCodeClient":
663
+ from StemCode.Sdk.Events import ToolCallsEventArgs # type: ignore
664
+
665
+ def handler(sender: Any, args: Any) -> None:
666
+ callback(args.ToolCalls)
667
+
668
+ return self._add_event_handler("ToolCallsStarted", ToolCallsEventArgs, handler)
669
+
670
+ def on_tool_results(self, callback: Callable[[Any], Any]) -> "StemCodeClient":
671
+ from StemCode.Sdk.Events import ToolResultsEventArgs # type: ignore
672
+
673
+ def handler(sender: Any, args: Any) -> None:
674
+ callback(args.Results)
675
+
676
+ return self._add_event_handler("ToolResultsReceived", ToolResultsEventArgs, handler)
677
+
678
+ def _add_event_handler(
679
+ self,
680
+ event_name: str,
681
+ event_args_type: Any,
682
+ handler: Callable[[Any, Any], None],
683
+ ) -> "StemCodeClient":
684
+ from System import EventHandler # type: ignore
685
+
686
+ typed_handler = EventHandler[event_args_type](handler)
687
+ event = getattr(self._client, event_name)
688
+ event += typed_handler
689
+ self._event_handlers.append(typed_handler)
690
+ return self
691
+
692
+
693
+ def _wait(task: Any) -> Any:
694
+ return task.GetAwaiter().GetResult()
695
+
696
+
697
+ def _none_or_str(value: Any) -> str | None:
698
+ if value is None:
699
+ return None
700
+ text = str(value)
701
+ return text if text else None
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.5
2
+ Name: stemcode-sdk
3
+ Version: 1.1.23
4
+ Summary: Python wrapper for the StemCode .NET SDK using pythonnet.
5
+ Project-URL: Repository, https://github.com/rizwan3d/StemCode
6
+ Project-URL: Documentation, https://github.com/rizwan3d/StemCode/blob/master/docs/documentation.md
7
+ Author: Rizwan3d
8
+ License: Apache-2.0
9
+ Keywords: agent,ai,dotnet,pythonnet,stemcode
10
+ Requires-Python: >=3.10
11
+ Requires-Dist: pythonnet>=3.0.5
12
+ Description-Content-Type: text/markdown
13
+
14
+ # StemCode Python Wrapper
15
+
16
+ This package is a thin Python facade over the `StemCode.Sdk` .NET API. It uses
17
+ [`pythonnet`](https://pythonnet.github.io/) to load a published `StemCode.dll`
18
+ and keeps the .NET SDK as the source of truth.
19
+
20
+ ## Requirements
21
+
22
+ - Python 3.10 or newer
23
+ - .NET runtime that can run the StemCode target framework
24
+
25
+ ## Setup From This Repository
26
+
27
+ From the repository root, enter the Python wrapper folder:
28
+
29
+ ```powershell
30
+ cd python
31
+ ```
32
+
33
+ Create a virtual environment and install the wrapper:
34
+
35
+ ```powershell
36
+ py -3.12 -m venv .venv
37
+ .\.venv\Scripts\Activate.ps1
38
+ pip install -e .
39
+ ```
40
+
41
+ The package loads the StemCode .NET SDK from `STEMCODE_DOTNET_PATH`, a bundled
42
+ payload if one was built, or a NuGet-backed cache. On first use, the wrapper can
43
+ download the NuGet package into that cache when no local payload is present.
44
+ Set your provider credentials:
45
+
46
+ ```powershell
47
+ $env:STEMCODE_PROVIDER = "openai"
48
+ $env:STEMCODE_API_KEY = "PASTE_NEW_ROTATED_KEY_HERE"
49
+ $env:STEMCODE_MODEL = "gpt-5"
50
+ ```
51
+
52
+ Run the example:
53
+
54
+ ```powershell
55
+ python .\examples\basic_chat.py "Explain this repository in one paragraph."
56
+ ```
57
+
58
+ ## Basic Usage
59
+
60
+ ```python
61
+ from stemcode import StemCodeClient
62
+
63
+ with (
64
+ StemCodeClient.builder()
65
+ .use_openai("PASTE_NEW_ROTATED_KEY_HERE", "gpt-5")
66
+ .use_build_tool()
67
+ .with_workspace(r"F:\Projects\GrowBitLabs\StemCode")
68
+ .auto_approve_tools()
69
+ .build()
70
+ ) as client:
71
+ client.on_assistant_message_chunk(print, end="")
72
+ session = client.initialize()
73
+ print(f"Using {session.provider_name} / {session.model_id}")
74
+
75
+ result = client.run_turn("Summarize the SDK entry points.")
76
+ print(result.response_text)
77
+ ```
78
+
79
+ The wrapper exposes synchronous convenience methods around the .NET async API.
80
+ Callbacks are kept alive for the lifetime of the Python client.
81
+
82
+ ## Runtime Path
83
+
84
+ The package resolves the StemCode .NET SDK in this order:
85
+
86
+ 1. `load_stemcode(runtime_path=...)`, `StemCodeClient.builder(runtime_path=...)`,
87
+ or `STEMCODE_DOTNET_PATH`
88
+ 2. a bundled `stemcode/_dotnet` payload, when the wheel was built with one
89
+ 3. a NuGet package downloaded into the StemCode Python cache
90
+
91
+ The runtime path can be:
92
+
93
+ - a folder containing `StemCode.dll`
94
+ - the full path to `StemCode.dll`
95
+
96
+ Publish output is preferred over copying a single assembly because pythonnet
97
+ must resolve StemCode's dependency assemblies too.
98
+
99
+ NuGet download settings:
100
+
101
+ - `STEMCODE_NUGET_PACKAGE`: package ID, default `StemCode`
102
+ - `STEMCODE_NUGET_VERSION`: package version, default matching `stemcode-sdk`
103
+ - `STEMCODE_NUGET_SOURCE`: flat-container source, default NuGet.org
104
+ - `STEMCODE_DOTNET_CACHE`: cache folder override
105
+
106
+ The NuGet package must contain `StemCode.dll` and its dependency DLLs in one of
107
+ these layouts:
108
+
109
+ - `tools/stemcode/<rid>/`
110
+ - `tools/stemcode/any/`
111
+ - `tools/<rid>/`
112
+ - `tools/`
113
+ - `lib/net10.0/`
114
+
115
+ To build a wheel with the .NET payload bundled instead of downloaded, set:
116
+
117
+ ```powershell
118
+ $env:STEMCODE_BUNDLE_DOTNET = "1"
119
+ python -m build
120
+ ```
121
+
122
+ To verify the NuGet download path end to end:
123
+
124
+ ```powershell
125
+ python .\scripts\test_nuget_runtime.py --version 1.1.22
126
+ ```
@@ -0,0 +1,5 @@
1
+ stemcode/__init__.py,sha256=8uKXnKq_6NP4UCEjsjlXC2wE8heau96yfCXJ0LxgtRE,356
2
+ stemcode/client.py,sha256=WtJybGZdtXEm-kq9-aaDVOFn7SZPD8_wMonXoZIcL4E,25019
3
+ stemcode_sdk-1.1.23.dist-info/METADATA,sha256=xC0m4x2tU-gl54ZV_c-w_r0XqikWBVhFwMUpusm018o,3549
4
+ stemcode_sdk-1.1.23.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
5
+ stemcode_sdk-1.1.23.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any