@stackfactor/agent-utils 1.13.4 → 1.33.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 (252) hide show
  1. package/README.md +688 -23
  2. package/dist/cjs/agentProto.d.ts +13 -3
  3. package/dist/cjs/agentProto.d.ts.map +1 -1
  4. package/dist/cjs/agentProto.js +25 -4
  5. package/dist/cjs/backoff.d.ts +17 -0
  6. package/dist/cjs/backoff.d.ts.map +1 -0
  7. package/dist/cjs/backoff.js +26 -0
  8. package/dist/cjs/cancellation.d.ts +22 -0
  9. package/dist/cjs/cancellation.d.ts.map +1 -0
  10. package/dist/cjs/cancellation.js +36 -0
  11. package/dist/cjs/cli.d.ts +3 -0
  12. package/dist/cjs/cli.d.ts.map +1 -0
  13. package/dist/cjs/cli.js +85 -0
  14. package/dist/cjs/client.d.ts +11 -0
  15. package/dist/cjs/client.d.ts.map +1 -1
  16. package/dist/cjs/client.js +27 -0
  17. package/dist/cjs/const.d.ts +23 -0
  18. package/dist/cjs/const.d.ts.map +1 -1
  19. package/dist/cjs/const.js +23 -0
  20. package/dist/cjs/daemon.d.ts +94 -0
  21. package/dist/cjs/daemon.d.ts.map +1 -0
  22. package/dist/cjs/daemon.js +507 -0
  23. package/dist/cjs/daemonConfig.d.ts +45 -0
  24. package/dist/cjs/daemonConfig.d.ts.map +1 -0
  25. package/dist/cjs/daemonConfig.js +148 -0
  26. package/dist/cjs/daemonEnv.d.ts +10 -0
  27. package/dist/cjs/daemonEnv.d.ts.map +1 -0
  28. package/dist/cjs/daemonEnv.js +12 -0
  29. package/dist/cjs/durable/clientTool.d.ts +39 -0
  30. package/dist/cjs/durable/clientTool.d.ts.map +1 -0
  31. package/dist/cjs/durable/clientTool.js +90 -0
  32. package/dist/cjs/durable/index.d.ts +9 -0
  33. package/dist/cjs/durable/index.d.ts.map +1 -0
  34. package/dist/cjs/durable/index.js +16 -0
  35. package/dist/cjs/durable/journal.d.ts +218 -0
  36. package/dist/cjs/durable/journal.d.ts.map +1 -0
  37. package/dist/cjs/durable/journal.js +392 -0
  38. package/dist/cjs/durable/pause.d.ts +84 -0
  39. package/dist/cjs/durable/pause.d.ts.map +1 -0
  40. package/dist/cjs/durable/pause.js +241 -0
  41. package/dist/cjs/durable/resume.d.ts +27 -0
  42. package/dist/cjs/durable/resume.d.ts.map +1 -0
  43. package/dist/cjs/durable/resume.js +80 -0
  44. package/dist/cjs/durable/snapshotSaver.d.ts +38 -0
  45. package/dist/cjs/durable/snapshotSaver.d.ts.map +1 -0
  46. package/dist/cjs/durable/snapshotSaver.js +81 -0
  47. package/dist/cjs/durable/step.d.ts +28 -0
  48. package/dist/cjs/durable/step.d.ts.map +1 -0
  49. package/dist/cjs/durable/step.js +43 -0
  50. package/dist/cjs/index.d.ts +30 -7
  51. package/dist/cjs/index.d.ts.map +1 -1
  52. package/dist/cjs/index.js +28 -1
  53. package/dist/cjs/infrastructure.d.ts +50 -0
  54. package/dist/cjs/infrastructure.d.ts.map +1 -0
  55. package/dist/cjs/infrastructure.js +163 -0
  56. package/dist/cjs/langChain.d.ts +15 -3
  57. package/dist/cjs/langChain.d.ts.map +1 -1
  58. package/dist/cjs/langChain.js +986 -180
  59. package/dist/cjs/learningActivityMedia.d.ts +196 -0
  60. package/dist/cjs/learningActivityMedia.d.ts.map +1 -0
  61. package/dist/cjs/learningActivityMedia.js +861 -0
  62. package/dist/cjs/learningContentPlan.d.ts +117 -0
  63. package/dist/cjs/learningContentPlan.d.ts.map +1 -0
  64. package/dist/cjs/learningContentPlan.js +327 -0
  65. package/dist/cjs/learningContentThread.d.ts +213 -0
  66. package/dist/cjs/learningContentThread.d.ts.map +1 -0
  67. package/dist/cjs/learningContentThread.js +448 -0
  68. package/dist/cjs/logger.d.ts +1 -0
  69. package/dist/cjs/logger.d.ts.map +1 -1
  70. package/dist/cjs/logger.js +17 -3
  71. package/dist/cjs/modelRates.d.ts +40 -0
  72. package/dist/cjs/modelRates.d.ts.map +1 -0
  73. package/dist/cjs/modelRates.js +76 -0
  74. package/dist/cjs/referenceContext.d.ts +4 -145
  75. package/dist/cjs/referenceContext.d.ts.map +1 -1
  76. package/dist/cjs/referenceContext.js +16 -251
  77. package/dist/cjs/retry.d.ts +64 -0
  78. package/dist/cjs/retry.d.ts.map +1 -0
  79. package/dist/cjs/retry.js +138 -0
  80. package/dist/cjs/runtimeContext.d.ts +8 -1
  81. package/dist/cjs/runtimeContext.d.ts.map +1 -1
  82. package/dist/cjs/runtimeContext.js +3 -1
  83. package/dist/cjs/serve.d.ts +3 -2
  84. package/dist/cjs/serve.d.ts.map +1 -1
  85. package/dist/cjs/serve.js +32 -2
  86. package/dist/cjs/sourceStore.d.ts +378 -0
  87. package/dist/cjs/sourceStore.d.ts.map +1 -0
  88. package/dist/cjs/sourceStore.js +872 -0
  89. package/dist/cjs/stackfactorKnowledge.d.ts +91 -7
  90. package/dist/cjs/stackfactorKnowledge.d.ts.map +1 -1
  91. package/dist/cjs/stackfactorKnowledge.js +108 -44
  92. package/dist/cjs/tavily.d.ts +108 -4
  93. package/dist/cjs/tavily.d.ts.map +1 -1
  94. package/dist/cjs/tavily.js +242 -21
  95. package/dist/cjs/usage.d.ts.map +1 -1
  96. package/dist/cjs/usage.js +9 -15
  97. package/dist/cjs/version.d.ts +3 -0
  98. package/dist/cjs/version.d.ts.map +1 -0
  99. package/dist/cjs/version.js +5 -0
  100. package/dist/cjs/workflow/bookkeeping.d.ts +78 -0
  101. package/dist/cjs/workflow/bookkeeping.d.ts.map +1 -0
  102. package/dist/cjs/workflow/bookkeeping.js +75 -0
  103. package/dist/cjs/workflow/index.d.ts +13 -0
  104. package/dist/cjs/workflow/index.d.ts.map +1 -0
  105. package/dist/cjs/workflow/index.js +51 -0
  106. package/dist/cjs/workflow/limits.d.ts +52 -0
  107. package/dist/cjs/workflow/limits.d.ts.map +1 -0
  108. package/dist/cjs/workflow/limits.js +62 -0
  109. package/dist/cjs/workflow/platformTransport.d.ts +39 -0
  110. package/dist/cjs/workflow/platformTransport.d.ts.map +1 -0
  111. package/dist/cjs/workflow/platformTransport.js +115 -0
  112. package/dist/cjs/workflow/retrying.d.ts +44 -0
  113. package/dist/cjs/workflow/retrying.d.ts.map +1 -0
  114. package/dist/cjs/workflow/retrying.js +82 -0
  115. package/dist/cjs/workflow/run.d.ts +195 -0
  116. package/dist/cjs/workflow/run.d.ts.map +1 -0
  117. package/dist/cjs/workflow/run.js +858 -0
  118. package/dist/cjs/workflow/testing/index.d.ts +3 -0
  119. package/dist/cjs/workflow/testing/index.d.ts.map +1 -0
  120. package/dist/cjs/workflow/testing/index.js +6 -0
  121. package/dist/cjs/workflow/testing/memoryTransport.d.ts +203 -0
  122. package/dist/cjs/workflow/testing/memoryTransport.d.ts.map +1 -0
  123. package/dist/cjs/workflow/testing/memoryTransport.js +1171 -0
  124. package/dist/cjs/workflow/transport.d.ts +219 -0
  125. package/dist/cjs/workflow/transport.d.ts.map +1 -0
  126. package/dist/cjs/workflow/transport.js +19 -0
  127. package/dist/esm/agentProto.d.ts +13 -3
  128. package/dist/esm/agentProto.d.ts.map +1 -1
  129. package/dist/esm/agentProto.js +23 -3
  130. package/dist/esm/backoff.d.ts +17 -0
  131. package/dist/esm/backoff.d.ts.map +1 -0
  132. package/dist/esm/backoff.js +22 -0
  133. package/dist/esm/cancellation.d.ts +22 -0
  134. package/dist/esm/cancellation.d.ts.map +1 -0
  135. package/dist/esm/cancellation.js +27 -0
  136. package/dist/esm/cli.d.ts +3 -0
  137. package/dist/esm/cli.d.ts.map +1 -0
  138. package/dist/esm/cli.js +80 -0
  139. package/dist/esm/client.d.ts +11 -0
  140. package/dist/esm/client.d.ts.map +1 -1
  141. package/dist/esm/client.js +25 -1
  142. package/dist/esm/const.d.ts +23 -0
  143. package/dist/esm/const.d.ts.map +1 -1
  144. package/dist/esm/const.js +23 -0
  145. package/dist/esm/daemon.d.ts +94 -0
  146. package/dist/esm/daemon.d.ts.map +1 -0
  147. package/dist/esm/daemon.js +499 -0
  148. package/dist/esm/daemonConfig.d.ts +45 -0
  149. package/dist/esm/daemonConfig.d.ts.map +1 -0
  150. package/dist/esm/daemonConfig.js +142 -0
  151. package/dist/esm/daemonEnv.d.ts +10 -0
  152. package/dist/esm/daemonEnv.d.ts.map +1 -0
  153. package/dist/esm/daemonEnv.js +9 -0
  154. package/dist/esm/durable/clientTool.d.ts +39 -0
  155. package/dist/esm/durable/clientTool.d.ts.map +1 -0
  156. package/dist/esm/durable/clientTool.js +82 -0
  157. package/dist/esm/durable/index.d.ts +9 -0
  158. package/dist/esm/durable/index.d.ts.map +1 -0
  159. package/dist/esm/durable/index.js +8 -0
  160. package/dist/esm/durable/journal.d.ts +218 -0
  161. package/dist/esm/durable/journal.d.ts.map +1 -0
  162. package/dist/esm/durable/journal.js +374 -0
  163. package/dist/esm/durable/pause.d.ts +84 -0
  164. package/dist/esm/durable/pause.d.ts.map +1 -0
  165. package/dist/esm/durable/pause.js +226 -0
  166. package/dist/esm/durable/resume.d.ts +27 -0
  167. package/dist/esm/durable/resume.d.ts.map +1 -0
  168. package/dist/esm/durable/resume.js +72 -0
  169. package/dist/esm/durable/snapshotSaver.d.ts +38 -0
  170. package/dist/esm/durable/snapshotSaver.d.ts.map +1 -0
  171. package/dist/esm/durable/snapshotSaver.js +77 -0
  172. package/dist/esm/durable/step.d.ts +28 -0
  173. package/dist/esm/durable/step.d.ts.map +1 -0
  174. package/dist/esm/durable/step.js +36 -0
  175. package/dist/esm/index.d.ts +30 -7
  176. package/dist/esm/index.d.ts.map +1 -1
  177. package/dist/esm/index.js +20 -4
  178. package/dist/esm/infrastructure.d.ts +50 -0
  179. package/dist/esm/infrastructure.d.ts.map +1 -0
  180. package/dist/esm/infrastructure.js +156 -0
  181. package/dist/esm/langChain.d.ts +15 -3
  182. package/dist/esm/langChain.d.ts.map +1 -1
  183. package/dist/esm/langChain.js +984 -179
  184. package/dist/esm/learningActivityMedia.d.ts +196 -0
  185. package/dist/esm/learningActivityMedia.d.ts.map +1 -0
  186. package/dist/esm/learningActivityMedia.js +807 -0
  187. package/dist/esm/learningContentPlan.d.ts +117 -0
  188. package/dist/esm/learningContentPlan.d.ts.map +1 -0
  189. package/dist/esm/learningContentPlan.js +320 -0
  190. package/dist/esm/learningContentThread.d.ts +213 -0
  191. package/dist/esm/learningContentThread.d.ts.map +1 -0
  192. package/dist/esm/learningContentThread.js +403 -0
  193. package/dist/esm/logger.d.ts +1 -0
  194. package/dist/esm/logger.d.ts.map +1 -1
  195. package/dist/esm/logger.js +17 -3
  196. package/dist/esm/modelRates.d.ts +40 -0
  197. package/dist/esm/modelRates.d.ts.map +1 -0
  198. package/dist/esm/modelRates.js +68 -0
  199. package/dist/esm/referenceContext.d.ts +4 -145
  200. package/dist/esm/referenceContext.d.ts.map +1 -1
  201. package/dist/esm/referenceContext.js +16 -243
  202. package/dist/esm/retry.d.ts +64 -0
  203. package/dist/esm/retry.d.ts.map +1 -0
  204. package/dist/esm/retry.js +127 -0
  205. package/dist/esm/runtimeContext.d.ts +8 -1
  206. package/dist/esm/runtimeContext.d.ts.map +1 -1
  207. package/dist/esm/runtimeContext.js +3 -1
  208. package/dist/esm/serve.d.ts +3 -2
  209. package/dist/esm/serve.d.ts.map +1 -1
  210. package/dist/esm/serve.js +33 -3
  211. package/dist/esm/sourceStore.d.ts +378 -0
  212. package/dist/esm/sourceStore.d.ts.map +1 -0
  213. package/dist/esm/sourceStore.js +855 -0
  214. package/dist/esm/stackfactorKnowledge.d.ts +91 -7
  215. package/dist/esm/stackfactorKnowledge.d.ts.map +1 -1
  216. package/dist/esm/stackfactorKnowledge.js +101 -41
  217. package/dist/esm/tavily.d.ts +108 -4
  218. package/dist/esm/tavily.d.ts.map +1 -1
  219. package/dist/esm/tavily.js +237 -20
  220. package/dist/esm/usage.d.ts.map +1 -1
  221. package/dist/esm/usage.js +9 -15
  222. package/dist/esm/version.d.ts +3 -0
  223. package/dist/esm/version.d.ts.map +1 -0
  224. package/dist/esm/version.js +2 -0
  225. package/dist/esm/workflow/bookkeeping.d.ts +78 -0
  226. package/dist/esm/workflow/bookkeeping.d.ts.map +1 -0
  227. package/dist/esm/workflow/bookkeeping.js +67 -0
  228. package/dist/esm/workflow/index.d.ts +13 -0
  229. package/dist/esm/workflow/index.d.ts.map +1 -0
  230. package/dist/esm/workflow/index.js +10 -0
  231. package/dist/esm/workflow/limits.d.ts +52 -0
  232. package/dist/esm/workflow/limits.d.ts.map +1 -0
  233. package/dist/esm/workflow/limits.js +59 -0
  234. package/dist/esm/workflow/platformTransport.d.ts +39 -0
  235. package/dist/esm/workflow/platformTransport.d.ts.map +1 -0
  236. package/dist/esm/workflow/platformTransport.js +110 -0
  237. package/dist/esm/workflow/retrying.d.ts +44 -0
  238. package/dist/esm/workflow/retrying.d.ts.map +1 -0
  239. package/dist/esm/workflow/retrying.js +73 -0
  240. package/dist/esm/workflow/run.d.ts +195 -0
  241. package/dist/esm/workflow/run.d.ts.map +1 -0
  242. package/dist/esm/workflow/run.js +850 -0
  243. package/dist/esm/workflow/testing/index.d.ts +3 -0
  244. package/dist/esm/workflow/testing/index.d.ts.map +1 -0
  245. package/dist/esm/workflow/testing/index.js +2 -0
  246. package/dist/esm/workflow/testing/memoryTransport.d.ts +203 -0
  247. package/dist/esm/workflow/testing/memoryTransport.d.ts.map +1 -0
  248. package/dist/esm/workflow/testing/memoryTransport.js +1167 -0
  249. package/dist/esm/workflow/transport.d.ts +219 -0
  250. package/dist/esm/workflow/transport.d.ts.map +1 -0
  251. package/dist/esm/workflow/transport.js +16 -0
  252. package/package.json +8 -7
