samagotchi 0.119.0 → 0.121.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 (91) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +100 -1
  3. data/bin/chi +6 -1
  4. data/docs/architecture.md +35 -5
  5. data/docs/cli.md +33 -8
  6. data/docs/configuration.md +74 -20
  7. data/docs/internals/participants.md +111 -12
  8. data/docs/internals/prompt-caching.md +7 -6
  9. data/docs/internals/remote-sessions.md +6 -1
  10. data/docs/internals/web-push.md +4 -2
  11. data/docs/plugins.md +24 -8
  12. data/docs/sessions.md +4 -3
  13. data/docs/testing.md +13 -2
  14. data/lib/samagotchi/answer_command.rb +2 -0
  15. data/lib/samagotchi/bridge.rb +56 -13
  16. data/lib/samagotchi/bridge_client/event_stream.rb +34 -3
  17. data/lib/samagotchi/bridge_client.rb +58 -19
  18. data/lib/samagotchi/bridge_secret.rb +35 -0
  19. data/lib/samagotchi/bundles/claude-peer/manifest.yml +2 -2
  20. data/lib/samagotchi/bundles/claude-peer/scripts/pair +1 -1
  21. data/lib/samagotchi/bundles/dev/manifest.yml +2 -2
  22. data/lib/samagotchi/bundles/mcp/manifest.yml +3 -3
  23. data/lib/samagotchi/bundles/mcp/plugin.rb +5 -1
  24. data/lib/samagotchi/bundles/system/manifest.yml +1 -1
  25. data/lib/samagotchi/config.rb +3 -0
  26. data/lib/samagotchi/engine.rb +1 -0
  27. data/lib/samagotchi/kernel_loop.rb +5 -0
  28. data/lib/samagotchi/participant_messages.rb +5 -0
  29. data/lib/samagotchi/participants.rb +16 -6
  30. data/lib/samagotchi/plugin/api.rb +6 -3
  31. data/lib/samagotchi/review_command.rb +3 -1
  32. data/lib/samagotchi/run_options.rb +3 -1
  33. data/lib/samagotchi/session_access/contract.rb +4 -1
  34. data/lib/samagotchi/session_access/local.rb +15 -4
  35. data/lib/samagotchi/session_access/remote.rb +43 -7
  36. data/lib/samagotchi/session_access.rb +11 -1
  37. data/lib/samagotchi/session_manager.rb +1 -1
  38. data/lib/samagotchi/sessions_command.rb +1 -2
  39. data/lib/samagotchi/share_command.rb +29 -8
  40. data/lib/samagotchi/terminal_ui/attached_loop.rb +3 -0
  41. data/lib/samagotchi/terminal_ui/local_link.rb +18 -3
  42. data/lib/samagotchi/terminal_ui/question_slot.rb +19 -8
  43. data/lib/samagotchi/tool_declarations.rb +1 -1
  44. data/lib/samagotchi/tool_runner.rb +37 -1
  45. data/lib/samagotchi/toolkit.rb +50 -26
  46. data/lib/samagotchi/toolkit_binding.rb +32 -0
  47. data/lib/samagotchi/toolkit_command.rb +23 -0
  48. data/lib/samagotchi/tools/deferred_tools.rb +10 -2
  49. data/lib/samagotchi/tools/delegate_relay.rb +4 -0
  50. data/lib/samagotchi/tools/registry.rb +20 -6
  51. data/lib/samagotchi/tools/tool_index.rb +103 -20
  52. data/lib/samagotchi/version.rb +1 -1
  53. data/lib/samagotchi/web/app.rb +117 -43
  54. data/lib/samagotchi/web/grants.rb +127 -16
  55. data/lib/samagotchi/web/link_codes.rb +24 -15
  56. data/lib/samagotchi/web/participant_access.rb +69 -13
  57. data/lib/samagotchi/web/participant_exposure.rb +44 -0
  58. data/lib/samagotchi/web/participant_review.rb +71 -9
  59. data/lib/samagotchi/web/participants_admin.rb +12 -6
  60. data/lib/samagotchi/web/proxy_gate.rb +18 -3
  61. data/lib/samagotchi/web/public/annotate_bar.css +18 -0
  62. data/lib/samagotchi/web/public/annotate_bar.js +10 -3
  63. data/lib/samagotchi/web/public/app.js +66 -155
  64. data/lib/samagotchi/web/public/composer.css +73 -0
  65. data/lib/samagotchi/web/public/composer_grip.js +21 -15
  66. data/lib/samagotchi/web/public/composer_mount.js +196 -0
  67. data/lib/samagotchi/web/public/forms.css +12 -0
  68. data/lib/samagotchi/web/public/index.html +14 -88
  69. data/lib/samagotchi/web/public/level_chip.js +2 -2
  70. data/lib/samagotchi/web/public/llm_context_chip.js +4 -4
  71. data/lib/samagotchi/web/public/notifications.js +58 -8
  72. data/lib/samagotchi/web/public/participant.html +46 -10
  73. data/lib/samagotchi/web/public/participant.js +101 -18
  74. data/lib/samagotchi/web/public/participant_annotate.js +75 -0
  75. data/lib/samagotchi/web/public/participant_model.js +53 -1
  76. data/lib/samagotchi/web/public/participants_panel.js +37 -13
  77. data/lib/samagotchi/web/public/question_card.js +15 -1
  78. data/lib/samagotchi/web/public/question_cards.js +11 -2
  79. data/lib/samagotchi/web/public/review_history.js +60 -0
  80. data/lib/samagotchi/web/public/scope.js +12 -8
  81. data/lib/samagotchi/web/public/stage_frame.js +9 -4
  82. data/lib/samagotchi/web/public/stage_view.js +4 -4
  83. data/lib/samagotchi/web/public/toolkit_chip.js +3 -0
  84. data/lib/samagotchi/web/push/notifier.rb +17 -3
  85. data/lib/samagotchi/web/running.rb +7 -4
  86. data/lib/samagotchi/web/server.rb +34 -11
  87. data/lib/samagotchi/web/session_create.rb +7 -7
  88. data/lib/samagotchi/web/start_dir.rb +26 -0
  89. data/lib/samagotchi/web/tunnel.rb +10 -1
  90. data/lib/samagotchi/worker_sidecar.rb +22 -11
  91. metadata +10 -1
