viasocket 0.2.0__tar.gz → 0.3.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: viasocket
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: viaSocket for Python agents: the 2,300+ apps each of your users connected (Slack, Google Sheets, HubSpot, Notion...) as tools for LangChain, CrewAI and LlamaIndex.
5
5
  Project-URL: Homepage, https://github.com/Walkover-Web-Solution/viasocket-apps/tree/main/python#readme
6
6
  Project-URL: Source, https://github.com/Walkover-Web-Solution/viasocket-apps
@@ -134,18 +134,46 @@ Each tool hands the model the action's JSON Schema as its declaration and runs t
134
134
  an app they have not connected answers the model "Slack is not connected for this user", so the agent
135
135
  can ask them to; it starts working on the next call after they do.
136
136
  - **Pick the actions.** An app left out of `actions` gives every published action as a tool — fine for a
137
- small app, too many for a large one (Notion has 57). Actions are named by `action_id` or by their path
138
- on the app's page (`send-message`).
137
+ small app, too many for a large one (Notion has 57). Actions are named by their key (`Send_Message`,
138
+ any case), by `action_id`, or by their path on the app's page (`send-message`).
139
139
  - **Tool names** are `<app>_<action>` (`slack_send-message`); the input schema is built from the action's
140
140
  form, so the model sees the same fields, choices and help text a person would.
141
141
  - **Fields that hold an id** (a channel, a spreadsheet) come from the user's own account. Each app with
142
- such a field also gets a `<app>_list-options` tool, which lists the real values on the user's connection.
142
+ such a field also gets a `<app>_list-options` tool, which lists the real values on the user's connection,
143
+ narrows a long list with `search` and pages it with `paginate` when it answers `"more": true`.
143
144
  - An error from the app comes back to the model as text, not as an exception, so one bad call does not
144
145
  end the run.
145
146
 
146
147
  The same tools without a framework — a name, a description, a JSON Schema and `invoke` — are
147
148
  `viasocket.agent_tools(viasocket, user, apps, actions)`.
148
149
 
150
+ ## Calls without a framework
151
+
152
+ The client underneath names things the way the catalog does: the app by its slug, an action or trigger by
153
+ its key, a version by its number. `user` is the unique identifier the user connected their apps under.
154
+
155
+ ```python
156
+ listing = viasocket.list_actions("user_123", "slack") # {"app", "service_id", "actions": [{"key", "name", "version", ...}]}
157
+
158
+ # Once per user and app: the flow that runs its actions on their connection.
159
+ script_id = viasocket.find_enabled("user_123", "slack")
160
+ if not script_id:
161
+ script_id = viasocket.enable("user_123", "slack", auth_id="auth8f3a9c2d")["script_id"]
162
+
163
+ # Run an action by key; pin a version when your code fills the input.
164
+ viasocket.run_action(script_id, "Send_Message", {"text": "hi", "channel": "C1"}, version="v3")
165
+
166
+ # The values a field accepts, with search and paging.
167
+ page = viasocket.field_options("user_123", "slack", "Send_Message", "channel", "auth8f3a9c2d", search="gen")
168
+ while page["has_more"]:
169
+ page = viasocket.field_options("user_123", "slack", "Send_Message", "channel", "auth8f3a9c2d", search="gen", paginate=page["paginate"])
170
+
171
+ # Your webhook (or `code=` JavaScript) on every event of a trigger.
172
+ viasocket.subscribe("user_123", "slack", "New_Message", auth_id="auth8f3a9c2d", webhook="https://example.com/hooks/slack")
173
+ ```
174
+
175
+ The `script_id` is the credential for `run_action` and `run_code`: keep it on your server.
176
+
149
177
  ## License
150
178
 
151
179
  MIT
@@ -111,18 +111,46 @@ Each tool hands the model the action's JSON Schema as its declaration and runs t
111
111
  an app they have not connected answers the model "Slack is not connected for this user", so the agent
112
112
  can ask them to; it starts working on the next call after they do.
113
113
  - **Pick the actions.** An app left out of `actions` gives every published action as a tool — fine for a
