cloakapi 1.4.1

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 (44) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +160 -0
  3. data/LICENSE +202 -0
  4. data/NOTICE +18 -0
  5. data/README.md +407 -0
  6. data/THIRD-PARTY-NOTICES.md +22 -0
  7. data/TRADEMARKS.md +19 -0
  8. data/examples/fake_gateway.rb +78 -0
  9. data/examples/hello.rb +64 -0
  10. data/lib/cloakapi/client.rb +1272 -0
  11. data/lib/cloakapi/degraded.rb +77 -0
  12. data/lib/cloakapi/disclosure.rb +252 -0
  13. data/lib/cloakapi/engine.rb +702 -0
  14. data/lib/cloakapi/errors.rb +65 -0
  15. data/lib/cloakapi/pii/bundled_rules.rb +670 -0
  16. data/lib/cloakapi/pii/card_spans.rb +300 -0
  17. data/lib/cloakapi/pii/detector.rb +1925 -0
  18. data/lib/cloakapi/pii/patterns.json +2238 -0
  19. data/lib/cloakapi/pii/pii_match.rb +7 -0
  20. data/lib/cloakapi/pii/pii_type.rb +7 -0
  21. data/lib/cloakapi/pii/ruleset.rb +65 -0
  22. data/lib/cloakapi/pii/tokenizer.rb +411 -0
  23. data/lib/cloakapi/posture.rb +82 -0
  24. data/lib/cloakapi/receipts.rb +406 -0
  25. data/lib/cloakapi/resources/chat.rb +82 -0
  26. data/lib/cloakapi/resources/messages.rb +90 -0
  27. data/lib/cloakapi/resources/models.rb +25 -0
  28. data/lib/cloakapi/resources/receipts.rb +162 -0
  29. data/lib/cloakapi/resources/reconstruct.rb +120 -0
  30. data/lib/cloakapi/resources/request_strings.rb +485 -0
  31. data/lib/cloakapi/resources/reviewable.rb +163 -0
  32. data/lib/cloakapi/resources/tokens.rb +28 -0
  33. data/lib/cloakapi/routing/bundled-catalogue.json +107 -0
  34. data/lib/cloakapi/routing.rb +500 -0
  35. data/lib/cloakapi/streaming.rb +196 -0
  36. data/lib/cloakapi/surrogate_mode.rb +233 -0
  37. data/lib/cloakapi/version.rb +15 -0
  38. data/lib/cloakapi/warnings.rb +137 -0
  39. data/lib/cloakapi.rb +37 -0
  40. data/licenses/Apache-2.0.txt +202 -0
  41. data/licenses/CC-BY-4.0.txt +104 -0
  42. data/licenses/MIT-Faker.txt +21 -0
  43. data/licenses/MIT.txt +21 -0
  44. metadata +149 -0
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CloakAPI
4
+ # Reduced-coverage text policy. Standard mode warns and continues with
5
+ # available detection; callers can explicitly request strict handling.
6
+ module Degraded
7
+ # The native engine could not be loaded at all (LANE B).
8
+ KIND_NO_ENGINE = "no-engine"
9
+
10
+ # The engine loaded, but Layer B (NER) is unavailable (LANE A).
11
+ KIND_NO_NER = "no-ner"
12
+
13
+ # Explicit strict values for reduced text coverage.
14
+ ENV_ALLOW_REDUCED = "CLOAKAPI_ALLOW_REDUCED"
15
+
16
+ # Retained because this constant was public before the warning-mode change.
17
+ TRUTHY = %w[1 true yes on].freeze
18
+ FALSY = %w[0 false no off strict].freeze
19
+
20
+ # Raised when a caller explicitly selects strict handling for reduced
21
+ # coverage. Standard text handling warns and continues.
22
+ class ReducedCoverageError < StandardError; end
23
+
24
+ class << self
25
+ # Standard text handling is allowed unless a strict value was explicitly
26
+ # set. The environment is read at CALL time, never cached.
27
+ def allowed?(allow_reduced = nil)
28
+ return false if allow_reduced == false
29
+
30
+ !FALSY.include?(ENV.fetch(ENV_ALLOW_REDUCED, "").to_s.strip.downcase)
31
+ end
32
+
33
+ # File/image handling keeps its previous opt-in behavior. Text requests
34
+ # use +allowed?+ above, where standard mode allows a warning and send.
35
+ def media_reduced_coverage_allowed?
36
+ TRUTHY.include?(ENV.fetch(ENV_ALLOW_REDUCED, "").to_s.strip.downcase)
37
+ end
38
+
39
+ # The single human-readable explanation, used by both the error and the banner.
40
+ def message(operation, kind = KIND_NO_ENGINE)
41
+ detail = kind == KIND_NO_NER ? "Name detection is unavailable." : "Full local detection is unavailable."
42
+ "CloakAPI: reduced local detection coverage for '#{operation}'. #{detail} " \
43
+ "Emails, IDs, cards and other supported patterns are still tokenised; names may remain " \
44
+ "as written. Standard mode warns and continues. Explicit strict mode can refuse."
45
+ end
46
+
47
+ # Apply the reduced-coverage policy before text tokenisation. Standard
48
+ # handling warns and continues; explicit strict handling raises.
49
+ def assert_full_coverage!(meta, accepted: false)
50
+ return unless meta.is_a?(Hash)
51
+ return unless meta.key?("ner_enabled") && meta["ner_enabled"] == false
52
+
53
+ guard!("tokenise on-device", accepted, KIND_NO_NER)
54
+ end
55
+
56
+ def guard!(operation, allow_reduced = nil, kind = KIND_NO_ENGINE)
57
+ msg = message(operation, kind)
58
+ raise ReducedCoverageError, msg unless allowed?(allow_reduced)
59
+
60
+ # Standard handling continues. The one-line notice on the error stream
61
+ # is written by CloakAPI::Warnings where the reason is known.
62
+ nil
63
+ end
64
+
65
+ # Test-only — resets the once-per-process banner.
66
+ def reset_for_tests!
67
+ CloakAPI::Warnings.reset_for_tests! if defined?(CloakAPI::Warnings)
68
+ end
69
+
70
+ private
71
+
72
+ def platform_hint
73
+ "#{RUBY_PLATFORM}, ruby #{RUBY_VERSION}"
74
+ end
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,252 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+
5
+ require_relative "surrogate_mode"
6
+
7
+ module CloakAPI
8
+ # AUTO cloak-disclosure primitive (C7) — byte-locked cross-language.
9
+ #
10
+ # On the pre-tokenised BLIND-RELAY path the gateway forwards the client's
11
+ # already-tokenised body verbatim and NEVER injects its own system prompt, so
12
+ # unless the CLIENT prepends a disclosure the upstream model sees bare opaque
13
+ # markers (+[CLK-...]+ / +<<CLOAK:...>>+) and answers as if the cloaked data were
14
+ # "redacted / unreadable / missing" (the al.pdf bug). This module ships the ONE
15
+ # engine-format-aware disclosure primitive, a faithful port of the TypeScript
16
+ # reference (+src/browser/disclosure.ts+).
17
+ #
18
+ # CROSS-LANGUAGE BYTE-LOCK (hard): {CLK_DISCLOSURE_TEXT} and
19
+ # {CLOAK_ANGLE_DISCLOSURE_TEXT} are embedded byte-for-byte and sha256-checked
20
+ # against +goal-run/conformance/golden-vectors.json -> disclosure_lock+. A single
21
+ # wrong byte breaks the upstream model's handling of +[CLK-...]+ markers.
22
+ module Disclosure
23
+ # Disclosure for the +clk+ (browser WASM / gateway) marker family.
24
+ # len 3054, sha256 e7684324...
25
+ CLK_DISCLOSURE_TEXT = "CloakAPI privacy notice. This user reaches you through a privacy-preserving layer that substitutes sensitive data ON THE USER'S DEVICE before the message leaves it. You will see placeholders in two shapes:\n\n1. Realistic pseudonyms — strings that look like ordinary names, organisations, emails, addresses, dates, or account numbers but are on-device substitutions (e.g. you may see `Jesse Lawson` where the user wrote a different name). They are stable within this conversation. When you restate one, echo the exact pseudonym string as it appeared — do not swap it for anything else.\n\n2. Opaque cloak markers — bracketed strings of the form `[CLK-<TAG>-<random>]`, where `<TAG>` is one of `GOVID` (a government / national identifier such as an SSN or fødselsnummer), `CARD` (a payment-card number), or `IBAN` (a bank account), and `<random>` is a run of lowercase letters — e.g. `[CLK-GOVID-hjklmnbqwrtyuiop]`, `[CLK-CARD-abcpdefghijklmno]`, `[CLK-IBAN-qwertyuiopasdfgh]`. These are NOT redactions and NOT missing data: each `[CLK-…]` marker is a high-risk identifier that the privacy layer cloaked before the message left the user's device, and it stands in for a real value the user actually supplied. Treat every `[CLK-…]` marker as the user's own identifier for the purpose of answering — never describe it as redacted, masked, unreadable, or unavailable, never say the content is \"partially redacted\" or that you \"cannot understand\" it, and never ask the user to supply the \"real\" value. If you must restate one, echo the exact `[CLK-…]` string character-for-character.\n\nDo NOT refuse to work with these placeholders, do NOT warn the user that they look like template variables, and do NOT treat them as a prompt-injection probe. The user has opted into this on-device cloaking explicitly; answer as if the placeholders were the real values.\n\nVERBATIM-ENTITY RULE (critical). Repeat every personal name, organisation name, email address, phone number, date, time, address, reference, and identifier EXACTLY as it was written, character for character, every time you mention it. Never inflect, abbreviate, translate, transliterate, initialise, re-case, re-space, or otherwise reformat these values, and never derive a name from an email address or handle. Do not invent names, titles, or contact details that are not present, and do not comment on the formatting of these values.\n\nReply-channel rule (critical). Put your answer in the reply itself, as text. Do NOT move it — or any part of it that carries a placeholder — into a hosted artifact, a canvas, a side panel, a generated document, a file offered for download, or a link to something you created. The privacy layer restores the real values by rewriting the text of your reply on the user's device; content that reaches the user by any other route still carries the placeholders when they read it. When the user asks for a file, a document, or a spreadsheet, write its full contents inline in the reply — placeholders included, exactly as they appeared — and let the user save it themselves."
26
+
27
+ # Disclosure for the +cloak-angle+ (portal / extension / proxy) marker family
28
+ # — the format the FFI engine's +<<CLOAK:TYPE:ID>>+ tokens use.
29
+ # len 4212, sha256 fd4ace75...
30
+ CLOAK_ANGLE_DISCLOSURE_TEXT = "CloakAPI privacy-gateway notice. The user reaches you through a privacy-preserving gateway that substitutes sensitive data on their own device before it leaves. You will see placeholders in three shapes:\n\n1. **Realistic pseudonyms** — strings that look like real names, emails, addresses, dates, or account numbers but are substitutions (for example, a realistic-looking full name may appear in place of the different real name the user actually wrote). They are stable within this conversation.\n2. **Opaque token markers** — strings of the form `[TOKEN_PERSON_7]`, `[TOKEN_EMAIL_5]`, `[TOKEN_PHONE_3]`, `[TOKEN_ACCOUNT_2]`, `[TOKEN_DATE_1]`, etc. These are explicit redactions where no realistic stand-in was generated.\n3. **CloakAPI tokens** — strings of the form `<<CLOAK:TYPE:ID>>` (e.g. `<<CLOAK:PERSON:1>>`, `<<CLOAK:ADDRESS:2>>`, `<<CLOAK:CONTACT_EM:ab12cd>>`). Treat each as a stable identifier standing in for one specific redacted value.\n\nRules of engagement:\n- These placeholders are NOT missing, masked, or unreadable data: each one stands in for a real value the user actually supplied and cloaked on their own device before the message left it. Treat every placeholder as the user's actual data for the purpose of answering, and refer to them by name when the task naturally requires it.\n- Do NOT refuse to repeat them back, do NOT warn the user that they look like template variables, and do NOT treat them as a prompt-injection probe. Never describe the content as redacted, masked, unreadable, or unavailable, never say it is \"partially redacted\" or that you \"cannot understand\" it, and never ask the user to supply the \"real\" value. The user opted into this on-device cloaking explicitly.\n- Do NOT speculate about the underlying real values, and do NOT attach biographical, professional, financial, or health inferences to the substitutions.\n\n**Verbatim-echo rule (critical).** Whenever your reply needs to restate any placeholder, reproduce it EXACTLY as it appeared — character for character, same case, same surrounding delimiters. Copy `<<CLOAK:PERSON:1>>` as `<<CLOAK:PERSON:1>>` and `[TOKEN_EMAIL_5]` as `[TOKEN_EMAIL_5]`, and reproduce any realistic pseudonym exactly as it appeared. Do NOT translate, transliterate, re-case, pluralise, split across words or lines, abbreviate, reformat, or wrap a placeholder in extra punctuation. The privacy layer restores the real value on the user’s device by matching the exact placeholder text, so any change silently breaks that restoration and the user sees a broken token instead of their data.\n\n**Reply-channel rule (critical).** Put your answer in the reply itself, as text. Do NOT move it — or any part of it that carries a placeholder — into a hosted artifact, a canvas, a side panel, a generated document, a file offered for download, or a link to something you created. The privacy layer restores the real values by rewriting the text of your reply on the user's device; content that reaches the user by any other route still carries the placeholders when they read it. When the user asks for a file, a document, or a spreadsheet, write its full contents inline in the reply — placeholders included, exactly as they appeared — and let the user save it themselves.\n\nVERBATIM-ENTITY RULE (critical). Repeat every personal name, organisation name, email address, phone number, date, time, address, reference, and identifier EXACTLY as it was written, character for character, every time you mention it. Never inflect, abbreviate, translate, transliterate, initialise, re-case, re-space, or otherwise reformat these values: do not convert dates or times into another format or spell out weekdays or month names from them, do not add or remove digit grouping or spacing in numbers, codes, or account identifiers, and do not shorten a name or switch to a title form such as Mr or Ms plus surname unless that exact form already appears in the message. Never derive a name from an email address, username, or handle; to refer to the owner of an email address, use the full address itself. Do not invent or add names, titles, honorifics, or contact details that are not present in the message, and do not comment on the formatting of these values."
31
+
32
+ # ── THE CONTINUITY SENTENCE (Task #7 residual) ──────────────────────────
33
+ #
34
+ # Both disclosures above have always told the upstream model, verbatim, "They
35
+ # are stable within this conversation." That is TRUE only on a lane that
36
+ # carries a conversation ledger. This SDK's default tokenise call carries
37
+ # none, so the claim was FALSE ON THE WIRE for every single-message send.
38
+ #
39
+ # The scope is now SELECTED, never asserted. Ruby stores its disclosures as
40
+ # INLINE frozen literals (unlike the Python SDK, which loads byte-locked data
41
+ # files), so the second, message-scoped artifact is DERIVED here — by a
42
+ # substitution that is VERIFIED, not hoped for:
43
+ #
44
+ # 1. {narrow_continuity} raises unless the conversation sentence occurs
45
+ # EXACTLY ONCE. A "narrowing" whose +sub+ silently failed to match — the
46
+ # exact Task #7 defect — is therefore not representable.
47
+ # 2. Every resulting constant is sha256-checked against a recorded lock by
48
+ # {verify_byte_locks!}, which runs AT LOAD.
49
+ #
50
+ # The CONVERSATION-scoped constants are byte-IDENTICAL to what shipped, so
51
+ # the cross-language golden +disclosure_lock+ holds unchanged.
52
+ #
53
+ # NARROWED, NEVER DROPPED, NEVER DEFAULTED WIDE. The model still learns to
54
+ # echo the stand-ins verbatim; it is simply not told something untrue.
55
+ CONTINUITY_SENTENCE = {
56
+ "conversation" => "They are stable within this conversation.",
57
+ "single-message" => "They are stable within this message."
58
+ }.freeze
59
+
60
+ # Substitute the continuity sentence, FAILING LOUD if the source does not
61
+ # contain exactly one occurrence to substitute.
62
+ def self.narrow_continuity(text, scope)
63
+ from = CONTINUITY_SENTENCE.fetch("conversation")
64
+ to = CONTINUITY_SENTENCE.fetch(scope)
65
+ count = text.scan(from).length
66
+ unless count == 1
67
+ raise "disclosure continuity narrowing FAILED: expected exactly 1 occurrence of " \
68
+ "#{from.inspect}, found #{count}. A narrowing that silently fails to match is " \
69
+ "the Task #7 defect and must never ship."
70
+ end
71
+
72
+ text.sub(from, to)
73
+ end
74
+ private_class_method :narrow_continuity
75
+
76
+ # The +clk+ disclosure with the continuity claim NARROWED to this message.
77
+ # len 3049, sha256 770b44de...
78
+ CLK_DISCLOSURE_TEXT_MESSAGE_SCOPED = narrow_continuity(CLK_DISCLOSURE_TEXT,
79
+ "single-message").freeze
80
+
81
+ # The +cloak-angle+ disclosure with the continuity claim NARROWED to this
82
+ # message. len 4207, sha256 a7bfc5e2...
83
+ CLOAK_ANGLE_DISCLOSURE_TEXT_MESSAGE_SCOPED = narrow_continuity(CLOAK_ANGLE_DISCLOSURE_TEXT,
84
+ "single-message").freeze
85
+
86
+ # Every disclosure string this module can emit, by [format][scope].
87
+ DISCLOSURES = {
88
+ "clk" => {
89
+ "conversation" => CLK_DISCLOSURE_TEXT,
90
+ "single-message" => CLK_DISCLOSURE_TEXT_MESSAGE_SCOPED
91
+ },
92
+ "cloak-angle" => {
93
+ "conversation" => CLOAK_ANGLE_DISCLOSURE_TEXT,
94
+ "single-message" => CLOAK_ANGLE_DISCLOSURE_TEXT_MESSAGE_SCOPED
95
+ }
96
+ }.freeze
97
+
98
+ # Flat list of every emittable disclosure — used for the idempotency check,
99
+ # so adding a scope can never leave a variant un-recognised (which would make
100
+ # {with_disclosure} DOUBLE it).
101
+ ALL_DISCLOSURES = DISCLOSURES.values.flat_map(&:values).freeze
102
+
103
+ # sha256 byte-locks for all FOUR artifacts. The two conversation-scoped
104
+ # digests are the cross-language golden +disclosure_lock+ values; the two
105
+ # message-scoped digests are this artifact's own locks, and match the Python
106
+ # SDK's +_disclosure/clk_message.txt+ / +cloak_angle_message.txt+ byte for
107
+ # byte.
108
+ #
109
+ # 2026-07-29: this file already required "digest" and its comments already
110
+ # claimed the strings were "sha256-checked", but NOTHING checked them — the
111
+ # lock was documentation only. It is now enforced at load.
112
+ BYTE_LOCKS = {
113
+ CLK_DISCLOSURE_TEXT =>
114
+ "e7684324ffa21e5e468563bf552ca86911e6f1586aba2c8273e898802e26c939",
115
+ CLOAK_ANGLE_DISCLOSURE_TEXT =>
116
+ "fd4ace75786a8c2e54c8b7f61ae1b7a05b6431338ea7a074964eadeb855b9548",
117
+ CLK_DISCLOSURE_TEXT_MESSAGE_SCOPED =>
118
+ "770b44deee1e3e78ef859b306e722251f7882753c1e4d0e8e4a43e6de5673fa7",
119
+ CLOAK_ANGLE_DISCLOSURE_TEXT_MESSAGE_SCOPED =>
120
+ "a7bfc5e2e2f8023bd7bfba82416efd20b618e70d82ac7d950fac156c90965264"
121
+ }.freeze
122
+
123
+ # Fail LOUD on drift: a wrong byte here is a safety regression (the upstream
124
+ # model mis-handles the markers), so a mismatch must never be tolerated.
125
+ def self.verify_byte_locks!
126
+ BYTE_LOCKS.each do |text, expected|
127
+ actual = Digest::SHA256.hexdigest(text)
128
+ next if actual == expected
129
+
130
+ raise "disclosure byte-lock FAILED: expected sha256 #{expected}, got #{actual}. " \
131
+ "The embedded disclosure text has drifted from the frozen contract."
132
+ end
133
+ true
134
+ end
135
+ verify_byte_locks!
136
+
137
+ # The correct disclosure text for a marker format AND continuity scope.
138
+ # Defaults to +clk+.
139
+ #
140
+ # @param continuity [String] how far the stand-ins in the accompanying body
141
+ # are ACTUALLY stable. Pass +result.surrogate_mode.continuity+ straight off
142
+ # the tokenise result that produced those bytes. This is the parameter that
143
+ # stops the disclosure from lying: a body tokenised without a bindings
144
+ # ledger gets the MESSAGE-scoped text, so the model is never told the
145
+ # stand-ins hold across turns when they do not.
146
+ #
147
+ # It defaults to "conversation" ONLY here, for source compatibility with
148
+ # callers written before the scope existed. The path that actually makes a
149
+ # claim about somebody else's already-tokenised bytes — {with_disclosure} —
150
+ # has NO default and REQUIRES it.
151
+ def self.disclosure_text(format = "clk", continuity: "conversation")
152
+ fmt = format.to_s == "cloak-angle" ? "cloak-angle" : "clk"
153
+ DISCLOSURES.fetch(fmt).fetch(CloakAPI::SurrogateMode.coerce_continuity(continuity))
154
+ end
155
+
156
+ # Best-effort detect which marker format a tokenised sample uses.
157
+ # <<CLOAK:...>> or [TOKEN_..._N] -> 'cloak-angle'
158
+ # [CLK-TAG-...] -> 'clk'
159
+ # (no marker) -> nil
160
+ def self.detect_marker_format(sample)
161
+ return nil unless sample.is_a?(String)
162
+ return "cloak-angle" if sample.match?(/<<CLOAK:[^>]*>>/) || sample.match?(/\[TOKEN_[A-Z]+_\d+\]/)
163
+ return "clk" if sample.match?(/\[CLK-[A-Z]+-[a-z]+\]/)
164
+
165
+ nil
166
+ end
167
+
168
+ # True when +first+ is already one of our disclosure system messages.
169
+ def self.already_disclosed?(first)
170
+ return false unless first.is_a?(Hash)
171
+
172
+ role = first[:role] || first["role"]
173
+ content = first[:content] || first["content"]
174
+ role == "system" && content.is_a?(String) && ALL_DISCLOSURES.include?(content)
175
+ end
176
+
177
+ # Prepend the format-correct cloak-disclosure as a leading +system+ message.
178
+ #
179
+ # Accepts EITHER an OpenAI-shape messages Array OR an Anthropic/OpenAI request
180
+ # BODY Hash (with a +messages+ array and/or a +system+ field). Returns a NEW
181
+ # value; the input is never mutated.
182
+ #
183
+ # IDEMPOTENT (never doubles an existing disclosure) and FAIL-SAFE (returns the
184
+ # input UNCHANGED on any internal error — never throws, never blocks the send).
185
+ # Applied BEFORE the pretokenised MAC so the disclosure is MAC-covered.
186
+ #
187
+ # For a body with a string +system+ the disclosure is merged onto the front of
188
+ # +system+ (message count unchanged); otherwise a leading system message is added.
189
+ #
190
+ # +continuity:+ is a REQUIRED keyword argument — API-shape lock #2. This
191
+ # method takes bytes that SOMEBODY ELSE tokenised and prepends a paragraph
192
+ # making a factual claim about them; it runs no engine and cannot observe the
193
+ # scope itself. Making the parameter optional would therefore mean "defaults
194
+ # to the strongest claim", which is precisely the Task #7 defect. Pass
195
+ # +result.surrogate_mode.continuity+ from the tokenise result that produced
196
+ # the body. Omitting it is an +ArgumentError+ at the call site, not a silent
197
+ # upgrade to the wide claim — and it is raised BEFORE the +rescue+ below, so
198
+ # the fail-safe cannot swallow it.
199
+ #
200
+ # @param input [Array, Hash]
201
+ # @param continuity [String] REQUIRED: 'conversation' | 'single-message'
202
+ # @param format [String] marker format ('clk' | 'cloak-angle'); default 'clk'
203
+ # @param detect_from [String, nil] auto-detect the format from this sample
204
+ def self.with_disclosure(input, continuity:, format: "clk", detect_from: nil)
205
+ fmt = (detect_from && detect_marker_format(detect_from)) || format || "clk"
206
+ text = disclosure_text(fmt, continuity: continuity)
207
+ return input if text.nil? || text.empty?
208
+
209
+ # Case 1: a bare messages array.
210
+ if input.is_a?(Array)
211
+ return input if already_disclosed?(input[0])
212
+
213
+ return [{ "role" => "system", "content" => text }, *input]
214
+ end
215
+
216
+ # Case 2: a request body hash.
217
+ if input.is_a?(Hash)
218
+ body = input.dup
219
+ sys = body[:system] || body["system"]
220
+
221
+ if sys.is_a?(String)
222
+ return input if ALL_DISCLOSURES.any? { |d| sys.start_with?(d) }
223
+
224
+ merged = sys.empty? ? text : "#{text}\n\n#{sys}"
225
+ key = body.key?(:system) ? :system : "system"
226
+ body[key] = merged
227
+ return body
228
+ end
229
+
230
+ msgs = body[:messages] || body["messages"]
231
+ if msgs.is_a?(Array)
232
+ return input if already_disclosed?(msgs[0])
233
+
234
+ key = body.key?(:messages) ? :messages : "messages"
235
+ body[key] = [{ "role" => "system", "content" => text }, *msgs]
236
+ return body
237
+ end
238
+
239
+ # Anthropic body with no string system and no messages: set system.
240
+ unless body.key?(:messages) || body.key?("messages")
241
+ body["system"] = text
242
+ return body
243
+ end
244
+ end
245
+
246
+ input
247
+ rescue StandardError
248
+ # FAIL-SAFE — never block the user's send on a disclosure build failure.
249
+ input
250
+ end
251
+ end
252
+ end