samagotchi 0.102.0 → 0.104.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 (106) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +93 -1
  3. data/bin/chi +60 -191
  4. data/docs/architecture.md +67 -1
  5. data/docs/cli.md +190 -9
  6. data/docs/configuration.md +7 -1
  7. data/docs/guardrails.md +4 -2
  8. data/docs/internals/context-telemetry.md +6 -2
  9. data/docs/internals/engine.md +5 -2
  10. data/docs/internals/llm-context-forget.md +11 -1
  11. data/docs/internals/participants.md +137 -0
  12. data/docs/internals/remote-sessions.md +429 -0
  13. data/docs/internals/working-set.md +95 -11
  14. data/docs/plugins.md +33 -3
  15. data/docs/sessions.md +16 -7
  16. data/docs/sub-agent.md +16 -0
  17. data/docs/testing.md +68 -4
  18. data/lib/samagotchi/answer_command.rb +27 -25
  19. data/lib/samagotchi/bridge.rb +31 -7
  20. data/lib/samagotchi/bridge_client/event_stream.rb +86 -12
  21. data/lib/samagotchi/bridge_client/stream_request.rb +77 -0
  22. data/lib/samagotchi/bridge_client.rb +26 -39
  23. data/lib/samagotchi/bundles/claude-peer/manifest.yml +2 -2
  24. data/lib/samagotchi/bundles/claude-peer/scripts/pair +30 -1
  25. data/lib/samagotchi/bundles/codex-peer/manifest.yml +2 -2
  26. data/lib/samagotchi/bundles/codex-peer/scripts/pair +49 -4
  27. data/lib/samagotchi/bundles/guardrails/guardrails/rules.yml +7 -4
  28. data/lib/samagotchi/bundles/guardrails/manifest.yml +1 -1
  29. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  30. data/lib/samagotchi/chi_invocation.rb +40 -0
  31. data/lib/samagotchi/cli/command.rb +3 -2
  32. data/lib/samagotchi/cli/flags.rb +5 -0
  33. data/lib/samagotchi/cli/parent_wait.rb +22 -13
  34. data/lib/samagotchi/context_command.rb +80 -73
  35. data/lib/samagotchi/context_status.rb +15 -2
  36. data/lib/samagotchi/engine.rb +28 -14
  37. data/lib/samagotchi/guardrail_wiring.rb +7 -1
  38. data/lib/samagotchi/idle_recap.rb +8 -2
  39. data/lib/samagotchi/idle_scheduler.rb +34 -9
  40. data/lib/samagotchi/kernel_loop.rb +21 -2
  41. data/lib/samagotchi/launch_mode.rb +26 -0
  42. data/lib/samagotchi/llm/chat_loop.rb +8 -1
  43. data/lib/samagotchi/llm_context_forget.rb +13 -6
  44. data/lib/samagotchi/note_command.rb +8 -7
  45. data/lib/samagotchi/owner_lock.rb +65 -5
  46. data/lib/samagotchi/parent_report.rb +55 -43
  47. data/lib/samagotchi/participants.rb +122 -0
  48. data/lib/samagotchi/remote_attach_command.rb +119 -0
  49. data/lib/samagotchi/remote_command.rb +170 -0
  50. data/lib/samagotchi/remotes.rb +130 -0
  51. data/lib/samagotchi/run_options.rb +245 -0
  52. data/lib/samagotchi/send_command/busy.rb +58 -0
  53. data/lib/samagotchi/send_command/parent_gate.rb +23 -10
  54. data/lib/samagotchi/send_command/wait_target.rb +16 -3
  55. data/lib/samagotchi/send_command.rb +173 -108
  56. data/lib/samagotchi/session.rb +38 -9
  57. data/lib/samagotchi/session_access/contract.rb +167 -0
  58. data/lib/samagotchi/session_access/dispatch.rb +152 -0
  59. data/lib/samagotchi/session_access/http_transport.rb +109 -0
  60. data/lib/samagotchi/session_access/local.rb +400 -0
  61. data/lib/samagotchi/session_access/remote.rb +734 -0
  62. data/lib/samagotchi/session_access/web_bridge_client.rb +236 -0
  63. data/lib/samagotchi/session_access.rb +223 -0
  64. data/lib/samagotchi/session_archive_command.rb +9 -5
  65. data/lib/samagotchi/session_commands.rb +20 -15
  66. data/lib/samagotchi/session_continue.rb +1 -1
  67. data/lib/samagotchi/session_delete_command.rb +8 -4
  68. data/lib/samagotchi/session_inbox.rb +18 -9
  69. data/lib/samagotchi/session_manager.rb +27 -6
  70. data/lib/samagotchi/session_setup.rb +11 -6
  71. data/lib/samagotchi/sessions_command.rb +36 -14
  72. data/lib/samagotchi/share_command.rb +174 -0
  73. data/lib/samagotchi/terminal_ui/attach_launcher.rb +66 -17
  74. data/lib/samagotchi/terminal_ui/attach_link.rb +114 -0
  75. data/lib/samagotchi/terminal_ui/attached_loop.rb +155 -87
  76. data/lib/samagotchi/terminal_ui/formatting.rb +13 -1
  77. data/lib/samagotchi/terminal_ui/local_link.rb +135 -0
  78. data/lib/samagotchi/terminal_ui/remote_connector.rb +66 -0
  79. data/lib/samagotchi/terminal_ui/remote_link.rb +245 -0
  80. data/lib/samagotchi/terminal_ui/version_lines.rb +28 -3
  81. data/lib/samagotchi/terminal_ui.rb +6 -3
  82. data/lib/samagotchi/testing/waiting.rb +92 -9
  83. data/lib/samagotchi/title_command.rb +9 -11
  84. data/lib/samagotchi/tools/task_runtime.rb +17 -3
  85. data/lib/samagotchi/version.rb +1 -1
  86. data/lib/samagotchi/web/app.rb +530 -126
  87. data/lib/samagotchi/web/grants.rb +302 -0
  88. data/lib/samagotchi/web/participant_access.rb +286 -0
  89. data/lib/samagotchi/web/principal.rb +29 -0
  90. data/lib/samagotchi/web/public/data.js +3 -2
  91. data/lib/samagotchi/web/public/index.html +20 -4
  92. data/lib/samagotchi/web/public/stage_frame.js +7 -2
  93. data/lib/samagotchi/web/public/stage_view.js +3 -2
  94. data/lib/samagotchi/web/public/stream_handlers.js +3 -1
  95. data/lib/samagotchi/web/public/working_set.js +159 -28
  96. data/lib/samagotchi/web/public/working_set_rail.js +39 -12
  97. data/lib/samagotchi/web/public/working_set_view.js +91 -33
  98. data/lib/samagotchi/web/server.rb +3 -1
  99. data/lib/samagotchi/web/session_access_routes.rb +459 -0
  100. data/lib/samagotchi/worker.rb +26 -5
  101. data/lib/samagotchi/worker_sidecar.rb +12 -5
  102. data/lib/samagotchi/working_set.rb +88 -14
  103. data/lib/samagotchi/working_set_command.rb +133 -30
  104. data/lib/samagotchi/working_set_pin.rb +34 -0
  105. data/lib/samagotchi/working_set_steer.rb +191 -27
  106. metadata +28 -1
