continuum-task-server-bundle 1.0.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.
Files changed (90) hide show
  1. continuum_task_server_bundle/__init__.py +1 -0
  2. continuum_task_server_bundle/daytona/__init__.py +4 -0
  3. continuum_task_server_bundle/daytona/common.py +534 -0
  4. continuum_task_server_bundle/daytona/create_sandbox.py +166 -0
  5. continuum_task_server_bundle/daytona/dispatch.py +125 -0
  6. continuum_task_server_bundle/daytona/execute_sandbox.py +243 -0
  7. continuum_task_server_bundle/daytona/filesystem.py +330 -0
  8. continuum_task_server_bundle/daytona/fs_edit.py +127 -0
  9. continuum_task_server_bundle/daytona/git_ops.py +585 -0
  10. continuum_task_server_bundle/daytona/github_app.py +207 -0
  11. continuum_task_server_bundle/daytona/manage_sandbox.py +104 -0
  12. continuum_task_server_bundle/daytona/plugin.py +18 -0
  13. continuum_task_server_bundle/daytona/s3_transfer.py +207 -0
  14. continuum_task_server_bundle/discord/__init__.py +4 -0
  15. continuum_task_server_bundle/discord/attachment_registry_db.py +127 -0
  16. continuum_task_server_bundle/discord/attachment_resolve.py +213 -0
  17. continuum_task_server_bundle/discord/await_cleanup.py +105 -0
  18. continuum_task_server_bundle/discord/discord_ready.py +39 -0
  19. continuum_task_server_bundle/discord/message_await_apply.py +143 -0
  20. continuum_task_server_bundle/discord/message_await_db.py +197 -0
  21. continuum_task_server_bundle/discord/message_await_inbound.py +54 -0
  22. continuum_task_server_bundle/discord/message_await_logic.py +133 -0
  23. continuum_task_server_bundle/discord/message_await_poller.py +122 -0
  24. continuum_task_server_bundle/discord/message_chunking.py +45 -0
  25. continuum_task_server_bundle/discord/methods.py +408 -0
  26. continuum_task_server_bundle/discord/plugin.py +105 -0
  27. continuum_task_server_bundle/discord/reaction_await_apply.py +238 -0
  28. continuum_task_server_bundle/discord/reaction_await_db.py +174 -0
  29. continuum_task_server_bundle/discord/reaction_await_inbound.py +47 -0
  30. continuum_task_server_bundle/discord/reaction_await_logic.py +118 -0
  31. continuum_task_server_bundle/discord/reaction_await_poller.py +131 -0
  32. continuum_task_server_bundle/discord/s3_attachment_config.py +25 -0
  33. continuum_task_server_bundle/discord/s3_message_attachments.py +139 -0
  34. continuum_task_server_bundle/discord/sql/001_message_awaits.sql +112 -0
  35. continuum_task_server_bundle/discord/sql/002_reaction_awaits.sql +61 -0
  36. continuum_task_server_bundle/github/__init__.py +4 -0
  37. continuum_task_server_bundle/github/awaits/__init__.py +1 -0
  38. continuum_task_server_bundle/github/awaits/apply.py +92 -0
  39. continuum_task_server_bundle/github/awaits/cleanup.py +94 -0
  40. continuum_task_server_bundle/github/awaits/db.py +220 -0
  41. continuum_task_server_bundle/github/awaits/evaluators.py +325 -0
  42. continuum_task_server_bundle/github/awaits/fetch.py +192 -0
  43. continuum_task_server_bundle/github/awaits/poller.py +82 -0
  44. continuum_task_server_bundle/github/awaits/register.py +37 -0
  45. continuum_task_server_bundle/github/ci_status.py +70 -0
  46. continuum_task_server_bundle/github/comment_normalize.py +76 -0
  47. continuum_task_server_bundle/github/errors.py +52 -0
  48. continuum_task_server_bundle/github/github_app.py +291 -0
  49. continuum_task_server_bundle/github/github_http.py +377 -0
  50. continuum_task_server_bundle/github/methods/__init__.py +90 -0
  51. continuum_task_server_bundle/github/methods/_common.py +183 -0
  52. continuum_task_server_bundle/github/methods/awaits.py +107 -0
  53. continuum_task_server_bundle/github/methods/ci.py +158 -0
  54. continuum_task_server_bundle/github/methods/comments.py +214 -0
  55. continuum_task_server_bundle/github/methods/credentials.py +59 -0
  56. continuum_task_server_bundle/github/methods/issues.py +131 -0
  57. continuum_task_server_bundle/github/methods/pulls.py +329 -0
  58. continuum_task_server_bundle/github/methods/repos.py +424 -0
  59. continuum_task_server_bundle/github/methods/search.py +109 -0
  60. continuum_task_server_bundle/github/plugin.py +91 -0
  61. continuum_task_server_bundle/github/sql/001_github_awaits.sql +65 -0
  62. continuum_task_server_bundle/github/webhook_server.py +126 -0
  63. continuum_task_server_bundle/jira/__init__.py +4 -0
  64. continuum_task_server_bundle/jira/await_poller.py +236 -0
  65. continuum_task_server_bundle/jira/await_store.py +271 -0
  66. continuum_task_server_bundle/jira/config.py +68 -0
  67. continuum_task_server_bundle/jira/jira_client.py +382 -0
  68. continuum_task_server_bundle/jira/methods.py +246 -0
  69. continuum_task_server_bundle/jira/plugin.py +86 -0
  70. continuum_task_server_bundle/jira/sql/001_jira_issue_comment_waits.sql +19 -0
  71. continuum_task_server_bundle/jira/webhook.py +70 -0
  72. continuum_task_server_bundle/openrouter/__init__.py +4 -0
  73. continuum_task_server_bundle/openrouter/chat_service.py +1037 -0
  74. continuum_task_server_bundle/openrouter/chat_store.py +849 -0
  75. continuum_task_server_bundle/openrouter/environment.py +29 -0
  76. continuum_task_server_bundle/openrouter/handler.py +59 -0
  77. continuum_task_server_bundle/openrouter/image_context.py +207 -0
  78. continuum_task_server_bundle/openrouter/openrouter_client.py +324 -0
  79. continuum_task_server_bundle/openrouter/plugin.py +37 -0
  80. continuum_task_server_bundle/openrouter/prompt_projection.py +417 -0
  81. continuum_task_server_bundle/openrouter/sql/chat.sql +50 -0
  82. continuum_task_server_bundle/openrouter/sql/migrate_prune_then_chunk_v1.sql +11 -0
  83. continuum_task_server_bundle/roblox/__init__.py +4 -0
  84. continuum_task_server_bundle/roblox/open_cloud.py +335 -0
  85. continuum_task_server_bundle/roblox/plugin.py +30 -0
  86. continuum_task_server_bundle/roblox/storage_s3.py +55 -0
  87. continuum_task_server_bundle-1.0.0.dist-info/METADATA +109 -0
  88. continuum_task_server_bundle-1.0.0.dist-info/RECORD +90 -0
  89. continuum_task_server_bundle-1.0.0.dist-info/WHEEL +5 -0
  90. continuum_task_server_bundle-1.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,29 @@
