Repository navigation
Expand file tree
/
Copy pathtools.py
More file actions
603 lines (505 loc) · 22.1 KB
/
Copy pathtools.py
File metadata and controls
603 lines (505 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
"""Hermes tool handlers for the Index Network plugin.
Handlers follow the official Hermes plugin contract:
- signature: handler(args: dict, **kwargs) -> str
- always return a JSON string
- catch errors and return JSON error payloads instead of raising
"""
from __future__ import annotations
import copy
import json
import os
import platform
import shutil
import urllib.parse
from subprocess import run as run_process
from typing import Any
from .env_transport import TransportError, upsert_index_env
from .transport import get_transport, reset_transport, set_transport_for_tests
# Universal-link host for Index deep links. The macOS app claims /o/*, /u/* and
# /i/* through its apple-app-site-association file, so the same https URL
# opens the app when it is installed and the web handoff when it is not. The
# plugin never detects app installation: it runs on the agent's host, which is
# usually not the user's Mac, so the OS decides at click time.
INDEX_APP_BASE_URL = "https://index.network"
_MAX_APP_URL_WALK_DEPTH = 16
_OPEN_URL_TIMEOUT_SECONDS = 15
_GUIDANCE_TOPICS = (
"identity-context",
"signals",
"communities-networks",
"opportunities",
"negotiations",
"workflows",
)
def _json(payload: dict[str, Any]) -> str:
return json.dumps(payload, separators=(",", ":"))
def _error(message: str, **extra: Any) -> str:
payload: dict[str, Any] = {"success": False, "error": message}
payload.update(extra)
return _json(payload)
def _error_payload(message: str, **extra: Any) -> dict[str, Any]:
payload: dict[str, Any] = {"success": False, "error": message}
payload.update(extra)
return payload
def _clean_string(value: Any) -> str | None:
if not isinstance(value, str):
return None
value = value.strip()
return value or None
def _positive_int(value: Any, name: str, *, maximum: int | None = None) -> tuple[int | None, str | None]:
if value is None:
return None, None
if isinstance(value, bool):
return None, f"{name} must be an integer."
try:
parsed = int(value)
except (TypeError, ValueError):
return None, f"{name} must be an integer."
if parsed < 1:
return None, f"{name} must be at least 1."
if maximum is not None and parsed > maximum:
return None, f"{name} must be at most {maximum}."
return parsed, None
def _app_base_url() -> str:
"""Return the universal-link origin used for Index deep links.
A well-formed `https://<host>` origin is honored. `http://` is allowed only
for loopback, so local Vite (`http://localhost:3000`) can serve `/cli-auth`.
A malformed or schemeless override (for example `index.network`) falls back
to the constant: a base that parses to an empty scheme/netloc would make
every relative path compare equal to it in `index_open_app` and turn that
tool into a generic local-file opener.
"""
raw = os.environ.get("INDEX_APP_BASE_URL", "").strip().rstrip("/")
if not raw:
return INDEX_APP_BASE_URL
try:
parts = urllib.parse.urlsplit(raw)
except ValueError:
return INDEX_APP_BASE_URL
host = (parts.hostname or "").lower()
loopback = host in {"localhost", "127.0.0.1", "::1"}
if not parts.netloc or parts.scheme not in {"https", "http"}:
return INDEX_APP_BASE_URL
if parts.scheme == "http" and not loopback:
return INDEX_APP_BASE_URL
return raw
def _attach_app_urls(value: Any, base_url: str, depth: int = 0) -> None:
"""Attach `appUrl` to every opportunity-, signal-, or user-shaped object.
An object with `opportunityId` links to `/o/`. Otherwise an object with
only `intentId` links to `/i/` and one with only `userId` links to `/u/`;
an object carrying both (an actor row) is ambiguous and left alone.
Existing `appUrl` values are never overwritten.
"""
if depth > _MAX_APP_URL_WALK_DEPTH:
return
if isinstance(value, dict):
opportunity_id = _clean_string(value.get("opportunityId"))
intent_id = _clean_string(value.get("intentId"))
user_id = _clean_string(value.get("userId"))
if not _clean_string(value.get("appUrl")):
if opportunity_id:
value["appUrl"] = f"{base_url}/o/{opportunity_id}"
elif intent_id and not user_id:
value["appUrl"] = f"{base_url}/i/{intent_id}"
elif user_id and not intent_id:
value["appUrl"] = f"{base_url}/u/{user_id}"
for item in value.values():
_attach_app_urls(item, base_url, depth + 1)
return
if isinstance(value, list):
for item in value:
_attach_app_urls(item, base_url, depth + 1)
def _with_app_urls(payload: Any) -> Any:
"""Return the payload with deep links attached, or untouched on any surprise."""
try:
enriched = copy.deepcopy(payload)
_attach_app_urls(enriched, _app_base_url())
return enriched
except Exception: # noqa: BLE001 - deep links are additive; never fail a response.
return payload
def _api_request(
method: str,
path: str,
body: dict[str, Any] | None = None,
*,
no_content_payload: dict[str, Any] | None = None,
) -> dict[str, Any]:
try:
result = get_transport().request_rest(method, path, body)
if result.get("status") == 401:
from .env_transport import refresh_transport
if refresh_transport(unauthorized=True):
result = get_transport().request_rest(method, path, body)
if result.get("no_content") is True and no_content_payload is not None:
return no_content_payload
return result
except TransportError as exc:
return exc.as_payload()
except Exception as exc: # noqa: BLE001 - Hermes handlers must not raise.
return _error_payload(f"Index transport response could not be processed: {exc}")
def selected_agent() -> dict[str, Any]:
"""Read the agent this key's owner selected to handle negotiations.
@returns The selected agent entity.
@throws ValueError when the read fails, or when the API cannot fence a turn
to one external executor — without that fence a stale negotiator on
another machine could still submit turns for this owner.
"""
payload = _api_request("GET", "/agents/me")
if payload.get("success") is False or payload.get("error"):
raise ValueError(payload.get("error") or "Index request failed")
if payload.get("negotiationExecutorFence") is not True:
raise ValueError("This Index API does not support fenced external turns. Upgrade the API before enabling the Hermes personal agent.")
return payload["agent"]
_LOCAL_AGENT_ENV = "INDEX_AGENT_ID"
def local_agent_id() -> str:
"""The agent id this Hermes install speaks as, persisted in the Hermes env."""
from .env_transport import _stored_env
return _stored_env(_LOCAL_AGENT_ENV)
def remember_local_agent(agent_id: str) -> None:
"""Store this install's agent id in the process and the gateway Hermes env.
@param agent_id - The Hermes agent registered by this install.
"""
agent_id = str(agent_id or "").strip()
if not agent_id:
return
os.environ[_LOCAL_AGENT_ENV] = agent_id
upsert_index_env(_LOCAL_AGENT_ENV, agent_id)
def this_install_selected(agent: dict[str, Any]) -> bool:
"""Whether `agent` is this install and the owner's selected negotiator.
An empty env adopts the selected agent named Hermes once, which is the
agent this dashboard registers.
@param agent - One `/agents/me` entity.
@returns True only when that entity's id is the stored id and it handles negotiations.
"""
agent_id = str(agent.get("id") or "").strip()
if agent.get("type") != "external" or agent.get("handleNegotiations") is not True or not agent_id:
return False
stored = local_agent_id()
if not stored and str(agent.get("name") or "").lower() == "hermes":
remember_local_agent(agent_id)
return True
return agent_id == stored
def login_app_base_url() -> str:
"""Web origin that serves `/cli-auth`, paired with the active API environment.
An explicit `INDEX_APP_BASE_URL` wins (it also drives deep links). Otherwise
the origin is derived from `INDEX_API_URL` by dropping a leading `protocol.`
host label (`protocol.dev.index.network` -> `dev.index.network`), so a plugin
pointed at dev/staging signs in against the matching web app instead of prod.
Without this pairing a dev-configured plugin would mint a prod key that then
401s against the dev API.
"""
from .env_transport import _stored_env
if _stored_env("INDEX_APP_BASE_URL"):
return _app_base_url()
api_url = _stored_env("INDEX_API_URL")
if not api_url:
return INDEX_APP_BASE_URL
try:
parts = urllib.parse.urlsplit(api_url)
except ValueError:
return INDEX_APP_BASE_URL
if parts.scheme in ("http", "https") and parts.netloc:
hostname = (parts.hostname or "").lower()
if hostname in {"localhost", "127.0.0.1", "::1"}:
return f"{parts.scheme}://{hostname}:3000"
host = parts.netloc
if host.startswith("protocol."):
host = host[len("protocol."):]
return f"{parts.scheme}://{host}"
return INDEX_APP_BASE_URL
def ensure_hermes_agent() -> None:
"""Register an external agent named Hermes when this account has none.
Runs once a session is live. Does not select it as the negotiator.
A registry failure must not block sign-in. Creating an agent requires a
session, so an API-key-only install keeps an agent the web app already made.
"""
try:
payload = _api_request("GET", "/agents")
if payload.get("success") is False:
return
agents = payload.get("agents")
if not isinstance(agents, list):
agents = []
for agent in agents:
if not isinstance(agent, dict):
continue
name = agent.get("name")
if not isinstance(name, str) or name.strip().lower() != "hermes":
continue
agent_id = agent.get("id")
if isinstance(agent_id, str) and agent_id.strip():
remember_local_agent(agent_id.strip())
return
created = _api_request("POST", "/agents", {"name": "Hermes"})
if created.get("success") is False:
return
agent = created.get("agent")
agent_id = agent.get("id") if isinstance(agent, dict) else ""
if isinstance(agent_id, str) and agent_id.strip():
remember_local_agent(agent_id.strip())
except Exception: # noqa: BLE001 - sign-in still completes.
return
def _api_result(
method: str,
path: str,
body: dict[str, Any] | None = None,
*,
no_content_payload: dict[str, Any] | None = None,
) -> str:
return _json(_with_app_urls(_api_request(method, path, body, no_content_payload=no_content_payload)))
def _query(params: dict[str, Any]) -> str:
encoded = urllib.parse.urlencode({key: value for key, value in params.items() if value is not None})
return f"?{encoded}" if encoded else ""
def _required_id(args: dict, key: str) -> tuple[str | None, str | None]:
value = _clean_string(args.get(key))
if value is None:
return None, f"{key} is required."
return value, None
def index_read_intents(args: dict, **kwargs) -> str:
"""Read the caller's signals, or the signals shared in one community."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
limit, limit_error = _positive_int(args.get("limit"), "limit", maximum=100)
if limit_error:
return _error(limit_error)
page, page_error = _positive_int(args.get("page"), "page")
if page_error:
return _error(page_error)
network_id = _clean_string(args.get("networkId"))
if network_id:
return _api_result("GET", f"/networks/{urllib.parse.quote(network_id)}/intents{_query({'limit': limit, 'page': page})}")
body: dict[str, Any] = {}
if limit is not None:
body["limit"] = limit
if page is not None:
body["page"] = page
query = _clean_string(args.get("query"))
if query:
body["q"] = query
if args.get("archived") is True:
body["archived"] = True
return _api_result("POST", "/intents/list", body)
def index_create_intent(args: dict, **kwargs) -> str:
"""Create a signal, shared in every community unless networkIds narrows it."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
description = _clean_string(args.get("description"))
if description is None:
return _error("description is required.")
body: dict[str, Any] = {"description": description}
network_ids = args.get("networkIds")
if isinstance(network_ids, list) and network_ids:
body["networkIds"] = [str(item) for item in network_ids]
return _api_result("POST", "/intents", body)
def index_update_intent(args: dict, **kwargs) -> str:
"""Rewrite a signal's description and reprocess it."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
intent_id, error = _required_id(args, "intentId")
if error:
return _error(error)
description = _clean_string(args.get("description"))
if description is None:
return _error("description is required.")
return _api_result("PATCH", f"/intents/{urllib.parse.quote(intent_id)}", {"description": description})
def index_list_intent_networks(args: dict, **kwargs) -> str:
"""List the communities a signal is shared in."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
intent_id, error = _required_id(args, "intentId")
if error:
return _error(error)
return _api_result("GET", f"/intents/{urllib.parse.quote(intent_id)}/networks")
def index_add_intent_to_network(args: dict, **kwargs) -> str:
"""Share a signal in one community."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
intent_id, intent_error = _required_id(args, "intentId")
if intent_error:
return _error(intent_error)
network_id, network_error = _required_id(args, "networkId")
if network_error:
return _error(network_error)
return _api_result(
"POST",
f"/intents/{urllib.parse.quote(intent_id)}/networks",
{"networkId": network_id},
no_content_payload={"success": True},
)
def index_read_networks(args: dict, **kwargs) -> str:
"""Read the communities the caller belongs to."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
return _api_result("GET", "/networks")
def index_read_network_memberships(args: dict, **kwargs) -> str:
"""Read one community's roster."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
network_id, error = _required_id(args, "networkId")
if error:
return _error(error)
return _api_result("GET", f"/networks/{urllib.parse.quote(network_id)}/members")
def index_create_network(args: dict, **kwargs) -> str:
"""Create a community, or submit an early-access request when not eligible."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
title = _clean_string(args.get("title"))
if title is None:
return _error("title is required.")
prompt = _clean_string(args.get("prompt"))
created = _api_request("POST", "/networks", {"title": title, **({"prompt": prompt} if prompt else {})})
if created.get("status") != 403:
return _json(created)
return _api_result("POST", "/network-requests", {"name": title, **({"purpose": prompt} if prompt else {})})
def index_update_network(args: dict, **kwargs) -> str:
"""Change a community's title or description. Owner only."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
network_id, error = _required_id(args, "networkId")
if error:
return _error(error)
settings: dict[str, Any] = {}
title = _clean_string(args.get("title"))
if title:
settings["title"] = title
prompt = _clean_string(args.get("prompt"))
if prompt:
settings["prompt"] = prompt
if not settings:
return _error("Supply title or prompt.")
return _api_result("PUT", f"/networks/{urllib.parse.quote(network_id)}", settings)
def index_join_network(args: dict, **kwargs) -> str:
"""Join an open community."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
network_id, error = _required_id(args, "networkId")
if error:
return _error(error)
return _api_result(
"POST",
f"/networks/{urllib.parse.quote(network_id)}/join",
{},
no_content_payload={"success": True},
)
def index_list_opportunities(args: dict, **kwargs) -> str:
"""Read persisted opportunities and their presentation."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
limit, limit_error = _positive_int(args.get("limit"), "limit", maximum=100)
if limit_error:
return _error(limit_error)
status = _clean_string(args.get("status"))
return _api_result("GET", f"/opportunities{_query({'status': status, 'limit': limit})}")
def index_update_opportunity(args: dict, **kwargs) -> str:
"""Move an opportunity to accepted or rejected. Accept only on owner approval."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
opportunity_id, error = _required_id(args, "opportunityId")
if error:
return _error(error)
status = _clean_string(args.get("status"))
if status not in {"accepted", "rejected"}:
return _error("status must be accepted or rejected.")
return _api_result(
"PATCH",
f"/opportunities/{urllib.parse.quote(opportunity_id)}/status",
{"status": status},
)
def index_research_profile(args: dict, **kwargs) -> str:
"""Research the owner's public identity without persisting the result."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
return _api_result("POST", "/enrichment/enrich", {})
def index_read_docs(args: dict, **kwargs) -> str:
"""Read the protocol's canonical guidance, optionally narrowed to one topic."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
topic = _clean_string(args.get("topic"))
if topic is not None and topic not in _GUIDANCE_TOPICS:
return _error(f"topic must be one of: {', '.join(_GUIDANCE_TOPICS)}.")
return _api_result("GET", f"/docs{_query({'topic': topic})}")
def _url_opener_command(url: str, system: str | None = None) -> list[str] | None:
"""Return the platform command that hands a URL to the OS, if there is one."""
resolved = (system or platform.system() or "").strip().lower()
if resolved == "darwin":
return ["open", url]
if resolved == "windows":
# Never route through `cmd /c start`: subprocess quotes an argument only
# when it contains whitespace, so cmd.exe metacharacters (& | ^ < > %)
# inside an otherwise valid https://index.network URL would survive
# unquoted and execute as separate commands. rundll32 is handed the URL
# as a single argv entry and no shell ever re-parses it.
return ["rundll32", "url.dll,FileProtocolHandler", url]
if shutil.which("xdg-open"):
return ["xdg-open", url]
return None
def _open_url(command: list[str]) -> str | None:
"""Run a URL-opener command. Returns None on success, an error string otherwise."""
try:
result = run_process(
command,
capture_output=True,
text=True,
timeout=_OPEN_URL_TIMEOUT_SECONDS,
check=False,
)
except Exception as exc: # noqa: BLE001 - Hermes handlers must not raise.
return str(exc)
if result.returncode != 0:
return (result.stderr or "").strip() or f"exit code {result.returncode}"
return None
def index_open_app(args: dict, **kwargs) -> str:
"""Open an Index universal link with the operating system's default handler."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
base_url = _app_base_url()
target = _clean_string(args.get("target")) or base_url
try:
base_parts = urllib.parse.urlsplit(base_url)
target_parts = urllib.parse.urlsplit(target)
except ValueError:
return _error(f"target must be an {base_url} URL.")
# An absolute https origin is required in its own right, not just an origin
# that matches the base: a bare filesystem path used as a target has an empty
# scheme and netloc and must never be handed to the OS opener.
if target_parts.scheme != "https" or not target_parts.netloc:
return _error(f"target must be an {base_url} URL.")
if target_parts.scheme != base_parts.scheme or target_parts.netloc != base_parts.netloc:
return _error(f"target must be an {base_url} URL.")
command = _url_opener_command(target)
if command is None:
return _error(
f"No URL opener is available on this host. Open {target} manually to continue in the Index app.",
url=target,
)
failure = _open_url(command)
if failure is not None:
return _error(f"Could not open {target}: {failure}", url=target)
return _json({"success": True, "url": target})
def index_agent_me(args: dict, **kwargs) -> str:
"""Return the agent the key's owner selected to handle negotiations."""
del kwargs
if not isinstance(args, dict):
return _error("Arguments must be an object.")
payload = _api_request("GET", "/agents/me")
if payload.get("success") is False:
return _json(payload)
merged = {"success": True}
merged.update(payload)
merged["success"] = True
return _json(merged)