package/dist/esm/const.js CHANGED
@@ -13,4 +13,27 @@ export default {
13
13
  UNSUPPORTED_MODEL: "The specified model is not supported",
14
14
  QUOTA_EXHAUSTED: "Agent session quota exhausted: no remaining budget for additional LLM calls.",
15
15
  },
16
+ /** The pool daemon (`npx @stackfactor/agent-utils daemon`). */
17
+ DAEMON: {
18
+ /** First retry delay after a failure. */
19
+ BACKOFF_MIN_MS: 1000,
20
+ /** Retry delay cap: three failures fit inside the 90 s liveness window. */
21
+ BACKOFF_MAX_MS: 15000,
22
+ /** How long to wait before asking again when the pool is disabled. */
23
+ DISABLED_RETRY_MS: 60000,
24
+ /** A claim may take its poll time plus this long before the client gives up. */
25
+ CLAIM_TIMEOUT_EXTRA_MS: 10000,
26
+ /** Bound on each cloud metadata probe. */
27
+ DETECT_TIMEOUT_MS: 1000,
28
+ /** A shutdown is not held up by an unreachable platform. */
29
+ DEREGISTER_TIMEOUT_MS: 5000,
30
+ /** Exit code asking the supervisor to restart on a new version. */
31
+ EXIT_UPGRADE: 75,
32
+ /** sysexits EX_CONFIG: the token or configuration is wrong; restarting will not help. */
33
+ EXIT_CONFIG: 78,
34
+ /** The runner this slice registers. */
35
+ RUNNER: "subprocess",
36
+ /** Tasks the daemon takes at once (none until the worker exists). */
37
+ CAPACITY: 0,
38
+ },
16
39
  };