@@ -0,0 +1,167 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../config"
4
+
5
+ module Samagotchi
6
+ module SessionAccess
7
+ # Which session commands and flags run against another machine's
8
+ # sessions (chi --remote NAME …, CHI_REMOTE; SessionAccess::Dispatch)
9
+ # and which run on this machine only (refused under a remote, exit 2:
10
+ # "chi <cmd> runs on this machine only: run it on <remote>"). The v1 scope is the remote-sessions plan's
11
+ # D3: send, answer, note, a session's context (add, push, ls, show, rm)
12
+ # and sessions list/stop/restart/archive/unarchive/delete, and chi share
13
+ # (the shared-sessions plan's P2); the rest
14
+ # stays local. bin/chi's subcommands that act on the machine, not on
15
+ # sessions, are MACHINE. The run flags (chi --attach, -p, --resume: a
16
+ # session in this terminal, a remote attach there) are RUN's.
17
+ #
18
+ # spec/session_access_contract_spec.rb fails when a subcommand, one of
19
+ # its subcommands or one of a supported one's flags is in neither, or
20
+ # a run flag (RunOptions.switches) is in neither RUN list and isn't a
21
+ # config registry flag.
22
+ module Contract
23
+ SUPPORTED = :supported
24
+ LOCAL_ONLY = :local_only
25
+
26
+ # bin/chi subcommands that act on this machine: never sessions. chi
27
+ # remote (this machine's list of remotes) runs here under a remote too
28
+ # (Dispatch); the others are refused there.
29
+ MACHINE = %w[bootstrap update models desktop memory bundle remote].freeze
30
+
31
+ # "command", "command sub" or either with a flag (its long name) →
32
+ # SUPPORTED or LOCAL_ONLY. A LOCAL_ONLY command or subcommand lists
33
+ # no flags: all of it is local.
34
+ TABLE = {
35
+ "send" => SUPPORTED,
36
+ "send --message" => SUPPORTED,
37
+ "send --new" => SUPPORTED,
38
+ # Required with --new under a remote (D4: no laptop path guessed).
39
+ "send --dir" => SUPPORTED,
40
+ "send --continues" => SUPPORTED,
41
+ "send --model" => SUPPORTED,
42
+ "send --llm-context" => SUPPORTED,
43
+ "send --llm-context-apply" => SUPPORTED,
44
+ "send --llm-context-budget" => SUPPORTED,
45
+ "send --thinking" => SUPPORTED,
46
+ "send --toolkit" => SUPPORTED,
47
+ "send --tool" => SUPPORTED,
48
+ "send --no-tool" => SUPPORTED,
49
+ "send --set" => SUPPORTED,
50
+ "send --parent-answers" => SUPPORTED,
51
+ "send --image" => SUPPORTED,
52
+ "send --wait" => SUPPORTED,
53
+ "send --cut" => SUPPORTED,
54
+ "send --queue" => SUPPORTED,
55
+ "send --timeout" => SUPPORTED,
56
+ "send --format" => SUPPORTED,
57
+ "send --turn" => SUPPORTED,
58
+ # Refused on both (there is no --all).
59
+ "send --all" => SUPPORTED,
60
+
61
+ "answer" => SUPPORTED,
62
+ "answer --question" => SUPPORTED,
63
+ "answer --option" => SUPPORTED,
64
+ "answer --text" => SUPPORTED,
65
+ "answer --dismiss" => SUPPORTED,
66
+ "answer --timeout" => SUPPORTED,
67
+ "answer --format" => SUPPORTED,
68
+
69
+ "note" => SUPPORTED,
70
+ "note --message" => SUPPORTED,
71
+ "note --source" => SUPPORTED,
72
+ "note --all" => SUPPORTED,
73
+
74
+ "context" => SUPPORTED,
75
+ "context add" => SUPPORTED,
76
+ "context add --cmd" => SUPPORTED,
77
+ "context add --push" => SUPPORTED,
78
+ "context add --every" => SUPPORTED,
79
+ "context add --why" => SUPPORTED,
80
+ "context add --hint" => SUPPORTED,
81
+ "context add --project" => LOCAL_ONLY,
82
+ "context push" => SUPPORTED,
83
+ "context push --message" => SUPPORTED,
84
+ "context push --project" => LOCAL_ONLY,
85
+ "context ls" => SUPPORTED,
86
+ "context ls --format" => SUPPORTED,
87
+ "context ls --project" => LOCAL_ONLY,
88
+ "context show" => SUPPORTED,
89
+ "context show --json" => SUPPORTED,
90
+ "context show --project" => LOCAL_ONLY,
91
+ "context rm" => SUPPORTED,
92
+ "context rm --project" => LOCAL_ONLY,
93
+ "context refresh" => LOCAL_ONLY,
94
+ "context mute" => LOCAL_ONLY,
95
+ "context unmute" => LOCAL_ONLY,
96
+
97
+ "sessions" => SUPPORTED,
98
+ "sessions list" => SUPPORTED,
99
+ "sessions list --sort" => SUPPORTED,
100
+ "sessions list --order" => SUPPORTED,
101
+ "sessions list --limit" => SUPPORTED,
102
+ "sessions list --cwd" => SUPPORTED,
103
+ "sessions list --format" => SUPPORTED,
104
+ # Remotely every project's by default (D4); --scope=project needs
105
+ # --cwd there.
106
+ "sessions list --scope" => SUPPORTED,
107
+ "sessions list --live" => SUPPORTED,
108
+ "sessions list --archived" => SUPPORTED,
109
+ "sessions stop" => SUPPORTED,
110
+ "sessions restart" => SUPPORTED,
111
+ "sessions archive" => SUPPORTED,
112
+ "sessions unarchive" => SUPPORTED,
113
+ "sessions delete" => SUPPORTED,
114
+ "sessions delete --force" => SUPPORTED,
115
+ "sessions prune" => LOCAL_ONLY,
116
+ "sessions clean" => LOCAL_ONLY,
117
+ "sessions stats" => LOCAL_ONLY,
118
+
119
+ # Participants (docs/internals/participants.md): the remote's link,
120
+ # through its chi web's participants routes.
121
+ "share" => SUPPORTED,
122
+ "share --name" => SUPPORTED,
123
+ "share --agent" => SUPPORTED,
124
+ "share --expires" => SUPPORTED,
125
+ "share ls" => SUPPORTED,
126
+ "share ls --format" => SUPPORTED,
127
+ "share revoke" => SUPPORTED,
128
+ "share revoke --all" => SUPPORTED,
129
+
130
+ "broadcast" => LOCAL_ONLY
131
+ }.freeze
132
+
133
+ # bin/chi's run flags under a remote (chi --remote NAME --attach ID,
134
+ # RemoteAttachCommand): what a remote attach takes, and what runs
135
+ # this machine's REPL or reads this machine's files (P4-D2..D4). A
136
+ # config registry flag (--recap-base-url …) is this machine's
137
+ # config: LOCAL_ONLY without being listed.
138
+ RUN = {
139
+ SUPPORTED => %w[--attach --resume -p --prompt --shared --model --thinking --llm-context --llm-context-apply
140
+ --llm-context-budget --toolkit --tool --no-tool --set --parent-answers --no-interrupt
141
+ --no-default-input --dir --version -h --help],
142
+ LOCAL_ONLY => %w[--no-shared --non-interactive -v --verbose --append-system-prompt --memory --mute --profile
143
+ --port --open --new-token --scope --web-markdown --no-web-markdown]
144
+ }.freeze
145
+ # A short run flag's name in a refusal.
146
+ RUN_WORDS = { "-v" => "--verbose" }.freeze
147
+
148
+ module_function
149
+
150
+ # @param flag [String] a run flag as RunOptions.switches lists it
151
+ # @return [Symbol, nil] SUPPORTED or LOCAL_ONLY; nil: not a run flag
152
+ def run_status(flag)
153
+ RUN.each { |status, flags| return status if flags.include?(flag) }
154
+ LOCAL_ONLY if Config.cli_entries.any? { |entry| [entry.cli_flag, entry.cli_flag.sub("--", "--no-")].include?(flag) }
155
+ end
156
+
157
+ # @param words [Array<String>] a command, maybe its subcommand, maybe
158
+ # a flag's long name: status("context", "add", "--cmd")
159
+ # @return [Symbol, nil] SUPPORTED, LOCAL_ONLY, or nil when not listed
160
+ def status(*words) = TABLE[words.join(" ")]
161
+
162
+ # Whether +words+ run against a remote: the command, its subcommand
163
+ # and the flag each listed SUPPORTED.
164
+ def supported?(*words) = (1..words.size).all? { |n| status(*words.first(n)) == SUPPORTED }
165
+ end
166
+ end
167
+ end
@@ -0,0 +1,152 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../session_access"
4
+ require_relative "contract"
5
+ require_relative "../remotes"
6
+ require_relative "../cli/exit"
7
+
8
+ module Samagotchi
9
+ module SessionAccess
10
+ # bin/chi's front for chi --remote NAME … and CHI_REMOTE=NAME: takes the
11
+ # flag off the front of the arguments (before the subcommand lookup),
12
+ # names the remote (the flag beats the env; no default remote), refuses
13
+ # what runs on this machine only (Contract) and runs a session command
14
+ # with a Remote for its SessionAccess. chi remote itself, --version and
15
+ # --help always run here.
16
+ class Dispatch
17
+ FLAG = "--remote"
18
+ ENV_KEY = "CHI_REMOTE"
19
+ # Run here whatever the remote: chi remote manages the remotes.
20
+ ALWAYS_HERE = %w[remote].freeze
21
+ # bin/chi's own words besides its SUBCOMMANDS (a refusal names them).
22
+ OWN_WORDS = %w[web scratch self].freeze
23
+ HELP = %w[--version -h --help].freeze
24
+ # --non-interactive's refusal: what runs one turn there instead.
25
+ ONE_TURN = "(%s send --new --dir D -m TEXT --wait runs one turn there)"
26
+
27
+ # A usage error in the flag itself (--remote with no name, a bad one).
28
+ class Usage < StandardError; end
29
+
30
+ # The flag (any number of them at the front; the last wins) taken off
31
+ # +argv+, and the remote it and +env+ name.
32
+ # @return [Dispatch]
33
+ # @raise [Usage]
34
+ def self.from(argv, env: ENV)
35
+ rest = argv.dup
36
+ flag = nil
37
+ while (arg = rest.first) && (arg == FLAG || arg.start_with?("#{FLAG}="))
38
+ rest.shift
39
+ flag = arg == FLAG ? rest.shift : arg.delete_prefix("#{FLAG}=")
40
+ raise Usage, "#{FLAG} needs a remote's name (chi remote ls lists them)" if flag.nil? || flag.strip.empty? || flag.start_with?("-")
41
+ end
42
+ from_env = env.fetch(ENV_KEY, "").to_s.strip
43
+ new(rest, remote: flag || (from_env.empty? ? nil : from_env))
44
+ end
45
+
46
+ attr_reader :argv, :remote
47
+
48
+ def initialize(argv, remote:)
49
+ @argv = argv
50
+ @remote = remote
51
+ end
52
+
53
+ def remote? = !@remote.nil?
54
+
55
+ # Whether the arguments are run flags, no subcommand: a session in
56
+ # this terminal (bin/chi's RunOptions parse them; under a remote,
57
+ # RemoteAttachCommand runs them).
58
+ def run_flags?
59
+ command = @argv.first
60
+ command.nil? || command.start_with?("-")
61
+ end
62
+
63
+ # Whether the arguments run here as they would without a remote: chi
64
+ # remote, --version, --help.
65
+ def here?
66
+ first = @argv.first
67
+ ALWAYS_HERE.include?(first) || (@argv.size == 1 && HELP.include?(first))
68
+ end
69
+
70
+ # The one refusal of a command or flag that runs on this machine only,
71
+ # or nil when the Contract lets it run against the remote.
72
+ # @return [String, nil]
73
+ def refusal
74
+ words = local_words or return nil
75
+
76
+ line = "chi #{words} runs on this machine only: run it on #{@remote}"
77
+ words == "--non-interactive" ? "#{line} #{format(ONE_TURN, "chi --remote #{@remote}")}" : line
78
+ end
79
+
80
+ # The session command against the remote: refused (exit 2), or run
81
+ # with a Remote. A failure to reach it is the command's line, exit 1.
82
+ # @param subcommands [Hash] bin/chi's SUBCOMMANDS
83
+ # @return [Integer] the exit status
84
+ def run(subcommands, stderr: $stderr, transport: nil)
85
+ command = @argv.first
86
+ unless command.nil? || command.start_with?("-") || subcommands.key?(command) || OWN_WORDS.include?(command)
87
+ stderr.puts("Error: unknown command #{command} (see chi --help)")
88
+ return CLI::Exit::FAILED
89
+ end
90
+ if (message = refusal)
91
+ stderr.puts("Error: #{message}")
92
+ return CLI::Exit::USAGE
93
+ end
94
+
95
+ entry = Remotes.find(Remotes.check_name!(@remote))
96
+ path, klass = subcommands.fetch(@argv.first)
97
+ require path
98
+ access = Remote.new(entry, transport: transport)
99
+ Samagotchi.const_get(klass).new(@argv[1..] || [], access: access).run
100
+ rescue Remotes::Invalid => e
101
+ stderr.puts("Error: #{e.message}")
102
+ CLI::Exit::USAGE
103
+ rescue RemoteFailed => e
104
+ stderr.puts("chi #{@argv.first}: #{e.message}")
105
+ CLI::Exit::FAILED
106
+ end
107
+
108
+ private
109
+
110
+ # The words that run here only: the command (and its subcommand, a
111
+ # flag) the Contract lists local_only, a machine command, or a run
112
+ # flag Contract::RUN lists local_only. nil: supported.
113
+ def local_words
114
+ command = @argv.first
115
+ return run_words if run_flags?
116
+ return command if Contract::MACHINE.include?(command) || Contract.status(command).nil?
117
+ return command if Contract.status(command) == Contract::LOCAL_ONLY
118
+
119
+ sub = @argv[1] if Contract::TABLE.key?("#{command} #{@argv[1]}")
120
+ return "#{command} #{sub}" if sub && Contract.status(command, sub) == Contract::LOCAL_ONLY
121
+
122
+ prefix = [command, sub].compact
123
+ flags.each do |flag|
124
+ return [*prefix, flag].join(" ") if Contract.status(*prefix, flag) == Contract::LOCAL_ONLY
125
+ end
126
+ nil
127
+ end
128
+
129
+ # The long flags given, up to a "--".
130
+ def flags
131
+ @argv.drop(1).take_while { |arg| arg != "--" }.select { |arg| arg.start_with?("--") }.map { |arg| arg.split("=", 2).first }
132
+ end
133
+
134
+ # The first local-only run flag, a value (-p TEXT, --model NAME)
135
+ # never read as one. An unknown flag is the parser's to refuse.
136
+ def run_words
137
+ require_relative "../run_options"
138
+ values = RunOptions.value_switches
139
+ words = @argv.take_while { |arg| arg != "--" }
140
+ index = 0
141
+ while index < words.size
142
+ arg = words[index]
143
+ flag = arg.start_with?("--") ? arg.split("=", 2).first : arg[0, 2]
144
+ return Contract::RUN_WORDS.fetch(flag, flag) if arg.start_with?("-") && Contract.run_status(flag) == Contract::LOCAL_ONLY
145
+
146
+ index += values.include?(arg) ? 2 : 1
147
+ end
148
+ nil
149
+ end
150
+ end
151
+ end
152
+ end
@@ -0,0 +1,109 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "uri"
6
+ require "openssl"
7
+ require_relative "../session_access"
8
+
9
+ module Samagotchi
10
+ module SessionAccess
11
+ # A remote's chi web over HTTP (Net::HTTP), its access token as
12
+ # Authorization: Bearer: one request per call, each on its own
13
+ # connection (a command makes a handful). A connection that fails
14
+ # raises RemoteFailed naming the remote and why.
15
+ class HTTPTransport
16
+ # One answer: the status, the body, and the body read as JSON (nil
17
+ # when it isn't).
18
+ Reply = Data.define(:status, :body, :json) do
19
+ def self.of(status, body)
20
+ json = begin
21
+ JSON.parse(body.to_s)
22
+ rescue JSON::ParserError
23
+ nil
24
+ end
25
+ new(status: status.to_i, body: body.to_s, json: json)
26
+ end
27
+
28
+ def error = json.is_a?(Hash) ? json["error"] : nil
29
+ end
30
+
31
+ OPEN_TIMEOUT = 5
32
+ # Above chi web's longest answer (a wait route's 30 s, a create's
33
+ # wait for its worker).
34
+ READ_TIMEOUT = 75
35
+
36
+ # @param entry [Remotes::Entry]
37
+ def initialize(entry, open_timeout: OPEN_TIMEOUT, read_timeout: READ_TIMEOUT)
38
+ @entry = entry
39
+ @uri = URI(entry.url)
40
+ @open_timeout = open_timeout
41
+ @read_timeout = read_timeout
42
+ end
43
+
44
+ def inspect = "#<#{self.class.name} #{@entry.label}>"
45
+
46
+ # @param method [Symbol] :get, :post, :delete
47
+ # @param path [String] "/api/…"
48
+ # @param query [Hash, nil] the query's parameters (nil values left out)
49
+ # @param body [Hash, nil] sent as JSON
50
+ # @param raw [String, nil] sent as is (an image), with +content_type+
51
+ # @param read_timeout [Numeric, nil] this request's, instead of the
52
+ # transport's (a remote attach's turn, its join reads)
53
+ # @return [Reply]
54
+ # @raise [RemoteFailed] it could not be asked
55
+ def call(method, path, query: nil, body: nil, raw: nil, content_type: nil, read_timeout: nil)
56
+ read_timeout ||= @read_timeout
57
+ request = build(method, path, query)
58
+ request["Authorization"] = "Bearer #{@entry.token}" if @entry.token
59
+ request["Accept"] = "application/json"
60
+ if raw
61
+ request["Content-Type"] = content_type || "application/octet-stream"
62
+ request.body = raw
63
+ elsif body
64
+ request["Content-Type"] = "application/json"
65
+ request.body = JSON.generate(body)
66
+ elsif method != :get
67
+ request["Content-Length"] = "0"
68
+ end
69
+ response = http(read_timeout).request(request)
70
+ Reply.of(response.code, response.body)
71
+ rescue Errno::ECONNREFUSED
72
+ failed("connection refused")
73
+ rescue Net::OpenTimeout, Errno::ETIMEDOUT
74
+ failed("no answer within #{@open_timeout} s")
75
+ rescue Net::ReadTimeout
76
+ failed("it took the request but sent no answer within #{read_timeout} s")
77
+ rescue SocketError => e
78
+ failed(e.message.include?("getaddrinfo") ? "can't find host #{@uri.host}" : e.message)
79
+ rescue Errno::EHOSTUNREACH, Errno::ENETUNREACH
80
+ failed("host unreachable")
81
+ rescue OpenSSL::SSL::SSLError => e
82
+ failed("TLS failed: #{e.message}")
83
+ rescue IOError, SystemCallError => e
84
+ failed("the connection broke (#{e.class.name.split("::").last})")
85
+ end
86
+
87
+ private
88
+
89
+ def http(read_timeout)
90
+ Net::HTTP.new(@uri.host, @uri.port).tap do |http|
91
+ http.use_ssl = @uri.scheme == "https"
92
+ http.open_timeout = @open_timeout
93
+ http.read_timeout = read_timeout
94
+ http.write_timeout = read_timeout
95
+ http.max_retries = 0
96
+ end
97
+ end
98
+
99
+ def build(method, path, query)
100
+ target = path
101
+ params = query&.compact
102
+ target = "#{path}?#{URI.encode_www_form(params)}" if params && !params.empty?
103
+ { get: Net::HTTP::Get, post: Net::HTTP::Post, delete: Net::HTTP::Delete }.fetch(method).new(target)
104
+ end
105
+
106
+ def failed(reason) = raise(RemoteFailed, "#{@entry.label}: #{reason}")
107
+ end
108
+ end
109
+ end