samagotchi 0.182.0 → 0.184.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +107 -1
- data/bin/chi +3 -1
- data/docs/architecture.md +22 -11
- data/docs/bundle-authoring.md +1 -1
- data/docs/bundles.md +103 -4
- data/docs/cli.md +28 -6
- data/docs/configuration.md +4 -2
- data/docs/guardrails.md +16 -1
- data/docs/internals/block-renderers.md +58 -3
- data/docs/internals/bridge.md +14 -6
- data/docs/internals/bundles.md +26 -5
- data/docs/internals/engine.md +20 -9
- data/docs/internals/participants.md +1 -1
- data/docs/internals/prompt-caching.md +8 -1
- data/docs/internals/remote-sessions.md +40 -5
- data/docs/internals/web-frontend.md +96 -31
- data/docs/internals/web-push.md +11 -0
- data/docs/internals/working-set.md +239 -7
- data/docs/mcp-server.md +84 -0
- data/docs/memory.md +2 -1
- data/docs/plugins.md +309 -22
- data/docs/scheduling.md +14 -0
- data/docs/sessions.md +4 -4
- data/docs/sub-agent.md +9 -0
- data/docs/testing.md +3 -1
- data/docs/thin-clients.md +165 -0
- data/lib/samagotchi/bridge/pending_card.rb +4 -3
- data/lib/samagotchi/bridge/sse_writer.rb +16 -15
- data/lib/samagotchi/bridge.rb +59 -68
- data/lib/samagotchi/bridge_client.rb +12 -4
- data/lib/samagotchi/bundle_command/api_calls.rb +1 -1
- data/lib/samagotchi/bundle_command/check.rb +55 -20
- data/lib/samagotchi/bundle_command.rb +50 -21
- data/lib/samagotchi/bundle_manifest.rb +105 -4
- data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
- data/lib/samagotchi/bundles/mcp/client.rb +260 -0
- data/lib/samagotchi/bundles/mcp/content.rb +107 -0
- data/lib/samagotchi/bundles/mcp/http_client.rb +432 -0
- data/lib/samagotchi/bundles/mcp/manifest.yml +13 -5
- data/lib/samagotchi/bundles/mcp/oauth.rb +814 -0
- data/lib/samagotchi/bundles/mcp/plugin.rb +556 -574
- data/lib/samagotchi/bundles/mcp/tools.rb +232 -0
- data/lib/samagotchi/bundles/system/config_modification_protocol.md +10 -2
- data/lib/samagotchi/bundles/system/manifest.yml +3 -3
- data/lib/samagotchi/bundles/system/self_map.md +7 -2
- data/lib/samagotchi/cli/parent_wait.rb +5 -3
- data/lib/samagotchi/command_intake.rb +7 -0
- data/lib/samagotchi/commands/registry.rb +8 -3
- data/lib/samagotchi/continue_offer.rb +24 -15
- data/lib/samagotchi/engine/block_fix.rb +4 -4
- data/lib/samagotchi/engine/cards.rb +14 -5
- data/lib/samagotchi/engine/events.rb +10 -15
- data/lib/samagotchi/engine/models.rb +1 -1
- data/lib/samagotchi/engine/plugins.rb +3 -0
- data/lib/samagotchi/engine/recap.rb +1 -1
- data/lib/samagotchi/engine/session.rb +14 -6
- data/lib/samagotchi/engine/side_requests.rb +1 -1
- data/lib/samagotchi/engine/sign_in.rb +142 -0
- data/lib/samagotchi/engine/turn_end.rb +3 -3
- data/lib/samagotchi/engine/turn_helpers.rb +4 -3
- data/lib/samagotchi/engine.rb +43 -27
- data/lib/samagotchi/engine_snapshots.rb +1 -1
- data/lib/samagotchi/guardrail_wiring.rb +3 -1
- data/lib/samagotchi/guardrails/protected_paths.rb +51 -2
- data/lib/samagotchi/guardrails/verdict.rb +3 -2
- data/lib/samagotchi/hold_stop.rb +4 -4
- data/lib/samagotchi/idle_recap.rb +19 -11
- data/lib/samagotchi/idle_reminders.rb +7 -5
- data/lib/samagotchi/idle_scheduler.rb +7 -10
- data/lib/samagotchi/installed_bundles/dir.rb +37 -0
- data/lib/samagotchi/installed_bundles/manifest.rb +7 -1
- data/lib/samagotchi/installed_bundles/plugin_ref.rb +9 -5
- data/lib/samagotchi/installed_bundles/record.rb +3 -2
- data/lib/samagotchi/installed_bundles/standing.rb +3 -1
- data/lib/samagotchi/llm/http.rb +96 -5
- data/lib/samagotchi/mcp_command.rb +110 -0
- data/lib/samagotchi/mcp_server/http.rb +112 -0
- data/lib/samagotchi/mcp_server/protocol.rb +263 -0
- data/lib/samagotchi/mcp_server/stdio.rb +93 -0
- data/lib/samagotchi/mcp_server/text.rb +155 -0
- data/lib/samagotchi/mcp_server/tools.rb +246 -0
- data/lib/samagotchi/memory_bundle/asset_installer.rb +40 -12
- data/lib/samagotchi/memory_bundle/builder.rb +20 -2
- data/lib/samagotchi/memory_bundle/installed_copy.rb +1 -1
- data/lib/samagotchi/memory_bundle/installer.rb +16 -3
- data/lib/samagotchi/memory_bundle/provenance.rb +18 -1
- data/lib/samagotchi/memory_bundle/shas.rb +6 -4
- data/lib/samagotchi/memory_bundle/shipped_update.rb +7 -3
- data/lib/samagotchi/memory_bundle/status.rb +15 -6
- data/lib/samagotchi/memory_bundle/uninstaller.rb +9 -4
- data/lib/samagotchi/model_notes.rb +34 -12
- data/lib/samagotchi/plugin/api.rb +6 -1
- data/lib/samagotchi/plugin/card.rb +36 -11
- data/lib/samagotchi/plugin/context.rb +63 -6
- data/lib/samagotchi/plugin/http.rb +40 -15
- data/lib/samagotchi/plugin/http_errors.rb +15 -0
- data/lib/samagotchi/plugin/http_stream.rb +86 -0
- data/lib/samagotchi/plugin/http_transport.rb +58 -16
- data/lib/samagotchi/plugin/loader.rb +18 -11
- data/lib/samagotchi/plugin/secrets.rb +266 -0
- data/lib/samagotchi/plugin/sign_in.rb +392 -0
- data/lib/samagotchi/plugin/sse_reader.rb +103 -0
- data/lib/samagotchi/prompt_files.rb +11 -4
- data/lib/samagotchi/prompt_layout.rb +88 -0
- data/lib/samagotchi/prompt_part.rb +82 -20
- data/lib/samagotchi/queued_command.rb +28 -4
- data/lib/samagotchi/recap_setup.rb +13 -4
- data/lib/samagotchi/ref.rb +3 -2
- data/lib/samagotchi/relay_verifier.rb +8 -7
- data/lib/samagotchi/relay_watcher.rb +4 -4
- data/lib/samagotchi/reply_wait.rb +6 -3
- data/lib/samagotchi/run_options.rb +2 -1
- data/lib/samagotchi/schedule_command.rb +18 -4
- data/lib/samagotchi/schedules.rb +40 -8
- data/lib/samagotchi/send_command.rb +54 -41
- data/lib/samagotchi/session_access/ask.rb +285 -0
- data/lib/samagotchi/session_access/contract.rb +5 -0
- data/lib/samagotchi/session_access/exchange/token.rb +101 -0
- data/lib/samagotchi/session_access/exchange.rb +176 -0
- data/lib/samagotchi/session_access/local.rb +34 -6
- data/lib/samagotchi/session_access/remote.rb +4 -1
- data/lib/samagotchi/session_command_catalog.rb +10 -0
- data/lib/samagotchi/session_commands.rb +17 -0
- data/lib/samagotchi/session_config.rb +4 -4
- data/lib/samagotchi/session_inbox.rb +15 -0
- data/lib/samagotchi/session_manager/delivery.rb +8 -4
- data/lib/samagotchi/session_observer.rb +27 -0
- data/lib/samagotchi/steer_cut.rb +4 -3
- data/lib/samagotchi/system_prompt.rb +196 -161
- data/lib/samagotchi/terminal_ui/attached_loop/sending.rb +4 -1
- data/lib/samagotchi/terminal_ui/formatting.rb +15 -0
- data/lib/samagotchi/testing/boundary.rb +4 -0
- data/lib/samagotchi/testing/bundle.rb +48 -2
- data/lib/samagotchi/testing/fake_http.rb +60 -15
- data/lib/samagotchi/testing/host.rb +4 -1
- data/lib/samagotchi/testing/recorder.rb +45 -5
- data/lib/samagotchi/tools/memory.rb +11 -3
- data/lib/samagotchi/tools/tool_index.rb +14 -3
- data/lib/samagotchi/turn_stages/warmup.rb +2 -2
- data/lib/samagotchi/version.rb +1 -1
- data/lib/samagotchi/web/app.rb +9 -8
- data/lib/samagotchi/web/ask_routes.rb +362 -0
- data/lib/samagotchi/web/mcp_route.rb +91 -0
- data/lib/samagotchi/web/public/app.js +2 -3
- data/lib/samagotchi/web/public/block_frame.js +72 -11
- data/lib/samagotchi/web/public/block_host.js +44 -8
- data/lib/samagotchi/web/public/block_regions.js +126 -0
- data/lib/samagotchi/web/public/card.js +22 -9
- data/lib/samagotchi/web/public/card_actions.js +21 -0
- data/lib/samagotchi/web/public/card_kinds.js +1 -1
- data/lib/samagotchi/web/public/card_registry.js +3 -2
- data/lib/samagotchi/web/public/data.js +15 -12
- data/lib/samagotchi/web/public/delete_sheet.js +231 -169
- data/lib/samagotchi/web/public/diagram_wiring.js +28 -0
- data/lib/samagotchi/web/public/format.js +3 -0
- data/lib/samagotchi/web/public/index.html +52 -7
- data/lib/samagotchi/web/public/more_sheet.js +6 -4
- data/lib/samagotchi/web/public/picture_regions.js +243 -0
- data/lib/samagotchi/web/public/picture_viewer.js +113 -12
- data/lib/samagotchi/web/public/refs.js +5 -3
- data/lib/samagotchi/web/public/region_hit.js +144 -0
- data/lib/samagotchi/web/public/removal_sheet_model.js +274 -0
- data/lib/samagotchi/web/public/running_tasks.js +3 -17
- data/lib/samagotchi/web/public/session_actions.js +96 -100
- data/lib/samagotchi/web/public/working_set_view.js +167 -21
- data/lib/samagotchi/web/public/ws_part_peek.js +277 -0
- data/lib/samagotchi/web/public/ws_peek.js +3 -1
- data/lib/samagotchi/web/public/ws_preview.css +30 -0
- data/lib/samagotchi/web/public/ws_reader.js +7 -3
- data/lib/samagotchi/web/public/ws_sections.js +37 -7
- data/lib/samagotchi/web/push/notifier.rb +33 -6
- data/lib/samagotchi/web/server.rb +1 -1
- data/lib/samagotchi/web/session_access_routes.rb +14 -11
- data/lib/samagotchi/web/session_control.rb +31 -9
- data/lib/samagotchi/web/session_create.rb +2 -2
- data/lib/samagotchi/web/session_hub.rb +26 -4
- data/lib/samagotchi/web/working_set_routes.rb +93 -5
- data/lib/samagotchi/worker/child_side.rb +3 -2
- data/lib/samagotchi/worker/command_queue.rb +13 -13
- data/lib/samagotchi/worker/leave.rb +3 -3
- data/lib/samagotchi/worker/scratch.rb +6 -6
- data/lib/samagotchi/worker/signal_grace.rb +6 -5
- data/lib/samagotchi/worker/startup.rb +3 -3
- data/lib/samagotchi/worker/wake_turns.rb +4 -4
- data/lib/samagotchi/worker.rb +32 -21
- data/lib/samagotchi/worker_exit_claim.rb +1 -1
- data/lib/samagotchi/worker_idle_exit.rb +18 -9
- data/lib/samagotchi/worker_inbound.rb +12 -7
- data/lib/samagotchi/worker_link.rb +2 -2
- data/lib/samagotchi/worker_participant_gate.rb +9 -7
- data/lib/samagotchi/worker_task_wakes.rb +7 -5
- data/lib/samagotchi/working_set.rb +162 -90
- data/lib/samagotchi/working_set_locator.rb +221 -0
- data/lib/samagotchi/working_set_own_changes.rb +221 -0
- data/lib/samagotchi/working_set_part.rb +281 -0
- metadata +36 -1
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "delegate"
|
|
4
|
+
require_relative "../bridge_client"
|
|
5
|
+
require_relative "../client_id"
|
|
6
|
+
require_relative "../reply_wait"
|
|
7
|
+
require_relative "../session"
|
|
8
|
+
require_relative "../session_command_catalog"
|
|
9
|
+
require_relative "../session_inbox"
|
|
10
|
+
require_relative "../turn_flow"
|
|
11
|
+
require_relative "../session_access/ask"
|
|
12
|
+
require_relative "../session_access/exchange"
|
|
13
|
+
require_relative "../session_access/exchange/token"
|
|
14
|
+
require_relative "request_body"
|
|
15
|
+
|
|
16
|
+
module Samagotchi
|
|
17
|
+
module Web
|
|
18
|
+
# The thin-client routes (docs/thin-clients.md): POST …/ask (one
|
|
19
|
+
# message, its answer in one call: SessionAccess::Ask), a wait token for
|
|
20
|
+
# POST …/wait (#handle_token_wait), wait: on POST …/answer
|
|
21
|
+
# (#answer_wait_option, #answered_wait) and a create's token
|
|
22
|
+
# (#create_token). Included in App through SessionAccessRoutes; its
|
|
23
|
+
# helpers (json_response, body_hash, wait_result_json, busy_json,
|
|
24
|
+
# parent_gate, owned_by_tui, refused_delivery, record_history, …) answer.
|
|
25
|
+
module AskRoutes
|
|
26
|
+
# One ask answers within this many seconds from its request's start,
|
|
27
|
+
# whatever it waits for (a continue in flight, the Bridge of a worker
|
|
28
|
+
# starting, the wait's slice): a proxy or a Shortcut with a 60 s limit
|
|
29
|
+
# is safe. The post to a live worker draws on it too (#ask_bridge), but
|
|
30
|
+
# never under POST_FLOOR, so a call ends within about 44 s.
|
|
31
|
+
ASK_MAX_SECONDS = 35.0
|
|
32
|
+
# The shortest read a post to a live worker gets (#ask_bridge),
|
|
33
|
+
# however little of the deadline is left: a healthy but loaded worker
|
|
34
|
+
# still reads the message in time.
|
|
35
|
+
POST_FLOOR = 8.0
|
|
36
|
+
# The fewest seconds the post's body deadline leaves before its read
|
|
37
|
+
# times out (BridgeClient's deadline_margin): a worker that took the
|
|
38
|
+
# turn just in time still has that long to answer 202, so a 504 means
|
|
39
|
+
# it was not taken.
|
|
40
|
+
POST_MARGIN = 2.5
|
|
41
|
+
# A wait route answers within this many seconds (status timeout); the
|
|
42
|
+
# client asks again until its own --timeout. SessionAccessRoutes'
|
|
43
|
+
# (which includes this module) too.
|
|
44
|
+
WAIT_MAX_SECONDS = 30.0
|
|
45
|
+
# GET /api/info's feature: this chi web has the ask route, wait
|
|
46
|
+
# tokens, the answer's wait and the create's token.
|
|
47
|
+
ASK_FEATURE = "ask"
|
|
48
|
+
# A line a worker may run as a session command (#ask_request_id): a
|
|
49
|
+
# / name (Registry::UNKNOWN_COMMAND_WORD's shape, which every
|
|
50
|
+
# built-in a worker runs and a bundle's COMMAND_NAME fits) followed by
|
|
51
|
+
# whitespace or nothing, so "/Users/x/a.rb fails" is a message. A !
|
|
52
|
+
# line is the shell's.
|
|
53
|
+
COMMAND_SHAPE = %r{\A/[A-Za-z][A-Za-z0-9_-]*(?:\s|\z)}
|
|
54
|
+
# An ask's request_id: 1 to 128 printable ASCII characters.
|
|
55
|
+
REQUEST_ID = /\A[\x21-\x7e]{1,128}\z/
|
|
56
|
+
# The wait body's own fields, which a token replaces.
|
|
57
|
+
TOKEN_EXCLUDES = %w[cursor baseline turn queued ended_before owner_grace].freeze
|
|
58
|
+
|
|
59
|
+
# The ask's backend: chi web's sessions (SessionAccess::Local),
|
|
60
|
+
# delivering through chi web's own manager and Bridge as POST …/turn
|
|
61
|
+
# does (the same Bridge wait and give-ups), and waiting at its poll
|
|
62
|
+
# interval. One per request.
|
|
63
|
+
class AskAccess < SimpleDelegator
|
|
64
|
+
def initialize(access, manager:, bridge:, poll_interval: nil)
|
|
65
|
+
super(access)
|
|
66
|
+
@manager = manager
|
|
67
|
+
@bridge = bridge
|
|
68
|
+
@poll_interval = poll_interval
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def deliver_turn(id, **)
|
|
72
|
+
__getobj__.deliver_turn(id, **, manager: @manager, bridge: -> { @bridge.call(id) })
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def wait_reply(id, **options)
|
|
76
|
+
options = { poll_interval: @poll_interval }.merge(options) if @poll_interval
|
|
77
|
+
__getobj__.wait_reply(id, **options)
|
|
78
|
+
end
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
private
|
|
82
|
+
|
|
83
|
+
# POST /api/sessions/:id/ask {prompt, timeout, queue, client_id,
|
|
84
|
+
# request_id}: the message delivered (to a chain's newest link; a
|
|
85
|
+
# running session queues it as its own turn unless queue is false) and
|
|
86
|
+
# its answer waited for, all within ASK_MAX_SECONDS. A request_id (a
|
|
87
|
+
# message's, not a command's) names its turn: a retry whose turn the
|
|
88
|
+
# session knows waits on it again, nothing sent and no second history
|
|
89
|
+
# line (SessionAccess::Ask#call). 200 wait_result_json's fields +
|
|
90
|
+
# session_id (+ asked, the id given, when another link ran it; +
|
|
91
|
+
# token when the status is timeout: POST …/wait {token} goes on; +
|
|
92
|
+
# request_id when one was given); 200 {status: command} for a session
|
|
93
|
+
# command. 404 not_found, 400 ambiguous_id / invalid_ask, 409 busy /
|
|
94
|
+
# waiting / continuing / owned_by_tui / enqueued_id_conflict (the
|
|
95
|
+
# same request_id, another prompt), the turn route's delivery
|
|
96
|
+
# refusals, 503 server_stopping.
|
|
97
|
+
def handle_ask(req, id)
|
|
98
|
+
# One deadline from the request's start: the gate, the continue
|
|
99
|
+
# waits, the Bridge wait and the slice all draw on it.
|
|
100
|
+
deadline = ask_clock + ASK_MAX_SECONDS
|
|
101
|
+
body = body_hash(req) or return error_response(400, "invalid_json", "invalid JSON body")
|
|
102
|
+
prompt, client_id, options, error = ask_request(id, body)
|
|
103
|
+
return error if error
|
|
104
|
+
|
|
105
|
+
gated = ask_gate(id, prompt, client_id)
|
|
106
|
+
return gated if gated
|
|
107
|
+
|
|
108
|
+
bridge = ->(sid) { ask_bridge(sid, deadline) }
|
|
109
|
+
access = AskAccess.new(session_access, manager: @manager, bridge: bridge, poll_interval: @wait_poll_interval)
|
|
110
|
+
stopping = -> { !@server_running.call }
|
|
111
|
+
exchange = SessionAccess::Exchange.new(access, continuing_wait: [SessionAccess::Exchange::CONTINUING_WAIT,
|
|
112
|
+
ASK_MAX_SECONDS].min, cancelled: stopping)
|
|
113
|
+
outcome = SessionAccess::Ask.new(access, exchange: exchange)
|
|
114
|
+
.call(id, prompt: prompt, client_id: client_id, cap: deadline - ask_clock,
|
|
115
|
+
cancelled: stopping, **options)
|
|
116
|
+
rebound = outcome.is_a?(SessionAccess::Ask::Reply) && outcome.rebound
|
|
117
|
+
record_history(body, prompt) unless outcome.is_a?(SessionAccess::Ask::Refused) || rebound
|
|
118
|
+
ask_response(id, outcome, request_id: options[:request_id])
|
|
119
|
+
rescue SessionManager::OwnedByTUI => e
|
|
120
|
+
owned_by_tui(e)
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
# The ask's body read: [prompt, client_id, {queue:, timeout:,
|
|
124
|
+
# request_id:}, nil] or [.., a 400 response].
|
|
125
|
+
def ask_request(id, body)
|
|
126
|
+
return [nil, nil, nil, error_response(400, "missing_fields", "prompt is required")] unless body["prompt"].is_a?(String)
|
|
127
|
+
|
|
128
|
+
prompt = SessionInbox.checked_text(body["prompt"], noun: "message")
|
|
129
|
+
if (entry = SessionCommandCatalog.ui_only_entry(prompt))
|
|
130
|
+
words = SessionCommandCatalog.ui_only_refusal(entry.name, id, runner: "ask")
|
|
131
|
+
return [nil, nil, nil, error_response(400, "local_command", words)]
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
timeout = body.fetch("timeout", WAIT_MAX_SECONDS)
|
|
135
|
+
unless timeout.is_a?(Numeric) && timeout.positive?
|
|
136
|
+
return [nil, nil, nil, error_response(400, "invalid_ask", "timeout is positive seconds")]
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
queue = body.fetch("queue", true)
|
|
140
|
+
return [nil, nil, nil, error_response(400, "invalid_ask", "queue is true or false")] unless [true, false].include?(queue)
|
|
141
|
+
|
|
142
|
+
client_id = body["client_id"]
|
|
143
|
+
return [nil, nil, nil, error_response(400, "invalid_ask", "client_id is a string")] unless client_id.nil? || client_id.is_a?(String)
|
|
144
|
+
|
|
145
|
+
request_id, error = ask_request_id(body, prompt)
|
|
146
|
+
return [nil, nil, nil, error] if error
|
|
147
|
+
|
|
148
|
+
options = { queue: queue, timeout: [timeout, WAIT_MAX_SECONDS].min }
|
|
149
|
+
options[:request_id] = request_id if request_id
|
|
150
|
+
[prompt, ask_sender(client_id, prompt), options, nil]
|
|
151
|
+
rescue SessionInbox::NoteRejected => e
|
|
152
|
+
[nil, nil, nil, error_response(400, "invalid_prompt", e.message)]
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
# The body's request_id: [nil or it, nil] or [nil, a 400]. A session
|
|
156
|
+
# command never runs as a turn of that id (the Bridge's command path
|
|
157
|
+
# takes none), so a retry would run it again: refused. Any line the
|
|
158
|
+
# worker may run as one, by its shape (COMMAND_SHAPE): chi web can't
|
|
159
|
+
# see a bundle's commands, which only the worker's registry has.
|
|
160
|
+
def ask_request_id(body, prompt)
|
|
161
|
+
request_id = body["request_id"]
|
|
162
|
+
return [nil, nil] if request_id.nil?
|
|
163
|
+
unless request_id.is_a?(String) && REQUEST_ID.match?(request_id)
|
|
164
|
+
return [nil, error_response(400, "invalid_ask", "request_id is 1 to 128 printable ASCII characters")]
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
line = prompt.strip
|
|
168
|
+
if line.start_with?("!") || COMMAND_SHAPE.match?(line)
|
|
169
|
+
return [nil, error_response(400, "invalid_ask", "request_id is for messages, not session commands")]
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
[request_id, nil]
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
# Who asks: the owner (WEB_UNNAMED) unless the body names a sender
|
|
176
|
+
# (owner_sender's rule); a parent agent's /continue yes sent as
|
|
177
|
+
# cli:send goes in as cli:answer, as chi send sends it (the worker
|
|
178
|
+
# holds that one to guardrails.parent_answers).
|
|
179
|
+
def ask_sender(client_id, prompt)
|
|
180
|
+
sender = owner_sender({ "client_id" => client_id })
|
|
181
|
+
sender == ClientId::CLI_SEND && TurnFlow.continue_yes?(prompt) ? ClientId::CLI_ANSWER : sender
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
# A parent agent's line refused before anything is sent, as POST
|
|
185
|
+
# …/turn refuses it (#parent_gate), held to the parent_answers of the
|
|
186
|
+
# session asked and of its chain's newest link (where it goes).
|
|
187
|
+
# @return [Array, nil] the response, or nil to go on
|
|
188
|
+
def ask_gate(id, prompt, client_id)
|
|
189
|
+
return nil unless App::CLI_SEND_IDS.include?(client_id)
|
|
190
|
+
|
|
191
|
+
asked = session_access.resolve(id)
|
|
192
|
+
ids = [asked, session_access.head(asked).id].uniq
|
|
193
|
+
sessions = ids.select { |sid| File.file?(Session.session_file(sid, state_dir: default_state_dir)) }
|
|
194
|
+
values = sessions.map { |sid| session_access.show(sid).parent_answers }
|
|
195
|
+
# No session left to read: config.yml's value alone (fail closed),
|
|
196
|
+
# as SendCommand::ParentGate#target_values falls back.
|
|
197
|
+
values = [nil] if values.empty?
|
|
198
|
+
parent_gate(prompt, client_id: client_id, values: values)
|
|
199
|
+
rescue ArgumentError # degrade-ok: no such session, or a prefix of several: the ask's own answer says which
|
|
200
|
+
nil
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
# The ask's answer for an Ask value (+request_id+ echoed when given:
|
|
204
|
+
# the client sees this chi web used it).
|
|
205
|
+
def ask_response(id, outcome, request_id: nil)
|
|
206
|
+
case outcome
|
|
207
|
+
when SessionAccess::Ask::Ran then json_response(200, { status: "command", session_id: outcome.session_id })
|
|
208
|
+
when SessionAccess::Ask::Refused then ask_refused(id, outcome)
|
|
209
|
+
else
|
|
210
|
+
result = outcome.result
|
|
211
|
+
return error_response(503, "server_stopping", "chi web is stopping; wait again") if result.status == :canceled
|
|
212
|
+
|
|
213
|
+
json = wait_result_json(result, session_access.parent_strategy(outcome.session_id)).merge(session_id: outcome.session_id)
|
|
214
|
+
json[:asked] = outcome.asked if outcome.asked && outcome.asked != outcome.session_id
|
|
215
|
+
json[:token] = outcome.token if outcome.token
|
|
216
|
+
json[:request_id] = request_id if request_id
|
|
217
|
+
json_response(200, json)
|
|
218
|
+
end
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
# Neutral words for a Busy, not chi send's flags.
|
|
222
|
+
ASK_BUSY_WORDS = { "busy" => "a turn is running: ask with queue, or wait for it",
|
|
223
|
+
"waiting" => "a question waits for an answer" }.freeze
|
|
224
|
+
|
|
225
|
+
def ask_refused(id, refused)
|
|
226
|
+
case refused.kind
|
|
227
|
+
when :canceled then error_response(503, "server_stopping", "chi web is stopping; ask again")
|
|
228
|
+
when :unknown
|
|
229
|
+
error = refused.error
|
|
230
|
+
return refusal_response(400, "ambiguous_id", error, ids: error.ids) if error.is_a?(Session::AmbiguousId)
|
|
231
|
+
|
|
232
|
+
session_not_found(id)
|
|
233
|
+
when :continuing then refusal(409, "continuing", refused.message, session_id: refused.session_id)
|
|
234
|
+
when :busy
|
|
235
|
+
words = ASK_BUSY_WORDS.fetch(refused.busy.error)
|
|
236
|
+
json_response(409, busy_json(refused.busy).merge(detail: words, message: words))
|
|
237
|
+
else refused_delivery(refused.result)
|
|
238
|
+
end
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
# POST /api/sessions/:id/wait {token, timeout}: the wait a token holds
|
|
242
|
+
# (an ask's, a create's, an answer's), for at most WAIT_MAX_SECONDS.
|
|
243
|
+
# The URL's id may be a prefix. 200 wait_result_json's fields +
|
|
244
|
+
# session_id (+ token, the same, while the status is timeout); 400 invalid_wait for a token that isn't one,
|
|
245
|
+
# another session's, a token beside the wait's own fields, or a
|
|
246
|
+
# participant's; 503 server_stopping.
|
|
247
|
+
def handle_token_wait(req, id, body)
|
|
248
|
+
return error_response(400, "invalid_wait", "a participant's wait takes a turn, not a token") unless principal(req).owner?
|
|
249
|
+
if TOKEN_EXCLUDES.any? { |key| ![nil, false].include?(body[key]) }
|
|
250
|
+
return error_response(400, "invalid_wait", "token or the wait's fields, not both")
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
timeout = body["timeout"]
|
|
254
|
+
unless timeout.nil? || (timeout.is_a?(Numeric) && timeout.positive?)
|
|
255
|
+
return error_response(400, "invalid_wait", "timeout is positive seconds")
|
|
256
|
+
end
|
|
257
|
+
|
|
258
|
+
session_id, target = SessionAccess::Exchange::Token.load(body["token"])
|
|
259
|
+
# The URL's id may be a prefix (as the ask's): resolved first (no
|
|
260
|
+
# such session, or several: session_route's 404).
|
|
261
|
+
full = session_access.resolve(id)
|
|
262
|
+
return error_response(400, "invalid_wait", "the token is another session's wait") unless session_id == full
|
|
263
|
+
|
|
264
|
+
result = plain_exchange.wait(full, target, timeout: [timeout || WAIT_MAX_SECONDS, WAIT_MAX_SECONDS].min,
|
|
265
|
+
**wait_extras)
|
|
266
|
+
return error_response(503, "server_stopping", "chi web is stopping; wait again") if result.status == :canceled
|
|
267
|
+
|
|
268
|
+
json = wait_result_json(result, session_access.parent_strategy(full)).merge(session_id: full)
|
|
269
|
+
json[:token] = body["token"] if result.status == :timeout
|
|
270
|
+
json_response(200, json)
|
|
271
|
+
rescue SessionAccess::Exchange::Token::Invalid => e
|
|
272
|
+
error_response(400, "invalid_wait", e.message)
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
# The answer's wait: [seconds, nil] (nil seconds: none asked), or
|
|
276
|
+
# [nil, a 400 response].
|
|
277
|
+
def answer_wait_option(body)
|
|
278
|
+
wait = body["wait"]
|
|
279
|
+
return [nil, nil] if wait.nil? || wait == false
|
|
280
|
+
return [nil, error_response(400, "invalid_wait", "wait is positive seconds")] unless wait.is_a?(Numeric) && wait.positive?
|
|
281
|
+
|
|
282
|
+
[[wait, WAIT_MAX_SECONDS].min, nil]
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
# What an answer's wait reads before the answer goes in
|
|
286
|
+
# (AnswerCommand's): the answered question is not the next thing.
|
|
287
|
+
# @return [WaitStart, nil] nil: the session is gone
|
|
288
|
+
def answer_wait_start(id, session, question_id)
|
|
289
|
+
session_access.prepare_wait(id, session: session, question_id: question_id.to_s)
|
|
290
|
+
rescue ArgumentError # degrade-ok: deleted meanwhile, the answer's 404
|
|
291
|
+
nil
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
# POST …/answer with wait: the answer relayed (+answered+; false: the
|
|
295
|
+
# question was answered elsewhere first, as chi answer still waits)
|
|
296
|
+
# and what comes next, for up to +seconds+. 200 {status: answered |
|
|
297
|
+
# not_pending, (answered_here: false,) session_id, id, reply:
|
|
298
|
+
# {wait_result_json's fields, token while it is timeout}}. The answer
|
|
299
|
+
# went in before the wait, so a wait that fails (chi web stopping, the
|
|
300
|
+
# session deleted, its files unreadable) is still a 200: wait_error
|
|
301
|
+
# {error: server_stopping | not_found | wait_failed, detail} in place
|
|
302
|
+
# of reply (an answer retried would be 409).
|
|
303
|
+
def answered_wait(id, question_id, start, seconds, answered:)
|
|
304
|
+
head = answered ? { status: "answered" } : { status: "not_pending", answered_here: false }
|
|
305
|
+
head = { **head, session_id: id, id: question_id }
|
|
306
|
+
target = ReplyWait::Target.answer(start)
|
|
307
|
+
result = plain_exchange.wait(id, target, timeout: seconds, **wait_extras)
|
|
308
|
+
if result.status == :canceled
|
|
309
|
+
return answer_wait_error(head, "server_stopping", "chi web is stopping; the answer went in")
|
|
310
|
+
end
|
|
311
|
+
|
|
312
|
+
reply = wait_result_json(result, session_access.parent_strategy(id))
|
|
313
|
+
reply[:token] = SessionAccess::Exchange::Token.dump(id, target) if result.status == :timeout
|
|
314
|
+
json_response(200, { **head, reply: reply })
|
|
315
|
+
rescue ArgumentError => e # deleted while waiting
|
|
316
|
+
answer_wait_error(head, "not_found", e.message)
|
|
317
|
+
rescue SystemCallError, IOError => e
|
|
318
|
+
answer_wait_error(head, "wait_failed", "#{e.class}: #{e.message}")
|
|
319
|
+
end
|
|
320
|
+
|
|
321
|
+
def answer_wait_error(head, error, detail) = json_response(200, { **head, wait_error: { error: error, detail: detail } })
|
|
322
|
+
|
|
323
|
+
# A create's 201 token, for a session started with its first turn
|
|
324
|
+
# (first_turn_id): POST …/wait {token} answers that turn. {} for an
|
|
325
|
+
# idle one.
|
|
326
|
+
def create_token(session)
|
|
327
|
+
turn = session.first_turn_id.to_s
|
|
328
|
+
return {} if turn.empty?
|
|
329
|
+
|
|
330
|
+
start = session_access.prepare_wait(session.id, session: (session if session.is_a?(Session)), created: true)
|
|
331
|
+
target = ReplyWait::Target.first_message(start, nil, direct_turn: turn)
|
|
332
|
+
{ token: SessionAccess::Exchange::Token.dump(session.id, target) }
|
|
333
|
+
end
|
|
334
|
+
|
|
335
|
+
def plain_exchange = SessionAccess::Exchange.new(session_access)
|
|
336
|
+
|
|
337
|
+
# The worker's Bridge client for an ask's delivery (App's
|
|
338
|
+
# live_bridge_client, drawn from +deadline+): a worker starting is
|
|
339
|
+
# waited for out of what is left, and the post's read is what is left
|
|
340
|
+
# after that but MIN_SLICE, within POST_FLOOR..READ_TIMEOUT. The
|
|
341
|
+
# client's body deadline is a share of that read (DEADLINE_SHARE, at
|
|
342
|
+
# least POST_MARGIN short of it), so
|
|
343
|
+
# a worker that reads the message late drops it (408
|
|
344
|
+
# deadline_passed) rather than run it after the call gave up.
|
|
345
|
+
# @param deadline [Numeric] ask_clock's seconds the call ends by
|
|
346
|
+
# @return [BridgeClient, nil] nil: no live worker in time
|
|
347
|
+
def ask_bridge(sid, deadline)
|
|
348
|
+
link = worker_link(sid)
|
|
349
|
+
link = await_worker_link(sid, timeout: [@bridge_wait_timeout.to_f, deadline - ask_clock].min.clamp(0.0..)) unless link.live?
|
|
350
|
+
return nil unless link.live?
|
|
351
|
+
|
|
352
|
+
read = (deadline - ask_clock - SessionAccess::Ask::MIN_SLICE).clamp(POST_FLOOR, BridgeClient::READ_TIMEOUT)
|
|
353
|
+
link.client(sid, host: App::DEFAULT_HOST, read_timeout: read, deadline_margin: POST_MARGIN)
|
|
354
|
+
end
|
|
355
|
+
|
|
356
|
+
# The ask's deadline clock (the Exchange's: monotonic seconds).
|
|
357
|
+
def ask_clock = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
358
|
+
|
|
359
|
+
def wait_extras = { poll_interval: @wait_poll_interval, cancelled: -> { !@server_running.call } }.compact
|
|
360
|
+
end
|
|
361
|
+
end
|
|
362
|
+
end
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "../mcp_server/protocol"
|
|
4
|
+
require_relative "../mcp_server/http"
|
|
5
|
+
require_relative "../mcp_server/tools"
|
|
6
|
+
require_relative "../mcp_server/text"
|
|
7
|
+
require_relative "../session_inbox"
|
|
8
|
+
require_relative "ask_routes"
|
|
9
|
+
require_relative "request_body"
|
|
10
|
+
|
|
11
|
+
module Samagotchi
|
|
12
|
+
module Web
|
|
13
|
+
# POST /api/mcp: chi as an MCP server on chi web (McpServer::Http, one
|
|
14
|
+
# JSON answer a POST, each call within McpServer::Tools::SLICE), for an
|
|
15
|
+
# MCP host that speaks HTTP. Behind the gates every owner route has
|
|
16
|
+
# (the Host check, a foreign Origin's 403, the token: none on loopback
|
|
17
|
+
# without web.public_url, Bearer on the LAN or a public URL; a
|
|
18
|
+
# participant's token is refused), with chi web's own {error, detail}
|
|
19
|
+
# bodies there; a tokenless request's 401 adds WWW-Authenticate:
|
|
20
|
+
# Bearer, so a host says it needs a token rather than look for OAuth.
|
|
21
|
+
# GET 405 (no stream), DELETE 200 (a legacy host closing its session).
|
|
22
|
+
# Included in App through SessionAccessRoutes; its helpers
|
|
23
|
+
# (request_body, session_access, ask_bridge, ask_clock, error_response)
|
|
24
|
+
# and ivars (@manager, @hub, @wait_poll_interval, @server_running)
|
|
25
|
+
# answer. See docs/mcp-server.md.
|
|
26
|
+
module McpRoute
|
|
27
|
+
# GET /api/info's feature: this chi web serves POST /api/mcp.
|
|
28
|
+
FEATURE = "mcp"
|
|
29
|
+
PATH = %r{\A/api/mcp\z}
|
|
30
|
+
# A POST's body cap: a chi_ask prompt at its 16 KiB limit, every byte
|
|
31
|
+
# JSON-escaped (a control character's \u0000 is 6 bytes), plus the
|
|
32
|
+
# envelope, so a host gets the tool's "the message is N bytes" over
|
|
33
|
+
# the limit, not chi web's 413.
|
|
34
|
+
BODY_LIMIT = (6 * SessionInbox::NOTE_MAX_BYTES) + (16 * 1024)
|
|
35
|
+
# App::ROUTES' rows for the path (all :owner).
|
|
36
|
+
ROUTES = [["POST", PATH, :handle_mcp, :owner], ["GET", PATH, :handle_mcp_get, :owner],
|
|
37
|
+
["DELETE", PATH, :handle_mcp_delete, :owner]].freeze
|
|
38
|
+
|
|
39
|
+
# The tools' backend on chi web: the ask's (its manager and Bridge),
|
|
40
|
+
# whose answer also closes the page's card once the worker took it,
|
|
41
|
+
# as POST …/answer does.
|
|
42
|
+
class McpAccess < AskRoutes::AskAccess
|
|
43
|
+
def initialize(access, hub:, **)
|
|
44
|
+
super(access, **)
|
|
45
|
+
@hub = hub
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def answer(id, question_id:, **)
|
|
49
|
+
reply = __getobj__.answer(id, question_id: question_id, **)
|
|
50
|
+
@hub&.resolve_question(id, question_id: question_id) if reply&.status == 200
|
|
51
|
+
reply
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
private
|
|
56
|
+
|
|
57
|
+
def handle_mcp(req)
|
|
58
|
+
# One deadline per POST (one call), as the ask's: the post to a
|
|
59
|
+
# live worker draws on it (AskRoutes#ask_bridge).
|
|
60
|
+
deadline = ask_clock + McpServer::Tools::CAP
|
|
61
|
+
body = request_body(req, BODY_LIMIT, what: "an MCP request")
|
|
62
|
+
McpServer::Http.new(mcp_protocol(deadline)).call(req.env, body)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def handle_mcp_get(_req)
|
|
66
|
+
text = JSON.generate({ error: "method_not_allowed", detail: "POST an MCP request; this server opens no stream" })
|
|
67
|
+
[405, { "Content-Type" => "application/json", "Allow" => "POST, DELETE", "Content-Length" => text.bytesize.to_s }, [text]]
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Nothing is kept for a legacy session id: nothing to end.
|
|
71
|
+
def handle_mcp_delete(_req) = [200, { "Content-Length" => "0" }, []]
|
|
72
|
+
|
|
73
|
+
def mcp_protocol(deadline)
|
|
74
|
+
bridge = ->(sid) { ask_bridge(sid, deadline) }
|
|
75
|
+
access = McpAccess.new(session_access, hub: @hub, manager: @manager, bridge: bridge, poll_interval: @wait_poll_interval)
|
|
76
|
+
stopping = -> { !@server_running.call }
|
|
77
|
+
exchange = ->(backend) { SessionAccess::Exchange.new(backend, cancelled: stopping) }
|
|
78
|
+
tools = McpServer::Tools.new(access, exchange: exchange, cancelled: stopping)
|
|
79
|
+
McpServer::Protocol.new(tools: tools, instructions: McpServer::Text::INSTRUCTIONS)
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# The /api/ 401 (App#unauthorized's), with WWW-Authenticate: Bearer
|
|
83
|
+
# on this path.
|
|
84
|
+
def api_unauthorized(req, detail)
|
|
85
|
+
status, headers, body = error_response(401, "unauthorized", detail)
|
|
86
|
+
headers = headers.merge("WWW-Authenticate" => "Bearer") if PATH.match?(req.path_info)
|
|
87
|
+
[status, headers, body]
|
|
88
|
+
end
|
|
89
|
+
end
|
|
90
|
+
end
|
|
91
|
+
end
|
|
@@ -68,7 +68,7 @@ import { parsePresets } from "./annotate_presets.js";
|
|
|
68
68
|
import { createAnnotateBar } from "./annotate_bar.js";
|
|
69
69
|
import { VERIFY_PRESET, VERIFY_UNAVAILABLE, verifyWorkerUnavailable, withVerify } from "./verify_preset.js";
|
|
70
70
|
import { actionLine, annotationActions, composerWithAction } from "./annotate_actions.js";
|
|
71
|
-
import {
|
|
71
|
+
import { wireDiagrams } from "./diagram_wiring.js";
|
|
72
72
|
import { wireBlockFix } from "./block_fix.js";
|
|
73
73
|
import { createWidgetDrawer } from "./inline_widgets.js";
|
|
74
74
|
import { copyText, installCopy } from "./copy.js";
|
|
@@ -1542,9 +1542,8 @@ turnRoots().forEach((root) => installCopy(root));
|
|
|
1542
1542
|
// chi-ui blocks (inline_widgets.js) are a core drawer, ahead of the bundles'
|
|
1543
1543
|
// renderers; a picks' Fill reply only fills the composer.
|
|
1544
1544
|
const widgets = createWidgetDrawer({ roots: turnRoots(), composerText: () => promptEl.value, fillComposer });
|
|
1545
|
-
|
|
1545
|
+
wireDiagrams({ roots: turnRoots(), sessionId: () => store.selected, drawers: [widgets], renderers: viewer.can("block_renderers"), pictures });
|
|
1546
1546
|
const blockFix = wireBlockFix({ viewer, roots: turnRoots(), store, getSession, composerText: () => promptEl.value, fillComposer, linkTextRefs: markdownPlace.linkTextRefs });
|
|
1547
|
-
window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener?.("change", () => pictures.close()); // a redrawn diagram's old picture
|
|
1548
1547
|
// A steps block, a thinking block and the recap open and close by hand
|
|
1549
1548
|
// with their height animated (details_motion.js), in the history and on
|
|
1550
1549
|
// the stage.
|
|
@@ -9,19 +9,36 @@
|
|
|
9
9
|
// the frame's error event). The protocol, the handshake first:
|
|
10
10
|
//
|
|
11
11
|
// frame → loaded, page → code {files}, frame → ready | failed {message}
|
|
12
|
-
// page → render {id, source, theme}, frame → done {id, svg} | error {id, message}
|
|
12
|
+
// page → render {id, source, theme}, frame → done {id, svg, regions?} | error {id, message, bundle?}
|
|
13
13
|
//
|
|
14
|
+
// A renderer's render returns the SVG, or {svg, regions} when the page says it
|
|
15
|
+
// takes regions (chi.features.regions; an older chi's bootstrap refuses anything
|
|
16
|
+
// but a string, so a bundle checks). Regions are capped here and copied bounded,
|
|
17
|
+
// before any of them is cloned to the page (block_regions.js cleans them there). An object without a
|
|
18
|
+
// string svg is the bundle's bug, error {bundle: true}: not the model's, so no fix
|
|
19
|
+
// is asked (block_fix.js). No object at all (undefined, null, a number) is as an
|
|
20
|
+
// older chi took it: a failed render, the model's like a throw (so fixable): a
|
|
21
|
+
// renderer may return nothing for a source it can't draw. draw resolves {svg, regions} (regions raw, or null);
|
|
22
|
+
// render is its SVG.
|
|
14
23
|
// One render at a time. A timer can't fire while the renderer hangs (the frame
|
|
15
24
|
// shares the page's thread): block_host.js's mark is for that.
|
|
16
25
|
//
|
|
17
26
|
// A module of its own: static JS is cached at unversioned URLs.
|
|
18
27
|
|
|
28
|
+
import { MAX_REGIONS } from "./block_regions.js";
|
|
29
|
+
|
|
19
30
|
// Same words as the spike that tested them; the page's frame-src 'none' covers
|
|
20
31
|
// what this doesn't (navigation).
|
|
21
32
|
export const FRAME_CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; form-action 'none'";
|
|
22
33
|
export const FRAME_TIMEOUT_MS = 15000;
|
|
23
34
|
// An SVG this size isn't a diagram anyone reads, and it would sit in the DOM.
|
|
24
35
|
export const MAX_SVG_CHARS = 8 * 1024 * 1024;
|
|
36
|
+
// The error a bundle's bug gets: its render returned an object without a string svg.
|
|
37
|
+
const NO_SVG = "the renderer returned no SVG";
|
|
38
|
+
// The frame's copy of a region keeps a string this long at most, and this many
|
|
39
|
+
// points (the page cuts to 80 / 120 characters and 16 points).
|
|
40
|
+
const FRAME_TEXT_CHARS = 200;
|
|
41
|
+
const FRAME_POINTS = 16;
|
|
25
42
|
|
|
26
43
|
// Runs in the frame, before any bundle code. CSP doesn't stop WebRTC, so its
|
|
27
44
|
// constructors go (a nested srcdoc frame gets a fresh one: the residual risk,
|
|
@@ -33,7 +50,7 @@ const BOOTSTRAP = `(() => {
|
|
|
33
50
|
const words = (e) => String((e && e.message) || e).split("\\n")[0].slice(0, 300);
|
|
34
51
|
let renderer = null;
|
|
35
52
|
let loadError = null;
|
|
36
|
-
window.chi = { defineRenderer(r) { renderer = r; } };
|
|
53
|
+
window.chi = { defineRenderer(r) { renderer = r; }, features: { regions: true } };
|
|
37
54
|
addEventListener("error", (e) => { loadError = loadError || words(e.message || e.error); });
|
|
38
55
|
async function load(files) {
|
|
39
56
|
for (const code of files) {
|
|
@@ -47,14 +64,54 @@ const BOOTSTRAP = `(() => {
|
|
|
47
64
|
try { await (renderer.init && renderer.init()); } catch (e) { return send({ type: "failed", message: words(e) }); }
|
|
48
65
|
send({ type: "ready" });
|
|
49
66
|
}
|
|
67
|
+
// Regions only as an array of at most ${MAX_REGIONS}, each posted as a bounded copy
|
|
68
|
+
// of its known keys (strings cut to ${FRAME_TEXT_CHARS}, a box of 4 and up to ${FRAME_POINTS} points):
|
|
69
|
+
// so nothing vast is ever cloned on the page's thread (600 one-megabyte labels
|
|
70
|
+
// crashed a Chromium tab), and nothing uncloneable. Else none. The page cleans
|
|
71
|
+
// the copy again (block_regions.js).
|
|
72
|
+
const cut = (v) => (typeof v === "string" ? v.slice(0, ${FRAME_TEXT_CHARS}) : "");
|
|
73
|
+
const num = (v) => (typeof v === "number" ? v : NaN);
|
|
74
|
+
function copyRegion(r) {
|
|
75
|
+
if (!r || typeof r !== "object") return null;
|
|
76
|
+
const c = { kind: cut(r.kind), id: cut(r.id), label: cut(r.label), from: cut(r.from), to: cut(r.to) };
|
|
77
|
+
const box = r.box;
|
|
78
|
+
if (Array.isArray(box) && box.length === 4) c.box = [num(box[0]), num(box[1]), num(box[2]), num(box[3])];
|
|
79
|
+
const points = r.points;
|
|
80
|
+
if (Array.isArray(points) && points.length <= ${FRAME_POINTS}) {
|
|
81
|
+
c.points = [];
|
|
82
|
+
for (let i = 0; i < points.length; i++) {
|
|
83
|
+
const p = points[i];
|
|
84
|
+
c.points.push(Array.isArray(p) && p.length === 2 ? [num(p[0]), num(p[1])] : null);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return c;
|
|
88
|
+
}
|
|
89
|
+
function regionsOf(out) {
|
|
90
|
+
try {
|
|
91
|
+
const r = out.regions;
|
|
92
|
+
if (!Array.isArray(r) || r.length > ${MAX_REGIONS}) return null;
|
|
93
|
+
const copy = [];
|
|
94
|
+
for (let i = 0; i < r.length; i++) copy.push(copyRegion(r[i]));
|
|
95
|
+
return copy;
|
|
96
|
+
} catch (_) { return null; }
|
|
97
|
+
}
|
|
50
98
|
async function render(m) {
|
|
99
|
+
let out;
|
|
51
100
|
try {
|
|
52
|
-
|
|
53
|
-
if (typeof svg !== "string") throw new Error("the renderer returned no SVG");
|
|
54
|
-
send({ type: "done", id: m.id, svg });
|
|
101
|
+
out = await renderer.render(m.source, m.theme);
|
|
55
102
|
} catch (e) {
|
|
56
|
-
send({ type: "error", id: m.id, message: words(e) });
|
|
103
|
+
return send({ type: "error", id: m.id, message: words(e) });
|
|
104
|
+
}
|
|
105
|
+
if (typeof out === "string") return send({ type: "done", id: m.id, svg: out });
|
|
106
|
+
if (!out || typeof out !== "object") return send({ type: "error", id: m.id, message: ${JSON.stringify(NO_SVG)} });
|
|
107
|
+
let svg;
|
|
108
|
+
try { svg = out.svg; } catch (_) { svg = null; }
|
|
109
|
+
if (typeof svg !== "string") return send({ type: "error", id: m.id, message: ${JSON.stringify(NO_SVG)}, bundle: true });
|
|
110
|
+
const regions = regionsOf(out);
|
|
111
|
+
if (regions) {
|
|
112
|
+
try { return send({ type: "done", id: m.id, svg, regions }); } catch (_) { /* uncloneable: sent without them */ }
|
|
57
113
|
}
|
|
114
|
+
send({ type: "done", id: m.id, svg });
|
|
58
115
|
}
|
|
59
116
|
addEventListener("message", (e) => {
|
|
60
117
|
if (e.source !== parent) return;
|
|
@@ -97,7 +154,8 @@ export class FrameError extends Error {
|
|
|
97
154
|
|
|
98
155
|
// @param files the renderer's file names, in load order
|
|
99
156
|
// @param fetchFile (file) => a promise of its text (block_host.js fetchRendererFile)
|
|
100
|
-
// @return {
|
|
157
|
+
// @return {draw(source, theme, {onStart}) → Promise<{svg, regions}> (regions raw: block_regions.js cleans them),
|
|
158
|
+
// render(...) → Promise<svg> (draw's SVG alone), drop(), dead()}
|
|
101
159
|
export function createBlockFrame({ files, fetchFile, doc = document, win = window, timeoutMs = FRAME_TIMEOUT_MS }) {
|
|
102
160
|
const iframe = doc.createElement("iframe");
|
|
103
161
|
iframe.setAttribute("sandbox", "allow-scripts");
|
|
@@ -147,9 +205,11 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
|
|
|
147
205
|
settle((w) => w.reject(new FrameError(String(m.message ?? "load failed"), { load: true })));
|
|
148
206
|
} else if (m.type === "done" && m.id === waiting.id) {
|
|
149
207
|
if (typeof m.svg !== "string" || m.svg.length > MAX_SVG_CHARS) settle((w) => w.reject(new FrameError("the renderer's SVG is too large or not text")));
|
|
150
|
-
else settle((w) => w.resolve(m.svg));
|
|
208
|
+
else settle((w) => w.resolve({ svg: m.svg, regions: m.regions ?? null }));
|
|
151
209
|
} else if (m.type === "error" && m.id === waiting.id) {
|
|
152
|
-
|
|
210
|
+
// A bundle's bug (its render's object had no svg) isn't the model's: no fix.
|
|
211
|
+
const renderer = m.bundle !== true;
|
|
212
|
+
settle((w) => w.reject(new FrameError(String(m.message ?? "render failed"), { renderer })));
|
|
153
213
|
}
|
|
154
214
|
}
|
|
155
215
|
|
|
@@ -184,7 +244,7 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
|
|
|
184
244
|
// One render at a time, whatever the last one came to.
|
|
185
245
|
let queue = ready.catch(() => {});
|
|
186
246
|
|
|
187
|
-
function
|
|
247
|
+
function draw(source, theme, { onStart = () => {} } = {}) {
|
|
188
248
|
const run = async () => {
|
|
189
249
|
await ready;
|
|
190
250
|
if (dead) throw new FrameError("the frame is gone", { dropped: true });
|
|
@@ -202,7 +262,8 @@ export function createBlockFrame({ files, fetchFile, doc = document, win = windo
|
|
|
202
262
|
|
|
203
263
|
return {
|
|
204
264
|
ready,
|
|
205
|
-
|
|
265
|
+
draw,
|
|
266
|
+
render: (source, theme, opts) => draw(source, theme, opts).then((r) => r.svg),
|
|
206
267
|
dead: () => dead,
|
|
207
268
|
drop: () => die(new FrameError("dropped", { dropped: true })),
|
|
208
269
|
};
|