@@ -0,0 +1,94 @@
1
+ import { agentPools } from "@stackfactor/client-api";
2
+ import { type DaemonConfig, type InfrastructureOverrides } from "./daemonConfig.js";
3
+ import { type Infrastructure } from "./infrastructure.js";
4
+ /**
5
+ * The pool daemon (design §7.2): it registers with its pool, then reports in
6
+ * through the claim every `pollSeconds`, and leaves on SIGTERM. In slice 2a
7
+ * it runs no task: every claim reports `capacity: 0` (R-C1).
8
+ *
9
+ * The pool token is never logged: messages carry the HTTP status, a network
10
+ * error's code, the platform's stated reason or a short message, never an
11
+ * error object or its config. Any text from outside is cut free of the token
12
+ * before it is clipped, and every line again before it is written (Review Focus 1).
13
+ */
14
+ type DaemonRegistration = agentPools.DaemonRegistration;
15
+ type DaemonRegistered = agentPools.DaemonRegistered;
16
+ type DaemonClaim = agentPools.DaemonClaim;
17
+ type ClaimAnswer = agentPools.ClaimAnswer;
18
+ /** A bound on one call to the platform. */
19
+ export interface PoolCallBound {
20
+ timeoutMs: number;
21
+ }
22
+ /**
23
+ * How the daemon reaches the platform's pool routes (design §5.1). The default
24
+ * is client-api's `agentPools`, called with the pool token and the configured
25
+ * backend URL. A call rejects with the platform's HTTP status on
26
+ * `error.response.status`, or with a network error's `code`.
27
+ */
28
+ export interface PoolTransport {
29
+ register(body: DaemonRegistration, options: PoolCallBound): Promise<DaemonRegistered>;
30
+ claim(body: DaemonClaim, options: PoolCallBound): Promise<ClaimAnswer>;
31
+ deregister(daemonId: string, options: PoolCallBound): Promise<void>;
32
+ }
33
+ /** A wait that ends early, without rejecting, when `signal` aborts. */
34
+ export type Sleep = (ms: number, signal: AbortSignal) => Promise<void>;
35
+ /** The levels the daemon writes at; each is one of the package logger's levels. */
36
+ export type DaemonLogLevel = "error" | "warn" | "info" | "debug";
37
+ /** Where the daemon's lines go; the default is the package's logger. */
38
+ export type DaemonLog = (level: DaemonLogLevel, message: string) => void;
39
+ export interface DaemonOptions {
40
+ /** What `readDaemonConfig` read from flags and environment. */
41
+ config: DaemonConfig;
42
+ /** Override how the platform is reached (e.g. in tests). Defaults to client-api's `agentPools`. */
43
+ transport?: PoolTransport;
44
+ /** Override waiting (e.g. in tests). Defaults to a timer that a signal ends at once. */
45
+ sleep?: Sleep;
46
+ /** Override the clock (e.g. in tests). Defaults to `Date.now`. */
47
+ now?: () => number;
48
+ /** Where SIGTERM and SIGINT arrive. Defaults to `process`; the handlers are removed when `start` resolves. */
49
+ signals?: NodeJS.EventEmitter;
50
+ /** Override logging (e.g. in tests). Defaults to the package's logger. */
51
+ log?: DaemonLog;
52
+ /** The hostname registered. Defaults to `os.hostname()`. */
53
+ hostname?: string;
54
+ /** The version registered and reported. Defaults to this package's version, written at build time. */
55
+ version?: string;
56
+ /** Override infrastructure detection (e.g. in tests). Defaults to `detectInfrastructure`. */
57
+ detect?: (overrides: InfrastructureOverrides) => Promise<Infrastructure>;
58
+ }
59
+ declare const STOPPED: unique symbol;
60
+ /**
61
+ * Settles with `call`, or with STOPPED as soon as `signal` aborts. The abort
62
+ * listener is removed when the call settles, so a signal that lives as long as
63
+ * the daemon holds on to nothing of the calls it guarded.
64
+ */
65
+ export declare const unlessAborted: <T>(call: Promise<T>, signal: AbortSignal) => Promise<T | typeof STOPPED>;
66
+ /**
67
+ * Runs the pool daemon until it is stopped or told to stop, and resolves the
68
+ * process's exit code:
69
+ * - `0` after SIGTERM or SIGINT, at once even mid-wait or mid-claim, having
70
+ * deregistered (bounded by `DEREGISTER_TIMEOUT_MS`; a failure is logged; a
71
+ * second signal, a second or more after the first, stops waiting for it). A
72
+ * registration still in flight is waited for within the same bound, so the
73
+ * daemon it creates is deregistered too;
74
+ * - `EXIT_UPGRADE` (75) when a claim answers `upgradeTo`;
75
+ * - `EXIT_CONFIG` (78) when the platform answers 401 (the token is gone) or
76
+ * 400 (this daemon's request is refused), or, before any request, when the
77
+ * configuration names no http(s) backend (R-C10).
78
+ *
79
+ * Otherwise it keeps going: a 404 on a claim registers again under the same
80
+ * deployment (at once after a good claim; with backoff when the daemon was
81
+ * lost again before a claim got through), a 403 (the pool is disabled, or the
82
+ * request was refused before it reached the platform) waits `DISABLED_RETRY_MS`, and network errors and anything else back off from 1 s
83
+ * to 15 s, forever. Only a good claim resets the backoff. Registration's
84
+ * errors follow the same table.
85
+ * @param options - The configuration and, for tests or embedding callers, overrides.
86
+ */
87
+ export declare const start: (options: DaemonOptions) => Promise<number>;
88
+ /** `start` runs the daemon; `readConfig` reads and checks its configuration from flags and environment. */
89
+ declare const daemon: {
90
+ start: (options: DaemonOptions) => Promise<number>;
91
+ readConfig: (argv: string[], env: NodeJS.ProcessEnv) => DaemonConfig;
92
+ };
93
+ export default daemon;
94
+ //# sourceMappingURL=daemon.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"daemon.d.ts","sourceRoot":"","sources":["../../src/daemon.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAIrD,OAAO,EAA4B,KAAK,YAAY,EAAE,KAAK,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC9G,OAAO,EAAwB,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAGhF;;;;;;;;;GASG;AAEH,KAAK,kBAAkB,GAAG,UAAU,CAAC,kBAAkB,CAAC;AACxD,KAAK,gBAAgB,GAAG,UAAU,CAAC,gBAAgB,CAAC;AACpD,KAAK,WAAW,GAAG,UAAU,CAAC,WAAW,CAAC;AAC1C,KAAK,WAAW,GAAG,UAAU,CAAC,WAAW,CAAC;AAK1C,2CAA2C;AAC3C,MAAM,WAAW,aAAa;IAC5B,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;;;GAKG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,IAAI,EAAE,kBAAkB,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;IACtF,KAAK,CAAC,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;IACvE,UAAU,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACrE;AAED,uEAAuE;AACvE,MAAM,MAAM,KAAK,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;AAEvE,mFAAmF;AACnF,MAAM,MAAM,cAAc,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAEjE,wEAAwE;AACxE,MAAM,MAAM,SAAS,GAAG,CAAC,KAAK,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;AAEzE,MAAM,WAAW,aAAa;IAC5B,+DAA+D;IAC/D,MAAM,EAAE,YAAY,CAAC;IACrB,mGAAmG;IACnG,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B,wFAAwF;IACxF,KAAK,CAAC,EAAE,KAAK,CAAC;IACd,kEAAkE;IAClE,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,8GAA8G;IAC9G,OAAO,CAAC,EAAE,MAAM,CAAC,YAAY,CAAC;IAC9B,0EAA0E;IAC1E,GAAG,CAAC,EAAE,SAAS,CAAC;IAChB,4DAA4D;IAC5D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sGAAsG;IACtG,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,6FAA6F;IAC7F,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,uBAAuB,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;CAC1E;AA2DD,QAAA,MAAM,OAAO,eAAoB,CAAC;AAGlC;;;;GAIG;AACH,eAAO,MAAM,aAAa,GAAI,CAAC,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,QAAQ,WAAW,KAAG,OAAO,CAAC,CAAC,GAAG,OAAO,OAAO,CAU/F,CAAC;AA4IL;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,eAAO,MAAM,KAAK,GAAU,SAAS,aAAa,KAAG,OAAO,CAAC,MAAM,CAsTlE,CAAC;AAEF,2GAA2G;AAC3G,QAAA,MAAM,MAAM;qBAzTyB,aAAa,KAAG,OAAO,CAAC,MAAM,CAAC;;CAyTd,CAAC;AAEvD,eAAe,MAAM,CAAC"}
@@ -0,0 +1,499 @@
1
+ import { hostname as osHostname } from "node:os";
2
+ import { agentPools } from "@stackfactor/client-api";
3
+ import constants from "./const.js";
4
+ import logger from "./logger.js";
5
+ import { backoff } from "./backoff.js";
6
+ import { poolOf, readDaemonConfig } from "./daemonConfig.js";
7
+ import { detectInfrastructure } from "./infrastructure.js";
8
+ import { VERSION } from "./version.js";
9
+ const { DAEMON } = constants;
10
+ const DEFAULT_POLL_SECONDS = 30;
11
+ /** However short the pool's `pollSeconds`, the daemon waits at least this long between claims. */
12
+ const MIN_POLL_SECONDS = 1;
13
+ /**
14
+ * However long the pool's `pollSeconds`, the daemon claims at least this often
15
+ * (R-C11): inside the 90 s liveness window, and far below the ~2,147,483 s at
16
+ * which setTimeout overflows and fires at once.
17
+ */
18
+ const MAX_POLL_SECONDS = 60;
19
+ /**
20
+ * Whether a plain-http backend's host is this machine, so the token does not
21
+ * cross a network: localhost, the whole 127.0.0.0/8 range, and ::1. Not
22
+ * `*.localhost`: Node resolves it through the system resolver, which a search
23
+ * domain can send off the host.
24
+ */
25
+ const isLoopback = (hostname) => hostname === "localhost" ||
26
+ hostname === "[::1]" ||
27
+ /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname);
28
+ /** What an `upgradeTo` must look like before it is put into a command for the operator. */
29
+ const RELEASE_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
30
+ /** A registration is answered at once; it is given the margin a claim gets beyond its poll. */
31
+ const REGISTER_TIMEOUT_MS = DAEMON.CLAIM_TIMEOUT_EXTRA_MS;
32
+ const CLOUDS = ["gcp", "aws", "azure", "other"];
33
+ /**
34
+ * What a claim asks the platform to wait for a task. None in this release: a
35
+ * daemon with no free slot is answered at once (design §5.1).
36
+ */
37
+ const CLAIM_WAIT_SECONDS = 0;
38
+ /**
39
+ * A claim is allowed its wait plus the margin (design §7.2). With no wait that
40
+ * is the margin alone, so a platform that stops answering costs 10 s a try and
41
+ * three tries still fit inside the 90 s liveness window.
42
+ */
43
+ const CLAIM_TIMEOUT_MS = CLAIM_WAIT_SECONDS * 1000 + DAEMON.CLAIM_TIMEOUT_EXTRA_MS;
44
+ /**
45
+ * A stop signal repeated inside this window is one keystroke delivered twice
46
+ * (a terminal's Ctrl-C reaches both npx and the daemon, and npx forwards it
47
+ * again), not the operator asking to leave without the deregister.
48
+ */
49
+ const REPEAT_SIGNAL_MS = 1000;
50
+ const MESSAGE_MAX = 200;
51
+ /** The longest hostname the platform's registration accepts (the longest DNS allows); a longer one is a 400. */
52
+ const HOSTNAME_MAX = 253;
53
+ const STOPPED = Symbol("stopped");
54
+ const LATE = Symbol("late");
55
+ /**
56
+ * Settles with `call`, or with STOPPED as soon as `signal` aborts. The abort
57
+ * listener is removed when the call settles, so a signal that lives as long as
58
+ * the daemon holds on to nothing of the calls it guarded.
59
+ */
60
+ export const unlessAborted = (call, signal) => new Promise((resolve, reject) => {
61
+ if (signal.aborted) {
62
+ call.catch(() => undefined);
63
+ resolve(STOPPED);
64
+ return;
65
+ }
66
+ const onAbort = () => resolve(STOPPED);
67
+ signal.addEventListener("abort", onAbort, { once: true });
68
+ call.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
69
+ });
70
+ /** The default wait: a timer that the signal clears and ends at once. */
71
+ const abortableSleep = (ms, signal) => new Promise((resolve) => {
72
+ if (signal.aborted)
73
+ return resolve();
74
+ const done = () => {
75
+ clearTimeout(timer);
76
+ signal.removeEventListener("abort", done);
77
+ resolve();
78
+ };
79
+ const timer = setTimeout(done, ms);
80
+ signal.addEventListener("abort", done, { once: true });
81
+ });
82
+ /**
83
+ * client-api's `agentPools`, with the pool token and the configured backend
84
+ * URL on every call. Never client-api's own base URL (R-C10): that falls back to
85
+ * whatever `BACKEND_URL`, `REACT_APP_BACKEND_URL` or a `.env` names, or to localhost.
86
+ */
87
+ const defaultTransport = (config) => {
88
+ const baseURL = config.backendUrl;
89
+ return {
90
+ register: (body, { timeoutMs }) => agentPools.registerDaemon(body, config.poolToken, { baseURL, timeoutMs }),
91
+ claim: (body, { timeoutMs }) => agentPools.claim(body, config.poolToken, { baseURL, timeoutMs }),
92
+ deregister: (daemonId, { timeoutMs }) => agentPools.deregisterDaemon(daemonId, config.poolToken, { baseURL, timeoutMs }),
93
+ };
94
+ };
95
+ /** The configured backend, or undefined when it is not an http(s) URL. */
96
+ const backendOf = (url) => {
97
+ if (typeof url !== "string" || url === "")
98
+ return undefined;
99
+ let parsed;
100
+ try {
101
+ parsed = new URL(url);
102
+ }
103
+ catch {
104
+ return undefined;
105
+ }
106
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:")
107
+ return undefined;
108
+ return {
109
+ origin: parsed.origin,
110
+ cleartext: parsed.protocol === "http:" && !isLoopback(parsed.hostname),
111
+ };
112
+ };
113
+ const defaultLog = (level, message) => logger.log(null, level, message);
114
+ /** Detection's answer in the wire shape (design §4.3: `orchestrator` is `{ kind }`, `cloud` one of four). */
115
+ const toWire = (found) => {
116
+ const wire = {
117
+ cloud: CLOUDS.find((cloud) => cloud === found.cloud) ?? "other",
118
+ orchestrator: { kind: found.orchestrator },
119
+ os: found.os,
120
+ arch: found.arch,
121
+ };
122
+ if (found.region !== undefined)
123
+ wire.region = found.region;
124
+ if (found.account !== undefined)
125
+ wire.account = found.account;
126
+ if (found.cluster !== undefined)
127
+ wire.cluster = found.cluster;
128
+ return wire;
129
+ };
130
+ /** The HTTP status a rejected call carries, if any. */
131
+ const statusOf = (error) => {
132
+ const status = error?.response?.status;
133
+ return typeof status === "number" ? status : undefined;
134
+ };
135
+ /**
136
+ * What went wrong, for a log line: the HTTP status, else a network error's
137
+ * code, else the error's message through `clip`. Never the error object or its config.
138
+ */
139
+ const describe = (error, clip) => {
140
+ const status = statusOf(error);
141
+ if (status !== undefined)
142
+ return `HTTP ${status}`;
143
+ const { code, message } = (error ?? {});
144
+ if (typeof code === "string" && code !== "")
145
+ return code;
146
+ if (typeof message === "string" && message !== "")
147
+ return clip(message);
148
+ return "unknown error";
149
+ };
150
+ /**
151
+ * The platform's own reason for refusing a call, through `clip`: the backend's
152
+ * `{ error }`, or a validation failure's `path: msg` pairs. A validation
153
+ * error's `value` is never repeated: it is what was refused.
154
+ */
155
+ const platformSays = (error, clip) => {
156
+ const data = error?.response?.data;
157
+ if (!data || typeof data !== "object")
158
+ return undefined;
159
+ const body = data;
160
+ if (typeof body.error === "string" && body.error !== "")
161
+ return clip(body.error);
162
+ if (!Array.isArray(body.errors))
163
+ return undefined;
164
+ const fields = body.errors
165
+ .map((entry) => {
166
+ const { path, msg } = (entry ?? {});
167
+ if (typeof msg !== "string")
168
+ return undefined;
169
+ return typeof path === "string" && path !== "" ? `${path}: ${msg}` : msg;
170
+ })
171
+ .filter((field) => field !== undefined);
172
+ return fields.length > 0 ? clip(fields.join("; ")) : undefined;
173
+ };
174
+ /**
175
+ * Cuts the token out of a line: whole, then what follows `sfp_<poolId>_`, then
176
+ * the secret after `sfp_<poolId>_<credentialId>_` (base64url, so it may hold
177
+ * `_` itself), then its last `_` segment on its own. Parts under 8 characters
178
+ * are left alone.
179
+ */
180
+ const redactor = (token) => {
181
+ const segments = token.split("_");
182
+ const parts = [
183
+ token,
184
+ token.slice(poolOf(token).length + 1),
185
+ segments.slice(3).join("_"),
186
+ segments[segments.length - 1],
187
+ ].filter((part) => part.length >= 8);
188
+ return (line) => parts.reduce((text, part) => text.split(part).join("[pool token]"), line);
189
+ };
190
+ /** The pool's `pollSeconds`: 30 when missing or not a positive number, else bounded to 1-60. */
191
+ const pollSecondsOf = (settings) => {
192
+ const seconds = settings.pollSeconds;
193
+ if (typeof seconds !== "number" || !Number.isFinite(seconds) || seconds <= 0) {
194
+ return DEFAULT_POLL_SECONDS;
195
+ }
196
+ return Math.min(MAX_POLL_SECONDS, Math.max(MIN_POLL_SECONDS, seconds));
197
+ };
198
+ const plural = (count, word) => `${count} ${word}${count === 1 ? "" : "s"}`;
199
+ /**
200
+ * Runs the pool daemon until it is stopped or told to stop, and resolves the
201
+ * process's exit code:
202
+ * - `0` after SIGTERM or SIGINT, at once even mid-wait or mid-claim, having
203
+ * deregistered (bounded by `DEREGISTER_TIMEOUT_MS`; a failure is logged; a
204
+ * second signal, a second or more after the first, stops waiting for it). A
205
+ * registration still in flight is waited for within the same bound, so the
206
+ * daemon it creates is deregistered too;
207
+ * - `EXIT_UPGRADE` (75) when a claim answers `upgradeTo`;
208
+ * - `EXIT_CONFIG` (78) when the platform answers 401 (the token is gone) or
209
+ * 400 (this daemon's request is refused), or, before any request, when the
210
+ * configuration names no http(s) backend (R-C10).
211
+ *
212
+ * Otherwise it keeps going: a 404 on a claim registers again under the same
213
+ * deployment (at once after a good claim; with backoff when the daemon was
214
+ * lost again before a claim got through), a 403 (the pool is disabled, or the
215
+ * request was refused before it reached the platform) waits `DISABLED_RETRY_MS`, and network errors and anything else back off from 1 s
216
+ * to 15 s, forever. Only a good claim resets the backoff. Registration's
217
+ * errors follow the same table.
218
+ * @param options - The configuration and, for tests or embedding callers, overrides.
219
+ */
220
+ export const start = async (options) => {
221
+ const { config } = options;
222
+ const write = options.log ?? defaultLog;
223
+ if (typeof config?.poolToken !== "string" || config.poolToken === "") {
224
+ write("error", "no pool token in the configuration: read it with daemon.readConfig, which checks it");
225
+ return DAEMON.EXIT_CONFIG;
226
+ }
227
+ const redact = redactor(config.poolToken);
228
+ const clip = (text) => redact(text).slice(0, MESSAGE_MAX);
229
+ const say = (level, message) => write(level, redact(message));
230
+ const backend = backendOf(config.backendUrl);
231
+ if (!backend) {
232
+ say("error", "no usable backend URL: set AGENT_POOL_BACKEND_URL (or --backend) to the StackFactor backend, http or https. There is no default.");
233
+ return DAEMON.EXIT_CONFIG;
234
+ }
235
+ const transport = options.transport ?? defaultTransport(config);
236
+ const sleep = options.sleep ?? abortableSleep;
237
+ const now = options.now ?? Date.now;
238
+ const signals = options.signals ?? process;
239
+ const detect = options.detect ?? ((overrides) => detectInfrastructure(overrides));
240
+ const pool = poolOf(config.poolToken);
241
+ const stop = new AbortController();
242
+ /** Aborted by a second signal: stop waiting for the deregister. */
243
+ const hurry = new AbortController();
244
+ /** Settles with the call, or with STOPPED as soon as a signal arrives. */
245
+ const unlessStopped = (call) => unlessAborted(call, stop.signal);
246
+ let stoppedAt = 0;
247
+ const onSignal = (name) => {
248
+ if (!stop.signal.aborted) {
249
+ stoppedAt = now();
250
+ say("info", `${name} received: leaving the pool`);
251
+ stop.abort();
252
+ }
253
+ else if (!hurry.signal.aborted && now() - stoppedAt >= REPEAT_SIGNAL_MS) {
254
+ say("info", `${name} again: leaving at once, without waiting for the deregister`);
255
+ hurry.abort();
256
+ }
257
+ };
258
+ const onTerm = () => onSignal("SIGTERM");
259
+ const onInt = () => onSignal("SIGINT");
260
+ signals.on("SIGTERM", onTerm);
261
+ signals.on("SIGINT", onInt);
262
+ const state = { daemonId: null, settings: {}, queue: null, queueAt: null };
263
+ /** False once the token is refused: leaving would be refused too. */
264
+ let mayDeregister = true;
265
+ /**
266
+ * Settles with the call, or with LATE once `DEREGISTER_TIMEOUT_MS` has
267
+ * passed or a second signal hurries the daemon out. The timer never outlives it.
268
+ */
269
+ const withinGrace = async (call) => {
270
+ const bound = new AbortController();
271
+ const hurried = () => bound.abort();
272
+ hurry.signal.addEventListener("abort", hurried, { once: true });
273
+ if (hurry.signal.aborted)
274
+ bound.abort();
275
+ try {
276
+ return await Promise.race([
277
+ call,
278
+ sleep(DAEMON.DEREGISTER_TIMEOUT_MS, bound.signal).then(() => LATE),
279
+ ]);
280
+ }
281
+ finally {
282
+ bound.abort();
283
+ hurry.signal.removeEventListener("abort", hurried);
284
+ }
285
+ };
286
+ const leave = async (daemonId) => {
287
+ try {
288
+ const outcome = await withinGrace(transport.deregister(daemonId, { timeoutMs: DAEMON.DEREGISTER_TIMEOUT_MS }));
289
+ if (outcome !== LATE) {
290
+ say("info", `deregistered daemon ${daemonId}`);
291
+ }
292
+ else if (!hurry.signal.aborted) {
293
+ say("warn", `deregistering daemon ${daemonId} took over ${DAEMON.DEREGISTER_TIMEOUT_MS / 1000} s: leaving without it (the platform drops a silent daemon)`);
294
+ }
295
+ }
296
+ catch (error) {
297
+ if (statusOf(error) === 404) {
298
+ say("info", `daemon ${daemonId} was already gone from the pool`);
299
+ }
300
+ else if (statusOf(error) === 403) {
301
+ // A disabled pool refuses the deregistration too (design §4.2).
302
+ say("warn", `the platform refused to deregister daemon ${daemonId} (HTTP 403: the pool is disabled): its record expires on the platform`);
303
+ }
304
+ else {
305
+ say("warn", `could not deregister daemon ${daemonId} (${describe(error, clip)}): the platform drops a silent daemon`);
306
+ }
307
+ }
308
+ };
309
+ const run = async () => {
310
+ const version = options.version ?? VERSION;
311
+ say("info", `daemon for pool ${pool} (agent-utils ${version}) using the backend ${backend.origin}`);
312
+ if (backend.cleartext) {
313
+ say("warn", `the backend ${backend.origin} is plain http and not this host: the pool token travels in cleartext; use https`);
314
+ }
315
+ // The platform refuses a registration (400) whose hostname is empty or over
316
+ // HOSTNAME_MAX; the name is for display, so it is cut or stood in for instead.
317
+ const hostname = (options.hostname ?? osHostname()).slice(0, HOSTNAME_MAX) || "unknown";
318
+ let infrastructure;
319
+ if (config.reportInfrastructure) {
320
+ const found = await unlessStopped(Promise.resolve()
321
+ .then(() => detect(config.overrides))
322
+ .then(toWire, () => {
323
+ say("warn", "could not detect the infrastructure: registering without it");
324
+ return undefined;
325
+ }));
326
+ if (found === STOPPED)
327
+ return 0;
328
+ infrastructure = found;
329
+ }
330
+ const registration = {
331
+ version,
332
+ runner: DAEMON.RUNNER,
333
+ schemes: [],
334
+ hostname,
335
+ };
336
+ if (config.deployment !== undefined)
337
+ registration.deployment = config.deployment;
338
+ if (infrastructure !== undefined)
339
+ registration.infrastructure = infrastructure;
340
+ const retry = backoff({ minMs: DAEMON.BACKOFF_MIN_MS, maxMs: DAEMON.BACKOFF_MAX_MS });
341
+ let failures = 0;
342
+ let failingSince = 0;
343
+ /** Whether a claim got through since the last registration. */
344
+ let claimedSinceRegistered = false;
345
+ /** Counts a failure and gives the next backoff delay. */
346
+ const failed = () => {
347
+ if (failures === 0)
348
+ failingSince = now();
349
+ failures++;
350
+ return retry.next();
351
+ };
352
+ /** A good claim: the loop is healthy again, and only now does the backoff start over. */
353
+ const recovered = () => {
354
+ if (failures > 0) {
355
+ const seconds = Math.round((now() - failingSince) / 1000);
356
+ say("info", `reached the platform again after ${plural(failures, "failed attempt")} (${seconds} s)`);
357
+ }
358
+ failures = 0;
359
+ retry.reset();
360
+ };
361
+ const inSeconds = (ms) => `${(ms / 1000).toFixed(1)} s`;
362
+ while (!stop.signal.aborted) {
363
+ const registering = state.daemonId === null;
364
+ try {
365
+ if (registering) {
366
+ const pending = transport.register(registration, { timeoutMs: REGISTER_TIMEOUT_MS });
367
+ const answer = await unlessStopped(pending);
368
+ if (answer === STOPPED) {
369
+ // The request may still land and leave a daemon registered: it is
370
+ // waited for, as long as a deregister is, so that daemon is deregistered too.
371
+ const landed = await withinGrace(pending.then((late) => late?.daemonId, () => undefined));
372
+ if (typeof landed === "string" && landed !== "")
373
+ state.daemonId = landed;
374
+ break;
375
+ }
376
+ if (typeof answer?.daemonId !== "string" || answer.daemonId === "") {
377
+ throw new Error("the registration answer carried no daemon id");
378
+ }
379
+ state.daemonId = answer.daemonId;
380
+ claimedSinceRegistered = false;
381
+ state.settings = answer.settings ?? state.settings;
382
+ say("info", `registered daemon ${answer.daemonId} in pool ${pool} (${clip(String(answer.pool?.kind ?? "unknown"))}), deployment ${config.deployment ?? "(none)"}`);
383
+ continue;
384
+ }
385
+ const body = {
386
+ daemonId: state.daemonId,
387
+ running: 0,
388
+ capacity: DAEMON.CAPACITY,
389
+ version,
390
+ tasks: [],
391
+ waitSeconds: CLAIM_WAIT_SECONDS,
392
+ };
393
+ const answer = await unlessStopped(transport.claim(body, { timeoutMs: CLAIM_TIMEOUT_MS }));
394
+ if (answer === STOPPED)
395
+ break;
396
+ if (!answer || typeof answer !== "object")
397
+ throw new Error("the claim answer was empty");
398
+ recovered();
399
+ claimedSinceRegistered = true;
400
+ state.settings = answer.settings ?? state.settings;
401
+ if (answer.queue) {
402
+ state.queue = answer.queue;
403
+ state.queueAt = now();
404
+ }
405
+ if (answer.task) {
406
+ // The platform never hands a task to a capacity-0 daemon; if it does,
407
+ // the task is not run and not listed (the platform gives it back).
408
+ say("error", `the platform handed this daemon task ${clip(String(answer.task.batchJobId))}, but it takes none in this release: not run`);
409
+ }
410
+ if (Array.isArray(answer.drop) && answer.drop.length > 0) {
411
+ say("warn", `the platform asks to drop tasks this daemon does not hold: ${clip(answer.drop.join(", "))}`);
412
+ }
413
+ if (answer.upgradeTo) {
414
+ const target = String(answer.upgradeTo);
415
+ const restart = RELEASE_VERSION.test(target)
416
+ ? `; restart it with: npx @stackfactor/agent-utils@${target} daemon`
417
+ : "";
418
+ say("info", `the pool runs agent-utils ${clip(target)} and this daemon ${version}: exiting ${DAEMON.EXIT_UPGRADE} to be restarted on it${restart}`);
419
+ return DAEMON.EXIT_UPGRADE;
420
+ }
421
+ if (stop.signal.aborted)
422
+ break;
423
+ await sleep(pollSecondsOf(state.settings) * 1000, stop.signal);
424
+ }
425
+ catch (error) {
426
+ const status = statusOf(error);
427
+ const said = platformSays(error, clip);
428
+ /** `HTTP 401`, with the platform's own reason when it gave one. */
429
+ const why = (head) => (said ? `${head}: ${said}` : head);
430
+ const what = registering ? "registration" : "claim";
431
+ if (status === 401) {
432
+ mayDeregister = false;
433
+ say("error", `the platform refused the pool token for ${pool} (${why("HTTP 401")}): it was revoked or has expired, or its workspace is suspended; issue a new token in Agent pools and set AGENT_POOL_TOKEN`);
434
+ return DAEMON.EXIT_CONFIG;
435
+ }
436
+ if (status === 400) {
437
+ say("error", registering
438
+ ? said
439
+ ? `the platform refused this daemon's registration: ${said} (HTTP 400); restarting will not help`
440
+ : "the platform refused this daemon's registration (HTTP 400): check the installation name (--installation-name / AGENT_POOL_INSTALLATION: 1-63 of a-z, 0-9 and -; hosted and BYO pools need one)"
441
+ : `the platform refused this daemon's claim (${why("HTTP 400")}): restarting will not help; ${said ? "upgrade or report @stackfactor/agent-utils" : "this @stackfactor/agent-utils may not speak the platform's protocol; upgrade agent-utils"}`);
442
+ return DAEMON.EXIT_CONFIG;
443
+ }
444
+ if (status === 403) {
445
+ // The platform's own 403 says why (the pool is disabled, design §4.2).
446
+ // One without a reason came from something in front of it (a
447
+ // firewall, a proxy): not called a disabled pool, waited out the same.
448
+ say("warn", said
449
+ ? `the pool is disabled (${why(`HTTP 403 on the ${what}`)}): asking again in ${DAEMON.DISABLED_RETRY_MS / 1000} s`
450
+ : `the ${what} was refused (HTTP 403) with no reason given: the pool may be disabled, or something in front of ${backend.origin} refuses this host; asking again in ${DAEMON.DISABLED_RETRY_MS / 1000} s`);
451
+ await sleep(DAEMON.DISABLED_RETRY_MS, stop.signal);
452
+ continue;
453
+ }
454
+ if (status === 404 && !registering) {
455
+ const lost = state.daemonId;
456
+ state.daemonId = null;
457
+ if (claimedSinceRegistered) {
458
+ say("warn", `the platform no longer knows daemon ${lost} (HTTP 404): registering again`);
459
+ continue;
460
+ }
461
+ // Lost again before one claim got through: back off, or a platform
462
+ // that keeps forgetting the daemon would be asked in a tight loop.
463
+ const delay = failed();
464
+ say("warn", `the platform lost daemon ${lost} before it could claim (HTTP 404): registering again in ${inSeconds(delay)}`);
465
+ await sleep(delay, stop.signal);
466
+ continue;
467
+ }
468
+ const delay = failed();
469
+ const unreached = status === undefined && typeof error?.code === "string";
470
+ let hint = "";
471
+ if (registering && status === 404) {
472
+ hint = `; no pool routes at ${backend.origin}: is AGENT_POOL_BACKEND_URL (--backend) the StackFactor backend?`;
473
+ }
474
+ else if (registering && unreached) {
475
+ hint = `; cannot reach ${backend.origin}: check AGENT_POOL_BACKEND_URL (--backend) and the network`;
476
+ }
477
+ else if (status !== undefined && status >= 300 && status < 400) {
478
+ hint = `; ${backend.origin} answered a redirect, which is never followed with the token: is AGENT_POOL_BACKEND_URL (--backend) the https URL of the StackFactor backend itself?`;
479
+ }
480
+ say("warn", `${what} failed (${describe(error, clip)}${hint}): trying again in ${inSeconds(delay)}`);
481
+ await sleep(delay, stop.signal);
482
+ }
483
+ }
484
+ return 0;
485
+ };
486
+ try {
487
+ const code = await run();
488
+ if (state.daemonId !== null && mayDeregister)
489
+ await leave(state.daemonId);
490
+ return code;
491
+ }
492
+ finally {
493
+ signals.off("SIGTERM", onTerm);
494
+ signals.off("SIGINT", onInt);
495
+ }
496
+ };
497
+ /** `start` runs the daemon; `readConfig` reads and checks its configuration from flags and environment. */
498
+ const daemon = { start, readConfig: readDaemonConfig };
499
+ export default daemon;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The pool daemon's configuration, read from flags and environment.
3
+ * A flag wins over its variable. Junk is refused here, before any request.
4
+ * No message names more of the token than `sfp_<poolId>`.
5
+ */
6
+ /** Thrown for a configuration the daemon must not start with. */
7
+ export declare class DaemonConfigError extends Error {
8
+ constructor(message: string);
9
+ }
10
+ export interface InfrastructureOverrides {
11
+ cloud?: string;
12
+ region?: string;
13
+ account?: string;
14
+ cluster?: string;
15
+ }
16
+ export interface DaemonConfig {
17
+ poolToken: string;
18
+ /**
19
+ * The installation's name (`--installation-name`). Sent to the platform as
20
+ * `deployment`, the protocol's name for it.
21
+ */
22
+ deployment?: string;
23
+ /**
24
+ * The StackFactor backend the pool token is sent to, http or https.
25
+ * Required, never defaulted (R-C10): a default could hand the token to
26
+ * whatever host a stray variable or `.env` names.
27
+ */
28
+ backendUrl: string;
29
+ reportInfrastructure: boolean;
30
+ overrides: InfrastructureOverrides;
31
+ /** Things worth telling the operator that do not stop the daemon. */
32
+ warnings: string[];
33
+ }
34
+ /**
35
+ * Reads the daemon's configuration.
36
+ * @throws DaemonConfigError for no token, a token not starting `sfp_` or
37
+ * holding a character no token has, a malformed installation name, no backend
38
+ * URL or one that is not a plain http(s) URL, an `AGENT_POOL_REPORT_INFRASTRUCTURE`
39
+ * that is neither true nor false, an unknown flag or a flag with no value.
40
+ */
41
+ export declare const readDaemonConfig: (argv: string[], env: NodeJS.ProcessEnv) => DaemonConfig;
42
+ /** `sfp_<poolId>` for logs: never more of the token than that. */
43
+ export declare const poolOf: (token: string) => string;
44
+ export default readDaemonConfig;
45
+ //# sourceMappingURL=daemonConfig.d.ts.map