@@ -0,0 +1,60 @@
1
+ // A participant's ↑/↓ in the comment box (participant.js over
2
+ // prompt_history.js): their own comments sent from this browser, newest
3
+ // last, in localStorage under one key per grant, never the owner's GET
4
+ // /api/history (the owner may open a link in the same browser, on the same
5
+ // origin: each grant's list and the owner's stay apart). Read and written
6
+ // through storage.js (guarded): a list that can't be read or written is just
7
+ // not there. A link that ends forgets its list.
8
+ import { readStored, removeStored, writeStored } from "./storage.js";
9
+
10
+ export const REVIEW_HISTORY_PREFIX = "chi_review_history:";
11
+ const REVIEW_HISTORY_SESSION_PREFIX = "chi_review_history_session:";
12
+ // How many comments a grant's list keeps (the oldest go first).
13
+ export const REVIEW_HISTORY_MAX = 50;
14
+
15
+ // The key for grant +grantId+'s list; null without one (an older server's
16
+ // review data): no history then.
17
+ export function reviewHistoryKey(grantId) {
18
+ return grantId ? `${REVIEW_HISTORY_PREFIX}${grantId}` : null;
19
+ }
20
+
21
+ // The grant's comments, oldest first; [] when there are none or they can't
22
+ // be read.
23
+ export function readReviewHistory(grantId) {
24
+ const key = reviewHistoryKey(grantId);
25
+ if (!key) return [];
26
+ try {
27
+ const list = JSON.parse(readStored(key, "[]"));
28
+ return Array.isArray(list) ? list.filter((entry) => typeof entry === "string") : [];
29
+ } catch (_) {
30
+ return [];
31
+ }
32
+ }
33
+
34
+ // The list with +text+ added at the end (not twice in a row), at most
35
+ // REVIEW_HISTORY_MAX long. Pure.
36
+ export function withComment(list, text) {
37
+ const entry = String(text || "").trim();
38
+ if (!entry) return list;
39
+ const next = list.at(-1) === entry ? list : [...list, entry];
40
+ return next.slice(-REVIEW_HISTORY_MAX);
41
+ }
42
+
43
+ // A comment the server took: saved at the end of the grant's list.
44
+ export function recordReviewComment(grantId, text) {
45
+ const key = reviewHistoryKey(grantId);
46
+ if (!key) return;
47
+ writeStored(key, JSON.stringify(withComment(readReviewHistory(grantId), text)));
48
+ }
49
+
50
+ export function rememberReviewHistory(sessionId, grantId) {
51
+ if (sessionId && grantId) writeStored(`${REVIEW_HISTORY_SESSION_PREFIX}${sessionId}`, grantId);
52
+ }
53
+
54
+ export function forgetReviewHistory(grantId, sessionId) {
55
+ const sessionKey = sessionId ? `${REVIEW_HISTORY_SESSION_PREFIX}${sessionId}` : null;
56
+ const remembered = sessionKey ? readStored(sessionKey) : null;
57
+ if (sessionKey) removeStored(sessionKey);
58
+ const key = reviewHistoryKey(grantId || remembered);
59
+ if (key) removeStored(key);
60
+ }
@@ -1,6 +1,9 @@
1
1
  // The page's scope: ?dir=<folder> shows that folder's project (`chi web` in
2
- // a repo opens it so); no dir shows every session. The hash routes
3
- // (#/s/<id>, #/sessions) work in either.
2
+ // a repo opens it so); ?scope=all shows every session. A bare page is chi
3
+ // web's start folder's project when that folder is in a repo (the server
4
+ // names it in data-scope-dir; web.start_dir, --start-dir), else every
5
+ // session. ?dir= beats ?scope=all. The hash routes (#/s/<id>, #/sessions)
6
+ // work in each.
4
7
  import { html, nothing } from "./vendor/lit-html.js";
5
8
 
6
9
  // The ?dir= folder in a location.search string, or null.
@@ -9,13 +12,14 @@ export function scopeDir(search) {
9
12
  return dir && dir.trim() ? dir : null;
10
13
  }
11
14
 
12
- // The same place in the all view: the page without ?dir, keeping the hash.
13
- // +fromDir+ (the project view's folder) rides along as ?from=, so the all
14
- // view can link back to it. +search+ (the page's location.search) keeps
15
- // its ?view= (VIEW_PARAM) on the new page.
15
+ // The same place in the all view: ?scope=all without ?dir (a bare page
16
+ // may be the start folder's project), keeping the hash. +fromDir+ (the
17
+ // project view's folder) rides along as ?from=, so the all view can link
18
+ // back to it. +search+ (the page's location.search) keeps its ?view=
19
+ // (VIEW_PARAM) on the new page.
16
20
  export function allScopeHref(hash, fromDir = null, search = "") {
17
- const params = [fromDir ? `from=${dirParam(fromDir)}` : "", viewParam(search)].filter(Boolean);
18
- return `/${params.length ? `?${params.join("&")}` : ""}${hash || ""}`;
21
+ const params = ["scope=all", fromDir ? `from=${dirParam(fromDir)}` : "", viewParam(search)].filter(Boolean);
22
+ return `/?${params.join("&")}${hash || ""}`;
19
23
  }
