pushary 1.9.285 → 1.9.287
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.
- package/CHANGELOG.md +10 -0
- package/dist/{api-4MGFAW5H.js → api-CT6IBO52.js} +14 -12
- package/dist/bin/pushary-ask.js +14 -14
- package/dist/bin/pushary-audit.js +3 -3
- package/dist/bin/pushary-bell-hook.js +28 -28
- package/dist/bin/pushary-bell.js +11 -11
- package/dist/bin/pushary-calls.js +14 -14
- package/dist/bin/pushary-claude.js +25 -25
- package/dist/bin/pushary-clean.js +39 -39
- package/dist/bin/pushary-codex-bridge.js +22 -22
- package/dist/bin/pushary-codex-hook.js +34 -34
- package/dist/bin/pushary-codex-session.js +8 -8
- package/dist/bin/pushary-codex.js +16 -16
- package/dist/bin/pushary-connect.js +35 -35
- package/dist/bin/pushary-cowork.js +5 -5
- package/dist/bin/pushary-daemon.js +46 -46
- package/dist/bin/pushary-disconnect.js +30 -30
- package/dist/bin/pushary-display-hook.js +1 -0
- package/dist/bin/pushary-doctor.js +49 -49
- package/dist/bin/pushary-elicitation-hook.js +27 -27
- package/dist/bin/pushary-gemini-bridge.js +17 -17
- package/dist/bin/pushary-gemini-hook.js +31 -31
- package/dist/bin/pushary-hook.js +35 -35
- package/dist/bin/pushary-login.js +42 -42
- package/dist/bin/pushary-logout.js +31 -31
- package/dist/bin/pushary-mcp.js +12 -12
- package/dist/bin/pushary-mode.js +15 -15
- package/dist/bin/pushary-notification-hook.js +27 -27
- package/dist/bin/pushary-opencode-bridge.js +21 -21
- package/dist/bin/pushary-opencode-hook.js +32 -32
- package/dist/bin/pushary-permission-denied-hook.js +34 -34
- package/dist/bin/pushary-permission-hook.js +35 -35
- package/dist/bin/pushary-post-hook.js +28 -28
- package/dist/bin/pushary-prompt-hook.js +27 -27
- package/dist/bin/pushary-session-end-hook.js +27 -27
- package/dist/bin/pushary-session-start-hook.js +39 -39
- package/dist/bin/pushary-sessions.js +12 -12
- package/dist/bin/pushary-setup.js +59 -59
- package/dist/bin/pushary-stats.js +5 -5
- package/dist/bin/pushary-status.js +36 -36
- package/dist/bin/pushary-stop-hook.js +27 -27
- package/dist/bin/pushary-stopfailure-hook.js +27 -27
- package/dist/bin/pushary-suggestions.js +15 -15
- package/dist/bin/pushary-transcript-register.js +16 -16
- package/dist/bin/pushary-transcripts.js +25 -25
- package/dist/bin/pushary-upgrade.js +47 -47
- package/dist/bin/pushary-wait.js +24 -24
- package/dist/bin/pushary.js +7 -7
- package/dist/{chunk-52XX2DYG.js → chunk-2KFYMPMJ.js} +6 -6
- package/dist/{chunk-4KPUTQPG.js → chunk-2NDMTOIT.js} +7 -7
- package/dist/{chunk-4TOJHGPX.js → chunk-3D5RKTFN.js} +2 -2
- package/dist/{chunk-WY2HGMNV.js → chunk-3NIZLXDB.js} +3 -3
- package/dist/{chunk-CP65XDI7.js → chunk-4GMY6BP5.js} +3 -3
- package/dist/{chunk-7U43GCFH.js → chunk-4JHW4D4N.js} +5 -5
- package/dist/{chunk-MTSTB2GL.js → chunk-5GACFNWL.js} +1 -1
- package/dist/{chunk-P47NDCPH.js → chunk-5VLFANI5.js} +2 -2
- package/dist/{chunk-L4PIOZIP.js → chunk-63HYM3BN.js} +2 -2
- package/dist/{chunk-2NUVES3K.js → chunk-6W4MKKWS.js} +4 -4
- package/dist/{chunk-QTNBPBYN.js → chunk-A3OU6RZ5.js} +1 -1
- package/dist/{chunk-745DB5AH.js → chunk-ARR5SMCD.js} +5 -5
- package/dist/{chunk-VVXWDBZK.js → chunk-AT5BTTQS.js} +2 -2
- package/dist/{chunk-7GHHQFHH.js → chunk-BFEH2J6N.js} +10 -10
- package/dist/{chunk-YPDWI6KV.js → chunk-C2JFC6HZ.js} +4 -4
- package/dist/{chunk-CE4D3FCO.js → chunk-CFBJJS7L.js} +12 -12
- package/dist/{chunk-ACAMCU2Y.js → chunk-CRIIKSYA.js} +1 -1
- package/dist/{chunk-PU5MHVE2.js → chunk-CWLAYD2J.js} +5 -5
- package/dist/{chunk-CDOFQJ2Z.js → chunk-DG3B7GSK.js} +1 -1
- package/dist/{chunk-XCPZ64EV.js → chunk-EK4DULO4.js} +3 -3
- package/dist/{chunk-QQDGYEWB.js → chunk-ELNLPO5R.js} +1 -1
- package/dist/{chunk-P4FD4WGC.js → chunk-EXILQZWQ.js} +3 -3
- package/dist/{chunk-FLUKEERY.js → chunk-FH6HNJF2.js} +5 -5
- package/dist/{chunk-2MQUKVMW.js → chunk-FHTK7OCG.js} +7 -7
- package/dist/{chunk-V5LIBKOQ.js → chunk-FO2HOIYA.js} +4 -4
- package/dist/{chunk-6ZRSO6PM.js → chunk-G3W7GSV6.js} +2 -2
- package/dist/{chunk-IVIG4LUZ.js → chunk-GJMN4CWA.js} +4 -4
- package/dist/{chunk-PGCMTR5N.js → chunk-GRLZVTBE.js} +5 -5
- package/dist/{chunk-WUDKVYSQ.js → chunk-H2FNFOSC.js} +2 -2
- package/dist/{chunk-LF2BFP3F.js → chunk-HSHZJ5Z5.js} +3 -3
- package/dist/{chunk-LAPJNDQG.js → chunk-I3QPRZX3.js} +4 -4
- package/dist/{chunk-VFPXC2HE.js → chunk-IAB2LINZ.js} +1 -1
- package/dist/{chunk-KI6IY52L.js → chunk-IGABHU5O.js} +6 -6
- package/dist/{chunk-BETDBGC7.js → chunk-IGM6MUL3.js} +1 -1
- package/dist/{chunk-7ZCIUEBP.js → chunk-IU4JSMWS.js} +1 -1
- package/dist/{chunk-6ZNQDNFS.js → chunk-J2EHHRY2.js} +6 -6
- package/dist/{chunk-CITB5W5V.js → chunk-JLVTNLZX.js} +8 -8
- package/dist/{chunk-DYIU6SSG.js → chunk-JO7CKMEZ.js} +1 -1
- package/dist/{chunk-A533F6TF.js → chunk-JYXGWEIA.js} +3 -3
- package/dist/{chunk-PMHOO355.js → chunk-K7H7QOHB.js} +4 -4
- package/dist/{chunk-SRGKENVI.js → chunk-KLIKQFV6.js} +1 -1
- package/dist/{chunk-IGDC2GMU.js → chunk-LCOYQP5Q.js} +2 -2
- package/dist/{chunk-4Y7RNQO5.js → chunk-LUBSO2VM.js} +3 -3
- package/dist/{chunk-WKXO22AI.js → chunk-M342TA6T.js} +4 -4
- package/dist/{chunk-RRDQYSNT.js → chunk-MDBETUXJ.js} +2 -2
- package/dist/{chunk-5DF6YZPG.js → chunk-MG65IOEE.js} +6 -6
- package/dist/{chunk-DBBLMMBL.js → chunk-NFFVLIYJ.js} +1 -1
- package/dist/{chunk-2HA6AGLM.js → chunk-NH5MKJDI.js} +5 -5
- package/dist/{chunk-SNR7BUWT.js → chunk-NYUSDIQJ.js} +4 -4
- package/dist/{chunk-XV7ZL2JN.js → chunk-OGFITATL.js} +5 -5
- package/dist/{chunk-YJ6OARPK.js → chunk-OJ5O6VRE.js} +14 -13
- package/dist/{chunk-ESTQIKTS.js → chunk-OSI26PGT.js} +1 -1
- package/dist/{chunk-JMPGFGCM.js → chunk-P7PXAD2O.js} +3 -3
- package/dist/{chunk-HWIDUN2Q.js → chunk-PGVLDCAC.js} +10 -10
- package/dist/{chunk-5IJ252DT.js → chunk-PK24TQTN.js} +16 -12
- package/dist/{chunk-YQVGPAZV.js → chunk-Q3NFM2TB.js} +1 -1
- package/dist/{chunk-7O4XAG63.js → chunk-Q5CSZPBJ.js} +2 -2
- package/dist/{chunk-EZBNWOZM.js → chunk-QCUAD2NL.js} +2 -2
- package/dist/{chunk-JPCVW3BA.js → chunk-QHI4OPBT.js} +2 -2
- package/dist/{chunk-MBUENM7S.js → chunk-REENDIUN.js} +1 -1
- package/dist/{chunk-FQC76AYR.js → chunk-RHHUEIN6.js} +5 -5
- package/dist/{chunk-LP2VGPHZ.js → chunk-RKPHCAJZ.js} +1 -1
- package/dist/{chunk-HOAWHKM3.js → chunk-RPLLLNH3.js} +53 -44
- package/dist/{chunk-5FZ2K4UV.js → chunk-S4JZRP3T.js} +1 -1
- package/dist/{chunk-77F7TPQE.js → chunk-SO4274QJ.js} +3 -3
- package/dist/{chunk-6YVIWLL2.js → chunk-SU6M73OQ.js} +2 -2
- package/dist/{chunk-YV7BK4UO.js → chunk-SVJ2WDNJ.js} +1 -1
- package/dist/{chunk-HHGZZIKD.js → chunk-SXDRZVS6.js} +6 -6
- package/dist/{chunk-VZXBPQIX.js → chunk-T4G54LCL.js} +4 -4
- package/dist/{chunk-QWBPCCFQ.js → chunk-TJ5YE7SG.js} +7 -7
- package/dist/{chunk-PAY473GK.js → chunk-TX6YNKDS.js} +1 -1
- package/dist/{chunk-6T367UEE.js → chunk-U4A5EEDI.js} +6 -6
- package/dist/{chunk-RT4KU4JT.js → chunk-UIDLO74Z.js} +1 -1
- package/dist/{chunk-V77JIYBK.js → chunk-UXZLFBSG.js} +1 -1
- package/dist/{chunk-2SW5J3J2.js → chunk-VCHZCTQB.js} +1 -1
- package/dist/{chunk-NAD2JOKF.js → chunk-W7P5GTFI.js} +1 -0
- package/dist/{chunk-O2BQDYHI.js → chunk-WAIYYGY4.js} +1 -1
- package/dist/{chunk-44RAWLI3.js → chunk-XCHF5GNH.js} +1 -1
- package/dist/{chunk-XNWLSADP.js → chunk-Y3ITUD3Q.js} +3 -3
- package/dist/{chunk-JBK7WRPB.js → chunk-YCJN6LZ6.js} +1 -1
- package/dist/{chunk-PCKCLSGP.js → chunk-YLOW6PDN.js} +6 -4
- package/dist/{chunk-6VN46PV6.js → chunk-YWAWRTRL.js} +5 -5
- package/dist/{chunk-BCYXPGOQ.js → chunk-ZUD3ILJI.js} +3 -3
- package/dist/{codex-app-cards-switch-JPDKYQ5R.js → codex-app-cards-switch-4LKL7RGN.js} +11 -11
- package/dist/{codex-card-routing-BDAI3C5X.js → codex-card-routing-36DOF7SM.js} +2 -2
- package/dist/{codex-desktop-launch-WELLPX34.js → codex-desktop-launch-W3OAG7VT.js} +3 -3
- package/dist/{codex-session-launch-BAVV7JK7.js → codex-session-launch-BUJS2QIH.js} +21 -21
- package/dist/{config-L57XINHY.js → config-VBRURSF7.js} +3 -3
- package/dist/{global-upgrade-ZD6PXYIH.js → global-upgrade-I7EA6TPR.js} +9 -9
- package/dist/{identity-ZTXVU75K.js → identity-MIO6FDAF.js} +4 -4
- package/dist/{live-capabilities-TFAUA6FN.js → live-capabilities-MHABDVR6.js} +4 -4
- package/dist/{paths-3VDI3LAG.js → paths-SIINCXTF.js} +3 -3
- package/dist/{reapply-DWXARPLQ.js → reapply-7HT5PW5T.js} +34 -34
- package/dist/src/index.d.ts +1 -0
- package/dist/src/index.js +33 -33
- package/dist/{upgrade-lock-KNVJBN5G.js → upgrade-lock-PIJW5W2P.js} +4 -4
- package/dist/{usage-YDADZALP.js → usage-A6QKFMIV.js} +3 -3
- package/package.json +1 -1
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
uninstallOpenClawPlugin,
|
|
17
17
|
unsetOpenClawEntry,
|
|
18
18
|
writeOpenClawEntry
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-EXILQZWQ.js";
|
|
20
20
|
import {
|
|
21
21
|
needsShell
|
|
22
22
|
} from "./chunk-3PSNUHC5.js";
|
|
@@ -28,14 +28,14 @@ import {
|
|
|
28
28
|
openClawDirectoriesToLookIn,
|
|
29
29
|
openClawPluginFolder,
|
|
30
30
|
openClawSetupReceiptDirectory
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-SU6M73OQ.js";
|
|
32
32
|
import {
|
|
33
33
|
atLeast,
|
|
34
34
|
parseVersion
|
|
35
35
|
} from "./chunk-6ICPEJY5.js";
|
|
36
36
|
import {
|
|
37
37
|
resolvePathBinary
|
|
38
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-NYUSDIQJ.js";
|
|
39
39
|
import {
|
|
40
40
|
readJsonSafe,
|
|
41
41
|
writeJsonAtomic
|
|
@@ -46,7 +46,7 @@ import {
|
|
|
46
46
|
} from "./chunk-CXQWDQCJ.js";
|
|
47
47
|
import {
|
|
48
48
|
isRecord
|
|
49
|
-
} from "./chunk-
|
|
49
|
+
} from "./chunk-W7P5GTFI.js";
|
|
50
50
|
|
|
51
51
|
// src/hermes/plugin-payload.ts
|
|
52
52
|
import { createHash } from "crypto";
|
|
@@ -1050,7 +1050,7 @@ def get_end_user_decision(decision_id, wait_seconds=45):
|
|
|
1050
1050
|
{ path: "approval_ledger.py", contents: 'from __future__ import annotations\n\nimport json\nimport os\nimport re\nimport secrets\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Callable, Dict, Iterable, List, Literal, Mapping, Optional, Set, Tuple, Union\n\nif TYPE_CHECKING:\n from typing_extensions import TypeGuard\n\nApprovalChoice = Literal["once", "session", "always", "deny"]\nRecordState = Literal["waiting", "settled"]\nClaimState = Literal["claiming", "won", "lost"]\nHandedBack = Literal["handed_to_hermes"]\nEnded = Literal["ended"]\nSettledOutcome = Union[ApprovalChoice, HandedBack]\nRecentOutcome = Union[SettledOutcome, Ended]\nDecider = Literal["hermes_desktop", "pushary_transport"]\nRefusedClaim = Literal["not_found", "not_waiting", "not_answerable_here", "not_offered", "already_claimed"]\nClaimResult = Union[Literal["claimed"], RefusedClaim]\nProcessIsRunning = Callable[[int], bool]\n\nAPPROVAL_CHOICES: Tuple[ApprovalChoice, ...] = ("once", "session", "always", "deny")\nWAITING: RecordState = "waiting"\nSETTLED: RecordState = "settled"\nCLAIMING: ClaimState = "claiming"\nWON: ClaimState = "won"\nLOST: ClaimState = "lost"\nCLAIM_STATES: Tuple[ClaimState, ...] = (CLAIMING, WON, LOST)\nHANDED_TO_HERMES: HandedBack = "handed_to_hermes"\nENDED: Ended = "ended"\nSETTLED_OUTCOMES: Tuple[SettledOutcome, ...] = (*APPROVAL_CHOICES, HANDED_TO_HERMES)\nRECENT_OUTCOMES: Tuple[RecentOutcome, ...] = (*SETTLED_OUTCOMES, ENDED)\nDECIDED_BY_DESKTOP: Decider = "hermes_desktop"\nDECIDED_BY_TRANSPORT: Decider = "pushary_transport"\n\nCLAIMED: Literal["claimed"] = "claimed"\nNOT_FOUND: RefusedClaim = "not_found"\nNOT_WAITING: RefusedClaim = "not_waiting"\nNOT_ANSWERABLE_HERE: RefusedClaim = "not_answerable_here"\nNOT_OFFERED: RefusedClaim = "not_offered"\nALREADY_CLAIMED: RefusedClaim = "already_claimed"\nREFUSED_CLAIMS: Tuple[RefusedClaim, ...] = (NOT_FOUND, NOT_WAITING, NOT_ANSWERABLE_HERE, NOT_OFFERED, ALREADY_CLAIMED)\n\nDESKTOP_ANSWER_SOURCE = "hermes_desktop"\nUNNAMED_ANSWER_SOURCE = "pushary"\n\nLEDGER_PATH = ("plugin-data", "pushary", "approvals")\nRECORD_SUFFIX = ".json"\nHOST_OUTCOME_PREFIX = "host-"\nTEMPORARY_PREFIX = "."\n\nCORRELATION_ID_PATTERN = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")\nREQUEST_ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,64}$")\nTOKEN_PATTERN = re.compile(r"^[a-z][a-z0-9_]{0,63}$")\n\nRETENTION_SECONDS = 24 * 60 * 60\nRECENT_LIMIT = 6\nSUBJECT_MAX = 200\nLABEL_MAX = 80\n\n\n@dataclass(frozen=True)\nclass OfferedChoice:\n choice: ApprovalChoice\n label: str\n\n\n@dataclass(frozen=True)\nclass OpenedApproval:\n correlation_id: str\n request_id: Optional[str]\n subject: str\n choices: Tuple[OfferedChoice, ...]\n pid: int\n opened_at_ms: int\n deadline_at_ms: int\n\n\n@dataclass(frozen=True)\nclass WaitingRecord:\n opened: OpenedApproval\n\n\n@dataclass(frozen=True)\nclass SettledRecord:\n opened: OpenedApproval\n outcome: SettledOutcome\n answer_source: Optional[str]\n settled_at_ms: int\n\n\nApprovalRecord = Union[WaitingRecord, SettledRecord]\n\n\n@dataclass(frozen=True)\nclass HostOutcome:\n request_id: str\n choice: str\n at_ms: int\n\n\n@dataclass(frozen=True)\nclass WaitingApproval:\n correlation_id: str\n subject: str\n choices: Tuple[OfferedChoice, ...]\n opened_at_ms: int\n deadline_at_ms: int\n answerable_here: bool\n routed_to: Optional[str]\n claim: Optional[ClaimState]\n\n\n@dataclass(frozen=True)\nclass RecentApproval:\n correlation_id: str\n subject: str\n opened_at_ms: int\n settled_at_ms: int\n outcome: RecentOutcome\n answer_source: Optional[str]\n host_outcome: Optional[str]\n\n\n@dataclass(frozen=True)\nclass ApprovalsView:\n waiting: Tuple[WaitingApproval, ...]\n recent: Tuple[RecentApproval, ...]\n\n\ndef is_correlation_id(value: object) -> TypeGuard[str]:\n return isinstance(value, str) and CORRELATION_ID_PATTERN.fullmatch(value) is not None\n\n\ndef is_request_id(value: object) -> TypeGuard[str]:\n return isinstance(value, str) and REQUEST_ID_PATTERN.fullmatch(value) is not None\n\n\ndef is_token(value: object) -> TypeGuard[str]:\n return isinstance(value, str) and TOKEN_PATTERN.fullmatch(value) is not None\n\n\ndef approval_choice(value: object) -> Optional[ApprovalChoice]:\n for choice in APPROVAL_CHOICES:\n if value == choice:\n return choice\n return None\n\n\ndef _record_state(value: object) -> Optional[RecordState]:\n for state in (WAITING, SETTLED):\n if value == state:\n return state\n return None\n\n\ndef _settled_outcome(value: object) -> Optional[SettledOutcome]:\n for outcome in SETTLED_OUTCOMES:\n if value == outcome:\n return outcome\n return None\n\n\ndef _instant(value: object) -> Optional[int]:\n return value if isinstance(value, int) and not isinstance(value, bool) and value >= 0 else None\n\n\ndef _bounded_text(value: object, limit: int) -> Optional[str]:\n return value if isinstance(value, str) and len(value) <= limit else None\n\n\ndef _fields(value: object) -> Optional[Mapping[object, object]]:\n return value if isinstance(value, dict) else None\n\n\ndef offered_choices(pairs: Iterable[Tuple[str, str]]) -> Tuple[OfferedChoice, ...]:\n offered = []\n for raw_choice, raw_label in pairs:\n choice = approval_choice(raw_choice)\n if choice is not None:\n offered.append(OfferedChoice(choice, str(raw_label)[:LABEL_MAX]))\n return tuple(offered)\n\n\ndef _parse_offered(value: object) -> Optional[OfferedChoice]:\n fields = _fields(value)\n if fields is None:\n return None\n choice = approval_choice(fields.get("choice"))\n label = _bounded_text(fields.get("label"), LABEL_MAX)\n return OfferedChoice(choice, label) if choice is not None and label is not None else None\n\n\ndef _parse_choices(value: object) -> Optional[Tuple[OfferedChoice, ...]]:\n if not isinstance(value, list):\n return None\n parsed: List[OfferedChoice] = []\n for item in value:\n offered = _parse_offered(item)\n if offered is None:\n return None\n parsed.append(offered)\n return tuple(parsed)\n\n\ndef _parse_opened(fields: Mapping[object, object]) -> Optional[OpenedApproval]:\n correlation_id = fields.get("correlationId")\n request_id = fields.get("requestId")\n subject = _bounded_text(fields.get("subject"), SUBJECT_MAX)\n choices = _parse_choices(fields.get("choices"))\n pid = fields.get("pid")\n opened_at_ms = _instant(fields.get("openedAtMs"))\n deadline_at_ms = _instant(fields.get("deadlineAtMs"))\n if not is_correlation_id(correlation_id):\n return None\n if request_id is not None and not is_request_id(request_id):\n return None\n if (\n subject is None\n or not choices\n or not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0\n or opened_at_ms is None\n or deadline_at_ms is None\n ):\n return None\n return OpenedApproval(\n correlation_id=correlation_id,\n request_id=request_id,\n subject=subject,\n choices=choices,\n pid=pid,\n opened_at_ms=opened_at_ms,\n deadline_at_ms=deadline_at_ms,\n )\n\n\ndef parse_record(value: object) -> Optional[ApprovalRecord]:\n fields = _fields(value)\n if fields is None:\n return None\n opened = _parse_opened(fields)\n state = _record_state(fields.get("state"))\n if opened is None or state is None:\n return None\n if state == WAITING:\n return WaitingRecord(opened)\n outcome = _settled_outcome(fields.get("outcome"))\n settled_at_ms = _instant(fields.get("settledAtMs"))\n answer_source = fields.get("answerSource")\n if outcome is None or settled_at_ms is None:\n return None\n if answer_source is not None and not is_token(answer_source):\n return None\n return SettledRecord(opened, outcome, answer_source, settled_at_ms)\n\n\ndef parse_host_outcome(value: object) -> Optional[HostOutcome]:\n fields = _fields(value)\n if fields is None:\n return None\n request_id = fields.get("requestId")\n choice = fields.get("choice")\n at_ms = _instant(fields.get("atMs"))\n if not is_request_id(request_id) or not is_token(choice) or at_ms is None:\n return None\n return HostOutcome(request_id, choice, at_ms)\n\n\ndef _offered_json(choice: OfferedChoice) -> Dict[str, object]:\n return {"choice": choice.choice, "label": choice.label}\n\n\ndef _opened_json(opened: OpenedApproval) -> Dict[str, object]:\n return {\n "correlationId": opened.correlation_id,\n "requestId": opened.request_id,\n "subject": opened.subject,\n "choices": [_offered_json(choice) for choice in opened.choices],\n "pid": opened.pid,\n "openedAtMs": opened.opened_at_ms,\n "deadlineAtMs": opened.deadline_at_ms,\n }\n\n\ndef _record_json(record: ApprovalRecord) -> Dict[str, object]:\n stored = _opened_json(record.opened)\n if isinstance(record, WaitingRecord):\n stored["state"] = WAITING\n return stored\n stored.update(state=SETTLED, outcome=record.outcome, answerSource=record.answer_source,\n settledAtMs=record.settled_at_ms)\n return stored\n\n\ndef _host_outcome_json(outcome: HostOutcome) -> Dict[str, object]:\n return {"requestId": outcome.request_id, "choice": outcome.choice, "atMs": outcome.at_ms}\n\n\ndef ledger_directory(home: Path) -> Path:\n return Path(home).joinpath(*LEDGER_PATH)\n\n\ndef _record_path(home: Path, correlation_id: str) -> Path:\n return ledger_directory(home) / f"{correlation_id}{RECORD_SUFFIX}"\n\n\ndef _host_outcome_path(home: Path, request_id: str) -> Path:\n return ledger_directory(home) / f"{HOST_OUTCOME_PREFIX}{request_id}{RECORD_SUFFIX}"\n\n\ndef _ensure_parent(path: Path) -> None:\n path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)\n\n\ndef _staged_json(path: Path, value: Dict[str, object]) -> Path:\n _ensure_parent(path)\n staged = path.with_name(f"{TEMPORARY_PREFIX}{path.name}.{secrets.token_hex(8)}.tmp")\n try:\n with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle:\n json.dump(value, handle)\n except BaseException:\n staged.unlink(missing_ok=True)\n raise\n return staged\n\n\ndef _replace_json(path: Path, value: Dict[str, object]) -> None:\n staged = _staged_json(path, value)\n try:\n os.replace(staged, path)\n finally:\n staged.unlink(missing_ok=True)\n\n\ndef _read_json(path: Path) -> object:\n try:\n return json.loads(path.read_text(encoding="utf-8"))\n except (OSError, ValueError):\n return None\n\n\ndef read_record(home: Path, correlation_id: str) -> Optional[ApprovalRecord]:\n if not is_correlation_id(correlation_id):\n return None\n record = parse_record(_read_json(_record_path(home, correlation_id)))\n return record if record is not None and record.opened.correlation_id == correlation_id else None\n\n\ndef read_host_outcome(home: Path, request_id: Optional[str]) -> Optional[HostOutcome]:\n if not is_request_id(request_id):\n return None\n outcome = parse_host_outcome(_read_json(_host_outcome_path(home, request_id)))\n return outcome if outcome is not None and outcome.request_id == request_id else None\n\n\ndef open_approval(\n home: Path,\n *,\n correlation_id: str,\n request_id: Optional[str],\n subject: str,\n choices: Tuple[OfferedChoice, ...],\n pid: int,\n opened_at_ms: int,\n deadline_at_ms: int,\n) -> bool:\n if not is_correlation_id(correlation_id) or pid <= 0 or not choices:\n return False\n opened = OpenedApproval(\n correlation_id=correlation_id,\n request_id=request_id if is_request_id(request_id) else None,\n subject=subject[:SUBJECT_MAX],\n choices=choices,\n pid=pid,\n opened_at_ms=opened_at_ms,\n deadline_at_ms=deadline_at_ms,\n )\n _replace_json(_record_path(home, correlation_id), _record_json(WaitingRecord(opened)))\n return True\n\n\ndef settle_approval(\n home: Path,\n correlation_id: str,\n *,\n outcome: SettledOutcome,\n answer_source: Optional[str],\n settled_at_ms: int,\n) -> bool:\n record = read_record(home, correlation_id)\n if not isinstance(record, WaitingRecord):\n return False\n source = answer_source if is_token(answer_source) else None\n _replace_json(_record_path(home, correlation_id), _record_json(SettledRecord(record.opened, outcome, source,\n settled_at_ms)))\n return True\n\n\ndef record_host_outcome(home: Path, request_id: str, choice: str, at_ms: int) -> bool:\n if not is_request_id(request_id) or not is_token(choice):\n return False\n _replace_json(_host_outcome_path(home, request_id), _host_outcome_json(HostOutcome(request_id, choice, at_ms)))\n return True\n\n\ndef host_has_finished(home: Path, request_id: Optional[str]) -> bool:\n return read_host_outcome(home, request_id) is not None\n\n\ndef _owner_is_running(opened: OpenedApproval, process_is_running: ProcessIsRunning) -> bool:\n return opened.pid > 0 and process_is_running(opened.pid)\n\n\ndef _is_live(record: ApprovalRecord, host_outcome: Optional[HostOutcome], now_ms: int,\n process_is_running: ProcessIsRunning) -> bool:\n return (\n isinstance(record, WaitingRecord)\n and host_outcome is None\n and now_ms < record.opened.deadline_at_ms\n and _owner_is_running(record.opened, process_is_running)\n )\n\n\ndef _waiting_elsewhere(record: WaitingRecord) -> WaitingApproval:\n opened = record.opened\n return WaitingApproval(\n correlation_id=opened.correlation_id,\n subject=opened.subject,\n choices=opened.choices,\n opened_at_ms=opened.opened_at_ms,\n deadline_at_ms=opened.deadline_at_ms,\n answerable_here=False,\n routed_to=None,\n claim=None,\n )\n\n\ndef _recent(record: ApprovalRecord, host_outcome: Optional[HostOutcome]) -> RecentApproval:\n opened = record.opened\n if isinstance(record, SettledRecord):\n outcome: RecentOutcome = record.outcome\n settled_at_ms = record.settled_at_ms\n answer_source = record.answer_source\n else:\n outcome = ENDED\n settled_at_ms = host_outcome.at_ms if host_outcome else opened.deadline_at_ms\n answer_source = None\n return RecentApproval(\n correlation_id=opened.correlation_id,\n subject=opened.subject,\n opened_at_ms=opened.opened_at_ms,\n settled_at_ms=settled_at_ms,\n outcome=outcome,\n answer_source=answer_source,\n host_outcome=host_outcome.choice if host_outcome else None,\n )\n\n\ndef approvals_view(\n records: Iterable[ApprovalRecord],\n host_outcomes: Mapping[str, HostOutcome],\n now_ms: int,\n process_is_running: ProcessIsRunning,\n) -> ApprovalsView:\n waiting = []\n recent = []\n for record in records:\n request_id = record.opened.request_id\n host_outcome = host_outcomes.get(request_id) if request_id else None\n if isinstance(record, WaitingRecord) and _is_live(record, host_outcome, now_ms, process_is_running):\n waiting.append(_waiting_elsewhere(record))\n else:\n recent.append(_recent(record, host_outcome))\n waiting.sort(key=lambda item: item.opened_at_ms)\n recent.sort(key=lambda item: item.settled_at_ms, reverse=True)\n return ApprovalsView(waiting=tuple(waiting), recent=tuple(recent[:RECENT_LIMIT]))\n\n\ndef _ledger_files(home: Path) -> List[Path]:\n try:\n return [path for path in ledger_directory(home).iterdir() if path.is_file()]\n except OSError:\n return []\n\n\ndef _correlation_id_of(name: str) -> Optional[str]:\n candidate = name[: -len(RECORD_SUFFIX)] if name.endswith(RECORD_SUFFIX) else None\n return candidate if is_correlation_id(candidate) else None\n\n\ndef _ledger_entries(home: Path) -> List[Tuple[Path, object]]:\n return [(path, _read_json(path)) for path in _ledger_files(home) if not path.name.startswith(TEMPORARY_PREFIX)]\n\n\ndef read_approvals(home: Path, now_ms: int, process_is_running: ProcessIsRunning) -> ApprovalsView:\n records: List[ApprovalRecord] = []\n host_outcomes: Dict[str, HostOutcome] = {}\n for path, value in _ledger_entries(home):\n name = path.name\n if name.startswith(HOST_OUTCOME_PREFIX):\n host_outcome = parse_host_outcome(value)\n if host_outcome is not None:\n host_outcomes[host_outcome.request_id] = host_outcome\n else:\n record = parse_record(value)\n if record is not None and name == f"{record.opened.correlation_id}{RECORD_SUFFIX}":\n records.append(record)\n return approvals_view(records, host_outcomes, now_ms, process_is_running)\n\n\ndef _unexpired_waiting(home: Path, now_ms: int) -> Set[str]:\n kept: Set[str] = set()\n for path, value in _ledger_entries(home):\n if path.name.startswith(HOST_OUTCOME_PREFIX) or not path.name.endswith(RECORD_SUFFIX):\n continue\n record = parse_record(value)\n if isinstance(record, WaitingRecord) and record.opened.deadline_at_ms > now_ms:\n kept.add(record.opened.correlation_id)\n return kept\n\n\ndef prune(home: Path, now_seconds: float) -> None:\n kept = _unexpired_waiting(home, int(now_seconds * 1000))\n for path in _ledger_files(home):\n if _correlation_id_of(path.name) in kept:\n continue\n try:\n if now_seconds - path.stat().st_mtime > RETENTION_SECONDS:\n path.unlink(missing_ok=True)\n except OSError:\n continue\n' },
|
|
1051
1051
|
{ path: "approval.py", contents: 'import contextvars\nimport logging\nimport os\nimport sys\nimport threading\nimport time\nfrom typing import Dict, Literal, Optional, Tuple\n\nfrom . import api, approval_ledger, cancellation, desktop_answers, desktop_contract, identity, installation\nfrom .approval_coverage import HERMES_SHELL_TOOL\n\nlogger = logging.getLogger(__name__)\n\nDECISION_LINE_MAX = 500\nACTION_BODY_MAX = 4000\nACTION_BODY_TRUNCATION_MARKER = "\\n\u2026 [truncated]"\nUTF16_SINGLE_UNIT_MAX = 0xFFFF\n\nPOLL_CEILING_SECONDS = 50.0\nWITHDRAW_RESERVE_SECONDS = 10.0\nHOST_RETURN_MARGIN_SECONDS = 1.0\nLATE_ANSWER_POLL_MS = 1000\n\nREQUESTER_LIMIT = 64\n_requesters: Dict[str, contextvars.Context] = {}\n_requesters_lock = threading.Lock()\n\nTUI_GATEWAY_MODULE = "tui_gateway.server"\n\nRouteAnswerability = Literal["requester", "routed_elsewhere", "unknown"]\nANSWERABLE_BY_REQUESTER: RouteAnswerability = "requester"\nROUTED_ELSEWHERE: RouteAnswerability = "routed_elsewhere"\nANSWERABILITY_UNKNOWN: RouteAnswerability = "unknown"\n\nWithdrawal = Literal["withdrawn", "answered_late", "ended", "stopped"]\nWITHDRAWN: Withdrawal = "withdrawn"\nANSWERED_LATE: Withdrawal = "answered_late"\nENDED_UNANSWERED: Withdrawal = "ended"\nSTOPPED: Withdrawal = "stopped"\n\n\nCHOICE_LABELS = (\n ("once", "Allow once"),\n ("session", "Allow for this session"),\n ("always", "Always allow"),\n ("deny", "Deny"),\n)\n\n\nclass TransportUnavailable(Exception):\n pass\n\n\nQUESTION_COMMAND_MAX = 160\n\n\ndef _offered(allowed):\n return [pair for pair in CHOICE_LABELS if pair[0] in set(allowed or ())]\n\n\ndef _command_head(command):\n return " ".join(str(command or "").split()[:2])[:80]\n\n\ndef _utf16_units(character: str) -> int:\n return 2 if ord(character) > UTF16_SINGLE_UNIT_MAX else 1\n\n\ndef _utf16_length(text: str) -> int:\n return sum(_utf16_units(character) for character in text)\n\n\ndef _prefix_within_utf16_units(text: str, units: int) -> str:\n used = 0\n for index, character in enumerate(text):\n used += _utf16_units(character)\n if used > units:\n return text[:index]\n return text\n\n\ndef cut_action_body(text: str) -> str:\n if len(_prefix_within_utf16_units(text, ACTION_BODY_MAX)) == len(text):\n return text\n kept = _prefix_within_utf16_units(text, ACTION_BODY_MAX - _utf16_length(ACTION_BODY_TRUNCATION_MARKER))\n return kept + ACTION_BODY_TRUNCATION_MARKER\n\n\ndef _command_summary(command):\n collapsed = " ".join(str(command or "").split())\n if len(collapsed) <= QUESTION_COMMAND_MAX:\n return collapsed\n return collapsed[:QUESTION_COMMAND_MAX - 1] + "\u2026"\n\n\ndef _choice_from_answer(value, offered, uses_select):\n answer = str(value or "").strip()\n if uses_select:\n for choice, label in offered:\n if answer.lower() == label.lower():\n return choice\n return "deny"\n return "once" if api.is_affirmative(answer) else "deny"\n\n\ndef _subject(request):\n return _command_summary(str(request.command or ""))\n\n\ndef _open_question(request, offered, uses_select):\n command = str(request.command or "")\n return api.ask_user(\n question=f"Allow Hermes to run `{_subject(request)}`?",\n question_type="select" if uses_select else "confirm",\n options=[label for _, label in offered] if uses_select else None,\n context=str(request.description or "")[:500] or None,\n agent_name=identity.agent_name(),\n session_id=identity.session_id(),\n machine_id=identity.machine_id(),\n tool_name=HERMES_SHELL_TOOL,\n tool_target=_command_head(command),\n action=command[:DECISION_LINE_MAX] or None,\n action_body=cut_action_body(command) or None,\n blocker=(\n f"Hermes flagged this command as {request.pattern_key}"[:DECISION_LINE_MAX]\n if request.pattern_key\n else None\n ),\n wait=False,\n )\n\n\ndef _stopped(result):\n return result.get("handoffAction") == cancellation.STOP_HANDOFF or result.get("status") in (\n "cancelled", cancellation.UNAVAILABLE_STATUS, "stopped")\n\n\ndef _route_answerability(created) -> RouteAnswerability:\n requester_may_answer = created.get("requesterMayAnswer")\n if requester_may_answer is True:\n return ANSWERABLE_BY_REQUESTER\n if requester_may_answer is False:\n return ROUTED_ELSEWHERE\n return ANSWERABILITY_UNKNOWN\n\n\ndef _routed_to(created) -> Optional[str]:\n routed_to = created.get("routedTo")\n return routed_to if isinstance(routed_to, str) and routed_to.strip() else None\n\n\ndef _withdraw(correlation_id) -> Tuple[Withdrawal, dict]:\n try:\n result = cancellation.classify_cancellation(api.cancel_question(correlation_id))\n if result in (cancellation.WITHDRAWN_BY_THIS_CALL, cancellation.CANCELLED_UNPROVEN):\n return WITHDRAWN, {}\n if result == cancellation.NOT_PENDING:\n answer = api.wait_for_answer(correlation_id, LATE_ANSWER_POLL_MS)\n if answer.get("answered"):\n return ANSWERED_LATE, answer\n if answer.get("status") in ("expired", "missing"):\n return ENDED_UNANSWERED, answer\n except Exception:\n pass\n return STOPPED, {}\n\n\ndef _wall_clock_ms():\n return int(time.time() * 1000)\n\n\ndef announce_approvals_changed() -> None:\n if TUI_GATEWAY_MODULE not in sys.modules:\n return\n try:\n from hermes_cli.plugin_events import broadcast_plugin_event\n except Exception:\n return\n try:\n broadcast_plugin_event(desktop_contract.PLUGIN_ID, desktop_contract.APPROVALS_CHANGED_EVENT, {})\n except Exception:\n logger.debug("[pushary] could not tell Hermes Desktop about an approval", exc_info=True)\n\n\ndef _open_answer_slot(request, correlation_id: str, offered, answerability: RouteAnswerability,\n routed_to: Optional[str], opened_at_ms: int, deadline_at_ms: int) -> None:\n try:\n desktop_answers.shared_answers().open_slot(\n correlation_id,\n request_id=getattr(request, "request_id", None),\n subject=_subject(request),\n choices=approval_ledger.offered_choices(offered),\n opened_at_ms=opened_at_ms,\n deadline_at_ms=deadline_at_ms,\n answerable_here=answerability == ANSWERABLE_BY_REQUESTER,\n routed_to=routed_to,\n )\n except Exception:\n logger.debug("[pushary] could not offer an approval to Hermes Desktop", exc_info=True)\n\n\ndef _close_answer_slot(correlation_id: str) -> None:\n try:\n desktop_answers.shared_answers().close_slot(correlation_id)\n except Exception:\n logger.debug("[pushary] could not withdraw an approval from Hermes Desktop", exc_info=True)\n\n\ndef _record_opened(request, correlation_id: str, offered, answerability: RouteAnswerability,\n routed_to: Optional[str]) -> None:\n opened_at_ms = _wall_clock_ms()\n deadline_at_ms = opened_at_ms + int(float(request.timeout_seconds or 0) * 1000)\n _open_answer_slot(request, correlation_id, offered, answerability, routed_to, opened_at_ms, deadline_at_ms)\n try:\n home = installation.hermes_home()\n approval_ledger.prune(home, time.time())\n opened = approval_ledger.open_approval(\n home,\n correlation_id=correlation_id,\n request_id=getattr(request, "request_id", None),\n subject=_subject(request),\n choices=approval_ledger.offered_choices(offered),\n pid=os.getpid(),\n opened_at_ms=opened_at_ms,\n deadline_at_ms=deadline_at_ms,\n )\n except Exception:\n logger.debug("[pushary] could not record an open approval", exc_info=True)\n opened = False\n if opened:\n announce_approvals_changed()\n\n\ndef _record_settled(correlation_id: str, outcome, answer_source: Optional[str]) -> None:\n try:\n settled = approval_ledger.settle_approval(\n installation.hermes_home(),\n correlation_id,\n outcome=outcome,\n answer_source=answer_source,\n settled_at_ms=_wall_clock_ms(),\n )\n except Exception:\n logger.debug("[pushary] could not record a settled approval", exc_info=True)\n return\n if settled:\n announce_approvals_changed()\n\n\ndef record_host_outcome(request_id, choice) -> None:\n try:\n desktop_answers.shared_answers().end_for_request(request_id)\n except Exception:\n logger.debug("[pushary] could not end an approval in Hermes Desktop", exc_info=True)\n try:\n recorded = approval_ledger.record_host_outcome(installation.hermes_home(), request_id, choice, _wall_clock_ms())\n except Exception:\n logger.debug("[pushary] could not record Hermes\'s approval outcome", exc_info=True)\n return\n if recorded:\n announce_approvals_changed()\n\n\ndef _decided(request, correlation_id, choice, answer_source):\n _record_settled(correlation_id, choice, answer_source)\n return request.respond(choice)\n\n\ndef _answer_source(answer) -> str:\n source = answer.get("answerSource")\n return source if approval_ledger.is_token(source) else approval_ledger.UNNAMED_ANSWER_SOURCE\n\n\ndef _answered(request, correlation_id, answer, offered, uses_select):\n choice = _choice_from_answer(answer.get("value"), offered, uses_select)\n return _decided(request, correlation_id, choice, _answer_source(answer))\n\n\ndef _offered_choices(offered) -> Tuple[str, ...]:\n return tuple(choice for choice, _ in offered)\n\n\ndef _host_has_finished(request, correlation_id: str) -> bool:\n try:\n if desktop_answers.shared_answers().has_ended(correlation_id):\n return True\n return approval_ledger.host_has_finished(installation.hermes_home(), getattr(request, "request_id", None))\n except Exception:\n return False\n\n\ndef _desktop_decision(correlation_id: str, offered) -> Optional[str]:\n try:\n return desktop_answers.shared_answers().desktop_decision(correlation_id, _offered_choices(offered))\n except Exception:\n logger.debug("[pushary] could not read a Hermes Desktop answer", exc_info=True)\n return None\n\n\ndef _final_say(correlation_id: str, offered, host_deadline: float, claim_may_still_win: bool) -> Optional[str]:\n wait = min(desktop_answers.CLAIM_RESOLVE_SECONDS, host_deadline - time.monotonic()) if claim_may_still_win else 0.0\n try:\n return desktop_answers.shared_answers().take_final_say(correlation_id, _offered_choices(offered),\n claim_wait_seconds=wait)\n except Exception:\n logger.debug("[pushary] could not settle who answers this approval", exc_info=True)\n return None\n\n\ndef remember_requester(request_id: str, session_id: Optional[str]) -> None:\n requester = contextvars.copy_context()\n requester.run(identity.bind_session, session_id)\n with _requesters_lock:\n _requesters[request_id] = requester\n while len(_requesters) > REQUESTER_LIMIT:\n del _requesters[next(iter(_requesters))]\n\n\ndef forget_requester(request_id: str) -> None:\n with _requesters_lock:\n _requesters.pop(request_id, None)\n\n\ndef present(request):\n with _requesters_lock:\n requester = _requesters.pop(str(getattr(request, "request_id", "")), None)\n return requester.run(_present, request) if requester is not None else _present(request)\n\n\ndef _present(request):\n offered = _offered(request.allowed_choices)\n if not offered:\n return request.respond("deny")\n uses_select = [choice for choice, _ in offered] != ["once", "deny"]\n # Reserve time for withdrawal before the host discards a late decision.\n started_at = time.monotonic()\n timeout_seconds = float(request.timeout_seconds or 0)\n deadline = started_at + max(timeout_seconds - WITHDRAW_RESERVE_SECONDS, 0.0)\n host_deadline = started_at + max(timeout_seconds - HOST_RETURN_MARGIN_SECONDS, 0.0)\n created = _open_question(request, offered, uses_select)\n if created.get("answered"):\n return request.respond(_choice_from_answer(created.get("value"), offered, uses_select))\n if _stopped(created):\n return request.respond("deny")\n correlation_id = created.get("correlationId")\n if not correlation_id:\n raise TransportUnavailable("Pushary did not create an approval")\n answerability = _route_answerability(created)\n _record_opened(request, correlation_id, offered, answerability, _routed_to(created))\n try:\n return _await_decision(request, created, correlation_id, offered, uses_select, answerability,\n started_at, deadline, host_deadline)\n finally:\n _close_answer_slot(correlation_id)\n\n\ndef _await_decision(request, created, correlation_id: str, offered, uses_select: bool,\n answerability: RouteAnswerability, started_at: float, deadline: float, host_deadline: float):\n may_hand_back = answerability != ROUTED_ELSEWHERE\n nothing_was_delivered = bool(created.get("noDevices") or created.get("status") in ("terminal", "notified"))\n policy_deadline = None\n window_ms = created.get("policyTimeoutMs")\n if may_hand_back and created.get("deliveryMode") == "push_first" and isinstance(window_ms, (int, float)) and window_ms >= 0:\n policy_deadline = started_at + window_ms / 1000\n deadline = min(deadline, policy_deadline)\n handoff = may_hand_back and (nothing_was_delivered or bool(created.get("suppressed")))\n nobody_can_answer = not may_hand_back and nothing_was_delivered\n answer = created\n try:\n while not handoff and not nobody_can_answer and time.monotonic() < deadline:\n if _host_has_finished(request, correlation_id):\n answer = {"handoffAction": "stop"}\n break\n remaining = deadline - time.monotonic()\n answer = api.wait_for_answer(correlation_id, int(min(POLL_CEILING_SECONDS, max(1.0, remaining)) * 1000))\n if answer.get("answered"):\n return _answered(request, correlation_id, answer, offered, uses_select)\n if _stopped(answer) or answer.get("error") or answer.get("status") in ("expired", "missing"):\n break\n # Some hosts/proxies return pending immediately instead of long-polling.\n time.sleep(min(0.1, max(0, deadline - time.monotonic())))\n except Exception:\n answer = {"handoffAction": "stop"}\n\n desktop = _desktop_decision(correlation_id, offered)\n if desktop:\n return _decided(request, correlation_id, desktop, approval_ledger.DESKTOP_ANSWER_SOURCE)\n withdrawal, late = _withdraw(correlation_id)\n if withdrawal == ANSWERED_LATE:\n return _answered(request, correlation_id, late, offered, uses_select)\n desktop = _final_say(correlation_id, offered, host_deadline, claim_may_still_win=withdrawal == STOPPED)\n if desktop:\n return _decided(request, correlation_id, desktop, approval_ledger.DESKTOP_ANSWER_SOURCE)\n if _stopped(answer) or withdrawal == STOPPED:\n return _decided(request, correlation_id, "deny", None)\n if handoff or (policy_deadline is not None and time.monotonic() >= policy_deadline):\n # Only a fenced question may reach Hermes\'s configured builtin fallback.\n _record_settled(correlation_id, approval_ledger.HANDED_TO_HERMES, None)\n raise TransportUnavailable("Approval handed back to Hermes")\n return _decided(request, correlation_id, "deny", None)\n' },
|
|
1052
1052
|
{ path: "cancellation.py", contents: 'from __future__ import annotations\n\nfrom typing import Literal, Mapping, Tuple\n\nCancellation = Literal[\n "withdrawn_by_this_call",\n "cancelled_unproven",\n "already_cancelled",\n "not_pending",\n "unreachable",\n]\n\nWITHDRAWN_BY_THIS_CALL: Cancellation = "withdrawn_by_this_call"\nCANCELLED_UNPROVEN: Cancellation = "cancelled_unproven"\nALREADY_CANCELLED: Cancellation = "already_cancelled"\nNOT_PENDING: Cancellation = "not_pending"\nUNREACHABLE: Cancellation = "unreachable"\nCANCELLATIONS: Tuple[Cancellation, ...] = (\n WITHDRAWN_BY_THIS_CALL,\n CANCELLED_UNPROVEN,\n ALREADY_CANCELLED,\n NOT_PENDING,\n UNREACHABLE,\n)\n\nUNAVAILABLE_STATUS = "unavailable"\nSTOP_HANDOFF = "stop"\n\n\ndef classify_cancellation(response: object) -> Cancellation:\n if not isinstance(response, Mapping):\n return UNREACHABLE\n fields: Mapping[object, object] = response\n cancelled = fields.get("cancelled")\n by_this_call = fields.get("cancelledByThisCall")\n if (\n not isinstance(cancelled, bool)\n or fields.get("status") == UNAVAILABLE_STATUS\n or fields.get("handoffAction") == STOP_HANDOFF\n or (by_this_call is not None and not isinstance(by_this_call, bool))\n or (by_this_call is True and not cancelled)\n ):\n return UNREACHABLE\n if not cancelled:\n return NOT_PENDING\n if by_this_call is None:\n return CANCELLED_UNPROVEN\n return WITHDRAWN_BY_THIS_CALL if by_this_call else ALREADY_CANCELLED\n' },
|
|
1053
|
-
{ path: "dashboard/manifest.json", contents: '{\n "name": "pushary",\n "label": "Pushary",\n "description": "Approvals Pushary is carrying to your phone, answerable from Hermes Desktop",\n "version": "1.0.
|
|
1053
|
+
{ path: "dashboard/manifest.json", contents: '{\n "name": "pushary",\n "label": "Pushary",\n "description": "Approvals Pushary is carrying to your phone, answerable from Hermes Desktop",\n "version": "1.0.16",\n "tab": { "hidden": true },\n "entry": "web.js",\n "api": "plugin_api.py"\n}\n' },
|
|
1054
1054
|
{ path: "dashboard/plugin_api.py", contents: `import importlib
|
|
1055
1055
|
import sys
|
|
1056
1056
|
import time
|
|
@@ -1298,7 +1298,7 @@ def shared_answers() -> DesktopAnswers:
|
|
|
1298
1298
|
` },
|
|
1299
1299
|
{ path: "desktop_contract.py", contents: 'from __future__ import annotations\n\nfrom typing import Callable, List, Literal, Mapping, Optional, Tuple, TypedDict, Union\n\nfrom . import approval_ledger as ledger\nfrom . import cancellation\nfrom .desktop_answers import DesktopAnswers\n\nCONTRACT_VERSION = 1\nPLUGIN_ID = "pushary"\nAPPROVALS_CHANGED_EVENT = "approvals.changed"\nAPPROVALS_CHANGED_WIRE_EVENT = f"plugin.{PLUGIN_ID}.{APPROVALS_CHANGED_EVENT}"\nAPPROVALS_PATH = "/approvals"\nANSWER_PATH_SUFFIX = "/answer"\n\nFenceOutcome = Literal["answered_here", "already_closed", "unreachable"]\nAnswerOutcome = Union[FenceOutcome, ledger.RefusedClaim]\n\nANSWERED_HERE: FenceOutcome = "answered_here"\nALREADY_CLOSED: FenceOutcome = "already_closed"\nUNREACHABLE: FenceOutcome = "unreachable"\nFENCE_OUTCOMES: Tuple[FenceOutcome, ...] = (ANSWERED_HERE, ALREADY_CLOSED, UNREACHABLE)\nANSWER_OUTCOMES: Tuple[AnswerOutcome, ...] = (*FENCE_OUTCOMES, *ledger.REFUSED_CLAIMS)\n\nHOST_FAILURE_OUTCOMES: Tuple[str, ...] = (\n "transport_busy",\n "transport_error",\n "transport_interrupted",\n "transport_invalid",\n "transport_stale",\n "transport_timeout",\n)\n\nCancelQuestion = Callable[[str], object]\n\n\nclass OfferedChoiceWire(TypedDict):\n choice: ledger.ApprovalChoice\n label: str\n\n\nclass WaitingApprovalWire(TypedDict):\n correlationId: str\n subject: str\n choices: List[OfferedChoiceWire]\n openedAtMs: int\n deadlineAtMs: int\n answerableHere: bool\n routedTo: Optional[str]\n claim: Optional[ledger.ClaimState]\n\n\nclass RecentApprovalWire(TypedDict):\n correlationId: str\n subject: str\n openedAtMs: int\n settledAtMs: int\n outcome: ledger.RecentOutcome\n answerSource: Optional[str]\n hostOutcome: Optional[str]\n\n\nclass SetupWire(TypedDict):\n apiKey: bool\n transport: bool\n pluginVersion: Optional[str]\n\n\nclass ApprovalsResponse(TypedDict):\n version: int\n waiting: List[WaitingApprovalWire]\n recent: List[RecentApprovalWire]\n setup: SetupWire\n\n\nclass AnswerResponse(TypedDict):\n version: int\n outcome: AnswerOutcome\n\n\nclass ContractFacts(TypedDict):\n version: int\n approvalsChangedWireEvent: str\n approvalsPath: str\n answerPathSuffix: str\n correlationIdPattern: str\n tokenPattern: str\n approvalChoices: List[str]\n claimStates: List[str]\n recentOutcomes: List[str]\n answerOutcomes: List[str]\n hostFailureOutcomes: List[str]\n\n\ndef _offered_wire(offered: ledger.OfferedChoice) -> OfferedChoiceWire:\n return {"choice": offered.choice, "label": offered.label}\n\n\ndef _waiting_wire(item: ledger.WaitingApproval) -> WaitingApprovalWire:\n return {\n "correlationId": item.correlation_id,\n "subject": item.subject,\n "choices": [_offered_wire(offered) for offered in item.choices],\n "openedAtMs": item.opened_at_ms,\n "deadlineAtMs": item.deadline_at_ms,\n "answerableHere": item.answerable_here,\n "routedTo": item.routed_to,\n "claim": item.claim,\n }\n\n\ndef _recent_wire(item: ledger.RecentApproval) -> RecentApprovalWire:\n return {\n "correlationId": item.correlation_id,\n "subject": item.subject,\n "openedAtMs": item.opened_at_ms,\n "settledAtMs": item.settled_at_ms,\n "outcome": item.outcome,\n "answerSource": item.answer_source,\n "hostOutcome": item.host_outcome,\n }\n\n\ndef setup_wire(*, api_key_saved: bool, transport_selected: bool, plugin_version: Optional[str]) -> SetupWire:\n return {"apiKey": api_key_saved, "transport": transport_selected, "pluginVersion": plugin_version}\n\n\ndef view_with_answers_here(view: ledger.ApprovalsView, here: Tuple[ledger.WaitingApproval, ...]) -> ledger.ApprovalsView:\n answered_here = {item.correlation_id for item in here}\n elsewhere = tuple(item for item in view.waiting if item.correlation_id not in answered_here)\n waiting = tuple(sorted((*here, *elsewhere), key=lambda item: item.opened_at_ms))\n return ledger.ApprovalsView(waiting=waiting, recent=view.recent)\n\n\ndef approvals_response(view: ledger.ApprovalsView, setup: SetupWire) -> ApprovalsResponse:\n return {\n "version": CONTRACT_VERSION,\n "waiting": [_waiting_wire(item) for item in view.waiting],\n "recent": [_recent_wire(item) for item in view.recent],\n "setup": setup,\n }\n\n\ndef answer_response(outcome: AnswerOutcome) -> AnswerResponse:\n return {"version": CONTRACT_VERSION, "outcome": outcome}\n\n\ndef parse_answer_request(body: object) -> Optional[ledger.ApprovalChoice]:\n if not isinstance(body, Mapping):\n return None\n fields: Mapping[object, object] = body\n if set(fields) != {"choice"}:\n return None\n return ledger.approval_choice(fields.get("choice"))\n\n\ndef _refused(result: ledger.ClaimResult) -> Optional[ledger.RefusedClaim]:\n for refused in ledger.REFUSED_CLAIMS:\n if result == refused:\n return refused\n return None\n\n\ndef _cancel_from_desktop(cancel_question: CancelQuestion, correlation_id: str) -> cancellation.Cancellation:\n try:\n return cancellation.classify_cancellation(cancel_question(correlation_id))\n except Exception:\n return cancellation.UNREACHABLE\n\n\ndef answer_from_desktop(\n answers: DesktopAnswers,\n correlation_id: str,\n choice: ledger.ApprovalChoice,\n *,\n cancel_question: CancelQuestion,\n now_ms: int,\n) -> AnswerResponse:\n refused = _refused(answers.claim(correlation_id, choice, now_ms=now_ms))\n if refused is not None:\n return answer_response(refused)\n withdrawal = _cancel_from_desktop(cancel_question, correlation_id)\n if withdrawal == cancellation.WITHDRAWN_BY_THIS_CALL and answers.decide_from_desktop(correlation_id, choice):\n return answer_response(ANSWERED_HERE)\n answers.lose_claim(correlation_id)\n return answer_response(UNREACHABLE if withdrawal == cancellation.UNREACHABLE else ALREADY_CLOSED)\n\n\ndef contract_facts() -> ContractFacts:\n return {\n "version": CONTRACT_VERSION,\n "approvalsChangedWireEvent": APPROVALS_CHANGED_WIRE_EVENT,\n "approvalsPath": APPROVALS_PATH,\n "answerPathSuffix": ANSWER_PATH_SUFFIX,\n "correlationIdPattern": ledger.CORRELATION_ID_PATTERN.pattern,\n "tokenPattern": ledger.TOKEN_PATTERN.pattern,\n "approvalChoices": list(ledger.APPROVAL_CHOICES),\n "claimStates": list(ledger.CLAIM_STATES),\n "recentOutcomes": list(ledger.RECENT_OUTCOMES),\n "answerOutcomes": list(ANSWER_OUTCOMES),\n "hostFailureOutcomes": list(HOST_FAILURE_OUTCOMES),\n }\n' },
|
|
1300
1300
|
{ path: "desktop/plugin.js", contents: "// Generated from desktop-src/plugin.ts by scripts/build-desktop.mjs. Edit the source, then run it.\nimport { atom, Button, CopyButton, host, Popover, PopoverContent, PopoverTrigger, STATUSBAR_AREAS, StatusDot, useValue } from '@hermes/plugin-sdk';\nimport { createElement as h, useEffect, useState } from 'react';\nexport const PLUGIN_ID = 'pushary';\nexport const CONTRACT_VERSION = 1;\nexport const APPROVALS_CHANGED_WIRE_EVENT = 'plugin.pushary.approvals.changed';\nexport const APPROVALS_PATH = '/approvals';\nexport const ANSWER_PATH_SUFFIX = '/answer';\nexport const CORRELATION_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\nexport const TOKEN_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;\nexport const APPROVAL_CHOICES = ['once', 'session', 'always', 'deny'];\nexport const CLAIM_STATES = ['claiming', 'won', 'lost'];\nexport const RECENT_OUTCOMES = ['once', 'session', 'always', 'deny', 'handed_to_hermes', 'ended'];\nexport const ANSWER_OUTCOMES = [\n 'answered_here', 'already_closed', 'unreachable',\n 'not_found', 'not_waiting', 'not_answerable_here', 'not_offered', 'already_claimed'\n];\nexport const HOST_FAILURE_OUTCOMES = [\n 'transport_busy', 'transport_error', 'transport_interrupted', 'transport_invalid', 'transport_stale', 'transport_timeout'\n];\nconst isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);\nconst isOneOf = (values) => (value) => typeof value === 'string' && values.includes(value);\nconst isApprovalChoice = isOneOf(APPROVAL_CHOICES);\nconst isClaimState = isOneOf(CLAIM_STATES);\nconst isRecentOutcome = isOneOf(RECENT_OUTCOMES);\nconst isAnswerOutcome = isOneOf(ANSWER_OUTCOMES);\nconst isHostFailureOutcome = isOneOf(HOST_FAILURE_OUTCOMES);\nconst isInstant = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;\nconst isCorrelationId = (value) => typeof value === 'string' && CORRELATION_ID_PATTERN.test(value);\nconst isTokenOrNull = (value) => value === null || (typeof value === 'string' && TOKEN_PATTERN.test(value));\nconst isContractVersion = (value) => value === CONTRACT_VERSION;\nconst parseList = (value, parse) => {\n if (!Array.isArray(value))\n return null;\n const parsed = [];\n for (const item of value) {\n const result = parse(item);\n if (result === null)\n return null;\n parsed.push(result);\n }\n return parsed;\n};\nconst parseOfferedChoice = (value) => {\n if (!isRecord(value) || !isApprovalChoice(value.choice) || typeof value.label !== 'string')\n return null;\n return { choice: value.choice, label: value.label };\n};\nconst parseWaitingApproval = (value) => {\n if (!isRecord(value))\n return null;\n const choices = parseList(value.choices, parseOfferedChoice);\n const claim = value.claim === null || isClaimState(value.claim) ? value.claim : undefined;\n const routedTo = value.routedTo === null || typeof value.routedTo === 'string' ? value.routedTo : undefined;\n if (!isCorrelationId(value.correlationId) || typeof value.subject !== 'string' || choices === null\n || !isInstant(value.openedAtMs) || !isInstant(value.deadlineAtMs) || claim === undefined\n || typeof value.answerableHere !== 'boolean' || routedTo === undefined)\n return null;\n return {\n correlationId: value.correlationId,\n subject: value.subject,\n choices,\n openedAtMs: value.openedAtMs,\n deadlineAtMs: value.deadlineAtMs,\n answerableHere: value.answerableHere,\n routedTo,\n claim\n };\n};\nconst parseRecentApproval = (value) => {\n if (!isRecord(value) || !isCorrelationId(value.correlationId) || typeof value.subject !== 'string'\n || !isInstant(value.openedAtMs) || !isInstant(value.settledAtMs) || !isRecentOutcome(value.outcome)\n || !isTokenOrNull(value.answerSource) || !isTokenOrNull(value.hostOutcome))\n return null;\n return {\n correlationId: value.correlationId,\n subject: value.subject,\n openedAtMs: value.openedAtMs,\n settledAtMs: value.settledAtMs,\n outcome: value.outcome,\n answerSource: value.answerSource,\n hostOutcome: value.hostOutcome\n };\n};\nconst parseSetup = (value) => {\n if (!isRecord(value) || typeof value.apiKey !== 'boolean' || typeof value.transport !== 'boolean')\n return null;\n const pluginVersion = value.pluginVersion;\n if (pluginVersion !== null && typeof pluginVersion !== 'string')\n return null;\n return { apiKey: value.apiKey, transport: value.transport, pluginVersion };\n};\nexport const parseApprovalsResponse = (value) => {\n if (!isRecord(value) || !isContractVersion(value.version))\n return null;\n const waiting = parseList(value.waiting, parseWaitingApproval);\n const recent = parseList(value.recent, parseRecentApproval);\n const setup = parseSetup(value.setup);\n if (waiting === null || recent === null || setup === null)\n return null;\n return { version: value.version, waiting, recent, setup };\n};\nexport const parseAnswerResponse = (value) => {\n if (!isRecord(value) || !isContractVersion(value.version) || !isAnswerOutcome(value.outcome))\n return null;\n return { version: value.version, outcome: value.outcome };\n};\nexport const answerPath = (correlationId) => isCorrelationId(correlationId) ? `${APPROVALS_PATH}/${correlationId}${ANSWER_PATH_SUFFIX}` : null;\nconst LIVE_REFRESH_MS = 2000;\nconst IDLE_REFRESH_MS = 15000;\nconst CLOCK_TICK_MS = 1000;\nconst GATEWAY_OPEN = 'open';\nconst SETTINGS_CHANGED_EVENT = `plugin.${PLUGIN_ID}.settings.changed`;\nconst TRANSPORT_COMMAND = 'hermes config set security.approval.transport pushary';\nconst SIGN_UP_URL = 'https://pushary.com/sign-up?from=hermes';\nconst UNKNOWN_SURFACE = 'Pushary';\nconst NOT_ANSWERED = 'Not answered';\nconst UNNAMED_SUBJECT = 'A command Hermes flagged';\nconst SENDING_ANSWER = 'Sending your answer\u2026';\nconst ANSWER_SURFACES = {\n mobile_app: 'phone',\n mobile_background: 'phone',\n mac_app: 'Mac',\n slack: 'Slack',\n dashboard: 'web',\n decide_page: 'web',\n live_page: 'web',\n answer_link: 'web',\n inbox: 'web',\n sandbox: 'sandbox',\n hermes_desktop: 'Hermes Desktop'\n};\nconst HOST_FAILURE_TEXT = {\n transport_busy: 'Hermes was busy',\n transport_error: 'Failed in Hermes',\n transport_interrupted: 'Turn interrupted',\n transport_invalid: 'Refused by Hermes',\n transport_stale: 'Refused by Hermes',\n transport_timeout: 'Timed out in Hermes'\n};\nconst CHOICE_RESULTS = {\n once: 'Allowed once',\n session: 'Allowed for this session',\n always: 'Always allowed',\n deny: 'Denied'\n};\nconst CHOICE_BUTTON_VARIANTS = {\n once: 'default',\n session: 'secondary',\n always: 'secondary',\n deny: 'outline'\n};\nconst ANSWER_NOTICES = {\n answered_here: { kind: 'success', message: 'Answered from Hermes Desktop.' },\n already_closed: { kind: 'info', message: 'This approval had already closed, so your answer was not used.' },\n unreachable: { kind: 'error', message: 'Pushary did not confirm your answer, so it was not used.' },\n not_found: { kind: 'info', message: 'This approval has already ended.' },\n not_waiting: { kind: 'info', message: 'This approval has already ended.' },\n not_answerable_here: { kind: 'info', message: 'A Team route sends this approval to someone else to answer.' },\n not_offered: { kind: 'error', message: 'Hermes did not offer that choice.' },\n already_claimed: { kind: 'info', message: 'This approval is already being answered.' }\n};\nconst ANSWER_FAILED = {\n kind: 'error',\n message: 'Hermes Desktop could not send that answer. Answer on your phone.'\n};\nexport const waitedFor = (ms) => {\n const seconds = Math.max(0, Math.floor(ms / 1000));\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`;\n};\nexport const ago = (ms) => {\n const minutes = Math.floor(Math.max(0, ms) / 60000);\n if (minutes < 1)\n return 'just now';\n if (minutes < 60)\n return `${minutes} min ago`;\n const hours = Math.floor(minutes / 60);\n if (hours < 24)\n return `${hours} h ago`;\n return `${Math.floor(hours / 24)} d ago`;\n};\nconst surfaceOf = (answerSource) => ANSWER_SURFACES[answerSource] ?? UNKNOWN_SURFACE;\nconst choiceOutcomeText = (choice, answerSource) => {\n if (answerSource === null)\n return choice === 'deny' ? NOT_ANSWERED : CHOICE_RESULTS[choice];\n return `${CHOICE_RESULTS[choice]} \xB7 ${surfaceOf(answerSource)}`;\n};\nexport const outcomeText = (item) => {\n if (item.outcome === 'handed_to_hermes')\n return 'Handed to Hermes';\n if (isHostFailureOutcome(item.hostOutcome))\n return HOST_FAILURE_TEXT[item.hostOutcome];\n if (item.outcome === 'ended')\n return 'Ended';\n return choiceOutcomeText(item.outcome, item.answerSource);\n};\nexport const waitingLabel = (count) => count === 1 ? '1 approval waiting' : `${count} approvals waiting`;\nexport const waitingLine = (item, now) => {\n const waited = waitedFor(now - item.openedAtMs);\n if (!item.answerableHere) {\n return item.routedTo === null ? `Answer it on your phone \xB7 ${waited}` : `Routed to ${item.routedTo} \xB7 ${waited}`;\n }\n switch (item.claim) {\n case 'claiming':\n return SENDING_ANSWER;\n case 'won':\n return 'Answered here. Handing it to Hermes\u2026';\n case 'lost':\n return `Answer it on your phone \xB7 ${waited}`;\n case null:\n return `Waiting on your phone \xB7 ${waited}`;\n }\n};\nexport const approvalStatusLine = (item, now, answering) => answering === item.correlationId ? SENDING_ANSWER : waitingLine(item, now);\nconst subjectOf = (subject) => subject || UNNAMED_SUBJECT;\nconst readyChipSummary = (response) => {\n if (response.waiting.length > 0) {\n const waiting = waitingLabel(response.waiting.length);\n return { tone: 'warn', text: `Pushary \xB7 ${waiting}`, label: `Pushary: ${waiting}` };\n }\n if (!response.setup.apiKey)\n return { tone: 'warn', text: 'Pushary \xB7 set up', label: 'Pushary needs your API key' };\n if (!response.setup.transport) {\n return { tone: 'warn', text: 'Pushary \xB7 not routing', label: 'Approvals are not routed to Pushary' };\n }\n return { tone: 'good', text: 'Pushary', label: 'Pushary carries approvals to your phone' };\n};\nexport const chipSummary = (state) => {\n switch (state.kind) {\n case 'loading':\n return { tone: 'muted', text: 'Pushary', label: 'Pushary is loading' };\n case 'offline':\n return { tone: 'muted', text: 'Pushary', label: 'The Pushary backend is not running' };\n case 'incompatible':\n return { tone: 'bad', text: 'Pushary \xB7 update', label: 'This Pushary Desktop half does not match its backend' };\n case 'ready':\n return readyChipSummary(state.response);\n }\n};\nexport const answerNotice = (value) => {\n const response = parseAnswerResponse(value);\n return response === null ? ANSWER_FAILED : ANSWER_NOTICES[response.outcome];\n};\nexport const panelStateFrom = (value) => {\n const response = parseApprovalsResponse(value);\n return response === null ? { kind: 'incompatible' } : { kind: 'ready', response };\n};\nconst waitingCount = (state) => (state.kind === 'ready' ? state.response.waiting.length : 0);\nexport const createApprovalsStore = (ctx) => {\n const state = atom({ kind: 'loading' });\n const open = atom(false);\n const answering = atom(null);\n let inFlight = null;\n let refreshAgain = false;\n let loadedAt = Number.NEGATIVE_INFINITY;\n const load = async () => {\n try {\n state.set(panelStateFrom(await ctx.rest(APPROVALS_PATH)));\n }\n catch {\n state.set({ kind: 'offline' });\n }\n finally {\n loadedAt = Date.now();\n }\n };\n const refresh = () => {\n if (inFlight !== null) {\n refreshAgain = true;\n return inFlight;\n }\n inFlight = load().finally(() => {\n inFlight = null;\n if (refreshAgain) {\n refreshAgain = false;\n void refresh();\n }\n });\n return inFlight;\n };\n const answer = async (item, choice) => {\n const path = answerPath(item.correlationId);\n if (answering.get() !== null || path === null)\n return;\n answering.set(item.correlationId);\n try {\n host.notify(answerNotice(await ctx.rest(path, { method: 'POST', body: { choice } })));\n }\n catch {\n host.notify(ANSWER_FAILED);\n }\n finally {\n answering.set(null);\n void refresh();\n }\n };\n const refreshIsDue = (now) => open.get() || waitingCount(state.get()) > 0 || now - loadedAt >= IDLE_REFRESH_MS;\n return { state, open, answering, refresh, answer, refreshIsDue };\n};\nconst STYLES = {\n chip: { display: 'inline-flex', alignItems: 'center', gap: '6px' },\n popover: { width: 'min(340px, calc(100vw - 24px))', padding: 0 },\n panel: {\n padding: '12px', display: 'flex', flexDirection: 'column', gap: '12px', overflowY: 'auto', overscrollBehavior: 'contain',\n maxHeight: 'min(560px, calc(var(--radix-popover-content-available-height, 100vh) - 16px))'\n },\n heading: { fontSize: '12px', fontWeight: 600, color: 'var(--ui-text-primary)' },\n muted: { fontSize: '11px', lineHeight: '16px', color: 'var(--ui-text-tertiary)' },\n section: { display: 'flex', flexDirection: 'column', gap: '8px' },\n card: {\n display: 'flex', flexDirection: 'column', gap: '8px', padding: '8px',\n borderRadius: '4px', boxShadow: 'inset 0 0 0 1px var(--ui-stroke-secondary)'\n },\n subject: {\n fontFamily: 'var(--font-mono, monospace)', fontSize: '11px', lineHeight: '16px',\n color: 'var(--ui-text-primary)', wordBreak: 'break-word', maxHeight: '160px', overflowY: 'auto'\n },\n choices: { display: 'flex', flexWrap: 'wrap', gap: '6px' },\n command: {\n fontFamily: 'var(--font-mono, monospace)', fontSize: '11px', padding: '6px 8px', borderRadius: '4px',\n background: 'var(--ui-bg-quaternary)', color: 'var(--ui-text-secondary)', userSelect: 'text', wordBreak: 'break-all'\n },\n row: { display: 'flex', justifyContent: 'space-between', gap: '8px', fontSize: '11px', lineHeight: '16px' },\n rowSubject: {\n overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',\n fontFamily: 'var(--font-mono, monospace)', color: 'var(--ui-text-secondary)'\n },\n rowOutcome: { flexShrink: 0, color: 'var(--ui-text-tertiary)' }\n};\nconst useNow = (ticking) => {\n const [now, setNow] = useState(Date.now());\n useEffect(() => {\n if (!ticking)\n return undefined;\n const timer = setInterval(() => setNow(Date.now()), CLOCK_TICK_MS);\n return () => clearInterval(timer);\n }, [ticking]);\n return now;\n};\nconst Muted = ({ text }) => h('div', { style: STYLES.muted }, text);\nconst SetupNotice = ({ setup, ctx }) => {\n if (!setup.apiKey) {\n return h('div', { style: STYLES.section }, h(Muted, { text: 'Add your Pushary API key under Settings, Plugins, Pushary.' }), h('div', null, h(Button, {\n variant: 'secondary', size: 'xs', onClick: () => void ctx.os.openExternal(SIGN_UP_URL), children: 'Get a key'\n })));\n }\n if (!setup.transport) {\n return h('div', { style: STYLES.section }, h(Muted, { text: 'Hermes is not sending approvals to Pushary yet. Run this once:' }), h('div', { style: STYLES.command }, TRANSPORT_COMMAND), h('div', null, h(CopyButton, { text: TRANSPORT_COMMAND, label: 'Copy', showLabel: true, buttonSize: 'xs' })));\n }\n return null;\n};\nconst ChoiceButtons = ({ item, store }) => {\n const answering = useValue(store.answering);\n const disabled = answering !== null || item.claim !== null;\n return h('div', { style: STYLES.choices }, ...item.choices.map(offered => h(Button, {\n key: offered.choice,\n variant: CHOICE_BUTTON_VARIANTS[offered.choice],\n size: 'xs',\n disabled,\n onClick: () => void store.answer(item, offered.choice),\n children: offered.label\n })));\n};\nconst ApprovalCard = ({ item, store, now }) => {\n const answering = useValue(store.answering);\n return h('div', { style: STYLES.card }, h('div', { style: STYLES.subject }, subjectOf(item.subject)), h(Muted, { text: approvalStatusLine(item, now, answering) }), item.answerableHere ? h(ChoiceButtons, { item, store }) : null);\n};\nconst RecentRow = ({ item, now }) => h('div', { style: STYLES.row }, h('span', { style: STYLES.rowSubject, title: subjectOf(item.subject) }, subjectOf(item.subject)), h('span', { style: STYLES.rowOutcome }, `${outcomeText(item)} \xB7 ${ago(now - item.settledAtMs)}`));\nconst WaitingList = ({ response, store, now }) => {\n if (response.waiting.length === 0) {\n return h(Muted, { text: 'No approvals waiting. Answer them here or on your phone, whichever is closer.' });\n }\n return h('div', { style: STYLES.section }, ...response.waiting.map(item => h(ApprovalCard, { key: item.correlationId, item, store, now })));\n};\nconst RecentList = ({ recent, now }) => {\n if (recent.length === 0)\n return null;\n return h('div', { style: STYLES.section }, h(Muted, { text: 'Recent' }), ...recent.map(item => h(RecentRow, { key: item.correlationId, item, now })));\n};\nconst ReadyPanel = ({ response, store, ctx }) => {\n const now = useNow(response.waiting.length > 0);\n const heading = response.waiting.length ? waitingLabel(response.waiting.length) : 'Pushary';\n return h('div', { style: STYLES.panel }, h('div', { style: STYLES.heading }, heading), h(SetupNotice, { setup: response.setup, ctx }), h(WaitingList, { response, store, now }), h(RecentList, { recent: response.recent, now }));\n};\nconst PANEL_MESSAGES = {\n loading: 'Loading\u2026',\n offline: 'The Pushary backend is not running. Enable Pushary under Capabilities, Plugins, then restart Hermes.',\n incompatible: 'This copy of the Pushary Desktop half does not match its backend. Rescan plugins under Capabilities.'\n};\nexport const PusharyPanel = ({ store, ctx }) => {\n const state = useValue(store.state);\n if (state.kind !== 'ready')\n return h('div', { style: STYLES.panel }, h(Muted, { text: PANEL_MESSAGES[state.kind] }));\n return h(ReadyPanel, { response: state.response, store, ctx });\n};\nexport const PusharyChip = ({ store, ctx }) => {\n const summary = chipSummary(useValue(store.state));\n const open = useValue(store.open);\n const onOpenChange = (value) => {\n store.open.set(value);\n if (value)\n void store.refresh();\n };\n return h(Popover, {\n open,\n onOpenChange,\n children: [\n h(PopoverTrigger, { key: 'trigger', asChild: true, children: h(Button, {\n variant: 'ghost', size: 'micro', 'aria-label': summary.label, title: summary.label,\n children: h('span', { style: STYLES.chip }, h(StatusDot, { tone: summary.tone }), h('span', null, summary.text))\n }) }),\n h(PopoverContent, { key: 'content', side: 'top', align: 'end', 'aria-label': 'Pushary approvals',\n style: STYLES.popover, children: h(PusharyPanel, { store, ctx }) })\n ]\n });\n};\nconst registerPushary = (ctx) => {\n const store = createApprovalsStore(ctx);\n ctx.register({ id: 'approvals', area: STATUSBAR_AREAS.right, order: 120, render: () => h(PusharyChip, { store, ctx }) });\n ctx.onEvent(APPROVALS_CHANGED_WIRE_EVENT, () => void store.refresh());\n ctx.onEvent(SETTINGS_CHANGED_EVENT, () => void store.refresh());\n ctx.onDispose(host.state.gateway.listen(value => {\n if (value === GATEWAY_OPEN)\n void store.refresh();\n }));\n ctx.setInterval(() => {\n if (store.refreshIsDue(Date.now()))\n void store.refresh();\n }, LIVE_REFRESH_MS);\n void store.refresh();\n};\nconst plugin = {\n id: PLUGIN_ID,\n name: 'Pushary',\n description: 'Approvals Pushary is carrying to your phone, answerable here too.',\n register: registerPushary\n};\nexport default plugin;\n" },
|
|
1301
|
-
{ path: "gate.py", contents: 'from __future__ import annotations\n\nimport contextvars\nimport hashlib\nimport json\nimport threading\nimport time\nfrom collections import deque\nfrom typing import Callable, Deque, List, Literal, Mapping, NamedTuple, Optional\n\nfrom . import api, cancellation, identity, installation\n\nANSWER_WINDOW_SECONDS = 600.0\nCREATE_TIMEOUT_SECONDS = 30.0\nREQUEST_GRACE_SECONDS = 2.0\nMIN_POLL_SECONDS = 1.0\nPOLL_PAUSE_SECONDS = 1.0\nLATE_ANSWER_POLL_MS = 1000\nAPPROVAL_REUSE_SECONDS = 5.0\nENDED_TURN_LIMIT = 256\nWAIT_FOR_ANSWER = "wait_for_answer"\n\nVerdict = Literal["allowed", "denied", "undeliverable", "handed_back", "waiting", "unapproved"]\nALLOWED: Verdict = "allowed"\nDENIED: Verdict = "denied"\nUNDELIVERABLE: Verdict = "undeliverable"\nHANDED_BACK: Verdict = "handed_back"\nWAITING: Verdict = "waiting"\nUNAPPROVED: Verdict = "unapproved"\n\nAnswer = Mapping[str, object]\nAsk = Callable[[], Answer]\n\n\nclass GatedCall(NamedTuple):\n home: str\n session_id: str\n turn_id: str\n tool_name: str\n arguments: str\n\n\nclass Turn(NamedTuple):\n home: str\n turn_id: str\n\n\nclass Question:\n def __init__(self, call: GatedCall) -> None:\n self.call = call\n self.opened_monotonic = time.monotonic()\n self.opened_wall = time.time()\n self.correlation_id = ""\n self.claimed = True\n self.claimed_at = self.opened_monotonic\n self.read_monotonic = self.opened_monotonic\n self.read_wall = self.opened_wall\n self.outcome: Optional[Verdict] = None\n self.withdrawn = threading.Event()\n self.step_finished = threading.Event()\n self.step_finished.set()\n\n def has_expired(self) -> bool:\n return _seconds_since(self.opened_monotonic, self.opened_wall) >= ANSWER_WINDOW_SECONDS\n\n def note_read_started(self) -> None:\n self.read_monotonic = time.monotonic()\n self.read_wall = time.time()\n\n def approval_must_be_read_again(self) -> bool:\n read_by_an_earlier_call = self.read_monotonic < self.claimed_at\n return read_by_an_earlier_call and _seconds_since(self.read_monotonic, self.read_wall) > APPROVAL_REUSE_SECONDS\n\n def usable_outcome(self) -> Optional[Verdict]:\n outcome = self.outcome\n return None if outcome == ALLOWED and self.approval_must_be_read_again() else outcome\n\n\ndef _seconds_since(monotonic: float, wall: float) -> float:\n return max(time.monotonic() - monotonic, time.time() - wall)\n\n\n_questions: List[Question] = []\n_ended_turns: Deque[Turn] = deque(maxlen=ENDED_TURN_LIMIT)\n_lock = threading.Lock()\n\n\ndef gated_call(session_id: Optional[str], turn_id: Optional[str], tool_name: str, args: object) -> GatedCall:\n encoded = json.dumps(args, sort_keys=True, ensure_ascii=True, default=repr)\n digest = hashlib.sha256(encoded.encode("utf-8")).hexdigest()\n return GatedCall(str(installation.hermes_home()), str(session_id or ""), str(turn_id or ""), tool_name, digest)\n\n\ndef is_same_call(asked: GatedCall, retried: GatedCall) -> bool:\n if (asked.home, asked.tool_name, asked.arguments) != (retried.home, retried.tool_name, retried.arguments):\n return False\n if asked.turn_id or retried.turn_id:\n return asked.turn_id == retried.turn_id\n return bool(asked.session_id) and asked.session_id == retried.session_id\n\n\ndef belongs_to_turn(call: GatedCall, home: str, session_id: str, turn_id: str) -> bool:\n if call.home != home:\n return False\n if turn_id and call.turn_id:\n return call.turn_id == turn_id\n return bool(session_id) and call.session_id == session_id\n\n\ndef can_be_retried(call: GatedCall) -> bool:\n return bool(call.turn_id or call.session_id)\n\n\ndef _may_still_be_answered(answer: Answer) -> bool:\n if answer.get("error"):\n return True\n return answer.get("nextAction") == WAIT_FOR_ANSWER and not answer.get("handoffAction")\n\n\ndef _could_not_be_read(answer: Answer) -> bool:\n return not answer.get("answered") and answer.get("status") == cancellation.UNAVAILABLE_STATUS\n\n\ndef _answered_verdict(answer: Answer) -> Verdict:\n return ALLOWED if api.is_affirmative(answer.get("value")) else DENIED\n\n\ndef _hand_back_verdict(answer: Answer) -> Verdict:\n if answer.get("noDevices"):\n return UNDELIVERABLE\n return HANDED_BACK if answer.get("handoffAction") else UNAPPROVED\n\n\ndef _withdraw_unless_answered(correlation_id: str, hand_back: Verdict) -> Verdict:\n result = cancellation.classify_cancellation(api.cancel_question(correlation_id))\n if result in (cancellation.WITHDRAWN_BY_THIS_CALL, cancellation.CANCELLED_UNPROVEN):\n return hand_back\n if result != cancellation.NOT_PENDING:\n return UNAPPROVED\n late = api.wait_for_answer(correlation_id, LATE_ANSWER_POLL_MS)\n return _answered_verdict(late) if late.get("answered") else UNAPPROVED\n\n\ndef _outcome_of(correlation_id: str, answer: Answer) -> Optional[Verdict]:\n if answer.get("answered"):\n return _answered_verdict(answer)\n if _may_still_be_answered(answer):\n return None\n if answer.get("handoffAction") == cancellation.STOP_HANDOFF:\n return UNAPPROVED\n return _withdraw_unless_answered(correlation_id, _hand_back_verdict(answer))\n\n\ndef _cancel_quietly(correlation_ids: List[str]) -> None:\n for correlation_id in correlation_ids:\n try:\n api.cancel_question(correlation_id)\n except Exception:\n continue\n\n\ndef _in_background(name: str, target: Callable[..., None], *args: object) -> threading.Thread:\n worker = threading.Thread(target=contextvars.copy_context().run, args=(target, *args), name=name, daemon=True)\n worker.start()\n return worker\n\n\ndef _withdraw(should_withdraw: Callable[[Question], bool], ended: Optional[Turn] = None) -> Optional[threading.Thread]:\n with _lock:\n if ended is not None:\n _ended_turns.append(ended)\n withdrawn = [question for question in _questions if should_withdraw(question)]\n _questions[:] = [question for question in _questions if question not in withdrawn]\n for question in withdrawn:\n question.withdrawn.set()\n correlation_ids = [question.correlation_id for question in withdrawn if question.correlation_id]\n if not correlation_ids:\n return None\n return _in_background("pushary-gate-withdraw", _cancel_quietly, correlation_ids)\n\n\ndef _is_stale(question: Question) -> bool:\n return not question.claimed and question.has_expired()\n\n\ndef _claim(call: GatedCall) -> Optional[Question]:\n with _lock:\n if call.turn_id and Turn(call.home, call.turn_id) in _ended_turns:\n return None\n for question in _questions:\n if not question.claimed and is_same_call(question.call, call):\n question.claimed = True\n question.claimed_at = time.monotonic()\n return question\n opened = Question(call)\n _questions.append(opened)\n return opened\n\n\ndef _open(question: Question, ask: Ask) -> Optional[Verdict]:\n question.note_read_started()\n answer = ask()\n correlation_id = str(answer.get("correlationId") or "")\n if answer.get("error") or not correlation_id:\n return UNAPPROVED\n with _lock:\n question.correlation_id = correlation_id\n withdrawn = question.withdrawn.is_set()\n if withdrawn:\n _cancel_quietly([correlation_id])\n return UNAPPROVED\n return _outcome_of(correlation_id, answer)\n\n\ndef _poll(question: Question, deadline: float) -> Optional[Verdict]:\n while not question.withdrawn.is_set() and time.monotonic() < deadline:\n question.note_read_started()\n wait = max(MIN_POLL_SECONDS, deadline - time.monotonic() - REQUEST_GRACE_SECONDS)\n try:\n answer = api.wait_for_answer(question.correlation_id, int(wait * 1000))\n outcome = None if _could_not_be_read(answer) else _outcome_of(question.correlation_id, answer)\n except Exception:\n outcome = None\n if outcome is not None:\n return outcome\n question.withdrawn.wait(min(POLL_PAUSE_SECONDS, max(0.0, deadline - time.monotonic())))\n return None\n\n\ndef _advance(question: Question, ask: Ask, deadline: float) -> None:\n try:\n outcome = None if question.correlation_id else _open(question, ask)\n question.outcome = outcome if outcome is not None else _poll(question, deadline)\n except Exception:\n question.outcome = UNAPPROVED\n finally:\n question.step_finished.set()\n\n\ndef _start_step(question: Question, ask: Ask, deadline: float) -> None:\n if not question.step_finished.is_set() or question.usable_outcome() is not None:\n return\n question.outcome = None\n question.step_finished.clear()\n context = contextvars.copy_context()\n context.run(identity.bind_only_session, question.call.session_id)\n threading.Thread(target=context.run, args=(_advance, question, ask, deadline),\n name="pushary-gate-question", daemon=True).start()\n\n\ndef _collect(question: Question) -> Verdict:\n with _lock:\n if question.withdrawn.is_set():\n return UNAPPROVED\n outcome = question.usable_outcome()\n if outcome is None and can_be_retried(question.call) and not question.has_expired():\n question.claimed = False\n return WAITING\n if outcome is not None and not question.has_expired():\n _questions.remove(question)\n return outcome\n _withdraw(lambda open_question: open_question is question)\n return UNAPPROVED\n\n\ndef _may_still_be_decided(question: Question) -> bool:\n return question.usable_outcome() is None and not question.withdrawn.is_set() and not question.has_expired()\n\n\ndef decide(call: GatedCall, budget_seconds: float, ask: Ask) -> Verdict:\n deadline = time.monotonic() + budget_seconds\n question = _claim(call)\n if question is None:\n return UNAPPROVED\n try:\n _withdraw(_is_stale)\n _await_step(question, ask, deadline)\n except Exception:\n _withdraw(lambda open_question: open_question is question)\n raise\n return _collect(question)\n\n\ndef _await_step(question: Question, ask: Ask, deadline: float) -> None:\n while _may_still_be_decided(question) and time.monotonic() < deadline:\n _start_step(question, ask, deadline)\n question.step_finished.wait(max(0.0, deadline - time.monotonic()))\n\n\ndef withdraw_turn(session_id: Optional[str], turn_id: Optional[str] = None) -> Optional[threading.Thread]:\n home = str(installation.hermes_home())\n\n def ended(question: Question) -> bool:\n return belongs_to_turn(question.call, home, str(session_id or ""), str(turn_id or ""))\n\n return _withdraw(ended, Turn(home, str(turn_id)) if turn_id else None)\n' },
|
|
1301
|
+
{ path: "gate.py", contents: 'from __future__ import annotations\n\nimport contextvars\nimport hashlib\nimport json\nimport threading\nimport time\nfrom collections import deque\nfrom typing import Callable, Deque, List, Literal, Mapping, NamedTuple, Optional\n\nfrom . import api, cancellation, identity, installation\n\nANSWER_WINDOW_SECONDS = 600.0\nCREATE_TIMEOUT_SECONDS = 30.0\nREQUEST_GRACE_SECONDS = 2.0\nMIN_POLL_SECONDS = 1.0\nPOLL_PAUSE_SECONDS = 1.0\nLATE_ANSWER_POLL_MS = 1000\nAPPROVAL_REUSE_SECONDS = 5.0\nENDED_TURN_LIMIT = 256\nWAIT_FOR_ANSWER = "wait_for_answer"\n\nVerdict = Literal["allowed", "denied", "undeliverable", "handed_back", "waiting", "unapproved"]\nALLOWED: Verdict = "allowed"\nDENIED: Verdict = "denied"\nUNDELIVERABLE: Verdict = "undeliverable"\nHANDED_BACK: Verdict = "handed_back"\nWAITING: Verdict = "waiting"\nUNAPPROVED: Verdict = "unapproved"\n\nAnswer = Mapping[str, object]\nAsk = Callable[[], Answer]\n\n\nclass GatedCall(NamedTuple):\n home: str\n session_id: str\n turn_id: str\n tool_name: str\n arguments: str\n\n\nclass Turn(NamedTuple):\n home: str\n session_id: str\n turn_id: str\n\n\nclass Question:\n def __init__(self, call: GatedCall) -> None:\n self.call = call\n self.opened_monotonic = time.monotonic()\n self.opened_wall = time.time()\n self.correlation_id = ""\n self.claimed = True\n self.claimed_at = self.opened_monotonic\n self.read_monotonic = self.opened_monotonic\n self.read_wall = self.opened_wall\n self.outcome: Optional[Verdict] = None\n self.withdrawn = threading.Event()\n self.step_finished = threading.Event()\n self.step_finished.set()\n\n def has_expired(self) -> bool:\n return _seconds_since(self.opened_monotonic, self.opened_wall) >= ANSWER_WINDOW_SECONDS\n\n def note_read_started(self) -> None:\n self.read_monotonic = time.monotonic()\n self.read_wall = time.time()\n\n def approval_must_be_read_again(self) -> bool:\n read_by_an_earlier_call = self.read_monotonic < self.claimed_at\n return read_by_an_earlier_call and _seconds_since(self.read_monotonic, self.read_wall) > APPROVAL_REUSE_SECONDS\n\n def usable_outcome(self) -> Optional[Verdict]:\n outcome = self.outcome\n return None if outcome == ALLOWED and self.approval_must_be_read_again() else outcome\n\n\ndef _seconds_since(monotonic: float, wall: float) -> float:\n return max(time.monotonic() - monotonic, time.time() - wall)\n\n\n_questions: List[Question] = []\n_ended_turns: Deque[Turn] = deque(maxlen=ENDED_TURN_LIMIT)\n_lock = threading.Lock()\n\n\ndef gated_call(session_id: Optional[str], turn_id: Optional[str], tool_name: str, args: object) -> GatedCall:\n encoded = json.dumps(args, sort_keys=True, ensure_ascii=True, default=repr)\n digest = hashlib.sha256(encoded.encode("utf-8")).hexdigest()\n return GatedCall(str(installation.hermes_home()), str(session_id or ""), str(turn_id or ""), tool_name, digest)\n\n\ndef is_same_call(asked: GatedCall, retried: GatedCall) -> bool:\n if (asked.home, asked.tool_name, asked.arguments) != (retried.home, retried.tool_name, retried.arguments):\n return False\n if asked.session_id != retried.session_id:\n return False\n if asked.turn_id or retried.turn_id:\n return asked.turn_id == retried.turn_id\n return bool(asked.session_id)\n\n\ndef belongs_to_turn(call: GatedCall, home: str, session_id: str, turn_id: str) -> bool:\n if call.home != home or (session_id and call.session_id != session_id):\n return False\n if turn_id and call.turn_id:\n return call.turn_id == turn_id\n return bool(session_id) and call.session_id == session_id\n\n\ndef can_be_retried(call: GatedCall) -> bool:\n return bool(call.turn_id or call.session_id)\n\n\ndef _may_still_be_answered(answer: Answer) -> bool:\n if answer.get("error"):\n return True\n return answer.get("nextAction") == WAIT_FOR_ANSWER and not answer.get("handoffAction")\n\n\ndef _could_not_be_read(answer: Answer) -> bool:\n return not answer.get("answered") and answer.get("status") == cancellation.UNAVAILABLE_STATUS\n\n\ndef _answered_verdict(answer: Answer) -> Verdict:\n return ALLOWED if api.is_affirmative(answer.get("value")) else DENIED\n\n\ndef _hand_back_verdict(answer: Answer) -> Verdict:\n if answer.get("noDevices"):\n return UNDELIVERABLE\n return HANDED_BACK if answer.get("handoffAction") else UNAPPROVED\n\n\ndef _withdraw_unless_answered(correlation_id: str, hand_back: Verdict) -> Verdict:\n result = cancellation.classify_cancellation(api.cancel_question(correlation_id))\n if result in (cancellation.WITHDRAWN_BY_THIS_CALL, cancellation.CANCELLED_UNPROVEN):\n return hand_back\n if result != cancellation.NOT_PENDING:\n return UNAPPROVED\n late = api.wait_for_answer(correlation_id, LATE_ANSWER_POLL_MS)\n return _answered_verdict(late) if late.get("answered") else UNAPPROVED\n\n\ndef _outcome_of(correlation_id: str, answer: Answer) -> Optional[Verdict]:\n if answer.get("answered"):\n return _answered_verdict(answer)\n if _may_still_be_answered(answer):\n return None\n if answer.get("handoffAction") == cancellation.STOP_HANDOFF:\n return UNAPPROVED\n return _withdraw_unless_answered(correlation_id, _hand_back_verdict(answer))\n\n\ndef _cancel_quietly(correlation_ids: List[str]) -> None:\n for correlation_id in correlation_ids:\n try:\n api.cancel_question(correlation_id)\n except Exception:\n continue\n\n\ndef _in_background(name: str, target: Callable[..., None], *args: object) -> threading.Thread:\n worker = threading.Thread(target=contextvars.copy_context().run, args=(target, *args), name=name, daemon=True)\n worker.start()\n return worker\n\n\ndef _withdraw(should_withdraw: Callable[[Question], bool], ended: Optional[Turn] = None) -> Optional[threading.Thread]:\n with _lock:\n if ended is not None:\n _ended_turns.append(ended)\n withdrawn = [question for question in _questions if should_withdraw(question)]\n _questions[:] = [question for question in _questions if question not in withdrawn]\n for question in withdrawn:\n question.withdrawn.set()\n correlation_ids = [question.correlation_id for question in withdrawn if question.correlation_id]\n if not correlation_ids:\n return None\n return _in_background("pushary-gate-withdraw", _cancel_quietly, correlation_ids)\n\n\ndef _is_stale(question: Question) -> bool:\n return not question.claimed and question.has_expired()\n\n\ndef _claim(call: GatedCall) -> Optional[Question]:\n with _lock:\n if call.turn_id and (Turn(call.home, call.session_id, call.turn_id) in _ended_turns\n or Turn(call.home, "", call.turn_id) in _ended_turns):\n return None\n for question in _questions:\n if not question.claimed and is_same_call(question.call, call):\n question.claimed = True\n question.claimed_at = time.monotonic()\n return question\n opened = Question(call)\n _questions.append(opened)\n return opened\n\n\ndef _open(question: Question, ask: Ask) -> Optional[Verdict]:\n question.note_read_started()\n answer = ask()\n correlation_id = str(answer.get("correlationId") or "")\n if answer.get("error") or not correlation_id:\n return UNAPPROVED\n with _lock:\n question.correlation_id = correlation_id\n withdrawn = question.withdrawn.is_set()\n if withdrawn:\n _cancel_quietly([correlation_id])\n return UNAPPROVED\n return _outcome_of(correlation_id, answer)\n\n\ndef _poll(question: Question, deadline: float) -> Optional[Verdict]:\n while not question.withdrawn.is_set() and time.monotonic() < deadline:\n question.note_read_started()\n wait = max(MIN_POLL_SECONDS, deadline - time.monotonic() - REQUEST_GRACE_SECONDS)\n try:\n answer = api.wait_for_answer(question.correlation_id, int(wait * 1000))\n outcome = None if _could_not_be_read(answer) else _outcome_of(question.correlation_id, answer)\n except Exception:\n outcome = None\n if outcome is not None:\n return outcome\n question.withdrawn.wait(min(POLL_PAUSE_SECONDS, max(0.0, deadline - time.monotonic())))\n return None\n\n\ndef _advance(question: Question, ask: Ask, deadline: float) -> None:\n try:\n outcome = None if question.correlation_id else _open(question, ask)\n question.outcome = outcome if outcome is not None else _poll(question, deadline)\n except Exception:\n question.outcome = UNAPPROVED\n finally:\n question.step_finished.set()\n\n\ndef _start_step(question: Question, ask: Ask, deadline: float) -> None:\n if not question.step_finished.is_set() or question.usable_outcome() is not None:\n return\n question.outcome = None\n question.step_finished.clear()\n context = contextvars.copy_context()\n context.run(identity.bind_only_session, question.call.session_id)\n threading.Thread(target=context.run, args=(_advance, question, ask, deadline),\n name="pushary-gate-question", daemon=True).start()\n\n\ndef _collect(question: Question) -> Verdict:\n with _lock:\n if question.withdrawn.is_set():\n return UNAPPROVED\n outcome = question.usable_outcome()\n if outcome is None and can_be_retried(question.call) and not question.has_expired():\n question.claimed = False\n return WAITING\n if outcome is not None and not question.has_expired():\n _questions.remove(question)\n return outcome\n _withdraw(lambda open_question: open_question is question)\n return UNAPPROVED\n\n\ndef _may_still_be_decided(question: Question) -> bool:\n return question.usable_outcome() is None and not question.withdrawn.is_set() and not question.has_expired()\n\n\ndef decide(call: GatedCall, budget_seconds: float, ask: Ask) -> Verdict:\n deadline = time.monotonic() + budget_seconds\n question = _claim(call)\n if question is None:\n return UNAPPROVED\n try:\n _withdraw(_is_stale)\n _await_step(question, ask, deadline)\n except Exception:\n _withdraw(lambda open_question: open_question is question)\n raise\n return _collect(question)\n\n\ndef _await_step(question: Question, ask: Ask, deadline: float) -> None:\n while _may_still_be_decided(question) and time.monotonic() < deadline:\n _start_step(question, ask, deadline)\n question.step_finished.wait(max(0.0, deadline - time.monotonic()))\n\n\ndef withdraw_turn(session_id: Optional[str], turn_id: Optional[str] = None) -> Optional[threading.Thread]:\n home = str(installation.hermes_home())\n\n def ended(question: Question) -> bool:\n return belongs_to_turn(question.call, home, str(session_id or ""), str(turn_id or ""))\n\n return _withdraw(ended, Turn(home, str(session_id or ""), str(turn_id)) if turn_id else None)\n' },
|
|
1302
1302
|
{ path: "history.py", contents: `from __future__ import annotations
|
|
1303
1303
|
|
|
1304
1304
|
import hashlib
|
|
@@ -2088,7 +2088,7 @@ def record_plugin_load(approval_transport_registered, home=None, pid=None, now=N
|
|
|
2088
2088
|
logger.debug("[pushary] could not record the plugin load: %s", exc)
|
|
2089
2089
|
return None
|
|
2090
2090
|
` },
|
|
2091
|
-
{ path: "plugin.yaml", contents: 'name: pushary\nversion: 1.0.
|
|
2091
|
+
{ path: "plugin.yaml", contents: 'name: pushary\nversion: 1.0.16\ndescription: Push notifications and human-in-the-loop for Hermes Agent via Pushary\nauthor: RalphNex OU\nrequires_env:\n - name: PUSHARY_API_KEY\n description: Your Pushary API key\n url: https://pushary.com/sign-up?from=hermes\n secret: true\nconfig_schema:\n api_key:\n type: secret\n env: PUSHARY_API_KEY\n label: Pushary API key\n description: "Get one at pushary.com/sign-up?from=hermes"\n required: true\nprovides_tools:\n - pushary_remind\n - pushary_notify\n - pushary_ask\n - pushary_wait\n - pushary_cancel\n - pushary_propose_scope\n - pushary_enroll\n - pushary_ask_end_user\nprovides_hooks:\n - pre_llm_call\n - pre_tool_call\n - post_tool_call\n - on_session_start\n - on_session_end\n - on_session_finalize\n - pre_approval_request\n - post_approval_response\nprovides_approval_transports:\n - pushary\n' },
|
|
2092
2092
|
{ path: "README.md", contents: "# Pushary for Hermes\n\nAsk a question in Hermes and answer it on your phone. Try it with your own device before routing command approvals there.\n\n## Connect your phone\n\n1. [Set up your Pushary Agent account](https://pushary.com/sign-up?from=ai-coding&utm_source=hermes-plugin&utm_medium=quickstart&utm_campaign=first-question). Pair your phone with that account and get its API key from Agent settings.\n2. In your terminal, install the catalog plugin:\n\n ```sh\n hermes plugins install pushary\n ```\n\n3. Enter `PUSHARY_API_KEY` when Hermes prompts for it. If you missed the prompt, save the key in the plugin\u2019s settings in Hermes Desktop. Keep it out of chat. Start a new Hermes session (for a running gateway, use `hermes gateway restart`).\n\n## Try one question\n\nTell Hermes: **Use `pushary_ask` to ask me \u201CDid this test reach your phone?\u201D Report my answer and do nothing else.** Open the question on your paired phone and tap **Yes** or **No**. Hermes should report the answer you tapped.\n\nIf nothing arrives, check the account and notification permissions on your phone. A pending question is still live: wait for the same question rather than sending another. If Pushary hands it back to Hermes, answer the local prompt instead. No answer is not approval.\n\nCommand approvals are separate from this test. To route them to your phone, set `security.approval.transport` to `pushary`. Set `security.approval.transport_fallback` to `builtin` if you want Hermes\u2019s local prompt after a safe handoff; an unconfirmed withdrawal does not authorize the command. See the [plugin guide](https://github.com/Pushary/hermes-plugin-pushary#readme) for approval routing and what the plugin reads and sends.\n" },
|
|
2093
2093
|
{ path: "schemas.py", contents: `PUSHARY_REMIND = {
|
|
2094
2094
|
"name": "pushary_remind",
|
|
@@ -4,10 +4,10 @@ import {
|
|
|
4
4
|
keyPrefix,
|
|
5
5
|
readConfigFileKey,
|
|
6
6
|
readMacAppKeyPrefix
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-AT5BTTQS.js";
|
|
8
8
|
import {
|
|
9
9
|
NPX_LATEST_COMMAND
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-IGM6MUL3.js";
|
|
11
11
|
|
|
12
12
|
// src/key-signed-out.ts
|
|
13
13
|
var VERDICT_BY_CHECK = {
|
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
import {
|
|
2
2
|
STOPPED_FROM_PUSHARY_LADDER,
|
|
3
3
|
UNREAD_MODE_LADDER
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-A3OU6RZ5.js";
|
|
5
5
|
import {
|
|
6
6
|
createIo
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-NFFVLIYJ.js";
|
|
8
8
|
import {
|
|
9
9
|
CLAUDE_CODE_AGENT,
|
|
10
10
|
fetchModeState,
|
|
11
11
|
getPolicy
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-OJ5O6VRE.js";
|
|
13
13
|
|
|
14
14
|
// src/cli/hook-wait-ladder.ts
|
|
15
15
|
var readClaudeCodeHookWaitState = async (apiKey) => {
|
|
@@ -9,10 +9,10 @@ import {
|
|
|
9
9
|
} from "./chunk-3EGEA4KH.js";
|
|
10
10
|
import {
|
|
11
11
|
testTrafficHeaders
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-PK24TQTN.js";
|
|
13
13
|
import {
|
|
14
14
|
getBaseUrl
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-QHI4OPBT.js";
|
|
16
16
|
import {
|
|
17
17
|
CLI_LOCAL_BIND_PATH,
|
|
18
18
|
LOCAL_CONFIRM_HOST,
|
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
isLocalConfirmToken,
|
|
24
24
|
isPhonePass,
|
|
25
25
|
localTerminalEntryUrl
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-W7P5GTFI.js";
|
|
27
27
|
|
|
28
28
|
// src/cli/login-ui.ts
|
|
29
29
|
import { hostname } from "os";
|
|
@@ -4,13 +4,13 @@ import {
|
|
|
4
4
|
configFailureKind,
|
|
5
5
|
retryAgentCommand,
|
|
6
6
|
writeSetupConfigFile
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-HSHZJ5Z5.js";
|
|
8
8
|
import {
|
|
9
9
|
MCP_BRIDGE_BINARY
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-K7H7QOHB.js";
|
|
11
11
|
import {
|
|
12
12
|
KEY_FILE_MODE
|
|
13
|
-
} from "./chunk-
|
|
13
|
+
} from "./chunk-AT5BTTQS.js";
|
|
14
14
|
import {
|
|
15
15
|
CLINE_SERVER_NAME_TAKEN,
|
|
16
16
|
CLINE_SETTINGS_REFUSALS,
|
|
@@ -32,10 +32,10 @@ import {
|
|
|
32
32
|
withClinePusharyServer,
|
|
33
33
|
withRefreshedClineKey,
|
|
34
34
|
withoutClinePusharyServer
|
|
35
|
-
} from "./chunk-
|
|
35
|
+
} from "./chunk-SU6M73OQ.js";
|
|
36
36
|
import {
|
|
37
37
|
resolveGlobalBinary
|
|
38
|
-
} from "./chunk-
|
|
38
|
+
} from "./chunk-NYUSDIQJ.js";
|
|
39
39
|
import {
|
|
40
40
|
readJsonSafe,
|
|
41
41
|
writeFileAtomic,
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
OPENCODE_PLUGIN_PLACEHOLDER,
|
|
7
7
|
OPENCODE_PLUGIN_SIBLING,
|
|
8
8
|
OPENCODE_PLUGIN_SIBLING_CONTENTS
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-JO7CKMEZ.js";
|
|
10
10
|
|
|
11
11
|
// src/opencode-runtime-bundle.ts
|
|
12
12
|
var openCodeRuntimeSource = `import { spawn } from 'child_process';
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
pusharyDir
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-SU6M73OQ.js";
|
|
4
4
|
import {
|
|
5
5
|
readJsonSafe
|
|
6
6
|
} from "./chunk-PM2NRK6Y.js";
|
|
7
7
|
import {
|
|
8
8
|
isRecord
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-W7P5GTFI.js";
|
|
10
10
|
|
|
11
11
|
// src/process-ownership.ts
|
|
12
12
|
import { createHash, randomUUID } from "crypto";
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
claudeConfigDir
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-SU6M73OQ.js";
|
|
4
4
|
import {
|
|
5
5
|
claudePermissionRulesFromSettings
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-W7P5GTFI.js";
|
|
7
7
|
|
|
8
8
|
// src/claude-permission-rules.ts
|
|
9
9
|
import { readFileSync, statSync } from "fs";
|
|
@@ -1,20 +1,20 @@
|
|
|
1
1
|
import {
|
|
2
2
|
CODEX_HOOK_STATUS,
|
|
3
3
|
HERMES_HISTORY_HELPER_COMMAND
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-ZUD3ILJI.js";
|
|
5
5
|
import {
|
|
6
6
|
HERMES_ALWAYS_ALLOWED_SHELL_RULE,
|
|
7
7
|
HERMES_COMMAND_ALLOWLIST_KEY,
|
|
8
8
|
HERMES_GATE_TOOLS_KEY,
|
|
9
9
|
HERMES_PLUGIN_ASKS_PAST_ALWAYS_ALLOW,
|
|
10
10
|
HERMES_SHELL_TOOL
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-2NDMTOIT.js";
|
|
12
12
|
import {
|
|
13
13
|
retryAgentCommand
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-HSHZJ5Z5.js";
|
|
15
15
|
import {
|
|
16
16
|
NPX_LATEST_COMMAND
|
|
17
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-IGM6MUL3.js";
|
|
18
18
|
|
|
19
19
|
// src/setup/codex-trust.ts
|
|
20
20
|
var CODEX_TRUST_TELEMETRY = {
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
import {
|
|
2
2
|
UNSET_IGNORED_SHELL_VALUE_STEP
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-T4G54LCL.js";
|
|
4
4
|
import {
|
|
5
5
|
notificationAnswerStep
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-2KFYMPMJ.js";
|
|
7
7
|
import {
|
|
8
8
|
matchMacAccountStep,
|
|
9
9
|
retryAgentCommand
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-HSHZJ5Z5.js";
|
|
11
11
|
import {
|
|
12
12
|
NPX_LATEST_COMMAND,
|
|
13
13
|
npmExecSetupCommandFor
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-IGM6MUL3.js";
|
|
15
15
|
import {
|
|
16
16
|
EXIT
|
|
17
17
|
} from "./chunk-BG4HHB7E.js";
|
|
@@ -21,7 +21,7 @@ import {
|
|
|
21
21
|
import {
|
|
22
22
|
compatibleProfileFor,
|
|
23
23
|
isCompatibleAgentType
|
|
24
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-W7P5GTFI.js";
|
|
25
25
|
|
|
26
26
|
// src/setup/closing.ts
|
|
27
27
|
var ACTIVITY_URL = "pushary.com/dashboard/agent/activity";
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
apiKeyInForce,
|
|
3
3
|
configFilePath,
|
|
4
4
|
keyPrefixToShow
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-QHI4OPBT.js";
|
|
6
6
|
import {
|
|
7
7
|
backupFile,
|
|
8
8
|
backupFileInto,
|
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
isRecord,
|
|
16
16
|
isValidApiKey,
|
|
17
17
|
normalizeInstallSource
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-W7P5GTFI.js";
|
|
19
19
|
|
|
20
20
|
// src/install-source.ts
|
|
21
21
|
import { readFileSync } from "fs";
|
|
@@ -3,13 +3,13 @@ import {
|
|
|
3
3
|
} from "./chunk-WHB622LP.js";
|
|
4
4
|
import {
|
|
5
5
|
ensureDaemonRunning
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-MG65IOEE.js";
|
|
7
7
|
import {
|
|
8
8
|
hookOwnerOf
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-FO2HOIYA.js";
|
|
10
10
|
import {
|
|
11
11
|
hookMeaning
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-OSI26PGT.js";
|
|
13
13
|
import {
|
|
14
14
|
buildTranscriptRecords,
|
|
15
15
|
changedRecipientsMessage,
|
|
@@ -24,11 +24,11 @@ import {
|
|
|
24
24
|
uploadTranscriptRecords,
|
|
25
25
|
verifyAnchoredRecipients,
|
|
26
26
|
wrapSessionKey
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-P7PXAD2O.js";
|
|
28
28
|
import {
|
|
29
29
|
transcriptEnvironmentPreference,
|
|
30
30
|
transcriptsEnabled
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-XCHF5GNH.js";
|
|
32
32
|
import {
|
|
33
33
|
external_exports,
|
|
34
34
|
ownedOnlyByThisUser,
|
|
@@ -36,19 +36,19 @@ import {
|
|
|
36
36
|
} from "./chunk-P6DUWKAO.js";
|
|
37
37
|
import {
|
|
38
38
|
fetchAsCredential
|
|
39
|
-
} from "./chunk-
|
|
39
|
+
} from "./chunk-YLOW6PDN.js";
|
|
40
40
|
import {
|
|
41
41
|
readTranscriptPreference
|
|
42
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-AT5BTTQS.js";
|
|
43
43
|
import {
|
|
44
44
|
claudeConfigDir,
|
|
45
45
|
codexHome,
|
|
46
46
|
pusharyDir
|
|
47
|
-
} from "./chunk-
|
|
47
|
+
} from "./chunk-SU6M73OQ.js";
|
|
48
48
|
import {
|
|
49
49
|
getApiKey,
|
|
50
50
|
getBaseUrl
|
|
51
|
-
} from "./chunk-
|
|
51
|
+
} from "./chunk-QHI4OPBT.js";
|
|
52
52
|
import {
|
|
53
53
|
writeJsonAtomic,
|
|
54
54
|
writeJsonAtomicDurable
|
|
@@ -61,7 +61,7 @@ import {
|
|
|
61
61
|
isHookSource,
|
|
62
62
|
isRecord,
|
|
63
63
|
redactSecretsFromContent
|
|
64
|
-
} from "./chunk-
|
|
64
|
+
} from "./chunk-W7P5GTFI.js";
|
|
65
65
|
|
|
66
66
|
// src/transcript-registration.ts
|
|
67
67
|
import { createHash as createHash4 } from "crypto";
|
|
@@ -4,21 +4,21 @@ import {
|
|
|
4
4
|
claimThrottle,
|
|
5
5
|
releaseThrottle,
|
|
6
6
|
reportEvent
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-OJ5O6VRE.js";
|
|
8
8
|
import {
|
|
9
9
|
deriveToolTarget,
|
|
10
10
|
permissionDeniedAction
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-OSI26PGT.js";
|
|
12
12
|
import {
|
|
13
13
|
projectNameFor
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-Q3NFM2TB.js";
|
|
15
15
|
import {
|
|
16
16
|
PERMISSION_ALLOWED_EVENT,
|
|
17
17
|
PERMISSION_DENIED_EVENT,
|
|
18
18
|
machineApprovalFor,
|
|
19
19
|
machineDecisionFor,
|
|
20
20
|
wireVerdictFor
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-W7P5GTFI.js";
|
|
22
22
|
|
|
23
23
|
// src/machine-decision-audit.ts
|
|
24
24
|
var MACHINE_DECISION_REPORT_TIMEOUT_MS = 800;
|