failproofai 1.0.15 → 1.0.16-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/.next/standalone/.next/BUILD_ID +1 -1
  2. package/.next/standalone/.next/build-manifest.json +13 -13
  3. package/.next/standalone/.next/prerender-manifest.json +4 -4
  4. package/.next/standalone/.next/required-server-files.json +1 -1
  5. package/.next/standalone/.next/server/app/_global-error/page/build-manifest.json +2 -2
  6. package/.next/standalone/.next/server/app/_global-error/page/server-reference-manifest.json +1 -1
  7. package/.next/standalone/.next/server/app/_global-error/page.js.nft.json +1 -1
  8. package/.next/standalone/.next/server/app/_global-error/page_client-reference-manifest.js +1 -1
  9. package/.next/standalone/.next/server/app/_global-error.html +1 -1
  10. package/.next/standalone/.next/server/app/_global-error.rsc +2 -2
  11. package/.next/standalone/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +2 -2
  12. package/.next/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +2 -2
  13. package/.next/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  14. package/.next/standalone/.next/server/app/_not-found/page/build-manifest.json +2 -2
  15. package/.next/standalone/.next/server/app/_not-found/page/server-reference-manifest.json +1 -1
  16. package/.next/standalone/.next/server/app/_not-found/page.js.nft.json +1 -1
  17. package/.next/standalone/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
  18. package/.next/standalone/.next/server/app/_not-found.html +1 -1
  19. package/.next/standalone/.next/server/app/_not-found.rsc +4 -4
  20. package/.next/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +4 -4
  21. package/.next/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +3 -3
  22. package/.next/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  23. package/.next/standalone/.next/server/app/api/audit/invite/route.js.nft.json +1 -1
  24. package/.next/standalone/.next/server/app/api/audit/run/route.js +22 -21
  25. package/.next/standalone/.next/server/app/api/audit/run/route.js.nft.json +1 -1
  26. package/.next/standalone/.next/server/app/api/audit/status/route.js.nft.json +1 -1
  27. package/.next/standalone/.next/server/app/api/auth/login-request/route.js.nft.json +1 -1
  28. package/.next/standalone/.next/server/app/api/auth/login-verify/route.js.nft.json +1 -1
  29. package/.next/standalone/.next/server/app/api/auth/logout/route.js.nft.json +1 -1
  30. package/.next/standalone/.next/server/app/api/auth/status/route.js.nft.json +1 -1
  31. package/.next/standalone/.next/server/app/api/download/[project]/[session]/route.js.nft.json +1 -1
  32. package/.next/standalone/.next/server/app/audit/page/build-manifest.json +2 -2
  33. package/.next/standalone/.next/server/app/audit/page/server-reference-manifest.json +2 -2
  34. package/.next/standalone/.next/server/app/audit/page.js +4 -3
  35. package/.next/standalone/.next/server/app/audit/page.js.nft.json +1 -1
  36. package/.next/standalone/.next/server/app/audit/page_client-reference-manifest.js +1 -1
  37. package/.next/standalone/.next/server/app/index.html +1 -1
  38. package/.next/standalone/.next/server/app/index.rsc +4 -4
  39. package/.next/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +3 -3
  40. package/.next/standalone/.next/server/app/index.segments/_full.segment.rsc +4 -4
  41. package/.next/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  42. package/.next/standalone/.next/server/app/page/build-manifest.json +2 -2
  43. package/.next/standalone/.next/server/app/page/server-reference-manifest.json +1 -1
  44. package/.next/standalone/.next/server/app/page.js.nft.json +1 -1
  45. package/.next/standalone/.next/server/app/page_client-reference-manifest.js +1 -1
  46. package/.next/standalone/.next/server/app/policies/page/build-manifest.json +2 -2
  47. package/.next/standalone/.next/server/app/policies/page/server-reference-manifest.json +14 -14
  48. package/.next/standalone/.next/server/app/policies/page.js +8 -7
  49. package/.next/standalone/.next/server/app/policies/page.js.nft.json +1 -1
  50. package/.next/standalone/.next/server/app/policies/page_client-reference-manifest.js +1 -1
  51. package/.next/standalone/.next/server/app/project/[name]/page/build-manifest.json +2 -2
  52. package/.next/standalone/.next/server/app/project/[name]/page/server-reference-manifest.json +1 -1
  53. package/.next/standalone/.next/server/app/project/[name]/page.js.nft.json +1 -1
  54. package/.next/standalone/.next/server/app/project/[name]/page_client-reference-manifest.js +1 -1
  55. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/build-manifest.json +2 -2
  56. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/react-loadable-manifest.json +2 -2
  57. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page/server-reference-manifest.json +2 -2
  58. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page.js.nft.json +1 -1
  59. package/.next/standalone/.next/server/app/project/[name]/session/[sessionId]/page_client-reference-manifest.js +1 -1
  60. package/.next/standalone/.next/server/app/projects/page/build-manifest.json +2 -2
  61. package/.next/standalone/.next/server/app/projects/page/server-reference-manifest.json +1 -1
  62. package/.next/standalone/.next/server/app/projects/page.js.nft.json +1 -1
  63. package/.next/standalone/.next/server/app/projects/page_client-reference-manifest.js +1 -1
  64. package/.next/standalone/.next/server/app/settings/page/build-manifest.json +2 -2
  65. package/.next/standalone/.next/server/app/settings/page/server-reference-manifest.json +8 -8
  66. package/.next/standalone/.next/server/app/settings/page.js +8 -7
  67. package/.next/standalone/.next/server/app/settings/page.js.nft.json +1 -1
  68. package/.next/standalone/.next/server/app/settings/page_client-reference-manifest.js +1 -1
  69. package/.next/standalone/.next/server/chunks/[root-of-the-server]__048f1wnr8pysf._.js +4 -4
  70. package/.next/standalone/.next/server/chunks/_0tovk6q0miud6._.js +1 -1
  71. package/.next/standalone/.next/server/chunks/_0trp3ycqv17cl._.js +1 -1
  72. package/.next/standalone/.next/server/chunks/package_json_[json]_cjs_1nxcc4vkpxxu7._.js +1 -1
  73. package/.next/standalone/.next/server/chunks/src_hooks_0fmclqlaj83-2._.js +5 -0
  74. package/.next/standalone/.next/server/chunks/src_hooks_15j31lnj-km9r._.js +3 -0
  75. package/.next/standalone/.next/server/chunks/src_hooks_daemon-client_ts_0il_yu1zc0291._.js +1 -1
  76. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__08ch3staq3ejw._.js +1 -1
  77. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0bigvy9xmv2ka._.js +1 -1
  78. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0h86bl2qf0k_o._.js +1 -1
  79. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0pia5h3p8re4c._.js +1 -1
  80. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__0t76rmc_vci18._.js +3 -0
  81. package/.next/standalone/.next/server/chunks/ssr/{[root-of-the-server]__1vofkb2oq7p7e._.js → [root-of-the-server]__0tayeyopslkf1._.js} +1 -1
  82. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1-ey9fgesfbc0._.js +1 -1
  83. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__15usvs-ms-0hf._.js +1 -1
  84. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__16gb3_92zvk5x._.js +1 -1
  85. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1avi2kypusyb_._.js +1 -1
  86. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__1r7drlqli-ado._.js +1 -1
  87. package/.next/standalone/.next/server/chunks/ssr/_0eoura3_9gjb-._.js +1 -1
  88. package/.next/standalone/.next/server/chunks/ssr/_0f-kswpk5hx7v._.js +3 -0
  89. package/.next/standalone/.next/server/chunks/ssr/_0pedwblqdoh58._.js +1 -1
  90. package/.next/standalone/.next/server/chunks/ssr/_1djqs9i27e4kg._.js +1 -1
  91. package/.next/standalone/.next/server/chunks/ssr/_next-internal_server_app_policies_page_actions_1sp2-yo5_vm5f.js +5 -5
  92. package/.next/standalone/.next/server/chunks/ssr/app_actions_get-scheduled-audit_ts_0ei9snixb5fd-._.js +1 -1
  93. package/.next/standalone/.next/server/chunks/ssr/app_audit__components_audit-dashboard_tsx_0p9ud47q0xq5w._.js +1 -1
  94. package/.next/standalone/.next/server/chunks/ssr/app_components_project-list_tsx_1ke6anr0vt64h._.js +1 -1
  95. package/.next/standalone/.next/server/chunks/ssr/app_global-error_tsx_1kp6l3x33jqb6._.js +1 -1
  96. package/.next/standalone/.next/server/chunks/ssr/app_policies_hooks-client_tsx_19dqvpcz0uxur._.js +1 -1
  97. package/.next/standalone/.next/server/chunks/ssr/app_settings_02tf1h47jmhhd._.js +1 -1
  98. package/.next/standalone/.next/server/chunks/ssr/{node_modules_html-to-image_es_index_0e3yg5gbcfsai.js → node_modules_html-to-image_es_index_0wgfci23_yqs_.js} +1 -1
  99. package/.next/standalone/.next/server/chunks/ssr/package_json_[json]_cjs_013tntikdft59._.js +1 -1
  100. package/.next/standalone/.next/server/chunks/ssr/src_hooks_1-ytegsicaf2d._.js +5 -0
  101. package/.next/standalone/.next/server/chunks/ssr/src_hooks_1euxn1va7c5gq._.js +5 -0
  102. package/.next/standalone/.next/server/chunks/ssr/src_hooks_daemon-client_ts_0k41_i7jg6ndv._.js +1 -1
  103. package/.next/standalone/.next/server/chunks/ssr/src_hooks_daemon-service_ts_0ibufora3s_bw._.js +1 -1
  104. package/.next/standalone/.next/server/chunks/ssr/src_hooks_effective-reviewers_ts_1h4wtvo55j16x._.js +3 -0
  105. package/.next/standalone/.next/server/middleware-build-manifest.js +13 -13
  106. package/.next/standalone/.next/server/pages/404.html +1 -1
  107. package/.next/standalone/.next/server/pages/500.html +1 -1
  108. package/.next/standalone/.next/server/preview-props.json +3 -3
  109. package/.next/standalone/.next/server/server-reference-manifest.js +1 -1
  110. package/.next/standalone/.next/server/server-reference-manifest.json +23 -23
  111. package/.next/standalone/.next/static/chunks/{0oxlfb02aqo3e.js → 0fqjv13piwa6z.js} +1 -1
  112. package/.next/standalone/.next/static/chunks/{1osrmi14e2jub.js → 0y9qczsccrmmf.js} +1 -1
  113. package/.next/standalone/.next/static/chunks/{0p14j2e6dnj1x.js → 0z70k3nof30ws.js} +1 -1
  114. package/.next/standalone/.next/static/chunks/{05g1pu2r8o5q3.js → 167exo9u6npy3.js} +1 -1
  115. package/.next/standalone/.next/static/chunks/{098vx6twrn-vk.js → 1xwh61k4505md.js} +1 -1
  116. package/.next/standalone/.next/static/chunks/{3d6_vjbvr0c2n.js → 24nikgpkr0qas.js} +1 -1
  117. package/.next/standalone/.next/static/chunks/{38lnk75xvqiug.js → 2ayu58wi805x4.js} +1 -1
  118. package/.next/standalone/.next/static/chunks/{0tiuj32d-qcy3.js → 2swcvie6i54dn.js} +1 -1
  119. package/.next/standalone/.next/static/chunks/2xx-2wehe-kwl.js +1 -0
  120. package/.next/standalone/.next/static/chunks/{1i9zuw01f0ogt.js → 3r-j6pmqrq4l1.js} +2 -2
  121. package/.next/standalone/.next/static/chunks/{2zwsbp8xyfv__.js → 3tfcj166ki-08.js} +1 -1
  122. package/.next/standalone/.next/static/chunks/{12ys9uaq6i1h2.js → 3uj5quosl7j_x.js} +1 -1
  123. package/.next/standalone/hermes-plugin/client.py +97 -37
  124. package/.next/standalone/hermes-plugin/plugin.yaml +1 -1
  125. package/.next/standalone/package.json +9 -9
  126. package/.next/standalone/server.js +1 -1
  127. package/bin/failproofai.mjs +66 -90
  128. package/dist/cli.mjs +1421 -1489
  129. package/dist/worker.mjs +19 -4
  130. package/hermes-plugin/client.py +97 -37
  131. package/hermes-plugin/plugin.yaml +1 -1
  132. package/openclaw-plugin/daemon-client.js +72 -16
  133. package/openclaw-plugin/hooks.js +12 -0
  134. package/package.json +9 -9
  135. package/pi-extension/index.ts +2 -0
  136. package/src/hooks/cloud-managed-policies.ts +22 -0
  137. package/src/hooks/config-status.ts +34 -21
  138. package/src/hooks/configure-wizard.ts +16 -3
  139. package/src/hooks/daemon-client.ts +59 -16
  140. package/src/hooks/daemon-service.ts +167 -19
  141. package/src/hooks/delivery-health.ts +10 -0
  142. package/src/hooks/fp-home.ts +8 -0
  143. package/src/hooks/fp-reset.ts +8 -2
  144. package/src/hooks/gateway-restart.ts +248 -0
  145. package/src/hooks/handler.ts +39 -2
  146. package/src/hooks/hermes-update.ts +18 -2
  147. package/src/hooks/hook-activity-store.ts +5 -0
  148. package/src/hooks/manager.ts +43 -9
  149. package/src/hooks/shell-quote.ts +19 -0
  150. package/src/hooks/update-run.ts +276 -0
  151. package/.next/standalone/.next/server/chunks/src_hooks_0_em82s16zfym._.js +0 -5
  152. package/.next/standalone/.next/server/chunks/ssr/[root-of-the-server]__05-glpesefmmi._.js +0 -3
  153. package/.next/standalone/.next/server/chunks/ssr/_0ge1hz9485xpp._.js +0 -3
  154. package/.next/standalone/.next/server/chunks/ssr/src_hooks_0agdmptetetdt._.js +0 -5
  155. package/.next/standalone/.next/server/chunks/ssr/src_hooks_0mdwgjisv4fub._.js +0 -5
  156. package/.next/standalone/.next/static/chunks/2o8j51ujh1ox4.js +0 -1
  157. /package/.next/standalone/.next/static/{-AugwIGiiIYcahO4J7mdM → _rnWxsoAWV0JPMURamq78}/_buildManifest.js +0 -0
  158. /package/.next/standalone/.next/static/{-AugwIGiiIYcahO4J7mdM → _rnWxsoAWV0JPMURamq78}/_clientMiddlewareManifest.js +0 -0
  159. /package/.next/standalone/.next/static/{-AugwIGiiIYcahO4J7mdM → _rnWxsoAWV0JPMURamq78}/_ssgManifest.js +0 -0
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Restart running Hermes and OpenClaw gateways after `failproofai update`, when
3
+ * they are next idle.
4
+ *
5
+ * A gateway is one long-lived process that imported our plugin when it
6
+ * started. npm replaces the plugin files on disk, but the gateway keeps running
7
+ * the code it already imported until it restarts — which nobody told it to.
8
+ *
9
+ * Both hosts ship a restart that waits for in-flight work, so this never has to
10
+ * judge "idle" itself:
11
+ * - Hermes: `hermes gateway restart` (SIGUSR1: refuse new turns, drain, exit;
12
+ * the service manager relaunches it).
13
+ * - OpenClaw: `openclaw gateway restart --safe` (restart after active work
14
+ * drains, bounded).
15
+ *
16
+ * Only a gateway a service manager is running is touched. Without one,
17
+ * `hermes gateway restart` stops the gateway and runs the new one in the
18
+ * FOREGROUND of the caller — `update` would hang holding someone's gateway. A
19
+ * hand-run gateway (tmux, `gateway run`) is left alone and reported as such.
20
+ *
21
+ * The restart is spawned detached, so `update` returns immediately while the
22
+ * host waits out its drain.
23
+ */
24
+ import { spawn, spawnSync } from "node:child_process";
25
+ import { chmodSync, closeSync, mkdirSync, openSync, readFileSync } from "node:fs";
26
+ import { dirname, join, resolve } from "node:path";
27
+ import { homedir } from "node:os";
28
+ import { listOpenClawProfiles, OPENCLAW_DEFAULT_PROFILE } from "../../lib/openclaw-profiles";
29
+ import { logsDir } from "./fp-home";
30
+
31
+ // integrations.ts's OPENCLAW_PLUGIN_ID; restated rather than imported so this
32
+ // module does not pull the whole integration table into `update`.
33
+ const OPENCLAW_PLUGIN_ID = "failproofai";
34
+
35
+ export type GatewayRestartStatus = "restarting" | "not-running" | "not-supervised" | "failed";
36
+
37
+ export interface GatewayRestart {
38
+ host: "hermes" | "openclaw";
39
+ profile: string;
40
+ status: GatewayRestartStatus;
41
+ }
42
+
43
+ export interface CommandResult {
44
+ status: number | null;
45
+ stdout: string;
46
+ }
47
+
48
+ export interface GatewayRestartDeps {
49
+ run?: (cmd: string, args: string[], env: NodeJS.ProcessEnv) => CommandResult;
50
+ spawnDetached?: (cmd: string, args: string[], env: NodeJS.ProcessEnv) => boolean;
51
+ openclawProfiles?: () => Array<{ name: string; home: string }>;
52
+ }
53
+
54
+ const STATUS_TIMEOUT_MS = 20_000;
55
+
56
+ function defaultRun(cmd: string, args: string[], env: NodeJS.ProcessEnv): CommandResult {
57
+ const out = spawnSync(cmd, args, {
58
+ env,
59
+ encoding: "utf8",
60
+ timeout: STATUS_TIMEOUT_MS,
61
+ // SIGTERM is the default, and a status command that handles it and stays
62
+ // stuck kept `update` from ever printing its report.
63
+ killSignal: "SIGKILL",
64
+ stdio: ["ignore", "pipe", "pipe"],
65
+ });
66
+ return { status: out.error ? null : out.status, stdout: `${out.stdout ?? ""}${out.stderr ?? ""}` };
67
+ }
68
+
69
+ function restartLogPath(): string {
70
+ return `${logsDir()}/gateway-restart.log`;
71
+ }
72
+
73
+ /**
74
+ * The gateways' restart output, owner-only like daemon.log. An existing file
75
+ * from before this was set is tightened too.
76
+ * @internal exported for tests
77
+ */
78
+ export function openRestartLog(): number {
79
+ const log = restartLogPath();
80
+ mkdirSync(dirname(log), { recursive: true, mode: 0o700 });
81
+ const fd = openSync(log, "a", 0o600);
82
+ chmodSync(log, 0o600);
83
+ return fd;
84
+ }
85
+
86
+ function defaultSpawnDetached(cmd: string, args: string[], env: NodeJS.ProcessEnv): boolean {
87
+ let fd: number | undefined;
88
+ try {
89
+ fd = openRestartLog();
90
+ const child = spawn(cmd, args, { env, detached: true, stdio: ["ignore", fd, fd] });
91
+ child.on("error", () => {});
92
+ child.unref();
93
+ return typeof child.pid === "number";
94
+ } catch {
95
+ return false;
96
+ } finally {
97
+ if (fd !== undefined) closeSync(fd);
98
+ }
99
+ }
100
+
101
+ /**
102
+ * What `hermes gateway status` prints when a service manager is running the
103
+ * gateway, verified on Hermes 0.20.0 and 0.21.3:
104
+ * - systemd: `✓ User gateway service is running` (`System …` for the system
105
+ * scope, which needs root to restart and is left alone);
106
+ * - launchd: `✓ Gateway is supervised by launchd (PID n)`.
107
+ * A detached fallback or hand-run gateway prints neither.
108
+ */
109
+ const HERMES_SUPERVISED = [/user gateway service is running/i, /supervised by launchd \(PID/i];
110
+ export function restartHermesGateway(
111
+ profile: { name: string; home: string },
112
+ deps: GatewayRestartDeps = {},
113
+ ): GatewayRestart {
114
+ try {
115
+ return restartHermesGatewayUnsafe(profile, deps);
116
+ } catch {
117
+ return { host: "hermes", profile: profile.name, status: "failed" };
118
+ }
119
+ }
120
+
121
+ function restartHermesGatewayUnsafe(
122
+ profile: { name: string; home: string },
123
+ deps: GatewayRestartDeps,
124
+ ): GatewayRestart {
125
+ const run = deps.run ?? defaultRun;
126
+ const spawnDetached = deps.spawnDetached ?? defaultSpawnDetached;
127
+ const env = { ...process.env, HERMES_HOME: profile.home };
128
+ const result = (status: GatewayRestartStatus): GatewayRestart => ({ host: "hermes", profile: profile.name, status });
129
+
130
+ const status = run("hermes", ["gateway", "status"], env);
131
+ if (status.status === null) return result("failed");
132
+ if (HERMES_SUPERVISED.some((line) => line.test(status.stdout))) {
133
+ return result(spawnDetached("hermes", ["gateway", "restart"], env) ? "restarting" : "failed");
134
+ }
135
+ // Running, but not under a service we may restart (system scope, a detached
136
+ // fallback, or by hand): every such status names the gateway's PID.
137
+ if (/gateway service is running|\(PID \d+\)/i.test(status.stdout)) return result("not-supervised");
138
+ return result("not-running");
139
+ }
140
+
141
+ interface OpenClawStatus {
142
+ service?: { loaded?: boolean; runtime?: { status?: string } };
143
+ }
144
+
145
+ export function restartOpenClawGateway(
146
+ profile: { name: string; home: string },
147
+ deps: GatewayRestartDeps = {},
148
+ ): GatewayRestart {
149
+ try {
150
+ return restartOpenClawGatewayUnsafe(profile, deps);
151
+ } catch {
152
+ return { host: "openclaw", profile: profile.name, status: "failed" };
153
+ }
154
+ }
155
+
156
+ function restartOpenClawGatewayUnsafe(
157
+ profile: { name: string; home: string },
158
+ deps: GatewayRestartDeps,
159
+ ): GatewayRestart {
160
+ const run = deps.run ?? defaultRun;
161
+ const spawnDetached = deps.spawnDetached ?? defaultSpawnDetached;
162
+ const profileArgs = profile.name === OPENCLAW_DEFAULT_PROFILE ? [] : ["--profile", profile.name];
163
+ const env = openclawProfileEnv(profile);
164
+ const result = (status: GatewayRestartStatus): GatewayRestart => ({ host: "openclaw", profile: profile.name, status });
165
+
166
+ const out = run("openclaw", [...profileArgs, "gateway", "status", "--json"], env);
167
+ if (out.status === null) return result("failed");
168
+ let parsed: OpenClawStatus;
169
+ try {
170
+ const start = out.stdout.indexOf("{");
171
+ parsed = JSON.parse(start >= 0 ? out.stdout.slice(start) : out.stdout) as OpenClawStatus;
172
+ } catch {
173
+ return result("failed");
174
+ }
175
+ if (parsed.service?.runtime?.status !== "running") return result("not-running");
176
+ if (parsed.service.loaded !== true) return result("not-supervised");
177
+
178
+ // `--safe` waits for active work. Older OpenClaw has no such flag; a plain
179
+ // restart there would cut a turn off, so it is left to the user.
180
+ const help = run("openclaw", ["gateway", "restart", "--help"], env);
181
+ if (!/--safe\b/.test(help.stdout)) return result("not-supervised");
182
+ return result(
183
+ spawnDetached("openclaw", [...profileArgs, "gateway", "restart", "--safe"], env) ? "restarting" : "failed",
184
+ );
185
+ }
186
+
187
+ /**
188
+ * The environment that selects exactly `profile`, and no other. Every OpenClaw
189
+ * profile selector inherited from the caller's shell is dropped: left in, the
190
+ * default row inherited an `OPENCLAW_PROFILE=ops` and acted on `ops`. A default
191
+ * profile living somewhere non-standard is named by its state directory.
192
+ */
193
+ export function openclawProfileEnv(
194
+ profile: { name: string; home: string },
195
+ base: NodeJS.ProcessEnv = process.env,
196
+ ): NodeJS.ProcessEnv {
197
+ const env = { ...base };
198
+ for (const key of ["OPENCLAW_PROFILE", "OPENCLAW_STATE_DIR", "OPENCLAW_HOME", "OPENCLAW_CONFIG_PATH"]) {
199
+ delete env[key];
200
+ }
201
+ // The account default is ~/.openclaw itself; a default profile anywhere else
202
+ // (a relocated `/srv/claw/.openclaw` included) is named by its directory.
203
+ if (profile.name === OPENCLAW_DEFAULT_PROFILE && resolve(profile.home) !== resolve(homedir(), ".openclaw")) {
204
+ env.OPENCLAW_STATE_DIR = profile.home;
205
+ }
206
+ return env;
207
+ }
208
+
209
+ /** Profiles whose openclaw.json loads our plugin; only their gateways run it. */
210
+ export function openclawProfilesUsingFailproofai(): Array<{ name: string; home: string }> {
211
+ return listOpenClawProfiles().filter((profile) => {
212
+ try {
213
+ const settings = JSON.parse(readFileSync(join(profile.home, "openclaw.json"), "utf8")) as {
214
+ plugins?: { entries?: Record<string, { enabled?: unknown }> };
215
+ };
216
+ return settings.plugins?.entries?.[OPENCLAW_PLUGIN_ID]?.enabled === true;
217
+ } catch {
218
+ return false;
219
+ }
220
+ });
221
+ }
222
+
223
+ export function restartOpenClawGateways(deps: GatewayRestartDeps = {}): GatewayRestart[] {
224
+ const profiles = (deps.openclawProfiles ?? openclawProfilesUsingFailproofai)();
225
+ return profiles.map((profile) => restartOpenClawGateway(profile, deps));
226
+ }
227
+
228
+ /**
229
+ * `update`'s OpenClaw block, shaped like its Hermes block: a heading over one
230
+ * row per profile, and nothing at all when no gateway had anything to report.
231
+ */
232
+ export function openclawRestartLines(restarts: GatewayRestart[]): string[] {
233
+ const rows = restarts.filter((r) => GATEWAY_STATUS_LABEL[r.status]);
234
+ if (rows.length === 0) return [];
235
+ const width = Math.max(...rows.map((r) => `openclaw/${r.profile}`.length));
236
+ return [
237
+ "OpenClaw:",
238
+ ...rows.map((r) => ` ${`openclaw/${r.profile}`.padEnd(width)} ${GATEWAY_STATUS_LABEL[r.status]}`),
239
+ ];
240
+ }
241
+
242
+ /** The word appended to a gateway's existing report row. */
243
+ export const GATEWAY_STATUS_LABEL: Record<GatewayRestartStatus, string> = {
244
+ restarting: "gateway restarting",
245
+ "not-running": "",
246
+ "not-supervised": "restart the gateway",
247
+ failed: "restart the gateway",
248
+ };
@@ -94,6 +94,29 @@ import { isHealthProbe } from "./health-probe";
94
94
  import { readRuntimeAgentIdentity, runtimeAgentSettingsPath } from "./agent-roster";
95
95
  import type { AgentIdentity } from "./agent-targets";
96
96
 
97
+ /** Set once the legacy-shim warning has been logged in this process. */
98
+ let legacyShimWarned = false;
99
+
100
+ /**
101
+ * The agent's own id for the tool call a hook payload is about: Claude, Devin,
102
+ * Factory and Pi (via its shim) send `tool_use_id`, Devin also
103
+ * `tool_call_id`, Hermes nests it under `hermes.tool_call_id`. It is the id the
104
+ * agent's transcript records that call under, so a hook event that carries it
105
+ * joins the transcript events for the same call instead of being placed
106
+ * beside them by timestamp alone.
107
+ */
108
+ export function toolCallIdOf(parsed: Record<string, unknown>): string | undefined {
109
+ const hermes = parsed.hermes;
110
+ const nested =
111
+ hermes && typeof hermes === "object" && !Array.isArray(hermes)
112
+ ? (hermes as Record<string, unknown>).tool_call_id
113
+ : undefined;
114
+ for (const value of [parsed.tool_use_id, parsed.tool_call_id, parsed.toolCallId, parsed.toolUseId, nested]) {
115
+ if (typeof value === "string" && value.length > 0 && value.length <= 256) return value;
116
+ }
117
+ return undefined;
118
+ }
119
+
97
120
  /**
98
121
  * Canonicalize an event name to PascalCase. Codex sends snake_case event names
99
122
  * on stdin and as the --hook arg; Cursor sends camelCase (`preToolUse`,
@@ -648,6 +671,9 @@ export async function evaluateHookEvent(
648
671
  opts?: EvaluateHookEventOptions,
649
672
  ): Promise<HookEventOutcome> {
650
673
  const startTime = performance.now();
674
+ // Wall clock at arrival, for the activity row's `startedAt`. Taken here, not
675
+ // derived from `durationMs`, which is measured before the work after it.
676
+ const arrivedAt = Date.now();
651
677
  // A home from another layout resolves to no global config, so every builtin
652
678
  // silently stops firing — the machine looks protected and is not. Say so on
653
679
  // every call rather than deleting anything (a hook is unattended) or denying
@@ -796,7 +822,10 @@ export async function evaluateHookEvent(
796
822
  // so an empty list still registers the guard — which is exactly what this
797
823
  // build should contribute once packs carry everything else.
798
824
  registerBuiltinPolicies(activePause ? [] : legacyNames);
799
- if (legacyNames.length > 0) {
825
+ // Once per process: the warm worker evaluates every hook on the machine,
826
+ // and repeating this on each one buried the daemon log.
827
+ if (legacyNames.length > 0 && !legacyShimWarned) {
828
+ legacyShimWarned = true;
800
829
  hookLogWarn(
801
830
  `enforcing ${legacyNames.length} policies from this build because no pack is installed — ` +
802
831
  `run \`failproofai policies add FailproofAI/policies\` to move them into a real pack`,
@@ -1240,8 +1269,16 @@ export async function evaluateHookEvent(
1240
1269
  const jevOrigin = result.policyName && result.twoTier?.decidedByJev ? result.twoTier.jevOrigin : undefined;
1241
1270
 
1242
1271
  // Persist activity to disk (visible in /policies activity tab)
1272
+ const writtenAt = Date.now();
1273
+ const toolCallId = toolCallIdOf(parsed);
1243
1274
  const activityEntry = {
1244
- timestamp: Date.now(),
1275
+ timestamp: writtenAt,
1276
+ // When the hook arrived. `timestamp` is when its evaluation ENDED, so a
1277
+ // hook start ordered by it sorted late by the whole evaluation.
1278
+ startedAt: Math.min(arrivedAt, writtenAt),
1279
+ // The agent's own id for the tool call this hook governed, the key its
1280
+ // transcript records the call under (see `toolCallIdOf`).
1281
+ ...(toolCallId ? { toolCallId } : {}),
1245
1282
  eventType: canonicalEventType,
1246
1283
  integration: cli,
1247
1284
  toolName: (parsed.tool_name as string) ?? null,
@@ -15,6 +15,7 @@
15
15
  * invisible.
16
16
  */
17
17
  import { migrateHermesProfiles, type HermesPluginInstallDeps, type HermesProfileMigration } from "./integrations";
18
+ import { GATEWAY_STATUS_LABEL, type GatewayRestart } from "./gateway-restart";
18
19
 
19
20
  export interface HermesUpdateResult {
20
21
  ok: boolean;
@@ -33,6 +34,11 @@ const STATUS_LABEL: Record<HermesProfileMigration["status"], string> = {
33
34
  export async function runHermesUpdateMigration(deps: {
34
35
  daemonSupportsPolicyEvaluation: () => Promise<boolean>;
35
36
  installDeps?: HermesPluginInstallDeps;
37
+ /**
38
+ * Restarts a profile's running gateway so it loads the plugin now on disk.
39
+ * Left out (`update --no-restart`), gateways are not touched.
40
+ */
41
+ restartGateway?: (profile: { name: string; home: string }) => GatewayRestart;
36
42
  }): Promise<HermesUpdateResult> {
37
43
  const profiles = await migrateHermesProfiles(deps);
38
44
  const relevant = profiles.filter((p) => p.status !== "untouched");
@@ -41,17 +47,27 @@ export async function runHermesUpdateMigration(deps: {
41
47
 
42
48
  const width = Math.max(...profiles.map((p) => ("hermes/" + p.name).length));
43
49
  const lines = ["Hermes:"];
50
+ let restarting = false;
44
51
  for (const p of profiles) {
45
52
  const label = ("hermes/" + p.name).padEnd(width);
46
53
  const detail = p.status === "current" ? "" : ` — ${p.detail}`;
47
- lines.push(` ${label} ${STATUS_LABEL[p.status]}${detail}`);
54
+ // Only a profile now on the linked plugin has new code for its gateway.
55
+ const loaded = p.status === "migrated" || p.status === "current";
56
+ const restart = loaded && deps.restartGateway ? deps.restartGateway(p).status : null;
57
+ if (restart === "restarting") restarting = true;
58
+ const gateway = restart ? GATEWAY_STATUS_LABEL[restart] : "";
59
+ lines.push(` ${label} ${STATUS_LABEL[p.status]}${detail}${gateway ? `, ${gateway}` : ""}`);
48
60
  }
49
61
 
50
62
  const blocked = profiles.filter((p) => p.status === "blocked");
51
63
  const failed = profiles.filter((p) => p.status === "failed");
52
64
  if (profiles.some((p) => p.status === "migrated")) {
53
65
  lines.push(
54
- " Cron jobs load the plugin on their next run; restart running Hermes gateways and sessions to load it there.",
66
+ // A gateway already queued for restart must not also be restarted by
67
+ // hand: that interrupts its drain.
68
+ restarting
69
+ ? " Cron jobs load the plugin on their next run; restart running Hermes sessions to load it there."
70
+ : " Cron jobs load the plugin on their next run; restart running Hermes gateways and sessions to load it there.",
55
71
  );
56
72
  }
57
73
  if (blocked.length > 0) {
@@ -54,7 +54,12 @@ let rotateSeq = 0;
54
54
  // ── Types ──
55
55
 
56
56
  export interface HookActivityEntry {
57
+ /** When the row was written: the END of the hook's evaluation. */
57
58
  timestamp: number;
59
+ /** When the hook arrived (`timestamp - durationMs`). Absent on older rows. */
60
+ startedAt?: number;
61
+ /** The agent's own id for the tool call this hook governed, when it sent one. */
62
+ toolCallId?: string;
58
63
  eventType: string;
59
64
  /** Which agent CLI fired the hook (claude | codex). */
60
65
  integration?: string;
@@ -33,6 +33,7 @@ import { CliError } from "../cli-error";
33
33
  import { hookLogWarn } from "./hook-logger";
34
34
  import { customPoliciesDir } from "./fp-home";
35
35
  import { listActiveCloudManagedPolicies, readCloudJevAssignments, readCloudJevState, type CloudJevMode } from "./cloud-managed-policies";
36
+ import { readCloudCredentials } from "./cloud-enrollment";
36
37
  import { readCloudPolicyErrors } from "./cloud-policy-errors";
37
38
  import { readRosterLabels } from "./agent-roster";
38
39
  import { CORE_SOURCE, addPack, setPackPolicyEnabled } from "./pack-store";
@@ -334,16 +335,23 @@ export function integrationsInstalledAt(scope: HookScope, cwd?: string): Integra
334
335
  */
335
336
  export type NotEnforcingReason = "no-hooks" | "no-policies" | "observe-only";
336
337
 
337
- /** Machine-wide assignments, like the listing: a `both` policy counts once. */
338
- function cloudPolicyStatus(): { count: number; observing: boolean } {
338
+ /**
339
+ * Machine-wide assignments, like the listing: a `both` policy counts once.
340
+ * `observingCount` is what `config --status` shows beside `count`; both read
341
+ * this one function so its policies row and this line cannot disagree.
342
+ */
343
+ export function cloudPolicyStatus(): { count: number; observing: boolean; observingCount: number } {
339
344
  let count = 0;
340
345
  let observing = false;
346
+ let observingCount = 0;
341
347
  const jsIds = new Set<string>();
342
348
  try {
343
349
  for (const artifact of listActiveCloudManagedPolicies()) {
344
350
  jsIds.add(artifact.id);
345
- if (artifact.effect === "observe") observing = true;
346
- else count++;
351
+ if (artifact.effect === "observe") {
352
+ observing = true;
353
+ observingCount++;
354
+ } else count++;
347
355
  }
348
356
  } catch {
349
357
  // The listing reports an unreadable JS deployment; Jev is read independently.
@@ -353,14 +361,16 @@ function cloudPolicyStatus(): { count: number; observing: boolean } {
353
361
  if (jevMode === "enforce" || jevMode === "observe") {
354
362
  for (const assignment of readCloudJevAssignments() ?? []) {
355
363
  if (jsIds.has(assignment.id)) continue;
356
- if (jevMode === "observe" || assignment.effect === "observe") observing = true;
357
- else count++;
364
+ if (jevMode === "observe" || assignment.effect === "observe") {
365
+ observing = true;
366
+ observingCount++;
367
+ } else count++;
358
368
  }
359
369
  }
360
370
  } catch {
361
371
  // No readable Jev state: neither enforcement nor observation is known.
362
372
  }
363
- return { count, observing };
373
+ return { count, observing, observingCount };
364
374
  }
365
375
 
366
376
  export function notEnforcingReason(cwd?: string): NotEnforcingReason | null {
@@ -1284,8 +1294,30 @@ export interface PoliciesScreen {
1284
1294
  * nothing for a machine enforcing all of them.
1285
1295
  */
1286
1296
  legacy?: Array<{ name: string; description: string }>;
1297
+ /**
1298
+ * The Cloud dashboard this machine pulls its policies from, when it does.
1299
+ * Its policies are deployed there, so the empty state points there instead
1300
+ * of at installing packs.
1301
+ */
1302
+ cloudDashboard?: string;
1303
+ }
1304
+
1305
+ /** The dashboard a cloud-connected machine pulls policies from, or undefined. */
1306
+ export function cloudDashboardUrl(): string | undefined {
1307
+ // FAILPROOFAI_CLOUD_URL wins over the credential file in the daemon, so a
1308
+ // machine connected that way pulls from Cloud too.
1309
+ const fromEnv = process.env.FAILPROOFAI_CLOUD_URL?.trim();
1310
+ if (fromEnv) return fromEnv;
1311
+ try {
1312
+ return readCloudCredentials()?.url || undefined;
1313
+ } catch {
1314
+ return undefined;
1315
+ }
1287
1316
  }
1288
1317
 
1318
+ /** @internal */
1319
+ export const cloudDashboardUrlForTest = cloudDashboardUrl;
1320
+
1289
1321
  /**
1290
1322
  * The policies screen (decision D14: "the policies list exactly as designed").
1291
1323
  *
@@ -1341,7 +1373,9 @@ export function renderPoliciesScreen(
1341
1373
  const { failed, text, fix } = screen.attention;
1342
1374
  out.push(failed ? kit.fail(text, fix) : kit.caution(text, fix));
1343
1375
  }
1344
- if (empty) {
1376
+ if (empty && screen.cloudDashboard) {
1377
+ out.push(`${INDENT}Deploy from Cloud: ${kit.cmd(screen.cloudDashboard)}`);
1378
+ } else if (empty) {
1345
1379
  // Ours first is a convenience, not a channel: a screen that named only ours
1346
1380
  // would read as the place policies come from.
1347
1381
  out.push(
@@ -1800,7 +1834,7 @@ export async function listHooks(cwd?: string, { all = false }: { all?: boolean }
1800
1834
  printBlock(
1801
1835
  process.stdout,
1802
1836
  renderPoliciesScreen(
1803
- { packs, refused, attention, custom, convention, cloud, legacy },
1837
+ { packs, refused, attention, custom, convention, cloud, legacy, cloudDashboard: cloudDashboardUrl() },
1804
1838
  // Descriptions are shortened only for a terminal; a pipe keeps every word.
1805
1839
  { ...optsFor(process.stdout), fit: Boolean(process.stdout.isTTY), all },
1806
1840
  ),
@@ -7,3 +7,22 @@
7
7
  export function shellQuote(value: string): string {
8
8
  return `'${value.replace(/'/g, `'\\''`)}'`;
9
9
  }
10
+
11
+ /**
12
+ * The words of a command built from {@link shellQuote}d parts, unquoted. Only
13
+ * that shape is understood; anything else (an operator's own
14
+ * `FAILPROOFAI_WORKER_CMD`) returns null, and callers leave it alone.
15
+ */
16
+ export function shellQuotedWords(command: string): string[] | null {
17
+ const words: string[] = [];
18
+ const re = /\s*'((?:[^']|'\\'')*)'(?=\s|$)/y;
19
+ // Kept apart from `re.lastIndex`, which a failed sticky match resets to 0:
20
+ // a trailing space after the last word then read as "nothing matched".
21
+ let end = 0;
22
+ let match: RegExpExecArray | null;
23
+ while (end < command.length && (match = re.exec(command))) {
24
+ words.push(match[1].replace(/'\\''/g, "'"));
25
+ end = re.lastIndex;
26
+ }
27
+ return words.length > 0 && command.slice(end).trim() === "" ? words : null;
28
+ }