20
24
 
21
25
  // A folder's project view, keeping the hash and +search+'s ?view=.
@@ -28,7 +28,7 @@ export function reducedMotion() {
28
28
 
29
29
  // +observed+: the elements whose size changes refit the frame (the stage's
30
30
  // slots, in the order they are observed).
31
- export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, holdEl, asking, extras, dockEl, centerEl, composerEl, observed, isHolding, isCollapsed, isCloudOpen, isRoomCap = () => false }) {
31
+ export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, holdEl, asking, extras, dockEl, centerEl, observed, isHolding, isCollapsed, isCloudOpen, isRoomCap = () => false }) {
32
32
  // The frame (fitFrame): the height held while the turn runs and the
33
33
  // tallest content seen.
34
34
  let held = null;
@@ -71,11 +71,13 @@ export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, h
71
71
  }
72
72
 
73
73
  // Scrolls the stage to show +slot+: eased, or at once (+now+: the cap
74
- // dropped under it). +fromStart+: revealTop's.
74
+ // dropped under it; a running ease stops, or its next frame would take
75
+ // the scroll back toward its target for the taller stage). +fromStart+:
76
+ // revealTop's.
75
77
  function reveal(slot, { now = false, fromStart = false } = {}) {
76
78
  const top = revealTop(slot, { fromStart });
77
79
  if (top === null) return;
78
- if (now) scroller.scrollTop = top;
80
+ if (now) easeScrollTo(scroller, top, { reduce: true });
79
81
  else easeStage(top);
80
82
  }
81
83
 
@@ -98,8 +100,11 @@ export function createStageFrame({ stage, scroller, status, cloud, queuedSlot, h
98
100
  requestAnimationFrame(() => reveal(extras, { now: true }));
99
101
  }
100
102
  }
103
+ // The whole dock, not only its composer card: the info bar under it
104
+ // fills and wraps after a load (the session's facts arrive), and a cap
105
+ // read before that would stay above the panel.
101
106
  new ResizeObserver(() => fitCap()).observe(centerEl);
102
- new ResizeObserver(() => fitCap()).observe(composerEl);
107
+ new ResizeObserver(() => fitCap()).observe(dockEl);
103
108
  window.addEventListener("resize", fitCap);
104
109
 
105
110
  // ── the frame: the one place that writes the stage's height ────────────
@@ -52,15 +52,15 @@ function readCollapsed() {
52
52
  }
53
53
 
54
54
  // +historyNearBottom+: the history's own follow check (the hand-off scrolls
55
- // the history only for a reader at its end). +dockEl+, +centerEl+ and
56
- // +composerEl+ size the stage's cap.
55
+ // the history only for a reader at its end). +dockEl+ and +centerEl+ size
56
+ // the stage's cap.
57
57
  // +taskStop+: the page's stopper (task_stop.js), for the stop-task button
58
58
  // on a running task_wait. +renderMarkdown+ and +linkRefs+: the asking
59
59
  // slot's markdown read and ref pass (stage_slots.js). +workingSet+: the
60
60
  // page's working set (working_set_view.js, web.working_set; null: off): its
61
61
  // rail in the live slots, its footprint at the hand-off.
