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
@@ -61,7 +61,7 @@ import {
61
61
  settingsPathsFor,
62
62
  } from "./integrations";
63
63
  import { INTEGRATION_TYPES, type IntegrationType, type HookScope } from "./types";
64
- import { enforcingPolicyCount, installHooks, notEnforcingReason } from "./manager";
64
+ import { cloudDashboardUrl, enforcingPolicyCount, installHooks, notEnforcingReason } from "./manager";
65
65
  import { installAgentSkill } from "./agent-skill";
66
66
  import {
67
67
  CODEX_UNTRUSTED_NOTICE,
@@ -1613,6 +1613,7 @@ export async function runConfigureWizard(
1613
1613
  agents: selected.length,
1614
1614
  connected: cloudAfter,
1615
1615
  codexTrust,
1616
+ cloudDashboard: cloudAfter ? cloudDashboardUrl() : undefined,
1616
1617
  }),
1617
1618
  );
1618
1619
 
@@ -1840,7 +1841,16 @@ function failClosedPacks(): Array<{ id: string | null }> {
1840
1841
  */
1841
1842
  export function doneLines(
1842
1843
  kit: ReturnType<typeof screenKit>,
1843
- state: { elapsedMs: number; done: string[]; cwd: string; agents: number; connected: boolean; codexTrust?: CodexHookTrust },
1844
+ state: {
1845
+ elapsedMs: number;
1846
+ done: string[];
1847
+ cwd: string;
1848
+ agents: number;
1849
+ connected: boolean;
1850
+ codexTrust?: CodexHookTrust;
1851
+ /** Set when this machine pulls its policies from Cloud: point there, not at packs. */
1852
+ cloudDashboard?: string;
1853
+ },
1844
1854
  ): string[] {
1845
1855
  const lines = [kit.head("Done", `in ${(state.elapsedMs / 1000).toFixed(1)}s`), ...state.done];
1846
1856
  // Codex with untrusted hooks runs none of them: it is not an agent anything
@@ -1851,7 +1861,10 @@ export function doneLines(
1851
1861
  if (notEnforcingReason(state.cwd)) {
1852
1862
  lines.push(
1853
1863
  kit.caution("Policies are not enforcing yet."),
1854
- ` Turn on ours: ${kit.cmd(`failproofai policies add ${CORE_SOURCE}`)}`,
1864
+ // The same line the policies screen's empty state uses for such a machine.
1865
+ state.cloudDashboard
1866
+ ? ` Deploy from Cloud: ${kit.cmd(state.cloudDashboard)}`
1867
+ : ` Turn on ours: ${kit.cmd(`failproofai policies add ${CORE_SOURCE}`)}`,
1855
1868
  );
1856
1869
  } else {
1857
1870
  const { count, custom } = enforcingPolicyCount(state.cwd);
@@ -15,8 +15,13 @@ import type { IntegrationType } from "./types";
15
15
  import { existsSync } from "node:fs";
16
16
  import { daemonSocket as daemonSocketPath } from "./fp-home";
17
17
  import { readConfig } from "./fp-config";
18
+ import { cloudDeploymentMayTargetAgents } from "./cloud-managed-policies";
18
19
 
19
20
  const PROTOCOL_VERSION = 2;
21
+ /** Oldest daemon version this client falls back to (crates/fpai-ipc MIN_PROTOCOL_VERSION). */
22
+ const MIN_PROTOCOL_VERSION = 1;
23
+ /** First version carrying `agentSettingsPath`; an older daemon is sent none. */
24
+ const AGENT_SETTINGS_PATH_SINCE = 2;
20
25
 
21
26
  /**
22
27
  * Reaching the daemon and getting an answer out of it are two different
@@ -114,7 +119,7 @@ interface DaemonRequestOptions {
114
119
 
115
120
  type DaemonWireAttempt =
116
121
  | { ok: true; message: Record<string, unknown> }
117
- | { ok: false; failure: DaemonFailure };
122
+ | { ok: false; failure: DaemonFailure; daemonVersion?: number };
118
123
 
119
124
  /**
120
125
  * Whether a daemon is listening, regardless of how it was started.
@@ -205,9 +210,44 @@ function encodeFrame(value: unknown): Buffer {
205
210
  * integrations share the transport, but require different response variants.
206
211
  */
207
212
  async function attemptDaemonRequest(
208
- request: Record<string, unknown>,
213
+ build: (protocolVersion: number) => Record<string, unknown>,
214
+ opts?: DaemonRequestOptions,
215
+ ): Promise<DaemonWireAttempt> {
216
+ const first = await attemptDaemonRequestAt(PROTOCOL_VERSION, build, opts);
217
+ // An older daemon still inside the supported range: ask again in its version
218
+ // rather than deny every call until it is replaced.
219
+ const older = !first.ok ? first.daemonVersion : undefined;
220
+ if (
221
+ older === undefined ||
222
+ !Number.isInteger(older) ||
223
+ older < MIN_PROTOCOL_VERSION ||
224
+ older >= PROTOCOL_VERSION ||
225
+ // The older daemon would evaluate without this agent, and a deployment
226
+ // with agent-targeted policies (schema 3) does not apply them to an
227
+ // unknown one: its answer could allow what they deny. One that cannot be
228
+ // read cannot be ruled out.
229
+ cloudDeploymentMayTargetAgents()
230
+ ) {
231
+ return withoutDaemonVersion(first);
232
+ }
233
+ const retried = await attemptDaemonRequestAt(older, build, opts);
234
+ // Asked again AFTER the answer: Cloud may have activated a targeted
235
+ // deployment while the older daemon was evaluating, and then its answer
236
+ // (made without this agent) is no safer than if it had been asked then.
237
+ if (cloudDeploymentMayTargetAgents()) return withoutDaemonVersion(first);
238
+ return withoutDaemonVersion(retried);
239
+ }
240
+
241
+ function withoutDaemonVersion(attempt: DaemonWireAttempt): DaemonWireAttempt {
242
+ return attempt.ok ? attempt : { ok: false, failure: attempt.failure };
243
+ }
244
+
245
+ async function attemptDaemonRequestAt(
246
+ protocolVersion: number,
247
+ build: (protocolVersion: number) => Record<string, unknown>,
209
248
  opts?: DaemonRequestOptions,
210
249
  ): Promise<DaemonWireAttempt> {
250
+ const request = build(protocolVersion);
211
251
  // Windows never has a daemon in this phase (see the plan's platform
212
252
  // scope) — skip the attempt outright rather than depending on however
213
253
  // Node happens to behave when handed a POSIX socket path on Windows.
@@ -278,12 +318,11 @@ async function attemptDaemonRequest(
278
318
  }
279
319
  const message = parsed as Record<string, unknown>;
280
320
 
281
- if (message.protocolVersion !== PROTOCOL_VERSION) {
282
- // Catches BOTH directions. A newer CLI sends v2 and the daemon replies
283
- // with an error stamped v1; an older CLI sends v1 and a newer daemon
284
- // replies stamped v2. Either way the versions disagree here, and either
285
- // way a daemon answered — so this is skew, not absence.
286
- fail("protocol-mismatch");
321
+ if (message.protocolVersion !== protocolVersion) {
322
+ // A daemon answered in another version — skew, not absence. When it is
323
+ // older, the caller retries once in that version.
324
+ const daemonVersion = typeof message.protocolVersion === "number" ? message.protocolVersion : undefined;
325
+ finish({ ok: false, failure: "protocol-mismatch", daemonVersion });
287
326
  return;
288
327
  }
289
328
  finish({ ok: true, message });
@@ -294,21 +333,25 @@ async function attemptDaemonRequest(
294
333
  });
295
334
  }
296
335
 
336
+ function settingsPathFor(protocolVersion: number, agentSettingsPath: string | undefined) {
337
+ return protocolVersion >= AGENT_SETTINGS_PATH_SINCE ? { agentSettingsPath } : {};
338
+ }
339
+
297
340
  /** Attempts a shell-hook daemon evaluation while preserving the failure category. */
298
341
  export async function attemptDaemonHook(
299
342
  req: DaemonHookRequest,
300
343
  opts?: DaemonRequestOptions,
301
344
  ): Promise<DaemonAttempt> {
302
345
  const attempt = await attemptDaemonRequest(
303
- {
346
+ (protocolVersion) => ({
304
347
  type: "hook",
305
- protocolVersion: PROTOCOL_VERSION,
348
+ protocolVersion,
306
349
  hookEvent: req.hookEvent,
307
350
  cli: req.cli,
308
351
  stdin: req.stdin,
309
352
  cwd: req.cwd,
310
- agentSettingsPath: req.agentSettingsPath,
311
- },
353
+ ...settingsPathFor(protocolVersion, req.agentSettingsPath),
354
+ }),
312
355
  opts,
313
356
  );
314
357
  if (!attempt.ok) return attempt;
@@ -351,15 +394,15 @@ export async function attemptDaemonPolicyEvaluation(
351
394
  opts?: DaemonRequestOptions,
352
395
  ): Promise<DaemonPolicyEvaluationAttempt> {
353
396
  const attempt = await attemptDaemonRequest(
354
- {
397
+ (protocolVersion) => ({
355
398
  type: "policyEvaluation",
356
- protocolVersion: PROTOCOL_VERSION,
399
+ protocolVersion,
357
400
  integration: req.integration,
358
401
  event: req.event,
359
402
  payload: req.payload,
360
403
  cwd: req.cwd,
361
- agentSettingsPath: req.agentSettingsPath,
362
- },
404
+ ...settingsPathFor(protocolVersion, req.agentSettingsPath),
405
+ }),
363
406
  opts,
364
407
  );
365
408
  if (!attempt.ok) return attempt;
@@ -14,6 +14,7 @@ import {
14
14
  mkdtempSync,
15
15
  readFileSync,
16
16
  readdirSync,
17
+ realpathSync,
17
18
  statSync,
18
19
  writeFileSync,
19
20
  unlinkSync,
@@ -25,7 +26,7 @@ import { execFileSync } from "node:child_process";
25
26
  import { hookLogWarn } from "./hook-logger";
26
27
  import { downloadFailproofaidBinary, installFromNpmPackage, installedBinaryPath } from "./daemon-download";
27
28
  import { logsDir } from "./fp-home";
28
- import { shellQuote } from "./shell-quote";
29
+ import { shellQuote, shellQuotedWords } from "./shell-quote";
29
30
  import { version } from "../../package.json";
30
31
  import { readVersionFile, updateConfig, writeVersionFile } from "./fp-config";
31
32
 
@@ -258,7 +259,78 @@ export function resolveWorkerCommand(): string | null {
258
259
  // silently, on exactly the machines least likely to notice. execPath is
259
260
  // whatever runtime is executing this CLI right now (node for the published
260
261
  // bin, bun in a source checkout), absolute either way.
261
- return `${shellQuote(process.execPath)} ${shellQuote(workerScript)}`;
262
+ return `${shellQuote(stableExecPath())} ${shellQuote(workerScript)}`;
263
+ }
264
+
265
+ /**
266
+ * `process.execPath`, or a stable link to the same binary when one is on PATH.
267
+ *
268
+ * execPath is the RESOLVED path, and some installers version it: Homebrew's is
269
+ * `/opt/homebrew/Cellar/node/<version>/bin/node`, which `brew upgrade node`
270
+ * deletes, while `/opt/homebrew/bin/node` and the global packages under
271
+ * `/opt/homebrew/lib/node_modules` survive. A service saved with the Cellar
272
+ * path then ran nothing after the upgrade — the daemon stayed up, its worker
273
+ * could not start, and every hook was denied. A PATH entry that resolves to
274
+ * the same file is the same runtime today and still names one tomorrow.
275
+ *
276
+ * nvm has no such link (its global packages live inside each version), so
277
+ * execPath is kept there; `failproofai update` repairs a service whose saved
278
+ * path is gone (see {@link daemonServiceNeedsUpgrade}).
279
+ */
280
+ export function stableExecPath(
281
+ execPath: string = process.execPath,
282
+ pathEnv: string = process.env.PATH ?? "",
283
+ stableDirs: readonly string[] = STABLE_BIN_DIRS,
284
+ ): string {
285
+ let real: string;
286
+ try {
287
+ real = realpathSync(execPath);
288
+ } catch {
289
+ return execPath;
290
+ }
291
+ const name = execPath.split("/").pop() ?? "";
292
+ for (const dir of pathEnv.split(":")) {
293
+ // Only a system bin directory a package manager owns: any PATH entry would
294
+ // let a temporary one (a dev shell, a CI step) be saved into the service
295
+ // and vanish after setup, taking the worker's runtime with it.
296
+ if (!dir.startsWith("/") || !stableDirs.includes(dir.replace(/\/+$/, ""))) continue;
297
+ const candidate = resolve(dir, name);
298
+ if (candidate === execPath) return execPath;
299
+ try {
300
+ if (realpathSync(candidate) === real) return candidate;
301
+ } catch {
302
+ // Not there: try the next entry.
303
+ }
304
+ }
305
+ return execPath;
306
+ }
307
+
308
+ /** Where Homebrew, Linuxbrew and the distributions keep a stable `node` link. */
309
+ const STABLE_BIN_DIRS: readonly string[] = [
310
+ "/opt/homebrew/bin",
311
+ "/usr/local/bin",
312
+ "/usr/bin",
313
+ "/home/linuxbrew/.linuxbrew/bin",
314
+ ];
315
+
316
+ /**
317
+ * Whether a saved `FAILPROOFAI_WORKER_CMD` / `FAILPROOFAI_CLI_CMD` is one this
318
+ * package generated: `'<runtime>' '<package>/dist/worker.mjs'` (or `cli.mjs`).
319
+ * Quoting alone does not say so, since an operator can quote their own.
320
+ */
321
+ function isPackageCommand(command: string | null): boolean {
322
+ const words = command ? shellQuotedWords(command) : null;
323
+ const script = words?.at(-1);
324
+ return words?.length === 2 && script !== undefined && /\/dist\/(worker|cli)\.mjs$/.test(script);
325
+ }
326
+
327
+ /**
328
+ * Whether a saved command this package generated names a file that no longer
329
+ * exists. An operator's own command is never second-guessed.
330
+ */
331
+ function savedCommandIsGone(command: string | null): boolean {
332
+ if (!isPackageCommand(command)) return false;
333
+ return shellQuotedWords(command!)!.some((word) => !existsSync(word));
262
334
  }
263
335
 
264
336
  /**
@@ -288,7 +360,7 @@ export function resolveCliCommand(): string | null {
288
360
  if (!packageRoot) return null;
289
361
  const cliScript = resolve(packageRoot, "dist", "cli.mjs");
290
362
  if (!existsSync(cliScript)) return null;
291
- return `${shellQuote(process.execPath)} ${shellQuote(cliScript)}`;
363
+ return `${shellQuote(stableExecPath())} ${shellQuote(cliScript)}`;
292
364
  }
293
365
 
294
366
 
@@ -348,6 +420,11 @@ export function workerScriptPath(): string | null {
348
420
  */
349
421
  const UNIT_UNSAFE_RE = /["\\\r\n]/;
350
422
 
423
+ /** A literal `%` in a unit value, written so systemd does not expand it. */
424
+ function escapeUnitPercent(value: string): string {
425
+ return value.replace(/%/g, "%%");
426
+ }
427
+
351
428
  /** Throws when a value cannot be safely interpolated into a unit file. */
352
429
  function assertUnitSafe(value: string, field: string): string {
353
430
  if (UNIT_UNSAFE_RE.test(value)) {
@@ -705,7 +782,13 @@ export function writePrivilegedFile(destination: string, contents: string, mode
705
782
  const staging = resolve(stagingDir, "service-definition");
706
783
  try {
707
784
  writeFileSync(staging, contents, "utf8");
708
- runPrivileged("install", ["-m", mode, staging, destination]);
785
+ // Installed beside the destination and renamed over it: `install` onto
786
+ // the destination unlinks the old file before copying, so a copy that
787
+ // failed part-way left no definition (launchd then cannot load the job
788
+ // at boot). A rename within one directory is atomic.
789
+ const sibling = `${destination}.failproofai-new`;
790
+ runPrivileged("install", ["-m", mode, staging, sibling]);
791
+ runPrivileged("mv", ["-f", sibling, destination]);
709
792
  } finally {
710
793
  rmSync(stagingDir, { recursive: true, force: true });
711
794
  }
@@ -777,7 +860,14 @@ export function systemdUnitContents(
777
860
  // Quoted because every value here contains a space or a path — systemd's
778
861
  // Environment= requires quoting whenever the value does.
779
862
  const envLines = serviceEnvironment(workerCmd, cliCmd)
780
- .map(([key, value]) => `Environment="${key}=${assertUnitSafe(value, key)}"\n`)
863
+ // `%` is a specifier inside a unit (`%n` is the unit name, `%h` a home),
864
+ // so in a command this package generated a literal one is written `%%`, or
865
+ // the path silently changes. An operator's own command is written as they
866
+ // saved it: its specifiers (`%i`, say) are meant.
867
+ .map(([key, value]) => {
868
+ const safe = assertUnitSafe(value, key);
869
+ return `Environment="${key}=${isPackageCommand(safe) ? escapeUnitPercent(safe) : safe}"\n`;
870
+ })
781
871
  .join("");
782
872
  const user = assertUnitSafe(serviceUser(), "User");
783
873
  assertUnitSafe(binaryPath, "ExecStart");
@@ -823,11 +913,15 @@ export function systemdUnitContents(
823
913
  // a command-with-arguments is not. Same rule the worker script already
824
914
  // follows — never gate on a path that is not there, or the freshly installed
825
915
  // unit skips on its very first start.
826
- const conditionPaths = [binaryPath, workerScriptPath()].filter(
916
+ // The package's worker script only when the unit runs it: an operator's own
917
+ // worker command does not need it, and gating on it skipped a service whose
918
+ // wrapper was intact once the unused script was removed.
919
+ const workerScript = workerCmd === null || isPackageCommand(workerCmd) ? workerScriptPath() : null;
920
+ const conditionPaths = [binaryPath, workerScript].filter(
827
921
  (p): p is string => typeof p === "string" && existsSync(p),
828
922
  );
829
923
  const conditionLines = conditionPaths
830
- .map((p) => `ConditionPathExists=${assertUnitSafe(p, "ConditionPathExists")}\n`)
924
+ .map((p) => `ConditionPathExists=${escapeUnitPercent(assertUnitSafe(p, "ConditionPathExists"))}\n`)
831
925
  .join("");
832
926
 
833
927
  return `[Unit]
@@ -985,12 +1079,23 @@ export async function installDaemonService(): Promise<DaemonInstallResult> {
985
1079
  // and threading it through as an absolute path in the service's
986
1080
  // environment is what makes a *service-managed* daemon actually find its
987
1081
  // worker regardless of what cwd the service manager starts it from.
988
- const workerCmd = resolveWorkerCommand();
1082
+ // An operator's own worker command saved in the service survives a
1083
+ // reinstall (one an expired audit path forces, say) when the shell running
1084
+ // it no longer exports FAILPROOFAI_WORKER_CMD; only a generated one is
1085
+ // re-resolved.
1086
+ const savedWorker = process.env.FAILPROOFAI_WORKER_CMD
1087
+ ? null
1088
+ : installedEnvValue(readInstalledServiceDefinition() ?? "", "FAILPROOFAI_WORKER_CMD");
1089
+ const workerCmd = savedWorker && !isPackageCommand(savedWorker) ? savedWorker : resolveWorkerCommand();
1090
+ // And the operator's own audit command, the same way.
1091
+ const savedCli = process.env.FAILPROOFAI_CLI_CMD
1092
+ ? null
1093
+ : installedEnvValue(readInstalledServiceDefinition() ?? "", "FAILPROOFAI_CLI_CMD");
989
1094
  // Same best-effort footing as the worker command, and null is survivable in
990
1095
  // the same way — the daemon just has no way to run an audit. Unlike the
991
1096
  // worker, there is no relative-path fallback to degrade to, which is exactly
992
1097
  // why it is resolved here where FAILPROOFAI_PACKAGE_ROOT is reliably set.
993
- const cliCmd = resolveCliCommand();
1098
+ const cliCmd = savedCli && !isPackageCommand(savedCli) ? savedCli : resolveCliCommand();
994
1099
 
995
1100
  // The service is installed system-wide, which needs root. Check before
996
1101
  // writing anything, so a machine that cannot elevate gets the exact
@@ -1049,15 +1154,19 @@ export async function installDaemonService(): Promise<DaemonInstallResult> {
1049
1154
  const plistPath = launchdPlistPath();
1050
1155
  const logDir = logsDir();
1051
1156
  mkdirSync(logDir, { recursive: true });
1052
- // Unload any previously-loaded copy first — reloading with a changed
1053
- // binary path (e.g. after an upgrade) is a no-op under plain `load`
1054
- // if launchd thinks the label is already loaded.
1157
+ // Written BEFORE the unload: a write that fails then leaves the running
1158
+ // daemon loaded and untouched, where unloading first left a healthy
1159
+ // machine with no daemon (every hook denied) over a failed rewrite.
1160
+ // `unload` finds the job by its label, which the new plist keeps.
1161
+ writePrivilegedFile(plistPath, launchdPlistContents(binaryPath, logDir, workerCmd, cliCmd));
1162
+ // Unload any previously-loaded copy — reloading with a changed binary
1163
+ // path (e.g. after an upgrade) is a no-op under plain `load` if launchd
1164
+ // thinks the label is already loaded.
1055
1165
  try {
1056
1166
  runPrivileged("launchctl", ["unload", plistPath]);
1057
1167
  } catch {
1058
1168
  // Wasn't loaded — fine, this is the common case on a fresh install.
1059
1169
  }
1060
- writePrivilegedFile(plistPath, launchdPlistContents(binaryPath, logDir, workerCmd, cliCmd));
1061
1170
  runPrivileged("launchctl", ["load", "-w", plistPath]);
1062
1171
  }
1063
1172
  } catch (err) {
@@ -1346,7 +1455,7 @@ function readInstalledServiceDefinition(): string | null {
1346
1455
  function installedEnvValue(definition: string, name: string): string | null {
1347
1456
  if (process.platform === "linux") {
1348
1457
  const m = new RegExp(`^Environment="${name}=(.*)"$`, "m").exec(definition);
1349
- return m ? m[1] : null;
1458
+ return m ? m[1].replace(/%%/g, "%") : null;
1350
1459
  }
1351
1460
  const m = new RegExp(`<key>${name}</key>\\s*<string>([^<]*)</string>`).exec(definition);
1352
1461
  return m ? unescapeXml(m[1]) : null;
@@ -1388,7 +1497,13 @@ function installedExecStart(definition: string): string | null {
1388
1497
  export function daemonServiceNeedsUpgrade(): boolean {
1389
1498
  const definition = readInstalledServiceDefinition();
1390
1499
  if (definition === null) return false;
1391
- return !definition.includes("FAILPROOFAI_CLI_CMD");
1500
+ if (!definition.includes("FAILPROOFAI_CLI_CMD")) return true;
1501
+ // A Node upgrade deleted the runtime (or package) the definition names: the
1502
+ // daemon runs, its worker cannot start, and every hook is denied.
1503
+ return (
1504
+ savedCommandIsGone(installedEnvValue(definition, "FAILPROOFAI_WORKER_CMD")) ||
1505
+ savedCommandIsGone(installedEnvValue(definition, "FAILPROOFAI_CLI_CMD"))
1506
+ );
1392
1507
  }
1393
1508
 
1394
1509
  /**
@@ -1412,7 +1527,13 @@ export function upgradedServiceDefinition(
1412
1527
  ): string | null {
1413
1528
  const binaryPath = installedExecStart(definition);
1414
1529
  if (!binaryPath) return null;
1415
- const workerCmd = resolveWorkerCommand() ?? installedEnvValue(definition, "FAILPROOFAI_WORKER_CMD");
1530
+ const saved = installedEnvValue(definition, "FAILPROOFAI_WORKER_CMD");
1531
+ // An operator's own saved command is carried over, never replaced by the
1532
+ // package default (only a generated one is re-resolved).
1533
+ const workerCmd =
1534
+ !process.env.FAILPROOFAI_WORKER_CMD && saved && !isPackageCommand(saved)
1535
+ ? saved
1536
+ : (resolveWorkerCommand() ?? saved);
1416
1537
  try {
1417
1538
  return process.platform === "linux"
1418
1539
  ? systemdUnitContents(binaryPath, workerCmd, cliCmd)
@@ -1566,11 +1687,15 @@ async function refreshFailed(message: string, previous: string | null): Promise<
1566
1687
  */
1567
1688
  export async function ensureDaemonServiceCurrent(): Promise<DaemonUpgradeResult> {
1568
1689
  const definition = readInstalledServiceDefinition();
1569
- if (definition === null || definition.includes("FAILPROOFAI_CLI_CMD")) {
1690
+ // The same test `update` uses: a definition carrying FAILPROOFAI_CLI_CMD is
1691
+ // still stale when a generated command in it names a file that is gone.
1692
+ if (definition === null || !daemonServiceNeedsUpgrade()) {
1570
1693
  return { outcome: "current" };
1571
1694
  }
1572
1695
 
1573
- const cliCmd = resolveCliCommand();
1696
+ const savedCli = installedEnvValue(definition, "FAILPROOFAI_CLI_CMD");
1697
+ const cliCmd =
1698
+ !process.env.FAILPROOFAI_CLI_CMD && savedCli && !isPackageCommand(savedCli) ? savedCli : resolveCliCommand();
1574
1699
  if (!cliCmd) {
1575
1700
  return {
1576
1701
  outcome: "failed",
@@ -1582,6 +1707,22 @@ export async function ensureDaemonServiceCurrent(): Promise<DaemonUpgradeResult>
1582
1707
 
1583
1708
  const logDir = logsDir();
1584
1709
  const upgraded = upgradedServiceDefinition(definition, cliCmd, logDir);
1710
+ // A rewrite that would still name a missing file repairs nothing, and then
1711
+ // reported "rewritten" while the next check flagged the same path. The
1712
+ // install it would point at is incomplete; say that instead.
1713
+ if (
1714
+ upgraded &&
1715
+ (savedCommandIsGone(installedEnvValue(upgraded, "FAILPROOFAI_WORKER_CMD")) ||
1716
+ savedCommandIsGone(installedEnvValue(upgraded, "FAILPROOFAI_CLI_CMD")))
1717
+ ) {
1718
+ return {
1719
+ outcome: "failed",
1720
+ reason:
1721
+ "the failproofai install the service would run is incomplete (its Node.js or dist/ files are missing). " +
1722
+ "Reinstall the package, then run `failproofai update`.",
1723
+ daemonRunning: daemonServiceStatus() === "running",
1724
+ };
1725
+ }
1585
1726
  if (!upgraded) {
1586
1727
  return {
1587
1728
  outcome: "failed",
@@ -1702,8 +1843,10 @@ export async function refreshDaemonToCliVersion(
1702
1843
  install?: () => Promise<DaemonInstallResult>;
1703
1844
  prime?: () => boolean;
1704
1845
  interactive?: () => boolean;
1846
+ needsUpgrade?: () => boolean;
1705
1847
  } = {},
1706
1848
  ): Promise<{ ok: boolean; lines: string[] }> {
1849
+ const needsUpgrade = deps.needsUpgrade ?? daemonServiceNeedsUpgrade;
1707
1850
  const status = deps.status ?? daemonServiceStatus;
1708
1851
  const install = deps.install ?? installDaemonService;
1709
1852
  const prime = deps.prime ?? primeElevation;
@@ -1722,7 +1865,12 @@ export async function refreshDaemonToCliVersion(
1722
1865
  // `VERSION.daemon` is written only after an install succeeds, and the binary
1723
1866
  // it names must still be on disk.
1724
1867
  const recorded = readVersionFile()?.daemon;
1725
- if (current === "running" && recorded === version && existsSync(installedBinaryPath(version))) {
1868
+ if (
1869
+ current === "running" &&
1870
+ recorded === version &&
1871
+ existsSync(installedBinaryPath(version)) &&
1872
+ !needsUpgrade()
1873
+ ) {
1726
1874
  return { ok: true, lines: [`failproofaid ${version} is already installed and running; nothing to update.`] };
1727
1875
  }
1728
1876
 
@@ -132,6 +132,12 @@ export interface DeliveryHealth {
132
132
  * and drops one only if the current key refuses it too.
133
133
  */
134
134
  resending: number;
135
+ /**
136
+ * Parked by a failure that was not a refusal (an outage, a timeout): the
137
+ * daemon retries these itself, and right away once the server accepts a
138
+ * batch again. Queued, not lost. Absent when there are none.
139
+ */
140
+ retrying?: number;
135
141
  /** Age of the oldest parked batch, in ms. Undefined when none are parked. */
136
142
  oldestAgeMs?: number;
137
143
  }
@@ -187,6 +193,7 @@ export function deliveryHealth(
187
193
  let rejected = 0;
188
194
  let credentialRejected = 0;
189
195
  let resending = 0;
196
+ let retrying = 0;
190
197
  let oldestMtime: number | undefined;
191
198
 
192
199
  for (const name of entries) {
@@ -221,6 +228,8 @@ export function deliveryHealth(
221
228
  rejected += 1;
222
229
  byStatus[parsed.clientStatus] = (byStatus[parsed.clientStatus] ?? 0) + 1;
223
230
  if (CREDENTIAL_STATUSES.has(parsed.clientStatus)) credentialRejected += 1;
231
+ } else if (!parsed.poison) {
232
+ retrying += 1;
224
233
  }
225
234
 
226
235
  if (oldestMtime === undefined || mtime < oldestMtime) oldestMtime = mtime;
@@ -232,6 +241,7 @@ export function deliveryHealth(
232
241
  credentialRejected,
233
242
  byStatus,
234
243
  resending,
244
+ ...(retrying > 0 ? { retrying } : {}),
235
245
  ...(oldestMtime !== undefined ? { oldestAgeMs: Math.max(0, now - oldestMtime) } : {}),
236
246
  };
237
247
  }
@@ -474,6 +474,13 @@ export const onboardingAttemptFile = (home?: string) =>
474
474
  * "failproofai reorganised … Removed 1 item(s) from the old layout."
475
475
  */
476
476
  export const lastVersionFile = (home?: string) => resolve(stateDir(home), "last-version");
477
+ /**
478
+ * The CLI version whose upgrade steps (`failproofai update`: Hermes profiles,
479
+ * gateway restarts) last finished on this machine. `config` runs them when it
480
+ * differs, so the first setup after an `npm i -g` leaves no gateway on the plugin
481
+ * it loaded before. Separate from `last-version`, which any first command writes.
482
+ */
483
+ export const updatedVersionFile = (home?: string) => resolve(stateDir(home), "updated-version");
477
484
  export const onboardingLockFile = (home?: string) => resolve(stateDir(home), "onboarding.lock");
478
485
  export const codexSessionPathsFile = (home?: string) => resolve(stateDir(home), "codex-session-paths.json");
479
486
 
@@ -684,6 +691,7 @@ export const HOME_CLASSES: readonly { path: (home?: string) => string; class: Da
684
691
  { path: semanticDir, class: "derived" },
685
692
  { path: logsDir, class: "derived" },
686
693
  { path: lastVersionFile, class: "derived" },
694
+ { path: updatedVersionFile, class: "derived" },
687
695
  { path: launcherMarker, class: "derived" },
688
696
  { path: onboardingLockFile, class: "derived" },
689
697
  { path: onboardingAttemptFile, class: "derived" },
@@ -1117,6 +1117,12 @@ export interface LayoutCheckDeps {
1117
1117
  daemonStatus?: () => DaemonServiceStatus;
1118
1118
  /** How to draw the banners. Defaults to what stderr can show, where they print. */
1119
1119
  render?: RenderOpts;
1120
+ /**
1121
+ * The command is setup (`failproofai config` without --status, --pause and
1122
+ * the like), which brings the daemon to this version itself: telling the
1123
+ * person to run `failproofai update` first would be wrong advice.
1124
+ */
1125
+ daemonUpdatedByCommand?: boolean;
1120
1126
  }
1121
1127
 
1122
1128
  /**
@@ -1164,7 +1170,7 @@ export async function checkLayoutForCli(deps: LayoutCheckDeps = {}): Promise<Lay
1164
1170
  // Read AFTER the migration: on a machine coming from layout 1 or 2 the
1165
1171
  // config this reads is the one the migration just carried across, so asking
1166
1172
  // any earlier would read a file that is about to move.
1167
- const daemonHint = staleDaemonHint(kit);
1173
+ const daemonHint = deps.daemonUpdatedByCommand ? [] : staleDaemonHint(kit);
1168
1174
  return {
1169
1175
  state,
1170
1176
  fatal: false,
@@ -1244,7 +1250,7 @@ export async function checkLayoutForCli(deps: LayoutCheckDeps = {}): Promise<Lay
1244
1250
  state,
1245
1251
  fatal: false,
1246
1252
  didReset: false,
1247
- lines: [...(await healDaemonFlag(deps, kit)), ...staleDaemonHint(kit)],
1253
+ lines: [...(await healDaemonFlag(deps, kit)), ...(deps.daemonUpdatedByCommand ? [] : staleDaemonHint(kit))],
1248
1254
  };
1249
1255
  }
1250
1256