114
- small app, too many for a large one (Notion has 57). Actions are named by `action_id` or by their path
115
- on the app's page (`send-message`).
114
+ small app, too many for a large one (Notion has 57). Actions are named by their key (`Send_Message`,
115
+ any case), by `action_id`, or by their path on the app's page (`send-message`).
116
116
  - **Tool names** are `<app>_<action>` (`slack_send-message`); the input schema is built from the action's
117
117
  form, so the model sees the same fields, choices and help text a person would.
118
118
  - **Fields that hold an id** (a channel, a spreadsheet) come from the user's own account. Each app with
119
- such a field also gets a `<app>_list-options` tool, which lists the real values on the user's connection.
119
+ such a field also gets a `<app>_list-options` tool, which lists the real values on the user's connection,
120
+ narrows a long list with `search` and pages it with `paginate` when it answers `"more": true`.
120
121
  - An error from the app comes back to the model as text, not as an exception, so one bad call does not
121
122
  end the run.
122
123
 
123
124
  The same tools without a framework — a name, a description, a JSON Schema and `invoke` — are
124
125
  `viasocket.agent_tools(viasocket, user, apps, actions)`.
125
126
 
127
+ ## Calls without a framework
128
+
129
+ The client underneath names things the way the catalog does: the app by its slug, an action or trigger by
130
+ its key, a version by its number. `user` is the unique identifier the user connected their apps under.
131
+
132
+ ```python
133
+ listing = viasocket.list_actions("user_123", "slack") # {"app", "service_id", "actions": [{"key", "name", "version", ...}]}
134
+
135
+ # Once per user and app: the flow that runs its actions on their connection.
136
+ script_id = viasocket.find_enabled("user_123", "slack")
137
+ if not script_id:
138
+ script_id = viasocket.enable("user_123", "slack", auth_id="auth8f3a9c2d")["script_id"]
139
+
140
+ # Run an action by key; pin a version when your code fills the input.
141
+ viasocket.run_action(script_id, "Send_Message", {"text": "hi", "channel": "C1"}, version="v3")
142
+
143
+ # The values a field accepts, with search and paging.
144
+ page = viasocket.field_options("user_123", "slack", "Send_Message", "channel", "auth8f3a9c2d", search="gen")
145
+ while page["has_more"]:
146
+ page = viasocket.field_options("user_123", "slack", "Send_Message", "channel", "auth8f3a9c2d", search="gen", paginate=page["paginate"])
147
+
148
+ # Your webhook (or `code=` JavaScript) on every event of a trigger.
149
+ viasocket.subscribe("user_123", "slack", "New_Message", auth_id="auth8f3a9c2d", webhook="https://example.com/hooks/slack")
150
+ ```
151
+
152
+ The `script_id` is the credential for `run_action` and `run_code`: keep it on your server.
153
+
126
154
  ## License
127
155
 
128
156
  MIT
@@ -12,4 +12,4 @@ from ._agent_tools import AgentTool, action_input_schema, agent_tools
12
12
  from ._client import ViaSocket, ViaSocketError, sign_embed_token
13
13
 
14
14
  __all__ = ["ViaSocket", "ViaSocketError", "sign_embed_token", "AgentTool", "agent_tools", "action_input_schema"]
15
- __version__ = "0.2.0"
15
+ __version__ = "0.3.0"
@@ -124,11 +124,38 @@ def _clip(text: str) -> str:
124
124
  return f"{text[:MAX_RESULT]}… (truncated)" if len(text) > MAX_RESULT else text
125
125
 
126
126
 
