@kairotic/app 0.0.0-stage → 0.2.1

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 (96) hide show
  1. package/README.md +9 -2
  2. package/index.html +1101 -0
  3. package/kairotic/api.cljs +362 -0
  4. package/kairotic/assistant.cljs +505 -0
  5. package/kairotic/backends/gun-backend.js +371 -0
  6. package/kairotic/canvas.cljs +751 -0
  7. package/kairotic/code.cljs +108 -0
  8. package/kairotic/components.cljs +838 -0
  9. package/kairotic/core.cljs +96 -0
  10. package/kairotic/corefns.cljs +473 -0
  11. package/kairotic/docs.mjs +2 -0
  12. package/kairotic/engine.cljs +482 -0
  13. package/kairotic/examples.mjs +96 -0
  14. package/kairotic/faust.cljs +225 -0
  15. package/kairotic/help.cljs +1036 -0
  16. package/kairotic/hiccup.cljs +566 -0
  17. package/kairotic/input.cljs +271 -0
  18. package/kairotic/kfile.mjs +138 -0
  19. package/kairotic/library.cljs +214 -0
  20. package/kairotic/links.cljs +41 -0
  21. package/kairotic/mt.cljs +1604 -0
  22. package/kairotic/mtboxes.cljs +276 -0
  23. package/kairotic/packages/analysis.mjs +64 -0
  24. package/kairotic/packages/controls.mjs +28 -0
  25. package/kairotic/packages/data.mjs +22 -0
  26. package/kairotic/packages/faust-units/cmaes.mjs +82 -0
  27. package/kairotic/packages/faust-units/graph.mjs +212 -0
  28. package/kairotic/packages/faust-units/listen.mjs +125 -0
  29. package/kairotic/packages/faust-units/notation.mjs +139 -0
  30. package/kairotic/packages/faust-units/parse.mjs +439 -0
  31. package/kairotic/packages/faust-units/recipe.mjs +195 -0
  32. package/kairotic/packages/faust-units/render.mjs +69 -0
  33. package/kairotic/packages/faust-units/units.mjs +130 -0
  34. package/kairotic/packages/faust-units/view.mjs +353 -0
  35. package/kairotic/packages/faust-units.mjs +9 -0
  36. package/kairotic/packages/io.mjs +58 -0
  37. package/kairotic/packages/net.mjs +28 -0
  38. package/kairotic/packages/patterns.mjs +34 -0
  39. package/kairotic/packages/spatial.mjs +22 -0
  40. package/kairotic/packages/spectral/shift.mjs +169 -0
  41. package/kairotic/packages/spectral.mjs +16 -0
  42. package/kairotic/packages/synth.mjs +28 -0
  43. package/kairotic/packages/theory/counterpoint.mjs +798 -0
  44. package/kairotic/packages/theory/mirror.mjs +221 -0
  45. package/kairotic/packages/theory.mjs +46 -0
  46. package/kairotic/patterns.cljs +538 -0
  47. package/kairotic/presets.cljs +227 -0
  48. package/kairotic/quantize.cljs +782 -0
  49. package/kairotic/record.cljs +169 -0
  50. package/kairotic/release.cljs +90 -0
  51. package/kairotic/ring.cljs +129 -0
  52. package/kairotic/ringaudio.cljs +232 -0
  53. package/kairotic/ringcore.mjs +270 -0
  54. package/kairotic/score.cljs +176 -0
  55. package/kairotic/shapes.cljs +283 -0
  56. package/kairotic/signal.cljs +327 -0
  57. package/kairotic/sounds.cljs +565 -0
  58. package/kairotic/sounds.mjs +108 -0
  59. package/kairotic/span.cljs +129 -0
  60. package/kairotic/spell.cljs +281 -0
  61. package/kairotic/structure.cljs +145 -0
  62. package/kairotic/talk.cljs +115 -0
  63. package/kairotic/tempo.cljs +226 -0
  64. package/kairotic/treecanvas.cljs +299 -0
  65. package/kairotic/tutorials.mjs +1283 -0
  66. package/kairotic/vendor/codemirror.mjs +23 -0
  67. package/package.json +23 -4
  68. package/page/00-work.cljs +862 -0
  69. package/page/01-commands.cljs +1219 -0
  70. package/page/02-patch-view.cljs +1051 -0
  71. package/page/03-history-view.cljs +481 -0
  72. package/page/04-panels.cljs +448 -0
  73. package/page/05-gestures.cljs +1247 -0
  74. package/page/06-connection.cljs +219 -0
  75. package/page/07-claude.cljs +430 -0
  76. package/page/08-sessions.cljs +423 -0
  77. package/page/09-learn.cljs +602 -0
  78. package/page/10-embed.cljs +469 -0
  79. package/page/11-startup.cljs +61 -0
  80. package/page/12-feedback.cljs +172 -0
  81. package/page/13-perform.cljs +325 -0
  82. package/page/14-editor.cljs +656 -0
  83. package/page/15-presets.cljs +230 -0
  84. package/page/16-release.cljs +242 -0
  85. package/page/17-sounds.cljs +147 -0
  86. package/page/18-lines.cljs +594 -0
  87. package/page/19-files.cljs +247 -0
  88. package/page/19-html.cljs +152 -0
  89. package/page/20-talk.cljs +527 -0
  90. package/page/21-net.cljs +110 -0
  91. package/page/22-learn.cljs +303 -0
  92. package/page/23-ids.cljs +233 -0
  93. package/page/24-clipboard.cljs +136 -0
  94. package/page/25-tidy.cljs +74 -0
  95. package/page/26-probes.cljs +111 -0
  96. package/sources.mjs +2 -0
