withruntime 0.28.0 → 1.0.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 (66) hide show
  1. checksums.yaml +4 -4
  2. data/lib/withruntime/generated/apps.rb +192 -0
  3. data/lib/withruntime/generated/audit.rb +78 -0
  4. data/lib/withruntime/generated/browsers.rb +192 -0
  5. data/lib/withruntime/generated/builds.rb +192 -0
  6. data/lib/withruntime/generated/ci.rb +192 -0
  7. data/lib/withruntime/generated/containers.rb +192 -0
  8. data/lib/withruntime/generated/desktops.rb +192 -0
  9. data/lib/withruntime/generated/domains.rb +152 -0
  10. data/lib/withruntime/generated/egress_ips.rb +81 -0
  11. data/lib/withruntime/generated/events.rb +60 -0
  12. data/lib/withruntime/generated/feedback.rb +96 -0
  13. data/lib/withruntime/generated/functions.rb +192 -0
  14. data/lib/withruntime/generated/identities.rb +68 -0
  15. data/lib/withruntime/generated/images.rb +391 -0
  16. data/lib/withruntime/generated/job_runs.rb +110 -0
  17. data/lib/withruntime/generated/jobs.rb +333 -0
  18. data/lib/withruntime/generated/keys.rb +261 -0
  19. data/lib/withruntime/generated/kit.rb +111 -0
  20. data/lib/withruntime/generated/me.rb +69 -0
  21. data/lib/withruntime/generated/networks.rb +72 -0
  22. data/lib/withruntime/generated/notebooks.rb +192 -0
  23. data/lib/withruntime/generated/otel.rb +94 -0
  24. data/lib/withruntime/generated/ports.rb +118 -0
  25. data/lib/withruntime/generated/previews.rb +124 -0
  26. data/lib/withruntime/generated/projects.rb +108 -0
  27. data/lib/withruntime/generated/roles.rb +68 -0
  28. data/lib/withruntime/generated/routes.rb +11 -0
  29. data/lib/withruntime/generated/runtime.rb +188 -0
  30. data/lib/withruntime/generated/sandboxes.rb +1835 -0
  31. data/lib/withruntime/generated/secrets.rb +294 -0
  32. data/lib/withruntime/generated/sessions.rb +143 -0
  33. data/lib/withruntime/generated/sites.rb +192 -0
  34. data/lib/withruntime/generated/snapshots.rb +32 -0
  35. data/lib/withruntime/generated/tunnels.rb +165 -0
  36. data/lib/withruntime/generated/usage.rb +287 -0
  37. data/lib/withruntime/generated/volumes.rb +61 -0
  38. data/lib/withruntime/generated/webhooks.rb +91 -0
  39. data/lib/withruntime/generated/workspaces.rb +192 -0
  40. data/lib/withruntime/signing.rb +162 -0
  41. data/lib/withruntime/version.rb +2 -2
  42. data/lib/withruntime.rb +5 -43
  43. metadata +45 -35
  44. data/lib/withruntime/agents.rb +0 -877
  45. data/lib/withruntime/api_defaults.rb +0 -17
  46. data/lib/withruntime/apps.rb +0 -377
  47. data/lib/withruntime/browsers.rb +0 -104
  48. data/lib/withruntime/builds.rb +0 -218
  49. data/lib/withruntime/ci.rb +0 -164
  50. data/lib/withruntime/client.rb +0 -140
  51. data/lib/withruntime/containers.rb +0 -39
  52. data/lib/withruntime/credentials.rb +0 -111
  53. data/lib/withruntime/fields.rb +0 -40
  54. data/lib/withruntime/file_watch.rb +0 -73
  55. data/lib/withruntime/images.rb +0 -258
  56. data/lib/withruntime/network_products.rb +0 -49
  57. data/lib/withruntime/parity_products.rb +0 -51
  58. data/lib/withruntime/products.rb +0 -560
  59. data/lib/withruntime/record.rb +0 -99
  60. data/lib/withruntime/reservations.rb +0 -76
  61. data/lib/withruntime/sandbox.rb +0 -775
  62. data/lib/withruntime/tar.rb +0 -292
  63. data/lib/withruntime/transport.rb +0 -575
  64. data/lib/withruntime/tunnel.rb +0 -275
  65. data/lib/withruntime/wallet.rb +0 -68
  66. data/lib/withruntime/websocket.rb +0 -384
