yatfa 1.0.98 → 1.0.99

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.
@@ -154,12 +154,12 @@ if command == "attach"
154
154
  puts ""
155
155
  agent_type = ARGV[1]&.downcase
156
156
  abort "Usage: npx yatfa attach [agent-type]" unless agent_type
157
- config = YatfaAgent::Config.load
157
+ config = YatfaAgent::Config.load(allow_remote_fetch: true)
158
158
  YatfaAgent::Config.fetch_repositories!(config)
159
159
  YatfaAgent::Agent.attach(agent_type, config, AGENT_CONFIGS)
160
160
  else
161
161
  # Handle run commands (worker, planner, reviewer, researcher, claw)
162
- config = YatfaAgent::Config.load
162
+ config = YatfaAgent::Config.load(allow_remote_fetch: true)
163
163
  # Fetch repositories from Rails API before building
164
164
  YatfaAgent::Config.fetch_repositories!(config)
165
165
  # Note: Docker.build_image is called inside Agent.run() only when a new
@@ -0,0 +1,389 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "fileutils"
5
+ require_relative "http"
6
+
7
+ module YatfaAgent
8
+ # Single-purpose runner bootstrap (YATFA-3203 / Creation→FULL WORK phase 7b —
9
+ # runner half).
10
+ #
11
+ # Lets a runner in a fresh checkout with no local +yatfa.env.rb+ obtain one
12
+ # by pasting a single bootstrap string (+<host>#<yrt_token>+), generated by
13
+ # the server (phase 7a, YATFA-3194). The token authorizes EXACTLY one read —
14
+ # +GET <host>/api/v1/bootstrap/env_file+ — and is:
15
+ # - NOT written into the served +yatfa.env.rb+,
16
+ # - NOT exported into runtime env,
17
+ # - NOT sent anywhere except the bootstrap endpoint.
18
+ # (spec YATFA-3019 §2.3 single-purpose invariant — see the comment at
19
+ # +fetch_remote_env_file+.)
20
+ #
21
+ # The {host, token} pair is cached under +~/.yatfa/runner_bootstrap.json+
22
+ # (0600) so subsequent fresh checkouts auto-fetch without re-prompting — the
23
+ # credential is single-purpose and read-only, equivalent to +~/.npmrc+. The
24
+ # cache stores the bootstrap CREDENTIAL, never the env-file CONTENT (each
25
+ # checkout fetches fresh so rotated keys / new agents propagate).
26
+ module Bootstrap
27
+ # Raw token shape: +yrt_+ prefix + 64 hex chars (256 bits). Mirrors the
28
+ # server's +ProjectRunnerToken.well_formed?+ regex so a malformed paste is
29
+ # rejected client-side with a friendly error before any network call.
30
+ TOKEN_PATTERN = /\Ayrt_[0-9a-f]{64}\z/.freeze
31
+
32
+ # The single endpoint this credential authorizes a read against.
33
+ ENV_FILE_PATH = "/api/v1/bootstrap/env_file".freeze
34
+
35
+ # Reuses the installer's +~/.yatfa/+ directory convention (installer.rb).
36
+ # Resolved at call time (methods, not load-time constants) so the path
37
+ # tracks the current +HOME+ — keeps the cache location correct under
38
+ # env changes and lets specs isolate it via +ENV["HOME"]+.
39
+ def self.cache_dir
40
+ File.expand_path("~/.yatfa")
41
+ end
42
+
43
+ def self.cache_file
44
+ File.join(cache_dir, "runner_bootstrap.json")
45
+ end
46
+ private_class_method :cache_dir, :cache_file
47
+
48
+ # Parsed paste string: either a valid {host, token} pair or an {error}
49
+ # message. Never echoes the token in +error+. Use +ok?+ to branch.
50
+ PasteString = Struct.new(:host, :token, :error, keyword_init: true) do
51
+ def ok?
52
+ error.nil?
53
+ end
54
+ end
55
+ private_constant :PasteString
56
+
57
+ # Result of +fetch_remote_env_file+: a successful +body+ (the env-file
58
+ # Ruby source) or a classified +error+ message. Use +ok?+ to branch.
59
+ FetchResult = Struct.new(:body, :error, keyword_init: true) do
60
+ def ok?
61
+ error.nil?
62
+ end
63
+ end
64
+ private_constant :FetchResult
65
+
66
+ # Split +<host>#<token>+ on the FIRST +#+ and validate the token shape and
67
+ # host scheme. The token is a URL fragment per the server contract (phase
68
+ # 7a), so everything after the first +#+ is the token regardless of any +#+
69
+ # it may contain (it never does for a +yrt_+ token, but splitting on the
70
+ # first delimiter is the robust choice). Returns a PasteString; never
71
+ # raises. Never echoes the token in the returned error.
72
+ #
73
+ # The host MUST use +https://+ — an +http://+ host would send the bootstrap
74
+ # Bearer token in cleartext over the wire. +http://+ is allowed only for
75
+ # loopback (local dev servers).
76
+ #
77
+ # @param input [String] the pasted bootstrap string
78
+ # @return [PasteString] parsed +host+/+token+ or a friendly +error+
79
+ def self.parse_paste_string(input)
80
+ input = input.to_s.strip
81
+
82
+ unless input.include?("#")
83
+ return malformed
84
+ end
85
+
86
+ host, token = input.split("#", 2)
87
+ host = host.to_s.strip
88
+ token = token.to_s.strip
89
+
90
+ return malformed if host.empty? || !token.match?(TOKEN_PATTERN)
91
+ return insecure_host unless secure_host?(host)
92
+
93
+ PasteString.new(host: host, token: token)
94
+ end
95
+
96
+ # Fetch the env file from the bootstrap endpoint, returning a FetchResult.
97
+ # On 200 the +body+ is the env-file Ruby source (served as +text/x-ruby+);
98
+ # non-2xx, network, and invalid-body responses are classified into friendly
99
+ # +error+ messages. Never echoes the token.
100
+ #
101
+ # Single-purpose invariant (spec §2.3): the token is sent ONLY to
102
+ # +<host>/api/v1/bootstrap/env_file+ as a Bearer credential. It is not
103
+ # written anywhere, not exported into the runtime environment, and not
104
+ # reused for any other API call. The served env file carries the EXISTING
105
+ # per-agent +mcp_api_key+s unchanged — those remain the runtime +X-API-Key+
106
+ # credential. This method is the ONLY site that handles the raw token.
107
+ #
108
+ # The fetched body is validated to be non-empty Ruby that evaluates to a
109
+ # Hash BEFORE it is treated as a success, so a transient empty/HTML/malformed
110
+ # response is reported cleanly instead of crashing +Config.load+'s
111
+ # downstream +eval+ (same trust boundary: the token-authenticated yatfa
112
+ # server, which +Config.load+ evals anyway).
113
+ #
114
+ # @param host [String] yatfa base URL (e.g. +https://app.yatfa.com+)
115
+ # @param token [String] raw +yrt_++64-hex bootstrap token
116
+ # @return [FetchResult] +body+ on success, classified +error+ otherwise
117
+ def self.fetch_remote_env_file(host:, token:)
118
+ url = "#{normalize_host(host)}#{ENV_FILE_PATH}"
119
+ body = YatfaAgent::HTTP.get_raw(url, headers: { "Authorization" => "Bearer #{token}" })
120
+ unless valid_env_file_body?(body)
121
+ return FetchResult.new(error: invalid_body_error)
122
+ end
123
+ FetchResult.new(body: body)
124
+ rescue YatfaAgent::HTTP::Error => e
125
+ FetchResult.new(error: classify_http_error(e.status_code, host))
126
+ rescue StandardError => e
127
+ # Network/DNS/timeout/socket — the server was unreachable. Do not echo
128
+ # the token; surface only the host and the generic failure cause.
129
+ FetchResult.new(error: "❌ Could not reach #{normalize_host(host)}: #{e.message}")
130
+ end
131
+
132
+ # Read the cached {host, token} pair, or nil if no cache exists / is
133
+ # unreadable. Returns a +[host, token]+ Array for ergonomic destructuring.
134
+ # @return [Array(String, String), nil]
135
+ def self.read_cached_credentials
136
+ return nil unless File.exist?(cache_file)
137
+
138
+ parsed =
139
+ begin
140
+ JSON.parse(File.read(cache_file))
141
+ rescue StandardError
142
+ nil
143
+ end
144
+
145
+ return nil unless parsed.is_a?(Hash)
146
+
147
+ host = parsed["host"].to_s
148
+ token = parsed["token"].to_s
149
+ return nil if host.empty? || !token.match?(TOKEN_PATTERN)
150
+
151
+ [host, token]
152
+ end
153
+
154
+ # Persist the {host, token} pair under +~/.yatfa/runner_bootstrap.json+
155
+ # with 0600 perms — created restrictive in ONE call (File.open + chmod
156
+ # would leave a world-readable window under umask 022; this cache holds the
157
+ # raw bootstrap token). Best effort — a cache write failure must not abort
158
+ # an otherwise-successful bootstrap, so it is logged and swallowed.
159
+ # @param host [String]
160
+ # @param token [String]
161
+ # @return [Boolean] true if written, false on failure
162
+ def self.write_cached_credentials(host:, token:)
163
+ FileUtils.mkdir_p(cache_dir)
164
+ File.open(cache_file, "w", 0o600) { |f| f.write(JSON.generate("host" => host, "token" => token)) }
165
+ true
166
+ rescue StandardError => e
167
+ puts "⚠️ Could not cache bootstrap token (#{e.message}); you'll need to paste again next time."
168
+ false
169
+ end
170
+
171
+ # Remove a stale/dead cache (e.g. after a cached fetch returns 401/404 so
172
+ # the next run re-prompts instead of looping on a revoked token). Logs a
173
+ # warning if the delete fails — a stuck cache means every subsequent run
174
+ # repeats a doomed fetch, which is worth surfacing (unlike a read failure,
175
+ # which is benignly treated as "no cache").
176
+ # @return [void]
177
+ def self.clear_cached_credentials
178
+ File.delete(cache_file) if File.exist?(cache_file)
179
+ rescue StandardError => e
180
+ puts "⚠️ Could not remove stale bootstrap cache (#{e.message}); it will be retried next run."
181
+ end
182
+
183
+ # Orchestrator: obtain +yatfa.env.rb+ for a fresh checkout via the
184
+ # bootstrap token path. Writes the file to +Dir.pwd+ on success (so the
185
+ # caller's subsequent +File.read+ finds it) and caches the credential for
186
+ # future checkouts. Exits 1 with guidance on any failure, or when no
187
+ # credential is obtainable non-interactively (CI/scripts).
188
+ #
189
+ # Precedence: a local +yatfa.env.rb+ ALWAYS wins — this method is only
190
+ # reached from +Config.load+ when that file is absent and the caller opted
191
+ # into the remote-fetch path via +allow_remote_fetch:+.
192
+ #
193
+ # @return [true] on success (file written)
194
+ # @raise [SystemExit] (+exit 1+) on failure or non-interactive-no-cache
195
+ def self.bootstrap_env_file!
196
+ # 1. Try a cached credential first (prior paste in another checkout).
197
+ if (creds = read_cached_credentials)
198
+ host, token = creds
199
+ result = fetch_remote_env_file(host: host, token: token)
200
+ if result.ok?
201
+ return true if write_env_file(result.body)
202
+
203
+ exit 1 # write_env_file already printed the cause
204
+ end
205
+
206
+ # Cached credential no longer works (revoked / server rotated keys).
207
+ # Clear it so we don't keep retrying a dead token, then fall through.
208
+ puts result.error
209
+ clear_cached_credentials
210
+ end
211
+
212
+ # 2. Non-interactive + no working cache → cannot prompt a tty that
213
+ # isn't there. Mirror the existing --no-prompt contract: exit, don't
214
+ # hang. Show the manual-setup template too, so a CI box with no token
215
+ # still has the actionable copy-paste fallback it had before this path.
216
+ if non_interactive?
217
+ puts ""
218
+ puts "❌ yatfa.env.rb not found and no bootstrap token cached."
219
+ puts " Run 'npx yatfa setup' interactively once, paste a runner"
220
+ puts " bootstrap token on a tty, OR create yatfa.env.rb manually:"
221
+ puts ""
222
+ puts YatfaAgent::Bootstrap.manual_setup_instructions
223
+ exit 1
224
+ end
225
+
226
+ # 3. Interactive: prompt ONCE for the paste string.
227
+ puts ""
228
+ puts "🔧 No yatfa.env.rb found in this checkout."
229
+ puts " Paste a runner bootstrap string to fetch it"
230
+ puts " (Project Settings → Runner token):"
231
+ print "> "
232
+ input = $stdin.gets&.strip.to_s
233
+
234
+ parsed = parse_paste_string(input)
235
+ unless parsed.ok?
236
+ puts parsed.error
237
+ exit 1
238
+ end
239
+
240
+ result = fetch_remote_env_file(host: parsed.host, token: parsed.token)
241
+ unless result.ok?
242
+ puts result.error
243
+ exit 1
244
+ end
245
+
246
+ exit 1 unless write_env_file(result.body)
247
+ write_cached_credentials(host: parsed.host, token: parsed.token)
248
+ true
249
+ end
250
+
251
+ # Write the fetched env-file content to +Dir.pwd/yatfa.env.rb+ — the same
252
+ # location the setup wizard writes to, so the downstream +Config.load+
253
+ # eval path (config.rb) is unchanged. Created 0600 (the file embeds agent
254
+ # +mcp_api_key+s and +dot_env+ secrets). Returns the path on success, nil
255
+ # (after printing a clean message) if the write itself fails — a rare but
256
+ # fatal condition (read-only cwd, ENOSPC) the caller cannot recover from.
257
+ # @param content [String] env-file Ruby source
258
+ # @return [String, nil] the path written, or nil on write failure
259
+ def self.write_env_file(content)
260
+ config_file = File.join(Dir.pwd, "yatfa.env.rb")
261
+ File.open(config_file, "w", 0o600) { |f| f.write(content) }
262
+ puts "✅ Wrote yatfa.env.rb from bootstrap token (#{config_file})"
263
+ puts " Reminder: ensure it's gitignored → echo 'yatfa.env.rb' >> .gitignore"
264
+ config_file
265
+ rescue StandardError => e
266
+ puts "❌ Could not write #{config_file}: #{e.message}"
267
+ puts " Fix the directory permissions/disk and re-run."
268
+ nil
269
+ end
270
+
271
+ # The manual-setup guidance shown when +yatfa.env.rb+ is missing and the
272
+ # bootstrap path can't produce one (no tty, no cached token — e.g. CI).
273
+ # Returned as a string so both this module's non-interactive branch and
274
+ # +Config.load+'s local-only missing-file branch can +puts+ the SAME
275
+ # actionable template (Config delegates here). Lives in Bootstrap rather
276
+ # than Config because +config.rb+ requires +bootstrap.rb+ (one-way), so the
277
+ # shared helper belongs in the lower layer to avoid a back-reference.
278
+ # @return [String]
279
+ def self.manual_setup_instructions
280
+ <<~MSG
281
+ ❌ Error: yatfa.env.rb not found in current directory
282
+
283
+ Create yatfa.env.rb:
284
+ {
285
+ yatfa_url: 'https://yatfa.example.com', # Required
286
+ # ...
287
+ # Paste your stripped .env content here:
288
+ dot_env: <<~ENV
289
+ STRIPE_KEY=sk_test_...
290
+ OPENAI_KEY=sk-...
291
+ ENV
292
+ }
293
+ echo 'yatfa.env.rb' >> .gitignore
294
+ MSG
295
+ end
296
+
297
+ # Whether prompting is impossible/forbidden. Mirrors Interaction#non_interactive?
298
+ # (interaction.rb) — duplicated here so the Bootstrap module stays
299
+ # self-contained (no load-order/coupling dependency on Agent extending
300
+ # Interaction). Kept in sync with that definition by contract.
301
+ # @return [Boolean]
302
+ def self.non_interactive?
303
+ !$stdin.tty? || ENV["YATFA_NO_PROMPT"] == "1" || ARGV.include?("--no-prompt") || ARGV.include?("-d")
304
+ end
305
+
306
+ # True if +host+ may safely carry the bootstrap token: +https://+ always,
307
+ # or +http://+ only for loopback (local dev servers where TLS is unusual).
308
+ def self.secure_host?(host)
309
+ h = host.to_s.strip.downcase
310
+ return true if h.start_with?("https://")
311
+ return true if h.start_with?("http://localhost") ||
312
+ h.start_with?("http://127.0.0.1") ||
313
+ h.start_with?("http://0.0.0.0") ||
314
+ h.start_with?("http://[::1]")
315
+
316
+ false
317
+ end
318
+ private_class_method :secure_host?
319
+
320
+ # A fetched env file is valid only if it is non-empty Ruby that evaluates
321
+ # to a Hash (the shape +Config.load+ expects). Guards against an empty /
322
+ # HTML / truncated server response being written to disk and then crashing
323
+ # the downstream +eval+.
324
+ def self.valid_env_file_body?(content)
325
+ return false if content.nil? || content.to_s.strip.empty?
326
+
327
+ eval(content).is_a?(Hash)
328
+ rescue StandardError, ScriptError
329
+ # ScriptError covers SyntaxError (malformed Ruby / HTML page); this is a
330
+ # validation predicate and must NEVER raise — any eval failure means the
331
+ # body is not a valid Hash literal, so report it as invalid.
332
+ false
333
+ end
334
+ private_class_method :valid_env_file_body?
335
+
336
+ # Classify a non-2xx status code into friendly, token-free guidance.
337
+ # Status semantics mirror the server contract (bootstrap_controller.rb):
338
+ # 401 = missing/malformed/revoked, 404 = well-formed but unknown.
339
+ def self.classify_http_error(status_code, host)
340
+ case status_code
341
+ when 401
342
+ "❌ Token invalid or revoked — generate a new bootstrap string in Project Settings → Runner token."
343
+ when 404
344
+ "❌ Token not recognized by this server — generate a new bootstrap string."
345
+ else
346
+ "❌ Server at #{normalize_host(host)} returned HTTP #{status_code} — try again or generate a new bootstrap string."
347
+ end
348
+ end
349
+ private_class_method :classify_http_error
350
+
351
+ # Strip trailing slashes from the host so +<host>+/api/v1/... is well-formed
352
+ # regardless of whether the pasted host ended in +/+. NOTE: the bootstrap
353
+ # host comes from the operator's paste string (the server that ISSUED the
354
+ # token), so it is intentionally NOT routed through YatfaAgent::UrlHelper —
355
+ # an explicit +YATFA_API_URL+ override must NOT redirect the token to a
356
+ # different server than the one that minted it (that would both fail auth
357
+ # and leak the credential).
358
+ def self.normalize_host(host)
359
+ host.to_s.sub(%r{/+\z}, "")
360
+ end
361
+ private_class_method :normalize_host
362
+
363
+ # The friendly "doesn't look like a bootstrap string" error. Centralized so
364
+ # the wording is identical for every malformed-input path. Never echoes input.
365
+ def self.malformed
366
+ PasteString.new(
367
+ error: "❌ That doesn't look like a runner bootstrap string — " \
368
+ "generate one from Project Settings → Runner token."
369
+ )
370
+ end
371
+ private_class_method :malformed
372
+
373
+ # The "host must use https" error (cleartext http would leak the token).
374
+ def self.insecure_host
375
+ PasteString.new(
376
+ error: "❌ Bootstrap host must use https:// (an http:// host would " \
377
+ "send the token in cleartext). Re-copy the full bootstrap " \
378
+ "string from Project Settings → Runner token."
379
+ )
380
+ end
381
+ private_class_method :insecure_host
382
+
383
+ def self.invalid_body_error
384
+ "❌ Server returned an invalid or empty env file. " \
385
+ "Try again, or generate a new bootstrap string."
386
+ end
387
+ private_class_method :invalid_body_error
388
+ end
389
+ end
@@ -3,6 +3,7 @@
3
3
  require "json"
