thinkthen 0.2.0-x64-mingw-ucrt

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 (171) hide show
  1. checksums.yaml +7 -0
  2. data/API.md +40 -0
  3. data/LICENSE +21 -0
  4. data/README.md +562 -0
  5. data/THIRD-PARTY-NOTICES/anstream-1.0.0/LICENSE-APACHE +202 -0
  6. data/THIRD-PARTY-NOTICES/anstream-1.0.0/LICENSE-MIT +19 -0
  7. data/THIRD-PARTY-NOTICES/anstyle-1.0.14/LICENSE-APACHE +202 -0
  8. data/THIRD-PARTY-NOTICES/anstyle-1.0.14/LICENSE-MIT +19 -0
  9. data/THIRD-PARTY-NOTICES/anstyle-parse-1.0.0/LICENSE-APACHE +202 -0
  10. data/THIRD-PARTY-NOTICES/anstyle-parse-1.0.0/LICENSE-MIT +19 -0
  11. data/THIRD-PARTY-NOTICES/anstyle-query-1.1.5/LICENSE-APACHE +202 -0
  12. data/THIRD-PARTY-NOTICES/anstyle-query-1.1.5/LICENSE-MIT +19 -0
  13. data/THIRD-PARTY-NOTICES/anstyle-wincon-3.0.11/LICENSE-APACHE +202 -0
  14. data/THIRD-PARTY-NOTICES/anstyle-wincon-3.0.11/LICENSE-MIT +19 -0
  15. data/THIRD-PARTY-NOTICES/base64-0.23.1/LICENSE-APACHE +201 -0
  16. data/THIRD-PARTY-NOTICES/base64-0.23.1/LICENSE-MIT +21 -0
  17. data/THIRD-PARTY-NOTICES/block-buffer-0.10.4/LICENSE-APACHE +201 -0
  18. data/THIRD-PARTY-NOTICES/block-buffer-0.10.4/LICENSE-MIT +25 -0
  19. data/THIRD-PARTY-NOTICES/bytes-1.12.1/LICENSE +25 -0
  20. data/THIRD-PARTY-NOTICES/cfg-if-1.0.5/LICENSE-APACHE +201 -0
  21. data/THIRD-PARTY-NOTICES/cfg-if-1.0.5/LICENSE-MIT +25 -0
  22. data/THIRD-PARTY-NOTICES/clap-4.6.7/LICENSE-APACHE +202 -0
  23. data/THIRD-PARTY-NOTICES/clap-4.6.7/LICENSE-MIT +19 -0
  24. data/THIRD-PARTY-NOTICES/clap_builder-4.6.7/LICENSE-APACHE +202 -0
  25. data/THIRD-PARTY-NOTICES/clap_builder-4.6.7/LICENSE-MIT +19 -0
  26. data/THIRD-PARTY-NOTICES/clap_complete-4.6.11/LICENSE-APACHE +202 -0
  27. data/THIRD-PARTY-NOTICES/clap_complete-4.6.11/LICENSE-MIT +19 -0
  28. data/THIRD-PARTY-NOTICES/clap_lex-1.1.1/LICENSE-APACHE +202 -0
  29. data/THIRD-PARTY-NOTICES/clap_lex-1.1.1/LICENSE-MIT +19 -0
  30. data/THIRD-PARTY-NOTICES/clap_mangen-0.2.33/LICENSE-APACHE +202 -0
  31. data/THIRD-PARTY-NOTICES/clap_mangen-0.2.33/LICENSE-MIT +19 -0
  32. data/THIRD-PARTY-NOTICES/colorchoice-1.0.5/LICENSE-APACHE +202 -0
  33. data/THIRD-PARTY-NOTICES/colorchoice-1.0.5/LICENSE-MIT +19 -0
  34. data/THIRD-PARTY-NOTICES/command-group-5.0.1/COPYRIGHT +29 -0
  35. data/THIRD-PARTY-NOTICES/command-group-5.0.1/LICENSE-APACHE +176 -0
  36. data/THIRD-PARTY-NOTICES/command-group-5.0.1/LICENSE-MIT +23 -0
  37. data/THIRD-PARTY-NOTICES/cpufeatures-0.2.17/LICENSE-APACHE +201 -0
  38. data/THIRD-PARTY-NOTICES/cpufeatures-0.2.17/LICENSE-MIT +25 -0
  39. data/THIRD-PARTY-NOTICES/crc32fast-1.5.3/LICENSE-APACHE +202 -0
  40. data/THIRD-PARTY-NOTICES/crc32fast-1.5.3/LICENSE-MIT +21 -0
  41. data/THIRD-PARTY-NOTICES/crypto-common-0.1.7/LICENSE-APACHE +201 -0
  42. data/THIRD-PARTY-NOTICES/crypto-common-0.1.7/LICENSE-MIT +25 -0
  43. data/THIRD-PARTY-NOTICES/ctrlc-3.5.2/LICENSE-APACHE +201 -0
  44. data/THIRD-PARTY-NOTICES/ctrlc-3.5.2/LICENSE-MIT +23 -0
  45. data/THIRD-PARTY-NOTICES/digest-0.10.7/LICENSE-APACHE +201 -0
  46. data/THIRD-PARTY-NOTICES/digest-0.10.7/LICENSE-MIT +25 -0
  47. data/THIRD-PARTY-NOTICES/dyn-clone-1.0.20/LICENSE-APACHE +176 -0
  48. data/THIRD-PARTY-NOTICES/dyn-clone-1.0.20/LICENSE-MIT +23 -0
  49. data/THIRD-PARTY-NOTICES/equivalent-1.0.3/LICENSE-APACHE +201 -0
  50. data/THIRD-PARTY-NOTICES/equivalent-1.0.3/LICENSE-MIT +25 -0
  51. data/THIRD-PARTY-NOTICES/fastrand-2.5.0/LICENSE-APACHE +201 -0
  52. data/THIRD-PARTY-NOTICES/fastrand-2.5.0/LICENSE-MIT +23 -0
  53. data/THIRD-PARTY-NOTICES/flate2-1.1.10/LICENSE-APACHE +201 -0
  54. data/THIRD-PARTY-NOTICES/flate2-1.1.10/LICENSE-MIT +25 -0
  55. data/THIRD-PARTY-NOTICES/generic-array-0.14.7/LICENSE +21 -0
  56. data/THIRD-PARTY-NOTICES/getrandom-0.2.17/LICENSE-APACHE +201 -0
  57. data/THIRD-PARTY-NOTICES/getrandom-0.2.17/LICENSE-MIT +26 -0
  58. data/THIRD-PARTY-NOTICES/getrandom-0.3.4/LICENSE-APACHE +201 -0
  59. data/THIRD-PARTY-NOTICES/getrandom-0.3.4/LICENSE-MIT +26 -0
  60. data/THIRD-PARTY-NOTICES/getrandom-0.4.3/LICENSE-APACHE +201 -0
  61. data/THIRD-PARTY-NOTICES/getrandom-0.4.3/LICENSE-MIT +26 -0
  62. data/THIRD-PARTY-NOTICES/hashbrown-0.17.1/LICENSE-APACHE +201 -0
  63. data/THIRD-PARTY-NOTICES/hashbrown-0.17.1/LICENSE-MIT +25 -0
  64. data/THIRD-PARTY-NOTICES/http-1.5.0/LICENSE-APACHE +201 -0
  65. data/THIRD-PARTY-NOTICES/http-1.5.0/LICENSE-MIT +25 -0
  66. data/THIRD-PARTY-NOTICES/httparse-1.10.1/LICENSE-APACHE +201 -0
  67. data/THIRD-PARTY-NOTICES/httparse-1.10.1/LICENSE-MIT +20 -0
  68. data/THIRD-PARTY-NOTICES/httpdate-1.0.3/LICENSE-APACHE +201 -0
  69. data/THIRD-PARTY-NOTICES/httpdate-1.0.3/LICENSE-MIT +19 -0
  70. data/THIRD-PARTY-NOTICES/index.json +605 -0
  71. data/THIRD-PARTY-NOTICES/indexmap-2.14.2/LICENSE-APACHE +201 -0
  72. data/THIRD-PARTY-NOTICES/indexmap-2.14.2/LICENSE-MIT +25 -0
  73. data/THIRD-PARTY-NOTICES/is_terminal_polyfill-1.70.2/LICENSE-APACHE +202 -0
  74. data/THIRD-PARTY-NOTICES/is_terminal_polyfill-1.70.2/LICENSE-MIT +19 -0
  75. data/THIRD-PARTY-NOTICES/itoa-1.0.18/LICENSE-APACHE +176 -0
  76. data/THIRD-PARTY-NOTICES/itoa-1.0.18/LICENSE-MIT +23 -0
  77. data/THIRD-PARTY-NOTICES/log-0.4.34/LICENSE-APACHE +201 -0
  78. data/THIRD-PARTY-NOTICES/log-0.4.34/LICENSE-MIT +25 -0
  79. data/THIRD-PARTY-NOTICES/memchr-2.8.3/COPYING +3 -0
  80. data/THIRD-PARTY-NOTICES/memchr-2.8.3/LICENSE-MIT +21 -0
  81. data/THIRD-PARTY-NOTICES/once_cell-1.21.4/LICENSE-APACHE +201 -0
  82. data/THIRD-PARTY-NOTICES/once_cell-1.21.4/LICENSE-MIT +23 -0
  83. data/THIRD-PARTY-NOTICES/once_cell_polyfill-1.70.2/LICENSE-APACHE +202 -0
  84. data/THIRD-PARTY-NOTICES/once_cell_polyfill-1.70.2/LICENSE-MIT +19 -0
  85. data/THIRD-PARTY-NOTICES/percent-encoding-2.3.2/LICENSE-APACHE +201 -0
  86. data/THIRD-PARTY-NOTICES/percent-encoding-2.3.2/LICENSE-MIT +25 -0
  87. data/THIRD-PARTY-NOTICES/quick-xml-0.41.0/LICENSE-MIT.md +23 -0
  88. data/THIRD-PARTY-NOTICES/ref-cast-1.0.27/LICENSE-APACHE +176 -0
  89. data/THIRD-PARTY-NOTICES/ref-cast-1.0.27/LICENSE-MIT +23 -0
  90. data/THIRD-PARTY-NOTICES/ring-0.17.14/LICENSE +9 -0
  91. data/THIRD-PARTY-NOTICES/ring-0.17.14/LICENSE-BoringSSL +272 -0
  92. data/THIRD-PARTY-NOTICES/ring-0.17.14/LICENSE-other-bits +13 -0
  93. data/THIRD-PARTY-NOTICES/ring-0.17.14/src/polyfill/once_cell/LICENSE-APACHE +201 -0
  94. data/THIRD-PARTY-NOTICES/ring-0.17.14/src/polyfill/once_cell/LICENSE-MIT +23 -0
  95. data/THIRD-PARTY-NOTICES/ring-0.17.14/third_party/fiat/LICENSE +15 -0
  96. data/THIRD-PARTY-NOTICES/roff-1.1.1/LICENSE-APACHE +202 -0
  97. data/THIRD-PARTY-NOTICES/roff-1.1.1/LICENSE-MIT +19 -0
  98. data/THIRD-PARTY-NOTICES/rustls-0.23.46/LICENSE-APACHE +201 -0
  99. data/THIRD-PARTY-NOTICES/rustls-0.23.46/LICENSE-ISC +15 -0
  100. data/THIRD-PARTY-NOTICES/rustls-0.23.46/LICENSE-MIT +25 -0
  101. data/THIRD-PARTY-NOTICES/rustls-pki-types-1.15.1/LICENSE-APACHE +201 -0
  102. data/THIRD-PARTY-NOTICES/rustls-pki-types-1.15.1/LICENSE-MIT +25 -0
  103. data/THIRD-PARTY-NOTICES/rustls-platform-verifier-0.7.1/LICENSE-APACHE +201 -0
  104. data/THIRD-PARTY-NOTICES/rustls-platform-verifier-0.7.1/LICENSE-MIT +21 -0
  105. data/THIRD-PARTY-NOTICES/rustls-webpki-0.103.16/LICENSE +19 -0
  106. data/THIRD-PARTY-NOTICES/schemars-1.2.3/LICENSE +21 -0
  107. data/THIRD-PARTY-NOTICES/serde-1.0.229/LICENSE-APACHE +176 -0
  108. data/THIRD-PARTY-NOTICES/serde-1.0.229/LICENSE-MIT +23 -0
  109. data/THIRD-PARTY-NOTICES/serde_core-1.0.229/LICENSE-APACHE +176 -0
  110. data/THIRD-PARTY-NOTICES/serde_core-1.0.229/LICENSE-MIT +23 -0
  111. data/THIRD-PARTY-NOTICES/serde_json-1.0.151/LICENSE-APACHE +176 -0
  112. data/THIRD-PARTY-NOTICES/serde_json-1.0.151/LICENSE-MIT +23 -0
  113. data/THIRD-PARTY-NOTICES/sha2-0.10.9/LICENSE-APACHE +201 -0
  114. data/THIRD-PARTY-NOTICES/sha2-0.10.9/LICENSE-MIT +27 -0
  115. data/THIRD-PARTY-NOTICES/strsim-0.11.1/LICENSE +23 -0
  116. data/THIRD-PARTY-NOTICES/subtle-2.6.1/LICENSE +29 -0
  117. data/THIRD-PARTY-NOTICES/tempfile-3.23.0/LICENSE-APACHE +201 -0
  118. data/THIRD-PARTY-NOTICES/tempfile-3.23.0/LICENSE-MIT +25 -0
  119. data/THIRD-PARTY-NOTICES/thiserror-2.0.21/LICENSE-APACHE +176 -0
  120. data/THIRD-PARTY-NOTICES/thiserror-2.0.21/LICENSE-MIT +23 -0
  121. data/THIRD-PARTY-NOTICES/tinyvec-1.13.3/LICENSE-APACHE.md +202 -0
  122. data/THIRD-PARTY-NOTICES/tinyvec-1.13.3/LICENSE-MIT.md +5 -0
  123. data/THIRD-PARTY-NOTICES/tinyvec-1.13.3/LICENSE-ZLIB.md +11 -0
  124. data/THIRD-PARTY-NOTICES/typed-path-0.13.0/LICENSE-APACHE +176 -0
  125. data/THIRD-PARTY-NOTICES/typed-path-0.13.0/LICENSE-MIT +23 -0
  126. data/THIRD-PARTY-NOTICES/typenum-1.20.1/LICENSE +1 -0
  127. data/THIRD-PARTY-NOTICES/typenum-1.20.1/LICENSE-APACHE +201 -0
  128. data/THIRD-PARTY-NOTICES/typenum-1.20.1/LICENSE-MIT +21 -0
  129. data/THIRD-PARTY-NOTICES/unicode-general-category-1.1.0/LICENSE +201 -0
  130. data/THIRD-PARTY-NOTICES/unicode-normalization-0.1.26/COPYRIGHT +7 -0
  131. data/THIRD-PARTY-NOTICES/unicode-normalization-0.1.26/LICENSE-APACHE +201 -0
  132. data/THIRD-PARTY-NOTICES/unicode-normalization-0.1.26/LICENSE-MIT +25 -0
  133. data/THIRD-PARTY-NOTICES/unicode-normalization-0.1.26/LICENSE-UNICODE +39 -0
  134. data/THIRD-PARTY-NOTICES/untrusted-0.9.0/LICENSE.txt +13 -0
  135. data/THIRD-PARTY-NOTICES/ureq-3.4.2/LICENSE-APACHE +201 -0
  136. data/THIRD-PARTY-NOTICES/ureq-3.4.2/LICENSE-MIT +21 -0
  137. data/THIRD-PARTY-NOTICES/ureq-proto-0.6.4/LICENSE-APACHE.txt +202 -0
  138. data/THIRD-PARTY-NOTICES/ureq-proto-0.6.4/LICENSE-MIT.txt +7 -0
  139. data/THIRD-PARTY-NOTICES/utf8-zero-0.8.1/LICENSE-APACHE +176 -0
  140. data/THIRD-PARTY-NOTICES/utf8-zero-0.8.1/LICENSE-MIT +23 -0
  141. data/THIRD-PARTY-NOTICES/utf8parse-0.2.2/LICENSE-APACHE +176 -0
  142. data/THIRD-PARTY-NOTICES/utf8parse-0.2.2/LICENSE-MIT +25 -0
  143. data/THIRD-PARTY-NOTICES/winapi-0.3.9/LICENSE-APACHE +201 -0
  144. data/THIRD-PARTY-NOTICES/winapi-0.3.9/LICENSE-MIT +19 -0
  145. data/THIRD-PARTY-NOTICES/windows-link-0.2.1/license-apache-2.0 +201 -0
  146. data/THIRD-PARTY-NOTICES/windows-link-0.2.1/license-mit +21 -0
  147. data/THIRD-PARTY-NOTICES/windows-sys-0.61.2/license-apache-2.0 +201 -0
  148. data/THIRD-PARTY-NOTICES/windows-sys-0.61.2/license-mit +21 -0
  149. data/THIRD-PARTY-NOTICES/zeroize-1.9.0/LICENSE-APACHE +202 -0
  150. data/THIRD-PARTY-NOTICES/zeroize-1.9.0/LICENSE-MIT +25 -0
  151. data/THIRD-PARTY-NOTICES/zip-9.1.2/LICENSE +21 -0
  152. data/THIRD-PARTY-NOTICES/zlib-rs-0.6.8/LICENSE +19 -0
  153. data/THIRD-PARTY-NOTICES/zmij-1.0.23/LICENSE-MIT +23 -0
  154. data/lib/thinkthen/call_owner.rb +68 -0
  155. data/lib/thinkthen/client.rb +293 -0
  156. data/lib/thinkthen/configuration.rb +76 -0
  157. data/lib/thinkthen/contract.rb +89 -0
  158. data/lib/thinkthen/native.rb +350 -0
  159. data/lib/thinkthen/native_allocator.rb +35 -0
  160. data/lib/thinkthen/native_reader.rb +87 -0
  161. data/lib/thinkthen/questions.rb +184 -0
  162. data/lib/thinkthen/row.rb +173 -0
  163. data/lib/thinkthen/rows.rb +199 -0
  164. data/lib/thinkthen/thinkthen_ffi.dll +0 -0
  165. data/lib/thinkthen/values.rb +111 -0
  166. data/lib/thinkthen/version.rb +5 -0
  167. data/lib/thinkthen.rb +105 -0
  168. data/sig/error_codes.rbs +3 -0
  169. data/sig/internal.rbs +277 -0
  170. data/sig/thinkthen.rbs +440 -0
  171. metadata +231 -0