@@ -1,877 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module WithRuntime
4
- # An agent: +id+, +name+, +version+ (one more on each update), +definition+,
5
- # +labels+, +created_at+, +updated_at+, and +warnings+, such as
6
- # "subscription_for_customers" for an agent that serves your customers on a
7
- # subscription login (an empty list when there are none).
8
- class Agent < Record
9
- def warnings = self["warnings"] || []
10
- end
11
-
12
- # One entry of a session's log: +seq+, +kind+ (input, answer, reply, ask,
13
- # status, result, error, note, child: a child session's end, posted into
14
- # its parent's log, turn: a model turn, or tool: a tool call, the trace's
15
- # spans with their fields in +body+), +actor+, +body+ and +created_at+.
16
- # +text+ is its words, +body.text+.
17
- class AgentEvent < Record
18
- def text = self["body"].is_a?(Hash) ? self["body"]["text"] : nil
19
- end
20
-
21
- # A session's trace (+AgentSession#trace+): +session_id+; +totals+ (turns,
22
- # tool_calls, input_tokens (uncached), output_tokens, cache_read_tokens,
23
- # cache_write_tokens, cost_usd at the provider's list price,
24
- # unpriced_turns, failed_turns, failed_tool_calls, model_ms, tool_ms);
25
- # +models+ and +tools+, the same by model and by tool; and +spans+, each
26
- # turn and tool call in order. A turn has its +model+, +started_at+,
27
- # +duration_ms+, +first_token_ms+, token counts, +cost_usd+ (nil for an
28
- # unpriced model), +stop_reason+, +status+, +error+ and +tool_calls+; a
29
- # tool call its +name+, +turn+, +started_at+, +duration_ms+, +input+,
30
- # +output+ and +error+.
31
- class AgentTrace < Record
32
- def totals = Record.new(self["totals"])
33
- def models = (self["models"] || []).map { |row| Record.new(row) }
34
- def tools = (self["tools"] || []).map { |row| Record.new(row) }
35
- def spans = (self["spans"] || []).map { |row| Record.new(row) }
36
- end
37
-
38
- # A session as the API answers it. Times are ISO 8601 strings.
39
- #
40
- # +id+, +agent_id+, +agent_version+, +key+, +trigger+ (api, slack, github,
41
- # schedule, webhook, or spawn: a child its parent's harness started),
42
- # +state+ (queued, running, waiting, done, failed or stopped), +reason+
43
- # (why it ended; among others "budget", "parent_ended", and "deleted" on a
44
- # deleted record), +result+, +sandbox_id+, +last_seq+, +labels+,
45
- # +overrides+ (what its start overrode of its agent's definition, as given,
46
- # or nil), +created_at+, +started_at+, +ended_at+.
47
- #
48
- # Its tree: +parent_session_id+ (nil for a top session), +root_session_id+
49
- # (itself for a top session) and +depth+ (0 to 3). Its use: +cost+ (this
50
- # session's so far) and +tree_cost+ (it and every session under it), each
51
- # an AgentCost. Its storage: +history_bytes+ (its log, kept until the
52
- # session is deleted) and +attachment_bytes+ (its files and screenshots).
53
- # +stop_why+ is why a stop was asked ("stopped", "budget" or
54
- # "parent_ended") or nil, and +deleted_at+ is set once its history was
55
- # deleted (+sessions.delete+). +workflow_id+ is the workflow that started
56
- # it as one of its steps, or nil.
57
- class AgentSessionInfo < Record
58
- def cost = AgentCost.new(self["cost"])
59
- def tree_cost = AgentCost.new(self["treeCost"])
60
- def deleted? = !self["deletedAt"].nil?
61
- end
62
-
63
- # What a session, or its tree, has used: +dollars+, +vcpu_seconds+ and
64
- # +gib_seconds+ (0 when not given).
65
- class AgentCost < Record
66
- def dollars = self["dollars"] || 0
67
- def vcpu_seconds = self["vcpuSeconds"] || 0
68
- def gib_seconds = self["gibSeconds"] || 0
69
- end
70
-
71
- # +runtime.agents+: agents that run in their own sandbox per session, started
72
- # by your own app through the API, Slack, GitHub, a schedule or a webhook. A private
73
- # beta: an account outside it is refused +product_in_beta+
74
- # (PermissionDeniedError).
75
- #
76
- # definition = runtime.agents.templates.definition("claude-code", use: "team")
77
- # runtime.agents.create("reviewer", definition)
78
- # session = runtime.agents.start("reviewer", "Review the open pull requests.")
79
- # session.events.each { |event| puts event.text if event.kind == "reply" }
80
- #
81
- # A definition is a Hash, by snake_case keyword (+memory_mib:+) or by the
82
- # API's own key ("memoryMiB"): +command+ (required), +from+ ({ image: },
83
- # { snapshot: }, or { repo: "owner/name" }: a repository connected to
84
- # CI/CD, each session a copy of its warm snapshot, checked out at
85
- # /workspace/repo), +vcpu+ and +memory_mib+ (4 vCPU and 8 GiB unless set; a
86
- # definition from a snapshot takes neither, InvalidRequestError, since a
87
- # snapshot keeps its own size), +instructions+, +env+, +secrets+ (names of
88
- # egress secrets: model keys go here), +pool+ (1 to 16 Claude accounts,
89
- # each an egress secret's name: each session takes the one with the most
90
- # usage left, and the review template moves to the next when one is out
91
- # of usage), +mcp+ ([{ name:, url: }]), +volumes+
92
- # ([{ volume:, path: }]), +network+ ({ internet:, allow: }: with allow,
93
- # each session's sandbox reaches only those hosts), +idle_pause_seconds+,
94
- # +max_session_seconds+,
95
- # +max_concurrent+, +max_session_dollars+ (more than 0, at most 10000, 5
96
- # unless set: the session and every session under it, the root's covering
97
- # its tree; a tree at it stops, reason "budget"), +max_day_dollars+ (more
98
- # than 0, at most 100000, 100 unless set: the agent's sessions started that
99
- # UTC day; an agent at it starts nothing new, +budget_reached+
100
- # (402), until the next day), +max_children+ (1 to 1000, 100 unless set:
101
- # the sessions one session's harness may start), +advisor+ ({ model:,
102
- # provider:, secret:, base_url:, max_calls:, instructions: }, all but
103
- # +model+ optional: a model its sessions may ask for advice with the
104
- # advise tool, each call kept in the log as a note) and +template+
105
- # ("support" or "team").
106
- class Agents < Product
107
- attr_reader :sessions, :triggers, :slack, :templates, :memory, :asks, :workflows
108
-
109
- def initialize(transport)
110
- super
111
- @sessions = AgentSessions.new(transport)
112
- @triggers = AgentTriggers.new(transport)
113
- @slack = AgentSlack.new(transport)
114
- @templates = AgentTemplates.new
115
- @memory = AgentMemory.new(transport)
116
- @asks = AgentAsks.new(transport)
117
- @workflows = AgentWorkflows.new(transport)
118
- end
119
-
120
- # Claude Managed Agents' API on Runtime: the options Anthropic's Ruby SDK
121
- # takes, so code written for it runs here unchanged:
122
- #
123
- # client = Anthropic::Client.new(**runtime.agents.anthropic)
124
- #
125
- # Sessions call the model with the account's own Anthropic key, the egress
126
- # secret ANTHROPIC_API_KEY (runtime secrets set ANTHROPIC_API_KEY --host
127
- # api.anthropic.com).
128
- def anthropic = { base_url: "#{@t.base_url}/anthropic", api_key: @t.api_key }
129
-
130
- # Makes an agent at version 1. A name already used is a ConflictError
131
- # (name_taken); the names sessions, triggers, templates and approvals are
132
- # refused, since they are paths beside the agents.
133
- def create(name, definition, labels: nil, idempotency_key: nil)
134
- body = Fields.body(name: name, definition: AgentTemplates.plain(definition), labels: labels)
135
- Agent.new(@t.json("POST", "/v1/agents", body: body, key: idempotency_key))
136
- end
137
-
138
- # By id or by name.
139
- def get(agent) = Agent.new(@t.json("GET", "/v1/agents/#{seg(agent)}"))
140
-
141
- # The first page of agents, at most +limit+ a page; +each+ walks every page.
142
- def list(cursor: nil, limit: nil) = agents_page(cursor, limit)
143
-
144
- # Replaces the whole definition: a new version. Sessions already running
145
- # keep the version they started with.
146
- def update(agent, definition)
147
- body = { "definition" => Fields.convert(AgentTemplates.plain(definition)) }
148
- Agent.new(@t.json("PATCH", "/v1/agents/#{seg(agent)}", body: body))
149
- end
150
-
151
- # Deletes an agent: its triggers go and its open sessions are asked to stop.
152
- def delete(agent) = @t.json("DELETE", "/v1/agents/#{seg(agent)}") && nil
153
-
154
- # Starts a session with +input+, its first words. With +key:+, your own
155
- # name for the conversation (a Slack thread, a pull request, one of your
156
- # customers such as "customer:42"), words with the same key join the open
157
- # session instead of starting a second; +session.joined+ says so.
158
- # +overrides:+ gives this session its own model, instructions, MCP
159
- # servers, disallowed tools, size and budget within the agent's
160
- # +sessionOverrides+ ({ model:, instructions:, instructions_mode:
161
- # "replace", mcp: [names], disallowed_tools: ["Bash", "spawn"], vcpu:,
162
- # memory_mib:, max_session_dollars: }); one it does not allow is refused
163
- # +permission_denied+ (403), naming what it allows. An agent at its day's
164
- # budget is refused +budget_reached+ (402).
165
- def start(agent, input, key: nil, labels: nil, overrides: nil, idempotency_key: nil)
166
- body = Fields.body(input: input, key: key, labels: labels, overrides: overrides)
167
- answer = @t.json("POST", "/v1/agents/#{seg(agent)}/sessions", body: body, key: idempotency_key)
168
- AgentSession.new(@t, answer["session"], joined: answer["joined"] == true, seq: answer["seq"])
169
- end
170
-
171
- private
172
-
173
- def agents_page(cursor, limit)
174
- body = @t.json("GET", "/v1/agents", query: { "cursor" => cursor, "limit" => limit })
175
- Page.new(body["data"].map { |item| Agent.new(item) }, body["nextCursor"]) { |after| agents_page(after, limit) }
176
- end
177
- end
178
-
179
- # +runtime.agents.sessions+: find sessions. A session is one piece of work
180
- # or one conversation; it has its own sandbox while it runs.
181
- class AgentSessions < Product
182
- # A session to follow, send to, stop or wait for.
183
- def get(id)
184
- info = @t.json("GET", "/v1/agents/sessions/#{seg(id)}")
185
- AgentSession.new(@t, info, joined: false, seq: info["lastSeq"])
186
- end
187
-
188
- # Deletes an ended session's history: its log, and every log under it in
189
- # its tree. Until then the history is kept, counted as storage. The
190
- # session is kept as a deleted record: +get+ still reads it, with
191
- # +deleted_at+ set, +reason+ "deleted", +key+ and +result+ cleared and its
192
- # cost kept (a delete never frees budget), and its log reads empty. An
193
- # open session or tree is refused +session_open+ (ConflictError): stop it
194
- # first.
195
- def delete(id) = @t.json("DELETE", "/v1/agents/sessions/#{seg(id)}") && nil
196
-
197
- # The first page of sessions, as AgentSessionInfo records; +each+ walks
198
- # every page. +agent+ is an id or a name; +state+ is queued, running,
199
- # waiting, done, failed or stopped; +parent+ (a session's id) lists its
200
- # direct children; +root+ (a top session's id) its whole tree, the root
201
- # included; +deleted: true+ includes deleted records, hidden otherwise; at
202
- # most +limit+ a page.
203
- def list(agent: nil, state: nil, parent: nil, root: nil, deleted: nil, cursor: nil, limit: nil)
204
- query = { "agent" => agent, "state" => state, "parent" => parent, "root" => root, "deleted" => deleted, "limit" => limit }
205
- sessions_page(query, cursor)
206
- end
207
-
208
- private
209
-
210
- def sessions_page(query, cursor)
211
- body = @t.json("GET", "/v1/agents/sessions", query: query.merge("cursor" => cursor))
212
- Page.new(body["data"].map { |item| AgentSessionInfo.new(item) }, body["nextCursor"]) { |after| sessions_page(query, after) }
213
- end
214
- end
215
-
216
- # A session of an agent. +info+ is its latest record, an AgentSessionInfo:
217
- # +state+ (queued, running, waiting, done, failed or stopped), +reason+,
218
- # +result+, +last_seq+, its tree (+parent_session_id+, +root_session_id+,
219
- # +depth+), its use (+cost+, +tree_cost+), its storage (+history_bytes+,
220
- # +attachment_bytes+), +stop_why+, +deleted_at+ and the rest; history is
221
- # kept until the session is deleted (+sessions.delete+). +joined+ is
222
- # whether +start+ joined an open session with the same key, and +seq+ the
223
- # number of the words it sent.
224
- class AgentSession
225
- ENDED = %w[done failed stopped].freeze
226
- # How long the API holds an events read open, and the margin past it a
227
- # read waits for its answer.
228
- POLL_SECONDS = 30
229
- POLL_MARGIN = 15
230
-
231
- attr_reader :info, :joined, :seq
232
-
233
- def initialize(transport, info, joined: false, seq: nil)
234
- @t = transport
235
- @info = AgentSessionInfo.new(info)
236
- @joined = joined
237
- @seq = seq
238
- end
239
-
240
- def id = @info["id"]
241
- def state = @info["state"]
242
- def joined? = @joined
243
- def ended? = ENDED.include?(state)
244
-
245
- # Reads the session again.
246
- def refresh(timeout: nil)
247
- @info = AgentSessionInfo.new(@t.json("GET", path, timeout: timeout))
248
- self
249
- end
250
-
251
- # The first page of its direct children, the sessions its harness started
252
- # (+trigger+ "spawn"), newest first; +each+ walks every page.
253
- # +sessions.list(root:)+ reads a whole tree.
254
- def children(cursor: nil, limit: nil) = AgentSessions.new(@t).list(parent: id, cursor: cursor, limit: limit)
255
-
256
- # Sends words into a running or waiting session and answers their seq.
257
- # The idempotency key, made here when not given, means a retried send is
258
- # never two messages. Named send_message, not send, so Ruby's own
259
- # Object#send stays as it is.
260
- def send_message(text, idempotency_key: nil)
261
- @t.json("POST", path("/messages"), body: { "text" => text }, key: idempotency_key)["seq"]
262
- end
263
-
264
- # The session's log after +after+ (0, the whole log), in order, each an
265
- # AgentEvent; without a block, an Enumerator. It waits for new events and
266
- # ends once the session has ended and its last event has been given.
267
- def events(after: 0, &block)
268
- return enum_for(:events, after: after) unless block
269
-
270
- wait = POLL_SECONDS
271
- loop do
272
- page = read_events(after, wait)
273
- data = page["data"] || []
274
- data.each do |item|
275
- event = AgentEvent.new(item)
276
- after = event.seq
277
- yield event
278
- end
279
- # Ended: read on at once, without waiting, until nothing is left.
280
- if page["ended"]
281
- return nil if wait.zero? && data.empty?
282
-
283
- wait = 0
284
- end
285
- end
286
- end
287
-
288
- # A page of its trace, an AgentTrace: every model turn and tool call its
289
- # harness made, with timing, tokens and cost. Its totals cover the whole
290
- # session; its spans are up to +limit+ (200 by default, 500 at most)
291
- # after +after+: call again with +after: page.next_after+ until it is nil.
292
- # +format: "otlp"+ returns the same page as OpenTelemetry traces instead,
293
- # OTLP/JSON (GenAI semantic conventions) as a Hash with "nextAfter", to
294
- # POST without it to any collector's /v1/traces.
295
- def trace(format: "json", after: 0, limit: nil)
296
- raise ArgumentError, "format is json or otlp" unless %w[json otlp].include?(format.to_s)
297
-
298
- query = { "format" => format.to_s, "after" => after }
299
- query["limit"] = limit if limit
300
- body = @t.json("GET", path("/trace"), query: query)
301
- format.to_s == "otlp" ? body : AgentTrace.new(body)
302
- end
303
-
304
- # Asks the session to stop and keeps the answer. A running session ends
305
- # once its sandbox is deleted; this does not wait for that (+wait+ does).
306
- def stop
307
- @info = AgentSessionInfo.new(@t.json("POST", path("/stop"), body: {}))
308
- end
309
-
310
- # The session once it has ended (done, failed or stopped); a failed
311
- # session is returned, not raised. Waits on the server, with no polling.
312
- # +timeout+ in seconds (nil or 0: no deadline) raises a ConnectionError
313
- # with code "timeout" when it passes first.
314
- def wait(timeout: nil)
315
- deadline = timeout&.positive? ? now + timeout : nil
316
- loop do
317
- refresh(timeout: deadline && left(deadline))
318
- return @info if ended?
319
-
320
- loop do
321
- seconds = deadline ? [POLL_SECONDS, left(deadline).ceil].min : POLL_SECONDS
322
- page = read_events(@info["lastSeq"] || 0, seconds)
323
- break if page["ended"] || !(page["data"] || []).empty?
324
-
325
- left(deadline) if deadline
326
- end
327
- end
328
- end
329
-
330
- def inspect = "#<#{self.class.name} #{id} #{state}>"
331
-
332
- private
333
-
334
- def path(suffix = "") = "/v1/agents/sessions/#{Transport.segment(id)}#{suffix}"
335
-
336
- # One long poll: its own deadline past the API's hold, whatever the client's.
337
- def read_events(after, wait)
338
- @t.json("GET", path("/events"), query: { "after" => after, "wait" => wait }, timeout: [@t.timeout, wait + POLL_MARGIN].max)
339
- end
340
-
341
- def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
342
-
343
- def left(deadline)
344
- seconds = deadline - now
345
- raise @t.connection_error(true, false, nil) unless seconds.positive?
346
-
347
- seconds
348
- end
349
- end
350
-
351
- # +runtime.agents.triggers+: what starts or feeds an agent's sessions
352
- # besides the API. A trigger is +id+, +agent_id+, +kind+, +config+,
353
- # +paused_at+, +paused_why+ and +created_at+. The kinds and their configs:
354
- #
355
- # slack { team: "T…", channel: "C…" }, once Runtime's Slack app is installed
356
- # github { repository: "owner/name", installation: <Runtime's GitHub App
357
- # installation id, the organization's own>, events: [...] (optional) }
358
- # schedule { cron: "0 9 * * 1-5", timezone: "America/Denver" (optional), input: "words" }
359
- # webhook {}
360
- #
361
- # A slack or github trigger whose app is not installed for the account is
362
- # refused +not_installed+ (ConflictError).
363
- #
364
- # Each trigger has +rules+, every one optional: +priority+ (-100 to 100:
365
- # queue order when the agent's maxConcurrent is full, higher first),
366
- # +max_starts_per_hour+ (a call past it is held for you), +on_ended+
367
- # ("start", "note" or "ask": what a call does when its key's session has
368
- # ended), +notify+ ("email" or "webhook": where a held call is told) and,
369
- # a webhook's only, +key+ ("{cause}": the key of a call that sends none,
370
- # from its JSON's fields). A call no session can take is held, never
371
- # dropped: +held+, +start_held+, +dismiss_held+.
372
- class AgentTriggers < Product
373
- def create(agent, kind, config = {}, rules: nil)
374
- body = { "kind" => kind, "config" => Fields.convert(config.to_h) }
375
- body["rules"] = Fields.convert(rules.to_h) if rules
376
- Record.new(@t.json("POST", "/v1/agents/#{seg(agent)}/triggers", body: body))
377
- end
378
-
379
- # Its rules, whole, in place: its secret stays. +{}+ is every default.
380
- def set_rules(id, rules)
381
- Record.new(@t.json("PATCH", "/v1/agents/triggers/#{seg(id)}", body: { "rules" => Fields.convert(rules.to_h) }))
382
- end
383
-
384
- # Calls a webhook trigger as its sender would, by its +secret+, never your
385
- # key: +outcome+ started, joined (the open session with +key+), noted or
386
- # held, with +session_id+, +seq+, +call_id+ and +why+. The same
387
- # +idempotency_key+ is the same call.
388
- def call(id, secret, text, key: nil, labels: nil, idempotency_key: nil)
389
- body = Fields.body(text: text, key: key, labels: labels)
390
- Record.new(@t.json("POST", "/v1/agents/triggers/#{seg(id)}/calls", body: body, bearer: secret,
391
- key: idempotency_key))
392
- end
393
-
394
- # The calls it held for you, newest first; +each+ walks every page.
395
- def held(id, state: nil, cursor: nil, limit: nil)
396
- held_page(id, { "state" => state, "limit" => limit }, cursor)
397
- end
398
-
399
- # Starts a held call: one session with it and every call held for its key
400
- # since, oldest first. +session+, +joined+ and +calls+.
401
- def start_held(id, call_id)
402
- Record.new(@t.json("POST", "/v1/agents/triggers/#{seg(id)}/held/#{seg(call_id)}/start", body: {}))
403
- end
404
-
405
- # Dismisses a held call: nothing runs.
406
- def dismiss_held(id, call_id)
407
- Record.new(@t.json("POST", "/v1/agents/triggers/#{seg(id)}/held/#{seg(call_id)}/dismiss", body: {}))
408
- end
409
-
410
- def list(agent) = @t.json("GET", "/v1/agents/#{seg(agent)}/triggers")["data"].map { |row| Record.new(row) }
411
-
412
- # Holds this trigger alone, saying +why+: a webhook's calls are held for
413
- # you (+held+), never dropped. Nothing else is held.
414
- def pause(id, why) = Record.new(@t.json("POST", "/v1/agents/triggers/#{seg(id)}/pause", body: { "why" => why }))
415
-
416
- def resume(id) = Record.new(@t.json("POST", "/v1/agents/triggers/#{seg(id)}/resume", body: {}))
417
-
418
- def delete(id) = @t.json("DELETE", "/v1/agents/triggers/#{seg(id)}") && nil
419
-
420
- private
421
-
422
- def held_page(id, query, cursor)
423
- body = @t.json("GET", "/v1/agents/triggers/#{seg(id)}/held", query: query.merge("cursor" => cursor))
424
- Page.new(body["data"].map { |item| Record.new(item) }, body["nextCursor"]) { |after| held_page(id, query, after) }
425
- end
426
- end
427
-
428
- # +runtime.agents.slack+: Runtime's Slack app in your workspaces. Add it with
429
- # +install+'s link; a slack trigger then names a workspace's +team+ and a
430
- # channel the app is in.
431
- class AgentSlack < Product
432
- # A link that adds Runtime's Slack app to a workspace, good for 15
433
- # minutes: +url+ and +expires_at+. Open it as a person who may add apps
434
- # to the workspace; Slack sends them back to the console once it is added.
435
- def install = Record.new(@t.json("POST", "/v1/agents/slack/installs", body: {}))
436
-
437
- # The workspaces added to this account: +team+, +name+, +bot_user+, +installed_at+.
438
- def teams = @t.json("GET", "/v1/agents/slack/teams")["data"].map { |row| Record.new(row) }
439
-
440
- # Removes a workspace: its token is revoked, and its triggers refuse
441
- # events until it is added again.
442
- def remove(team) = @t.json("DELETE", "/v1/agents/slack/teams/#{seg(team)}") && nil
443
- end
444
-
445
- # +runtime.agents.asks+: the account's inbox, the questions its agents'
446
- # sessions need answered to go on. Each has +why+ it matters, +options+
447
- # ({label, detail}), a recommended +pick+ and maybe an expiry. Asks of
448
- # one agent's sessions sharing a memory, with the same +step+, are one
449
- # row while it is open, and one answer reaches every session asking. +state+: open, answered,
450
- # withdrawn, expired (no pick) or closed (every asking session ended).
451
- #
452
- # A tool call the agent's +permissions+ hold is an ask too, with the
453
- # options Allow and Deny and the call in +toolCall+ ({tool, input,
454
- # toolUseId, seq, policy, reasonCode}): +approve+ lets it run, +deny+ keeps
455
- # it from running.
456
- class AgentAsks < Product
457
- # The first page, newest first: open asks unless +state+ (one or a list)
458
- # says otherwise; of one +agent+; carrying every one of +labels+ (who sees
459
- # an ask). +each+ walks every page.
460
- def list(state: nil, agent: nil, labels: nil, cursor: nil, limit: nil)
461
- label = labels&.map { |k, v| "#{k}:#{v}" }
462
- asks_page({ "state" => state, "agent" => agent, "label" => label, "limit" => limit }, cursor)
463
- end
464
-
465
- # One ask, with the sessions asking it.
466
- def get(id) = Record.new(@t.json("GET", "/v1/agents/asks/#{seg(id)}"))
467
-
468
- # Answers with an +option+'s label, +text+, or both: every session asking
469
- # reads it next and wakes. One no longer open is refused +ask_closed+
470
- # (ConflictError).
471
- def answer(id, option = nil, text: nil, idempotency_key: nil)
472
- raise ArgumentError, "an answer is an option's label, text, or both" if option.nil? && text.nil?
473
-
474
- body = Fields.body(option: option, text: text)
475
- Record.new(@t.json("POST", "/v1/agents/asks/#{seg(id)}/answer", body: body, key: idempotency_key))
476
- end
477
-
478
- # Lets a tool call the agent's permissions held run (its ask's Allow).
479
- def approve(id, idempotency_key: nil) = answer(id, "Allow", idempotency_key: idempotency_key)
480
-
481
- # Keeps a held tool call from running (its ask's Deny); +message+ is told
482
- # to the agent as the reason.
483
- def deny(id, message = nil, idempotency_key: nil) = answer(id, "Deny", text: message, idempotency_key: idempotency_key)
484
-
485
- private
486
-
487
- def asks_page(query, cursor)
488
- body = @t.json("GET", "/v1/agents/asks", query: query.merge("cursor" => cursor))
489
- Page.new(body["data"].map { |item| Record.new(item) }, body["nextCursor"]) { |after| asks_page(query, after) }
490
- end
491
- end
492
-
493
- # +runtime.agents.workflows+: many sessions in phases. A workflow is data,
494
- # not code: each phase names an +agent+ (or uses the workflow's), an
495
- # +input+ template ({{input}}, {{item}}, {{index}}, and {{<phase>}} for an
496
- # earlier phase's results) and +each+, a list of items (1 to 1000) or
497
- # { from: "<phase>", split: "json" | "lines" } to fan out over an earlier
498
- # phase's result. A phase waits for every phase before it, unless
499
- # +pipeline+ is true: then each item starts as soon as its own item in the
500
- # source phase ends. +max_sessions+ (100 unless set, at most 1000),
501
- # +max_concurrent+ (20, at most 200) and +max_dollars+ (10, at most 10000)
502
- # bound it; at the cap it fails with reason "budget".
503
- #
504
- # flow = runtime.agents.workflows.run(agent: "dev", phases: [
505
- # { name: "fix", input: "Fix {{item}}", each: %w[a.ts b.ts] }
506
- # ])
507
- # flow.follow { |w| puts w.phases.map { |p| "#{p.name} #{p.done}/#{p.total}" } }
508
- # puts flow.wait.result
509
- class AgentWorkflows < Product
510
- # Runs it now and answers an AgentWorkflow to follow, wait for and stop.
511
- # An invalid spec is refused (InvalidRequestError), its details naming
512
- # the field.
513
- def run(spec = nil, idempotency_key: nil, **fields)
514
- body = Fields.convert(spec || fields)
515
- AgentWorkflow.new(@t, @t.json("POST", "/v1/agents/workflows", body: body, key: idempotency_key))
516
- end
517
-
518
- def get(id) = AgentWorkflow.new(@t, @t.json("GET", "/v1/agents/workflows/#{seg(id)}"))
519
-
520
- # The first page, newest first, in a +state+ (one or a list) if given;
521
- # +each+ walks every page.
522
- def list(state: nil, cursor: nil, limit: nil) = workflows_page({ "state" => state, "limit" => limit }, cursor)
523
-
524
- private
525
-
526
- def workflows_page(query, cursor)
527
- body = @t.json("GET", "/v1/agents/workflows", query: query.merge("cursor" => cursor))
528
- Page.new(body["data"].map { |item| Record.new(item) }, body["nextCursor"]) { |after| workflows_page(query, after) }
529
- end
530
- end
531
-
532
- # One workflow. +info+: +id+, +name+, +state+ (running, done, failed or
533
- # stopped), +reason+, +result+ (one step's result as it is, or a JSON
534
- # array of the last phase's results), +parent_session_id+, +spec+, its
535
- # limits, +started+, +version+ (one more on every change), +labels+,
536
- # +phases+ (each +name+, +agent_id+, +total+, +ready+, +pending+,
537
- # +running+, +done+, +failed+), +cost+ and its times.
538
- class AgentWorkflow
539
- POLL_SECONDS = AgentSession::POLL_SECONDS
540
- POLL_MARGIN = AgentSession::POLL_MARGIN
541
-
542
- attr_reader :info
543
-
544
- def initialize(transport, info)
545
- @t = transport
546
- @info = Record.new(info)
547
- end
548
-
549
- def id = @info["id"]
550
- def state = @info["state"]
551
- def ended? = state != "running"
552
- def result = @info["result"]
553
-
554
- # Reads it again.
555
- def refresh
556
- @info = Record.new(@t.json("GET", path))
557
- self
558
- end
559
-
560
- # Each change after version +after+ (0: from the start) as it happens;
561
- # without a block, an Enumerator. Waits on the server and ends once the
562
- # workflow has ended.
563
- def follow(after: 0)
564
- return enum_for(:follow, after: after) unless block_given?
565
-
566
- loop do
567
- now = poll(after)
568
- @info = now
569
- if now["version"] > after
570
- after = now["version"]
571
- yield now
572
- end
573
- return nil if ended?
574
- end
575
- end
576
-
577
- # The workflow once it has ended; a failed one is returned, not raised.
578
- # Waits on the server, with no polling.
579
- def wait
580
- refresh
581
- @info = poll(@info["version"]) until ended?
582
- @info
583
- end
584
-
585
- # The first page of its steps in phase and item order: +phase+, +item+,
586
- # +item_text+, +state+ (pending, running, done, failed, stopped or
587
- # skipped), +reason+, +result+, +session_id+ and times.
588
- def steps(state: nil, cursor: nil, limit: nil) = steps_page({ "state" => state, "limit" => limit }, cursor)
589
-
590
- # Stops it: nothing more starts, and its open sessions are asked to stop.
591
- def stop
592
- @info = Record.new(@t.json("POST", path("/stop"), body: {}))
593
- end
594
-
595
- def inspect = "#<#{self.class.name} #{id} #{state}>"
596
-
597
- private
598
-
599
- def path(suffix = "") = "/v1/agents/workflows/#{Transport.segment(id)}#{suffix}"
600
-
601
- def poll(after)
602
- Record.new(@t.json("GET", path, query: { "after" => after, "wait" => POLL_SECONDS },
603
- timeout: [@t.timeout, POLL_SECONDS + POLL_MARGIN].max))
604
- end
605
-
606
- def steps_page(query, cursor)
607
- body = @t.json("GET", path("/steps"), query: query.merge("cursor" => cursor))
608
- Page.new(body["data"].map { |item| Record.new(item) }, body["nextCursor"]) { |after| steps_page(query, after) }
609
- end
610
- end
611
-
612
- # A page of an agent's memory files; +usage+ is the agent's whole memory,
613
- # every scope: +bytes+, +files+, +limit_bytes+ and +limit_files+.
614
- class AgentMemoryPage < Page
615
- attr_reader :usage
616
-
617
- def initialize(data, next_cursor, usage, &fetch)
618
- super(data, next_cursor, &fetch)
619
- @usage = usage
620
- end
621
- end
622
-
623
- # +runtime.agents.memory+: an agent's built-in memory, text files its
624
- # sessions keep across sessions and search. A +scope+ is whose: "" (the
625
- # default) for what every session of the agent shares, or a session key such
626
- # as "customer:42" for that key's alone. Up to 1 MiB a file, 1 GiB and
627
- # 100,000 files an agent, billed as storage; past them a write is refused
628
- # +memory_full+ (ConflictError).
629
- #
630
- # runtime.agents.memory.write("helpdesk", "faq/refunds.md", "Refunds within 30 days.")
631
- # runtime.agents.memory.search("helpdesk", "refund").each { |hit| puts "#{hit.path}: #{hit.snippet}" }
632
- class AgentMemory < Product
633
- # The first page of an agent's files by scope and path, each with +scope+,
634
- # +path+, +bytes+, +updated_at+ and +updated_by+; every scope unless
635
- # +scope:+ is given. +each+ walks every page.
636
- def list(agent, scope: nil, prefix: nil, cursor: nil, limit: nil)
637
- memory_page(agent, { "scope" => scope, "prefix" => prefix, "limit" => limit }, cursor)
638
- end
639
-
640
- # The files whose words or path match +q+ (words, "a phrase", or, -not),
641
- # best first, each with a +snippet+ and +rank+; every scope unless
642
- # +scope:+ is given.
643
- def search(agent, q, scope: nil, limit: nil)
644
- body = @t.json("GET", "/v1/agents/#{seg(agent)}/memory", query: { "scope" => scope, "q" => q, "limit" => limit })
645
- body["data"].map { |row| Record.new(row) }
646
- end
647
-
648
- # A file with its +content+; none there is NotFoundError.
649
- def read(agent, path, scope: "")
650
- Record.new(@t.json("GET", file(agent), query: { "scope" => scope, "path" => path }))
651
- end
652
-
653
- # Seeds or replaces a file; +created+ says which.
654
- def write(agent, path, content, scope: "")
655
- Record.new(@t.json("PUT", file(agent), query: { "scope" => scope, "path" => path }, body: { "content" => content }))
656
- end
657
-
658
- # Deletes a file; whether there was one.
659
- def delete(agent, path, scope: "")
660
- @t.json("DELETE", file(agent), query: { "scope" => scope, "path" => path })["deleted"] == true
661
- end
662
-
663
- private
664
-
665
- def file(agent) = "/v1/agents/#{seg(agent)}/memory/content"
666
-
667
- def memory_page(agent, query, cursor)
668
- body = @t.json("GET", "/v1/agents/#{seg(agent)}/memory", query: query.merge("cursor" => cursor))
669
- AgentMemoryPage.new(body["data"].map { |item| Record.new(item) }, body["nextCursor"], Record.new(body["usage"] || {})) do |after|
670
- memory_page(agent, query, after)
671
- end
672
- end
673
- end
674
-
675
- # +runtime.agents.templates+: the harnesses an agent can run, each usable
676
- # for either use, and the two uses. +review+ is a CI/CD agent step's
677
- # reviewer, on a +pool+ of Claude accounts.
678
- #
679
- # runtime.agents.templates.map(&:key) # claude-code, codex, gemini-cli, claude-agent-sdk, openai-agents-sdk, review, judge, browser
680
- # runtime.agents.templates["codex"].api_key_secret
681
- # runtime.agents.templates.uses["support"].session_key
682
- # runtime.agents.templates.definition("claude-code", use: "support")
683
- #
684
- # A subscription is for your own team's agents. An agent that serves your
685
- # customers (api or webhook sessions for end users) uses an API key: those
686
- # are the providers' terms, and the API warns +subscription_for_customers+
687
- # on an agent that does not.
688
- class AgentTemplates
689
- include Enumerable
690
-
691
- # The same values as every Runtime SDK and the guide
692
- # (packages/cloud-guide/agent-templates.json).
693
- DATA = {
694
- "templates" => {
695
- "claude-code" => {
696
- "key" => "claude-code",
697
- "title" => "Claude Code",
698
- "command" => "npx -y @anthropic-ai/claude-code --dangerously-skip-permissions --mcp-config ~/.runtime-agent/mcp.json -p \"$(cat ~/.runtime-agent/start.md)\"",
699
- "apiKeySecret" => "ANTHROPIC_API_KEY",
700
- "apiKeyHost" => "api.anthropic.com",
701
- "subscription" => "token: run `claude setup-token` on your own computer (Pro/Max), then `runtime secrets set CLAUDE_CODE_OAUTH_TOKEN` scoped to api.anthropic.com",
702
- "definition" => {
703
- "command" => "npx -y @anthropic-ai/claude-code --dangerously-skip-permissions --mcp-config ~/.runtime-agent/mcp.json -p \"$(cat ~/.runtime-agent/start.md)\"",
704
- "secrets" => ["ANTHROPIC_API_KEY"]
705
- }
706
- },
707
- "codex" => {
708
- "key" => "codex",
709
- "title" => "Codex CLI",
710
- "command" => "npx -y @openai/codex exec --dangerously-bypass-approvals-and-sandbox \"$(cat ~/.runtime-agent/start.md)\"",
711
- "apiKeySecret" => "OPENAI_API_KEY",
712
- "apiKeyHost" => "api.openai.com",
713
- "subscription" => "login once in the sandbox's terminal: `npx -y @openai/codex login --device-auth`, kept in the snapshot or a volume at `~/.codex`",
714
- "definition" => {
715
- "command" => "npx -y @openai/codex exec --dangerously-bypass-approvals-and-sandbox \"$(cat ~/.runtime-agent/start.md)\"",
716
- "secrets" => ["OPENAI_API_KEY"]
717
- }
718
- },
719
- "gemini-cli" => {
720
- "key" => "gemini-cli",
721
- "title" => "Gemini CLI",
722
- "command" => "npx -y @google/gemini-cli --yolo -p \"$(cat ~/.runtime-agent/start.md)\"",
723
- "apiKeySecret" => "GEMINI_API_KEY",
724
- "apiKeyHost" => "generativelanguage.googleapis.com",
725
- "subscription" => "login once in the sandbox's terminal (Sign in with Google), kept at `~/.gemini`",
726
- "definition" => {
727
- "command" => "npx -y @google/gemini-cli --yolo -p \"$(cat ~/.runtime-agent/start.md)\"",
728
- "secrets" => ["GEMINI_API_KEY"]
729
- }
730
- },
731
- "claude-agent-sdk" => {
732
- "key" => "claude-agent-sdk",
733
- "title" => "Claude Agent SDK",
734
- "command" => "python3 ~/agent.py",
735
- "apiKeySecret" => "ANTHROPIC_API_KEY",
736
- "apiKeyHost" => "api.anthropic.com",
737
- "subscription" => nil,
738
- "definition" => {
739
- "command" => "python3 ~/agent.py",
740
- "secrets" => ["ANTHROPIC_API_KEY"]
741
- }
742
- },
743
- "openai-agents-sdk" => {
744
- "key" => "openai-agents-sdk",
745
- "title" => "OpenAI Agents SDK",
746
- "command" => "python3 ~/agent.py",
747
- "apiKeySecret" => "OPENAI_API_KEY",
748
- "apiKeyHost" => "api.openai.com",
749
- "subscription" => nil,
750
- "definition" => {
751
- "command" => "python3 ~/agent.py",
752
- "secrets" => ["OPENAI_API_KEY"]
753
- }
754
- },
755
- "review" => {
756
- "key" => "review",
757
- "title" => "Code review",
758
- "command" => "python3 ~/.runtime-agent/runtime-agent review",
759
- "apiKeySecret" => "ANTHROPIC_API_KEY",
760
- "apiKeyHost" => "api.anthropic.com",
761
- "subscription" => "a token per account: run `claude setup-token` on your own computer (Pro/Max) for each, store each with `runtime secrets set CLAUDE_1` scoped to api.anthropic.com, then name them all in pool (--pool CLAUDE_1 --pool CLAUDE_2)",
762
- "definition" => {
763
- "command" => "python3 ~/.runtime-agent/runtime-agent review",
764
- "pool" => ["ANTHROPIC_API_KEY"],
765
- "vcpu" => 2,
766
- "memoryMiB" => 2048,
767
- "maxSessionSeconds" => 1800
768
- }
769
- },
770
- "judge" => {
771
- "key" => "judge",
772
- "title" => "Your rules",
773
- "command" => "python3 ~/.runtime-agent/runtime-agent judge",
774
- "apiKeySecret" => "ANTHROPIC_API_KEY",
775
- "apiKeyHost" => "api.anthropic.com",
776
- "subscription" => "a token per account, as for review: `runtime secrets set CLAUDE_1` scoped to api.anthropic.com for each, then name them all in pool; its instructions are the rules that block",
777
- "definition" => {
778
- "command" => "python3 ~/.runtime-agent/runtime-agent judge",
779
- "pool" => ["ANTHROPIC_API_KEY"],
780
- "vcpu" => 2,
781
- "memoryMiB" => 2048,
782
- "maxSessionSeconds" => 1800
783
- }
784
- },
785
- "browser" => {
786
- "key" => "browser",
787
- "title" => "Browser task",
788
- "command" => "python3 ~/.runtime-agent/runtime-agent browse",
789
- "apiKeySecret" => "ANTHROPIC_API_KEY",
790
- "apiKeyHost" => "api.anthropic.com",
791
- "subscription" => nil,
792
- "definition" => {
793
- "command" => "python3 ~/.runtime-agent/runtime-agent browse",
794
- "secrets" => ["ANTHROPIC_API_KEY"],
795
- "vcpu" => 2,
796
- "memoryMiB" => 4096,
797
- "maxSessionSeconds" => 1800
798
- }
799
- }
800
- },
801
- "uses" => {
802
- "support" => {
803
- "key" => "support",
804
- "title" => "Your customers",
805
- "sessionKey" => "customer:<id>",
806
- "triggers" => %w[api webhook],
807
- "definition" => {
808
- "template" => "support",
809
- "vcpu" => 1,
810
- "memoryMiB" => 1024,
811
- "idlePauseSeconds" => 10,
812
- "maxConcurrent" => 1000
813
- }
814
- },
815
- "team" => {
816
- "key" => "team",
817
- "title" => "Your team",
818
- "sessionKey" => nil,
819
- "triggers" => %w[slack github],
820
- "definition" => {
821
- "template" => "team",
822
- "vcpu" => 4,
823
- "memoryMiB" => 8192
824
- }
825
- }
826
- }
827
- }.then { |data| JSON.parse(JSON.generate(data), freeze: true) }
828
-
829
- # A definition given as a Record (a template's own) as the Hash it holds.
830
- def self.plain(definition) = definition.is_a?(Record) ? definition.to_h : definition
831
-
832
- # The harness template +key+ (+key+, +title+, +command+, +api_key_secret+,
833
- # +api_key_host+, +subscription+: how to log in on one, or nil, and
834
- # +definition+), or nil.
835
- def [](key) = DATA["templates"][key.to_s]&.then { |template| Record.new(template) }
836
-
837
- def keys = DATA["templates"].keys
838
-
839
- # The harness templates, in order.
840
- def each(&block)
841
- return enum_for(:each) unless block
842
-
843
- DATA["templates"].each_value { |template| block.call(Record.new(template)) }
844
- end
845
-
846
- # The uses, "support" (your customers, driven by your own app: one session
847
- # per end customer under your own key such as "customer:42", paused between
848
- # their messages) and "team" (your team's
849
- # code, from Slack and GitHub): +key+, +title+, +session_key+, +triggers+
850
- # and the +definition+ preset merged over a template's.
851
- def uses = DATA["uses"].transform_values { |use| Record.new(use) }
852
-
853
- # A new definition: the template's, with the use's preset over it. Ready
854
- # for +agents.create(name, definition)+. An unknown key raises
855
- # InvalidRequestError before anything is sent.
856
- def definition(template, use: nil)
857
- found = DATA["templates"][template.to_s] or raise unknown("template", template, DATA["templates"].keys)
858
- out = JSON.parse(JSON.generate(found["definition"]))
859
- return out if use.nil?
860
-
861
- preset = DATA["uses"][use.to_s] or raise unknown("use", use, DATA["uses"].keys)
862
- out.merge(JSON.parse(JSON.generate(preset["definition"])))
863
- end
864
-
865
- # Every template and use as plain JSON data: { "templates" => ..., "uses" => ... }.
866
- def to_h = JSON.parse(JSON.generate(DATA))
867
-
868
- def inspect = "#<#{self.class.name} #{keys.join(", ")}; uses #{DATA["uses"].keys.join(", ")}>"
869
-
870
- private
871
-
872
- def unknown(what, value, known)
873
- InvalidRequestError.new("No agent #{what} is called #{value.inspect}.", code: "invalid_request", status: 400,
874
- hint: "One of: #{known.join(", ")}.")
875
- end
876
- end
877
- end