1
+ """Per-invocation environment namespace for OpenRouter plugin configuration.
2
+
3
+ The host selects a prefix while starting the service or executing a handler.
4
+ A ContextVar keeps concurrent workers independent without mutating os.environ.
5
+ """
6
+
7
+ from contextlib import contextmanager
8
+ from contextvars import ContextVar
9
+ import os
10
+
11
+
12
+ _prefix = ContextVar("openrouter_environment_prefix", default="")
13
+
14
+
15
+ def current_prefix():
16
+ return _prefix.get()
17
+
18
+
19
+ def getenv(name, default=None):
20
+ return os.getenv(current_prefix() + name, default)
21
+
22
+
23
+ @contextmanager
24
+ def use_prefix(prefix):
25
+ token = _prefix.set(prefix)
26
+ try:
27
+ yield
28
+ finally:
29
+ _prefix.reset(token)
@@ -0,0 +1,59 @@
1
+ from .chat_service import DATABASE_UNAVAILABLE
2
+ from .environment import current_prefix
3
+ from .image_context import prepare_image
4
+ from .openrouter_client import run_completion
5
+
6
+ COMPLETION = "completion"
7
+ CREATE = "create"
8
+ SEND = "send"
9
+ TRANSCRIPT = "transcript"
10
+ PREPARE_IMAGE = "prepare_image"
11
+ METHODS = {COMPLETION, CREATE, SEND, TRANSCRIPT, PREPARE_IMAGE}
12
+
13
+
14
+ def resolve_method(definition):
15
+ method = definition.get("method")
16
+ if method is None:
17
+ return COMPLETION, None
18
+ if not isinstance(method, str):
19
+ return None, {"error": "Unknown method"}
20
+ stripped = method.strip()
21
+ if not stripped:
22
+ return COMPLETION, None
23
+ if stripped not in METHODS:
24
+ return None, {"error": "Unknown method"}
25
+ return stripped, None
26
+
27
+
28
+ def handle_openrouter(definition, data, chats, *, complete=run_completion):
29
+ method, err = resolve_method(definition)
30
+ if err:
31
+ return err
32
+ if method in {COMPLETION, SEND}:
33
+ model_override = data.get("model")
34
+ if model_override is not None:
35
+ if not isinstance(model_override, str) or not model_override.strip():
36
+ return {"error": "model must be a non-empty string"}
37
+ # Item definition remains the default; an enqueue override applies only
38
+ # to this invocation and never changes the persisted task-item version.
39
+ definition = {**definition, "model": model_override.strip()}
40
+ reasoning_override = data.get("reasoning")
41
+ if reasoning_override is not None:
42
+ if not isinstance(reasoning_override, dict):
43
+ return {"error": "reasoning must be an object"}
44
+ # Like the model override, this replaces the definition value only for
45
+ # the current invocation and is never persisted on a stored chat.
46
+ definition = {**definition, "reasoning": reasoning_override}
47
+ if method == PREPARE_IMAGE:
48
+ return prepare_image(data)
49
+ if method == COMPLETION:
50
+ return complete(definition, data)
51
+ if chats is None:
52
+ return {"error": current_prefix() + DATABASE_UNAVAILABLE}
53
+ if method == CREATE:
54
+ return chats.create(data, definition=definition)
55
+ if method == SEND:
56
+ return chats.send(definition, data)
57
+ if method == TRANSCRIPT:
58
+ return chats.transcript(data)
59
+ return {"error": "Unknown method"}
@@ -0,0 +1,207 @@
1
+ """Bounded S3 image references for OpenRouter chat context.
2
+
3
+ Image bytes never leave this process except in the outgoing OpenRouter request.
4
+ References are validated again on every send so a mutable S3 key cannot silently
5
+ change an image already seen by the model.
6
+ """
7
+ import base64
8
+ import hashlib
9
+ import math
10
+ from io import BytesIO
11
+ from urllib.parse import urlsplit
12
+
13
+ import boto3
14
+ from botocore.config import Config
15
+ from PIL import Image, UnidentifiedImageError
16
+
17
+ from .environment import current_prefix, getenv
18
+
19
+
20
+ class ImageError(Exception):
21
+ pass
22
+
23
+
24
+ def _positive(name, default):
25
+ try:
26
+ value = int(getenv(name, str(default)))
27
+ except ValueError:
28
+ raise ImageError(f"Invalid {name}") from None
29
+ if value < 1:
30
+ raise ImageError(f"Invalid {name}")
31
+ return value
32
+
33
+
34
+ def _location(uri):
35
+ bucket = getenv("IMAGE_S3_BUCKET", "").strip()
36
+ prefix = getenv("IMAGE_S3_PREFIX", "").strip().strip("/")
37
+ if not bucket or not prefix:
38
+ raise ImageError("Image storage is not configured")
39
+ if not isinstance(uri, str) or len(uri) > 2048:
40
+ raise ImageError("Invalid image S3 URI")
41
+ try:
42
+ parsed = urlsplit(uri)
43
+ except ValueError:
44
+ raise ImageError("Invalid image S3 URI") from None
45
+ key = parsed.path.lstrip("/")
46
+ if (parsed.scheme != "s3" or parsed.netloc != bucket or parsed.query or parsed.fragment
47
+ or not key.startswith(prefix + "/") or any(p in (".", "..", "") for p in key.split("/"))):
48
+ raise ImageError("Image S3 URI is outside the configured location")
49
+ return bucket, key
50
+
51
+
52
+ def _s3_client():
53
+ config = Config(connect_timeout=5, read_timeout=15, retries={"max_attempts": 2})
54
+ if not current_prefix():
55
+ # Preserve the complete boto3 credential/config chain in standalone mode.
56
+ return boto3.client("s3", config=config)
57
+
58
+ access = getenv("AWS_ACCESS_KEY_ID")
59
+ secret = getenv("AWS_SECRET_ACCESS_KEY")
60
+ token = getenv("AWS_SESSION_TOKEN")
61
+ if bool(access) != bool(secret) or (token and not access):
62
+ raise ImageError("Incomplete image AWS credentials")
63
+ kwargs = {"config": config}
64
+ if access:
65
+ kwargs.update(aws_access_key_id=access, aws_secret_access_key=secret)
66
+ if token:
67
+ kwargs["aws_session_token"] = token
68
+ region = getenv("AWS_REGION") or getenv("AWS_DEFAULT_REGION")
69
+ if region:
70
+ kwargs["region_name"] = region
71
+ # Without explicit prefixed credentials boto3 uses its normal host chain.
72
+ return boto3.client("s3", **kwargs)
73
+
74
+
75
+ def _read(uri, version_id=None, *, client=None):
76
+ bucket, key = _location(uri)
77
+ max_bytes = _positive("IMAGE_MAX_BYTES", 5 * 1024 * 1024)
78
+ try:
79
+ s3 = client or _s3_client()
80
+ args = {"Bucket": bucket, "Key": key}
81
+ if version_id:
82
+ args["VersionId"] = version_id
83
+ response = s3.get_object(**args)
84
+ body = response["Body"]
85
+ try:
86
+ size = response.get("ContentLength")
87
+ if size is not None and size > max_bytes:
88
+ raise ImageError("Image exceeds the byte limit")
89
+ data = body.read(max_bytes + 1)
90
+ finally:
91
+ body.close()
92
+ except ImageError:
93
+ raise
94
+ except Exception:
95
+ raise ImageError("Could not read image from S3") from None
96
+ if not data or len(data) > max_bytes:
97
+ raise ImageError("Image is empty or exceeds the byte limit")
98
+ try:
99
+ with Image.open(BytesIO(data)) as image:
100
+ width, height = image.size
101
+ media = {"PNG": "image/png", "JPEG": "image/jpeg", "WEBP": "image/webp", "GIF": "image/gif"}.get(image.format)
102
+ if not media:
103
+ raise ImageError("Unsupported image format")
104
+ max_dimension = _positive("IMAGE_MAX_DIMENSION", 4096)
105
+ max_pixels = _positive("IMAGE_MAX_PIXELS", 16_777_216)
106
+ if width < 1 or height < 1 or width > max_dimension or height > max_dimension or width * height > max_pixels:
107
+ raise ImageError("Image exceeds the dimension limit")
108
+ image.verify()
109
+ except ImageError:
110
+ raise
111
+ except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError):
112
+ raise ImageError("Invalid image") from None
113
+ ref = {"type": "s3_image", "s3_uri": uri, "sha256": hashlib.sha256(data).hexdigest(),
114
+ "width": width, "height": height, "media_type": media}
115
+ version = response.get("VersionId")
116
+ if version and version != "null":
117
+ ref["version_id"] = version
118
+ return ref, data
119
+
120
+
121
+ def prepare_image(data, *, client=None):
122
+ if not isinstance(data, dict) or set(data) != {"s3_uri"}:
123
+ return {"error": "Provide only s3_uri", "error_code": "image_error"}
124
+ try:
125
+ ref, _ = _read(data["s3_uri"], client=client)
126
+ return {"success": True, "image": ref}
127
+ except ImageError as exc:
128
+ return {"error": str(exc), "error_code": "image_error"}
129
+
130
+
131
+ def normalize_messages(messages, *, client=None):
132
+ """Validate small image references and retain bytes only for this model send."""
133
+ result, images, warnings = [], {}, []
134
+ count = 0
135
+ maximum = _positive("IMAGE_MAX_COUNT", 8)
136
+ total = sum(len(m.get("continuum_images", [])) for m in messages if isinstance(m.get("continuum_images"), list))
137
+ skip_oldest = max(0, total - maximum)
138
+ for message in messages:
139
+ updated = dict(message)
140
+ refs = updated.pop("continuum_images", None)
141
+ if refs is None:
142
+ result.append(updated)
143
+ continue
144
+ if message.get("role") != "user" or not isinstance(refs, list):
145
+ raise ImageError("Image references require a user message and an array")
146
+ accepted = []
147
+ for part in refs:
148
+ count += 1
149
+ if count <= skip_oldest:
150
+ warnings.append("Too many images in context")
151
+ updated["content"] = str(updated.get("content") or "") + "\n[An older image was omitted: image count limit reached.]"
152
+ continue
153
+ try:
154
+ if not isinstance(part, dict) or part.get("type") != "s3_image":
155
+ raise ImageError("Invalid image reference")
156
+ ref, data = _read(part.get("s3_uri"), part.get("version_id"), client=client)
157
+ if any(part.get(k) != ref.get(k) for k in ("sha256", "width", "height", "media_type", "version_id")):
158
+ raise ImageError("Image changed or its reference is invalid")
159
+ key = (ref["s3_uri"], ref["sha256"], ref.get("version_id"))
160
+ images[key] = data
161
+ accepted.append(ref)
162
+ except ImageError as exc:
163
+ warnings.append(str(exc))
164
+ # Never put a rejected URL or underlying exception in the prompt.
165
+ content = updated.get("content")
166
+ if not isinstance(content, str):
167
+ raise ImageError("Image context must have text content")
168
+ updated["content"] = content + "\n[Image unavailable: " + str(exc) + ". Do not assume you saw it.]"
169
+ if accepted:
170
+ updated["continuum_images"] = accepted
171
+ result.append(updated)
172
+ return result, images, warnings
173
+
174
+
175
+ def materialize_messages(messages, images):
176
+ result = []
177
+ for message in messages:
178
+ updated = dict(message)
179
+ refs = updated.pop("continuum_images", None)
180
+ if refs:
181
+ text = updated.get("content")
182
+ if not isinstance(text, str):
183
+ raise ImageError("Image context must have text content")
184
+ parts = [{"type": "text", "text": text}]
185
+ for part in refs:
186
+ key = (part["s3_uri"], part["sha256"], part.get("version_id"))
187
+ data = images[key]
188
+ url = "data:" + part["media_type"] + ";base64," + base64.b64encode(data).decode("ascii")
189
+ parts.append({"type": "image_url", "image_url": {"url": url}})
190
+ updated["content"] = parts
191
+ result.append(updated)
192
+ return result
193
+
194
+
195
+ def image_token_estimate(messages):
196
+ """Conservative configurable reservation, not a provider's actual token count."""
197
+ base = _positive("IMAGE_TOKEN_BASE", 1024)
198
+ tile = _positive("IMAGE_TOKEN_PER_512_TILE", 1024)
199
+ total = 0
200
+ for message in messages:
201
+ for part in message.get("continuum_images", []):
202
+ if isinstance(part, dict) and part.get("type") == "s3_image":
203
+ width, height = part.get("width"), part.get("height")
204
+ if not isinstance(width, int) or not isinstance(height, int) or width <= 0 or height <= 0:
205
+ raise ImageError("Invalid image dimensions")
206
+ total += base + math.ceil(width / 512) * math.ceil(height / 512) * tile
207
+ return total
@@ -0,0 +1,324 @@
1
+ from json import JSONDecodeError
2
+
3
+ import httpx
4
+
5
+ from .environment import current_prefix, getenv
6
+ from .image_context import ImageError, materialize_messages, normalize_messages
7
+
8
+ OPENROUTER_CHAT_COMPLETIONS_URL = "https://openrouter.ai/api/v1/chat/completions"
9
+ OPENROUTER_TIMEOUT = httpx.Timeout(300.0, connect=30.0)
10
+
11
+ ENCRYPTED_REASONING_TYPE = "reasoning.encrypted"
12
+
13
+
14
+ def system_message_if_present(text):
15
+ if text is None:
16
+ return None
17
+ stripped = str(text).strip()
18
+ if not stripped:
19
+ return None
20
+ return {"role": "system", "content": stripped}
21
+
22
+
23
+ def leading_system_messages(definition, data):
24
+ messages = []
25
+ for text in (definition.get("system_prompt"), data.get("system_prompt")):
26
+ sys_msg = system_message_if_present(text)
27
+ if sys_msg:
28
+ messages.append(sys_msg)
29
+ return messages
30
+
31
+
32
+ def message_error(message, label):
33
+ if not isinstance(message, dict):
34
+ return {"error": f"{label} must be an object"}
35
+ role = message.get("role")
36
+ if not isinstance(role, str) or not role.strip():
37
+ return {"error": f"{label} must include a non-empty string role"}
38
+ return None
39
+
40
+
41
+ def messages_from_input(definition, data):
42
+ """Return (messages, None) or (None, error_dict).
43
+
44
+ If ``messages`` is a non-empty array, it is sent as-is (full transcript for
45
+ agent loops). Otherwise ``prompt`` is required and messages are built from
46
+ version/item system prompts plus one user turn.
47
+ """
48
+ raw = data.get("messages")
49
+ if raw is not None:
50
+ if not isinstance(raw, list):
51
+ return None, {"error": "messages must be an array"}
52
+ if len(raw) > 0:
53
+ out = []
54
+ for i, message in enumerate(raw):
55
+ err = message_error(message, f"messages[{i}]")
56
+ if err:
57
+ return None, err
58
+ out.append(message)
59
+ return out, None
60
+
61
+ prompt = data.get("prompt")
62
+ if not prompt:
63
+ return None, {"error": "No prompt provided"}
64
+
65
+ messages = leading_system_messages(definition, data)
66
+ messages.append({"role": "user", "content": prompt})
67
+ return messages, None
68
+
69
+
70
+ def model_and_reasoning(definition):
71
+ model = definition.get("model")
72
+ if not model:
73
+ return None, None, {"error": "No model provided"}
74
+ reasoning = definition.get("reasoning")
75
+ if reasoning is not None and not isinstance(reasoning, dict):
76
+ return None, None, {"error": "reasoning must be an object"}
77
+ return model, reasoning, None
78
+
79
+
80
+ def chat_payload(model, messages, reasoning, tools, tool_choice):
81
+ payload = {
82
+ "model": model,
83
+ # Retention is an internal stored-chat hint, never an OpenRouter field.
84
+ "messages": [{k: v for k, v in message.items() if k not in ('continuum_retention', 'continuum_compact_content', 'continuum_raw_tool_result')}
85
+ if any(k in message for k in ('continuum_retention', 'continuum_compact_content', 'continuum_raw_tool_result')) else message for message in messages],
86
+ }
87
+ if reasoning is not None:
88
+ payload["reasoning"] = reasoning
89
+ if tools:
90
+ payload["tools"] = tools
91
+ if tool_choice is not None:
92
+ payload["tool_choice"] = tool_choice
93
+ return payload
94
+
95
+
96
+ def openrouter_error_message(status_code, body):
97
+ if isinstance(body, dict):
98
+ err = body.get("error")
99
+ if isinstance(err, dict):
100
+ msg = err.get("message")
101
+ if msg:
102
+ return str(msg)
103
+ if err:
104
+ return str(err)
105
+ if body.get("message"):
106
+ return str(body["message"])
107
+ if isinstance(body, str) and body.strip():
108
+ return body.strip()[:500]
109
+ return f"OpenRouter HTTP {status_code}"
110
+
111
+
112
+ def chat_completions(payload):
113
+ """POST /api/v1/chat/completions with the payload JSON as-is.
114
+
115
+ The official OpenRouter Python SDK's ChatRequestReasoning model only
116
+ serializes ``effort`` and ``summary``, so ``enabled`` / ``exclude`` /
117
+ ``max_tokens`` were being dropped before they reached OpenRouter.
118
+ """
119
+ api_key = getenv("OPENROUTER_API_KEY")
120
+ if not api_key:
121
+ return None, {"error": f"{current_prefix()}OPENROUTER_API_KEY is not set"}
122
+
123
+ with httpx.Client(timeout=OPENROUTER_TIMEOUT) as client:
124
+ response = client.post(
125
+ OPENROUTER_CHAT_COMPLETIONS_URL,
126
+ headers={
127
+ "Authorization": f"Bearer {api_key}",
128
+ "Content-Type": "application/json",
129
+ },
130
+ json=payload,
131
+ )
132
+
133
+ try:
134
+ body = response.json()
135
+ except JSONDecodeError:
136
+ return None, {
137
+ "error": openrouter_error_message(response.status_code, response.text),
138
+ }
139
+
140
+ if response.status_code >= 400:
141
+ return None, {"error": openrouter_error_message(response.status_code, body)}
142
+ if not isinstance(body, dict):
143
+ return None, {"error": "OpenRouter returned a non-object response"}
144
+ return body, None
145
+
146
+
147
+ def tool_calls_payload(message):
148
+ raw = message.get("tool_calls") or []
149
+ out = []
150
+ for tc in raw:
151
+ if not isinstance(tc, dict):
152
+ continue
153
+ fn = tc.get("function") or {}
154
+ if not isinstance(fn, dict):
155
+ fn = {}
156
+ out.append(
157
+ {
158
+ "id": tc.get("id"),
159
+ "type": tc.get("type"),
160
+ "function": {
161
+ "name": fn.get("name"),
162
+ "arguments": fn.get("arguments"),
163
+ },
164
+ }
165
+ )
166
+ return out
167
+
168
+
169
+ def public_reasoning_details(details):
170
+ """Drop encrypted reasoning blobs. Return None when nothing remains."""
171
+ if not isinstance(details, list):
172
+ return details or None
173
+ kept = []
174
+ for detail in details:
175
+ if isinstance(detail, dict) and detail.get("type") == ENCRYPTED_REASONING_TYPE:
176
+ continue
177
+ kept.append(detail)
178
+ return kept or None
179
+
180
+
181
+ def reasoning_fields(message, *, strip_encrypted=False):
182
+ out = {}
183
+ reasoning = message.get("reasoning")
184
+ details = message.get("reasoning_details")
185
+ if strip_encrypted:
186
+ details = public_reasoning_details(details)
187
+ if reasoning is not None:
188
+ out["reasoning"] = reasoning
189
+ if details:
190
+ out["reasoning_details"] = details
191
+ return out
192
+
193
+
194
+ def public_message(body):
195
+ """Copy of a stored message with encrypted reasoning removed."""
196
+ out = dict(body)
197
+ if "reasoning_details" not in out:
198
+ return out
199
+ kept = public_reasoning_details(out.get("reasoning_details"))
200
+ if kept:
201
+ out["reasoning_details"] = kept
202
+ else:
203
+ del out["reasoning_details"]
204
+ return out
205
+
206
+
207
+ def _usage_number(value):
208
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
209
+ return None
210
+ return value
211
+
212
+
213
+ def usage_from_response(response):
214
+ """OpenRouter's native token count and the credits charged for this call."""
215
+ if not isinstance(response, dict):
216
+ return None
217
+ usage = response.get("usage")
218
+ if not isinstance(usage, dict):
219
+ return None
220
+ out = {}
221
+ for key in ("prompt_tokens", "completion_tokens", "cost"):
222
+ number = _usage_number(usage.get(key))
223
+ if number is not None:
224
+ out[key] = number
225
+ details = usage.get("prompt_tokens_details")
226
+ if isinstance(details, dict):
227
+ cached = _usage_number(details.get("cached_tokens"))
228
+ if cached is not None:
229
+ out["cached_tokens"] = cached
230
+ return out or None
231
+
232
+
233
+ def parse_chat_response(response):
234
+ choices = response.get("choices") or []
235
+ if not choices:
236
+ return None, {"error": "OpenRouter returned no choices"}
237
+ choice = choices[0]
238
+ if not isinstance(choice, dict):
239
+ return None, {"error": "OpenRouter returned an invalid choice"}
240
+ message = choice.get("message") or {}
241
+ if not isinstance(message, dict):
242
+ message = {}
243
+ return {
244
+ "message": message,
245
+ "model": response.get("model"),
246
+ "finish_reason": choice.get("finish_reason"),
247
+ "usage": usage_from_response(response),
248
+ }, None
249
+
250
+
251
+ def stored_assistant_body(message):
252
+ body = dict(message)
253
+ role = body.get("role")
254
+ if not isinstance(role, str) or not role.strip():
255
+ body["role"] = "assistant"
256
+ return body
257
+
258
+
259
+ def task_result(message, *, model, finish_reason, strip_encrypted=False, cursor=None):
260
+ content = message.get("content")
261
+ base = {
262
+ "model": model,
263
+ "finish_reason": finish_reason,
264
+ **reasoning_fields(message, strip_encrypted=strip_encrypted),
265
+ }
266
+ tool_calls = tool_calls_payload(message)
267
+ if tool_calls:
268
+ result = {
269
+ "response_type": "tool",
270
+ "tool_calls": tool_calls,
271
+ "content": content,
272
+ **base,
273
+ }
274
+ else:
275
+ result = {
276
+ "response_type": "chat",
277
+ "content": content,
278
+ **base,
279
+ }
280
+ if cursor is not None:
281
+ return {"cursor": cursor, **result}
282
+ return result
283
+
284
+
285
+ def run_completion(definition, data, *, chat_completions=chat_completions):
286
+ model, reasoning, err = model_and_reasoning(definition)
287
+ if err:
288
+ return err
289
+
290
+ messages, err = messages_from_input(definition, data)
291
+ if err:
292
+ return err
293
+
294
+ if any("continuum_images" in m for m in messages):
295
+ try:
296
+ messages, images, _warnings = normalize_messages(messages)
297
+ messages = materialize_messages(messages, images)
298
+ except ImageError as exc:
299
+ return {"error": str(exc), "error_code": "image_error"}
300
+
301
+ payload = chat_payload(
302
+ model,
303
+ messages,
304
+ reasoning,
305
+ data.get("tools"),
306
+ data.get("tool_choice"),
307
+ )
308
+ response, err = chat_completions(payload)
309
+ if err:
310
+ if "data:image/" in str(err).lower():
311
+ return {"error": "Image model request failed"}
312
+ return err
313
+
314
+ parsed, err = parse_chat_response(response)
315
+ if err:
316
+ return err
317
+ result = task_result(
318
+ parsed["message"],
319
+ model=parsed["model"],
320
+ finish_reason=parsed["finish_reason"],
321
+ )
322
+ if parsed.get("usage"):
323
+ result["usage"] = parsed["usage"]
324
+ return result
@@ -0,0 +1,37 @@
1
+ """Register the OpenRouter task and its stored-chat lifecycle."""
2
+
3
+ from .chat_service import build_chat_service
4
+ from .handler import handle_openrouter
5
+ from .environment import use_prefix
6
+
7
+
8
+ class _OpenRouterService:
9
+ def __init__(self, env_prefix):
10
+ self.env_prefix = env_prefix
11
+ self.chats = None
12
+
13
+ def start(self):
14
+ with use_prefix(self.env_prefix):
15
+ self.chats = build_chat_service()
16
+
17
+ def stop(self):
18
+ if self.chats is not None:
19
+ self.chats.close()
20
+ self.chats = None
21
+
22
+
23
+ def register_openrouter(host, *, concurrency=4, env_prefix=""):
24
+ """Register OpenRouter before host.run(), optionally namespacing its settings."""
25
+ if not isinstance(env_prefix, str):
26
+ raise TypeError("env_prefix must be a string")
27
+ service = _OpenRouterService(env_prefix)
28
+ server = host.server
29
+
30
+ def openrouter(item):
31
+ version = server.client.task_items.versions.get_by_id(item.task_item_version_id)
32
+ definition = version.item_definition_json or {}
33
+ with use_prefix(env_prefix):
34
+ return handle_openrouter(definition, item.input_data_json or {}, service.chats)
35
+
36
+ server.register("openrouter", openrouter, concurrency=concurrency)
37
+ host.add_service("openrouter", service)