127
+ def _published_actions(viasocket: ViaSocket, user: str, slug: str) -> "tuple[str, str, List[dict]]":
128
+ """
129
+ The app's actions with everything a tool needs: the key and version id from viaSocket's own
130
+ listing, the name, description and `input_schema` from the public catalog, joined by `action_id`.
131
+ """
132
+ listing = viasocket.list_actions(user, slug)
133
+ service_id = listing["service_id"]
134
+ app = viasocket.versions(service_id) if service_id else None
135
+ if not app:
136
+ raise ViaSocketError(f'agent_tools: "{slug}" has nothing published')
137
+ listed = {entry.get("action_id"): entry for entry in listing["actions"] if entry.get("type") != "trigger"}
138
+ merged = []
139
+ for action in app["actions"]:
140
+ entry = listed.get(action.get("action_id")) or {}
141
+ merged.append({**action, "key": entry.get("key"), "action_version_id": entry.get("action_version_id") or action.get("action_version_id")})
142
+ return service_id, app["service"]["name"], merged
143
+
144
+
145
+ def _matches(action: dict, event: str) -> bool:
146
+ """An action is named by its key (`Send_Message`, any case), its `action_id`, or its path (`send-message`)."""
147
+ return (
148
+ (action.get("key") or "").lower() == event.lower()
149
+ or action.get("action_id") == event
150
+ or _event_path(action.get("name", "")) == event
151
+ )
152
+
153
+
127
154
  def agent_tools(viasocket: ViaSocket, user: str, apps: List[str], actions: Optional[Dict[str, List[str]]] = None) -> List[AgentTool]:
128
155
  """
129
156
  One tool per chosen action of each app, for one end user (`user`, the unique identifier their
130
157
  connections were made under). An app left out of `actions` gets every published action. Reads the
131
- public catalog only; the user's connection is looked up when a tool first runs.
158
+ catalog only; the user's connection is looked up when a tool first runs.
132
159
  """
133
160
  taken: set = set()
134
161
 