@@ -0,0 +1,173 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ThinkThen
4
+ # A result owns its immutable value; item remains the caller's own object.
5
+ class Result
6
+ undef_method :<=>
7
+ attr_reader :function, :status, :probability, :error, :position, :id, :source, :detail, :item
8
+
9
+ def initialize(fields, question: nil, item: nil, parent: nil, raw_code: nil)
10
+ if parent
11
+ fields = fields.merge("position" => parent.position, "source" => parent.source.to_h)
12
+ fields = fields.merge("id" => parent.id) if parent.id_present?
13
+ end
14
+ @wire = Values.freeze_copy(fields)
15
+ @function, @status = fields.fetch("function").to_sym, fields.fetch("status").to_sym
16
+ @position, @id, @item = parent ? [parent.position, parent.id, parent.item] : [fields["position"], Values.freeze_copy(fields["id"]), item]
17
+ @source = parent ? parent.source : Row.value(Source, fields.fetch("source"))
18
+ @probability = fields["probability"]
19
+ @error = fields["error"] && Row.row_error(fields["error"], raw_code: raw_code)
20
+ @detail = Row.detail(fields.fetch("function"), fields["detail"])
21
+ @answer = answered? ? Row.answer(fields.fetch("function"), fields["answer"], question, self) : nil
22
+ @value = [function, status, @answer, probability, Values.freeze_copy(@error&.to_h), position, id, source, detail].freeze
23
+ freeze
24
+ end
25
+ private_class_method :new
26
+
27
+ def answered? = status == :answered
28
+ def unsure? = status == :unsure
29
+ def failed? = status == :failed
30
+ def id_present? = @wire.key?("id")
31
+
32
+ def answer
33
+ raise UnsureError.new(self) if unsure?
34
+ raise_failure(self) if failed?
35
+ @answer
36
+ end
37
+
38
+ def raise_if_failed
39
+ failed = failed? ? self : function == :annotate && @answer&.each_value&.find(&:failed?)
40
+ raise_failure(failed) if failed
41
+ self
42
+ end
43
+
44
+ def ==(other)
45
+ raise TypeError, "compare the result's .answer" unless other.is_a?(Result)
46
+ eql?(other)
47
+ end
48
+ def eql?(other) = other.is_a?(Result) && @value.eql?(other.instance_variable_get(:@value))
49
+ def hash = @value.hash
50
+ def to_h = Values.wire(@wire)
51
+ def to_json(*_args) = JSON.generate(@wire)
52
+ def to_s = Row.text(self, @answer)
53
+ def inspect = "#<#{self.class.name} #{to_s}>"
54
+
55
+ private
56
+
57
+ def raise_failure(row)
58
+ # Native failed outcomes carry an error; the public getter remains optional.
59
+ # @type var failure: untyped
60
+ failure = row.error
61
+ raise FailedError.new(failure.message, code: failure.code, http_status: failure.http_status, rows: [row])
62
+ end
63
+ end
64
+
65
+ class DecideRow < Result
66
+ def yes? = answer
67
+ end
68
+ class ChooseRow < Result; end
69
+ class TagRow < Result; end
70
+ class ScoreRow < Result; end
71
+ class RankRow < Result; end
72
+ class FindRow < Result; end
73
+ class RecognizeRow < Result; end
74
+ class RelateRow < Result; end
75
+ class AnnotateRow < Result; end
76
+
77
+ # Symbols and strings address the same canonical question name, loudly.
78
+ class AnnotationAnswers < Hash
79
+ def [](name) = fetch(name)
80
+ def fetch(name) = super(name.to_s)
81
+ end
82
+
83
+ module Row
84
+ def self.decode(native, question: nil, item: nil)
85
+ variant(Native.parse(Native.row_json(native)), question: question, item: item, raw_code: native[:error_code])
86
+ end
87
+
88
+ def self.variant(fields, question: nil, item: nil, parent: nil, raw_code: nil)
89
+ function = fields.fetch("function")
90
+ klass = function == "filter" ? Result : ThinkThen.const_get("#{function.capitalize}Row")
91
+ klass.send(:new, fields, question: question, item: item, parent: parent, raw_code: raw_code)
92
+ end
93
+
94
+ def self.value(klass, fields)
95
+ # @type var values: Hash[Symbol, untyped]
96
+ values = klass.members.to_h { |key| [key, Values.freeze_copy(fields[key.to_s])] }
97
+ klass.new(**values)
98
+ end
99
+
100
+ def self.row_error(fields, raw_code: nil)
101
+ name = fields.fetch("code")
102
+ known = NativeContract::CODE_NAMES.value?(name)
103
+ RowError.new(code: known ? Native.error_symbol(name) : :unknown, message: Values.freeze_copy(fields.fetch("message")),
104
+ http_status: fields["http_status"], raw_code: known ? fields["raw_code"] : raw_code || fields["raw_code"],
105
+ raw_name: fields["raw_name"] || (known ? nil : name)).freeze
106
+ end
107
+
108
+ def self.relation(fields)
109
+ value(Relation, fields.merge("either" => fields.fetch("either", false), "source" => value(RelationName, fields.fetch("source")),
110
+ "target" => value(RelationName, fields.fetch("target"))))
111
+ end
112
+
113
+ def self.answer(function, fields, question, parent)
114
+ case function
115
+ when "find" then fields && value(Span, fields)
116
+ when "recognize" then fields.map { |entry| value(Name, entry) }.freeze
117
+ when "relate" then fields.map { |entry| relation(entry) }.freeze
118
+ when "annotate"
119
+ # @type var questions: Hash[String, untyped]
120
+ questions = question.is_a?(AnnotateQuestion) ? question.questions : {}
121
+ AnnotationAnswers[fields.to_h { |name, entry| [name, variant(entry, question: questions[name], parent: parent)] }].freeze
122
+ when "choose" then question&.symbols? ? fields.to_sym : Values.freeze_copy(fields)
123
+ when "tag" then fields.map { |entry| question&.symbols? ? entry.to_sym : Values.freeze_copy(entry) }.freeze
124
+ when "score" then fields.to_f
125
+ else Values.freeze_copy(fields)
126
+ end
127
+ end
128
+
129
+ def self.detail(function, fields)
130
+ return nil unless fields
131
+ case function
132
+ when "choose", "tag" then value(LabelDetail, fields)
133
+ when "score", "rank" then value(LevelDetail, fields)
134
+ when "relate"
135
+ RelationDetail.new(names: fields.fetch("names").map { |entry| value(Name, entry) }.freeze,
136
+ pairs: fields.fetch("pairs").map { |entry| relation(entry) }.freeze)
137
+ when "recognize"
138
+ RecognizeDetail.new(pieces: fields.fetch("pieces").map { |entry| value(PieceDetail, entry) }.freeze,
139
+ names: fields.fetch("names").map { |entry| value(KindDetail, entry) }.freeze)
140
+ end
141
+ end
142
+
143
+ def self.number(value)
144
+ parts = value.to_s.split("e")
145
+ mantissa, exponent = parts.fetch(0), parts[1]
146
+ return mantissa.sub(/\.0\z/, "") unless exponent
147
+ "0." + "0" * (-exponent.to_i - 1) + mantissa.delete(".").sub(/0+\z/, "")
148
+ end
149
+
150
+ # Fold only string leaves. The tabs joining labels/entries remain separators.
151
+ def self.leaf(value) = value.to_s.tr("\r\n\t", " ")
152
+ def self.text(row, answer)
153
+ return "unsure" if row.unsure?
154
+ if row.failed?
155
+ # @type var failure: untyped
156
+ failure = row.error
157
+ return "failed: #{leaf(failure.raw_name || failure.code)}: #{leaf(failure.message)}"
158
+ end
159
+ case row.function
160
+ when :decide, :filter then answer ? "true" : "false"
161
+ when :choose then leaf(answer)
162
+ when :tag then answer.map { |label| leaf(label) }.join("\t")
163
+ when :score then number(answer)
164
+ when :rank then answer.to_s
165
+ when :find then answer ? leaf(answer.text) : ""
166
+ when :recognize then answer.map { |name| "#{leaf(name.kind)}: #{leaf(name.text)} (#{name.start}..#{name.end})" }.join("\t")
167
+ when :relate then answer.map { |entry| "#{leaf(entry.source.text)} --#{leaf(entry.relation)}--> #{leaf(entry.target.text)}" }.join("\t")
168
+ when :annotate then answer.map { |name, entry| "#{leaf(name)}=#{entry}" }.join("\t")
169
+ end
170
+ end
171
+ end
172
+ private_constant :Row, :Values, :WireValue, :AnnotationAnswers, :NativeContract
173
+ end
@@ -0,0 +1,199 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ThinkThen
4
+ # A single-pass Enumerable of native outcomes. Close it when external iteration stops early.
5
+ class Rows < Enumerator
6
+
7
+ def initialize(client, request, records, cancel, question)
8
+ @client, @question, @items, @position = client, question, {}, 0
9
+ initial = records.is_a?(Array) ? Array.new(records) : nil
10
+ @initial = initial
11
+ @owner = CallOwner.new(client.send(:admit, request, initial))
12
+ @cancel = cancel
13
+ @cancel&.attach(@owner)
14
+ # @type var input: untyped
15
+ input = initial ? [] : records
16
+ @records = input.to_enum(:each)
17
+ @reader = nil
18
+ @driver = Mutex.new
19
+ @traversal = Mutex.new
20
+ @traversing = false
21
+ # Steep crashes on super with this native Enumerator constructor block.
22
+ # Only the core initializer crosses this boundary; produce stays checked.
23
+ # @type var initializer: untyped
24
+ initializer = Enumerator.instance_method(:initialize)
25
+ initializer.bind_call(self, initial ? initial.size : records.respond_to?(:size) ? records.size : nil) { |yielder| produce(yielder) }
26
+ # The block above captures this scope; drop the admitted copy it no longer needs.
27
+ initial = nil
28
+ rescue Exception
29
+ close if @owner
30
+ raise
31
+ end
32
+
33
+ def each
34
+ return self unless block_given?
35
+ entered = false
36
+ begin
37
+ @traversal.synchronize do
38
+ raise ThreadError, "call already has an active driver" if @traversing
39
+ @traversing = entered = true
40
+ end
41
+ super { |row| yield row }
42
+ ensure
43
+ if entered
44
+ begin
45
+ close
46
+ ensure
47
+ @traversal.synchronize { @traversing = false }
48
+ end
49
+ end
50
+ end
51
+ end
52
+
53
+ def cancel
54
+ @client.send(:check_process)
55
+ @owner.cancel
56
+ end
57
+ def close
58
+ @client.send(:check_process)
59
+ @owner.close
60
+ @cancel&.detach(@owner)
61
+ release
62
+ @client.send(:forget, self)
63
+ nil
64
+ end
65
+ def closed? = @owner.closed?
66
+
67
+ def rewind
68
+ raise IOError, "calls cannot be rewound"
69
+ end
70
+
71
+ private
72
+
73
+ def produce(yielder)
74
+ begin
75
+ while true
76
+ row = begin
77
+ pull
78
+ rescue StopIteration
79
+ break
80
+ end
81
+ yielder << row
82
+ end
83
+ ensure
84
+ close
85
+ end
86
+ end
87
+
88
+ def pull
89
+ @client.send(:check_process)
90
+ unless @driver.try_lock
91
+ raise ThreadError, "call already has an active driver"
92
+ end
93
+ begin
94
+ # Thread#kill is not an Exception, so only Object holds it back here.
95
+ Thread.handle_interrupt(Object => :never) do
96
+ begin
97
+ drive
98
+ rescue Interrupt => interruption
99
+ @owner.cancel
100
+ begin
101
+ Native.checked { |error| Native.thinkthen_cancelled_error(error) }
102
+ rescue CancelledError => error
103
+ raise error, cause: interruption
104
+ end
105
+ end
106
+ end
107
+ ensure
108
+ @driver.unlock
109
+ release if @owner.closed?
110
+ end
111
+ end
112
+
113
+ # A driver held in caller input must not hold up close, so it releases on its way out.
114
+ def release
115
+ return unless @driver&.try_lock
116
+ begin
117
+ @reader&.close
118
+ @reader = nil
119
+ @initial = nil
120
+ @items.clear
121
+ @records = nil
122
+ ensure
123
+ @driver.unlock
124
+ end
125
+ end
126
+
127
+ def drive
128
+ while true
129
+ native = Native::Row.new
130
+ begin
131
+ status = blocking_next(native)
132
+ if status == 0
133
+ position = native[:position]
134
+ item = @initial ? @initial[position - 1] : @items.delete(position)
135
+ return Row.decode(native, question: @question, item: item)
136
+ end
137
+ raise StopIteration if status == 1
138
+ ensure
139
+ Native.thinkthen_row_free(native)
140
+ end
141
+ supply_input
142
+ end
143
+ end
144
+
145
+ # Ruby can interrupt a thread wait; FFI cannot interrupt a foreign call.
146
+ # Cancel before joining, then release row memory after the foreign call ends.
147
+ def blocking_next(native)
148
+ @reader ||= NativeReader.new(@owner)
149
+ read = @reader.start(native)
150
+ finished = false
151
+ begin
152
+ status = Thread.handle_interrupt(Object => :immediate) { read.value }
153
+ finished = true
154
+ status
155
+ ensure
156
+ begin
157
+ # Thread#kill runs ensure blocks but no rescue, so cancel here.
158
+ @owner.cancel unless finished
159
+ ensure
160
+ # Keep the row pinned until the native operation has stopped.
161
+ read.value rescue nil
162
+ end
163
+ end
164
+ end
165
+
166
+ def supply_input
167
+ record = begin
168
+ # Caller input may block in Ruby; native storage stays protected outside it.
169
+ Thread.handle_interrupt(Object => :immediate) { @records.next }
170
+ rescue StopIteration
171
+ @owner.use { |pointer| Native.thinkthen_call_end_input(pointer) }
172
+ return
173
+ end
174
+ @position += 1
175
+ @items[@position] = record
176
+ kind, value = Native.record_value(record)
177
+ if value.nil?
178
+ @owner.use do |pointer|
179
+ Native.checked do |error|
180
+ kind == "missing" ? Native.thinkthen_call_send_missing(pointer, error) : Native.thinkthen_call_send_invalid(pointer, error)
181
+ end
182
+ end
183
+ return
184
+ end
185
+ text = kind == "text"
186
+ Native.bytes(value) do |bytes, length|
187
+ @owner.use do |pointer|
188
+ Native.checked do |error|
189
+ if text
190
+ Native.thinkthen_call_send_text(pointer, bytes, length, error)
191
+ else
192
+ Native.thinkthen_call_send_json(pointer, bytes, length, error)
193
+ end
194
+ end
195
+ end
196
+ end
197
+ end
198
+ end
199
+ end
Binary file
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ThinkThen
4
+ module Values
5
+ def self.freeze_copy(value)
6
+ case value
7
+ when String then String.new(value).freeze
8
+ when Array then Array.new(value).map { |entry| freeze_copy(entry) }.freeze
9
+ when Hash then value.to_h { |key, entry| [freeze_copy(key), freeze_copy(entry)] }.freeze
10
+ else value
11
+ end
12
+ end
13
+ def self.wire(value)
14
+ case value
15
+ when Data, RowError then value.to_h
16
+ when Symbol then value.to_s
17
+ when Array then value.map { |entry| wire(entry) }
18
+ when Hash then value.to_h { |key, entry| [key.to_s, wire(entry)] }
19
+ else value
20
+ end
21
+ end
22
+ end
23
+ module WireValue
24
+ # Serialize the contract value, including when JSON.generate calls this method.
25
+ def to_json(*_args) = JSON.generate(to_h)
26
+ def to_h
27
+ # @type var klass: untyped
28
+ klass = self.class
29
+ klass.members.to_h { |key| [key.to_s, Values.wire(public_send(key))] }.reject { |_, value| value.nil? }
30
+ end
31
+ end
32
+ # Provider-reported token sum (nil on overflow), with finished unknown attempts.
33
+ TokenUsage = Data.define(:reported, :unknown_attempts)
34
+ # An immutable copied cumulative client snapshot, independent of native ownership.
35
+ Usage = Data.define(:attempts, :responses, :status_retries, :connection_retries,
36
+ :request_body_bytes, :active_attempts, :active_calls, :input_tokens, :output_tokens)
37
+ # The question identity, backend, model and optional execution name.
38
+ Source = Data.define(:question_identity, :backend, :model, :name)
39
+ class Source
40
+ include WireValue
41
+ def initialize(question_identity:, backend:, model:, name: nil)
42
+ super(question_identity: question_identity, backend: backend.to_sym, model: model, name: name)
43
+ end
44
+ end
45
+ # A record failure can be inspected as a value or raised as an exception.
46
+ class RowError < FailedError
47
+ attr_reader :raw_code, :raw_name
48
+ def initialize(code:, message:, http_status: nil, raw_code: nil, raw_name: nil)
49
+ @raw_code, @raw_name = raw_code, Values.freeze_copy(raw_name)
50
+ super(message, code: code, http_status: http_status)
51
+ end
52
+ def to_h
53
+ {"code" => code.to_s, "message" => message, "http_status" => http_status,
54
+ "raw_code" => raw_code, "raw_name" => raw_name}.reject { |_, value| value.nil? }
55
+ end
56
+ def to_json(*_args) = JSON.generate(to_h)
57
+ end
58
+ # A named source/target relationship and its optional phrase.
59
+ RelationRule = Data.define(:source, :target, :relation, :reads, :either)
60
+ class RelationRule
61
+ include WireValue
62
+ def initialize(source:, target:, relation:, reads: nil, either: false)
63
+ super(source: Values.freeze_copy(source), target: Values.freeze_copy(target), relation: Values.freeze_copy(relation),
64
+ reads: Values.freeze_copy(reads), either: either)
65
+ end
66
+ private
67
+ def definition
68
+ {"source" => source, "target" => target, "relation" => relation, "reads" => reads, "either" => either}.reject { |_, value| value.nil? }
69
+ end
70
+ end
71
+ # Retry delays and attempt timeouts are expressed in seconds.
72
+ RetryPolicy = Data.define(:max_retries, :initial_backoff, :attempt_timeout)
73
+ class RetryPolicy
74
+ include WireValue
75
+ def initialize(max_retries: nil, initial_backoff: nil, attempt_timeout: nil)
76
+ super
77
+ end
78
+ def to_h
79
+ {"max_retries" => max_retries, "initial_backoff_ms" => initial_backoff && (initial_backoff * 1000).round,
80
+ "attempt_timeout_ms" => attempt_timeout && (attempt_timeout * 1000).round}.reject { |_, value| value.nil? }
81
+ end
82
+ end
83
+ # Per-label probabilities for choose and tag answers.
84
+ LabelDetail = Data.define(:labels) { include WireValue }
85
+ # Per-level probabilities for score and rank answers.
86
+ LevelDetail = Data.define(:levels) { include WireValue }
87
+ # Matched text and zero-based character offsets.
88
+ Span = Data.define(:text, :start, :end) { include WireValue }
89
+ # Recognized text, character offsets, kind and probability.
90
+ Name = Data.define(:kind, :text, :start, :end, :probability) { include WireValue }
91
+ # An endpoint name, its character offsets and its kind.
92
+ RelationName = Data.define(:kind, :text, :start, :end) { include WireValue }
93
+ # The source and target names, relation probability and symmetry.
94
+ Relation = Data.define(:source, :target, :relation, :probability, :either)
95
+ class Relation
96
+ include WireValue
97
+ def to_h
98
+ result = super
99
+ result.delete("either") unless self.either
100
+ result
101
+ end
102
+ end
103
+ # The recognized names and evaluated relation pairs.
104
+ RelationDetail = Data.define(:names, :pairs) { include WireValue }
105
+ # A text piece, character offsets and tag probabilities.
106
+ PieceDetail = Data.define(:text, :start, :end, :tags) { include WireValue }
107
+ # Name text, character offsets and kind probabilities.
108
+ KindDetail = Data.define(:text, :start, :end, :kinds) { include WireValue }
109
+ # The text pieces and recognized name details.
110
+ RecognizeDetail = Data.define(:pieces, :names) { include WireValue }
111
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ThinkThen
4
+ VERSION = "0.2.0"
5
+ end
data/lib/thinkthen.rb ADDED
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "ffi"
5
+ require "weakref"
6
+ require_relative "thinkthen/version"
7
+ require_relative "thinkthen/contract"
8
+
9
+ module ThinkThen
10
+ UNSET = Object.new.freeze
11
+ private_constant :UNSET
12
+ # Rescue every engine and binding error through this shared family.
13
+ module Error
14
+ attr_reader :code, :http_status
15
+ def initialize(message = nil, code:, http_status: nil)
16
+ @code, @http_status = code.to_sym, http_status
17
+ super(message)
18
+ end
19
+ end
20
+ class LibraryError < StandardError
21
+ include Error
22
+ end
23
+ private_constant :LibraryError
24
+ class UnknownCodeError < LibraryError
25
+ attr_reader :raw_code, :raw_name
26
+ def initialize(message = nil, raw_code:, raw_name: nil, http_status: nil)
27
+ @raw_code, @raw_name = raw_code, raw_name&.dup&.freeze
28
+ super(message, code: :unknown, http_status: http_status)
29
+ end
30
+ end
31
+ # An invalid call; also an ArgumentError for normal Ruby argument handling.
32
+ class UsageError < ArgumentError
33
+ include Error
34
+ end
35
+ # The engine could not start or a remote call was refused.
36
+ class SetupError < LibraryError; end
37
+ # A cancelled native call, including a Ruby interrupt during native work.
38
+ class CancelledError < LibraryError; end
39
+ # An unexpected native engine failure.
40
+ class InternalError < LibraryError; end
41
+
42
+ # Rescue either missing-answer outcome without treating uncertainty as failure.
43
+ module NoAnswerError; end
44
+
45
+ # A probability band did not select a definite answer.
46
+ class UnsureError < StandardError
47
+ include NoAnswerError
48
+ attr_reader :probability, :row
49
+ def initialize(row)
50
+ @row, @probability = row, row.probability
51
+ super("the answer is not sure")
52
+ end
53
+ end
54
+ # Failed input rows, retained in input order after the kept records.
55
+ class FailedError < LibraryError
56
+ include NoAnswerError
57
+ attr_reader :rows
58
+ def initialize(message = nil, code:, http_status: nil, rows: [])
59
+ @rows = rows.freeze
60
+ super(message, code: code, http_status: http_status)
61
+ end
62
+ end
63
+
64
+ def self.native
65
+ raise @native_error if @native_error
66
+ require_relative "thinkthen/native"
67
+ private_constant :Native
68
+ Native
69
+ rescue UsageError => error
70
+ @native_error = error
71
+ raise
72
+ end
73
+ private_class_method :native
74
+
75
+ # Cancel any attached calls without closing their client.
76
+ class Cancel
77
+ def initialize
78
+ @mutex, @cancelled, @calls = Mutex.new, false, []
79
+ end
80
+ def cancel
81
+ @mutex.synchronize do
82
+ @cancelled = true
83
+ @calls.each { |reference| reference.__getobj__.cancel if reference.weakref_alive? }
84
+ end
85
+ nil
86
+ end
87
+ def cancelled? = @mutex.synchronize { @cancelled }
88
+ def attach(owner)
89
+ @mutex.synchronize do
90
+ @calls.reject! { |reference| !reference.weakref_alive? }
91
+ @calls << WeakRef.new(owner)
92
+ owner.cancel if @cancelled
93
+ end
94
+ end
95
+ def detach(owner) = @mutex.synchronize { @calls.reject! { |reference| !reference.weakref_alive? || reference.__getobj__.equal?(owner) } }
96
+ end
97
+ end
98
+ require_relative "thinkthen/values"
99
+ require_relative "thinkthen/questions"
100
+ require_relative "thinkthen/row"
101
+ require_relative "thinkthen/call_owner"
102
+ require_relative "thinkthen/native_reader"
103
+ require_relative "thinkthen/rows"
104
+ require_relative "thinkthen/client"
105
+ require_relative "thinkthen/configuration"
@@ -0,0 +1,3 @@
1
+ module ThinkThen
2
+ type error_code = :"usage.threshold" | :"usage.question" | :"usage.name" | :"usage.settings" | :"usage.backend" | :"usage.url" | :"usage.key-missing" | :"usage.batch" | :"usage.pointer" | :"usage.sql-policy" | :"usage.sql-selection" | :"usage.abi" | :"usage.closed" | :"usage.function" | :"usage.record-kind" | :"usage.offsets" | :"usage.argument" | :"usage.option" | :"usage.column" | :"usage.sheet" | :"usage.output" | :"usage.table" | :"record.json" | :"record.missing" | :"record.too-large" | :"record.invalid" | :"record.empty" | :"backend.transport" | :"backend.status" | :"backend.reply" | :"local.cancelled" | :"local.io" | :"local.toolbox" | :"local.accounting" | :"local.request-limit" | :"internal.bug" | :unknown
3
+ end