@kairotic/app 0.0.0-stage → 0.2.2

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,505 @@
1
+ ;; SPDX-License-Identifier: MPL-2.0
2
+ ;; Kairotic · assistant
3
+ ;; Writing components with Claude, inside the work. The page asks Claude (claude.ai's `sample`
4
+ ;; capability, on the viewer's own Claude account) with a prompt built here: the component contract,
5
+ ;; the Kairotic API, real components as examples and the classes the work already has. While it
6
+ ;; writes, Claude can call the page's tools defined here to check what it wrote — evaluate and
7
+ ;; validate it, send it messages, draw its view — so what arrives in the work has been tried.
8
+ ;; The result is an ordinary component box, created as gestures, in the history like any other.
9
+ ;;
10
+ ;; Study 16: Claude can also write Faust (checked by compiling it), abstractions — components that are
11
+ ;; a patch, with faust~ boxes, controls and a panel of presented boxes (a bpatcher) — and packages of
12
+ ;; several components. Real examples come from a catalog (examples/catalog.mjs) that Claude sees as a
13
+ ;; list and reads one by one with a tool, so it can grow without the prompt growing.
14
+
15
+ (ns kairotic.assistant
16
+ (:require [clojure.string :as str]
17
+ [clojure.walk :as walk]
18
+ [kairotic.corefns :as cf]
19
+ [kairotic.components :as comp]
20
+ [kairotic.shapes :as shp]
21
+ [kairotic.code :as code]
22
+ [kairotic.library :as lib]))
23
+
24
+ ;; ───────── evaluating a source ─────────
25
+
26
+ (defn evaluate
27
+ "{:ok definition-or-package} or {:error reason} for a component source (one expression)."
28
+ [source]
29
+ (try
30
+ (let [m (js/scittle.core.eval_string (str "(do " source "\n)"))]
31
+ (if-let [reason (lib/validate m)] {:error reason} {:ok m}))
32
+ (catch :default e {:error (str "does not evaluate: " (or (.-message e) e))})))
33
+
34
+ (defn definition
35
+ "{:ok definition} for class `cls` of a source (a component, or one of a package's), or {:error}."
36
+ [source cls]
37
+ (let [{:keys [ok error]} (evaluate source)]
38
+ (if error
39
+ {:error error}
40
+ (let [defs (lib/definitions ok)
41
+ d (if (seq (str cls)) (first (filter #(= (str cls) (:class %)) defs)) (first defs))]
42
+ (if d {:ok d} {:error (str "no class " cls " in this source (" (str/join ", " (map :class defs)) ")")})))))
43
+
44
+ (defn read-edn
45
+ "A value written as EDN by Claude (messages, a shown value)."
46
+ [s]
47
+ (when (and (string? s) (seq (str/trim s)))
48
+ (js/scittle.core.eval_string (str "(quote " s ")"))))
49
+
50
+ (defn cut [s n] (let [s (str s)] (if (> (count s) n) (str (subs s 0 n) " …") s)))
51
+
52
+ (defn box-text [m args-text]
53
+ (str (:class m) (when (seq (str/trim (str args-text))) (str " " (str/trim args-text)))))
54
+
55
+ ;; ───────── the tools ─────────
56
+
57
+ (defn describe
58
+ "What one definition is, for Claude."
59
+ [m]
60
+ (let [io (:io m)]
61
+ (cond-> {:class (:class m)
62
+ :kind (if (:patch m) "abstraction" "component")
63
+ :io (if (fn? io) "computed" io)
64
+ :core-class-clash (= :core (:origin (comp/lookup (:class m))))}
65
+ (sequential? (:args m)) (assoc :args (pr-str (:args m)))
66
+ (not (:patch m)) (assoc :view (cond (:view m) "view template" (:draw m) "draw function" :else "text box")
67
+ :gesture (boolean (:gesture m)) :persist (boolean (:persist m))
68
+ :audio (when (map? (:audio m)) (vec (map name (keys (:audio m)))))))))
69
+
70
+ (defn check
71
+ "What a source defines, or why it does not work (synchronous: no Faust inside is compiled)."
72
+ [source]
73
+ (let [{:keys [ok error]} (evaluate source)]
74
+ (if error
75
+ {:ok false :error error}
76
+ (let [defs (lib/definitions ok)]
77
+ (assoc (describe (first defs)) :ok true
78
+ :classes (mapv :class defs)
79
+ :package (:package ok))))))
80
+
81
+ ;; ───────── Faust ─────────
82
+
83
+ (defn compile-faust
84
+ "Promise of {:ok true :ins :outs :params} or {:ok false :error} for a Faust source, compiled with the
85
+ page's own compiler (the result stays in the cache, so the box that uses it starts at once)."
86
+ [source]
87
+ (if-let [f (get @code/compilers "faust")]
88
+ (-> (js/Promise.resolve nil)
89
+ (.then (fn [_] (f (str source))))
90
+ (.then (fn [r]
91
+ (swap! code/cache assoc ["faust" (str source)] (assoc r :status :ok :n (swap! code/counter inc)))
92
+ (let [i (:info r)]
93
+ {:ok true :ins (:ins i) :outs (:outs i)
94
+ :params (mapv (fn [p] (select-keys p [:label :type :min :max :init])) (:params i))})))
95
+ (.catch (fn [e] {:ok false :error (cut (or (.-message e) (str e)) 1500)})))
96
+ (js/Promise.resolve {:ok false :error "no Faust compiler in this page"})))
97
+
98
+ ;; ───────── abstractions ─────────
99
+
100
+ (defn available?
101
+ "Whether class k can be used in a patch: known now, defined next to it, or brought from an official
102
+ package when it is used."
103
+ [k siblings]
104
+ (boolean (or (comp/lookup k) (contains? siblings k) (lib/package-of k))))
105
+
106
+ (defn check-patch
107
+ "Errors of the :patch of an abstraction (boxes, classes, ports), and what it offers."
108
+ [m siblings]
109
+ (let [p (:patch m) bs (:boxes p) lines (:lines p)
110
+ k-of (fn [b] (comp/klass (str/replace (str (:text b)) #"\$\d" "0")))
111
+ box-errs (for [[id b] bs
112
+ :let [k (k-of b)]
113
+ err [(when-not (keyword? id) (str id ": box ids are keywords like :b1"))
114
+ (when-not (string? (:text b)) (str id ": a box has :text"))
115
+ (when-not (and (number? (:x b)) (number? (:y b))) (str id ": a box has :x and :y"))
116
+ (when (and (string? (:text b)) (not (available? k siblings))) (str id ": no class «" k "»"))
117
+ (when (and (= k "faust~") (str/blank? (str (get-in b [:data :source])))) (str id ": a faust~ needs :data {:source \"…\"}"))]
118
+ :when err] err)
119
+ io-of (fn [id] (let [b (get bs id)] (when (and b (comp/lookup (k-of b)) (not (comp/dynamic? b)))
120
+ (comp/io (update b :text #(str/replace (str %) #"\$\d" "0"))))))
121
+ line-errs (for [l lines
122
+ :let [[a o b i] (when (and (vector? l) (= 4 (count l))) l)
123
+ [_ outs] (io-of a) [ins _] (io-of b)]
124
+ err [(when-not a (str (pr-str l) ": a line is [from outlet to inlet]"))
125
+ (when (and a (not (get bs a))) (str (pr-str l) ": no box " a))
126
+ (when (and b (not (get bs b))) (str (pr-str l) ": no box " b))
127
+ (when (and outs (>= o outs)) (str (pr-str l) ": " a " has " outs " outlets"))
128
+ (when (and ins (>= i ins)) (str (pr-str l) ": " b " has " ins " inlets"))]
129
+ :when err] err)
130
+ ports (fn [ks] (count (filter (fn [[_ b]] (ks (k-of b))) bs)))]
131
+ {:errors (vec (concat box-errs line-errs))
132
+ :inlets (ports #{"inlet" "inlet~"}) :outlets (ports #{"outlet" "outlet~"})
133
+ :presented (vec (for [[id b] bs :when (:present b)] (str (name id) " " (:text b))))
134
+ :faust (vec (for [[id b] bs :when (= "faust~" (k-of b))] [id (get-in b [:data :source])]))}))
135
+
136
+ (defn check-full
137
+ "Promise of the whole check of a source, for Claude and before a result enters the work: it
138
+ evaluates and validates every definition, checks the patch of abstractions and compiles every
139
+ Faust source inside them."
140
+ [source]
141
+ (let [{:keys [ok error]} (evaluate source)]
142
+ (if error
143
+ (js/Promise.resolve {:ok false :error error})
144
+ (let [defs (vec (lib/definitions ok))
145
+ siblings (set (map :class defs))
146
+ patches (into {} (for [d defs :when (map? (:patch d))] [(:class d) (check-patch d siblings)]))
147
+ fausts (for [[cls r] patches [id src] (:faust r)] [cls id src])]
148
+ (-> (js/Promise.all (clj->js (for [[_ _ src] fausts] (compile-faust src))))
149
+ (.then (fn [results]
150
+ (let [faust-errs (vec (keep (fn [[[cls id _] r]] (when-not (:ok r) (str cls " " (name id) ": Faust: " (:error r))))
151
+ (map vector fausts (js->clj results :keywordize-keys true))))
152
+ errs (vec (concat (mapcat (fn [[cls r]] (map #(str cls " " %) (:errors r))) patches) faust-errs))]
153
+ {:ok (empty? errs)
154
+ :package (:package ok)
155
+ :definitions (mapv (fn [d] (merge (describe d)
156
+ (when-let [r (get patches (:class d))]
157
+ (select-keys r [:inlets :outlets :presented]))))
158
+ defs)
159
+ :errors errs}))))))))
160
+
161
+ (defn used-classes
162
+ "The classes that the abstractions of a source use (to bring the official ones into the work)."
163
+ [source]
164
+ (let [{:keys [ok]} (evaluate source)]
165
+ (when ok
166
+ (distinct (for [d (lib/definitions ok) :when (map? (:patch d)) [_ b] (:boxes (:patch d))]
167
+ (comp/klass (str/replace (str (:text b)) #"\$\d" "0")))))))
168
+
169
+ (defn try-receive
170
+ "Sends messages ([[inlet value] …], as EDN) to the component, one after another, threading its
171
+ state as the engine does. args-text: the words after the class in the box text."
172
+ [source cls args-text messages]
173
+ (let [{:keys [ok error]} (definition source cls)]
174
+ (cond
175
+ error {:ok false :error error}
176
+ (not (fn? (:receive ok))) {:ok false :error "it has no :receive"}
177
+ :else
178
+ (let [m ok text (box-text m args-text) args (comp/args-for m text)
179
+ msgs (try (read-edn messages) (catch :default e (throw (js/Error. (str "messages are not EDN: " (.-message e))))))]
180
+ (when-not (sequential? msgs) (throw (js/Error. "messages: a vector of [inlet value], e.g. [[0 440] [0 :bang]]")))
181
+ (loop [state nil [[inlet value] & more] (seq msgs) acc [] t 0]
182
+ (if (nil? inlet)
183
+ {:ok true :box-text text :args (pr-str args) :results acc}
184
+ (let [r (try ((:receive m) {:id :b1 :state state :args args :inlet inlet :value value :at t :data nil})
185
+ (catch :default e {::error (or (.-message e) (str e))}))]
186
+ (if-let [err (::error r)]
187
+ {:ok false :box-text text :results (conj acc {:in (pr-str [inlet value]) :error err})}
188
+ (recur (if (and (map? r) (contains? r :state)) (:state r) state) more
189
+ (conj acc {:in (pr-str [inlet value])
190
+ :result (cut (pr-str (select-keys r [:out :show :effects :later :state])) 600)})
191
+ (+ t 0.1))))))))))
192
+
193
+ (def shape-kinds #{:rect :circle :line :arc :needle :path :text :curve :group})
194
+
195
+ (defn holes [template]
196
+ (let [acc (atom #{})]
197
+ (walk/postwalk (fn [x] (when-let [k (shp/hole x)] (swap! acc conj k)) x) template)
198
+ @acc))
199
+
200
+ (defn try-view
201
+ "Draws the component's view for a shown value (EDN) and the box text, and checks it: shape kinds,
202
+ holes without a value, numbers. With a gesture, also tries one drag and what it would persist."
203
+ [source cls args-text shown]
204
+ (let [{:keys [ok error]} (definition source cls)]
205
+ (cond
206
+ error {:ok false :error error}
207
+ (not (or (:view ok) (:draw ok))) {:ok true :note "no :view nor :draw: the box is shown as text"}
208
+ :else
209
+ (let [m ok text (box-text m args-text) args (comp/args-for m text)
210
+ [w h] (let [s (:size m)] (if (vector? s) s [80 40]))
211
+ shown (read-edn shown)
212
+ ctx {:shown shown :state nil :args args :text text :data nil :w w :h h}
213
+ derived (when (:derive m) ((:derive m) ctx))
214
+ vals (merge (when (map? args) args) {:shown shown :w w :h h} derived)
215
+ missing (when (:view m) (vec (remove #(contains? vals %) (holes (:view m)))))
216
+ shapes (vec (remove nil? (if (:view m) (shp/fill (:view m) vals) ((:draw m) ctx))))
217
+ bad (vec (keep (fn [s] (when-not (and (vector? s) (shape-kinds (first s)) (map? (second s)))
218
+ (cut (pr-str s) 120)))
219
+ shapes))
220
+ nan (vec (keep (fn [s] (when (some (fn [[_ v]] (and (number? v) (not (js/isFinite v)))) (second s))
221
+ (cut (pr-str s) 120)))
222
+ (filter #(map? (second %)) shapes)))
223
+ gesture (when (:gesture m)
224
+ (try (let [v ((:gesture m) (assoc ctx :start shown :x (/ w 2) :y (/ h 2) :dx 10 :dy -10 :fine false))]
225
+ {:value (pr-str v)
226
+ :on-release (pr-str ((:gesture m) (assoc ctx :start shown :x (/ w 2) :y (/ h 2) :dx 10 :dy -10 :fine false :up true)))
227
+ :persist (when (:persist m) (comp/args-text m (:class m) (merge (comp/args-for m text) ((:persist m) v))))})
228
+ (catch :default e {:error (or (.-message e) (str e))})))]
229
+ {:ok (and (empty? missing) (empty? bad) (empty? nan) (not (:error gesture)))
230
+ :size [w h] :shapes (count shapes)
231
+ :holes-without-value missing :not-shapes bad :non-finite-numbers nan
232
+ :drawn (cut (pr-str shapes) 1500)
233
+ :gesture gesture}))))
234
+
235
+ (defn classes
236
+ "The classes the work knows now: \"class [in out] — first sentence of its doc\", and the functions of
237
+ clojure.core that are boxes by themselves."
238
+ []
239
+ (conj (vec (for [[k d] (sort-by key @comp/registry)
240
+ :let [io (:io d) doc (first (str/split (str (:doc d)) #"(?<=\.)\s"))]]
241
+ (str k " " (if (vector? io) (pr-str io) "") " — " (cut doc 110) " (" (name (or (:origin d) :core)) ")")))
242
+ (str "Also, without defining anything, a box named after one of these pure functions is that function: its "
243
+ "other words are its EDN arguments, the message goes last (or where % is) and is always the left inlet, the only "
244
+ "hot one; one more inlet per other argument, in order (vector % 0 0 is a pack, hash-map :freq % :amp 0.5 makes an "
245
+ "event); ^:hot before the class makes every inlet hot; a keyword, set or map written first is a function too, "
246
+ "the message first (:freq · #{60 64} · {60 :c}); nil sends nothing; xf/ before a function is its transducer over "
247
+ "the stream of messages, with memory (xf/partition-all 4 collects, xf/partition 4 1 slides, xf/dedupe, xf/take 1; "
248
+ "flush and clear); functions travel through wires as their EDN form: comp, partial, juxt, complement, fnil, "
249
+ "constantly, every-pred and some-fn are boxes that send one on a bang (comp inc (partial * 2)), and a name or "
250
+ "such a form in any argument is the function, so sending one into the inlet of inc in map inc changes it live "
251
+ "(msg dec does it too). A msg box is read as Clojure: keywords with their colon (msg :stop, msg :rec 4), any "
252
+ "other word a name (msg inc; free text such as e4, 6/5, a URL), \"strings\" and EDN forms ([0 4 7], {:freq 440}); "
253
+ "msg stop is a name and does not stop anything: "
254
+ (str/join " " (cf/names)))))
255
+
256
+ ;; ───────── the prompt ─────────
257
+
258
+ (def rules
259
+ "You write box classes for Kairotic, a visual patcher of music (like Max/Pd) whose patch and code are
260
+ the same work, written in ClojureScript and run with Scittle (SCI, interpreted, no compiler) in the
261
+ browser. You may write:
262
+
263
+ 1. A component: ONE ClojureScript expression that evaluates to the definition map. It may be
264
+ `(let [helpers …] {…})`. No `ns`, no top-level `def`/`defn`, no requires. Available: clojure.core,
265
+ clojure.string as `str/`, the Kairotic API as `api/` (below), and JavaScript interop (`js/Math`,
266
+ the Web Audio objects you are given). Do NOT use other kairotic namespaces (`comp/`, `cv/`, `eng/`…).
267
+ Never touch the DOM, the network or storage.
268
+ 2. An abstraction: a component whose class IS a patch — {:class :doc :usage :patch {:boxes {…} :lines […]}}.
269
+ Boxes: `:b1 {:text \"faust~\" :x 20 :y 140 :data {:source \"…Faust…\"}}`; lines: `[:b1 0 :b4 0]`
270
+ (from-box outlet to-box inlet). Its ports are its `inlet`/`outlet` (messages) and `inlet~`/`outlet~`
271
+ (audio) boxes, numbered left to right by :x. `$1 $2` in box texts take the words of each instance.
272
+ `:present [x y]` on a box puts it on the panel every instance shows (a bpatcher); only boxes with
273
+ their own view act there (knob, adsr~, space~, or components with a :view). Inside, use classes that
274
+ exist (`list_classes`); the official ones adsr~ synth~ pan~ space~ knob keyboard are brought into
275
+ the work automatically. For audio DSP prefer a `faust~` box with Faust code: its audio ports are
276
+ those of `process`, and its left inlet takes parameters as messages `[:cutoff 800]` — exactly what
277
+ a named knob sends (`knob 40 12000 1200 log cutoff`); a list of Hz sets freq and gate = 1.
278
+ 3. A package, when you need several definitions together (a control of your own and the abstraction
279
+ that uses it): {:package \"work/<name>\" :version \"0.1.0\" :components [definition …]}.
280
+
281
+ Write in English (names, :doc, comments). Keep it small and readable, in sections like the examples:
282
+ about (:class :license \"MPL-2.0\" :doc :usage :io), arguments (:args, :persist), logic (:receive,
283
+ :gesture, called once more with :up true on release: return a release message there if the
284
+ component needs press and release), view (:derive, :view as data, :size), audio (:audio), help (:help {:inlets [\"one line per inlet\" …]
285
+ :outlets […] :try \"something to do with it\"}, shown in the Help tab). Prefer :view (a data template with
286
+ $holes) over :draw. A class name is one word; audio classes end in ~. Do not reuse a core class name.
287
+ :receive is pure: it returns data ({:out … :state … :show … :effects … :later …}); side effects on
288
+ sound happen only through :audio :effects. Anything else a box needs from outside (a URL, an API, a file)
289
+ is a task: declare :tasks {:get (fn [x box] promise)} (api/http-get makes the request), ask for it from
290
+ :receive with :effects [[:get x]], and handle its outcome when it arrives on inlet :task as
291
+ {:task :get :arg x :value v} or {:task :get :arg x :error \"…\"} (compare :arg with what :state waits for:
292
+ a late answer to an older request is dropped). To keep the outcome in the work (the history, the same
293
+ for everyone) return :effects [[:keep d]] with a :model {:empty {} :load (fn [d] d)} whose data is d; to
294
+ use it only live, keep it in :state. Never call js/fetch, set timers or keep atoms in :receive or :state.
295
+ See the example data/fetch. The same value arriving again must change nothing that is
296
+ going on (data boxes send what they hold again after ■ or when the patch before them changes): a player
297
+ does not start over, an accumulator does not count it twice — compare with what :state keeps. Messages are numbers, keywords (:bang), strings or vectors.
298
+ Faust: `import(\"stdfaust.lib\");`, the standard libraries (os. fi. en. re. ef. si. ba. no. de.),
299
+ hslider/button for parameters, `process = …;`. In ClojureScript source the Faust code is a string:
300
+ escape its double quotes.
301
+ Musical data (notation, composition, CAC) travels as musical trees (kairotic.mt, alias mt/ in sources):
302
+ hiccup vectors such as [:voice [:measure {:meter [4 4]} [:note {:pitch \"c4\" :dur 1}] \"d4/.5 e4\"]]
303
+ (tags :piece :voice :section :seq :par :measure :tuplet {:ratio [3 2]} :chord :note :rest :param :dyn
304
+ :text; any extra key is allowed). Proportional rhythm: [:rtm {:shares [1 [1 [1 1 1]] -1 2] :pitches \"c4 d4\"}]
305
+ fills its measure (or its :dur) with those shares; note values and tuplets follow from the meter.
306
+ Grouped meters: [:measure {:meter \"5/8[2+3]\"} …] (or :meter [5 8] :groups [2 3]); mt/meter-level and
307
+ mt/indispensability (Barlow) give metric weight, mt/thin keeps the notes on the strongest positions.
308
+ A component that makes or changes music sends a tree from :receive;
309
+ use mt/events, mt/transpose, mt/pitch-name … rather than your own parsing. See the example notation/walk.
310
+
311
+ Work method: the catalog below lists real examples; read the ones close to the request with
312
+ `read_example` before writing. Write, then CHECK before answering: `check_faust` for Faust code,
313
+ `check_component` for the whole source (it also compiles the Faust inside abstractions), then
314
+ `try_messages` with representative messages and `try_view` if it has a view. Fix what fails and check
315
+ again. Keep tool calls few.
316
+
317
+ Your final answer: one or two sentences saying what it does and how to use it (inlets, outlets,
318
+ arguments), then the complete source in ONE ```clojure fenced block. Nothing after it.")
319
+
320
+ (defn catalog-text
321
+ "The catalog as Claude sees it: one line per example."
322
+ [examples]
323
+ (str/join "\n" (for [e examples] (str "- " (:name e) " (" (:category e) ", " (:kind e) "): " (:about e)))))
324
+
325
+ (defn prompt
326
+ "The whole input for Claude. `change` is the source of an existing component to modify (or nil);
327
+ `always` are examples given whole; `examples` the catalog (read with read_example)."
328
+ [{:keys [request change contract api always examples]}]
329
+ (str rules
330
+ "\n\n━━━ The component contract (from kairotic/components.cljs) ━━━\n" contract
331
+ "\n\n━━━ The Kairotic API (kairotic/api.cljs), usable as api/… ━━━\n" api
332
+ "\n\n━━━ Two examples, whole ━━━\n"
333
+ (str/join "\n\n" (map (fn [e] (str ";; ── example: " (:name e) " — " (:about e) " ──\n" (:source e))) always))
334
+ "\n\n━━━ The catalog of examples (read any with read_example) ━━━\n" (catalog-text examples)
335
+ (when change (str "\n\n━━━ The component to change (keep what is not asked to change) ━━━\n" change))
336
+ "\n\n━━━ The request ━━━\n" request "\n"))
337
+
338
+ (defn header-of
339
+ "The leading comment block of a source file, without the ;; marks (what documents it)."
340
+ [text]
341
+ (->> (str/split-lines (str text))
342
+ (take-while #(str/starts-with? (str/triml %) ";;"))
343
+ (map #(str/replace % #"^\s*;; ?" ""))
344
+ (str/join "\n")))
345
+
346
+ (defn source-of
347
+ "The last ```clojure (or plain ```) fenced block of an answer."
348
+ [text]
349
+ (let [blocks (re-seq #"```(?:clojure|clj|cljs|edn)?\s*\n([\s\S]*?)```" (str text))]
350
+ (some-> (last blocks) second str/trim)))
351
+
352
+ ;; ───────── patches (Study 23) ─────────
353
+ ;; Claude can also make a whole patch from a description, or change the one that is open. It answers
354
+ ;; with the patch's code — only the calls a patch is made of, as a link carries it — which the page
355
+ ;; checks (classes, ports, Faust compiled, components evaluated) and loads as one event of the history.
356
+
357
+ (def patch-rules
358
+ "You make patches for Kairotic, a visual patcher of music (like Max/Pd) whose patch and code are the
359
+ same work. A patch is written as a list of calls, one per line, with LITERAL arguments only (numbers,
360
+ strings, keywords, vectors, maps) — no let, def, fn, str, arithmetic or any other form:
361
+
362
+ (box :b1 \"osc~ 440\" 40 60) ; a box: id, text (class and arguments), x, y
363
+ (connect :b1 0 :b2 0) ; from :b1 outlet 0 to :b2 inlet 0 (numbered from 0, left to right)
364
+ (code :b3 \"…source…\") ; the source of a code box (faust~, script, component, tree)
365
+ (present :b4 20 20) ; puts a box on the presentation (the performer's panel), at x y
366
+ (view :b5 :roll) ; shows a tree box as a roll (it is a :score at first; a freqt :canvas or :score), same data
367
+ (tree! :b5 [:voice \"c4/1 e4 g4/2\"]) ; the musical tree of a tree box
368
+ (stroke :b6 [[0 220] [1 440]]) (axis :b6 :x 0 4) ; drawings of canvas/freqt boxes
369
+
370
+ Rules:
371
+ - Use only classes that exist (`list_classes`; `class_help` gives the inlets and outlets of one).
372
+ Official classes such as knob, keyboard, synth~, adsr~, pan~, space~ come into the work by
373
+ themselves when a box uses them.
374
+ - Messages flow without ▶; ▶ starts sound and time (metro, ramp, loadbang). Audio classes end in ~.
375
+ Send sound to `dac~ 1 2` (both channels: connect to inlets 0 and 1) through a `gain~` of 0.1–0.3:
376
+ never louder.
377
+ - For sound that core classes do not make (FM, filters, effects, physical models…), use a `faust~` box
378
+ with Faust code: `(box :b3 \"faust~\" x y)` and `(code :b3 \"import(\\\"stdfaust.lib\\\"); …process = …;\")`.
379
+ Its audio ports are those of process; its LEFT inlet takes parameters as messages [:name value],
380
+ which is exactly what a named knob sends: `knob 50 2000 300 log carrier` sends [:carrier v] to an
381
+ hslider(\"carrier\", …). Write every parameter as hslider with sensible ranges and a smoothing
382
+ (si.smoo). Call `check_faust` on the Faust code before using it.
383
+ For a POLYPHONIC instrument (chords, a keyboard, a tree played in several voices) write one voice
384
+ with `declare options \"[nvoices:8]\";` and controls named exactly freq, gain and gate (Faust's own
385
+ allocator sets them note by note; gate drives an envelope such as en.adsr), and optionally
386
+ `effect = …;` for one effect on the sum of the voices. Such a faust~ gets Hz on its LEFT inlet and
387
+ voice ids on its RIGHT one (inlet 1), as synth~: keyboard 0→0, 1→1, 3→0 (velocity); mt play 0→0,
388
+ 1→1; reader 0→0, 1→1. Its other parameters [:name v] apply to every voice.
389
+ - Musical trees (tree boxes, notation): to PLAY one, prefer `tree` → `mt play` → `synth~` (mt play
390
+ sends Hz and voice ids at the tree's tempo once ▶ is on; see class_help). To SHOW one as notation,
391
+ send it to a tree box (it is shown as a score): tree → mt → tree. (A `freqt` with `(view :bN :score)` can
392
+ preview one too, but trees go to tree boxes; a freqt is for strokes with no musical form yet.) A freqt's own strokes shown as a score are
393
+ quantized into measures in the meter of its bar grid (`(grid-x :bN 0.5 [1.5 1.5])` → 6/8); `(quantize
394
+ :bN {:meter \"3/4\"})` gives that measured tree. As a box: `quantize` (the freqt's outlet 1 on its right
395
+ inlet, or a free tree on the left) keeps options sent as messages ([:meter \"3/4\"], [:divs [1 2 3 4]],
396
+ [:legato 0.25], [:time :track]…) and only on a bang sends the measured tree, for a tree box — e.g.
397
+ adc~ → pitch~ → transcribe → freqt → quantize → tree. Pitches are written with their names (\"bb4\", \"f#3\"),
398
+ kept as written; `{:key \"eb\"}` on a tree, voice or measure gives the score its key; numbers are named
399
+ by the key (mt/spell); `mt transpose M3` moves by an interval keeping the spelling.
400
+ A tree box is also a piano roll ((view :bN :roll)): strokes drawn there, or (stroke :bN pts), become notes
401
+ of the tree; (quantize! :bN) writes its free time in measures; its outlet 1 is a buffer for reader~. A freqt that shows a tree is also a
402
+ buffer: `phasor~` → `reader~ norm` (left) with the freqt's outlet 1 on its right inlet gives the pitch as
403
+ a signal (Hz), e.g. into a faust~ whose process takes a frequency input.
404
+ A tree box sends its tree by itself: it needs no loadbang.
405
+ - Sound from outside: `adc~ 1` is the microphone (asked for at ▶). `snapshot~ 50` turns any signal into
406
+ numbers (`snapshot~ 50 db` its level), `scope~` draws it. Never connect an adc~ to dac~ without a
407
+ `gain~` and a warning about headphones: it feeds back. `sample [seconds]` records what reaches its
408
+ left inlet on `rec` until `stop`; its outlet 1 into the right inlet of `reader~ norm`, with a `phasor~` at
409
+ 1/length Hz on the left, plays it (every reader and reader~ reads positions in its buffer's units — X of a
410
+ canvas, time of a freqt, seconds — unless it says norm: 0…1) (its outlet 0 gives the length in seconds; `!/ 1` turns it into Hz).
411
+ A sample can be a sound from a URL that every browser fetches: `(sample! :bN {:url \"https://…\"})`.
412
+ Prefer `github:owner/repo@ref/path.wav` (e.g. `github:tidalcycles/Dirt-Samples@master/bd/BT0A0A7.wav`,
413
+ served by jsDelivr) or `freesound:id`: most other sites refuse it (CORS).
414
+ - Listening (package @kairotic/analysis, it comes by itself): `pitch~ [lo hi]` gives Hz (0 when it stops
415
+ hearing a pitch) and clarity; `onset~` a bang per attack; `chroma~` 12 pitch-class values and the
416
+ strongest class (:a …); `features~ [ms] rms centroid …` one outlet per descriptor; `spectrum~` draws.
417
+ To see any stream over time: `monitor [seconds] [name …]`, one inlet (and lane) per name — numbers as
418
+ lines, lists as strips, bangs and words as marks.
419
+ - Music theory as geometry (package @kairotic/theory, it comes by itself): `pcclock` (a pitch-class set on
420
+ the clock, its prime form on the left, interval vector in the middle), `fourier` (six Fourier magnitudes
421
+ on the left), `tonnetz` (triads and the path of the harmony; the triad as :C, :am… on the left); they take
422
+ lists of pitches in Hz (as a keyboard or midiin sends them; MIDI or 0…11 with the word midi: `pcclock midi`),
423
+ notes one by one, or a chroma from `chroma~`; pressing a pitch class sends it (right).
424
+ Counterpoint in the same package: `comes [system] [mode]` (you play the dux, in Hz or with midi; it answers
425
+ with the comes as a canon: the Hz of both voices on 0 after their voice ids on 1, for one synth~ 0→0 1→1; the
426
+ futuribles on 2, where the canon is on 3; :engine plays alone; `live` on a pulse) and `cancrizans` (a crab or
427
+ `table` canon written from both ends; when it closes, patterns on 0 and 1 and the score as a tree on 4, for a
428
+ tree box). The words name a system (diatonic, meantone, septimal31, pentatonic) and one of its modes (dorian…,
429
+ penta-A…), in any order. Orders are keywords: msg :engine, not msg engine.
430
+ Rhythm in the same package: `euclid k n [rotation] [bars]` (a Euclidean rhythm drawn as a necklace: a musical
431
+ tree on 0, for a tree box, with an :rtm whose shares are the intervals between onsets; the :rtm map alone on
432
+ 1; the pulses as 0/1 on 2). Its right inlet (cold) gives the pitches the notes take in turn (a keyboard's
433
+ keys in Hz, a melody string, {:pitches …}, a pattern {:note […]}); [:k 5] [:n 16] [:rotation 2] [:bars 4]
434
+ [:meter \"3/4\"] change it, a bang sends it.
435
+ - The outside (package @kairotic/io, it comes by itself; listening while ▶ runs): `midiin` (MIDI in: Hz and
436
+ voice ids for synth~ like a keyboard, and every event as a map {:type :note :freq :amp :gate …}),
437
+ `midiout [mpe]` (Hz after voice ids, or events, to a MIDI port; mpe for microtones), `oscout [target]` and
438
+ `oscin [pattern]` (OSC through `npx @kairotic/relay --osc`: events as /kairotic/note id freq amp gate…),
439
+ `motion` (a phone's tilt [x y] and shakes), `gamepad` ([name value] and events), `serial [baud]` (a board's
440
+ lines as numbers; msg :open asks for the port); `control cc 74` · `control pad lx` · `control tilt x` · `control osc
441
+ /addr` picks one controller out of their events (event outlet), into `scale in-lo in-hi out-lo out-hi [log] [ms]`
442
+ (@kairotic/controls) to bring it to a parameter's range — what (learn :bN) makes by itself.
443
+ - The room (package @kairotic/net, it comes by itself): `share [channel]` sends any value to everyone in the
444
+ shared room (and this page), `shared [channel]` gives what anyone shares (value left, who right, while ▶);
445
+ `pulse [division]` counts the room's beat on the audio clock — one tempo for every page; `start [bpm]`,
446
+ `stop`, `bpm n` change it for everyone.
447
+ - Data (package @kairotic/data, it comes by itself): `fetch [json|text|edn] [live]` brings in what is at a
448
+ URL (a msg with the URL, or `github:owner/repo@ref/path`) and keeps it in the work (live: only here); on
449
+ the left what it found, [:get k …] a part of it; `edn [w h]` shows any value as a tree to open and pick
450
+ from (the part on the left, its path on the right). Most sites outside GitHub refuse a page (CORS).
451
+ - Patterns (package @kairotic/patterns, it comes by itself), after SuperCollider's and Overtone's: `pbind
452
+ [seed] [repeat] [loop]` is a code box whose source is an EDN map of constants, vectors (sequences) and
453
+ generators — #pat/choose [..], #pat/shuffle [..], #pat/white [lo hi], #pat/walk [x step lo hi],
454
+ #pat/series [x step n], #pat/hold [beats [..]], #pat/chord [0 4 7] — set with `(code :bN \"{:degree [0 2
455
+ 4] :dur 0.5}\")`; `pattern [seed]` is the same as Clojure code (pbind, pwhite, pchoose… and seeded rand),
456
+ which needs (trust-scripts true) in a room; both send a pattern to the right inlet of `player [bpm]
457
+ [quant]`, which plays it on `start`/`stop`, one step per bang, or at a position in beats (a number, from a
458
+ ramp, either way: going back, each note starts from its end; seek p jumps). Its outlets: Hz (left) and voice ids (second) for synth~ or a polyphonic faust~, the whole event,
459
+ the beat. Event keys: :freq, :note (MIDI, \"c4\"), or :degree with :scale :root :octave; :dur in beats,
460
+ :legato; :rest (or nil) is a silence; :amp 0…1 is the loudness of its notes in synth~ and a polyphonic faust~. `render [from] [to]` draws a stretch of a pattern into a freqt (pattern left, freqt after it); a canvas
461
+ on its right inlet is a time map (x: beats of the drawing, y: beats of the pattern; down = backwards, flat =
462
+ hold, several strokes = layers). Write durations as decimals (0.25), not ratios.
463
+ - Pitch shifting (package @kairotic/spectral, it comes by itself): `shift~ [factor …]` transposes the signal
464
+ on its inlet by every factor at once (one interval or a chord), one frame (~21 ms) late. A factor is a
465
+ ratio (1.5, 3/2), semitones with a sign (+7, -12, +0) or cents (386c); a msg with a list of them changes
466
+ the chord; [:semitones 0 4 7], [:cents …], [:transpose st] (all of them at once, for glides), [:formants q t]
467
+ (q ms keeps the formants, 1 for a voice; t shifts them), [:rms 1], [:dry x]. Typical: adc~ → shift~ 1 5/4 3/2 → dac~.
468
+ - `draw [w h]` draws the shapes that reach it (the shapes of a component's view, or as a msg writes them:
469
+ `msg :circle 40 40 10 :accent :hit :sun`, `msg :set :cursor :line 0 0 0 100`); a shape with :hit k sends k.
470
+ - Annotations: `(mark :notes {:kind :text :at [:b3 0 -12] :txt \"…\"})`, `(mark :notes {:kind :arrow :pts
471
+ [[:b1 120 10] [:b4 -6 10]]})` — points anchored to a box ([:bN dx dy] from its top-left corner) or to the
472
+ paper ([:patch x y]); `(layer :notes {:z :over :show #{:patch :present}})`; `(project :bN :viz [x y w h])`
473
+ draws a box's view large on a layer. Explain a patch with a few marks when it helps.
474
+ To record any stream of numbers (a knob, `snapshot~ 50 rms`, a descriptor) as strokes: `record [lo hi]`
475
+ → a `canvas` inlet, with `rec`/`stop`; a `reader~ norm` reads it back as an automation.
476
+ A canon or a delay of messages: `ring [seconds]` (values on its left) → its RIGHT outlet → the right inlet
477
+ of `reader d 1` (1 s behind; `reader d 2 speed 0.5`: later and slower); a number on a reader's left moves it
478
+ instead. `writer` (left: what to write; middle: the ring's right outlet; right: a position) → the ring's left.
479
+ With sound: `ring~ [seconds]` (sound on its left) → its RIGHT outlet → the right inlet of `reader~ d 1` (a
480
+ delay; `speed 0.5` an octave down) or the middle inlet of `writer~` (sound left, position signal right).
481
+ To write what is played into notation: `pitch~` → `transcribe [bpm] [notes|glide]` (left; `onset~` on its
482
+ right) → a `freqt`'s inlet; `rec`/`stop` messages on transcribe's left.
483
+ - `gain~ 0.2` sets its factor as an argument; a message into its right inlet changes it, a signal
484
+ there replaces it. Do not leave a gain waiting for a message nobody sends.
485
+ - Lay it out top to bottom, following the signal: x from 20 to 900, about 60 px between rows,
486
+ controls on top. Code boxes are about 330 wide and 200 tall: leave them room.
487
+ - Present the controls and displays a performer needs (`present`), in a compact panel.
488
+ - When a patch is given to change, keep its boxes, ids and positions unless the request changes them;
489
+ new boxes take new ids (the next numbers).
490
+
491
+ Work method: `list_classes` first if unsure; `check_faust` for each Faust source; then `check_patch`
492
+ with the WHOLE code, fix what it reports and check again. Keep tool calls few.
493
+
494
+ Your final answer: one or two sentences saying what the patch does and how to play it, then the
495
+ WHOLE patch code in ONE ```clojure fenced block (only the calls above). Nothing after it.")
496
+
497
+ (defn patch-prompt
498
+ "The whole input for Claude when it makes or changes a patch."
499
+ [{:keys [request current classes]}]
500
+ (str patch-rules
501
+ "\n\n━━━ The classes this work knows now (more official ones come when used) ━━━\n"
502
+ (str/join "\n" classes)
503
+ (when (seq (str/trim (str current)))
504
+ (str "\n\n━━━ The patch to change (keep what is not asked to change) ━━━\n" current))
505
+ "\n\n━━━ The request ━━━\n" request "\n"))