placecontext 0.2.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 (5) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +28 -0
  3. data/README.md +5 -0
  4. data/lib/placecontext.rb +318 -0
  5. metadata +47 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 32f30fc70fcc8f7e4854420191dd614d8a41e23da4e92474204bdcf643f7a891
4
+ data.tar.gz: 5fa524e692b528874a650bd050299dc251c62226aab6c02982ee21d1e778b6a4
5
+ SHA512:
6
+ metadata.gz: 594de6844daea77d615140986be044867d6d6ea0b69aee8561700ba2c1fd05edca4c82b3f9326518b468acfe0a58eb157be155513bff43a16fd4081824464c0a
7
+ data.tar.gz: 867452d6b1f9ef929b716171808b90a695c9b4ca23aa0cabea5c7b47e40b5da29acfe535ae3819ce39e33dd25983f1654a8adb4adb4f2ac1927ef75302acccfa
data/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Bradley Lietz / CTRL SIGNAL SOFTWARE PTY LTD
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ YOUR DATA AND JOBS
24
+
25
+ The operator of a PlaceContext instance retains ownership of the data, job
26
+ definitions, runs, artifacts, and other content stored or created in that
27
+ instance. This statement does not limit the rights granted by the MIT License
28
+ to the Software itself.
data/README.md ADDED
@@ -0,0 +1,5 @@
1
+ # PlaceContext SDK
2
+
3
+ Declare jobs and human/agent workflow steps in your code. Configure your PlaceContext endpoint, project ID and API key, sync metadata, and run the SDK worker inside your application.
4
+
5
+ See the [SDK guide and examples](https://github.com/bradlnz/placecontext/tree/main/sdks) for configuration, named step routing, string-path invocation and cooperative cancellation. Named routes in version 0.2.0 need a PlaceContext server that accepts SDK manifest version 2; package files can be installed locally before registry publication.
@@ -0,0 +1,318 @@
1
+ require 'json'
2
+ require 'net/http'
3
+ require 'uri'
4
+
5
+ module PlaceContext
6
+ Config = Struct.new(:endpoint, :project_id, :api_key, keyword_init: true) do
7
+ def initialize(endpoint:, project_id:, api_key:)
8
+ base = URI(endpoint)
9
+ unless %w[http https].include?(base.scheme) && base.host && !base.userinfo && !base.query && !base.fragment &&
10
+ /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i.match?(project_id) &&
11
+ project_id != '00000000-0000-0000-0000-000000000000' && !api_key.to_s.empty?
12
+ raise ArgumentError, 'SDK configuration requires an HTTP(S) endpoint, project ID and API key'
13
+ end
14
+ super
15
+ freeze
16
+ end
17
+ end
18
+
19
+ class RequestError < StandardError
20
+ attr_reader :status
21
+ def initialize(response)
22
+ @status = response.code.to_i
23
+ super("PlaceContext request failed (#{response.code}): #{response.body}")
24
+ end
25
+ end
26
+
27
+ class CancellationToken
28
+ def initialize
29
+ @mutex, @wake, @cancelled = Mutex.new, ConditionVariable.new, false
30
+ end
31
+ def cancel
32
+ @mutex.synchronize { @cancelled = true; @wake.broadcast }
33
+ end
34
+ def cancelled?
35
+ @mutex.synchronize { @cancelled }
36
+ end
37
+ def check!
38
+ raise 'SDK invocation cancelled' if cancelled?
39
+ end
40
+ def wait(seconds)
41
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + seconds
42
+ @mutex.synchronize do
43
+ until @cancelled
44
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
45
+ break if remaining <= 0
46
+ @wake.wait(@mutex, remaining)
47
+ end
48
+ end
49
+ check!
50
+ end
51
+ end
52
+
53
+ class App
54
+ def initialize(package, config: nil)
55
+ @package = package
56
+ @config = config
57
+ @placements = []
58
+ @jobs, @workflows, @steps = {}, {}, {}
59
+ end
60
+
61
+ def register(key, step)
62
+ key = key.to_s
63
+ raise ArgumentError, "Duplicate declaration: #{key}" if @steps.key?(key)
64
+ @steps[key] = step
65
+ step
66
+ end
67
+
68
+ def job(key, callable = nil, name: key.to_s, description: nil, parameters: [], defaults: {}, order: nil, when_condition: nil, step_key: nil, next_step: nil, else_step: nil, &block)
69
+ callable ||= block
70
+ raise ArgumentError, 'Job needs a callable' unless callable.respond_to?(:call)
71
+ step = register(key, { type: 'job', job: key.to_s })
72
+ place(key, order, when_condition, step_key: step_key, next_step: next_step, else_step: else_step)
73
+ @jobs[key.to_s] = [callable, { key: key.to_s, name: name, description: description, parameters: parameters,
74
+ defaults: defaults }]
75
+ step
76
+ end
77
+
78
+ def human(key, instructions:, response_field:, response_type: 'text', order: nil, when_condition: nil, step_key: nil, next_step: nil, else_step: nil)
79
+ place(key, order, when_condition, step_key: step_key, next_step: next_step, else_step: else_step)
80
+ register(key, { type: 'humanInput', instructions: instructions, responseField: response_field,
81
+ responseType: response_type, agentProvider: 'external' })
82
+ end
83
+
84
+ def agent(key, instructions:, response_field:, provider: 'automatic', connection_id: nil, model: nil, agent_id: nil, order: nil, when_condition: nil, step_key: nil, next_step: nil, else_step: nil)
85
+ place(key, order, when_condition, step_key: step_key, next_step: next_step, else_step: else_step)
86
+ register(key, { type: 'agentInput', instructions: instructions, responseField: response_field,
87
+ agentProvider: provider, connectionId: connection_id, model: model, agentId: agent_id })
88
+ end
89
+
90
+ def agent_task(key, instructions:, response_field:, connection_id:, model:, agent_id: nil, order: nil, when_condition: nil, step_key: nil, next_step: nil, else_step: nil)
91
+ place(key, order, when_condition, step_key: step_key, next_step: next_step, else_step: else_step)
92
+ register(key, { type: 'agentTask', instructions: instructions, responseField: response_field,
93
+ agentProvider: 'automatic', connectionId: connection_id, model: model, agentId: agent_id })
94
+ end
95
+
96
+ def place(key, order, condition, step_key: nil, next_step: nil, else_step: nil)
97
+ if step_key.nil? && (!next_step.nil? || !else_step.nil?)
98
+ raise ArgumentError, 'Routing requires step_key'
99
+ end
100
+ @placements << [key.to_s, nil, order, condition, step_key, next_step, else_step] unless order.nil? && step_key.nil?
101
+ end
102
+
103
+ def named_workflow_steps(placements)
104
+ by_key = {}
105
+ placements.each do |placement|
106
+ _, _, order, condition, key, _, else_step = placement
107
+ unless order.nil? && key.is_a?(String) && /\A[a-zA-Z][a-zA-Z0-9_.-]{0,119}\z/.match?(key) && !by_key.key?(key)
108
+ raise ArgumentError, 'Named workflows require every step to have a unique key and no numeric order'
109
+ end
110
+ raise ArgumentError, 'else_step requires when_condition' if !else_step.nil? && condition.to_s.strip.empty?
111
+ by_key[key] = placement
112
+ end
113
+ incoming = by_key.keys.to_h { |key| [key, 0] }
114
+ successors = ->(p) { p[5..6].compact.reject { |target| target == '$end' }.uniq }
115
+ placements.each do |placement|
116
+ successors.call(placement).each do |target|
117
+ raise ArgumentError, "Unknown next step: #{target}" unless incoming.key?(target)
118
+ incoming[target] += 1
119
+ end
120
+ end
121
+ ready = incoming.select { |_, count| count.zero? }.keys
122
+ raise ArgumentError, 'Named workflows require one starting step' unless ready.length == 1
123
+ ordered = []
124
+ until ready.empty?
125
+ placement = by_key.fetch(ready.sort!.shift)
126
+ ordered << placement
127
+ successors.call(placement).each do |target|
128
+ incoming[target] -= 1
129
+ ready << target if incoming[target].zero?
130
+ end
131
+ end
132
+ raise ArgumentError, 'Named workflows cannot contain cycles' unless ordered.length == placements.length
133
+ ordered
134
+ end
135
+
136
+ def workflow(key, type, name: key.to_s, description: nil)
137
+ raise ArgumentError, 'Workflow metadata belongs to a class' unless type.is_a?(Class)
138
+ register(key, nil)
139
+ @workflows[key.to_s] = { key: key.to_s, name: name, description: description }
140
+ references = type.constants(false).map { |constant| type.const_get(constant) }
141
+ @placements.each do |placement|
142
+ next unless references.any? { |value| value.equal?(@steps[placement[0]]) }
143
+ raise ArgumentError, 'A step already belongs to a workflow class' if placement[1]
144
+ placement[1] = key.to_s
145
+ end
146
+ type
147
+ end
148
+
149
+ def manifest
150
+ raise ArgumentError, 'A step references an undeclared workflow' if @placements.any? { |p| !@workflows.key?(p[1]) }
151
+ workflows = @workflows.values.map do |w|
152
+ placements = @placements.select { |p| p[1] == w[:key] }
153
+ named = placements.any? { |p| !p[4].nil? }
154
+ if named
155
+ ordered = named_workflow_steps(placements)
156
+ else
157
+ orders = placements.map { |p| p[2] }
158
+ if orders.empty? || orders.any? { |n| !n.is_a?(Integer) || n < 1 } || orders.uniq.length != orders.length
159
+ raise ArgumentError, "Workflow '#{w[:key]}' requires steps with unique positive orders"
160
+ end
161
+ ordered = placements.sort_by { |p| p[2] }
162
+ end
163
+ w.merge(steps: ordered.map do |key, _, _, condition, step_key, next_step, else_step|
164
+ definition = @steps.fetch(key).merge(when: condition)
165
+ if named
166
+ definition.merge!(key: step_key, nextStep: next_step || '$end')
167
+ definition[:elseStep] = else_step || '$end' unless condition.to_s.strip.empty?
168
+ end
169
+ definition
170
+ end)
171
+ end
172
+ { version: (@placements.any? { |p| !p[4].nil? } ? 2 : 1), package: @package, jobs: @jobs.values.map(&:last), workflows: workflows }
173
+ end
174
+
175
+ def request(path, payload)
176
+ raise ArgumentError, 'Configure the SDK endpoint, project ID and API key first' unless @config
177
+ post(@config.endpoint, @config.project_id, @config.api_key, path, payload)
178
+ end
179
+
180
+ def invoke_path(path, input)
181
+ request('code/invoke', { package: @package, path: path, input: input })
182
+ end
183
+
184
+ def cancel(run)
185
+ request('code/cancel', run)
186
+ end
187
+
188
+ def get_run(run)
189
+ request('code/status', run)
190
+ end
191
+
192
+ def sync(url = nil, project_id = nil, api_key = nil, overwrite: false)
193
+ @config = Config.new(endpoint: url, project_id: project_id, api_key: api_key) if url
194
+ request("code/sync?overwrite=#{overwrite == true}", manifest)
195
+ end
196
+
197
+ def post(url, project_id, api_key, path, payload)
198
+ base = URI(url)
199
+ unless %w[http https].include?(base.scheme) && base.host && !base.userinfo && !base.query && !base.fragment
200
+ raise ArgumentError, 'Provide an HTTP(S) server URL without credentials, query, or fragment'
201
+ end
202
+ unless /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i.match?(project_id)
203
+ raise ArgumentError, 'Invalid project ID'
204
+ end
205
+ uri = URI("#{url.sub(%r{/$}, '')}/api/v1/projects/#{project_id}/#{path}")
206
+ request = Net::HTTP::Post.new(uri, { 'Authorization' => "Bearer #{api_key}", 'Content-Type' => 'application/json' })
207
+ request.body = JSON.generate(payload)
208
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: 10, read_timeout: 60) { |http| http.request(request) }
209
+ raise RequestError.new(response) unless response.is_a?(Net::HTTPSuccess)
210
+ JSON.parse(response.body)
211
+ end
212
+
213
+ def invoke(key, payload, cancellation: CancellationToken.new)
214
+ raise ArgumentError, 'Job input must be a JSON object' unless payload.is_a?(Hash)
215
+ callable, definition = @jobs.fetch(key.to_s)
216
+ values = definition[:defaults].transform_keys(&:to_s).merge(payload.transform_keys(&:to_s))
217
+ arguments = definition[:parameters].each_with_object({}) do |p, args|
218
+ name = p.fetch(:name).to_s
219
+ raise ArgumentError, "Missing input: #{name}" if p.fetch(:required, true) && !values.key?(name)
220
+ args[name.to_sym] = values[name] if values.key?(name)
221
+ end
222
+ arguments[:cancellation] = cancellation if callable.parameters.any? { |kind, name| [:key, :keyreq].include?(kind) && name == :cancellation }
223
+ cancellation.check!
224
+ previous = $stdout
225
+ begin
226
+ $stdout = $stderr
227
+ callable.call(**arguments)
228
+ ensure
229
+ $stdout = previous
230
+ end
231
+ end
232
+
233
+ def run
234
+ if ['invoke-path', 'cancel', 'status'].include?(ARGV.first)
235
+ raise ArgumentError, 'Usage: invoke-path URL PROJECT_ID PATH | cancel URL PROJECT_ID | status URL PROJECT_ID; JSON on stdin' unless ARGV.length == (ARGV.first == 'invoke-path' ? 4 : 3)
236
+ @config = Config.new(endpoint: ARGV[1], project_id: ARGV[2], api_key: ENV.fetch('PLACECONTEXT_API_KEY'))
237
+ input = JSON.parse($stdin.read)
238
+ result = ARGV.first == 'invoke-path' ? invoke_path(ARGV[3], input) : ARGV.first == 'cancel' ? cancel(input) : get_run(input)
239
+ puts JSON.generate(result)
240
+ return
241
+ end
242
+ if ARGV.first == 'sync'
243
+ unless [3, 4].include?(ARGV.length) && (ARGV.length == 3 || ARGV[3] == '--overwrite')
244
+ raise ArgumentError, 'Usage: sync URL PROJECT_ID [--overwrite]; set PLACECONTEXT_API_KEY'
245
+ end
246
+ puts JSON.generate(sync(ARGV[1], ARGV[2], ENV.fetch('PLACECONTEXT_API_KEY'), overwrite: ARGV[3] == '--overwrite'))
247
+ return
248
+ end
249
+ if ARGV == ['manifest']
250
+ puts JSON.pretty_generate(manifest)
251
+ return
252
+ end
253
+ if ARGV.first == 'worker'
254
+ unless [3, 4].include?(ARGV.length) && (ARGV.length == 3 || ARGV[3] == '--once')
255
+ raise ArgumentError, 'Usage: worker URL PROJECT_ID [--once]; set PLACECONTEXT_API_KEY'
256
+ end
257
+ serve(ARGV[1], ARGV[2], ENV.fetch('PLACECONTEXT_API_KEY'), once: ARGV[3] == '--once')
258
+ return
259
+ end
260
+ if ARGV.length == 2 && ARGV.first == 'invoke'
261
+ puts JSON.generate(invoke(ARGV[1], JSON.parse($stdin.read)))
262
+ return
263
+ end
264
+ raise ArgumentError, 'Usage: manifest | sync URL PROJECT_ID [--overwrite] | worker URL PROJECT_ID [--once] | invoke FUNCTION'
265
+ end
266
+
267
+ def serve(url = nil, project_id = nil, api_key = nil, once: false)
268
+ sync(url, project_id, api_key)
269
+ url, project_id, api_key = @config.endpoint, @config.project_id, @config.api_key
270
+ warn "SDK '#{@package}' connected. Functions execute in this process."
271
+ loop do
272
+ work = post(url, project_id, api_key, 'sdk/claim', { package: @package })['work']
273
+ unless work
274
+ sleep 1
275
+ next
276
+ end
277
+ lease = { id: work.fetch('id'), lease: work.fetch('lease') }
278
+ cancellation = CancellationToken.new
279
+ heartbeat_error = nil
280
+ stopped = false
281
+ mutex = Mutex.new
282
+ wake = ConditionVariable.new
283
+ heartbeat = Thread.new do
284
+ begin
285
+ loop do
286
+ break if mutex.synchronize { wake.wait(mutex, 2) unless stopped; stopped }
287
+ post(url, project_id, api_key, 'sdk/heartbeat', lease)
288
+ end
289
+ rescue StandardError => error
290
+ heartbeat_error = error
291
+ cancellation.cancel
292
+ end
293
+ end
294
+ begin
295
+ completed = lease.merge(output: invoke(work.fetch('function'), work.fetch('input'), cancellation: cancellation))
296
+ JSON.generate(completed)
297
+ rescue StandardError => error
298
+ completed = lease.merge(error: error.message[0, 4000])
299
+ ensure
300
+ mutex.synchronize { stopped = true; wake.signal }
301
+ heartbeat.join
302
+ end
303
+ if heartbeat_error.is_a?(RequestError) && heartbeat_error.status == 409
304
+ warn "SDK invocation cancelled: #{work['id']}"
305
+ else
306
+ raise heartbeat_error if heartbeat_error
307
+ begin
308
+ post(url, project_id, api_key, 'sdk/complete', completed)
309
+ rescue RequestError => error
310
+ raise unless error.status == 409
311
+ end
312
+ warn "SDK finished #{work['function']} (#{work['id']})."
313
+ end
314
+ return if once
315
+ end
316
+ end
317
+ end
318
+ end
metadata ADDED
@@ -0,0 +1,47 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: placecontext
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - PlaceContext
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-12-01 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Declare workflows and execute SDK jobs in your own application with PlaceContext
14
+ orchestration.
15
+ email:
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - LICENSE
21
+ - README.md
22
+ - lib/placecontext.rb
23
+ homepage: https://github.com/bradlnz/placecontext
24
+ licenses:
25
+ - MIT
26
+ metadata:
27
+ source_code_uri: https://github.com/bradlnz/placecontext/tree/main/sdks/ruby
28
+ post_install_message:
29
+ rdoc_options: []
30
+ require_paths:
31
+ - lib
32
+ required_ruby_version: !ruby/object:Gem::Requirement
33
+ requirements:
34
+ - - ">="
35
+ - !ruby/object:Gem::Version
36
+ version: '3.1'
37
+ required_rubygems_version: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: '0'
42
+ requirements: []
43
+ rubygems_version: 3.5.22
44
+ signing_key:
45
+ specification_version: 4
46
+ summary: Code-first jobs and workflows for PlaceContext
47
+ test_files: []