pushary 1.9.273 → 1.9.274
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 +9 -0
- package/dist/bin/pushary-clean.js +1 -1
- package/dist/bin/pushary-codex-hook.js +1 -1
- package/dist/bin/pushary-daemon.js +2 -2
- package/dist/bin/pushary-doctor.js +5 -4
- package/dist/bin/pushary-login.js +2 -2
- package/dist/bin/pushary-session-start-hook.js +2 -2
- package/dist/bin/pushary-setup.js +3 -3
- package/dist/bin/pushary-upgrade.js +3 -3
- package/dist/{chunk-4ABPC46K.js → chunk-AGIAZ7RG.js} +3 -3
- package/dist/{chunk-B5UMFUDM.js → chunk-TUWADETS.js} +140 -468
- package/dist/{chunk-FFRI5JDM.js → chunk-V4U3UE2D.js} +5 -4
- package/dist/{chunk-ZHHPX5GG.js → chunk-Z3JYKLYD.js} +1 -1
- package/dist/{reapply-G6PMYS6P.js → reapply-PRZDZU3C.js} +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.9.274
|
|
4
|
+
|
|
5
|
+
- Setup now installs Hermes plugin 1.0.14. A tool named in `PUSHARY_GATE_TOOLS` is asked about on your phone also when Pushary is Hermes's approval transport, which setup selects, and when Hermes's approvals are off. Before, the question went to Hermes's own prompt and never to the phone, and with Hermes's approvals off the tool ran with nobody asked.
|
|
6
|
+
- A gated call nobody has answered yet no longer runs past Hermes's hook limit, after which Hermes blocked every tool for a minute. The question stays open, and the same call made again collects the answer.
|
|
7
|
+
- In a Hermes gateway that serves several profiles, an approval uses the key, home and session of the profile that raised it. A profile's own `PUSHARY_GATE_TOOLS` adds to the list the gateway was started with.
|
|
8
|
+
- The end of a Hermes turn withdraws a gated call's question, and a yes after that never runs the call. An answer more than 10 minutes late is not used.
|
|
9
|
+
- `doctor` says that an Always allow for `terminal` only lets commands through on a Hermes plugin older than 1.0.14. It no longer warns about it when the plugin Hermes runs is 1.0.14 or later.
|
|
10
|
+
- Two changes for anyone using `PUSHARY_GATE_TOOLS` with Pushary as the approval transport. A gated call is now a plain yes or no for that one call, so **Allow for this session** and **Always allow** no longer apply to it. And when Pushary is not asking the phone (In agent, Notify only, phone asks paused, or no device connected), the call is blocked instead of going to Hermes's own prompt.
|
|
11
|
+
|
|
3
12
|
## 1.9.273
|
|
4
13
|
|
|
5
14
|
- A program held in a variable or printed by a plain `echo` or `printf` is also judged by its name. Under an allow rule, `x=rm; $x -rf ~` and `$(echo rm) -rf ~` ran; they now wait, as `rm -rf ~` does. The same covers options, such as `rsync -a $(echo --delete) src/ dst/`. A variable is read when it is assigned a plain word earlier in the same shell and is the program of a step. One behind `env`, `nice`, `timeout`, `xargs` or `find -exec`, copied from another variable, or set by a `for` loop is still not read.
|
|
@@ -1085,7 +1085,7 @@ var decidePreToolUse = async (input) => {
|
|
|
1085
1085
|
};
|
|
1086
1086
|
var repairCodexHoldsQuietly = async () => {
|
|
1087
1087
|
try {
|
|
1088
|
-
const { repairCodexHolds } = await import("../reapply-
|
|
1088
|
+
const { repairCodexHolds } = await import("../reapply-PRZDZU3C.js");
|
|
1089
1089
|
repairCodexHolds();
|
|
1090
1090
|
} catch {
|
|
1091
1091
|
return;
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
import "../chunk-YWM6DGX3.js";
|
|
7
7
|
import {
|
|
8
8
|
inspectConfiguredManagedProviders
|
|
9
|
-
} from "../chunk-
|
|
9
|
+
} from "../chunk-Z3JYKLYD.js";
|
|
10
10
|
import "../chunk-TWWOQKXK.js";
|
|
11
11
|
import "../chunk-D5ZK4VY5.js";
|
|
12
12
|
import {
|
|
@@ -25,7 +25,7 @@ import {
|
|
|
25
25
|
HERMES_INSTALL_MARKER_FILE,
|
|
26
26
|
defaultHermesHome,
|
|
27
27
|
parseHermesInstallMarker
|
|
28
|
-
} from "../chunk-
|
|
28
|
+
} from "../chunk-TUWADETS.js";
|
|
29
29
|
import {
|
|
30
30
|
writeHuman
|
|
31
31
|
} from "../chunk-QCGNGEGE.js";
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
openClawRepairStep,
|
|
5
5
|
readHermesShellGate,
|
|
6
6
|
readSetupFailure
|
|
7
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-AGIAZ7RG.js";
|
|
8
8
|
import {
|
|
9
9
|
CODEX_HOOK_REMEDY,
|
|
10
10
|
HERMES_RESTART_COMMAND,
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
describeHermesShellGate,
|
|
13
13
|
describeHermesState,
|
|
14
14
|
hermesRepairStep
|
|
15
|
-
} from "../chunk-
|
|
15
|
+
} from "../chunk-V4U3UE2D.js";
|
|
16
16
|
import {
|
|
17
17
|
describeWaitLadder,
|
|
18
18
|
waitRuleLabelOf
|
|
@@ -73,6 +73,7 @@ import {
|
|
|
73
73
|
findHermesLauncher,
|
|
74
74
|
hasUpdateFrom,
|
|
75
75
|
hermesPluginDirectory,
|
|
76
|
+
hermesPluginVersionInUse,
|
|
76
77
|
hermesSetupWasRecorded,
|
|
77
78
|
hermesWiringOwner,
|
|
78
79
|
inspectHermesWiring,
|
|
@@ -82,7 +83,7 @@ import {
|
|
|
82
83
|
routesHermesQuestions,
|
|
83
84
|
runsAnOlderPlugin,
|
|
84
85
|
shippedHermesPlugin
|
|
85
|
-
} from "../chunk-
|
|
86
|
+
} from "../chunk-TUWADETS.js";
|
|
86
87
|
import "../chunk-QCGNGEGE.js";
|
|
87
88
|
import {
|
|
88
89
|
findOpenClawLauncher,
|
|
@@ -1615,7 +1616,7 @@ var main = async () => {
|
|
|
1615
1616
|
if (hermes.kind === "inspected" && (hermes.state.kind !== "not_wired" || hermesSetupRecorded)) {
|
|
1616
1617
|
checking("Hermes");
|
|
1617
1618
|
reportHermesWiring(hermes);
|
|
1618
|
-
reportHermesShellGate(describeHermesShellGate(await readHermesShellGate(hermes.launcher)));
|
|
1619
|
+
reportHermesShellGate(describeHermesShellGate(await readHermesShellGate(hermes.launcher, hermesPluginVersionInUse(hermes.state))));
|
|
1619
1620
|
} else if (hermes.kind === "unreadable" && hermesSetupRecorded) {
|
|
1620
1621
|
check(false, "Hermes: settings readable", `Hermes would not report its settings through hermes config get \u2014 run hermes update, then ${hermesRepairStep(existsSync(hermesAppWiringRecord()) ? "mac_app" : "cli")}`);
|
|
1621
1622
|
} else {
|
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
import "../chunk-PUZZELE6.js";
|
|
14
14
|
import {
|
|
15
15
|
refreshEmbeddedAgentKeys
|
|
16
|
-
} from "../chunk-
|
|
16
|
+
} from "../chunk-Z3JYKLYD.js";
|
|
17
17
|
import "../chunk-TWWOQKXK.js";
|
|
18
18
|
import {
|
|
19
19
|
writeJsonError,
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
import "../chunk-3EGEA4KH.js";
|
|
23
23
|
import "../chunk-KIJZSOAD.js";
|
|
24
24
|
import "../chunk-TFSXOOKJ.js";
|
|
25
|
-
import "../chunk-
|
|
25
|
+
import "../chunk-TUWADETS.js";
|
|
26
26
|
import "../chunk-33OPFYPX.js";
|
|
27
27
|
import "../chunk-E6RGE25R.js";
|
|
28
28
|
import "../chunk-FW6JKPTU.js";
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import {
|
|
3
3
|
reapplyClaudeForVersion
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-Z3JYKLYD.js";
|
|
5
5
|
import "../chunk-TWWOQKXK.js";
|
|
6
6
|
import "../chunk-TFSXOOKJ.js";
|
|
7
|
-
import "../chunk-
|
|
7
|
+
import "../chunk-TUWADETS.js";
|
|
8
8
|
import "../chunk-33OPFYPX.js";
|
|
9
9
|
import "../chunk-E6RGE25R.js";
|
|
10
10
|
import "../chunk-FW6JKPTU.js";
|
|
@@ -90,7 +90,7 @@ import {
|
|
|
90
90
|
gateHermesShell,
|
|
91
91
|
readHermesShellGate,
|
|
92
92
|
saveSetupFailure
|
|
93
|
-
} from "../chunk-
|
|
93
|
+
} from "../chunk-AGIAZ7RG.js";
|
|
94
94
|
import {
|
|
95
95
|
CODEX_NEEDS_A_NEWER_VERSION,
|
|
96
96
|
CODEX_SETTINGS_STOP_A_HOOK,
|
|
@@ -106,7 +106,7 @@ import {
|
|
|
106
106
|
describeHermesState,
|
|
107
107
|
hermesGateShellCommand,
|
|
108
108
|
needsCodexTrustStep
|
|
109
|
-
} from "../chunk-
|
|
109
|
+
} from "../chunk-V4U3UE2D.js";
|
|
110
110
|
import {
|
|
111
111
|
describeWaitLadder
|
|
112
112
|
} from "../chunk-HCYAMXSY.js";
|
|
@@ -233,7 +233,7 @@ import {
|
|
|
233
233
|
routesHermesQuestions,
|
|
234
234
|
runsAnOlderPlugin,
|
|
235
235
|
shippedHermesPlugin
|
|
236
|
-
} from "../chunk-
|
|
236
|
+
} from "../chunk-TUWADETS.js";
|
|
237
237
|
import {
|
|
238
238
|
setHumanStream
|
|
239
239
|
} from "../chunk-QCGNGEGE.js";
|
|
@@ -29,13 +29,13 @@ import "../chunk-BSUHG6MP.js";
|
|
|
29
29
|
import {
|
|
30
30
|
ensureCodexTrustAfterReapply,
|
|
31
31
|
reapplyAllAgents
|
|
32
|
-
} from "../chunk-
|
|
32
|
+
} from "../chunk-Z3JYKLYD.js";
|
|
33
33
|
import "../chunk-TWWOQKXK.js";
|
|
34
34
|
import {
|
|
35
35
|
HERMES_RESTART_COMMAND,
|
|
36
36
|
describeCodexTrustConfirmation,
|
|
37
37
|
describeHermesHistoryHelperRecord
|
|
38
|
-
} from "../chunk-
|
|
38
|
+
} from "../chunk-V4U3UE2D.js";
|
|
39
39
|
import "../chunk-KIJZSOAD.js";
|
|
40
40
|
import {
|
|
41
41
|
keepLinuxDaemonAfterLogout,
|
|
@@ -54,7 +54,7 @@ import {
|
|
|
54
54
|
import {
|
|
55
55
|
readMacAppAgentKey
|
|
56
56
|
} from "../chunk-JCNBJAG3.js";
|
|
57
|
-
import "../chunk-
|
|
57
|
+
import "../chunk-TUWADETS.js";
|
|
58
58
|
import "../chunk-33OPFYPX.js";
|
|
59
59
|
import {
|
|
60
60
|
FX_RELOAD_AFTER_BRIDGE,
|
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
settingSnapshot,
|
|
19
19
|
writeHermesSetting,
|
|
20
20
|
writeSetupReceipt
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-TUWADETS.js";
|
|
22
22
|
import {
|
|
23
23
|
OPENCLAW_MIN_VERSION,
|
|
24
24
|
OPENCLAW_PLUGIN_ID,
|
|
@@ -40,7 +40,7 @@ import {
|
|
|
40
40
|
} from "./chunk-ZHMA3XMN.js";
|
|
41
41
|
|
|
42
42
|
// src/hermes/shell-gate.ts
|
|
43
|
-
var readHermesShellGate = async (launcher) => {
|
|
43
|
+
var readHermesShellGate = async (launcher, pluginVersion = null) => {
|
|
44
44
|
const [terminal, terminalEnv, dockerVolumes, dockerMountCwd, gateReading, allowlist, transport] = await Promise.all([
|
|
45
45
|
readHermesSetting(launcher, HERMES_TERMINAL_SECTION),
|
|
46
46
|
readHermesSetting(launcher, HERMES_TERMINAL_ENV_KEY),
|
|
@@ -53,7 +53,7 @@ var readHermesShellGate = async (launcher) => {
|
|
|
53
53
|
return hermesShellGateState({
|
|
54
54
|
coverage: hermesApprovalCoverage({ terminal, terminalEnv, dockerVolumes, dockerMountCwd }),
|
|
55
55
|
gate: hermesGateToolsFrom(gateReading),
|
|
56
|
-
alwaysAllowed: hermesAlwaysAllowsShell({ allowlist, transport })
|
|
56
|
+
alwaysAllowed: hermesAlwaysAllowsShell({ allowlist, transport, pluginVersion })
|
|
57
57
|
});
|
|
58
58
|
};
|
|
59
59
|
var RECEIPT_FAILURES = {
|
|
@@ -29,6 +29,10 @@ import {
|
|
|
29
29
|
openClawPluginFolder,
|
|
30
30
|
openClawSetupReceiptDirectory
|
|
31
31
|
} from "./chunk-K6UVBV3O.js";
|
|
32
|
+
import {
|
|
33
|
+
atLeast,
|
|
34
|
+
parseVersion
|
|
35
|
+
} from "./chunk-6ICPEJY5.js";
|
|
32
36
|
import {
|
|
33
37
|
resolvePathBinary
|
|
34
38
|
} from "./chunk-LFPNXVGA.js";
|
|
@@ -55,7 +59,7 @@ import os
|
|
|
55
59
|
import threading
|
|
56
60
|
from pathlib import Path
|
|
57
61
|
|
|
58
|
-
from . import api, approval, approval_coverage, history, host, identity, installation, schemas, tools
|
|
62
|
+
from . import api, approval, approval_coverage, gate, history, host, identity, installation, schemas, tools
|
|
59
63
|
|
|
60
64
|
logger = logging.getLogger(__name__)
|
|
61
65
|
|
|
@@ -113,6 +117,8 @@ _session_totals = {"tools": 0, "errors": 0}
|
|
|
113
117
|
_last_turn = {"completed": False, "interrupted": False}
|
|
114
118
|
_plugin_activity = {"attempted": False}
|
|
115
119
|
_plugin_activity_lock = threading.Lock()
|
|
120
|
+
_known_gated_tools = set()
|
|
121
|
+
_known_gated_tools_lock = threading.Lock()
|
|
116
122
|
|
|
117
123
|
|
|
118
124
|
def register(ctx):
|
|
@@ -132,6 +138,7 @@ def register(ctx):
|
|
|
132
138
|
"on_session_start": _on_session_start,
|
|
133
139
|
"on_session_end": _on_session_end,
|
|
134
140
|
"on_session_finalize": _on_session_finalize,
|
|
141
|
+
"pre_approval_request": _on_pre_approval_request,
|
|
135
142
|
"post_approval_response": _on_post_approval_response,
|
|
136
143
|
}
|
|
137
144
|
for hook_name, callback in hooks.items():
|
|
@@ -180,9 +187,24 @@ def _register_system_prompt_section(ctx):
|
|
|
180
187
|
logger.debug("[pushary] system prompt section unavailable: %s", exc)
|
|
181
188
|
|
|
182
189
|
|
|
190
|
+
def _tool_names(raw):
|
|
191
|
+
return {name.strip().lower() for name in (raw or "").split(approval_coverage.GATE_TOOLS_SEPARATOR) if name.strip()}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _gate_list():
|
|
195
|
+
process = _tool_names(os.environ.get(approval_coverage.GATE_TOOLS_ENV))
|
|
196
|
+
try:
|
|
197
|
+
profile = _tool_names(host.read_profile_setting(approval_coverage.GATE_TOOLS_ENV))
|
|
198
|
+
except Exception:
|
|
199
|
+
with _known_gated_tools_lock:
|
|
200
|
+
return process | _known_gated_tools, False
|
|
201
|
+
with _known_gated_tools_lock:
|
|
202
|
+
_known_gated_tools.update(profile)
|
|
203
|
+
return process | profile, True
|
|
204
|
+
|
|
205
|
+
|
|
183
206
|
def _gated_tools():
|
|
184
|
-
|
|
185
|
-
return {name.strip().lower() for name in raw.split(approval_coverage.GATE_TOOLS_SEPARATOR) if name.strip()}
|
|
207
|
+
return _gate_list()[0]
|
|
186
208
|
|
|
187
209
|
|
|
188
210
|
def _warn_when_hermes_skips_the_shell():
|
|
@@ -254,9 +276,6 @@ def _arg_target(args):
|
|
|
254
276
|
return None
|
|
255
277
|
|
|
256
278
|
|
|
257
|
-
_APPROVE_VALUES = {"yes", "y", "true", "approve", "approved", "allow", "ok"}
|
|
258
|
-
|
|
259
|
-
|
|
260
279
|
def _block_unapproved(tool_name):
|
|
261
280
|
return {
|
|
262
281
|
"action": "block",
|
|
@@ -264,19 +283,9 @@ def _block_unapproved(tool_name):
|
|
|
264
283
|
}
|
|
265
284
|
|
|
266
285
|
|
|
267
|
-
def _escalate_to_host_gate(tool_name, args):
|
|
268
|
-
summary = _summarize_args(args)
|
|
269
|
-
detail = f"\\n{summary}" if summary else ""
|
|
270
|
-
return {
|
|
271
|
-
"action": "approve",
|
|
272
|
-
"message": f"Run {tool_name}?{detail}"[:500],
|
|
273
|
-
"rule_key": tool_name,
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
|
|
277
286
|
def _requested_gate_seconds():
|
|
278
287
|
try:
|
|
279
|
-
return int(
|
|
288
|
+
return int(host.profile_setting("PUSHARY_GATE_TIMEOUT_MS") or "55000") / 1000
|
|
280
289
|
except (TypeError, ValueError):
|
|
281
290
|
return host.GATE_MAX_SECONDS
|
|
282
291
|
|
|
@@ -286,12 +295,73 @@ def _block_undeliverable(tool_name):
|
|
|
286
295
|
"action": "block",
|
|
287
296
|
"message": (
|
|
288
297
|
f"'{tool_name}' is gated by Pushary but no phone, browser, or Slack "
|
|
289
|
-
"channel is connected to approve on, so nobody could be asked.
|
|
290
|
-
"this session
|
|
298
|
+
"channel is connected to approve on, so nobody could be asked. An answer in "
|
|
299
|
+
"this session cannot unlock it. Connect a device in the Pushary dashboard, or "
|
|
300
|
+
f"remove '{tool_name}' from {approval_coverage.GATE_TOOLS_ENV}."
|
|
301
|
+
),
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _block_handed_back(tool_name):
|
|
306
|
+
return {
|
|
307
|
+
"action": "block",
|
|
308
|
+
"message": (
|
|
309
|
+
f"'{tool_name}' was blocked: Pushary gates it, but is not asking on the phone right now: its mode answers in "
|
|
310
|
+
"the agent, only notifies, or pushes are paused. An answer in this session cannot unlock it. Tell the user "
|
|
311
|
+
f"to change the mode in Pushary, or remove '{tool_name}' from {approval_coverage.GATE_TOOLS_ENV}."
|
|
312
|
+
),
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _block_waiting(tool_name):
|
|
317
|
+
return {
|
|
318
|
+
"action": "block",
|
|
319
|
+
"message": (
|
|
320
|
+
f"'{tool_name}' has not run. Pushary is asking the user and has no answer yet. Call {tool_name} again "
|
|
321
|
+
"with exactly the same arguments to keep waiting for the answer. Do not change the arguments, use "
|
|
322
|
+
"another tool for the same outcome, or treat the wait as approval."
|
|
291
323
|
),
|
|
292
324
|
}
|
|
293
325
|
|
|
294
326
|
|
|
327
|
+
def _ask_about_gated_call(tool_name, args):
|
|
328
|
+
def ask():
|
|
329
|
+
lines = _redacted_arg_lines(args)
|
|
330
|
+
return api.ask_user(
|
|
331
|
+
f"Allow Hermes to run \`{tool_name}\`?",
|
|
332
|
+
question_type="confirm",
|
|
333
|
+
context=_summary_of(lines),
|
|
334
|
+
agent_name=identity.agent_name(),
|
|
335
|
+
wait=False,
|
|
336
|
+
create_timeout_seconds=gate.CREATE_TIMEOUT_SECONDS,
|
|
337
|
+
tool_name=tool_name,
|
|
338
|
+
tool_target=_arg_target(args),
|
|
339
|
+
action_body=_gated_call_action_body(tool_name, lines),
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
return ask
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _gate_verdict(tool_name, name, args, session_id, turn_id):
|
|
346
|
+
try:
|
|
347
|
+
call = gate.gated_call(session_id, turn_id, name, args)
|
|
348
|
+
return gate.decide(call, host.gate_budget_seconds(_requested_gate_seconds()), _ask_about_gated_call(tool_name, args))
|
|
349
|
+
except Exception:
|
|
350
|
+
return gate.UNAPPROVED
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def _gate_directive(tool_name, verdict):
|
|
354
|
+
if verdict == gate.ALLOWED:
|
|
355
|
+
return None
|
|
356
|
+
if verdict == gate.DENIED:
|
|
357
|
+
return {"action": "block", "message": f"Denied from Pushary: '{tool_name}' was not approved by the user."}
|
|
358
|
+
if verdict == gate.WAITING:
|
|
359
|
+
return _block_waiting(tool_name)
|
|
360
|
+
if verdict == gate.HANDED_BACK:
|
|
361
|
+
return _block_handed_back(tool_name)
|
|
362
|
+
return _block_undeliverable(tool_name) if verdict == gate.UNDELIVERABLE else _block_unapproved(tool_name)
|
|
363
|
+
|
|
364
|
+
|
|
295
365
|
def _redirects_question_tool(tool_name):
|
|
296
366
|
return (
|
|
297
367
|
(tool_name or "").lower() == HERMES_QUESTION_TOOL
|
|
@@ -300,13 +370,13 @@ def _redirects_question_tool(tool_name):
|
|
|
300
370
|
)
|
|
301
371
|
|
|
302
372
|
|
|
303
|
-
def _on_pre_tool_call(tool_name=None, args=None, session_id=None, **kwargs):
|
|
373
|
+
def _on_pre_tool_call(tool_name=None, args=None, session_id=None, turn_id=None, **kwargs):
|
|
304
374
|
identity.remember_session(session_id)
|
|
305
375
|
|
|
306
376
|
if _redirects_question_tool(tool_name):
|
|
307
377
|
return {"action": "block", "message": QUESTION_TOOL_REDIRECT}
|
|
308
378
|
|
|
309
|
-
gated =
|
|
379
|
+
gated, readable = _gate_list()
|
|
310
380
|
if not gated:
|
|
311
381
|
return None
|
|
312
382
|
|
|
@@ -316,63 +386,23 @@ def _on_pre_tool_call(tool_name=None, args=None, session_id=None, **kwargs):
|
|
|
316
386
|
if name not in gated:
|
|
317
387
|
return None
|
|
318
388
|
|
|
319
|
-
if
|
|
320
|
-
return _escalate_to_host_gate(tool_name, args)
|
|
321
|
-
|
|
322
|
-
if not api.is_configured():
|
|
389
|
+
if not readable or not api.is_configured():
|
|
323
390
|
return _block_unapproved(tool_name)
|
|
391
|
+
return _gate_directive(tool_name, _gate_verdict(tool_name, name, args, session_id, turn_id))
|
|
324
392
|
|
|
325
|
-
try:
|
|
326
|
-
budget_ms = int(host.gate_budget_seconds(_requested_gate_seconds()) * 1000)
|
|
327
|
-
lines = _redacted_arg_lines(args)
|
|
328
|
-
result = json.loads(tools.pushary_ask({
|
|
329
|
-
"question": f"Allow Hermes to run \`{tool_name}\`?",
|
|
330
|
-
"type": "confirm",
|
|
331
|
-
"context": _summary_of(lines),
|
|
332
|
-
"agent_name": identity.agent_name(),
|
|
333
|
-
"tool_name": tool_name,
|
|
334
|
-
"tool_target": _arg_target(args),
|
|
335
|
-
"action_body": _gated_call_action_body(tool_name, lines),
|
|
336
|
-
"wait": True,
|
|
337
|
-
"timeout_ms": budget_ms,
|
|
338
|
-
}))
|
|
339
|
-
if "error" in result:
|
|
340
|
-
return _block_unapproved(tool_name)
|
|
341
|
-
|
|
342
|
-
correlation_id = result.get("correlationId")
|
|
343
|
-
if not correlation_id:
|
|
344
|
-
return _block_unapproved(tool_name)
|
|
345
|
-
|
|
346
|
-
answer = result
|
|
347
|
-
if result.get("handoffAction") == "cancel_then_ask_in_current_client":
|
|
348
|
-
cancellation = api.cancel_question(correlation_id)
|
|
349
|
-
if cancellation.get("handoffAction") == "stop":
|
|
350
|
-
return _block_unapproved(tool_name)
|
|
351
|
-
if not cancellation.get("cancelled"):
|
|
352
|
-
answer = api.wait_for_answer(correlation_id, 1000)
|
|
353
|
-
|
|
354
|
-
if answer.get("answered"):
|
|
355
|
-
if str(answer.get("value", "")).strip().lower() in _APPROVE_VALUES:
|
|
356
|
-
return None
|
|
357
|
-
return {"action": "block", "message": f"Denied from Pushary: '{tool_name}' was not approved by the user."}
|
|
358
|
-
|
|
359
|
-
if answer.get("error"):
|
|
360
|
-
return _block_unapproved(tool_name)
|
|
361
393
|
|
|
362
|
-
|
|
363
|
-
api.cancel_question(correlation_id)
|
|
364
|
-
if result.get("noDevices"):
|
|
365
|
-
return _block_undeliverable(tool_name)
|
|
366
|
-
return _block_unapproved(tool_name)
|
|
367
|
-
except Exception:
|
|
368
|
-
return _block_unapproved(tool_name)
|
|
394
|
+
PUSHARY_TRANSPORT_SURFACE = f"transport:{host.TRANSPORT_NAME}"
|
|
369
395
|
|
|
370
396
|
|
|
371
|
-
|
|
397
|
+
def _on_pre_approval_request(surface=None, request_id=None, session_id=None, **kwargs):
|
|
398
|
+
if surface == PUSHARY_TRANSPORT_SURFACE and request_id:
|
|
399
|
+
approval.remember_requester(str(request_id), session_id)
|
|
400
|
+
return None
|
|
372
401
|
|
|
373
402
|
|
|
374
403
|
def _on_post_approval_response(choice=None, surface=None, request_id=None, **kwargs):
|
|
375
404
|
if surface == PUSHARY_TRANSPORT_SURFACE and request_id:
|
|
405
|
+
approval.forget_requester(str(request_id))
|
|
376
406
|
approval.record_host_outcome(str(request_id), choice)
|
|
377
407
|
return None
|
|
378
408
|
|
|
@@ -455,9 +485,17 @@ def _turn_failure_reason(failed, interrupted, turn_exit_reason):
|
|
|
455
485
|
return reason[:FAILED_TURN_REASON_MAX_LENGTH]
|
|
456
486
|
|
|
457
487
|
|
|
488
|
+
def _withdraw_gated_questions(session_id, turn_id):
|
|
489
|
+
try:
|
|
490
|
+
gate.withdraw_turn(session_id, turn_id)
|
|
491
|
+
except Exception:
|
|
492
|
+
logger.warning("[pushary] could not withdraw this turn's gated questions", exc_info=True)
|
|
493
|
+
|
|
494
|
+
|
|
458
495
|
def _on_session_end(session_id=None, completed=False, interrupted=False, failed=False,
|
|
459
|
-
turn_exit_reason=None, **kwargs):
|
|
496
|
+
turn_exit_reason=None, turn_id=None, **kwargs):
|
|
460
497
|
identity.remember_session(session_id)
|
|
498
|
+
_withdraw_gated_questions(session_id, turn_id)
|
|
461
499
|
_last_turn.update(completed=bool(completed), interrupted=bool(interrupted))
|
|
462
500
|
_report_session_event(
|
|
463
501
|
"session_end",
|
|
@@ -467,6 +505,7 @@ def _on_session_end(session_id=None, completed=False, interrupted=False, failed=
|
|
|
467
505
|
|
|
468
506
|
|
|
469
507
|
def _on_session_finalize(session_id=None, **kwargs):
|
|
508
|
+
_withdraw_gated_questions(session_id, None)
|
|
470
509
|
history.stop_history(session_id or identity.session_id())
|
|
471
510
|
_report_session_event("session_closed", session_id or identity.session_id())
|
|
472
511
|
tool_count = _session_totals["tools"]
|
|
@@ -750,7 +789,14 @@ def agent_event(event, session_id, can_drain=False, error=None):
|
|
|
750
789
|
return {"error": str(exc)}
|
|
751
790
|
|
|
752
791
|
|
|
753
|
-
def
|
|
792
|
+
def _request_timeout_seconds(tool_name, params):
|
|
793
|
+
if tool_name == "cancel_question":
|
|
794
|
+
return 4
|
|
795
|
+
blocking = tool_name in ("wait_for_answer", "propose_scope") or (tool_name == "ask_user" and params.get("wait", True))
|
|
796
|
+
return min(max(params.get("timeoutMs", 30000), 1000), 55000) / 1000 + 2 if blocking else 10
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
def _mcp_call(tool_name, params, timeout_seconds=None):
|
|
754
800
|
api_key = _get_api_key()
|
|
755
801
|
url = f"{BASE_URL}/api/mcp/mcp"
|
|
756
802
|
payload = json.dumps({
|
|
@@ -771,8 +817,7 @@ def _mcp_call(tool_name, params):
|
|
|
771
817
|
method="POST",
|
|
772
818
|
)
|
|
773
819
|
|
|
774
|
-
|
|
775
|
-
timeout = min(max(params.get("timeoutMs", 30000), 1000), 55000) / 1000 + 2 if blocking else 4 if tool_name == "cancel_question" else 10
|
|
820
|
+
timeout = timeout_seconds or _request_timeout_seconds(tool_name, params)
|
|
776
821
|
try:
|
|
777
822
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
778
823
|
raw = resp.read().decode("utf-8")
|
|
@@ -872,7 +917,7 @@ def schedule_reminder(body=None, title=None, in_minutes=None, at=None,
|
|
|
872
917
|
|
|
873
918
|
|
|
874
919
|
def ask_user(question, question_type="confirm", options=None, placeholder=None,
|
|
875
|
-
context=None, agent_name=None, wait=True, timeout_ms=None, **decision):
|
|
920
|
+
context=None, agent_name=None, wait=True, timeout_ms=None, create_timeout_seconds=None, **decision):
|
|
876
921
|
params = {"question": question, "type": question_type, "wait": wait}
|
|
877
922
|
if options:
|
|
878
923
|
params["options"] = options
|
|
@@ -884,7 +929,8 @@ def ask_user(question, question_type="confirm", options=None, placeholder=None,
|
|
|
884
929
|
params["agentName"] = agent_name
|
|
885
930
|
if timeout_ms is not None:
|
|
886
931
|
params["timeoutMs"] = min(max(int(timeout_ms), 1000), 55000)
|
|
887
|
-
|
|
932
|
+
request_limit = {} if create_timeout_seconds is None else {"timeout_seconds": create_timeout_seconds}
|
|
933
|
+
return _mcp_call("ask_user", _with_decision_fields(params, decision), **request_limit)
|
|
888
934
|
|
|
889
935
|
|
|
890
936
|
def propose_scope(done_when, session_id, allowed_paths=None, off_limits_paths=None,
|
|
@@ -1002,396 +1048,9 @@ def get_end_user_decision(decision_id, wait_seconds=45):
|
|
|
1002
1048
|
` },
|
|
1003
1049
|
{ path: "approval_coverage.py", contents: 'import json\nimport re\nfrom typing import AbstractSet, Any, List, Mapping, Optional\n\nHERMES_SHELL_TOOL = "terminal"\nGATE_TOOLS_ENV = "PUSHARY_GATE_TOOLS"\nTERMINAL_BACKEND_ENV = "TERMINAL_ENV"\nDOCKER_MOUNT_CWD_ENV = "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE"\nDOCKER_VOLUMES_ENV = "TERMINAL_DOCKER_VOLUMES"\n\nDEFAULT_BACKEND = "local"\nDOCKER_BACKEND = "docker"\nBACKENDS_THAT_SKIP_APPROVALS = frozenset({"modal", "daytona", "vercel_sandbox"})\n\nBACKEND_NAME = re.compile(r"^[a-z0-9_]+$")\nTRUE_WORDS = frozenset({"true", "1", "yes"})\nHOST_PATH_PREFIXES = ("/", "~", "./", "../")\nWINDOWS_DRIVE_SEPARATORS = ("/", "\\\\")\nGATE_TOOLS_SEPARATOR = ","\n\n\ndef _is_blank(value: Any) -> bool:\n return value is None or (isinstance(value, str) and not value.strip())\n\n\ndef _backend_name(value: Any) -> Optional[str]:\n if not isinstance(value, str):\n return None\n name = value.strip()\n return name if BACKEND_NAME.match(name) else None\n\n\ndef terminal_backend(environ: Mapping[str, str], terminal_config: Mapping[str, Any]) -> Optional[str]:\n for value in (environ.get(TERMINAL_BACKEND_ENV), terminal_config.get("backend")):\n if not _is_blank(value):\n return _backend_name(value)\n return DEFAULT_BACKEND\n\n\ndef _is_true(value: Any) -> bool:\n if isinstance(value, bool):\n return value\n if isinstance(value, int):\n return value == 1\n return isinstance(value, str) and value.strip().lower() in TRUE_WORDS\n\n\ndef volume_binds_host_path(spec: Any) -> bool:\n if not isinstance(spec, str):\n return False\n volume = spec.strip()\n if not volume:\n return False\n if volume.startswith(HOST_PATH_PREFIXES):\n return True\n return len(volume) >= 3 and volume[1] == ":" and volume[2] in WINDOWS_DRIVE_SEPARATORS\n\n\ndef _docker_volumes(environ: Mapping[str, str], terminal_config: Mapping[str, Any]) -> List[Any]:\n raw = environ.get(DOCKER_VOLUMES_ENV)\n volumes: Any = terminal_config.get("docker_volumes")\n if raw is not None:\n try:\n volumes = json.loads(raw)\n except ValueError:\n return []\n return volumes if isinstance(volumes, list) else []\n\n\ndef _docker_may_reach_host(environ: Mapping[str, str], terminal_config: Mapping[str, Any]) -> bool:\n mount = environ.get(DOCKER_MOUNT_CWD_ENV, terminal_config.get("docker_mount_cwd_to_workspace"))\n return _is_true(mount) or any(volume_binds_host_path(volume) for volume in _docker_volumes(environ, terminal_config))\n\n\ndef skips_dangerous_command_approvals(environ: Mapping[str, str], terminal_config: Mapping[str, Any]) -> bool:\n backend = terminal_backend(environ, terminal_config)\n if backend == DOCKER_BACKEND:\n return not _docker_may_reach_host(environ, terminal_config)\n return backend in BACKENDS_THAT_SKIP_APPROVALS\n\n\ndef _gate_tools_with_shell(environ: Mapping[str, str]) -> str:\n listed = [entry.strip() for entry in environ.get(GATE_TOOLS_ENV, "").split(GATE_TOOLS_SEPARATOR) if entry.strip()]\n return GATE_TOOLS_SEPARATOR.join([*listed, HERMES_SHELL_TOOL])\n\n\ndef shell_gate_warning(\n environ: Mapping[str, str],\n terminal_config: Mapping[str, Any],\n gated_tools: AbstractSet[str],\n) -> Optional[str]:\n if HERMES_SHELL_TOOL in gated_tools or not skips_dangerous_command_approvals(environ, terminal_config):\n return None\n backend = terminal_backend(environ, terminal_config)\n return (\n f"[pushary] Hermes skips its dangerous-command approvals on the {backend} terminal backend, "\n f"because it treats the container as the boundary. Pushary only gates the tools listed in "\n f"{GATE_TOOLS_ENV}, and {HERMES_SHELL_TOOL} is not one of them, so no shell command reaches "\n f"your phone. To gate them, run: hermes config set {GATE_TOOLS_ENV} {_gate_tools_with_shell(environ)} "\n f"and restart Hermes."\n )\n' },
|
|
1004
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' },
|
|
1005
|
-
{ path: "approval.py", contents: `import logging
|
|
1006
|
-
import os
|
|
1007
|
-
import sys
|
|
1008
|
-
import time
|
|
1009
|
-
from typing import Literal, Optional, Tuple
|
|
1010
|
-
|
|
1011
|
-
from . import api, approval_ledger, cancellation, desktop_answers, desktop_contract, identity, installation
|
|
1012
|
-
from .approval_coverage import HERMES_SHELL_TOOL
|
|
1013
|
-
|
|
1014
|
-
logger = logging.getLogger(__name__)
|
|
1015
|
-
|
|
1016
|
-
DECISION_LINE_MAX = 500
|
|
1017
|
-
ACTION_BODY_MAX = 4000
|
|
1018
|
-
ACTION_BODY_TRUNCATION_MARKER = "\\n\u2026 [truncated]"
|
|
1019
|
-
UTF16_SINGLE_UNIT_MAX = 0xFFFF
|
|
1020
|
-
|
|
1021
|
-
POLL_CEILING_SECONDS = 50.0
|
|
1022
|
-
WITHDRAW_RESERVE_SECONDS = 10.0
|
|
1023
|
-
HOST_RETURN_MARGIN_SECONDS = 1.0
|
|
1024
|
-
LATE_ANSWER_POLL_MS = 1000
|
|
1025
|
-
|
|
1026
|
-
TUI_GATEWAY_MODULE = "tui_gateway.server"
|
|
1027
|
-
|
|
1028
|
-
RouteAnswerability = Literal["requester", "routed_elsewhere", "unknown"]
|
|
1029
|
-
ANSWERABLE_BY_REQUESTER: RouteAnswerability = "requester"
|
|
1030
|
-
ROUTED_ELSEWHERE: RouteAnswerability = "routed_elsewhere"
|
|
1031
|
-
ANSWERABILITY_UNKNOWN: RouteAnswerability = "unknown"
|
|
1032
|
-
|
|
1033
|
-
Withdrawal = Literal["withdrawn", "answered_late", "ended", "stopped"]
|
|
1034
|
-
WITHDRAWN: Withdrawal = "withdrawn"
|
|
1035
|
-
ANSWERED_LATE: Withdrawal = "answered_late"
|
|
1036
|
-
ENDED_UNANSWERED: Withdrawal = "ended"
|
|
1037
|
-
STOPPED: Withdrawal = "stopped"
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
CHOICE_LABELS = (
|
|
1041
|
-
("once", "Allow once"),
|
|
1042
|
-
("session", "Allow for this session"),
|
|
1043
|
-
("always", "Always allow"),
|
|
1044
|
-
("deny", "Deny"),
|
|
1045
|
-
)
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
class TransportUnavailable(Exception):
|
|
1049
|
-
pass
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
QUESTION_COMMAND_MAX = 160
|
|
1053
|
-
|
|
1054
|
-
PLUGIN_RULE_MARKER = "(plugin approval rule)"
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
def _offered(allowed):
|
|
1058
|
-
return [pair for pair in CHOICE_LABELS if pair[0] in set(allowed or ())]
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
def _command_head(command):
|
|
1062
|
-
return " ".join(str(command or "").split()[:2])[:80]
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
def _utf16_units(character: str) -> int:
|
|
1066
|
-
return 2 if ord(character) > UTF16_SINGLE_UNIT_MAX else 1
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
def _utf16_length(text: str) -> int:
|
|
1070
|
-
return sum(_utf16_units(character) for character in text)
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
def _prefix_within_utf16_units(text: str, units: int) -> str:
|
|
1074
|
-
used = 0
|
|
1075
|
-
for index, character in enumerate(text):
|
|
1076
|
-
used += _utf16_units(character)
|
|
1077
|
-
if used > units:
|
|
1078
|
-
return text[:index]
|
|
1079
|
-
return text
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
def cut_action_body(text: str) -> str:
|
|
1083
|
-
if len(_prefix_within_utf16_units(text, ACTION_BODY_MAX)) == len(text):
|
|
1084
|
-
return text
|
|
1085
|
-
kept = _prefix_within_utf16_units(text, ACTION_BODY_MAX - _utf16_length(ACTION_BODY_TRUNCATION_MARKER))
|
|
1086
|
-
return kept + ACTION_BODY_TRUNCATION_MARKER
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
def _command_summary(command):
|
|
1090
|
-
collapsed = " ".join(str(command or "").split())
|
|
1091
|
-
if len(collapsed) <= QUESTION_COMMAND_MAX:
|
|
1092
|
-
return collapsed
|
|
1093
|
-
return collapsed[:QUESTION_COMMAND_MAX - 1] + "\u2026"
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
def _choice_from_answer(value, offered, uses_select):
|
|
1097
|
-
answer = str(value or "").strip()
|
|
1098
|
-
if uses_select:
|
|
1099
|
-
for choice, label in offered:
|
|
1100
|
-
if answer.lower() == label.lower():
|
|
1101
|
-
return choice
|
|
1102
|
-
return "deny"
|
|
1103
|
-
return "once" if api.is_affirmative(answer) else "deny"
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
def _subject(request):
|
|
1107
|
-
"""What to put in the question.
|
|
1108
|
-
|
|
1109
|
-
A dangerous-command approval carries the real command. A plugin rule
|
|
1110
|
-
escalated from pre_tool_call carries a synthetic display label instead, and
|
|
1111
|
-
the plugin's own message is the part worth reading, so use that.
|
|
1112
|
-
"""
|
|
1113
|
-
command = str(request.command or "")
|
|
1114
|
-
if PLUGIN_RULE_MARKER in command:
|
|
1115
|
-
lines = str(request.description or "").strip().splitlines()
|
|
1116
|
-
if lines and lines[0].strip():
|
|
1117
|
-
return _command_summary(lines[0])
|
|
1118
|
-
return _command_summary(command)
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
def _open_question(request, offered, uses_select):
|
|
1122
|
-
command = str(request.command or "")
|
|
1123
|
-
return api.ask_user(
|
|
1124
|
-
question=f"Allow Hermes to run \`{_subject(request)}\`?",
|
|
1125
|
-
question_type="select" if uses_select else "confirm",
|
|
1126
|
-
options=[label for _, label in offered] if uses_select else None,
|
|
1127
|
-
context=str(request.description or "")[:500] or None,
|
|
1128
|
-
agent_name=identity.agent_name(),
|
|
1129
|
-
session_id=identity.session_id(),
|
|
1130
|
-
machine_id=identity.machine_id(),
|
|
1131
|
-
tool_name=HERMES_SHELL_TOOL,
|
|
1132
|
-
tool_target=_command_head(command),
|
|
1133
|
-
action=command[:DECISION_LINE_MAX] or None,
|
|
1134
|
-
action_body=cut_action_body(command) or None,
|
|
1135
|
-
blocker=(
|
|
1136
|
-
f"Hermes flagged this command as {request.pattern_key}"[:DECISION_LINE_MAX]
|
|
1137
|
-
if request.pattern_key
|
|
1138
|
-
else None
|
|
1139
|
-
),
|
|
1140
|
-
wait=False,
|
|
1141
|
-
)
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
def _stopped(result):
|
|
1145
|
-
return result.get("handoffAction") == cancellation.STOP_HANDOFF or result.get("status") in (
|
|
1146
|
-
"cancelled", cancellation.UNAVAILABLE_STATUS, "stopped")
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
def _route_answerability(created) -> RouteAnswerability:
|
|
1150
|
-
requester_may_answer = created.get("requesterMayAnswer")
|
|
1151
|
-
if requester_may_answer is True:
|
|
1152
|
-
return ANSWERABLE_BY_REQUESTER
|
|
1153
|
-
if requester_may_answer is False:
|
|
1154
|
-
return ROUTED_ELSEWHERE
|
|
1155
|
-
return ANSWERABILITY_UNKNOWN
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
def _routed_to(created) -> Optional[str]:
|
|
1159
|
-
routed_to = created.get("routedTo")
|
|
1160
|
-
return routed_to if isinstance(routed_to, str) and routed_to.strip() else None
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
def _withdraw(correlation_id) -> Tuple[Withdrawal, dict]:
|
|
1164
|
-
try:
|
|
1165
|
-
result = cancellation.classify_cancellation(api.cancel_question(correlation_id))
|
|
1166
|
-
if result in (cancellation.WITHDRAWN_BY_THIS_CALL, cancellation.CANCELLED_UNPROVEN):
|
|
1167
|
-
return WITHDRAWN, {}
|
|
1168
|
-
if result == cancellation.NOT_PENDING:
|
|
1169
|
-
answer = api.wait_for_answer(correlation_id, LATE_ANSWER_POLL_MS)
|
|
1170
|
-
if answer.get("answered"):
|
|
1171
|
-
return ANSWERED_LATE, answer
|
|
1172
|
-
if answer.get("status") in ("expired", "missing"):
|
|
1173
|
-
return ENDED_UNANSWERED, answer
|
|
1174
|
-
except Exception:
|
|
1175
|
-
pass
|
|
1176
|
-
return STOPPED, {}
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
def _wall_clock_ms():
|
|
1180
|
-
return int(time.time() * 1000)
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
def announce_approvals_changed() -> None:
|
|
1184
|
-
if TUI_GATEWAY_MODULE not in sys.modules:
|
|
1185
|
-
return
|
|
1186
|
-
try:
|
|
1187
|
-
from hermes_cli.plugin_events import broadcast_plugin_event
|
|
1188
|
-
except Exception:
|
|
1189
|
-
return
|
|
1190
|
-
try:
|
|
1191
|
-
broadcast_plugin_event(desktop_contract.PLUGIN_ID, desktop_contract.APPROVALS_CHANGED_EVENT, {})
|
|
1192
|
-
except Exception:
|
|
1193
|
-
logger.debug("[pushary] could not tell Hermes Desktop about an approval", exc_info=True)
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
def _open_answer_slot(request, correlation_id: str, offered, answerability: RouteAnswerability,
|
|
1197
|
-
routed_to: Optional[str], opened_at_ms: int, deadline_at_ms: int) -> None:
|
|
1198
|
-
try:
|
|
1199
|
-
desktop_answers.shared_answers().open_slot(
|
|
1200
|
-
correlation_id,
|
|
1201
|
-
request_id=getattr(request, "request_id", None),
|
|
1202
|
-
subject=_subject(request),
|
|
1203
|
-
choices=approval_ledger.offered_choices(offered),
|
|
1204
|
-
opened_at_ms=opened_at_ms,
|
|
1205
|
-
deadline_at_ms=deadline_at_ms,
|
|
1206
|
-
answerable_here=answerability == ANSWERABLE_BY_REQUESTER,
|
|
1207
|
-
routed_to=routed_to,
|
|
1208
|
-
)
|
|
1209
|
-
except Exception:
|
|
1210
|
-
logger.debug("[pushary] could not offer an approval to Hermes Desktop", exc_info=True)
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
def _close_answer_slot(correlation_id: str) -> None:
|
|
1214
|
-
try:
|
|
1215
|
-
desktop_answers.shared_answers().close_slot(correlation_id)
|
|
1216
|
-
except Exception:
|
|
1217
|
-
logger.debug("[pushary] could not withdraw an approval from Hermes Desktop", exc_info=True)
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
def _record_opened(request, correlation_id: str, offered, answerability: RouteAnswerability,
|
|
1221
|
-
routed_to: Optional[str]) -> None:
|
|
1222
|
-
opened_at_ms = _wall_clock_ms()
|
|
1223
|
-
deadline_at_ms = opened_at_ms + int(float(request.timeout_seconds or 0) * 1000)
|
|
1224
|
-
_open_answer_slot(request, correlation_id, offered, answerability, routed_to, opened_at_ms, deadline_at_ms)
|
|
1225
|
-
try:
|
|
1226
|
-
home = installation.hermes_home()
|
|
1227
|
-
approval_ledger.prune(home, time.time())
|
|
1228
|
-
opened = approval_ledger.open_approval(
|
|
1229
|
-
home,
|
|
1230
|
-
correlation_id=correlation_id,
|
|
1231
|
-
request_id=getattr(request, "request_id", None),
|
|
1232
|
-
subject=_subject(request),
|
|
1233
|
-
choices=approval_ledger.offered_choices(offered),
|
|
1234
|
-
pid=os.getpid(),
|
|
1235
|
-
opened_at_ms=opened_at_ms,
|
|
1236
|
-
deadline_at_ms=deadline_at_ms,
|
|
1237
|
-
)
|
|
1238
|
-
except Exception:
|
|
1239
|
-
logger.debug("[pushary] could not record an open approval", exc_info=True)
|
|
1240
|
-
opened = False
|
|
1241
|
-
if opened:
|
|
1242
|
-
announce_approvals_changed()
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
def _record_settled(correlation_id: str, outcome, answer_source: Optional[str]) -> None:
|
|
1246
|
-
try:
|
|
1247
|
-
settled = approval_ledger.settle_approval(
|
|
1248
|
-
installation.hermes_home(),
|
|
1249
|
-
correlation_id,
|
|
1250
|
-
outcome=outcome,
|
|
1251
|
-
answer_source=answer_source,
|
|
1252
|
-
settled_at_ms=_wall_clock_ms(),
|
|
1253
|
-
)
|
|
1254
|
-
except Exception:
|
|
1255
|
-
logger.debug("[pushary] could not record a settled approval", exc_info=True)
|
|
1256
|
-
return
|
|
1257
|
-
if settled:
|
|
1258
|
-
announce_approvals_changed()
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
def record_host_outcome(request_id, choice) -> None:
|
|
1262
|
-
try:
|
|
1263
|
-
desktop_answers.shared_answers().end_for_request(request_id)
|
|
1264
|
-
except Exception:
|
|
1265
|
-
logger.debug("[pushary] could not end an approval in Hermes Desktop", exc_info=True)
|
|
1266
|
-
try:
|
|
1267
|
-
recorded = approval_ledger.record_host_outcome(installation.hermes_home(), request_id, choice, _wall_clock_ms())
|
|
1268
|
-
except Exception:
|
|
1269
|
-
logger.debug("[pushary] could not record Hermes's approval outcome", exc_info=True)
|
|
1270
|
-
return
|
|
1271
|
-
if recorded:
|
|
1272
|
-
announce_approvals_changed()
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
def _decided(request, correlation_id, choice, answer_source):
|
|
1276
|
-
_record_settled(correlation_id, choice, answer_source)
|
|
1277
|
-
return request.respond(choice)
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
def _answer_source(answer) -> str:
|
|
1281
|
-
source = answer.get("answerSource")
|
|
1282
|
-
return source if approval_ledger.is_token(source) else approval_ledger.UNNAMED_ANSWER_SOURCE
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
def _answered(request, correlation_id, answer, offered, uses_select):
|
|
1286
|
-
choice = _choice_from_answer(answer.get("value"), offered, uses_select)
|
|
1287
|
-
return _decided(request, correlation_id, choice, _answer_source(answer))
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
def _offered_choices(offered) -> Tuple[str, ...]:
|
|
1291
|
-
return tuple(choice for choice, _ in offered)
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
def _host_has_finished(request, correlation_id: str) -> bool:
|
|
1295
|
-
try:
|
|
1296
|
-
if desktop_answers.shared_answers().has_ended(correlation_id):
|
|
1297
|
-
return True
|
|
1298
|
-
return approval_ledger.host_has_finished(installation.hermes_home(), getattr(request, "request_id", None))
|
|
1299
|
-
except Exception:
|
|
1300
|
-
return False
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
def _desktop_decision(correlation_id: str, offered) -> Optional[str]:
|
|
1304
|
-
try:
|
|
1305
|
-
return desktop_answers.shared_answers().desktop_decision(correlation_id, _offered_choices(offered))
|
|
1306
|
-
except Exception:
|
|
1307
|
-
logger.debug("[pushary] could not read a Hermes Desktop answer", exc_info=True)
|
|
1308
|
-
return None
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
def _final_say(correlation_id: str, offered, host_deadline: float, claim_may_still_win: bool) -> Optional[str]:
|
|
1312
|
-
wait = min(desktop_answers.CLAIM_RESOLVE_SECONDS, host_deadline - time.monotonic()) if claim_may_still_win else 0.0
|
|
1313
|
-
try:
|
|
1314
|
-
return desktop_answers.shared_answers().take_final_say(correlation_id, _offered_choices(offered),
|
|
1315
|
-
claim_wait_seconds=wait)
|
|
1316
|
-
except Exception:
|
|
1317
|
-
logger.debug("[pushary] could not settle who answers this approval", exc_info=True)
|
|
1318
|
-
return None
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
def present(request):
|
|
1322
|
-
offered = _offered(request.allowed_choices)
|
|
1323
|
-
if not offered:
|
|
1324
|
-
return request.respond("deny")
|
|
1325
|
-
uses_select = [choice for choice, _ in offered] != ["once", "deny"]
|
|
1326
|
-
# Reserve time for withdrawal before the host discards a late decision.
|
|
1327
|
-
started_at = time.monotonic()
|
|
1328
|
-
timeout_seconds = float(request.timeout_seconds or 0)
|
|
1329
|
-
deadline = started_at + max(timeout_seconds - WITHDRAW_RESERVE_SECONDS, 0.0)
|
|
1330
|
-
host_deadline = started_at + max(timeout_seconds - HOST_RETURN_MARGIN_SECONDS, 0.0)
|
|
1331
|
-
created = _open_question(request, offered, uses_select)
|
|
1332
|
-
if created.get("answered"):
|
|
1333
|
-
return request.respond(_choice_from_answer(created.get("value"), offered, uses_select))
|
|
1334
|
-
if _stopped(created):
|
|
1335
|
-
return request.respond("deny")
|
|
1336
|
-
correlation_id = created.get("correlationId")
|
|
1337
|
-
if not correlation_id:
|
|
1338
|
-
raise TransportUnavailable("Pushary did not create an approval")
|
|
1339
|
-
answerability = _route_answerability(created)
|
|
1340
|
-
_record_opened(request, correlation_id, offered, answerability, _routed_to(created))
|
|
1341
|
-
try:
|
|
1342
|
-
return _await_decision(request, created, correlation_id, offered, uses_select, answerability,
|
|
1343
|
-
started_at, deadline, host_deadline)
|
|
1344
|
-
finally:
|
|
1345
|
-
_close_answer_slot(correlation_id)
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
def _await_decision(request, created, correlation_id: str, offered, uses_select: bool,
|
|
1349
|
-
answerability: RouteAnswerability, started_at: float, deadline: float, host_deadline: float):
|
|
1350
|
-
may_hand_back = answerability != ROUTED_ELSEWHERE
|
|
1351
|
-
nothing_was_delivered = bool(created.get("noDevices") or created.get("status") in ("terminal", "notified"))
|
|
1352
|
-
policy_deadline = None
|
|
1353
|
-
window_ms = created.get("policyTimeoutMs")
|
|
1354
|
-
if may_hand_back and created.get("deliveryMode") == "push_first" and isinstance(window_ms, (int, float)) and window_ms >= 0:
|
|
1355
|
-
policy_deadline = started_at + window_ms / 1000
|
|
1356
|
-
deadline = min(deadline, policy_deadline)
|
|
1357
|
-
handoff = may_hand_back and (nothing_was_delivered or bool(created.get("suppressed")))
|
|
1358
|
-
nobody_can_answer = not may_hand_back and nothing_was_delivered
|
|
1359
|
-
answer = created
|
|
1360
|
-
try:
|
|
1361
|
-
while not handoff and not nobody_can_answer and time.monotonic() < deadline:
|
|
1362
|
-
if _host_has_finished(request, correlation_id):
|
|
1363
|
-
answer = {"handoffAction": "stop"}
|
|
1364
|
-
break
|
|
1365
|
-
remaining = deadline - time.monotonic()
|
|
1366
|
-
answer = api.wait_for_answer(correlation_id, int(min(POLL_CEILING_SECONDS, max(1.0, remaining)) * 1000))
|
|
1367
|
-
if answer.get("answered"):
|
|
1368
|
-
return _answered(request, correlation_id, answer, offered, uses_select)
|
|
1369
|
-
if _stopped(answer) or answer.get("error") or answer.get("status") in ("expired", "missing"):
|
|
1370
|
-
break
|
|
1371
|
-
# Some hosts/proxies return pending immediately instead of long-polling.
|
|
1372
|
-
time.sleep(min(0.1, max(0, deadline - time.monotonic())))
|
|
1373
|
-
except Exception:
|
|
1374
|
-
answer = {"handoffAction": "stop"}
|
|
1375
|
-
|
|
1376
|
-
desktop = _desktop_decision(correlation_id, offered)
|
|
1377
|
-
if desktop:
|
|
1378
|
-
return _decided(request, correlation_id, desktop, approval_ledger.DESKTOP_ANSWER_SOURCE)
|
|
1379
|
-
withdrawal, late = _withdraw(correlation_id)
|
|
1380
|
-
if withdrawal == ANSWERED_LATE:
|
|
1381
|
-
return _answered(request, correlation_id, late, offered, uses_select)
|
|
1382
|
-
desktop = _final_say(correlation_id, offered, host_deadline, claim_may_still_win=withdrawal == STOPPED)
|
|
1383
|
-
if desktop:
|
|
1384
|
-
return _decided(request, correlation_id, desktop, approval_ledger.DESKTOP_ANSWER_SOURCE)
|
|
1385
|
-
if _stopped(answer) or withdrawal == STOPPED:
|
|
1386
|
-
return _decided(request, correlation_id, "deny", None)
|
|
1387
|
-
if handoff or (policy_deadline is not None and time.monotonic() >= policy_deadline):
|
|
1388
|
-
# Only a fenced question may reach Hermes's configured builtin fallback.
|
|
1389
|
-
_record_settled(correlation_id, approval_ledger.HANDED_TO_HERMES, None)
|
|
1390
|
-
raise TransportUnavailable("Approval handed back to Hermes")
|
|
1391
|
-
return _decided(request, correlation_id, "deny", None)
|
|
1392
|
-
` },
|
|
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' },
|
|
1393
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' },
|
|
1394
|
-
{ 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.14",\n "tab": { "hidden": true },\n "entry": "web.js",\n "api": "plugin_api.py"\n}\n' },
|
|
1395
1054
|
{ path: "dashboard/plugin_api.py", contents: `import importlib
|
|
1396
1055
|
import sys
|
|
1397
1056
|
import time
|
|
@@ -1639,6 +1298,7 @@ def shared_answers() -> DesktopAnswers:
|
|
|
1639
1298
|
` },
|
|
1640
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' },
|
|
1641
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\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.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 elapsed = max(time.monotonic() - self.opened_monotonic, time.time() - self.opened_wall)\n return elapsed >= ANSWER_WINDOW_SECONDS\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 return question\n opened = Question(call)\n _questions.append(opened)\n return opened\n\n\ndef _open(question: Question, ask: Ask) -> Optional[Verdict]:\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 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 question.outcome is not None or not question.step_finished.is_set():\n return\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 if question.outcome is None and can_be_retried(question.call) and not question.has_expired():\n question.claimed = False\n return WAITING\n if question.outcome is not None and not question.has_expired():\n _questions.remove(question)\n return question.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.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' },
|
|
1642
1302
|
{ path: "history.py", contents: `from __future__ import annotations
|
|
1643
1303
|
|
|
1644
1304
|
import hashlib
|
|
@@ -2297,8 +1957,8 @@ def stop_history(session_id: str) -> None:
|
|
|
2297
1957
|
if thread.is_alive():
|
|
2298
1958
|
logger.warning("[pushary] Hermes final history export is still pending")
|
|
2299
1959
|
` },
|
|
2300
|
-
{ path: "host.py", contents: 'import os\n\nTRANSPORT_NAME = "pushary"\n\nHOOK_TIMEOUT_DEFAULT_SECONDS = 30.0\nHOOK_TIMEOUT_MAX_SECONDS = 600.0\n\nGATE_HEADROOM_SECONDS = 5.0\
|
|
2301
|
-
{ path: "identity.py", contents: 'import hashlib\nimport os\nimport re\nimport socket\nfrom pathlib import Path\n\nDEFAULT_AGENT_NAME = "Hermes"\nMAX_ID_LENGTH = 128\nSHARED_MACHINE_ID_FILE = Path.home() / ".pushary" / "machine-id"\nSHARED_MACHINE_ID_PATTERN = re.compile(r"^[A-Za-z0-9-]{1,128}$")\n\n_session_id = None\n\n\ndef agent_name():\n return os.environ.get("PUSHARY_AGENT_NAME", DEFAULT_AGENT_NAME)\n\n\ndef labelled_agent_name(requested):\n project = str(requested or "").partition(" - ")[2].strip()\n return f"{agent_name()} - {project}" if project else agent_name()\n\n\ndef shared_machine_id(path=None):\n try:\n value = (path or SHARED_MACHINE_ID_FILE).read_text(encoding="utf-8").strip()\n except OSError:\n return None\n return value if SHARED_MACHINE_ID_PATTERN.match(value) else None\n\n\ndef hostname_machine_id():\n try:\n host = socket.gethostname()\n except Exception:\n return None\n if not host:\n return None\n return hashlib.sha256(host.encode("utf-8")).hexdigest()[:8]\n\n\ndef machine_id():\n return shared_machine_id() or hostname_machine_id()\n\n\ndef remember_session(value):\n global _session_id\n if value:\n _session_id = str(value)[:MAX_ID_LENGTH]\n\n\ndef forget_session():\n global _session_id\n _session_id = None\n\n\ndef session_id():\n return _session_id\n' },
|
|
1960
|
+
{ path: "host.py", contents: 'import os\n\nTRANSPORT_NAME = "pushary"\n\nHOOK_TIMEOUT_DEFAULT_SECONDS = 30.0\nHOOK_TIMEOUT_MAX_SECONDS = 600.0\n\nGATE_HEADROOM_SECONDS = 5.0\nGATE_MAX_SECONDS = 55.0\n\n# The last Hermes that runs a pre_tool_call callback to completion. Anything\n# after this abandons one that outlives plugins.hook_callback_timeout.\nUNBOUNDED_THROUGH_VERSION = (0, 20, 5)\nUNSTAMPED_VERSION = (0, 0, 0)\n\n\ndef _config():\n try:\n from hermes_cli.config import load_config_readonly\n\n loaded = load_config_readonly()\n except Exception:\n return {}\n return loaded if isinstance(loaded, dict) else {}\n\n\ndef _section(node, *path):\n for key in path:\n node = node.get(key) if isinstance(node, dict) else None\n if node is None:\n return {}\n return node if isinstance(node, dict) else {}\n\n\ndef profile_secret(name):\n try:\n from agent.secret_scope import get_secret\n except Exception:\n return os.environ.get(name) or None\n try:\n return get_secret(name) or None\n except Exception:\n return None\n\n\ndef read_profile_setting(name):\n try:\n from agent.secret_scope import get_secret\n except ImportError:\n return os.environ.get(name) or None\n return get_secret(name) or None\n\n\ndef profile_setting(name):\n try:\n return read_profile_setting(name)\n except Exception:\n return os.environ.get(name) or None\n\n\ndef hermes_version_label():\n try:\n from importlib.metadata import version\n\n return version("hermes-cli")\n except Exception:\n try:\n import hermes_cli\n\n label = getattr(hermes_cli, "__version__", None)\n except Exception:\n return None\n return str(label) if label else None\n\n\ndef _hermes_version():\n """This Hermes as a comparable tuple, or None when it will not say."""\n raw = hermes_version_label()\n if not raw:\n return None\n parts = []\n for piece in str(raw).split(".")[:3]:\n digits = ""\n for char in piece:\n if not char.isdigit():\n break\n digits += char\n if not digits:\n return None\n parts.append(int(digits))\n while len(parts) < 3:\n parts.append(0)\n return tuple(parts)\n\n\ndef bounds_pre_tool_call():\n """Whether this Hermes abandons a slow pre_tool_call callback.\n\n The timeout was added after 0.20.5, which runs plugin hooks to completion.\n Clamping the wait on a host that would never have cut it off just shortens\n the window the user has to answer, for nothing.\n\n Unreadable means assume bounded. A wait that is shorter than it had to be\n costs the user seconds; a wait longer than the host allows costs them the\n answer they already gave.\n\n That rule is why the private symbol is not asked on its own. `hasattr` on\n `_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS` cannot tell "this host runs hooks to\n completion" apart from "the private name moved", and those two answers want\n opposite behaviour: the first earns the full window, the second spends 55\n seconds against a budget of 30 and loses an answer the user already gave.\n A rename is the likelier of the two, because a private name is the one thing\n a host is free to change. So the symbol is taken as proof of bounded, and\n only a version this side of the timeout landing is taken as proof of the\n other. Anything unreadable falls to bounded.\n """\n try:\n from hermes_cli import plugins\n except Exception:\n return True\n if hasattr(plugins, "_HOOK_TIMEOUT_FAIL_CLOSED_HOOKS"):\n return True\n version = _hermes_version()\n if version is None or version == UNSTAMPED_VERSION:\n return True\n return version > UNBOUNDED_THROUGH_VERSION\n\n\ndef hook_callback_timeout_seconds():\n raw = _section(_config(), "plugins").get("hook_callback_timeout")\n if raw is None:\n return HOOK_TIMEOUT_DEFAULT_SECONDS\n try:\n timeout = float(raw)\n except (TypeError, ValueError):\n return HOOK_TIMEOUT_DEFAULT_SECONDS\n if timeout < 0:\n return HOOK_TIMEOUT_DEFAULT_SECONDS\n return min(timeout, HOOK_TIMEOUT_MAX_SECONDS)\n\n\ndef gate_budget_seconds(requested_seconds):\n if not bounds_pre_tool_call():\n return max(1.0, min(float(requested_seconds), GATE_MAX_SECONDS))\n timeout = hook_callback_timeout_seconds()\n if timeout <= 0:\n return max(1.0, min(float(requested_seconds), GATE_MAX_SECONDS))\n headroom = min(GATE_HEADROOM_SECONDS, timeout / 2)\n return min(max(1.0, float(requested_seconds)), timeout - headroom, GATE_MAX_SECONDS)\n\n\ndef terminal_config():\n return _section(_config(), "terminal")\n\n\ndef pushary_is_selected_transport():\n selected = _section(_config(), "security", "approval").get("transport")\n return str(selected or "").strip().lower() == TRANSPORT_NAME\n' },
|
|
1961
|
+
{ path: "identity.py", contents: 'import contextvars\nimport hashlib\nimport os\nimport re\nimport socket\nfrom pathlib import Path\n\nDEFAULT_AGENT_NAME = "Hermes"\nMAX_ID_LENGTH = 128\nSHARED_MACHINE_ID_FILE = Path.home() / ".pushary" / "machine-id"\nSHARED_MACHINE_ID_PATTERN = re.compile(r"^[A-Za-z0-9-]{1,128}$")\n\n_session_id = None\n_bound_session = contextvars.ContextVar("pushary_bound_session", default=None)\n\n\ndef agent_name():\n return os.environ.get("PUSHARY_AGENT_NAME", DEFAULT_AGENT_NAME)\n\n\ndef labelled_agent_name(requested):\n project = str(requested or "").partition(" - ")[2].strip()\n return f"{agent_name()} - {project}" if project else agent_name()\n\n\ndef shared_machine_id(path=None):\n try:\n value = (path or SHARED_MACHINE_ID_FILE).read_text(encoding="utf-8").strip()\n except OSError:\n return None\n return value if SHARED_MACHINE_ID_PATTERN.match(value) else None\n\n\ndef hostname_machine_id():\n try:\n host = socket.gethostname()\n except Exception:\n return None\n if not host:\n return None\n return hashlib.sha256(host.encode("utf-8")).hexdigest()[:8]\n\n\ndef machine_id():\n return shared_machine_id() or hostname_machine_id()\n\n\ndef remember_session(value):\n global _session_id\n if value:\n _session_id = str(value)[:MAX_ID_LENGTH]\n\n\ndef forget_session():\n global _session_id\n _session_id = None\n\n\ndef bind_session(value):\n if value:\n _bound_session.set(str(value)[:MAX_ID_LENGTH])\n\n\ndef bind_only_session(value):\n _bound_session.set(str(value or "")[:MAX_ID_LENGTH])\n\n\ndef session_id():\n bound = _bound_session.get()\n return _session_id if bound is None else bound or None\n' },
|
|
2302
1962
|
{ path: "installation.py", contents: `import json
|
|
2303
1963
|
import logging
|
|
2304
1964
|
import os
|
|
@@ -2428,7 +2088,7 @@ def record_plugin_load(approval_transport_registered, home=None, pid=None, now=N
|
|
|
2428
2088
|
logger.debug("[pushary] could not record the plugin load: %s", exc)
|
|
2429
2089
|
return None
|
|
2430
2090
|
` },
|
|
2431
|
-
{ path: "plugin.yaml", contents: 'name: pushary\nversion: 1.0.
|
|
2091
|
+
{ path: "plugin.yaml", contents: 'name: pushary\nversion: 1.0.14\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' },
|
|
2432
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" },
|
|
2433
2093
|
{ path: "schemas.py", contents: `PUSHARY_REMIND = {
|
|
2434
2094
|
"name": "pushary_remind",
|
|
@@ -3082,6 +2742,7 @@ var HERMES_SHELL_TOOL = "terminal";
|
|
|
3082
2742
|
var HERMES_DOCKER_VOLUMES_KEY = "TERMINAL_DOCKER_VOLUMES";
|
|
3083
2743
|
var HERMES_DOCKER_MOUNT_CWD_KEY = "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE";
|
|
3084
2744
|
var HERMES_COMMAND_ALLOWLIST_KEY = "command_allowlist";
|
|
2745
|
+
var HERMES_PLUGIN_ASKS_PAST_ALWAYS_ALLOW = "1.0.14";
|
|
3085
2746
|
var HERMES_ALWAYS_ALLOWED_SHELL_RULE = `plugin_rule:${HERMES_SHELL_TOOL}`;
|
|
3086
2747
|
var HERMES_DEFAULT_BACKEND = "local";
|
|
3087
2748
|
var HERMES_DOCKER_BACKEND = "docker";
|
|
@@ -3188,7 +2849,12 @@ var allowlistEntries = (allowlist) => {
|
|
|
3188
2849
|
return typeof allowlist.value === "string" ? legacyListEntries(allowlist.value) : [];
|
|
3189
2850
|
};
|
|
3190
2851
|
var escalatesToHermesApprovals = (transport) => transport?.kind === "set" && transport.value === HERMES_PUSHARY_TRANSPORT;
|
|
3191
|
-
var
|
|
2852
|
+
var asksPastAlwaysAllow = (pluginVersion) => {
|
|
2853
|
+
const version = pluginVersion === null ? null : parseVersion(pluginVersion);
|
|
2854
|
+
const floor = parseVersion(HERMES_PLUGIN_ASKS_PAST_ALWAYS_ALLOW);
|
|
2855
|
+
return version !== null && floor !== null && atLeast(version, floor);
|
|
2856
|
+
};
|
|
2857
|
+
var hermesAlwaysAllowsShell = ({ allowlist, transport, pluginVersion }) => !asksPastAlwaysAllow(pluginVersion) && escalatesToHermesApprovals(transport) && allowlistEntries(allowlist).includes(HERMES_ALWAYS_ALLOWED_SHELL_RULE);
|
|
3192
2858
|
var skipOf = (coverage) => coverage.kind === "hermes_skips" ? { kind: "skips" } : { kind: "may_skip", doubt: coverage.doubt };
|
|
3193
2859
|
var hermesShellGateState = ({ coverage, gate, alwaysAllowed }) => {
|
|
3194
2860
|
if (coverage.kind === "unreadable") return { kind: "unreadable" };
|
|
@@ -3612,6 +3278,10 @@ var hermesWiringOwner = (folder, macAppRecordExists) => {
|
|
|
3612
3278
|
if (folder.kind === "pushary") return folder.marker.installedBy;
|
|
3613
3279
|
return macAppRecordExists ? "mac_app" : null;
|
|
3614
3280
|
};
|
|
3281
|
+
var hermesPluginVersionInUse = (state) => {
|
|
3282
|
+
if (state.kind !== "connected") return null;
|
|
3283
|
+
return state.gatewayRunning ? state.runningVersion : state.version;
|
|
3284
|
+
};
|
|
3615
3285
|
var routesHermesApprovals = (settings) => settings.approvalTransport === HERMES_PUSHARY_TRANSPORT;
|
|
3616
3286
|
var routesHermesQuestions = (folder) => folder.kind === "pushary" && folder.marker.routeQuestions;
|
|
3617
3287
|
var folderVersion = (folder) => folder.kind === "absent" ? null : folder.version;
|
|
@@ -4156,6 +3826,7 @@ export {
|
|
|
4156
3826
|
HERMES_DOCKER_VOLUMES_KEY,
|
|
4157
3827
|
HERMES_DOCKER_MOUNT_CWD_KEY,
|
|
4158
3828
|
HERMES_COMMAND_ALLOWLIST_KEY,
|
|
3829
|
+
HERMES_PLUGIN_ASKS_PAST_ALWAYS_ALLOW,
|
|
4159
3830
|
HERMES_ALWAYS_ALLOWED_SHELL_RULE,
|
|
4160
3831
|
hermesApprovalCoverage,
|
|
4161
3832
|
hermesGateToolsFrom,
|
|
@@ -4174,6 +3845,7 @@ export {
|
|
|
4174
3845
|
defaultHermesHome,
|
|
4175
3846
|
parseHermesInstallMarker,
|
|
4176
3847
|
hermesWiringOwner,
|
|
3848
|
+
hermesPluginVersionInUse,
|
|
4177
3849
|
routesHermesApprovals,
|
|
4178
3850
|
routesHermesQuestions,
|
|
4179
3851
|
runsAnOlderPlugin,
|
|
@@ -6,8 +6,9 @@ import {
|
|
|
6
6
|
HERMES_ALWAYS_ALLOWED_SHELL_RULE,
|
|
7
7
|
HERMES_COMMAND_ALLOWLIST_KEY,
|
|
8
8
|
HERMES_GATE_TOOLS_KEY,
|
|
9
|
+
HERMES_PLUGIN_ASKS_PAST_ALWAYS_ALLOW,
|
|
9
10
|
HERMES_SHELL_TOOL
|
|
10
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-TUWADETS.js";
|
|
11
12
|
import {
|
|
12
13
|
retryAgentCommand
|
|
13
14
|
} from "./chunk-FW6JKPTU.js";
|
|
@@ -167,9 +168,9 @@ var describeHermesShellGate = (state) => {
|
|
|
167
168
|
case "always_allowed":
|
|
168
169
|
return {
|
|
169
170
|
tone: "warn",
|
|
170
|
-
label: `Hermes: ${HERMES_SHELL_TOOL} commands run without asking`,
|
|
171
|
-
detail: `${HERMES_COMMAND_ALLOWLIST_KEY} holds ${HERMES_ALWAYS_ALLOWED_SHELL_RULE}, which "Always allow" adds, so Hermes lets every ${HERMES_SHELL_TOOL} command through before Pushary is asked`,
|
|
172
|
-
fix: `remove ${HERMES_ALWAYS_ALLOWED_SHELL_RULE} from ${HERMES_COMMAND_ALLOWLIST_KEY} in your Hermes config.yaml, then ${HERMES_RESTART_COMMAND}`
|
|
171
|
+
label: `Hermes: ${HERMES_SHELL_TOOL} commands run without asking on a Pushary plugin older than ${HERMES_PLUGIN_ASKS_PAST_ALWAYS_ALLOW}`,
|
|
172
|
+
detail: `${HERMES_COMMAND_ALLOWLIST_KEY} holds ${HERMES_ALWAYS_ALLOWED_SHELL_RULE}, which "Always allow" adds, so with an older plugin Hermes lets every ${HERMES_SHELL_TOOL} command through before Pushary is asked. From ${HERMES_PLUGIN_ASKS_PAST_ALWAYS_ALLOW} the rule has no effect`,
|
|
173
|
+
fix: `update the Pushary plugin, or remove ${HERMES_ALWAYS_ALLOWED_SHELL_RULE} from ${HERMES_COMMAND_ALLOWLIST_KEY} in your Hermes config.yaml, then ${HERMES_RESTART_COMMAND}`
|
|
173
174
|
};
|
|
174
175
|
case "ungated":
|
|
175
176
|
return {
|
|
@@ -15,10 +15,10 @@ import {
|
|
|
15
15
|
refreshCodexEmbeddedKey,
|
|
16
16
|
refreshEmbeddedAgentKeys,
|
|
17
17
|
repairCodexHolds
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-Z3JYKLYD.js";
|
|
19
19
|
import "./chunk-TWWOQKXK.js";
|
|
20
20
|
import "./chunk-TFSXOOKJ.js";
|
|
21
|
-
import "./chunk-
|
|
21
|
+
import "./chunk-TUWADETS.js";
|
|
22
22
|
import "./chunk-33OPFYPX.js";
|
|
23
23
|
import "./chunk-E6RGE25R.js";
|
|
24
24
|
import "./chunk-FW6JKPTU.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pushary",
|
|
3
|
-
"version": "1.9.
|
|
3
|
+
"version": "1.9.274",
|
|
4
4
|
"description": "Human-in-the-loop (HITL) for AI agents: ask a person for approvals or answers by push notification. One command connects Claude Code, Codex, Cursor, Gemini CLI and more.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pushary",
|