@@ -0,0 +1,219 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · the page, part 7 of 12: connection
3
+ ;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).
4
+
5
+ (in-ns 'user)
6
+
7
+ ;; ───────────────────────── connection to the shared history ─────────────────────────
8
+
9
+ (defn js->node [d]
10
+ (let [m (js->clj (.data d))
11
+ at (get m "at") parent (get m "parent") evs (get m "events") t (get m "t")
12
+ sess (get m "session") mg (get m "merge") ln (get m "line")]
13
+ {:id (.-id d)
14
+ :line (when (and (string? ln) (seq ln) (not= ln main-line)) ln)
15
+ :parent (when (string? parent) parent)
16
+ :at (if (number? at) at 0)
17
+ :author (str (get m "author"))
18
+ :session (when (string? sess) sess)
19
+ :merge (when (valid-pos? mg) mg)
20
+ :t (if (number? t) t 0)
21
+ :events (if (sequential? evs)
22
+ (vec (keep (fn [x] (let [v (dec* x)] (when (and (vector? v) (keyword? (first v))) v))) evs))
23
+ [])}))
24
+
25
+ (defn merge-incoming
26
+ "The segments of one line as they arrive, with yours not saved yet (or longer here than there) kept."
27
+ [local incoming]
28
+ (let [mine? (fn [n] (= (:author n) (my-author)))
29
+ pending (into {} (filter (fn [[k n]] (and (not (contains? incoming k)) (mine? n))) local))]
30
+ (into pending
31
+ (for [[k r] incoming :let [l (get local k)]]
32
+ [k (if (and l (mine? l) (> (count (:events l)) (count (:events r)))) l r)]))))
33
+
34
+ (defn on-history [snap]
35
+ (let [incoming (group-by (fn [n] (or (:line n) main-line))
36
+ (for [d (array-seq (.-docs snap)) :when (.-exists d)] (js->node d)))
37
+ by-id (fn [ns] (into {} (map (fn [n] [(:id n) n]) ns)))]
38
+ (swap! hist
39
+ (fn [h]
40
+ (let [active (active-line)
41
+ lines (disj (into (set (keys incoming)) (keys (:other h))) active)]
42
+ (assoc h
43
+ :nodes (merge-incoming (:nodes h) (by-id (get incoming active)))
44
+ :other (into {} (for [l lines] [l (merge-incoming (get-in h [:other l]) (by-id (get incoming l)))]))
45
+ :loaded true))))
46
+ (when (nil? (:pos @world))
47
+ (when-let [t (newest-tip)] (swap! world assoc :pos t)))))
48
+
49
+ (defn start-local!
50
+ "A local work begins empty: the first gesture is its root (the example work is a button away, in the history pane)."
51
+ []
52
+ (swap! hist assoc :mode :local :loaded true))
53
+
54
+ (defn setup-room!
55
+ "Presence inside the open room (one named room per shared work)."
56
+ [room]
57
+ (.onPeers room
58
+ (fn [ch]
59
+ (reset! peers
60
+ (vec (for [p (array-seq (.-peers ch)) :when (not= "agent" (.-kind p))]
61
+ {:peer (.-peer p) :by (.-by p) :me (.-isMe p) :same (.-sameTab p) :kind (.-kind p)
62
+ :session (let [s (.. p -presence -session)] (when (string? s) s))
63
+ :pos (let [pp (js->clj (.. p -presence -pos))] (when (valid-pos? pp) pp))
64
+ ;; the line they are on (#117): their position is a point of that line
65
+ :line (let [l (.. p -presence -line)] (if (and (string? l) (seq l)) l main-line))
66
+ ;; performing in a jam (issue #5): its id and the point of the history it starts from
67
+ :jam (let [j (.. p -presence -jam)] (when (string? j) j))
68
+ :jam-at (let [pp (js->clj (.. p -presence -jamAt))] (when (valid-pos? pp) pp))}))))
69
+ (fn [_] nil))
70
+ (publish-presence!))
71
+
72
+ ;; Where the page gets its database, rooms, user and Claude: inside claude.ai from the viewer
73
+ ;; (window.claude); anywhere else from a backend with the same shape (window.kairoticBackend: GUN for
74
+ ;; data and rooms, Claude with your own API key — see kairotic/backends/gun-backend.js). Study 17.
75
+ (defn backend [] (.-kairoticBackend js/window))
76
+ (defn pages? "True outside claude.ai, when the page runs on its own backend (Kairotic Pages)."
77
+ [] (boolean (and (not (.-claude js/window)) (backend))))
78
+ ;; ───── relays (Pages): which ones this page syncs through, chosen in the session manager ─────
79
+ ;; The choice is ?peer= in the address (boot.js reads it and remembers it in this browser): a list of
80
+ ;; wss://…/gun, off (no relay at all) or none (back to the site's, site/config.js). Choosing reloads the
81
+ ;; page with it. While the relays are not the site's, the address and the room links carry ?peer=, so
82
+ ;; whoever opens them syncs through the same relays and sees the same rooms.
83
+
84
+ (defn site-relays [] (vec (js->clj (or (.-KAIROTIC_PEERS js/window) #js []))))
85
+ (defn current-relays [] (vec (js->clj (or (.-kairoticPeers js/window) #js []))))
86
+
87
+ (defn relay-param
88
+ "What ?peer= must say for someone else to sync through the relays of this page: nil when they are the site's."
89
+ []
90
+ (let [c (current-relays)]
91
+ (cond (= c (site-relays)) nil
92
+ (empty? c) "off"
93
+ :else (str/join "," c))))
94
+
95
+ (defn with-relay
96
+ "url with the ?peer= of this page's relays (or without one, when they are the site's)."
97
+ [url]
98
+ (let [u (js/URL. url (.-href js/location)) p (relay-param)]
99
+ (if p (.set (.-searchParams u) "peer" p) (.delete (.-searchParams u) "peer"))
100
+ (str/replace (.toString u) #"peer=([^&#]*)" (fn [[_ v]] (str "peer=" (js/decodeURIComponent v))))))
101
+
102
+ (defn normalize-relay
103
+ "What someone writes as a relay, as GUN wants it: https://host → wss://host/gun, host:port → ws(s)://host:port/gun.
104
+ nil if it cannot be a relay."
105
+ [s]
106
+ (let [s (str/trim (str s))
107
+ s (cond (str/starts-with? s "https://") (str "wss://" (subs s 8))
108
+ (str/starts-with? s "http://") (str "ws://" (subs s 7))
109
+ (re-find #"^wss?://" s) s
110
+ (re-find #"^(localhost|127\.0\.0\.1)(:|/|$)" s) (str "ws://" s)
111
+ (seq s) (str "wss://" s)
112
+ :else s)]
113
+ (when-let [[_ scheme host path] (re-matches #"(wss?)://([^/\s,]+)(/[^\s,]*)?" s)]
114
+ (str scheme "://" host (if (or (nil? path) (= "/" path)) "/gun" path)))))
115
+
116
+ (defn relay-problem
117
+ "Why a page could not use relay url, or nil."
118
+ [url]
119
+ (cond (nil? url) "That is not a relay address: it looks like wss://host/gun."
120
+ (and (= "https:" (.-protocol js/location)) (str/starts-with? url "ws://")
121
+ (not (re-find #"^ws://(localhost|127\.0\.0\.1)[:/]" url)))
122
+ "This page is served over https, so it can only reach a relay at wss:// (a host with TLS)."
123
+ :else nil))
124
+
125
+ (defn choose-relays!
126
+ "Reloads the page syncing through v: a list of relays, \"off\" (no relay) or \"none\" (the site's)."
127
+ [v]
128
+ (let [u (js/URL. (.-href js/location))]
129
+ (.set (.-searchParams u) "peer" v)
130
+ (.assign js/location (str/replace (.toString u) #"peer=([^&#]*)" (fn [[_ x]] (str "peer=" (js/decodeURIComponent x)))))))
131
+
132
+ (defn address-carries-relay!
133
+ "Keeps ?peer= in the address while the relays are not the site's (so a copied address takes them along),
134
+ and takes it away when they are."
135
+ []
136
+ (when (and (pages?) (not embed-mode))
137
+ (let [now (.-href js/location) want (with-relay now)]
138
+ (when (not= now want)
139
+ (try (.replaceState js/history nil "" want) (catch :default _ nil))))))
140
+
141
+ (defonce relay-status (atom [])) ; [{:url :state}] while the session manager is open
142
+ (defonce relay-test (atom nil)) ; {:url :state :testing|:ok|:fail :msg}
143
+
144
+ (defn refresh-relay-status! []
145
+ (when-let [f (and (pages?) (.-relays (backend)))]
146
+ (let [st (vec (for [r (array-seq (f))] {:url (.-url r) :state (keyword (.-state r))}))]
147
+ (when (not= st @relay-status) (reset! relay-status st)))))
148
+
149
+ (defn test-relay!
150
+ "Tries to open a connection to a relay (a free one may take up to a minute to wake up)."
151
+ [url]
152
+ (reset! relay-test {:url url :state :testing})
153
+ (try
154
+ (let [ws (js/WebSocket. url)
155
+ done (fn [state msg]
156
+ (when (= (:url @relay-test) url)
157
+ (when (= :testing (:state @relay-test)) (reset! relay-test {:url url :state state :msg msg})))
158
+ (try (.close ws) (catch :default _ nil)))]
159
+ (set! (.-onopen ws) (fn [_] (done :ok "It answers.")))
160
+ (set! (.-onerror ws) (fn [_] (done :fail "It does not answer: check the address, or that the relay is running.")))
161
+ (js/setTimeout (fn [] (done :fail "No answer after 20 seconds (a free relay may take up to a minute to wake up: try again).")) 20000))
162
+ (catch :default e (reset! relay-test {:url url :state :fail :msg (str (.-message e))}))))
163
+
164
+ (def relay-states {:open ["ok" "connected"] :connecting ["wait" "connecting…"] :waiting ["wait" "waiting for it (a free relay may take a minute to wake up)"]})
165
+
166
+ (defn relay-section
167
+ "On Pages, the relays of this page in the session manager: their state, choosing others, running your own."
168
+ [open?]
169
+ (when (pages?)
170
+ (let [cur (current-relays) site (site-relays) default? (= cur site)
171
+ st (into {} (map (juxt :url :state) @relay-status))
172
+ {t-url :url t-state :state t-msg :msg} @relay-test
173
+ dot (fn [u] (let [[cls word] (get relay-states (get st u :waiting))]
174
+ (str "<span class=\"rdot " cls "\"></span><span class=\"rstate\">" word "</span>")))
175
+ summary (cond (empty? cur) "No relay: works stay in this browser, rooms reach nobody else"
176
+ default? (str "The site's relay" (when (> (count cur) 1) "s"))
177
+ :else (str "Your relay" (when (> (count cur) 1) "s")))
178
+ all-open (and (seq cur) (every? (fn [u] (= :open (get st u))) cur))]
179
+ (str "<details class=\"relays\" id=\"relays\"" (when open? " open") ">"
180
+ "<summary><span class=\"rlabel\">Relay</span> " (esc summary)
181
+ (when (seq cur) (str " <span class=\"rdot " (if all-open "ok" "wait") "\"></span>")) "</summary>"
182
+ "<p class=\"mgr-hint\">A relay is a small server that passes works and rooms between browsers and keeps a copy. "
183
+ "Everyone in a community uses the same one: the rooms of one relay are not seen through another.</p>"
184
+ (when (seq cur)
185
+ (str "<ul class=\"rlist\">"
186
+ (apply str (for [u cur]
187
+ (str "<li><code>" (esc u) "</code> " (dot u)
188
+ (when (> (count cur) 1)
189
+ (str " <button class=\"act small\" data-act=\"relay-drop\" data-url=\"" (esc u) "\">Remove</button>"))
190
+ "</li>")))
191
+ "</ul>"))
192
+ "<form class=\"new\" data-kind=\"relay\"><input id=\"relay-url\" placeholder=\"wss://your-relay.example/gun\" spellcheck=\"false\" autocomplete=\"off\">"
193
+ "<button type=\"button\" class=\"act\" data-act=\"relay-test\">Test</button>"
194
+ "<button class=\"act primary\">Use</button></form>"
195
+ (when t-url
196
+ (str "<p class=\"rtest " (name t-state) "\"><code>" (esc t-url) "</code>: "
197
+ (case t-state :testing "trying…" (esc t-msg)) "</p>"))
198
+ "<p class=\"rchoices\">"
199
+ (when-not default? (str "<button class=\"act\" data-act=\"relay-site\">Use the site's relay" (when (> (count site) 1) "s") "</button> "))
200
+ (when (seq cur) "<button class=\"act\" data-act=\"relay-off\">Work without a relay</button>")
201
+ "</p>"
202
+ "<p class=\"mgr-hint\">Changing it reloads the page. While it is not the site's, the address and the room links carry it "
203
+ "(<code>?peer=…</code>), so whoever opens them syncs through it too.</p>"
204
+ "<details class=\"rown\"><summary>Run your own relay</summary>"
205
+ "<p>On any computer or server with Node.js 18 or later:</p>"
206
+ "<pre>npx @kairotic/relay --port 8765 --data ./radata</pre>"
207
+ "<p>It answers at <code>ws://localhost:8765/gun</code>. For others to reach it, put it on a host with TLS — a small VPS, "
208
+ "<a href=\"https://render.com/deploy?repo=https://github.com/bonuoq/kairotic\" target=\"_blank\" rel=\"noopener\">Render</a>, "
209
+ "Fly.io, Railway, or your machine behind a tunnel — and use <code>wss://&lt;that host&gt;/gun</code> here. "
210
+ "It keeps what it is sent in its data folder: rooms in clear, solo works encrypted. Back that folder up. "
211
+ "<a href=\"https://github.com/bonuoq/kairotic/tree/main/relay#readme\" target=\"_blank\" rel=\"noopener\">More</a></p>"
212
+ "</details>"
213
+ "</details>"))))
214
+
215
+ (defn cuse [nm]
216
+ (cond
217
+ (.-claude js/window) (.catch (.use (.-claude js/window) nm) (fn [_] nil))
218
+ (backend) (js/Promise.resolve (aget (backend) nm))
219
+ :else (js/Promise.resolve nil)))
@@ -0,0 +1,430 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · the page, part 8 of 12: claude
3
+ ;; The page's ClojureScript, in the order it is evaluated (app/index.html lists the files).
4
+
5
+ (in-ns 'user)
6
+
7
+ ;; ───────────────────────── components written with Claude (Study 15) ─────────────────────────
8
+ ;; The page asks Claude through claude.ai's `sample` capability: on the viewer's own Claude account,
9
+ ;; with their consent. Claude gets the contract, the API, real components and the request, and can call
10
+ ;; the page's tools (kairotic.assistant) to check what it writes before it answers. The answer's source
11
+ ;; becomes a component box, written as gestures like any other.
12
+
13
+ (defonce sample-fn (atom nil))
14
+ (defonce ask-ctl (atom nil))
15
+ (defonce ask-refs (atom nil))
16
+
17
+ ;; ───── the log of requests to Claude, kept in this browser (Study 23) ─────
18
+
19
+ (def ask-log-key "kairotic.claude-log")
20
+ (defonce asking (atom nil)) ; the request on its way: {:id :t :kind :request :change :tier :lines :status :code :answer}
21
+
22
+ (defn ask-entries []
23
+ (or (try (some-> (.getItem js/localStorage ask-log-key) js/JSON.parse (js->clj :keywordize-keys true) vec)
24
+ (catch :default _ nil))
25
+ []))
26
+
27
+ (defn save-ask-entries! [es]
28
+ (let [es (vec (take-last 200 es))]
29
+ (try (.setItem js/localStorage ask-log-key (js/JSON.stringify (clj->js es)))
30
+ (catch :default _
31
+ ;; full: the older half goes
32
+ (try (.setItem js/localStorage ask-log-key (js/JSON.stringify (clj->js (vec (take-last (quot (count es) 2) es)))))
33
+ (catch :default _ nil))))))
34
+
35
+ (declare render-ask-history!)
36
+
37
+ (defn begin-ask! [kind request change?]
38
+ (reset! asking {:id (str (js/Date.now)) :t (.toISOString (js/Date.)) :kind (name kind) :request request
39
+ :change (boolean change?) :tier (some-> ($ "ask-tier") .-value) :work (:name @work)
40
+ :lines [] :status "asked"}))
41
+
42
+ (defn note-answer! [r src]
43
+ (when @asking (swap! asking assoc :answer (ai/cut (.-text r) 8000) :code src :model (.-modelTierApplied r))))
44
+
45
+ (defn end-ask! []
46
+ (when-let [a @asking]
47
+ (reset! asking nil)
48
+ (save-ask-entries! (conj (ask-entries) a))
49
+ (render-ask-history!)))
50
+
51
+ (defn ask-log! [cls text]
52
+ (when @asking
53
+ (swap! asking (fn [a] (cond-> (update a :lines conj (str (when (seq cls) (str cls ": ")) text))
54
+ (= cls "done") (assoc :status "made")
55
+ (and (= cls "err") (not= "made" (:status a))) (assoc :status "failed" :error text)))))
56
+ ;; the bar of a link (?ask=) shows the last line too
57
+ (when-let [st ($ "ab-status")] (set! (.-textContent st) text))
58
+ (when-let [ol ($ "ask-log")]
59
+ (let [li (js/document.createElement "li")]
60
+ (set! (.-className li) (or cls ""))
61
+ (set! (.-textContent li) text)
62
+ (.appendChild ol li))))
63
+
64
+ (defn fetch-text [path] (-> (js/fetch path) (.then (fn [r] (if (.-ok r) (.text r) (throw (js/Error. (str path " " (.-status r)))))))))
65
+
66
+ (defn load-ask-refs
67
+ "Promise of what Claude reads besides the request: the contract and shapes documentation, the API
68
+ and the catalog of examples (two of them given whole, the rest read with a tool). Loaded once."
69
+ []
70
+ (or @ask-refs
71
+ (let [p (-> (js/Promise.all #js [(fetch-text "kairotic/components.cljs") (fetch-text "kairotic/shapes.cljs")
72
+ (fetch-text "kairotic/api.cljs")
73
+ ((.-kairoticImport js/window) "kairotic/examples.mjs")])
74
+ (.then (fn [a]
75
+ (let [examples (:examples (js->clj (aget a 3) :keywordize-keys true))
76
+ by-name (fn [n] (first (filter #(= n (:name %)) examples)))]
77
+ {:contract (str (ai/header-of (aget a 0)) "\n\nViews — " (ai/header-of (aget a 1)))
78
+ :api (aget a 2)
79
+ :examples (vec examples)
80
+ :always (vec (keep by-name ["knob" "filter-panel"]))})))
81
+ (.catch (fn [e] (reset! ask-refs nil) (throw e))))]
82
+ (reset! ask-refs p)
83
+ p)))
84
+
85
+ (defn ask-tools
86
+ "The page functions Claude may call while it writes (small plain-data results)."
87
+ [refs]
88
+ (let [src-schema {:type "string" :description "the complete source (a component, an abstraction or a package)"}
89
+ cls-schema {:type "string" :description "which class, when the source is a package (else omit)"}
90
+ logged (fn [label f]
91
+ (fn [input _]
92
+ (-> (js/Promise.resolve nil)
93
+ (.then (fn [_] (f input)))
94
+ (.catch (fn [e] {:ok false :error (or (.-message e) (str e))}))
95
+ (.then (fn [r]
96
+ (ask-log! (if (:ok r) "ok" "err")
97
+ (str label (when-let [c (or (:class r) (:box-text r) (:name r)
98
+ (some->> (:definitions r) (map :class) seq (str/join ", ")))]
99
+ (str " · " c))
100
+ (when-let [e (or (:error r) (first (:errors r)))] (str " · " (ai/cut e 160)))))
101
+ (clj->js r))))))]
102
+ #js [#js {:name "read_example"
103
+ :description "The whole source of an example of the catalog, by name. Read the ones close to the request before writing."
104
+ :inputSchema (clj->js {:type "object" :properties {:name {:type "string"}} :required ["name"]})
105
+ :execute (logged "read example"
106
+ (fn [i] (if-let [e (first (filter #(= (str (.-name i)) (:name %)) (:examples refs)))]
107
+ {:ok true :name (:name e) :kind (:kind e) :source (:source e)}
108
+ {:ok false :error (str "no example " (.-name i))})))}
109
+ #js {:name "check_faust"
110
+ :description "Compiles Faust code with the page's compiler. Returns {ok, ins, outs, params} or {ok:false, error} with the compiler's message. Use it for every Faust source before putting it in a faust~ box."
111
+ :inputSchema (clj->js {:type "object" :properties {:code {:type "string" :description "the Faust source"}} :required ["code"]})
112
+ :execute (logged "check Faust" (fn [i] (ai/compile-faust (str (.-code i)))))}
113
+ #js {:name "check_component"
114
+ :description "Evaluates the whole source and validates it: every definition, the patch of abstractions (classes that exist, valid ports in every line) and the Faust inside them, compiled. Returns {ok, definitions, errors}. Call it before answering, and again after every fix."
115
+ :inputSchema (clj->js {:type "object" :properties {:source src-schema} :required ["source"]})
116
+ :execute (logged "check" (fn [i] (ai/check-full (str (.-source i)))))}
117
+ #js {:name "try_messages"
118
+ :description "Sends messages to a component's :receive one after another (its state carried over, as in the engine) and returns what each returned (out, show, effects, later, state) or the error. Not for abstractions (they are patches). args_text is what follows the class in the box text, e.g. \"0 1 log\"."
119
+ :inputSchema (clj->js {:type "object"
120
+ :properties {:source src-schema :class cls-schema
121
+ :args_text {:type "string" :description "words after the class in the box text (may be empty)"}
122
+ :messages {:type "string" :description "EDN vector of [inlet value], e.g. [[0 440] [0 :bang] [1 [1 2]]]"}}
123
+ :required ["source" "messages"]})
124
+ :execute (logged "try messages" (fn [i] (ai/try-receive (str (.-source i)) (str (or (.-class i) "")) (str (or (.-args_text i) "")) (str (.-messages i)))))}
125
+ #js {:name "try_view"
126
+ :description "Draws a component's own view (:view with :derive, or :draw) for a shown value and box text, and reports shapes without a valid kind, holes without a value and non-finite numbers; with a :gesture it also tries one drag and what :persist would write."
127
+ :inputSchema (clj->js {:type "object"
128
+ :properties {:source src-schema :class cls-schema
129
+ :args_text {:type "string"}
130
+ :shown {:type "string" :description "EDN of the last shown value, e.g. 0.5 or [0.2 0.8], or empty"}}
131
+ :required ["source"]})
132
+ :execute (logged "try view" (fn [i] (ai/try-view (str (.-source i)) (str (or (.-class i) "")) (str (or (.-args_text i) "")) (str (or (.-shown i) "")))))}
133
+ #js {:name "list_classes"
134
+ :description "The box classes the work knows now (core, packages, the work's own), one line each: name, [inlets outlets], first sentence of its doc."
135
+ :execute (logged "list classes" (fn [_] {:ok true :classes (ai/classes)}))}]))
136
+
137
+ (declare open-definition)
138
+
139
+ (defn selected-component
140
+ "The component box chosen in the Components tab (or open in the code window), if it is in the patch on
141
+ screen: [id source]."
142
+ []
143
+ (let [[path id] (or @chosen-def (open-definition))
144
+ b (when (= (vec path) (cmd-path)) (get-in (current) [:boxes id]))]
145
+ (when (definition? b) [id (str (get-in b [:data :source]))])))
146
+
147
+ (defn ask-busy! [busy?]
148
+ (set! (.-disabled ($ "ask-go")) busy?)
149
+ (set! (.-disabled ($ "ask-stop")) (not busy?)))
150
+
151
+ (defn ask-error-copy [code]
152
+ (case code
153
+ "not_granted" (if (some-> @sample-fn .-byok) "There is no API key, or it was refused: paste yours above." "Claude is not allowed for this page (you can allow it next time you open it).")
154
+ "sampling_disabled" "Claude is not available for this account."
155
+ "rate_limited" "Too many requests, or your Claude usage limit: try again later."
156
+ "session_expired" "Sign in to Claude again."
157
+ "refused" "Claude declined this request: try asking it differently."
158
+ "prompt_too_large" "The request is too large."
159
+ "no_credit" "Your Anthropic account has no credit left (console.anthropic.com → Billing)."
160
+ "overloaded" "Claude is overloaded right now: try again in a moment."
161
+ "no_model" "The API does not know the model asked for."
162
+ "tools_unavailable" "This view cannot let Claude try the component."
163
+ (str "Claude could not answer (" code ").")))
164
+
165
+ (defn ask-component!
166
+ "Asks Claude for a component (or a change to the selected component box) described by `request`."
167
+ ([] (ask-component! (.-value ($ "ask-text"))))
168
+ ([request]
169
+ (let [s @sample-fn request (str/trim (str request))
170
+ change (when (.-checked ($ "ask-change")) (selected-component))
171
+ out ($ "ask-out")]
172
+ (cond
173
+ (nil? s) (repl-print! "err" "Claude is not available in this view (it needs claude.ai).")
174
+ (empty? request) (ask-log! "err" "Describe the component first.")
175
+ :else
176
+ (let [ctl (js/AbortController.)]
177
+ (reset! ask-ctl ctl)
178
+ (set! (.-innerHTML ($ "ask-log")) "")
179
+ (set! (.-textContent out) "")
180
+ (ask-busy! true)
181
+ (begin-ask! :component request change)
182
+ (ask-log! "" (if change (str "changing " (name (first change)) " · thinking…") "thinking…"))
183
+ ;; everything inside the promise chain: whatever fails, the panel is released in .finally
184
+ (-> (js/Promise.resolve nil)
185
+ (.then (fn [_] (js/Promise.all #js [(load-ask-refs)
186
+ (-> (js/Promise.resolve (when (fn? (.-limits s)) (.limits s)))
187
+ (.catch (fn [_] nil)))])))
188
+ (.then (fn [a]
189
+ (let [refs (aget a 0) lim (aget a 1)
190
+ input (ai/prompt (assoc refs :request request :change (second change)))
191
+ opts (cond-> {:modelTier (.-value ($ "ask-tier")) :signal (.-signal ctl)
192
+ :onText (fn [u] (set! (.-textContent out) (.-text u)))}
193
+ (and lim (.-tools lim)) (assoc :tools (ask-tools refs)))]
194
+ (s input (clj->js opts)))))
195
+ (.then (fn [r]
196
+ (let [src (ai/source-of (.-text r)) _ (note-answer! r src)]
197
+ (if (nil? src)
198
+ (ask-log! "err" "The answer has no source block: try again or ask differently.")
199
+ (-> (ai/check-full src)
200
+ (.then (fn [chk]
201
+ (if-not (:ok chk)
202
+ (ask-log! "err" (str "The source does not work: " (or (:error chk) (str/join "; " (:errors chk))) " (it is in the answer above)."))
203
+ (let [names (mapv :class (:definitions chk))
204
+ what (or (:package chk) (first names))
205
+ hdr (str ";; " what " · written with Claude\n"
206
+ ";; asked: " (str/replace (ai/cut request 300) #"\s+" " ") "\n")
207
+ id (if change
208
+ (let [id (first change)] (gesture! (str "(code " id " " (pr-str (str hdr src)) ")")) id)
209
+ (new-definition! (str hdr src)))]
210
+ ;; the official classes its abstractions use come into the work too
211
+ (doseq [k (ai/used-classes src)] (ensure-class! (str k)))
212
+ (ask-log! "done" (str (str/join ", " (map #(str "«" % "»") names)) " in the work (" (name id) "): write "
213
+ (str "«" (last names) "»") " in a box to use it."))
214
+ (when (.-truncated r) (ask-log! "err" "The answer was cut short.")))))))))))
215
+ (.catch (fn [e]
216
+ (let [code (or (.-code e) "error")]
217
+ (when-not (= code "cancelled")
218
+ (ask-log! "err" (if (= code "error") (str "Error: " (or (.-message e) e)) (str (ask-error-copy code) (when-let [m (.-message e)] (str " — " (ai/cut m 400))))))))))
219
+ (.finally (fn [] (ask-busy! false) (reset! ask-ctl nil) (end-ask!)))))))
220
+ :asking))
221
+
222
+ (defn ask-what [] (if (.-checked (.querySelector js/document "input[name=ask-what][value=component]")) :component :patch))
223
+
224
+ (defn render-ask-mode! []
225
+ (let [patch? (= :patch (ask-what)) byok (some-> @sample-fn .-byok)]
226
+ (set! (.-textContent ($ "ask-change-t")) (if patch? "change the open patch" "change the selected component"))
227
+ (set! (.-title ($ "ask-change-l")) (if patch? "Claude gets the open patch and changes it; unchecked, it makes a new one" "Choose a component in the Components tab first (a click on its row)"))
228
+ (set! (.-checked ($ "ask-change")) patch?)
229
+ (set! (.-textContent ($ "ask-go")) (if patch? "Make it" "Write it"))
230
+ (set! (.-placeholder ($ "ask-text"))
231
+ (if patch?
232
+ "A hello world: a sine at 440 Hz with a volume knob… · add a knob that does FM synthesis… · a canon in two voices played by synth~…"
233
+ "A stereo chorus in Faust with rate and depth knobs on its panel… · a resonant filter whose cutoff follows an envelope… · a Markov chain of pitch classes…"))
234
+ (set! (.-innerHTML ($ "ask-note"))
235
+ (str (if patch?
236
+ "Describe a patch and Claude makes it — or changes the open one — checks it (classes, ports, Faust) and loads it as one event of the history."
237
+ "Describe a component and Claude writes it, tries it and puts it in the work as a component box, like one you wrote.")
238
+ (if byok
239
+ " Here, outside claude.ai, it uses <b>your own Anthropic API key</b> (console.anthropic.com): it stays in this browser and is only sent to api.anthropic.com, so you pay your own use."
240
+ " It uses <b>your own</b> Claude account: the first time, Claude asks you to allow this page.")))))
241
+
242
+ (.addEventListener (.querySelector js/document ".ask-what") "change" (fn [_] (render-ask-mode!)))
243
+
244
+ ;; ───── patches made by Claude (Study 23) ─────
245
+
246
+ (declare link-code)
247
+
248
+ (defn ensure-classes!
249
+ "After a whole patch is loaded: the official classes its boxes use come into the work (a definition
250
+ that was there before the load may have gone with it)."
251
+ []
252
+ (doseq [b (vals (:boxes (eng/flat (root-patch))))] (ensure-class! (str (:text b)))))
253
+
254
+ (defn check-patch-code
255
+ "Promise of {:ok :errors :boxes}: whether patch code (as a link carries it) makes a patch that works —
256
+ only patch calls, classes that exist, lines between ports that exist, Faust that compiles and
257
+ components that evaluate. Nothing goes into the work."
258
+ [src]
259
+ (-> (js/Promise.resolve nil)
260
+ (.then (fn [_]
261
+ (let [p (build (link-code src))
262
+ bs (:boxes p)
263
+ k-of (fn [b] (klass (:text b)))
264
+ known? (fn [k] (or (comp/lookup k) (lib/package-of k)))
265
+ unknown (vec (for [[id b] bs :let [k (k-of b)] :when (not (known? k))] (str (name id) ": no class «" k "»")))
266
+ fausts (vec (for [[id b] bs :when (= "faust~" (k-of b))] [id (str (get-in b [:data :source]))]))
267
+ comps (vec (for [[id b] bs :when (#{"component"} (k-of b))] [id (str (get-in b [:data :source]))]))]
268
+ (-> (js/Promise.all (into-array (concat (for [[_ src] fausts] (ai/compile-faust src))
269
+ (for [[_ src] comps] (ai/check-full src)))))
270
+ (.then (fn [rs]
271
+ (let [rs (vec (array-seq rs))
272
+ code-errs (vec (keep (fn [[[id _] r]] (when-not (:ok r) (str (name id) ": " (or (:error r) (first (:errors r))))))
273
+ (map vector (concat fausts comps) rs)))
274
+ ;; ports, now that the Faust boxes know theirs (package classes not loaded yet are left out)
275
+ io-of (fn [id] (let [b (get bs id)] (when (and b (comp/lookup (k-of b))) (io b))))
276
+ line-errs (vec (for [[a o b i :as l] (:lines p)
277
+ :let [[_ outs] (io-of a) [ins _] (io-of b)]
278
+ e [(when-not (get bs a) (str (pr-str l) ": no box " a))
279
+ (when-not (get bs b) (str (pr-str l) ": no box " b))
280
+ (when (and outs (>= o outs)) (str (pr-str l) ": " (name a) " has " outs " outlet(s)"))
281
+ (when (and ins (>= i ins)) (str (pr-str l) ": " (name b) " has " ins " inlet(s)"))]
282
+ :when e] e))
283
+ errs (vec (concat unknown code-errs line-errs))]
284
+ {:ok (empty? errs) :errors errs
285
+ :boxes (vec (for [[id b] bs] (str (name id) " " (:text b) (when-let [x (io-of id)] (str " " (pr-str x))))))})))))))
286
+ (.catch (fn [e] {:ok false :errors [(str (or (.-message e) e))]}))))
287
+
288
+ (defn patch-tools
289
+ "The page functions Claude may call while it makes a patch."
290
+ [refs]
291
+ (let [comp-tools (ask-tools refs)
292
+ pick (fn [n] (first (filter #(= n (.-name %)) (array-seq comp-tools))))
293
+ logged (fn [label f]
294
+ (fn [input _]
295
+ (-> (js/Promise.resolve nil)
296
+ (.then (fn [_] (f input)))
297
+ (.catch (fn [e] {:ok false :errors [(or (.-message e) (str e))]}))
298
+ (.then (fn [r]
299
+ (ask-log! (if (:ok r) "ok" "err") (str label (when-let [e (first (:errors r))] (str " · " (ai/cut e 160)))))
300
+ (clj->js r))))))]
301
+ #js [(pick "list_classes") (pick "check_faust") (pick "read_example") (pick "check_component")
302
+ #js {:name "class_help"
303
+ :description "What one class does: its doc, usage, inlets and outlets (what each takes and sends), and an example."
304
+ :inputSchema (clj->js {:type "object" :properties {:class {:type "string"}} :required ["class"]})
305
+ :execute (logged "help"
306
+ (fn [i] (let [k (str (.-class i)) d (comp/lookup k) h (hlp/of k)]
307
+ (if (or d (seq h) (lib/package-of k))
308
+ {:ok true :class k :doc (or (:doc d) (:doc h)) :usage (:usage d)
309
+ :io (let [x (:io d)] (if (vector? x) x "depends on its arguments"))
310
+ :inlets (:inlets h) :outlets (:outlets h) :example (:example h)
311
+ :note (when-not d "an official class: it comes into the work when a box uses it")}
312
+ {:ok false :errors [(str "no class " k)]}))))}
313
+ #js {:name "check_patch"
314
+ :description "Checks the WHOLE patch code: only patch calls with literal arguments, classes that exist, every line between ports that exist, every Faust source compiled and every component evaluated. Returns {ok, errors, boxes}. Call it before answering, and again after every fix."
315
+ :inputSchema (clj->js {:type "object" :properties {:code {:type "string" :description "the whole patch code"}} :required ["code"]})
316
+ :execute (logged "check patch" (fn [i] (check-patch-code (str (.-code i)))))}]))
317
+
318
+ (defn apply-patch-code!
319
+ "Loads patch code made by Claude into the open work (one event). Its scripts and components run: you
320
+ asked for them."
321
+ [src]
322
+ (let [code (link-code src) p (build code)
323
+ srcs (for [b (vals (:boxes p)) :when (#{"script" "component"} (klass (:text b)))] (str (get-in b [:data :source])))]
324
+ (swap! cbox/trusted into srcs)
325
+ (cbox/forget-language! "component")
326
+ (cbox/forget-language! "clojurescript")
327
+ (dispatch! [:load p])
328
+ (ensure-classes!)
329
+ (render-all!)
330
+ code))
331
+
332
+ (defn ask-patch!
333
+ "Asks Claude for a patch described by `request` (or a change to the open one, when change? is true).
334
+ Promise of the code loaded, or nil."
335
+ [request change?]
336
+ (let [s @sample-fn request (str/trim (str request)) out ($ "ask-out")]
337
+ (cond
338
+ (nil? s) (do (ask-log! "err" "Claude is not available here.") (js/Promise.resolve nil))
339
+ (empty? request) (do (ask-log! "err" "Describe the patch first.") (js/Promise.resolve nil))
340
+ (nil? (:kind @work)) (do (ask-log! "err" "Open or create a work first.") (js/Promise.resolve nil))
341
+ :else
342
+ (let [ctl (js/AbortController.)
343
+ current (when change? (let [p (work-patch)] (when (seq (:boxes p)) (patch->code p))))]
344
+ (reset! ask-ctl ctl)
345
+ (set! (.-innerHTML ($ "ask-log")) "")
346
+ (set! (.-textContent out) "")
347
+ (ask-busy! true)
348
+ (begin-ask! :patch request current)
349
+ (ask-log! "" (if current "changing the patch · thinking…" "making the patch · thinking…"))
350
+ (-> (js/Promise.resolve nil)
351
+ (.then (fn [_] (js/Promise.all #js [(load-ask-refs)
352
+ (-> (js/Promise.resolve (when (fn? (.-limits s)) (.limits s))) (.catch (fn [_] nil)))])))
353
+ (.then (fn [a]
354
+ (let [refs (aget a 0) lim (aget a 1)
355
+ input (ai/patch-prompt {:request request :current current :classes (ai/classes)})
356
+ opts (cond-> {:modelTier (.-value ($ "ask-tier")) :signal (.-signal ctl)
357
+ :onText (fn [u] (set! (.-textContent out) (.-text u)))}
358
+ (and lim (.-tools lim)) (assoc :tools (patch-tools refs)))]
359
+ (s input (clj->js opts)))))
360
+ (.then (fn [r]
361
+ (let [src (ai/source-of (.-text r)) _ (note-answer! r src)]
362
+ (if (nil? src)
363
+ (do (ask-log! "err" "The answer has no patch code: try again or ask differently.") nil)
364
+ (.then (check-patch-code src)
365
+ (fn [chk]
366
+ (if-not (:ok chk)
367
+ (do (ask-log! "err" (str "The patch does not work yet: " (str/join "; " (take 3 (:errors chk))) " (it is in the answer, in the Claude tab).")) nil)
368
+ (let [code (apply-patch-code! src)]
369
+ (ask-log! "done" (str "Patch loaded (" (count (:boxes (work-patch))) " boxes): ▶ to hear it."
370
+ (when (.-truncated r) " The answer was cut short.")))
371
+ code))))))))
372
+ (.catch (fn [e]
373
+ (let [code (or (.-code e) "error")]
374
+ (when-not (= code "cancelled")
375
+ (ask-log! "err" (if (= code "error") (str "Error: " (or (.-message e) e)) (str (ask-error-copy code) (when-let [m (.-message e)] (str " — " (ai/cut m 400))))))))
376
+ nil))
377
+ (.finally (fn [] (ask-busy! false) (reset! ask-ctl nil) (end-ask!))))))))
378
+
379
+ (defn ask!
380
+ "The Claude tab's button: a patch or a component, as chosen."
381
+ ([] (ask! (.-value ($ "ask-text"))))
382
+ ([request]
383
+ (if (= :patch (ask-what))
384
+ (do (ask-patch! request (.-checked ($ "ask-change"))) :asking)
385
+ (ask-component! request))))
386
+
387
+ (defn ask-patch
388
+ "Asks Claude to make a patch, or change the open one: (ask-patch \"add a knob that does FM\"). Uses your
389
+ own Claude account (or your own API key outside claude.ai)."
390
+ ([request] (ask-patch request true))
391
+ ([request change?]
392
+ (set! (.-value ($ "ask-text")) (str request))
393
+ (.click ($ "tab-claude"))
394
+ (ask-patch! request change?)
395
+ :asking))
396
+
397
+ (defn ask-component
398
+ "Asks Claude to write a component: (ask-component \"a slow LFO with its waveform drawn\"). The result
399
+ is a component box in the work. Uses your own Claude account."
400
+ [request]
401
+ (set! (.-value ($ "ask-text")) (str request))
402
+ (.click ($ "tab-claude"))
403
+ (ask-component! request))
404
+
405
+ (.addEventListener ($ "ask-go") "click" (fn [_] (ask!)))
406
+ (.addEventListener ($ "ask-stop") "click" (fn [_] (when-let [c @ask-ctl] (.abort c))))
407
+ (.addEventListener ($ "ask-text") "keydown"
408
+ (fn [e] (when (and (= "Enter" (.-key e)) (or (.-ctrlKey e) (.-metaKey e))) (.preventDefault e) (ask!))))
409
+
410
+ ;; outside claude.ai Claude runs with your own Anthropic API key, kept only in this browser
411
+ (defn render-key! []
412
+ (when-let [s @sample-fn]
413
+ (when (.-byok s)
414
+ (set! (.-hidden ($ "ask-key")) false)
415
+ (set! (.-textContent ($ "ask-key-state")) (if (.hasKey s) "a key is saved in this browser" "no key yet")))))
416
+
417
+ (.addEventListener ($ "ask-key-save") "click"
418
+ (fn [_] (when-let [s @sample-fn]
419
+ (let [v (str/trim (.-value ($ "ask-key-in")))]
420
+ (when (seq v) (.setKey s v) (set! (.-value ($ "ask-key-in")) "") (render-key!))))))
421
+ (.addEventListener ($ "ask-key-forget") "click"
422
+ (fn [_] (when-let [s @sample-fn] (.setKey s nil) (render-key!))))
423
+
424
+ (-> (cuse "sample")
425
+ (.then (fn [s]
426
+ (reset! sample-fn s)
427
+ (set! (.-hidden ($ "tab-claude")) (nil? s))
428
+ (render-key!)
429
+ (render-ask-mode!)
430
+ (render-askbar!))))