@@ -142,21 +169,17 @@ def agent_tools(viasocket: ViaSocket, user: str, apps: List[str], actions: Optio
142
169
 
143
170
  tools: List[AgentTool] = []
144
171
  for slug in apps or []:
145
- service_id = viasocket.service_id_for(slug)
146
- app = viasocket.versions(service_id)
147
- if not app:
148
- raise ViaSocketError(f'agent_tools: "{slug}" has nothing published')
149
- app_name = app["service"]["name"]
172
+ service_id, app_name, published = _published_actions(viasocket, user, slug)
150
173
  wanted = (actions or {}).get(slug)
151
174
  if wanted:
152
175
  chosen = []
153
176
  for event in wanted:
154
- match = next((a for a in app["actions"] if a.get("action_id") == event or _event_path(a.get("name", "")) == event), None)
177
+ match = next((a for a in published if _matches(a, event)), None)
155
178
  if not match:
156
179
  raise ViaSocketError(f'agent_tools: {app_name} has no published action "{event}"')
157
180
  chosen.append(match)
158
181
  else:
159
- chosen = app["actions"]
182
+ chosen = published
160
183
  tools.extend(_app_tools(viasocket, user, slug, service_id, app_name, chosen, unique_name, taken))
161
184
  return tools
162
185
 
@@ -224,12 +247,25 @@ def _app_tools(viasocket, user, slug, service_id, app_name, chosen, unique_name,
224
247
  if not flow:
225
248
  return not_connected
226
249
  chosen_so_far = input.get("chosen") if isinstance(input.get("chosen"), dict) else {}
227
- existing = {**chosen_so_far, "_searchText": str(input["search"])} if input.get("search") else chosen_so_far
228
- result = viasocket.list_options(user, action["action_version_id"], str(input.get("field", "")), flow["auth_id"], existing)
250
+ search = str(input["search"]) if input.get("search") else None
251
+ field = str(input.get("field", ""))
252
+ if action.get("key"):
253
+ result = viasocket.field_options(
254
+ user, slug, action["key"], field, flow["auth_id"], existing_fields=chosen_so_far, search=search, paginate=input.get("paginate")
255
+ )
256
+ more, next_page, note = result["has_more"], result["paginate"], result["message"]
257
+ else:
258
+ # An action viaSocket's listing does not name: the older route, which searches through a field.
259
+ existing = {**chosen_so_far, "_searchText": search} if search else chosen_so_far
260
+ result = viasocket.list_options(user, action["action_version_id"], field, flow["auth_id"], existing)
261
+ more, next_page, note = bool(result["offset"]), None, None
229
262
  if not result["options"]:
230
- return 'No values. If this field depends on another, put that one in "chosen" first, or try other search words.'
263
+ return f"No values. {note}" if note else 'No values. If this field depends on another, put that one in "chosen" first, or try other search words.'
231
264
  values = [{"label": o.get("label"), "value": o.get("value")} for o in result["options"]]
232
- return _clip(json.dumps({"options": values, "more": bool(result["offset"])}))
265
+ answer: Dict[str, Any] = {"options": values, "more": more}
266
+ if more and next_page is not None:
267
+ answer["paginate"] = next_page
268
+ return _clip(json.dumps(answer))
233
269
  except ViaSocketError as error:
234
270
  return f"{app_name}: listing values failed: {error}"
235
271
 
@@ -239,7 +275,7 @@ def _app_tools(viasocket, user, slug, service_id, app_name, chosen, unique_name,
239
275
  description=(
240
276
  f"{app_name}: lists the values a field of another {app_name} tool accepts (a channel, a sheet, a list), "
241
277
  f"read from the user's own {app_name} account. Call it before filling a field whose description names "
242
- "this tool; send the value, show the label."
278
+ 'this tool; send the value, show the label. A long list is searched with "search" and paged with "paginate".'
243
279
  ),
244
280
  parameters={
245
281
  "type": "object",
@@ -254,6 +290,12 @@ def _app_tools(viasocket, user, slug, service_id, app_name, chosen, unique_name,
254
290
  ),
255
291
  },
256
292
  "search": {"type": "string", "description": "Words to narrow a long list, such as part of a channel name."},
293
+ "paginate": {
294
+ "description": (
295
+ 'The "paginate" value from this tool\'s previous answer, sent back with the same "search" and '
296
+ '"chosen", to get the next page when that answer said "more".'
297
+ )
298
+ },
257
299
  },
258
300
  "required": ["tool", "field"],
259
301
  },
@@ -0,0 +1,376 @@
1
+ """
2
+ The part of the viaSocket Apps API an agent needs, with no dependencies: the public catalog, the
3
+ signed embed token, a user's flows and field values, and running an action. Mirrors the calls of
4
+ the `viasocket-apps` npm package, so both read the same responses the same way.
5
+
6
+ Apps, actions and versions are named the way the catalog shows them: the app by its slug (`slack`),
7
+ an action by its key (`Send_Message`), a version by its number (`v55`). The row ids the older
8
+ routes took still work everywhere a key does.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import hashlib
15
+ import hmac
16
+ import json
17
+ import re
18
+ import time
19
+ import urllib.error
20
+ import urllib.parse
21
+ import urllib.request
22
+ from typing import Any, Callable, Dict, List, Optional
23
+
24
+ DEFAULT_API_BASE_URL = "https://flow-api.viasocket.com"
25
+ DEFAULT_RUN_BASE_URL = "https://flow.sokt.io"
26
+ # `/<slug or service_id>` is the app, `/<slug or service_id>/actions` the app with its published actions and triggers.
27
+ CATALOG_PLUGINS = "https://plug-service.viasocket.com/api/v1/plugins"
28
+ REQUEST_TIMEOUT = 120
29
+ VERSIONS_TTL = 10 * 60
30
+ # A row id (`rowbu58rc`), as opposed to a slug or an action key.
31
+ ROW_ID = re.compile(r"^row[a-z0-9]+$")
32
+
33
+ # (method, url, headers, body) -> (status, text). Swapped in tests; urllib otherwise.
34
+ Transport = Callable[[str, str, Dict[str, str], Optional[bytes], float], "tuple[int, str]"]
35
+
36
+
37
+ class ViaSocketError(Exception):
38
+ """A refusal from viaSocket, with the API's own message; `status` is None for a local check."""
39
+
40
+ def __init__(self, message: str, status: Optional[int] = None, body: Any = None):
41
+ super().__init__(message)
42
+ self.status = status
43
+ self.body = body
44
+
45
+
46
+ def _urllib_transport(method: str, url: str, headers: Dict[str, str], body: Optional[bytes], timeout: float):
47
+ req = urllib.request.Request(url, data=body, headers=headers, method=method)
48
+ try:
49
+ with urllib.request.urlopen(req, timeout=timeout) as response:
50
+ return response.status, response.read().decode("utf-8")
51
+ except urllib.error.HTTPError as error:
52
+ return error.code, error.read().decode("utf-8", "replace")
53
+ except (urllib.error.URLError, TimeoutError) as error:
54
+ raise ViaSocketError(f"Request to {url} failed: {getattr(error, 'reason', error)}") from error
55
+
56
+
57
+ def _b64url(data: bytes) -> str:
58
+ return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
59
+
60
+
61
+ def sign_embed_token(org_id: str, project_id: str, unique_identifier: str, secret: str) -> str:
62
+ """The embed token: an HS256 JWT of exactly { org_id, project_id, unique_identifier }."""
63
+ for name, value in (("org_id", org_id), ("project_id", project_id), ("unique_identifier", unique_identifier), ("secret", secret)):
64
+ if not isinstance(value, str) or not value:
65
+ raise ViaSocketError(f"sign_embed_token: {name} is required")
66
+ compact = {"separators": (",", ":"), "ensure_ascii": False}
67
+ header = _b64url(json.dumps({"alg": "HS256", "typ": "JWT"}, **compact).encode())
68
+ payload = _b64url(
69
+ json.dumps({"org_id": org_id, "project_id": project_id, "unique_identifier": unique_identifier}, **compact).encode()
70
+ )
71
+ signing_input = f"{header}.{payload}"
72
+ signature = hmac.new(secret.encode(), signing_input.encode(), hashlib.sha256).digest()
73
+ return f"{signing_input}.{_b64url(signature)}"
74
+
75
+
76
+ def _required(name: str, value: Any) -> str:
77
+ if not isinstance(value, str) or not value.strip():
78
+ raise ViaSocketError(f"{name} is required")
79
+ return value
80
+
81
+
82
+ class ViaSocket:
83
+ """The server-side client. `secret` is the embed secret: keep it on the server."""
84
+
85
+ def __init__(
86
+ self,
87
+ org_id: str,
88
+ project_id: str,
89
+ secret: str,
90
+ api_base_url: str = DEFAULT_API_BASE_URL,
91
+ run_base_url: str = DEFAULT_RUN_BASE_URL,
92
+ transport: Optional[Transport] = None,
93
+ ):
94
+ self.org_id = _required("org_id", org_id)
95
+ self.project_id = _required("project_id", project_id)
96
+ self._secret = _required("secret", secret)
97
+ self.api_base_url = api_base_url.rstrip("/")
98
+ self.run_base_url = run_base_url.rstrip("/")
99
+ self._transport = transport or _urllib_transport
100
+ self._service_ids: Dict[str, str] = {}
101
+ self._versions: Dict[str, "tuple[float, Optional[dict]]"] = {}
102
+ self._actions: Dict[str, "tuple[float, dict]"] = {}
103
+
104
+ def _request(self, method: str, url: str, body: Any = None, token: Optional[str] = None, timeout: float = REQUEST_TIMEOUT) -> Any:
105
+ """
106
+ The envelope `{ success, data }` is unwrapped and a refusal raised. A body is the envelope only
107
+ when it has a boolean `success` and a `data` key (or is `success: false`): many actions answer
108
+ with their own result at the top level, which is returned whole.
109
+ """
110
+ # urllib's default User-Agent is refused (403) by the catalog's firewall.
111
+ headers = {"Content-Type": "application/json", "User-Agent": "viasocket-python"}
112
+ if token:
113
+ headers["authorization"] = token
114
+ data = None if body is None else (body if isinstance(body, bytes) else json.dumps(body).encode())
115
+ status, text = self._transport(method, url, headers, data, timeout)
116
+ try:
117
+ payload = json.loads(text) if text else None
118
+ except ValueError:
119
+ payload = text
120
+ envelope = (
121
+ payload
122
+ if isinstance(payload, dict) and isinstance(payload.get("success"), bool) and ("data" in payload or payload["success"] is False)
123
+ else None
124
+ )
125
+ if not 200 <= status < 300 or (envelope is not None and envelope["success"] is False):
126
+ raw = payload if isinstance(payload, dict) else {}
127
+ # A failed action run puts the app's own failure in `errorMsg`; other refusals in `error` or `message`.
128
+ nested = raw.get("errorMsg") if isinstance(raw.get("errorMsg"), dict) else raw.get("error")
129
+ message = (
130
+ raw.get("message")
131
+ or (nested.get("message") if isinstance(nested, dict) else None)
132
+ or f"viaSocket responded {status} for {method} {url}"
133
+ )
134
+ raise ViaSocketError(message, status=status, body=payload)
135
+ return envelope["data"] if envelope is not None else payload
136
+
137
+ # The catalog: public, nothing per user.
138
+
139
+ def service_id_for(self, slug: str) -> str:
140
+ """
141
+ The `service_id` of the app with this slug (`slack`, `google-sheets`), from the plug-service
142
+ catalog. Exact and case-sensitive. Prefer `service_id_of`, which reads viaSocket itself:
143
+ plug-service does not know some slugs (`gmail` among them).
144
+ """
145
+ key = _required("slug", slug)
146
+ if key not in self._service_ids:
147
+ try:
148
+ data = self._request("GET", f"{CATALOG_PLUGINS}/{urllib.parse.quote(key)}")
149
+ except ViaSocketError as error:
150
+ if error.status != 404:
151
+ raise
152
+ data = None
153
+ service = data.get("service") if isinstance(data, dict) else None
154
+ service_id = (service or {}).get("service_id")
155
+ if not service_id:
156
+ raise ViaSocketError(f'No viaSocket app has the slug "{key}" (slugs are exact and case-sensitive)')
157
+ self._service_ids[key] = service_id
158
+ return self._service_ids[key]
159
+
160
+ def versions(self, service_id: str) -> Optional[dict]:
161
+ """One app with its published actions and triggers, or None for an unknown service id. Cached 10 minutes."""
162
+ cached = self._versions.get(service_id)
163
+ if cached and time.time() - cached[0] < VERSIONS_TTL:
164
+ return cached[1]
165
+ try:
166
+ data = self._request("GET", f"{CATALOG_PLUGINS}/{urllib.parse.quote(_required('service_id', service_id))}/actions")
167
+ except ViaSocketError as error:
168
+ if error.status == 404: # an unknown app: nothing to list
169
+ return None
170
+ raise
171
+ # No `success` key, so the body arrives whole; tolerate an envelope anyway.
172
+ body = data if isinstance(data, dict) else {}
173
+ if "service" not in body:
174
+ body = body.get("data") if isinstance(body.get("data"), dict) else {}
175
+ service = body.get("service") or {}
176
+ if not service.get("name"):
177
+ return None
178
+ app = {
179
+ "service": service,
180
+ "actions": body.get("actions") if isinstance(body.get("actions"), list) else [],
181
+ "triggers": body.get("triggers") if isinstance(body.get("triggers"), list) else [],
182
+ }
183
+ self._versions[service_id] = (time.time(), app)
184
+ return app
185
+
186
+ # Calls for one end user.
187
+
188
+ def token_for(self, unique_identifier: str) -> str:
189
+ return sign_embed_token(self.org_id, self.project_id, _required("unique_identifier", unique_identifier), self._secret)
190
+
191
+ def list_flows(self, unique_identifier: str) -> List[dict]:
192
+ """Every flow the user has: one per enabled app, one per trigger subscription."""
193
+ data = self._request("GET", f"{self.api_base_url}/projects/{self.project_id}/integrations", token=self.token_for(unique_identifier))
194
+ return [
195
+ {
196
+ "id": flow.get("id"),
197
+ "status": flow.get("status"),
198
+ "auth_id": flow.get("auth_id"),
199
+ "service_id": flow.get("service_id"),
200
+ "title": flow.get("title"),
201
+ }
202
+ for flow in ((data or {}).get("flows") or [])
203
+ ]
204
+
205
+ def list_actions(self, unique_identifier: str, app: str, type: Optional[str] = None) -> dict:
206
+ """
207
+ The app's actions and triggers as viaSocket names them: `{ app, service_id, actions }`, each
208
+ action with `key`, `name`, `type`, `description`, `action_id`, `version` (the published one),
209
+ `action_version_id` and `versions`. `type` narrows to `action` or `trigger`. Cached 10 minutes.
210
+ """
211
+ slug = _required("app", app)
212
+ cache_key = f"{slug}?{type or ''}"
213
+ cached = self._actions.get(cache_key)
214
+ if cached and time.time() - cached[0] < VERSIONS_TTL:
215
+ return cached[1]
216
+ url = f"{self.api_base_url}/embed/services/{urllib.parse.quote(slug)}/actions"
217
+ if type:
218
+ url += f"?type={urllib.parse.quote(type)}"
219
+ data = self._request("GET", url, token=self.token_for(unique_identifier)) or {}
220
+ listing = {
221
+ "app": slug,
222
+ "service_id": data.get("service_id"),
223
+ "actions": data.get("actions") if isinstance(data.get("actions"), list) else [],
224
+ }
225
+ self._actions[cache_key] = (time.time(), listing)
226
+ return listing
227
+
228
+ def service_id_of(self, unique_identifier: str, app: str) -> str:
229
+ """The `service_id` of the app with this slug, read from viaSocket. Cached with `list_actions`."""
230
+ service_id = self.list_actions(unique_identifier, app)["service_id"]
231
+ if not service_id:
232
+ raise ViaSocketError(f'No viaSocket app has the slug "{app}"')
233
+ return service_id
234
+
235
+ def enable(self, unique_identifier: str, app: str, auth_id: str) -> dict:
236
+ """
237
+ Enables the app for the user on this connection, so its actions run on `webhook_url`:
238
+ `{ script_id, webhook_url, service, service_id, auth_id }`. Once per user and app: check
239
+ `find_enabled` first. `app` is a slug, or a service id for the older route.
240
+ """
241
+ name = _required("app", app)
242
+ connection = _required("auth_id", auth_id)
243
+ if ROW_ID.match(name):
244
+ url = f"{self.api_base_url}/embed/enable/{name}/{connection}"
245
+ else:
246
+ url = f"{self.api_base_url}/embed/services/{urllib.parse.quote(name)}/enable/{connection}"
247
+ return self._request("POST", url, {}, token=self.token_for(unique_identifier)) or {}
248
+
249
+ def find_enabled(self, unique_identifier: str, app: str) -> Optional[str]:
250
+ """The script_id of the user's enabled flow for this app (active or paused), or None. `app` is a slug or a service id."""
251
+ name = _required("app", app)
252
+ service_id = name if ROW_ID.match(name) else self.service_id_of(unique_identifier, name)
253
+ return next(
254
+ (flow["id"] for flow in self.list_flows(unique_identifier) if flow["service_id"] == service_id and flow["status"] in ("active", "paused")),
255
+ None,
256
+ )
257
+
258
+ def field_options(
259
+ self,
260
+ unique_identifier: str,
261
+ app: str,
262
+ action: str,
263
+ field_key: str,
264
+ auth_id: str,
265
+ existing_fields: Optional[dict] = None,
266
+ version: Optional[str] = None,
267
+ search: Optional[str] = None,
268
+ paginate: Any = None,
269
+ custom_code: Optional[str] = None,
270
+ ) -> dict:
271
+ """
272
+ The values one field of an action accepts, read from the user's own account:
273
+ `{ options, paginate, has_more, message }`. Send `paginate` back, with the same `search` and
274
+ `existing_fields`, for the next page; a new `search` starts over without it.
275
+ """
276
+ body: Dict[str, Any] = {
277
+ "auth_id": _required("auth_id", auth_id),
278
+ "fieldKey": _required("field_key", field_key),
279
+ "existingFields": existing_fields or {},
280
+ }
281
+ for key, value in (("version", version), ("search", search), ("paginate", paginate), ("custom_code", custom_code)):
282
+ if value is not None:
283
+ body[key] = value
284
+ data = self._request(
285
+ "POST",
286
+ f"{self.api_base_url}/embed/services/{urllib.parse.quote(_required('app', app))}/actions/{urllib.parse.quote(_required('action', action))}/options",
287
+ body,
288
+ token=self.token_for(unique_identifier),
289
+ )
290
+ data = data if isinstance(data, dict) else {}
291
+ options = data.get("options")
292
+ return {
293
+ "options": options if isinstance(options, list) else [],
294
+ "paginate": data.get("paginate"),
295
+ "has_more": bool(data.get("has_more")),
296
+ "message": data.get("message"),
297
+ }
298
+
299
+ def subscribe(
300
+ self,
301
+ unique_identifier: str,
302
+ app: str,
303
+ trigger: str,
304
+ auth_id: Optional[str] = None,
305
+ input_data: Optional[dict] = None,
306
+ code: Optional[str] = None,
307
+ webhook: Optional[str] = None,
308
+ version: Optional[str] = None,
309
+ meta: Any = None,
310
+ description: Optional[str] = None,
311
+ ) -> dict:
312
+ """
313
+ Subscribes the user to a trigger: every event calls `webhook` or runs `code` (exactly one).
314
+ Answers `{ script_id, title, auth_id, inputData, meta }`; keep the script_id to pause or change it.
315
+ """
316
+ if bool(code) == bool(webhook):
317
+ raise ViaSocketError("subscribe: pass exactly one of `code` (JavaScript run per event) or `webhook`")
318
+ body: Dict[str, Any] = {"code": code} if code else {"webhook": webhook}
319
+ for key, value in (("auth_id", auth_id), ("inputData", input_data), ("version", version), ("meta", meta), ("description", description)):
320
+ if value is not None:
321
+ body[key] = value
322
+ return (
323
+ self._request(
324
+ "POST",
325
+ f"{self.api_base_url}/embed/services/{urllib.parse.quote(_required('app', app))}/triggers/{urllib.parse.quote(_required('trigger', trigger))}/subscribe",
326
+ body,
327
+ token=self.token_for(unique_identifier),
328
+ )
329
+ or {}
330
+ )
331
+
332
+ def list_options(self, unique_identifier: str, action_version_id: str, field_key: str, auth_id: str, existing_fields: Optional[dict] = None) -> dict:
333
+ """
334
+ Deprecated: use `field_options`, which names the action by key and searches and pages.
335
+ The values one field accepts, read from the user's own account: `{ options, offset }`.
336
+ """
337
+ data = self._request(
338
+ "POST",
339
+ f"{self.api_base_url}/embed/list-options/{_required('action_version_id', action_version_id)}",
340
+ {"fieldKey": _required("field_key", field_key), "auth_id": _required("auth_id", auth_id), "existingFields": existing_fields or {}},
341
+ token=self.token_for(unique_identifier),
342
+ )
343
+ if isinstance(data, list):
344
+ return {"options": data, "offset": None}
345
+ # A connection that cannot be read answers 200 with the failure nested inside.
346
+ response = (data or {}).get("response") if isinstance(data, dict) else None
347
+ if isinstance(response, dict) and int(response.get("status") or 0) >= 400:
348
+ raise ViaSocketError(((response.get("data") or {}).get("message")) or "list-options failed", status=int(response["status"]), body=data)
349
+ options = (data or {}).get("data") if isinstance(data, dict) else None
350
+ return {"options": options if isinstance(options, list) else [], "offset": (data or {}).get("offset")}
351
+
352
+ def run_action(self, script_id: str, action: str, input_data: Optional[dict] = None, version: Optional[str] = None) -> Any:
353
+ """
354
+ Runs one action on the user's enabled flow and answers what the app returned. `action` is its
355
+ key (`Send_Message`; `version` picks a version, the published one when left out) or a version's
356
+ row id. The script_id is the credential: server only.
357
+ """
358
+ name = _required("action", action)
359
+ body: Dict[str, Any] = {"action_version_id": name} if ROW_ID.match(name) else {"action": name}
360
+ if version is not None and "action" in body:
361
+ body["version"] = version
362
+ body["inputData"] = input_data or {}
363
+ return self._request("POST", f"{self.run_base_url}/func/{_required('script_id', script_id)}", body)
364
+
365
+ def run_code(self, script_id: str, code: str, input_data: Optional[dict] = None, action: Optional[str] = None, version: Optional[str] = None) -> Any:
366
+ """
367
+ Runs your JavaScript with the user's connection, where an action would run: `context.inputData`,
368
+ `context.authData`, and `axios`/`fetch` that carry the credentials. Name an `action` and the
369
+ code can call that action's helpers.
370
+ """
371
+ body: Dict[str, Any] = {"custom_code": _required("code", code), "inputData": input_data or {}}
372
+ if action is not None:
373
+ body["action"] = action
374
+ if version is not None:
375
+ body["version"] = version
376
+ return self._request("POST", f"{self.run_base_url}/func/{_required('script_id', script_id)}", body)