4
4
  require "digest"
5
5
  require_relative "http"
6
+ require_relative "bootstrap"
6
7
  # Single source of truth for URL→{api,ws} derivation + the hosted default.
7
8
  # Loaded here (not duplicated) so the host-side launcher routes ALL URL
8
9
  # derivation through YatfaAgent::UrlHelper — the same module the in-container
@@ -31,24 +32,38 @@ module YatfaAgent
31
32
  nil
32
33
  end
33
34
 
34
- def self.load
35
+ # Load +yatfa.env.rb+ from the current directory and normalize it.
36
+ #
37
+ # When the file is absent and +allow_remote_fetch+ is true (the runner
38
+ # entry point opts in), the bootstrap token path runs first: it fetches the
39
+ # env file from the server via a single-purpose runner token (see
40
+ # YatfaAgent::Bootstrap) and writes it to +Dir.pwd+, then this method
41
+ # loads it as if it had been there all along. A LOCAL +yatfa.env.rb+
42
+ # always wins — the remote-fetch path only runs when one is missing.
43
+ #
44
+ # When +allow_remote_fetch+ is false (the default — tests, CI, library
45
+ # callers), +Config.load+ stays a pure local-file reader: a missing file
46
+ # prints the manual-setup guidance and exits 1, exactly as before.
47
+ #
48
+ # @param allow_remote_fetch [Boolean] enable the bootstrap token path on a
49
+ # missing file (default: false, keeps callers deterministic)
50
+ def self.load(allow_remote_fetch: false)
35
51
  config_file = File.join(Dir.pwd, "yatfa.env.rb")
