dotcode-sdk 0.1.0__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.
- dotcode_sdk/__init__.py +45 -0
- dotcode_sdk/client.py +308 -0
- dotcode_sdk/types.py +100 -0
- dotcode_sdk-0.1.0.dist-info/METADATA +66 -0
- dotcode_sdk-0.1.0.dist-info/RECORD +8 -0
- dotcode_sdk-0.1.0.dist-info/WHEEL +5 -0
- dotcode_sdk-0.1.0.dist-info/licenses/LICENSE +21 -0
- dotcode_sdk-0.1.0.dist-info/top_level.txt +1 -0
dotcode_sdk/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""DotCode SDK for Python.
|
|
2
|
+
|
|
3
|
+
Embed the DotCode multi-LLM coding agent (Anthropic, OpenAI, Azure, Gemini, DeepSeek, Ollama, …) in your
|
|
4
|
+
Python application. The SDK talks JSON-RPC to a ``dotcode serve`` child process.
|
|
5
|
+
|
|
6
|
+
Built by Gravicode Studios, led by Kang Fadhil.
|
|
7
|
+
|
|
8
|
+
Example::
|
|
9
|
+
|
|
10
|
+
import asyncio
|
|
11
|
+
from dotcode_sdk import DotCodeClient
|
|
12
|
+
|
|
13
|
+
async def main():
|
|
14
|
+
async with DotCodeClient() as client:
|
|
15
|
+
session = await client.create_session(model="openai:gpt-5")
|
|
16
|
+
result = await session.send("Summarize README.md")
|
|
17
|
+
print(result["result"])
|
|
18
|
+
|
|
19
|
+
asyncio.run(main())
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from .client import DotCodeClient, Session, DotCodeError, tool, PROTOCOL_VERSION
|
|
23
|
+
from .types import (
|
|
24
|
+
AgentEvent,
|
|
25
|
+
PermissionDecision,
|
|
26
|
+
PermissionRequest,
|
|
27
|
+
SendResult,
|
|
28
|
+
Tool,
|
|
29
|
+
UserQuestion,
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"DotCodeClient",
|
|
34
|
+
"Session",
|
|
35
|
+
"DotCodeError",
|
|
36
|
+
"tool",
|
|
37
|
+
"PROTOCOL_VERSION",
|
|
38
|
+
"AgentEvent",
|
|
39
|
+
"PermissionDecision",
|
|
40
|
+
"PermissionRequest",
|
|
41
|
+
"SendResult",
|
|
42
|
+
"Tool",
|
|
43
|
+
"UserQuestion",
|
|
44
|
+
]
|
|
45
|
+
__version__ = "0.1.0"
|
dotcode_sdk/client.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""Async client for the DotCode JSON-RPC server (``dotcode serve``)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import inspect
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import shutil
|
|
10
|
+
from typing import Any, AsyncIterator, Callable, Dict, List, Optional
|
|
11
|
+
|
|
12
|
+
from .types import (
|
|
13
|
+
AgentEvent,
|
|
14
|
+
EventHandler,
|
|
15
|
+
PermissionDecision,
|
|
16
|
+
PermissionHandler,
|
|
17
|
+
QuestionHandler,
|
|
18
|
+
SendResult,
|
|
19
|
+
Tool,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
PROTOCOL_VERSION = "1.0"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class DotCodeError(Exception):
|
|
26
|
+
def __init__(self, code: int, message: str):
|
|
27
|
+
super().__init__(message)
|
|
28
|
+
self.code = code
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
async def _maybe_await(value: Any) -> Any:
|
|
32
|
+
return await value if inspect.isawaitable(value) else value
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def tool(name: str, description: str, input_schema: Optional[Dict[str, Any]] = None, read_only: bool = False):
|
|
36
|
+
"""Decorator turning a (sync or async) function into a :class:`Tool`.
|
|
37
|
+
|
|
38
|
+
::
|
|
39
|
+
|
|
40
|
+
@tool("get_weather", "Weather for a city", {"type": "object", "properties": {"city": {"type": "string"}}})
|
|
41
|
+
async def get_weather(args):
|
|
42
|
+
return f"{args['city']}: sunny"
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def wrap(fn: Callable[[Dict[str, Any]], Any]) -> Tool:
|
|
46
|
+
return Tool(name=name, description=description, handler=fn,
|
|
47
|
+
input_schema=input_schema or {"type": "object", "properties": {}}, read_only=read_only)
|
|
48
|
+
|
|
49
|
+
return wrap
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class DotCodeClient:
|
|
53
|
+
"""Starts ``dotcode serve`` and manages sessions. Use as an async context manager."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, cli_path: Optional[str] = None, cwd: Optional[str] = None,
|
|
56
|
+
env: Optional[Dict[str, str]] = None, server_args: Optional[List[str]] = None):
|
|
57
|
+
self._cli = cli_path or os.environ.get("DOTCODE_CLI_PATH") or shutil.which("dotcode") or "dotcode"
|
|
58
|
+
self._cwd = cwd
|
|
59
|
+
self._env = env or {}
|
|
60
|
+
self._server_args = server_args or []
|
|
61
|
+
self._proc: Optional[asyncio.subprocess.Process] = None
|
|
62
|
+
self._next_id = 1
|
|
63
|
+
self._pending: Dict[int, asyncio.Future] = {}
|
|
64
|
+
self._sessions: Dict[str, "Session"] = {}
|
|
65
|
+
self._reader_task: Optional[asyncio.Task] = None
|
|
66
|
+
self._write_lock = asyncio.Lock()
|
|
67
|
+
self.server_version: Optional[str] = None
|
|
68
|
+
|
|
69
|
+
async def __aenter__(self) -> "DotCodeClient":
|
|
70
|
+
await self.start()
|
|
71
|
+
return self
|
|
72
|
+
|
|
73
|
+
async def __aexit__(self, *exc: Any) -> None:
|
|
74
|
+
await self.close()
|
|
75
|
+
|
|
76
|
+
async def start(self) -> None:
|
|
77
|
+
if self._proc is not None:
|
|
78
|
+
return
|
|
79
|
+
args = ["dotnet", self._cli, "serve"] if self._cli.endswith(".dll") else [self._cli, "serve"]
|
|
80
|
+
env = {**os.environ, **self._env}
|
|
81
|
+
try:
|
|
82
|
+
self._proc = await asyncio.create_subprocess_exec(
|
|
83
|
+
*args, *self._server_args,
|
|
84
|
+
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL,
|
|
85
|
+
cwd=self._cwd, env=env, limit=64 * 1024 * 1024)
|
|
86
|
+
except FileNotFoundError as e:
|
|
87
|
+
raise RuntimeError(f"Could not start '{self._cli}'. Install the DotCode CLI or set DOTCODE_CLI_PATH.") from e
|
|
88
|
+
self._reader_task = asyncio.create_task(self._read_loop())
|
|
89
|
+
init = await self._request("initialize", {
|
|
90
|
+
"protocolVersion": PROTOCOL_VERSION,
|
|
91
|
+
"clientInfo": {"name": "dotcode-sdk-python", "version": "0.1.0"},
|
|
92
|
+
"capabilities": {"permissions": True, "questions": True},
|
|
93
|
+
})
|
|
94
|
+
self.server_version = (init or {}).get("serverInfo", {}).get("version")
|
|
95
|
+
|
|
96
|
+
async def close(self) -> None:
|
|
97
|
+
if self._proc is None:
|
|
98
|
+
return
|
|
99
|
+
try:
|
|
100
|
+
await asyncio.wait_for(self._request("shutdown", {}), timeout=1.5)
|
|
101
|
+
except Exception:
|
|
102
|
+
pass
|
|
103
|
+
if self._proc.stdin:
|
|
104
|
+
self._proc.stdin.close()
|
|
105
|
+
try:
|
|
106
|
+
await asyncio.wait_for(self._proc.wait(), timeout=3)
|
|
107
|
+
except asyncio.TimeoutError:
|
|
108
|
+
self._proc.kill()
|
|
109
|
+
if self._reader_task:
|
|
110
|
+
self._reader_task.cancel()
|
|
111
|
+
self._proc = None
|
|
112
|
+
|
|
113
|
+
# ------------------------------------------------------------------ JSON-RPC plumbing
|
|
114
|
+
|
|
115
|
+
async def _write(self, msg: Dict[str, Any]) -> None:
|
|
116
|
+
assert self._proc and self._proc.stdin
|
|
117
|
+
data = (json.dumps(msg, ensure_ascii=False) + "\n").encode("utf-8")
|
|
118
|
+
async with self._write_lock:
|
|
119
|
+
self._proc.stdin.write(data)
|
|
120
|
+
await self._proc.stdin.drain()
|
|
121
|
+
|
|
122
|
+
async def _request(self, method: str, params: Dict[str, Any]) -> Any:
|
|
123
|
+
msg_id = self._next_id
|
|
124
|
+
self._next_id += 1
|
|
125
|
+
fut: asyncio.Future = asyncio.get_running_loop().create_future()
|
|
126
|
+
self._pending[msg_id] = fut
|
|
127
|
+
await self._write({"jsonrpc": "2.0", "id": msg_id, "method": method, "params": params})
|
|
128
|
+
return await fut
|
|
129
|
+
|
|
130
|
+
async def _read_loop(self) -> None:
|
|
131
|
+
assert self._proc and self._proc.stdout
|
|
132
|
+
while True:
|
|
133
|
+
line = await self._proc.stdout.readline()
|
|
134
|
+
if not line:
|
|
135
|
+
break
|
|
136
|
+
try:
|
|
137
|
+
msg = json.loads(line)
|
|
138
|
+
except json.JSONDecodeError:
|
|
139
|
+
continue
|
|
140
|
+
if "method" not in msg:
|
|
141
|
+
fut = self._pending.pop(msg.get("id"), None)
|
|
142
|
+
if fut and not fut.done():
|
|
143
|
+
if "error" in msg:
|
|
144
|
+
fut.set_exception(DotCodeError(msg["error"].get("code", 0), msg["error"].get("message", "error")))
|
|
145
|
+
else:
|
|
146
|
+
fut.set_result(msg.get("result"))
|
|
147
|
+
continue
|
|
148
|
+
params = msg.get("params") or {}
|
|
149
|
+
if msg.get("id") is None:
|
|
150
|
+
if msg["method"] == "session.event":
|
|
151
|
+
session = self._sessions.get(params.get("sessionId"))
|
|
152
|
+
if session:
|
|
153
|
+
session._dispatch(params.get("event", {}))
|
|
154
|
+
continue
|
|
155
|
+
asyncio.create_task(self._answer(msg["id"], msg["method"], params))
|
|
156
|
+
for fut in self._pending.values():
|
|
157
|
+
if not fut.done():
|
|
158
|
+
fut.set_exception(RuntimeError("DotCode server connection closed"))
|
|
159
|
+
|
|
160
|
+
async def _answer(self, msg_id: Any, method: str, params: Dict[str, Any]) -> None:
|
|
161
|
+
session = self._sessions.get(params.get("sessionId"))
|
|
162
|
+
try:
|
|
163
|
+
if session is None:
|
|
164
|
+
raise DotCodeError(-32001, "Unknown session")
|
|
165
|
+
result = await session._handle_server_request(method, params)
|
|
166
|
+
await self._write({"jsonrpc": "2.0", "id": msg_id, "result": result})
|
|
167
|
+
except DotCodeError as e:
|
|
168
|
+
await self._write({"jsonrpc": "2.0", "id": msg_id, "error": {"code": e.code, "message": str(e)}})
|
|
169
|
+
except Exception as e: # noqa: BLE001 - report handler failures to the server
|
|
170
|
+
await self._write({"jsonrpc": "2.0", "id": msg_id, "error": {"code": -32603, "message": str(e)}})
|
|
171
|
+
|
|
172
|
+
# ------------------------------------------------------------------ API
|
|
173
|
+
|
|
174
|
+
async def create_session(self, *, model: Optional[str] = None, cwd: Optional[str] = None,
|
|
175
|
+
permission_mode: Optional[str] = None, system_prompt: Optional[str] = None,
|
|
176
|
+
append_system_prompt: Optional[str] = None, allowed_tools: Optional[List[str]] = None,
|
|
177
|
+
disallowed_tools: Optional[List[str]] = None, builtin_tools: Optional[List[str]] = None,
|
|
178
|
+
tools: Optional[List[Tool]] = None, mcp_servers: Optional[Dict[str, Any]] = None,
|
|
179
|
+
settings: Optional[Dict[str, Any]] = None, max_turns: Optional[int] = None,
|
|
180
|
+
effort: Optional[str] = None, persist_session: bool = True, no_mcp: bool = False,
|
|
181
|
+
on_permission_request: Optional[PermissionHandler] = None,
|
|
182
|
+
on_question: Optional[QuestionHandler] = None,
|
|
183
|
+
on_plan_review: Optional[Callable[[str], Any]] = None,
|
|
184
|
+
on_event: Optional[EventHandler] = None,
|
|
185
|
+
resume_session_id: Optional[str] = None, fork: bool = False) -> "Session":
|
|
186
|
+
"""Create (or resume) an agent session. Without ``on_permission_request`` the session is deny-by-default."""
|
|
187
|
+
await self.start()
|
|
188
|
+
params: Dict[str, Any] = {
|
|
189
|
+
"cwd": cwd or self._cwd, "model": model, "permissionMode": permission_mode,
|
|
190
|
+
"systemPrompt": system_prompt, "appendSystemPrompt": append_system_prompt,
|
|
191
|
+
"allowedTools": allowed_tools, "disallowedTools": disallowed_tools, "tools": builtin_tools,
|
|
192
|
+
"hostTools": [t.to_wire() for t in tools] if tools else None,
|
|
193
|
+
"mcpServers": mcp_servers, "settings": settings, "maxTurns": max_turns, "effort": effort,
|
|
194
|
+
"persistSession": persist_session, "noMcp": no_mcp,
|
|
195
|
+
}
|
|
196
|
+
params = {k: v for k, v in params.items() if v is not None}
|
|
197
|
+
if resume_session_id:
|
|
198
|
+
params["sessionId"] = resume_session_id
|
|
199
|
+
params["fork"] = fork
|
|
200
|
+
info = await self._request("session.resume" if resume_session_id else "session.create", params)
|
|
201
|
+
session = Session(self, info, tools or [], on_permission_request, on_question, on_plan_review, on_event)
|
|
202
|
+
self._sessions[session.id] = session
|
|
203
|
+
return session
|
|
204
|
+
|
|
205
|
+
async def list_models(self) -> Dict[str, Any]:
|
|
206
|
+
await self.start()
|
|
207
|
+
return await self._request("models.list", {"cwd": self._cwd} if self._cwd else {})
|
|
208
|
+
|
|
209
|
+
async def list_sessions(self) -> Dict[str, Any]:
|
|
210
|
+
await self.start()
|
|
211
|
+
return await self._request("session.list", {"cwd": self._cwd} if self._cwd else {})
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class Session:
|
|
215
|
+
def __init__(self, client: DotCodeClient, info: Dict[str, Any], tools: List[Tool],
|
|
216
|
+
on_permission_request: Optional[PermissionHandler], on_question: Optional[QuestionHandler],
|
|
217
|
+
on_plan_review: Optional[Callable[[str], Any]], on_event: Optional[EventHandler]):
|
|
218
|
+
self._client = client
|
|
219
|
+
self.info = info
|
|
220
|
+
self.id: str = info["sessionId"]
|
|
221
|
+
self.model: str = info.get("model", "")
|
|
222
|
+
self._tools = {t.name: t for t in tools}
|
|
223
|
+
self._on_permission = on_permission_request
|
|
224
|
+
self._on_question = on_question
|
|
225
|
+
self._on_plan_review = on_plan_review
|
|
226
|
+
self._on_event = on_event
|
|
227
|
+
self._queues: List[asyncio.Queue] = []
|
|
228
|
+
|
|
229
|
+
def _dispatch(self, event: AgentEvent) -> None:
|
|
230
|
+
if event.get("type") == "model.changed":
|
|
231
|
+
self.model = event.get("model", self.model) # type: ignore[call-overload]
|
|
232
|
+
if self._on_event:
|
|
233
|
+
self._on_event(event)
|
|
234
|
+
for q in self._queues:
|
|
235
|
+
q.put_nowait(event)
|
|
236
|
+
|
|
237
|
+
async def _handle_server_request(self, method: str, params: Dict[str, Any]) -> Any:
|
|
238
|
+
if method == "permission.request":
|
|
239
|
+
if not self._on_permission:
|
|
240
|
+
return {"decision": "deny", "feedback": "No permission handler registered in the SDK host (deny by default)."}
|
|
241
|
+
decision: PermissionDecision = await _maybe_await(self._on_permission(params["request"]))
|
|
242
|
+
return decision
|
|
243
|
+
if method == "user.question":
|
|
244
|
+
answers = await _maybe_await(self._on_question(params["questions"])) if self._on_question else []
|
|
245
|
+
return {"answers": answers}
|
|
246
|
+
if method == "plan.review":
|
|
247
|
+
ok = True if not self._on_plan_review else await _maybe_await(self._on_plan_review(params.get("plan", "")))
|
|
248
|
+
return {"approval": "approve" if ok else "reject"}
|
|
249
|
+
if method == "tool.call":
|
|
250
|
+
t = self._tools.get(params.get("name"))
|
|
251
|
+
if t is None:
|
|
252
|
+
raise DotCodeError(-32601, f"Unknown host tool {params.get('name')}")
|
|
253
|
+
try:
|
|
254
|
+
content = await _maybe_await(t.handler(params.get("input") or {}))
|
|
255
|
+
return {"content": content if isinstance(content, (str, list)) else json.dumps(content)}
|
|
256
|
+
except Exception as e: # noqa: BLE001 - tool errors are reported to the model
|
|
257
|
+
return {"content": f"Error: {e}", "isError": True}
|
|
258
|
+
raise DotCodeError(-32601, method)
|
|
259
|
+
|
|
260
|
+
async def send(self, prompt: str, attachments: Optional[List[Dict[str, Any]]] = None) -> SendResult:
|
|
261
|
+
"""Run a prompt to completion and return the final result."""
|
|
262
|
+
params: Dict[str, Any] = {"sessionId": self.id, "prompt": prompt}
|
|
263
|
+
if attachments:
|
|
264
|
+
params["attachments"] = attachments
|
|
265
|
+
return await self._client._request("session.send", params)
|
|
266
|
+
|
|
267
|
+
async def stream(self, prompt: str) -> AsyncIterator[AgentEvent]:
|
|
268
|
+
"""Run a prompt and yield events as they arrive; the last event is ``turn.completed``."""
|
|
269
|
+
queue: asyncio.Queue = asyncio.Queue()
|
|
270
|
+
self._queues.append(queue)
|
|
271
|
+
task = asyncio.create_task(self.send(prompt))
|
|
272
|
+
try:
|
|
273
|
+
while True:
|
|
274
|
+
getter = asyncio.create_task(queue.get())
|
|
275
|
+
done, _ = await asyncio.wait({getter, task}, return_when=asyncio.FIRST_COMPLETED)
|
|
276
|
+
if getter in done:
|
|
277
|
+
event = getter.result()
|
|
278
|
+
yield event
|
|
279
|
+
if event.get("type") == "turn.completed" and not event.get("parentToolUseId"):
|
|
280
|
+
break
|
|
281
|
+
else:
|
|
282
|
+
getter.cancel()
|
|
283
|
+
while not queue.empty():
|
|
284
|
+
yield queue.get_nowait()
|
|
285
|
+
break
|
|
286
|
+
await task
|
|
287
|
+
finally:
|
|
288
|
+
self._queues.remove(queue)
|
|
289
|
+
|
|
290
|
+
async def abort(self) -> None:
|
|
291
|
+
await self._client._request("session.abort", {"sessionId": self.id})
|
|
292
|
+
|
|
293
|
+
async def set_model(self, model: str) -> None:
|
|
294
|
+
await self._client._request("session.setModel", {"sessionId": self.id, "model": model})
|
|
295
|
+
self.model = model
|
|
296
|
+
|
|
297
|
+
async def set_permission_mode(self, mode: str) -> None:
|
|
298
|
+
await self._client._request("session.setMode", {"sessionId": self.id, "mode": mode})
|
|
299
|
+
|
|
300
|
+
async def compact(self, instructions: Optional[str] = None) -> None:
|
|
301
|
+
await self._client._request("session.compact", {"sessionId": self.id, "instructions": instructions})
|
|
302
|
+
|
|
303
|
+
async def messages(self) -> List[Dict[str, Any]]:
|
|
304
|
+
return (await self._client._request("session.messages", {"sessionId": self.id}))["messages"]
|
|
305
|
+
|
|
306
|
+
async def close(self) -> None:
|
|
307
|
+
await self._client._request("session.close", {"sessionId": self.id})
|
|
308
|
+
self._client._sessions.pop(self.id, None)
|
dotcode_sdk/types.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Protocol types (see schema/protocol.schema.json in the DotCode repository)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from typing import Any, Awaitable, Callable, Dict, List, Literal, Optional, TypedDict, Union
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Usage(TypedDict, total=False):
|
|
10
|
+
inputTokens: int
|
|
11
|
+
outputTokens: int
|
|
12
|
+
cacheReadTokens: int
|
|
13
|
+
cacheWriteTokens: int
|
|
14
|
+
reasoningTokens: int
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class AgentEvent(TypedDict, total=False):
|
|
18
|
+
"""Engine event. ``type`` is one of: session.started, user.message, assistant.text.delta,
|
|
19
|
+
assistant.thinking.delta, assistant.message, tool.started, tool.progress, tool.completed, todo.updated,
|
|
20
|
+
subagent.started, subagent.completed, context.compacted, usage.updated, model.changed, model.fallback,
|
|
21
|
+
retry, notice, error, mode.changed, turn.completed."""
|
|
22
|
+
|
|
23
|
+
type: str
|
|
24
|
+
sessionId: str
|
|
25
|
+
parentToolUseId: str
|
|
26
|
+
text: str
|
|
27
|
+
name: str
|
|
28
|
+
displayName: str
|
|
29
|
+
toolUseId: str
|
|
30
|
+
output: str
|
|
31
|
+
summary: str
|
|
32
|
+
isError: bool
|
|
33
|
+
resultText: str
|
|
34
|
+
diff: str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class PermissionRequest(TypedDict, total=False):
|
|
38
|
+
toolUseId: str
|
|
39
|
+
toolName: str
|
|
40
|
+
displayName: str
|
|
41
|
+
input: Dict[str, Any]
|
|
42
|
+
title: str
|
|
43
|
+
detail: str
|
|
44
|
+
suggestedRule: str
|
|
45
|
+
diff: str
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class PermissionDecision(TypedDict, total=False):
|
|
49
|
+
decision: Literal["allow", "allow_always", "allow_session", "deny"]
|
|
50
|
+
feedback: str
|
|
51
|
+
rule: str
|
|
52
|
+
updatedInput: Dict[str, Any]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class UserQuestion(TypedDict, total=False):
|
|
56
|
+
question: str
|
|
57
|
+
header: str
|
|
58
|
+
options: List[Dict[str, str]]
|
|
59
|
+
multiSelect: bool
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class SendResult(TypedDict, total=False):
|
|
63
|
+
sessionId: str
|
|
64
|
+
stopReason: str
|
|
65
|
+
result: str
|
|
66
|
+
isError: bool
|
|
67
|
+
error: str
|
|
68
|
+
durationMs: int
|
|
69
|
+
numModelCalls: int
|
|
70
|
+
costUsd: float
|
|
71
|
+
totalCostUsd: float
|
|
72
|
+
usage: Usage
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
ToolContent = Union[str, List[Dict[str, Any]]]
|
|
76
|
+
ToolHandler = Callable[[Dict[str, Any]], Union[ToolContent, Awaitable[ToolContent]]]
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
@dataclass
|
|
80
|
+
class Tool:
|
|
81
|
+
"""A tool implemented by your application and offered to the model."""
|
|
82
|
+
|
|
83
|
+
name: str
|
|
84
|
+
description: str
|
|
85
|
+
handler: ToolHandler
|
|
86
|
+
input_schema: Dict[str, Any] = field(default_factory=lambda: {"type": "object", "properties": {}})
|
|
87
|
+
read_only: bool = False
|
|
88
|
+
|
|
89
|
+
def to_wire(self) -> Dict[str, Any]:
|
|
90
|
+
return {
|
|
91
|
+
"name": self.name,
|
|
92
|
+
"description": self.description,
|
|
93
|
+
"inputSchema": self.input_schema,
|
|
94
|
+
"readOnly": self.read_only,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
PermissionHandler = Callable[[PermissionRequest], Union[PermissionDecision, Awaitable[PermissionDecision]]]
|
|
99
|
+
QuestionHandler = Callable[[List[UserQuestion]], Union[List[Dict[str, str]], Awaitable[List[Dict[str, str]]]]]
|
|
100
|
+
EventHandler = Callable[[AgentEvent], None]
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dotcode-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python SDK for DotCode — embed a multi-LLM coding agent (Anthropic, OpenAI, Azure, Gemini, DeepSeek, Ollama) in your app. By Gravicode Studios, led by Kang Fadhil.
|
|
5
|
+
Author: Gravicode Studios (Kang Fadhil)
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/DotNetVibeCoderz/Vibe_Dev
|
|
8
|
+
Project-URL: Repository, https://github.com/DotNetVibeCoderz/Vibe_Dev
|
|
9
|
+
Keywords: ai,agent,coding-agent,llm,claude,openai,gemini,deepseek,ollama,mcp,dotcode
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Framework :: AsyncIO
|
|
14
|
+
Classifier: Topic :: Software Development
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# DotCode SDK — Python
|
|
21
|
+
|
|
22
|
+
Embed the [DotCode](https://github.com/DotNetVibeCoderz/Vibe_Dev) coding agent in your application and drive it with **any LLM** (Anthropic, OpenAI, Azure OpenAI, Gemini, DeepSeek, Ollama, OpenAI-compatible). The SDK talks JSON-RPC to a `dotcode serve` process.
|
|
23
|
+
|
|
24
|
+
*Built by Gravicode Studios, led by Kang Fadhil.* · 🇮🇩 Dokumentasi Bahasa Indonesia: [docs/id/sdk.md](https://github.com/DotNetVibeCoderz/Vibe_Dev/blob/main/DotCode/docs/id/sdk.md)
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
pip install dotcode-sdk
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
The SDK needs the `dotcode` CLI: put it on `PATH` or set `DOTCODE_CLI_PATH` (a path to `dotcode.dll` is started with `dotnet`). Configure providers with environment variables (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `DEEPSEEK_API_KEY`, …), `~/.dotcode/settings.json`, or per session with the `settings` option.
|
|
33
|
+
|
|
34
|
+
## Usage
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
import asyncio
|
|
38
|
+
from dotcode_sdk import DotCodeClient, tool
|
|
39
|
+
|
|
40
|
+
@tool("now", "Current time")
|
|
41
|
+
def now(args):
|
|
42
|
+
import datetime
|
|
43
|
+
return datetime.datetime.now().isoformat()
|
|
44
|
+
|
|
45
|
+
async def main():
|
|
46
|
+
async with DotCodeClient() as client: # spawns `dotcode serve`
|
|
47
|
+
session = await client.create_session(model="deepseek:deepseek-v4-flash", tools=[now],
|
|
48
|
+
on_permission_request=lambda r: {"decision": "allow"})
|
|
49
|
+
async for e in session.stream("What time is it? Then list the files here."):
|
|
50
|
+
if e["type"] == "assistant.text.delta":
|
|
51
|
+
print(e["text"], end="")
|
|
52
|
+
|
|
53
|
+
asyncio.run(main())
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Features
|
|
57
|
+
|
|
58
|
+
- Sessions with streaming events (text deltas, tool calls, diffs, todos, usage, cost)
|
|
59
|
+
- **Custom tools** implemented in your app
|
|
60
|
+
- **Permission handler** — sessions are deny-by-default without one; decisions: `allow`, `allow_always`, `allow_session`, `deny` (with feedback)
|
|
61
|
+
- Question (AskUserQuestion) and plan-review handlers
|
|
62
|
+
- MCP servers, allowed/disallowed tool rules, permission modes, system prompt overrides, model switching, compaction, transcripts, resume/fork
|
|
63
|
+
|
|
64
|
+
Full guide: [docs/en/sdk.md](https://github.com/DotNetVibeCoderz/Vibe_Dev/blob/main/DotCode/docs/en/sdk.md) · Protocol: [schema/protocol.schema.json](https://github.com/DotNetVibeCoderz/Vibe_Dev/blob/main/DotCode/schema/protocol.schema.json)
|
|
65
|
+
|
|
66
|
+
License: MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
dotcode_sdk/__init__.py,sha256=QIaQddgyHUFDCokI2Uqfr7VXbup9KyVEkOafIGreM8M,1067
|
|
2
|
+
dotcode_sdk/client.py,sha256=rhPBoXMr3pJcx47rFXBOJxMXxMCxWYvowta9E3ACtSM,14384
|
|
3
|
+
dotcode_sdk/types.py,sha256=IE5egNgTjzK8y5Ntcwk2Kyy4dqQ3lLATt9oENqXF_z4,2720
|
|
4
|
+
dotcode_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=ewThhW4UXgzcgPeeHr9hmFVOVT9CHZdZEYw7A5SIx00,1095
|
|
5
|
+
dotcode_sdk-0.1.0.dist-info/METADATA,sha256=l30Lxwqz4RL8g8CwlY_j4fzBidpCr-2MkMJkzkfi5dw,3171
|
|
6
|
+
dotcode_sdk-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
7
|
+
dotcode_sdk-0.1.0.dist-info/top_level.txt,sha256=gOCzfeSBSnLcXzYBz53BSKdvzEfWLW88bba7cm_3yZY,12
|
|
8
|
+
dotcode_sdk-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gravicode Studios (led by Kang Fadhil)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
dotcode_sdk
|