krnla 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.
krnla/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ from .client import (
2
+ AgentIdentity,
3
+ DeclarationResult,
4
+ InboxAcknowledgement,
5
+ InboxMessage,
6
+ KRNLA,
7
+ LLMResult,
8
+ MessageResult,
9
+ SendStatus,
10
+ )
11
+ from .errors import *
12
+
13
+ __all__ = [
14
+ "AgentIdentity",
15
+ "DeclarationResult",
16
+ "InboxAcknowledgement",
17
+ "InboxMessage",
18
+ "KRNLA",
19
+ "LLMResult",
20
+ "MessageResult",
21
+ "SendStatus",
22
+ ]
krnla/client.py ADDED
@@ -0,0 +1,856 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import math
5
+ import os
6
+ import re
7
+ import socket
8
+ import ssl
9
+ import sys
10
+ import uuid
11
+ from dataclasses import dataclass
12
+ from importlib.resources import files
13
+ from pathlib import Path
14
+ from typing import Any, Callable, Iterator, Mapping, Protocol, Sequence
15
+ from urllib.error import HTTPError, URLError
16
+ from urllib.parse import urlsplit
17
+ from urllib.request import HTTPRedirectHandler, HTTPSHandler, ProxyHandler, Request, build_opener
18
+
19
+ from .errors import (
20
+ KRNLAAgentDisabledError,
21
+ KRNLAAuthenticationError,
22
+ KRNLAConfigurationError,
23
+ KRNLAConflictError,
24
+ KRNLAConnectionError,
25
+ KRNLAError,
26
+ KRNLAForbiddenError,
27
+ KRNLAInvalidRequestError,
28
+ KRNLAPolicyBlockedError,
29
+ KRNLAProtocolError,
30
+ KRNLARateLimitedError,
31
+ KRNLARequestCancelledError,
32
+ KRNLARequestTimeoutError,
33
+ KRNLAResponseTooLargeError,
34
+ KRNLAServerError,
35
+ KRNLAServiceUnavailableError,
36
+ KRNLAUpstreamTimeoutError,
37
+ KRNLADestinationNotFoundError,
38
+ )
39
+
40
+ CONTRACT: dict[str, Any] = json.loads(
41
+ files("krnla").joinpath("contract.json").read_text(encoding="utf-8")
42
+ )
43
+
44
+
45
+ class Response(Protocol):
46
+ status: int
47
+ headers: Any
48
+
49
+ def read(self, amount: int = -1) -> bytes: ...
50
+ def readline(self, amount: int = -1) -> bytes: ...
51
+ def close(self) -> None: ...
52
+
53
+
54
+ Transport = Callable[[str, str, Mapping[str, str], bytes | None, float], Response]
55
+
56
+
57
+ class _NoRedirect(HTTPRedirectHandler):
58
+ def redirect_request(self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str) -> None:
59
+ return None
60
+
61
+
62
+ def _https_context() -> ssl.SSLContext:
63
+ # Python.org macOS builds may lack a bundled CA path. Trust the OS CA bundle,
64
+ # never an unverified context, and honor explicitly configured CA paths.
65
+ paths = ssl.get_default_verify_paths()
66
+ if (
67
+ sys.platform == "darwin"
68
+ and paths.cafile is None
69
+ and "SSL_CERT_FILE" not in os.environ
70
+ and "SSL_CERT_DIR" not in os.environ
71
+ and Path("/etc/ssl/cert.pem").is_file()
72
+ ):
73
+ return ssl.create_default_context(cafile="/etc/ssl/cert.pem")
74
+ return ssl.create_default_context()
75
+
76
+
77
+ def _default_transport(
78
+ method: str, url: str, headers: Mapping[str, str], body: bytes | None, timeout: float
79
+ ) -> Response:
80
+ # Empty ProxyHandler prevents environment proxy discovery from receiving credentials.
81
+ opener = build_opener(ProxyHandler({}), _NoRedirect(), HTTPSHandler(context=_https_context()))
82
+ request = Request(url, data=body, headers=dict(headers), method=method)
83
+ try:
84
+ return opener.open(request, timeout=timeout)
85
+ except HTTPError as error:
86
+ return error
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class AgentIdentity:
91
+ agent_id: str
92
+ organization_id: str
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class MessageResult:
97
+ operation_id: str | None
98
+ trace_id: str
99
+ delivery_id: str
100
+ destination_agent_id: str
101
+ decision: str
102
+ matched_policy_id: str | None
103
+ reason_code: str
104
+ policy_set_revision: str
105
+ transport: str
106
+ outcome: str
107
+ upstream_status: int | None
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class SendStatus:
112
+ operation_id: str
113
+ state: str
114
+ trace_id: str | None = None
115
+ delivery_id: str | None = None
116
+ destination_agent_id: str | None = None
117
+ decision: str | None = None
118
+ matched_policy_id: str | None = None
119
+ reason_code: str | None = None
120
+ policy_set_revision: str | None = None
121
+ transport: str | None = None
122
+
123
+
124
+ @dataclass(frozen=True)
125
+ class InboxMessage:
126
+ delivery_id: str
127
+ lease_id: str
128
+ source_agent_id: str
129
+ connection_id: str
130
+ event_type: str
131
+ destination_interface: Mapping[str, str | None]
132
+ content: tuple[Mapping[str, str], ...]
133
+ queued_at: str
134
+ expires_at: str
135
+ lease_expires_at: str
136
+ delivery_attempt: int
137
+
138
+
139
+ @dataclass(frozen=True)
140
+ class InboxAcknowledgement:
141
+ delivery_id: str
142
+ acknowledged_at: str
143
+ duplicate: bool
144
+
145
+
146
+ @dataclass(frozen=True)
147
+ class LLMResult:
148
+ trace_id: str
149
+ request_id: str
150
+ request_decision: Mapping[str, Any]
151
+ transport_outcome: str
152
+ upstream_status: int | None
153
+ response_decision: Mapping[str, Any] | None
154
+ response_content_type: str | None
155
+ response_body: str | None
156
+ usage: Mapping[str, int] | None
157
+
158
+
159
+ @dataclass(frozen=True)
160
+ class DeclarationResult:
161
+ version: int
162
+ revision: str
163
+ changed: bool
164
+ declarations: tuple[Mapping[str, Any], ...]
165
+
166
+
167
+ ERROR_CLASSES: dict[str, type[KRNLAError]] = {
168
+ "UNAUTHENTICATED": KRNLAAuthenticationError,
169
+ "FORBIDDEN": KRNLAForbiddenError,
170
+ "POLICY_BLOCKED": KRNLAPolicyBlockedError,
171
+ "AGENT_DISABLED": KRNLAAgentDisabledError,
172
+ "DESTINATION_NOT_FOUND": KRNLADestinationNotFoundError,
173
+ "NOT_FOUND": KRNLADestinationNotFoundError,
174
+ "METHOD_NOT_ALLOWED": KRNLAInvalidRequestError,
175
+ "INVALID_REQUEST": KRNLAInvalidRequestError,
176
+ "CONFLICT": KRNLAConflictError,
177
+ "REQUEST_TOO_LARGE": KRNLAInvalidRequestError,
178
+ "UNSUPPORTED_MEDIA_TYPE": KRNLAInvalidRequestError,
179
+ "RATE_LIMITED": KRNLARateLimitedError,
180
+ "CONFIG_UNAVAILABLE": KRNLAServiceUnavailableError,
181
+ "UPSTREAM_TIMEOUT": KRNLAUpstreamTimeoutError,
182
+ "INTERNAL_ERROR": KRNLAServerError,
183
+ }
184
+
185
+
186
+ def _configuration(message: str) -> None:
187
+ raise KRNLAConfigurationError(message, "CONFIGURATION_ERROR")
188
+
189
+
190
+ def _gateway_origin(value: str | None) -> str:
191
+ if not value:
192
+ _configuration("KRNLA_GATEWAY_URL is required.")
193
+ assert value is not None
194
+ if len(value) > CONTRACT["gatewayUrlMaximumLength"] or re.search(r"[\x00-\x20\\?#]", value):
195
+ _configuration("KRNLA_GATEWAY_URL is invalid.")
196
+ try:
197
+ parsed = urlsplit(value)
198
+ port = parsed.port
199
+ except ValueError:
200
+ _configuration("KRNLA_GATEWAY_URL is invalid.")
201
+ loopback = parsed.hostname in {"localhost", "127.0.0.1", "::1"}
202
+ if (
203
+ not parsed.hostname
204
+ or (parsed.scheme != "https" and not (parsed.scheme == "http" and loopback))
205
+ or parsed.username is not None
206
+ or parsed.password is not None
207
+ or parsed.query
208
+ or parsed.fragment
209
+ or parsed.path not in {"", "/"}
210
+ ):
211
+ _configuration("KRNLA_GATEWAY_URL must be an HTTPS origin (HTTP is local-only).")
212
+ host = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname
213
+ return f"{parsed.scheme}://{host}{f':{port}' if port is not None else ''}"
214
+
215
+
216
+ def _credential(value: str | None) -> str:
217
+ if not value:
218
+ _configuration("KRNLA_API_KEY is required.")
219
+ assert value is not None
220
+ if re.fullmatch(CONTRACT["credentialPattern"], value) is None:
221
+ _configuration("KRNLA_API_KEY is invalid.")
222
+ return value
223
+
224
+
225
+ def _bounded_timeout(value: float, name: str) -> float:
226
+ if (
227
+ isinstance(value, bool)
228
+ or not isinstance(value, (int, float))
229
+ or not math.isfinite(value)
230
+ or value < 0.1
231
+ or value > 120
232
+ ):
233
+ _configuration(f"{name} must be between 0.1 and 120 seconds.")
234
+ return float(value)
235
+
236
+
237
+ def _object(value: Any) -> dict[str, Any]:
238
+ if not isinstance(value, dict):
239
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
240
+ return value
241
+
242
+
243
+ def _utf16_units(value: str) -> int:
244
+ try:
245
+ return len(value.encode("utf-16-le")) // 2
246
+ except UnicodeError:
247
+ return 1_000_000_000
248
+
249
+
250
+ def _error_from_envelope(value: Any, status: int, ambiguous: bool) -> KRNLAError:
251
+ envelope = _object(value)
252
+ details = _object(envelope.get("error"))
253
+ code = details.get("code")
254
+ if envelope.get("ok") is not False or not isinstance(code, str) or code not in CONTRACT["errors"]:
255
+ return KRNLAProtocolError("Gateway error response is invalid.", "PROTOCOL_ERROR", status)
256
+ definition = CONTRACT["errors"][code]
257
+ return ERROR_CLASSES.get(code, KRNLAServerError)(
258
+ definition["message"], code, status, "UNKNOWN" if ambiguous else None
259
+ )
260
+
261
+
262
+ class KRNLA:
263
+ __slots__ = (
264
+ "__gateway",
265
+ "__api_key",
266
+ "__timeout",
267
+ "__streaming_inactivity_timeout",
268
+ "__transport",
269
+ "_verified_identity",
270
+ "llm",
271
+ )
272
+
273
+ def __init__(
274
+ self,
275
+ *,
276
+ api_key: str | None = None,
277
+ gateway_url: str | None = None,
278
+ timeout: float = 15.0,
279
+ streaming_inactivity_timeout: float = 10.0,
280
+ transport: Transport | None = None,
281
+ ) -> None:
282
+ self.__gateway = _gateway_origin(
283
+ gateway_url if gateway_url is not None else os.environ.get("KRNLA_GATEWAY_URL")
284
+ )
285
+ self.__api_key = _credential(
286
+ api_key if api_key is not None else os.environ.get("KRNLA_API_KEY")
287
+ )
288
+ self.__timeout = _bounded_timeout(timeout, "timeout")
289
+ self.__streaming_inactivity_timeout = _bounded_timeout(
290
+ streaming_inactivity_timeout, "streaming_inactivity_timeout"
291
+ )
292
+ self.__transport = transport or _default_transport
293
+ self._verified_identity: AgentIdentity | None = None
294
+ self.llm = LLMClient(self)
295
+
296
+ @classmethod
297
+ def connect(
298
+ cls,
299
+ *,
300
+ api_key: str | None = None,
301
+ gateway_url: str | None = None,
302
+ timeout: float = 15.0,
303
+ streaming_inactivity_timeout: float = 10.0,
304
+ transport: Transport | None = None,
305
+ ) -> KRNLA:
306
+ client = cls(
307
+ api_key=api_key,
308
+ gateway_url=gateway_url,
309
+ timeout=timeout,
310
+ streaming_inactivity_timeout=streaming_inactivity_timeout,
311
+ transport=transport,
312
+ )
313
+ client._verified_identity = client.me()
314
+ return client
315
+
316
+ @property
317
+ def identity(self) -> AgentIdentity | None:
318
+ return self._verified_identity
319
+
320
+ def __repr__(self) -> str:
321
+ return f'KRNLA(gateway="{self.__gateway}", credential="[REDACTED]")'
322
+
323
+ __str__ = __repr__
324
+
325
+ def me(self) -> AgentIdentity:
326
+ data = self._json("identity", "GET", None, ambiguous=False)
327
+ return AgentIdentity(agent_id=self._string(data, "agentId"), organization_id=self._string(data, "organizationId"))
328
+
329
+ def send(
330
+ self,
331
+ *,
332
+ agent: str,
333
+ data: Mapping[str, str],
334
+ event: str | None = None,
335
+ ) -> MessageResult:
336
+ if len(data) < 1 or len(data) > CONTRACT["request"]["maximumContentFields"]:
337
+ raise KRNLAInvalidRequestError("Message data has an invalid field count.", "INVALID_REQUEST")
338
+ content: list[dict[str, str]] = []
339
+ for field_id, text in data.items():
340
+ if (
341
+ re.fullmatch(r"[A-Za-z][A-Za-z0-9_.-]*", field_id) is None
342
+ or len(field_id) > CONTRACT["request"]["maximumFieldIdLength"]
343
+ or not isinstance(text, str)
344
+ or _utf16_units(text) > CONTRACT["request"]["maximumFieldTextUtf16CodeUnits"]
345
+ ):
346
+ raise KRNLAInvalidRequestError("Message data is invalid.", "INVALID_REQUEST")
347
+ content.append({"id": field_id, "text": text})
348
+ body: dict[str, Any] = {"destinationAgentId": agent, "content": content}
349
+ if event is not None:
350
+ body["eventType"] = event
351
+ response = self._json("messages", "POST", body, ambiguous=True)
352
+ if (
353
+ response.get("operationId") is not None
354
+ or response.get("decision") not in {"ALLOW", "BLOCK", "REDACT"}
355
+ or response.get("outcome") not in CONTRACT["messageOutcomes"]
356
+ or response.get("transport") not in {"INBOX", "DIRECT_PUSH"}
357
+ or (response.get("outcome") == "BLOCKED") != (response.get("decision") == "BLOCK")
358
+ or not (response.get("matchedPolicyId") is None or isinstance(response.get("matchedPolicyId"), str))
359
+ or not self._valid_status(response.get("upstreamStatus"))
360
+ ):
361
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
362
+ return MessageResult(
363
+ operation_id=response.get("operationId"),
364
+ trace_id=self._string(response, "traceId"),
365
+ delivery_id=self._string(response, "deliveryId"),
366
+ destination_agent_id=self._string(response, "destinationAgentId"),
367
+ decision=self._string(response, "decision"),
368
+ matched_policy_id=response.get("matchedPolicyId"),
369
+ reason_code=self._string(response, "reasonCode"),
370
+ policy_set_revision=self._string(response, "policySetRevision"),
371
+ transport=self._string(response, "transport"),
372
+ outcome=self._string(response, "outcome"),
373
+ upstream_status=response.get("upstreamStatus"),
374
+ )
375
+
376
+ def emit(self, event: str, data: Mapping[str, str], *, target: str) -> MessageResult:
377
+ return self.send(agent=target, event=event, data=data)
378
+
379
+ def send_connection(
380
+ self,
381
+ *,
382
+ connection: str,
383
+ data: Mapping[str, str],
384
+ operation_id: str | None = None,
385
+ ) -> MessageResult:
386
+ if re.fullmatch(
387
+ r"[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}",
388
+ connection,
389
+ re.IGNORECASE,
390
+ ) is None:
391
+ raise KRNLAInvalidRequestError(
392
+ "Connection identifier is invalid.", "INVALID_REQUEST"
393
+ )
394
+ if len(data) < 1 or len(data) > CONTRACT["request"]["maximumContentFields"]:
395
+ raise KRNLAInvalidRequestError(
396
+ "Message data has an invalid field count.", "INVALID_REQUEST"
397
+ )
398
+ content: list[dict[str, str]] = []
399
+ for field_id, text in data.items():
400
+ if (
401
+ re.fullmatch(r"[A-Za-z][A-Za-z0-9_.-]*", field_id) is None
402
+ or len(field_id) > CONTRACT["request"]["maximumFieldIdLength"]
403
+ or not isinstance(text, str)
404
+ or _utf16_units(text)
405
+ > CONTRACT["request"]["maximumFieldTextUtf16CodeUnits"]
406
+ ):
407
+ raise KRNLAInvalidRequestError("Message data is invalid.", "INVALID_REQUEST")
408
+ content.append({"id": field_id, "text": text})
409
+ operation_id = operation_id or f"op_{uuid.uuid4().hex}"
410
+ if re.fullmatch(CONTRACT["sendOperationPattern"], operation_id) is None:
411
+ raise KRNLAInvalidRequestError(
412
+ "Send operation identifier is invalid.", "INVALID_REQUEST"
413
+ )
414
+ try:
415
+ response = self._json(
416
+ "messages",
417
+ "POST",
418
+ {"connectionId": connection, "operationId": operation_id, "content": content},
419
+ ambiguous=True,
420
+ operation_id=operation_id,
421
+ )
422
+ except KRNLAError as error:
423
+ error.operation_id = operation_id
424
+ raise
425
+ if (
426
+ response.get("operationId") != operation_id
427
+ or response.get("decision") not in {"ALLOW", "BLOCK", "REDACT"}
428
+ or response.get("outcome") not in CONTRACT["messageOutcomes"]
429
+ or response.get("transport") not in {"INBOX", "DIRECT_PUSH"}
430
+ or (response.get("outcome") == "BLOCKED") != (response.get("decision") == "BLOCK")
431
+ or not (
432
+ response.get("matchedPolicyId") is None
433
+ or isinstance(response.get("matchedPolicyId"), str)
434
+ )
435
+ or not self._valid_status(response.get("upstreamStatus"))
436
+ ):
437
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
438
+ return MessageResult(
439
+ operation_id=response.get("operationId"),
440
+ trace_id=self._string(response, "traceId"),
441
+ delivery_id=self._string(response, "deliveryId"),
442
+ destination_agent_id=self._string(response, "destinationAgentId"),
443
+ decision=self._string(response, "decision"),
444
+ matched_policy_id=response.get("matchedPolicyId"),
445
+ reason_code=self._string(response, "reasonCode"),
446
+ policy_set_revision=self._string(response, "policySetRevision"),
447
+ transport=self._string(response, "transport"),
448
+ outcome=self._string(response, "outcome"),
449
+ upstream_status=response.get("upstreamStatus"),
450
+ )
451
+
452
+ def get_send_status(self, *, operation_id: str) -> SendStatus:
453
+ if re.fullmatch(CONTRACT["sendOperationPattern"], operation_id) is None:
454
+ raise KRNLAInvalidRequestError(
455
+ "Send operation identifier is invalid.", "INVALID_REQUEST"
456
+ )
457
+ response = self._json(
458
+ f'{CONTRACT["paths"]["sendStatus"]}/{operation_id}',
459
+ "GET",
460
+ None,
461
+ ambiguous=False,
462
+ )
463
+ state = response.get("state")
464
+ if response.get("operationId") != operation_id or state not in {
465
+ "NOT_FOUND", "BLOCKED", "QUEUED", "LEASED", "ACKNOWLEDGED", "EXPIRED", "FAILED"
466
+ }:
467
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
468
+ if state == "NOT_FOUND":
469
+ return SendStatus(operation_id=operation_id, state=state)
470
+ if response.get("transport") != "INBOX":
471
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
472
+ return SendStatus(
473
+ operation_id=operation_id,
474
+ state=state,
475
+ trace_id=self._string(response, "traceId"),
476
+ delivery_id=self._string(response, "deliveryId"),
477
+ destination_agent_id=self._string(response, "destinationAgentId"),
478
+ decision=self._string(response, "decision"),
479
+ matched_policy_id=response.get("matchedPolicyId"),
480
+ reason_code=self._string(response, "reasonCode"),
481
+ policy_set_revision=self._string(response, "policySetRevision"),
482
+ transport="INBOX",
483
+ )
484
+
485
+ def poll_inbox(self, *, limit: int = 1) -> tuple[InboxMessage, ...]:
486
+ if type(limit) is not int or not 1 <= limit <= CONTRACT["inbox"]["maximumBatchSize"]:
487
+ raise KRNLAInvalidRequestError("Inbox batch size is invalid.", "INVALID_REQUEST")
488
+ data = self._json(f'{CONTRACT["paths"]["inbox"]}?limit={limit}', "GET", None, ambiguous=False)
489
+ messages = data.get("messages")
490
+ if not isinstance(messages, list) or len(messages) > limit:
491
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
492
+ result: list[InboxMessage] = []
493
+ for item in messages:
494
+ value = _object(item)
495
+ content = value.get("content")
496
+ interface = _object(value.get("destinationInterface"))
497
+ if (
498
+ re.fullmatch(r"dl_[0-9a-f]{32}", str(value.get("deliveryId"))) is None
499
+ or re.fullmatch(r"ls_[0-9a-f]{32}", str(value.get("leaseId"))) is None
500
+ or not isinstance(content, list)
501
+ or type(value.get("deliveryAttempt")) is not int
502
+ ):
503
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
504
+ result.append(InboxMessage(
505
+ delivery_id=self._string(value, "deliveryId"),
506
+ lease_id=self._string(value, "leaseId"),
507
+ source_agent_id=self._string(value, "sourceAgentId"),
508
+ connection_id=self._string(value, "connectionId"),
509
+ event_type=self._string(value, "eventType"),
510
+ destination_interface=interface,
511
+ content=tuple(_object(field) for field in content),
512
+ queued_at=self._string(value, "queuedAt"),
513
+ expires_at=self._string(value, "expiresAt"),
514
+ lease_expires_at=self._string(value, "leaseExpiresAt"),
515
+ delivery_attempt=value["deliveryAttempt"],
516
+ ))
517
+ return tuple(result)
518
+
519
+ def acknowledge(self, *, delivery_id: str, lease_id: str) -> InboxAcknowledgement:
520
+ if re.fullmatch(r"dl_[0-9a-f]{32}", delivery_id) is None or re.fullmatch(r"ls_[0-9a-f]{32}", lease_id) is None:
521
+ raise KRNLAInvalidRequestError("Inbox acknowledgement is invalid.", "INVALID_REQUEST")
522
+ data = self._json(
523
+ f'{CONTRACT["paths"]["inbox"]}/{delivery_id}/acknowledge',
524
+ "POST",
525
+ {"leaseId": lease_id},
526
+ ambiguous=False,
527
+ )
528
+ if data.get("deliveryId") != delivery_id or data.get("state") != "ACKNOWLEDGED" or not isinstance(data.get("acknowledgedAt"), str) or type(data.get("duplicate")) is not bool:
529
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
530
+ return InboxAcknowledgement(delivery_id, data["acknowledgedAt"], data["duplicate"])
531
+
532
+ def declare(
533
+ self,
534
+ *,
535
+ emits: Sequence[str | Mapping[str, str | None]] = (),
536
+ accepts: Sequence[str | Mapping[str, str | None]] = (),
537
+ ) -> DeclarationResult:
538
+ body = {
539
+ "version": 1,
540
+ "emits": [self._declaration(item) for item in emits],
541
+ "receives": [self._declaration(item) for item in accepts],
542
+ }
543
+ keys = [
544
+ (kind, item["name"], item["version"])
545
+ for kind, items in (("EVENT_EMIT", body["emits"]), ("EVENT_RECEIVE", body["receives"]))
546
+ for item in items
547
+ ]
548
+ if len(keys) > CONTRACT["declarations"]["maximumPerAgent"] or len(set(keys)) != len(keys):
549
+ raise KRNLAInvalidRequestError(
550
+ "Interface declaration set is invalid.", "INVALID_REQUEST"
551
+ )
552
+ return self._declaration_result(self._json("interfaces", "PUT", body, ambiguous=False))
553
+
554
+ def declarations(self) -> DeclarationResult:
555
+ return self._declaration_result(self._json("interfaces", "GET", None, ambiguous=False))
556
+
557
+ def _llm_generate(self, provider_config_id: str, inputs: Sequence[Mapping[str, str]]) -> LLMResult:
558
+ response = self._json(
559
+ "llm", "POST", {"providerConfigId": provider_config_id, "input": list(inputs)}, ambiguous=True
560
+ )
561
+ usage = response.get("usage")
562
+ valid_usage = usage is None or (
563
+ isinstance(usage, dict)
564
+ and all(
565
+ isinstance(usage.get(key), int) and not isinstance(usage.get(key), bool) and usage[key] >= 0
566
+ for key in ("inputTokens", "outputTokens", "totalTokens")
567
+ )
568
+ )
569
+ if (
570
+ response.get("transportOutcome") not in CONTRACT["transportOutcomes"]
571
+ or not self._valid_status(response.get("upstreamStatus"))
572
+ or not (response.get("responseContentType") is None or isinstance(response.get("responseContentType"), str))
573
+ or not (response.get("responseBody") is None or isinstance(response.get("responseBody"), str))
574
+ or not (response.get("responseDecision") is None or isinstance(response.get("responseDecision"), dict))
575
+ or not valid_usage
576
+ ):
577
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
578
+ return LLMResult(
579
+ trace_id=self._string(response, "traceId"),
580
+ request_id=self._string(response, "requestId"),
581
+ request_decision=_object(response.get("requestDecision")),
582
+ transport_outcome=self._string(response, "transportOutcome"),
583
+ upstream_status=response.get("upstreamStatus"),
584
+ response_decision=response.get("responseDecision"),
585
+ response_content_type=response.get("responseContentType"),
586
+ response_body=response.get("responseBody"),
587
+ usage=usage,
588
+ )
589
+
590
+ def _llm_stream(self, provider_config_id: str, inputs: Sequence[Mapping[str, str]]) -> Iterator[Mapping[str, Any]]:
591
+ body = self._body({"providerConfigId": provider_config_id, "stream": True, "input": list(inputs)})
592
+ response = self._open("llm", "POST", body, ambiguous=True)
593
+ try:
594
+ if not 200 <= response.status < 300:
595
+ payload = self._read_json_response(response)
596
+ raise _error_from_envelope(payload, response.status, True)
597
+ content_type = str(response.headers.get("content-type", "")).lower()
598
+ if not content_type.startswith("application/x-ndjson"):
599
+ raise KRNLAProtocolError("Gateway streaming response is invalid.", "PROTOCOL_ERROR", response.status, "UNKNOWN")
600
+ total = 0
601
+ started = False
602
+ completed = False
603
+ next_sequence = 0
604
+ released_bytes = 0
605
+ while True:
606
+ line = response.readline(CONTRACT["response"]["maximumJsonBytes"] + 1)
607
+ if not line:
608
+ break
609
+ total += len(line)
610
+ if len(line) > CONTRACT["response"]["maximumJsonBytes"] or total > CONTRACT["response"]["maximumStreamBytes"]:
611
+ raise KRNLAResponseTooLargeError("Gateway stream exceeded the SDK limit.", "RESPONSE_TOO_LARGE", None, "UNKNOWN")
612
+ try:
613
+ frame = _object(json.loads(line.decode("utf-8")))
614
+ except (UnicodeError, json.JSONDecodeError):
615
+ raise KRNLAProtocolError("Gateway stream frame is invalid.", "PROTOCOL_ERROR", None, "UNKNOWN") from None
616
+ if frame.get("version") != 1 or frame.get("type") not in {"start", "data", "complete", "error"}:
617
+ raise KRNLAProtocolError("Gateway stream frame is invalid.", "PROTOCOL_ERROR", None, "UNKNOWN")
618
+ kind = frame["type"]
619
+ expected = {
620
+ "start": {"version", "type", "traceId", "requestId", "requestDecision", "upstreamStatus"},
621
+ "data": {"version", "type", "sequence", "text"},
622
+ "complete": {"version", "type", "transportOutcome", "releasedBytes"},
623
+ "error": {"version", "type", "code", "transportOutcome", "releasedBytes"},
624
+ }
625
+ if set(frame) != expected[kind] or completed or (kind == "start") != (not started):
626
+ raise KRNLAProtocolError("Gateway stream order is invalid.", "PROTOCOL_ERROR", None, "UNKNOWN")
627
+ if kind == "start":
628
+ if (not isinstance(frame["traceId"], str) or not isinstance(frame["requestId"], str)
629
+ or not isinstance(frame["requestDecision"], dict)
630
+ or isinstance(frame["upstreamStatus"], bool)
631
+ or not isinstance(frame["upstreamStatus"], int)
632
+ or not 100 <= frame["upstreamStatus"] <= 599):
633
+ raise KRNLAProtocolError("Gateway stream frame is invalid.", "PROTOCOL_ERROR", None, "UNKNOWN")
634
+ started = True
635
+ if frame.get("type") == "data" and (
636
+ not isinstance(frame.get("text"), str)
637
+ or isinstance(frame.get("sequence"), bool)
638
+ or not isinstance(frame.get("sequence"), int)
639
+ or frame["sequence"] != next_sequence
640
+ or _utf16_units(frame["text"])
641
+ > CONTRACT["response"]["maximumStreamFrameTextUtf16CodeUnits"]
642
+ ):
643
+ raise KRNLAProtocolError(
644
+ "Gateway stream frame is invalid.",
645
+ "PROTOCOL_ERROR",
646
+ None,
647
+ "UNKNOWN",
648
+ )
649
+ if kind == "data":
650
+ next_sequence += 1
651
+ released_bytes += len(frame["text"].encode("utf-8"))
652
+ if kind in {"complete", "error"} and (
653
+ isinstance(frame["releasedBytes"], bool)
654
+ or not isinstance(frame["releasedBytes"], int)
655
+ or frame["releasedBytes"] < 0
656
+ ):
657
+ raise KRNLAProtocolError("Gateway stream frame is invalid.", "PROTOCOL_ERROR", None, "UNKNOWN")
658
+ if kind == "complete":
659
+ if frame["transportOutcome"] != "ACKNOWLEDGED" or frame["releasedBytes"] != released_bytes:
660
+ raise KRNLAProtocolError("Gateway stream frame is invalid.", "PROTOCOL_ERROR", None, "UNKNOWN")
661
+ completed = True
662
+ if frame.get("type") == "error":
663
+ code = frame.get("code")
664
+ outcome = frame.get("transportOutcome")
665
+ if (
666
+ not isinstance(code, str)
667
+ or code not in CONTRACT["errors"]
668
+ or outcome not in {"ACKNOWLEDGED", "UNKNOWN"}
669
+ ):
670
+ raise KRNLAProtocolError(
671
+ "Gateway stream frame is invalid.",
672
+ "PROTOCOL_ERROR",
673
+ None,
674
+ "UNKNOWN",
675
+ )
676
+ raise ERROR_CLASSES.get(code, KRNLAServerError)(
677
+ CONTRACT["errors"][code]["message"],
678
+ code,
679
+ None,
680
+ "UNKNOWN" if outcome == "UNKNOWN" else None,
681
+ )
682
+ yield frame
683
+ if not completed:
684
+ raise KRNLAProtocolError("Gateway stream ended without completion.", "PROTOCOL_ERROR", None, "UNKNOWN")
685
+ except socket.timeout:
686
+ raise KRNLARequestTimeoutError("Streaming response timed out.", "REQUEST_TIMEOUT", None, "UNKNOWN") from None
687
+ except (URLError, OSError):
688
+ raise KRNLAConnectionError("Gateway connection failed.", "CONNECTION_ERROR", None, "UNKNOWN") from None
689
+ except KRNLAError:
690
+ raise
691
+ except Exception:
692
+ raise KRNLAConnectionError("Gateway connection failed.", "CONNECTION_ERROR", None, "UNKNOWN") from None
693
+ finally:
694
+ try:
695
+ response.close()
696
+ except Exception:
697
+ pass
698
+
699
+ def _headers(self, operation_id: str | None = None) -> Mapping[str, str]:
700
+ return {
701
+ "Authorization": f"Bearer {self.__api_key}",
702
+ "Content-Type": "application/json",
703
+ "Accept": "application/json, application/x-ndjson",
704
+ "User-Agent": f"KRNLA-Python-SDK/{CONTRACT['sdkVersion']}",
705
+ **({"X-KRNLA-Operation-ID": operation_id} if operation_id else {}),
706
+ }
707
+
708
+ def _body(self, value: Any) -> bytes:
709
+ try:
710
+ body = json.dumps(value, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
711
+ except (TypeError, ValueError, UnicodeError):
712
+ raise KRNLAInvalidRequestError("Request is invalid.", "INVALID_REQUEST") from None
713
+ if len(body) > CONTRACT["request"]["maximumBytes"]:
714
+ raise KRNLAInvalidRequestError("Request exceeds the Gateway limit.", "REQUEST_TOO_LARGE")
715
+ return body
716
+
717
+ def _open(
718
+ self,
719
+ path: str,
720
+ method: str,
721
+ body: bytes | None,
722
+ *,
723
+ ambiguous: bool,
724
+ operation_id: str | None = None,
725
+ ) -> Response:
726
+ try:
727
+ return self.__transport(
728
+ method,
729
+ f"{self.__gateway}{path if path.startswith('/') else CONTRACT['paths'][path]}",
730
+ self._headers(operation_id),
731
+ body,
732
+ self.__streaming_inactivity_timeout if path == "llm" and body and b'"stream":true' in body else self.__timeout,
733
+ )
734
+ except (TimeoutError, socket.timeout):
735
+ raise KRNLARequestTimeoutError("Gateway request timed out.", "REQUEST_TIMEOUT", None, "UNKNOWN" if ambiguous else None) from None
736
+ except (URLError, OSError):
737
+ raise KRNLAConnectionError("Gateway connection failed.", "CONNECTION_ERROR", None, "UNKNOWN" if ambiguous else None) from None
738
+ except Exception:
739
+ raise KRNLAConnectionError("Gateway connection failed.", "CONNECTION_ERROR", None, "UNKNOWN" if ambiguous else None) from None
740
+
741
+ def _json(
742
+ self,
743
+ path: str,
744
+ method: str,
745
+ value: Any,
746
+ *,
747
+ ambiguous: bool,
748
+ operation_id: str | None = None,
749
+ ) -> dict[str, Any]:
750
+ response = self._open(
751
+ path,
752
+ method,
753
+ None if value is None else self._body(value),
754
+ ambiguous=ambiguous,
755
+ operation_id=operation_id,
756
+ )
757
+ try:
758
+ payload = self._read_json_response(response)
759
+ if not 200 <= response.status < 300:
760
+ raise _error_from_envelope(payload, response.status, ambiguous)
761
+ envelope = _object(payload)
762
+ if envelope.get("ok") is not True:
763
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR", response.status)
764
+ return _object(envelope.get("data"))
765
+ except (TimeoutError, socket.timeout):
766
+ raise KRNLARequestTimeoutError("Gateway response timed out.", "REQUEST_TIMEOUT", None, "UNKNOWN" if ambiguous else None) from None
767
+ except (URLError, OSError):
768
+ raise KRNLAConnectionError("Gateway connection failed.", "CONNECTION_ERROR", None, "UNKNOWN" if ambiguous else None) from None
769
+ except KRNLAError:
770
+ raise
771
+ except Exception:
772
+ raise KRNLAConnectionError("Gateway connection failed.", "CONNECTION_ERROR", None, "UNKNOWN" if ambiguous else None) from None
773
+ finally:
774
+ try:
775
+ response.close()
776
+ except Exception:
777
+ pass
778
+
779
+ def _read_json_response(self, response: Response) -> Any:
780
+ maximum = CONTRACT["response"]["maximumJsonBytes"]
781
+ source = response.read(maximum + 1)
782
+ if len(source) > maximum:
783
+ raise KRNLAResponseTooLargeError("Gateway response exceeded the SDK limit.", "RESPONSE_TOO_LARGE")
784
+ try:
785
+ return json.loads(source.decode("utf-8"))
786
+ except (UnicodeError, json.JSONDecodeError):
787
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR", response.status) from None
788
+
789
+ @staticmethod
790
+ def _string(data: Mapping[str, Any], key: str) -> str:
791
+ value = data.get(key)
792
+ if not isinstance(value, str):
793
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
794
+ return value
795
+
796
+ @staticmethod
797
+ def _valid_status(value: Any) -> bool:
798
+ return value is None or (type(value) is int and 100 <= value <= 599)
799
+
800
+ @staticmethod
801
+ def _declaration(item: str | Mapping[str, str | None]) -> dict[str, str | None]:
802
+ value = (
803
+ {"name": item, "version": None}
804
+ if isinstance(item, str)
805
+ else {"name": item.get("name"), "version": item.get("version")}
806
+ )
807
+ name = value["name"]
808
+ version = value["version"]
809
+ if (
810
+ not isinstance(name, str)
811
+ or re.fullmatch(r"[A-Za-z][A-Za-z0-9_.:-]*", name) is None
812
+ or len(name) > CONTRACT["declarations"]["maximumNameLength"]
813
+ or not (
814
+ version is None
815
+ or (
816
+ isinstance(version, str)
817
+ and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:-]*", version)
818
+ is not None
819
+ and len(version) <= CONTRACT["declarations"]["maximumVersionLength"]
820
+ )
821
+ )
822
+ ):
823
+ raise KRNLAInvalidRequestError(
824
+ "Interface declaration is invalid.", "INVALID_REQUEST"
825
+ )
826
+ return value
827
+
828
+ @staticmethod
829
+ def _declaration_result(data: Mapping[str, Any]) -> DeclarationResult:
830
+ declarations = data.get("declarations")
831
+ if data.get("version") != 1 or not isinstance(data.get("revision"), str) or not isinstance(data.get("changed"), bool) or not isinstance(declarations, list) or len(declarations) > CONTRACT["declarations"]["maximumPerAgent"]:
832
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
833
+ checked = []
834
+ for item in declarations:
835
+ value = _object(item)
836
+ if (
837
+ value.get("kind") not in CONTRACT["declarations"]["kinds"]
838
+ or not isinstance(value.get("name"), str)
839
+ or not (value.get("interfaceVersion") is None or isinstance(value.get("interfaceVersion"), str))
840
+ or value.get("source") != "DECLARED"
841
+ or value.get("state") != "ACTIVE"
842
+ ):
843
+ raise KRNLAProtocolError("Gateway response is invalid.", "PROTOCOL_ERROR")
844
+ checked.append(value)
845
+ return DeclarationResult(1, data["revision"], data["changed"], tuple(checked))
846
+
847
+
848
+ class LLMClient:
849
+ def __init__(self, client: KRNLA) -> None:
850
+ self.__client = client
851
+
852
+ def generate(self, *, provider_config_id: str, input: Sequence[Mapping[str, str]]) -> LLMResult:
853
+ return self.__client._llm_generate(provider_config_id, input)
854
+
855
+ def stream(self, *, provider_config_id: str, input: Sequence[Mapping[str, str]]) -> Iterator[Mapping[str, Any]]:
856
+ return self.__client._llm_stream(provider_config_id, input)
krnla/contract.json ADDED
@@ -0,0 +1,59 @@
1
+ {
2
+ "apiVersion": 1,
3
+ "sdkVersion": "0.1.0",
4
+ "paths": {
5
+ "identity": "/api/gateway/v1/identity",
6
+ "interfaces": "/api/gateway/v1/interfaces",
7
+ "messages": "/api/gateway/v1/messages",
8
+ "sendStatus": "/api/gateway/v1/messages",
9
+ "inbox": "/api/gateway/v1/inbox",
10
+ "llm": "/api/gateway/v1/llm"
11
+ },
12
+ "credentialPattern": "^krn_live_[0-9a-f]{32}_[A-Za-z0-9_-]{43}$",
13
+ "sendOperationPattern": "^op_[0-9a-f]{32}$",
14
+ "gatewayUrlMaximumLength": 2048,
15
+ "request": {
16
+ "maximumBytes": 65536,
17
+ "maximumContentFields": 8,
18
+ "maximumFieldIdLength": 64,
19
+ "maximumFieldTextUtf16CodeUnits": 32768
20
+ },
21
+ "response": {
22
+ "maximumJsonBytes": 65536,
23
+ "maximumStreamBytes": 1048576,
24
+ "maximumStreamFrameTextUtf16CodeUnits": 8192
25
+ },
26
+ "declarations": {
27
+ "kinds": ["EVENT_EMIT", "EVENT_RECEIVE"],
28
+ "maximumPerAgent": 256,
29
+ "maximumNameLength": 128,
30
+ "maximumVersionLength": 64
31
+ },
32
+ "transportOutcomes": ["BLOCKED", "NOT_SENT", "ACKNOWLEDGED", "UNKNOWN"],
33
+ "messageOutcomes": ["BLOCKED", "NOT_SENT", "QUEUED", "ACKNOWLEDGED", "UNKNOWN"],
34
+ "inbox": {
35
+ "maximumBatchSize": 20,
36
+ "maximumPendingPerAgent": 500,
37
+ "maximumPendingPerOrganization": 10000,
38
+ "ttlSeconds": 86400,
39
+ "leaseSeconds": 120,
40
+ "maximumDeliveryAttempts": 20
41
+ },
42
+ "errors": {
43
+ "UNAUTHENTICATED": { "status": 401, "message": "Authentication is required." },
44
+ "FORBIDDEN": { "status": 403, "message": "Access is not permitted." },
45
+ "POLICY_BLOCKED": { "status": 403, "message": "Request blocked by an organization policy." },
46
+ "AGENT_DISABLED": { "status": 403, "message": "Agent is disabled." },
47
+ "DESTINATION_NOT_FOUND": { "status": 404, "message": "Destination was not found." },
48
+ "NOT_FOUND": { "status": 404, "message": "Resource was not found." },
49
+ "METHOD_NOT_ALLOWED": { "status": 405, "message": "Method is not allowed." },
50
+ "INVALID_REQUEST": { "status": 400, "message": "Request is invalid." },
51
+ "CONFLICT": { "status": 409, "message": "Request conflicts with the current resource state." },
52
+ "REQUEST_TOO_LARGE": { "status": 413, "message": "Request is too large." },
53
+ "UNSUPPORTED_MEDIA_TYPE": { "status": 415, "message": "Content type is not supported." },
54
+ "RATE_LIMITED": { "status": 429, "message": "Request rate limit exceeded." },
55
+ "CONFIG_UNAVAILABLE": { "status": 503, "message": "Required configuration is unavailable." },
56
+ "UPSTREAM_TIMEOUT": { "status": 504, "message": "Upstream request timed out." },
57
+ "INTERNAL_ERROR": { "status": 500, "message": "Request could not be completed." }
58
+ }
59
+ }
krnla/errors.py ADDED
@@ -0,0 +1,84 @@
1
+ from __future__ import annotations
2
+
3
+
4
+ class KRNLAError(Exception):
5
+ def __init__(
6
+ self,
7
+ message: str,
8
+ code: str,
9
+ status: int | None = None,
10
+ outcome: str | None = None,
11
+ ) -> None:
12
+ super().__init__(message)
13
+ self.code = code
14
+ self.status = status
15
+ self.outcome = outcome
16
+ self.operation_id: str | None = None
17
+
18
+
19
+ class KRNLAConfigurationError(KRNLAError):
20
+ pass
21
+
22
+
23
+ class KRNLAAuthenticationError(KRNLAError):
24
+ pass
25
+
26
+
27
+ class KRNLAForbiddenError(KRNLAError):
28
+ pass
29
+
30
+
31
+ class KRNLAPolicyBlockedError(KRNLAError):
32
+ pass
33
+
34
+
35
+ class KRNLAAgentDisabledError(KRNLAError):
36
+ pass
37
+
38
+
39
+ class KRNLADestinationNotFoundError(KRNLAError):
40
+ pass
41
+
42
+
43
+ class KRNLARateLimitedError(KRNLAError):
44
+ pass
45
+
46
+
47
+ class KRNLAInvalidRequestError(KRNLAError):
48
+ pass
49
+
50
+
51
+ class KRNLAConflictError(KRNLAError):
52
+ pass
53
+
54
+
55
+ class KRNLAServiceUnavailableError(KRNLAError):
56
+ pass
57
+
58
+
59
+ class KRNLAUpstreamTimeoutError(KRNLAError):
60
+ pass
61
+
62
+
63
+ class KRNLAServerError(KRNLAError):
64
+ pass
65
+
66
+
67
+ class KRNLAProtocolError(KRNLAError):
68
+ pass
69
+
70
+
71
+ class KRNLAResponseTooLargeError(KRNLAError):
72
+ pass
73
+
74
+
75
+ class KRNLARequestTimeoutError(KRNLAError):
76
+ pass
77
+
78
+
79
+ class KRNLARequestCancelledError(KRNLAError):
80
+ pass
81
+
82
+
83
+ class KRNLAConnectionError(KRNLAError):
84
+ pass
krnla/py.typed ADDED
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,69 @@
1
+ Metadata-Version: 2.4
2
+ Name: krnla
3
+ Version: 0.1.0
4
+ Summary: First-party Python client for the KRNLA Gateway API v1
5
+ Author: KRNLA
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://krnla.com
8
+ Project-URL: Documentation, https://krnla.com/docs/
9
+ Project-URL: Repository, https://github.com/ZenSched/krnla.git
10
+ Project-URL: Support, https://krnla.com/support/
11
+ Keywords: ai-agents,governance,security,gateway
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Dynamic: license-file
22
+
23
+ # KRNLA Python SDK 0.1.0
24
+
25
+ An unprivileged, standard-library client for KRNLA Gateway API v1.
26
+ Install version 0.1.0 from the official registry after its release:
27
+
28
+ ```sh
29
+ python -m pip install krnla==0.1.0
30
+ ```
31
+
32
+ Configure `KRNLA_API_KEY` in the agent's secret manager and set
33
+ `KRNLA_GATEWAY_URL=https://gateway.krnla.com`. Keep credentials out of source code.
34
+
35
+ ```python
36
+ import os
37
+
38
+ from krnla import KRNLA
39
+
40
+ krnla = KRNLA.connect()
41
+ print(krnla.identity.agent_id)
42
+
43
+ delivery = krnla.send_connection(
44
+ connection=os.environ["KRNLA_CONNECTION_ID"],
45
+ data={"reportId": "synthetic-123"},
46
+ )
47
+ print(delivery.outcome)
48
+
49
+ for message in krnla.poll_inbox():
50
+ process_message(message.content)
51
+ krnla.acknowledge(
52
+ delivery_id=message.delivery_id,
53
+ lease_id=message.lease_id,
54
+ )
55
+ ```
56
+
57
+ The one-call bootstrap validates configuration and verifies identity. It does not
58
+ capture existing arbitrary traffic or claim online presence. Use `send`, `emit`,
59
+ `declare`, and `llm.generate`/`llm.stream` for supported governed operations. No
60
+ decorators or action registration are required. The [developer guide](https://krnla.com/docs/)
61
+ explains outcomes, examples, security boundaries, and deferred capabilities. A configured
62
+ connection ID selects a server-managed route; the agent never receives the destination URL or
63
+ verification secret. New connections use durable inbox delivery by default: a send returns
64
+ `QUEUED`, retrieval leases a message, and `acknowledge` records successful destination
65
+ processing. Delivery is at-least-once.
66
+ If a send times out or loses its connection, read the typed error's `operation_id` and
67
+ call `get_send_status(operation_id=...)`. Replaying the identical send with that
68
+ operation ID returns the original result; changed input is rejected. Reconcile within
69
+ seven days.
@@ -0,0 +1,10 @@
1
+ krnla/__init__.py,sha256=6uyBWc7vXVFqybZMhRzA97yn3Z5zNfgKCsq0a1zEog4,371
2
+ krnla/client.py,sha256=4YtMvfux0XC3MSA7T4rpooG7gAOWT2P4KOOGjE1pHCQ,36826
3
+ krnla/contract.json,sha256=flWK5pQDE57LB0NyDTCsqR_rbzf_yNAOlQ8N89MeB_s,2581
4
+ krnla/errors.py,sha256=zOSWl3Y1gcgI65NYv0tJAVD1yaFeYdZN5ZhJOCYa76c,1303
5
+ krnla/py.typed,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
6
+ krnla-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
7
+ krnla-0.1.0.dist-info/METADATA,sha256=T9pJzQ0S94Wv49leN7d55VjfnMw0Jkfidbo2i-qn3G0,2590
8
+ krnla-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
9
+ krnla-0.1.0.dist-info/top_level.txt,sha256=yd3v9VE4nd1BeB-VhesKUoy42Z9xQLnJIojMjjZXzAw,6
10
+ krnla-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1 @@
1
+ krnla