36
52
 
37
53
  unless File.exist?(config_file)
38
- puts "❌ Error: yatfa.env.rb not found in current directory"
39
- puts ""
40
- puts "Create yatfa.env.rb:"
41
- puts " {"
42
- puts " yatfa_url: 'https://yatfa.example.com', # Required"
43
- puts " # ..."
44
- puts " # Paste your stripped .env content here:"
45
- puts " dot_env: <<~ENV"
46
- puts " STRIPE_KEY=sk_test_..."
47
- puts " OPENAI_KEY=sk-..."
48
- puts " ENV"
49
- puts " }"
50
- puts " echo 'yatfa.env.rb' >> .gitignore"
51
- exit 1
54
+ if allow_remote_fetch
55
+ # Fetches +yatfa.env.rb+ via a single-purpose bootstrap token and
56
+ # writes it to Dir.pwd, or exits 1 with guidance. On success the
57
+ # file now exists and the eval path below loads it unchanged.
58
+ # Local>token>error precedence holds: we only reach here when no
59
+ # local file is present.
60
+ YatfaAgent::Bootstrap.bootstrap_env_file!
61
+ else
62
+ # Shared with the bootstrap non-interactive path so both surfaces
63
+ # print the same actionable template.
64
+ puts YatfaAgent::Bootstrap.manual_setup_instructions
65
+ exit 1
66
+ end
52
67
  end