62
62
  export function createStageView({
63
- historyEl, appendToHistory, isNearBottom: historyNearBottom, sawText, sessionId, dockEl, centerEl, composerEl, taskStop = null,
63
+ historyEl, appendToHistory, isNearBottom: historyNearBottom, sawText, sessionId, dockEl, centerEl, taskStop = null,
64
64
  renderMarkdown, linkRefs, workingSet = null,
65
65
  }) {
66
66
  // The dock becomes a clear column: the stage's card, then the composer's
@@ -521,7 +521,7 @@ export function createStageView({
521
521
  // The cap and the frame (stage_frame.js): the stage's height, held while
522
522
  // it holds a turn, and its own scrolls.
523
523
  const frame = createStageFrame({
524
- stage, scroller, status, cloud, queuedSlot, holdEl, asking, extras, dockEl, centerEl, composerEl,
524
+ stage, scroller, status, cloud, queuedSlot, holdEl, asking, extras, dockEl, centerEl,
525
525
  observed: [status, promptSlot, live, extras, answer, tail, cloudBody, cloud, queuedSlot],
526
526
  isHolding: () => holding,
527
527
  isCollapsed: () => collapsed,
@@ -16,6 +16,9 @@ export function chipModel(summary) {
16
16
  const label = summary.label || summary.name;
17
17
  const parts = [`Toolkit: ${label}, the tools this session declares.`];
18
18
  if (summary.fallback) parts.push(`${summary.fallback}: every tool is declared (full) until it resolves.`);
19
+ if (Array.isArray(summary.groups)) {
20
+ parts.push(`Source groups: ${summary.groups.length ? summary.groups.join(", ") : "none"}.`);
21
+ }
19
22
  const reachable = Array.isArray(summary.reachable) ? summary.reachable : [];
20
23
  const removed = Array.isArray(summary.removed) ? summary.removed : [];
21
24
  if (reachable.length) {
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "json"
4
+ require "uri"
4
5
  require "time"
5
6
  require_relative "attention"
6
7
  require_relative "../../log"
@@ -57,11 +58,23 @@ module Samagotchi
57
58
  # recently and isn't in sent.json.
58
59
  CATCH_UP = 3600
59
60
 
60
- Show = Data.define(:attention, :title, :body, :at)
61
+ # url: the page the notification opens (Notifier.session_url).
62
+ Show = Data.define(:attention, :title, :body, :at, :url)
61
63
  Close = Data.define(:keys)
62
64
  # One device's show, again at +at+ (the push service said when).
63
65
  Retry = Data.define(:show, :sub_id, :at)
64
66
 
67
+ # The page a session's notification opens: the session in its own
68
+ # project's view (?dir=<its project root>), or in the all view
69
+ # (?scope=all) for a session in no repo, never chi web's bare page
70
+ # (its start folder's project). The service worker navigates an open
71
+ # window to it, query and all.
72
+ def self.session_url(summary)
73
+ root = summary[:project_root]
74
+ scope = root ? "dir=#{URI.encode_www_form_component(root).gsub("%2F", "/")}" : "scope=all"
75
+ "/?#{scope}#/s/#{summary[:id]}"
76
+ end
77
+
65
78
  # @param store [Store] the devices (and the key the client signs with)
66
79
  # @param client [#deliver] Client
67
80
  # @param origin [String] this run's public origin: only the
@@ -203,7 +216,8 @@ module Samagotchi
203
216
 
204
217
  def enqueue_show(attention, summary)
205
218
  title, body = Attention.text(summary, attention.reason)
206
- @queue << Show.new(attention: attention, title: title, body: body, at: @now.call)
219
+ @queue << Show.new(attention: attention, title: title, body: body, at: @now.call,
220
+ url: Notifier.session_url(summary))
207
221
  end
208
222
 
209
223
  def run
@@ -302,7 +316,7 @@ module Samagotchi
302
316
 
303
317
  def show_payload(show, open)
304
318
  payload = { v: 1, kind: "show", tag: show.attention.key, title: show.title, body: show.body,
305
- url: "/#/s/#{show.attention.session_id}", badge: open.size }
319
+ url: show.url, badge: open.size }
306
320
  with_open = payload.merge(open: open)
307
321
  JSON.generate(with_open).bytesize <= OPEN_LIMIT ? with_open : payload
308
322
  end
@@ -30,9 +30,12 @@ module Samagotchi
30
30
 
31
31
  # @return [String] +path+
32
32
  # @param public_url [String, nil] the https origin it runs behind
33
- def record(port:, path: self.path, pid: Process.pid, public_url: nil)
33
+ # @param identity_header [String, nil] the header that proxy names the
34
+ # signed-in user in (a --tunnel's, which no config has)
35
+ def record(port:, path: self.path, pid: Process.pid, public_url: nil, identity_header: nil)
34
36
  FileUtils.mkdir_p(File.dirname(path))
35
- AtomicFile.write(path, JSON.generate({ pid: pid, port: port, public_url: public_url }.compact))
37
+ AtomicFile.write(path, JSON.generate({ pid: pid, port: port, public_url: public_url,
38
+ identity_header: identity_header }.compact))
36
39
  end
37
40
 
38
41
  # Removes the file when this process wrote it (a second chi web's
@@ -57,14 +60,14 @@ module Samagotchi
57
60
  # @return [PublicUrl, nil]
58
61
  def live_public_url(path: self.path, probe: ->(port) { InfoProbe.call("127.0.0.1", port, timeout: PROBE_TIMEOUT) })
59
62
  data = read(path) or return nil
60
- pid, port, url = data.values_at("pid", "port", "public_url")
63
+ pid, port, url, header = data.values_at("pid", "port", "public_url", "identity_header")
61
64
  return nil unless pid.is_a?(Integer) && pid.positive? && port.is_a?(Integer) && port.positive? && url.is_a?(String)
62
65
  return nil unless alive?(pid)
63
66
 
64
67
  info = probe.call(port)
65
68
  return nil unless info.is_a?(Hash) && info["pid"] == pid
66
69
 
67
- PublicUrl.from_config(url: url)
70
+ PublicUrl.from_config(url: url, identity_header: header.is_a?(String) ? header : nil)
68
71
  rescue PublicUrl::Invalid
69
72
  nil
70
73
  end
@@ -15,10 +15,12 @@ require_relative "public_url"
15
15
  require_relative "push"
16
16
  require_relative "qr"
17
17
  require_relative "running"
18
+ require_relative "start_dir"
18
19
  require_relative "session_hub"
19
20
  require_relative "token"
20
21
  require_relative "tunnel"
21
22
  require_relative "../config"
23
+ require_relative "../paths"
22
24
  require_relative "../project_scope"
23
25
  require_relative "../log"
24
26
  require_relative "../version"
@@ -69,25 +71,31 @@ module Samagotchi
69
71
 
70
72
  # `chi web`: one server serves every project, the scope is in the page
71
73
  # URL. If a chi web already runs on the port, print (and with --open,
72
- # open) its page for +dir+ and leave it be; else start one.
74
+ # open) its page for +start_dir+ and leave it be; else start one.
73
75
  # @param scope ["project", "all"] "all": the plain page, every session
76
+ # @param start_dir [String, nil] the folder chi web starts in
77
+ # (--start-dir, web.start_dir; StartDir.resolve, nil: the cwd): its
78
+ # project's page, and where a new session without a dir starts. A
79
+ # folder that isn't one stops it before anything else (never a chdir)
74
80
  # @param new_token [Boolean] replace the LAN access token first
75
81
  # (--new-token): a running server takes the new one at once
76
82
  # @param tunnel [String, nil] --tunnel's provider (Tunnel.for): this
77
83
  # run's public_url is the tunnel's, never config's, and the tunnel is
78
84
  # on while the server runs
79
85
  # @return [Integer] the exit status
80
- def self.launch(port: nil, host: nil, scope: "project", dir: Dir.pwd, open_browser: false, markdown: false,
86
+ def self.launch(port: nil, host: nil, scope: "project", start_dir: nil, open_browser: false, markdown: false,
81
87
  view: Config::BY_KEY["web.view"].default, annotate_presets: Config::BY_KEY["web.annotate_presets"].default,
82
88
  editor: Config::BY_KEY["web.editor"].default, new_token: false,
83
89
  working_set: Config::BY_KEY["web.working_set"].default, tunnel: nil)
90
+ start_given = !start_dir.to_s.strip.empty?
91
+ start_dir = StartDir.resolve(start_dir)
84
92
  rotate_token if new_token
85
93
  public_url = public_url_setting unless tunnel
86
94
  setting = host_setting(host)
87
95
  lan = Lan.wanted?(setting) ? Lan.choose(setting) : nil
88
96
  host = resolve_host(setting)
89
97
  port = resolve_port(port)
90
- url = scope_url(host, port, dir: dir, scope: scope)
98
+ url = scope_url(host, port, dir: start_dir, scope: scope)
91
99
  found = probe(host, port)
92
100
  raise Tunnel::AlreadyRunning, port if tunnel && found.is_a?(Hash)
93
101
 
@@ -99,6 +107,8 @@ module Samagotchi
99
107
  return 1
100
108
  end
101
109
  puts "chi web already runs on port #{port} (pid #{found["pid"]}): #{url}"
110
+ other_start = start_given && other_start_line(found["start_dir"], start_dir)
111
+ puts other_start if other_start
102
112
  puts running_lan_lines(found["lan"], port) if found["lan"]
103
113
  running_public = public_url || Running.live_public_url(probe: ->(at) { probe(host, at) })
104
114
  puts running_public_lines(running_public) if running_public
@@ -128,7 +138,7 @@ module Samagotchi
128
138
  Push.preflight!(public_url)
129
139
  options = { port: port, host: host, url: url, open_browser: open_browser, markdown: markdown, view: view,
130
140
  annotate_presets: annotate_presets, editor: editor, lan: lan, working_set: working_set,
131
- public_url: public_url }
141
+ public_url: public_url, start_dir: start_dir }
132
142
  started = if plan
133
143
  with_tunnel(provider, plan) do |up|
134
144
  start(**options, public_notes: provider.start_lines(plan), on_bound: up)
@@ -138,7 +148,7 @@ module Samagotchi
138
148
  end
139
149
  started ? 0 : 1
140
150
  end
141
- rescue Lan::Error, Grants::Insecure, PublicUrl::Invalid, Tunnel::Refused, Push::Refused, Push::Store::Insecure => e
151
+ rescue StartDir::Invalid, Lan::Error, Grants::Insecure, PublicUrl::Invalid, Tunnel::Refused, Push::Refused, Push::Store::Insecure => e
142
152
  warn "Error: #{e.message}"
143
153
  1
144
154
  rescue Interrupt
@@ -148,6 +158,15 @@ module Samagotchi
148
158
  CLI::Exit::INTERRUPTED
149
159
  end
150
160
 
161
+ # A second chi web given a start folder (--start-dir, web.start_dir)
162
+ # other than the running one's: one line saying it stays; nil when
163
+ # they match or the running one doesn't say (an older chi web).
164
+ def self.other_start_line(running, wanted)
165
+ return nil if running.nil? || running == wanted
166
+
167
+ "It starts in #{Paths.tilde(running)}; restart it to use #{Paths.tilde(wanted)}"
168
+ end
169
+
151
170
  # The tunnel on while the block runs (the server), off after it
152
171
  # whatever ends it (Ctrl-C, SIGTERM, SIGHUP), once #up may have taken
153
172
  # effect: a refusal before it turns off nothing (a live tunnel of
@@ -209,12 +228,13 @@ module Samagotchi
209
228
  # (the tunnel's)
210
229
  # @param on_bound [#call, nil] run once the port is bound, before any
211
230
  # line (the tunnel's #up); what it raises ends the run
231
+ # @param start_dir [String] the folder chi web starts in (App's)
212
232
  # @return [Boolean] false when the port was taken (said so on stderr)
213
233
  def self.start(port: nil, host: nil, url: nil, open_browser: false, state_dir: nil, manager: nil, markdown: false,
214
234
  view: Config::BY_KEY["web.view"].default, annotate_presets: Config::BY_KEY["web.annotate_presets"].default, hub: nil, lan: nil,
215
235
  editor: Config::BY_KEY["web.editor"].default, token_path: Token.path,
216
236
  working_set: Config::BY_KEY["web.working_set"].default, public_url: nil, public_notes: [],
217
- on_bound: nil)
237
+ on_bound: nil, start_dir: Dir.pwd)
218
238
  config_restart_unsubscribe = ConfigFile.watch_restart_settings!(process: :web) do |message|
219
239
  Samagotchi::Log.warn(:config, "restart_required", echo: "Warning: config: #{message}")
220
240
  end
@@ -229,7 +249,7 @@ module Samagotchi
229
249
  push = push_runtime(public_url, state_dir)
230
250
  app = App.new(manager: manager, state_dir: state_dir, markdown: markdown, view: view,
231
251
  annotate_presets: annotate_presets, editor: editor, hub: hub, lan: lan_option, working_set: working_set,
232
- public_url: public_url, public_token: public_token, push: push)
252
+ public_url: public_url, public_token: public_token, push: push, start_dir: start_dir)
233
253
  Samagotchi::Log.info(:web, "start", url: "http://#{host}:#{port}", version: Samagotchi::VERSION)
234
254
  Samagotchi::Log.info(:web, "lan", ip: lan.ip, interface: lan.interface) if lan
235
255
  if public_url
@@ -316,7 +336,8 @@ module Samagotchi
316
336
  # tunnel's), for chi share's link (Web::Running); a write that fails
317
337
  # leaves the server running and the readers on web.port and config.
318
338
  def self.record_running(path, port, public_url = nil)
319
- Running.record(port: port, path: path, public_url: public_url&.origin)
339
+ Running.record(port: port, path: path, public_url: public_url&.origin,
340
+ identity_header: public_url&.identity_header)
320
341
  rescue SystemCallError => e
321
342
  Samagotchi::Log.warn(:web, "running_record_failed", error: e.class.name)
322
343
  end
@@ -414,11 +435,13 @@ module Samagotchi
414
435
  DEFAULT_HOST
415
436
  end
416
437
 
417
- # The page for +dir+: its project view (?dir=) when it is in a repo,
418
- # the plain page (every session) outside one or with scope "all".
438
+ # The page for +dir+: its project view (?dir=, explicit though a bare
439
+ # page opens the start folder's project too) when it is in a repo;
440
+ # every session (?scope=all) outside one or with scope "all", as a
441
+ # running chi web's bare page may be its own start project.
419
442
  def self.scope_url(host, port, dir:, scope: "project")
420
443
  base = "http://#{url_host(host)}:#{port}/"
421
- return base if scope.to_s == "all" || ProjectScope.root_for(dir).nil?
444
+ return "#{base}?scope=all" if scope.to_s == "all" || ProjectScope.root_for(dir).nil?
422
445
 
423
446
  # Slashes stay as they are (valid in a query): a URL people can read.
424
447
  "#{base}?dir=#{URI.encode_www_form_component(dir).gsub("%2F", "/")}"
@@ -28,7 +28,7 @@ module Samagotchi
28
28
  # (request_toolkit, request_parent_answers, request_llm_context,
29
29
  # request_thinking). Included in App: its ROUTES name handle_create, and
30
30
  # its helpers (json_response, error_response, parse_json, request_body,
31
- # await_bridge_port, session_to_json, record_history, scope_dir, …) and
31
+ # await_bridge_sidecar, session_to_json, record_history, scope_dir, …) and
32
32
  # ivars (@manager, @session_class, @state_dir, @hub) answer. See
33
33
  # docs/architecture.md (chi web's routes).
34
34
  module SessionCreate
@@ -64,7 +64,7 @@ module Samagotchi
64
64
  return handle_continue(body, prompt, idle) if body.key?("continues")
65
65
 
66
66
  # dir: the folder the chat starts in (the page's scope); without it,
67
- # the server's own cwd.
67
+ # the folder chi web starts in (StartDir).
68
68
  dir, error = scope_dir(body["dir"])
69
69
  return error if error
70
70
 
@@ -103,7 +103,7 @@ module Samagotchi
103
103
  refused = create_refusal(body, idle ? body["preview"] : prompt, values: [parent_answers], model: model)
104
104
  return refused if refused
105
105
 
106
- folder = dir ? { working_directory: dir } : {}
106
+ folder = { working_directory: dir || start_dir }
107
107
  # model: the model the session starts on (the start page's picker,
108
108
  # spelled as GET /api/models lists it); blank means the default.
109
109
  folder[:model_name] = model unless model.empty?
@@ -117,7 +117,7 @@ module Samagotchi
117
117
  folder[:setup] = setup unless setup.empty?
118
118
  begin
119
119
  session = if review
120
- ReviewStart.start(subjects: review.subjects, dir: dir || Dir.pwd, model: folder[:model_name],
120
+ ReviewStart.start(subjects: review.subjects, dir: dir || start_dir, model: folder[:model_name],
121
121
  setup: setup, state_dir: @state_dir)
122
122
  else
123
123
  @manager.spawn_session(prompt: idle ? nil : prompt.to_s, state_dir: @state_dir, **folder)
@@ -130,7 +130,7 @@ module Samagotchi
130
130
  end
131
131
  # The worker's Bridge is the single live transport: wait (bounded) for
132
132
  # it so the client can attach without client-side polling.
133
- port = await_bridge_port(session.id)
133
+ port = await_bridge_sidecar(session.id)&.port
134
134
  # The projection holds it before the page hears back (no tick wait).
135
135
  @hub&.touch(session.id)
136
136
  record_history(body, prompt) if !idle && PromptHistory.shell_line?(prompt.to_s.strip)
@@ -172,7 +172,7 @@ module Samagotchi
172
172
  model: model.empty? ? nil : model)
173
173
  return error if error
174
174
 
175
- port = await_bridge_port(session.id)
175
+ port = await_bridge_sidecar(session.id)&.port
176
176
  moved = session.moved_children || []
177
177
  # The moved delegates' cards fold under the new link now.
178
178
  [session.continues, session.id, *moved].each { |sid| @hub&.touch(sid) }
@@ -228,7 +228,7 @@ module Samagotchi
228
228
  rescue ArgumentError => e
229
229
  return error_response(404, "not_found", e.message)
230
230
  end
231
- port = await_bridge_port(session.id)
231
+ port = await_bridge_sidecar(session.id)&.port
232
232
  @hub&.touch(session.id)
233
233
  json_response(201, session_to_json(session).merge(bridge_port: port, model_warning: session.model_warning))
234
234
  end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Samagotchi
4
+ module Web
5
+ # The folder chi web starts in (web.start_dir, chi web --start-dir): the
6
+ # project its bare page shows, and where a new session from the all view
7
+ # (or one created without a dir) starts. chi web's own cwd when unset; it
8
+ # never changes chi web's cwd.
9
+ module StartDir
10
+ class Invalid < StandardError; end
11
+
12
+ # +given+ as an absolute folder (~ expanded, a relative one against
13
+ # +cwd+); nil or blank: +cwd+.
14
+ # @raise [Invalid] when it is no folder
15
+ def self.resolve(given, cwd: Dir.pwd)
16
+ return File.expand_path(cwd) if given.nil? || given.to_s.strip.empty?
17
+
18
+ dir = File.expand_path(given.to_s.strip, cwd)
19
+ raise Invalid, "--start-dir #{given}: no such folder" unless File.exist?(dir)
20
+ raise Invalid, "--start-dir #{given}: not a folder" unless File.directory?(dir)
21
+
22
+ dir
23
+ end
24
+ end
25
+ end
26
+ end
@@ -103,10 +103,19 @@ module Samagotchi
103
103
  # @return [Result]
104
104
  # @raise [Timeout]
105
105
  # @raise [SystemCallError] the command can't run (ENOENT, EACCES)
106
- def call(argv, timeout:)
106
+ # +before_timeout+ lets a test synchronize the deadline with a
107
+ # child-side ready signal; the timeout starts after it returns.
108
+ def call(argv, timeout:, before_timeout: nil)
107
109
  Open3.popen3(*argv, pgroup: true) do |stdin, out, err, wait|
108
110
  stdin.close
109
111
  readers = [out, err].map { |io| Thread.new { io.read }.tap { |t| t.report_on_exception = false } }
112
+ begin
113
+ before_timeout&.call
114
+ rescue StandardError
115
+ stop(wait.pid)
116
+ readers.each { |reader| reader.join(1) }
117
+ raise
118
+ end
110
119
  unless wait.join(timeout)
111
120
  stop(wait.pid)
112
121
  readers.each { |reader| reader.join(1) }
@@ -12,12 +12,14 @@ module Samagotchi
12
12
  # badge), the input-file format it reads (SessionInbox::INPUT_FORMAT) and
13
13
  # what else it can do (Bridge::FEATURES), and its Bridge's epoch (the
14
14
  # one worker identity: the epoch in every event id, so a remote client
15
- # tells a restarted worker apart; nil from a worker before it). The
16
- # Bridge writes it on start
15
+ # tells a restarted worker apart; nil from a worker before it), and its
16
+ # Bridge's secret (every request names it in X-Chi-Bridge, Bridge#secret_ok?;
17
+ # nil from a worker before it, which asks for none). The Bridge writes it
18
+ # on start
17
19
  # and removes it on stop; one a dead worker left stays until a client's
18
20
  # probe finds its port closed (.live with unlink: true).
19
21
  class WorkerSidecar < Data.define(:port, :bind, :session_id, :started_at, :version, :input_format, :features,
20
- :epoch)
22
+ :epoch, :secret)
21
23
  FILE = "bridge.json"
22
24
  # Seconds a liveness probe waits for the port to take a connect.
23
25
  PROBE_TIMEOUT = 0.2
@@ -33,11 +35,17 @@ module Samagotchi
33
35
  port = data["port"]
34
36
  new(port: port.respond_to?(:to_i) ? port.to_i : 0, bind: data["bind"], session_id: data["session_id"],
35
37
  started_at: data["started_at"], version: data["version"], input_format: data["input_format"],
36
- features: Array(data["features"]).map(&:to_s), epoch: data["epoch"]&.to_s)
38
+ features: Array(data["features"]).map(&:to_s), epoch: data["epoch"]&.to_s, secret: secret_in(data["secret"]))
37
39
  rescue JSON::ParserError, SystemCallError
38
40
  nil
39
41
  end
40
42
 
43
+ # The shape a Bridge's secret has (Bridge#initialize): anything else
44
+ # (a hand-edited file) is read as none, so it never reaches a header.
45
+ SECRET_SHAPE = /\A\h{32,128}\z/
46
+
47
+ def self.secret_in(value) = value.is_a?(String) && SECRET_SHAPE.match?(value) ? value : nil
48
+
41
49
  # The sidecar of a worker whose Bridge takes a connect on its port, or
42
50
  # nil. One whose port refuses (its worker died) is stale: +unlink+
43
51
  # removes it (the clients that would talk to it), else it stays (a
@@ -64,20 +72,23 @@ module Samagotchi
64
72
  nil
65
73
  end
66
74
 
67
- # @return [Integer, nil] .live's port
68
- def self.live_port(session_dir, unlink:, host: "127.0.0.1") = live(session_dir, unlink: unlink, host: host)&.port
69
-
70
75
  def initialize(port:, bind: nil, session_id: nil, started_at: nil, version: nil, input_format: nil, features: [],
71
- epoch: nil) = super
76
+ epoch: nil, secret: nil) = super
77
+
78
+ # The secret never shows in an inspect (a log line, an error's message).
79
+ def inspect = "#<#{self.class.name} port=#{port} session_id=#{session_id.inspect} epoch=#{epoch.inspect}>"
80
+ alias to_s inspect
72
81
 
73
- # Written whole or not at all, readable by this user only (0600: no
74
- # other account learns the worker's port from it); input_format and
75
- # epoch only when they name one.
82
+ # Written whole or not at all, readable by this user only (0600 from the
83
+ # moment the file exists, AtomicFile: no other account learns the
84
+ # worker's port or its secret from it); input_format, epoch and secret
85
+ # only when they name one.
76
86
  def write(session_dir)
77
87
  FileUtils.mkdir_p(session_dir)
78
88
  record = to_h.transform_keys(&:to_s)
79
89
  record.delete("input_format") if input_format.nil?
80
90
  record.delete("epoch") if epoch.nil?
91
+ record.delete("secret") if secret.nil?
81
92
  AtomicFile.write(self.class.path(session_dir), "#{JSON.pretty_generate(record)}\n", perm: 0o600)
82
93
  end
83
94
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: samagotchi
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.119.0
4
+ version: 0.121.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dmitry Dedov
@@ -198,6 +198,7 @@ files:
198
198
  - lib/samagotchi/bridge_client/event_stream.rb
199
199
  - lib/samagotchi/bridge_client/sse_parser.rb
200
200
  - lib/samagotchi/bridge_client/stream_request.rb
201
+ - lib/samagotchi/bridge_secret.rb
201
202
  - lib/samagotchi/broadcast/recipients.rb
202
203
  - lib/samagotchi/broadcast/scope_card.rb
203
204
  - lib/samagotchi/broadcast/tags.rb
@@ -725,6 +726,7 @@ files:
725
726
  - lib/samagotchi/web/markdown_renderer.rb
726
727
  - lib/samagotchi/web/message_display.rb
727
728
  - lib/samagotchi/web/participant_access.rb
729
+ - lib/samagotchi/web/participant_exposure.rb
728
730
  - lib/samagotchi/web/participant_review.rb
729
731
  - lib/samagotchi/web/participant_stream_filter.rb
730
732
  - lib/samagotchi/web/participant_view.rb
@@ -734,6 +736,7 @@ files:
734
736
  - lib/samagotchi/web/proxy_gate.rb
735
737
  - lib/samagotchi/web/public/activity.js
736
738
  - lib/samagotchi/web/public/annotate_actions.js
739
+ - lib/samagotchi/web/public/annotate_bar.css
737
740
  - lib/samagotchi/web/public/annotate_bar.js
738
741
  - lib/samagotchi/web/public/annotate_presets.js
739
742
  - lib/samagotchi/web/public/annotations.js
@@ -751,9 +754,11 @@ files:
751
754
  - lib/samagotchi/web/public/command_list.js
752
755
  - lib/samagotchi/web/public/command_view.js
753
756
  - lib/samagotchi/web/public/commands.js
757
+ - lib/samagotchi/web/public/composer.css
754
758
  - lib/samagotchi/web/public/composer.js
755
759
  - lib/samagotchi/web/public/composer_fold.js
756
760
  - lib/samagotchi/web/public/composer_grip.js
761
+ - lib/samagotchi/web/public/composer_mount.js
757
762
  - lib/samagotchi/web/public/composer_size.js
758
763
  - lib/samagotchi/web/public/context_chips.js
759
764
  - lib/samagotchi/web/public/copy.js
@@ -765,6 +770,7 @@ files:
765
770
  - lib/samagotchi/web/public/families_view.js
766
771
  - lib/samagotchi/web/public/favicon.svg
767
772
  - lib/samagotchi/web/public/format.js
773
+ - lib/samagotchi/web/public/forms.css
768
774
  - lib/samagotchi/web/public/hold.js
769
775
  - lib/samagotchi/web/public/icons/chi-180.png
770
776
  - lib/samagotchi/web/public/icons/chi-192.png
@@ -791,6 +797,7 @@ files:
791
797
  - lib/samagotchi/web/public/notify.js
792
798
  - lib/samagotchi/web/public/participant.html
793
799
  - lib/samagotchi/web/public/participant.js
800
+ - lib/samagotchi/web/public/participant_annotate.js
794
801
  - lib/samagotchi/web/public/participant_model.js
795
802
  - lib/samagotchi/web/public/participant_names.js
796
803
  - lib/samagotchi/web/public/participants_panel.js
@@ -807,6 +814,7 @@ files:
807
814
  - lib/samagotchi/web/public/refs.js
808
815
  - lib/samagotchi/web/public/restore.js
809
816
  - lib/samagotchi/web/public/review_apply.js
817
+ - lib/samagotchi/web/public/review_history.js
810
818
  - lib/samagotchi/web/public/review_start.js
811
819
  - lib/samagotchi/web/public/route.js
812
820
  - lib/samagotchi/web/public/scope.js
@@ -875,6 +883,7 @@ files:
875
883
  - lib/samagotchi/web/session_hub.rb
876
884
  - lib/samagotchi/web/session_show.rb
877
885
  - lib/samagotchi/web/session_summary.rb
886
+ - lib/samagotchi/web/start_dir.rb
878
887
  - lib/samagotchi/web/token.rb
879
888
  - lib/samagotchi/web/tunnel.rb
880
889
  - lib/samagotchi/web/tunnel/tailscale.rb