53
68
 
54
69
  puts "⚙️ Loading configuration from yatfa.env.rb"
@@ -43,6 +43,30 @@ module YatfaAgent
43
43
  handle_response(response)
44
44
  end
45
45
 
46
+ # Perform a GET request returning the RAW response body as a String on
47
+ # success (NO JSON parsing). Use this for endpoints that serve non-JSON
48
+ # bodies — e.g. the bootstrap env-file endpoint serves +text/x-ruby+
49
+ # (Ruby source), which would raise JSON::ParserError under +.get+.
50
+ #
51
+ # Raises YatfaAgent::HTTP::Error (with +status_code+) for non-2xx exactly
52
+ # like +.get+, so callers can reuse the +rescue HTTP::Error => e;
53
+ # case e.status_code+ classification pattern unchanged.
54
+ #
55
+ # @param url [String] full URL to request
56
+ # @param headers [Hash] HTTP headers (e.g. { "Authorization" => "Bearer x" })
57
+ # @param open_timeout [Integer] connection timeout in seconds (default: 5)
58
+ # @param read_timeout [Integer] response timeout in seconds (default: 10)
59
+ # @return [String] raw response body
60
+ # @raise [Error] for non-2xx HTTP responses
61
+ def self.get_raw(url, headers: {}, open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT)
62
+ uri = URI(url)
63
+ http = build_http(uri, open_timeout: open_timeout, read_timeout: read_timeout)
64
+ request = Net::HTTP::Get.new(uri)
65
+ headers.each { |k, v| request[k] = v }
66
+ response = http.request(request)
67
+ handle_response(response, raw: true)
68
+ end
69
+
46
70
  # Perform a POST request. Returns parsed JSON body on success.
47
71
  # Raises YatfaAgent::HTTP::Error for non-2xx responses.
48
72
  # Raises exceptions on network/timeout errors.
@@ -81,9 +105,14 @@ module YatfaAgent
81
105
  JSON.parse(body)
82
106
  end
83
107
 
84
- def handle_response(response)
108
+ # Parse a 2xx success body. By default the body is parsed as JSON (the
109
+ # contract every existing caller relies on); pass +raw: true+ to return
110
+ # the body verbatim — for non-JSON endpoints (e.g. the bootstrap env-file
111
+ # endpoint serves +text/x-ruby+). The non-2xx error path is shared so the
112
+ # +Error+ shape (with +status_code+) is identical either way.
113
+ def handle_response(response, raw: false)
85
114
  if response.is_a?(Net::HTTPSuccess)
86
- parse_json(response.body)
115
+ raw ? response.body : parse_json(response.body)
87
116
  else
88
117
  raise Error.new(
89
118
  "HTTP #{response.code} #{response.message}",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yatfa",
3
- "version": "1.0.98",
3
+ "version": "1.0.99",
4
4
  "description": "YATFA - Yet Another Tool For Agents",
5
5
  "bin": "./bin/run-yatfa-agent.rb",
6
6
  "files": [
@@ -43,6 +43,30 @@ module YatfaAgent
43
43
  handle_response(response)
44
44
  end
45
45
 
46
+ # Perform a GET request returning the RAW response body as a String on
47
+ # success (NO JSON parsing). Use this for endpoints that serve non-JSON
48
+ # bodies — e.g. the bootstrap env-file endpoint serves +text/x-ruby+
49
+ # (Ruby source), which would raise JSON::ParserError under +.get+.
50
+ #
51
+ # Raises YatfaAgent::HTTP::Error (with +status_code+) for non-2xx exactly
52
+ # like +.get+, so callers can reuse the +rescue HTTP::Error => e;
53
+ # case e.status_code+ classification pattern unchanged.
54
+ #
55
+ # @param url [String] full URL to request
56
+ # @param headers [Hash] HTTP headers (e.g. { "Authorization" => "Bearer x" })
57
+ # @param open_timeout [Integer] connection timeout in seconds (default: 5)
58
+ # @param read_timeout [Integer] response timeout in seconds (default: 10)
59
+ # @return [String] raw response body
60
+ # @raise [Error] for non-2xx HTTP responses
61
+ def self.get_raw(url, headers: {}, open_timeout: DEFAULT_OPEN_TIMEOUT, read_timeout: DEFAULT_READ_TIMEOUT)
62
+ uri = URI(url)
63
+ http = build_http(uri, open_timeout: open_timeout, read_timeout: read_timeout)
64
+ request = Net::HTTP::Get.new(uri)
65
+ headers.each { |k, v| request[k] = v }
66
+ response = http.request(request)
67
+ handle_response(response, raw: true)
68
+ end
69
+
46
70
  # Perform a POST request. Returns parsed JSON body on success.
47
71
  # Raises YatfaAgent::HTTP::Error for non-2xx responses.
48
72
  # Raises exceptions on network/timeout errors.
@@ -81,9 +105,14 @@ module YatfaAgent
81
105
  JSON.parse(body)
82
106
  end
83
107
 
84
- def handle_response(response)
108
+ # Parse a 2xx success body. By default the body is parsed as JSON (the
109
+ # contract every existing caller relies on); pass +raw: true+ to return
110
+ # the body verbatim — for non-JSON endpoints (e.g. the bootstrap env-file
111
+ # endpoint serves +text/x-ruby+). The non-2xx error path is shared so the
112
+ # +Error+ shape (with +status_code+) is identical either way.
113
+ def handle_response(response, raw: false)
85
114
  if response.is_a?(Net::HTTPSuccess)
86
- parse_json(response.body)
115
+ raw ? response.body : parse_json(response.body)
87
116
  else
88
117
  raise Error.new(
89
118
  "HTTP #{response.code} #{response.message}",