Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX DJ9// File : App/Sources/Features/ClaudeStudio/ClaudeStub.swift10// Description : Debug-only local transport for Claude Studio11// (`-ORIXClaudeStub YES`): a URLProtocol that answers the12// Models and Messages endpoints with canned data in the real13// wire format, so the request, streaming and validation path14// can be exercised without an API key or a network15// connection. Not compiled in Release.16// Module : Features17// Repository : https://git.spboucher.ai/orix-dj18// Created : 2026-11-2119// Last Modified : 2026-11-2120//21// =============================================================================22// AUTHOR & PROFESSIONAL AFFILIATION23// =============================================================================24//25// Author : Simon-Pierre Boucher26// Position : Professor of Finance27// Institution : Université du Québec en Outaouais (UQO)28// Department : Département des sciences administratives29// Organization : SP Boucher30//31// Website : https://spboucher.ai32// Git : https://git.spboucher.ai33//34// =============================================================================35// OFFICIAL CONTACT DIRECTORY36// =============================================================================37//38// General : info@spboucher.ai39// Professional : contact@spboucher.ai40// Direct : simon@spboucher.ai41// Research : research@spboucher.ai42// Development : dev@spboucher.ai43// Support : support@spboucher.ai44// Security/Admin : admin@spboucher.ai45// Notifications : notifications@spboucher.ai46//47// Preferred Contact: support@spboucher.ai48//49// =============================================================================50// COPYRIGHT & INTELLECTUAL PROPERTY51// =============================================================================52//53// Copyright (c) 202654// Simon-Pierre Boucher55//56// All rights reserved where applicable.57//58// This file is governed by the applicable project license,59// copyright notices, institutional agreements and relevant law.60//61// Unless expressly authorized by the applicable license or62// rights holder, copying, redistribution, sublicensing,63// publication and commercial exploitation are not permitted.64//65// Existing third-party rights and notices remain unaffected.66//67// =============================================================================68// CONFIDENTIALITY & SECURITY69// =============================================================================70//71// Classification : Public72// Distribution : Public repository; use is governed by the project license73// Security Contact : admin@spboucher.ai74//75// Access to this source does not independently grant permission76// to redistribute or disclose confidential materials.77//78// Do not embed credentials, private keys, access tokens,79// certificates or confidential personal information.80//81// =============================================================================82// LICENSE & MAINTENANCE83// =============================================================================84//85// License : None specified (no license file in this repository)86// Maintainer : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293#if DEBUG94import Foundation95import ORIXDJCore9697enum ClaudeStub {98 /// Sent in the header to the stub only. It is not a credential.99 static let placeholderKey = "stub-transport-no-key"100101 static func client() -> AnthropicClient {102 let c = URLSessionConfiguration.ephemeral103 c.protocolClasses = [StubURLProtocol.self]104 return AnthropicClient(session: URLSession(configuration: c))105 }106107 static let models = """108 {"data":[{"id":"claude-fable-5-2","display_name":"Claude Fable 5.2","max_input_tokens":1000000,"max_tokens":64000},{"id":"claude-opus-5-5","display_name":"Claude Opus 5.5","max_input_tokens":1000000,"max_tokens":64000},{"id":"claude-sonnet-5-5","display_name":"Claude Sonnet 5.5","max_input_tokens":1000000,"max_tokens":64000}],"has_more":false}109 """110111 static let scriptAnswer = """112 Here is an eight-bar transition from deck A to deck B with a filter sweep and an echo tail.113114 ```orixdj115 automation "Filter Sweep Handover" quantize bar {116 deck.B.sync(true)117 deck.B.volume = -60dB118 deck.B.eq.low = -26dB119 deck.B.play()120 over 4 bars {121 deck.B.volume -> 0dB122 deck.A.filter.highpass -> 400Hz123 }124 // Swap the bass on the bar line.125 deck.A.eq.low = -26dB126 deck.B.eq.low = 0dB127 over 4 bars {128 deck.A.filter.highpass -> 8kHz129 deck.A.volume -> -60dB130 }131 deck.A.pause()132 deck.A.filter.highpass = 20Hz133 deck.A.eq.low = 0dB134 deck.A.volume = 0dB135 }136 ```137138 **Bars 1 to 4.** Deck B starts in sync, silent and without bass, and fades up while a high-pass opens on deck A.139140 **Bar 5.** The bass lines swap on the bar line: deck A loses its low band, deck B gets its own back.141142 **Bars 5 to 8.** Deck A's high-pass climbs to 8 kHz while its fader closes; then deck A is paused and its filter, EQ and fader are reset.143144 Before running it live: deck A must be playing and deck B must be loaded and cued on a downbeat.145 """146147 static let midiAnswer = """148 I do not know this controller's MIDI numbers, so this is a generic two-deck layout to correct with MIDI learn.149150 ```json151 {"name": "Generic Two Deck", "controllerNameHint": "", "mappings": [152 {"control": {"kind": "note", "channel": 0, "number": 11}, "target": "deck.A.play", "mode": "trigger"},153 {"control": {"kind": "note", "channel": 1, "number": 11}, "target": "deck.B.play", "mode": "trigger"},154 {"control": {"kind": "cc", "channel": 0, "number": 19}, "target": "deck.A.volume", "mode": "absolute"},155 {"control": {"kind": "cc", "channel": 1, "number": 19}, "target": "deck.B.volume", "mode": "absolute"},156 {"control": {"kind": "cc", "channel": 6, "number": 31}, "target": "mixer.crossfader", "mode": "absolute"},157 {"control": {"kind": "cc", "channel": 6, "number": 40}, "target": "deck.A.sparkle", "mode": "absolute"}158 ]}159 ```160161 Faders and the crossfader are absolute; the play buttons are triggers.162 """163164 static let explainAnswer = """165 The script fades deck A out over four bars, pauses it, and puts its fader back to 0 dB.166167 - **Bars 1 to 4:** `deck.A.volume` ramps down to -60 dB, which is silence.168 - **After bar 4:** deck A is paused and its fader is restored, so the deck is ready for the next track.169170 The risk in a live set: if deck A is the only deck playing, the room goes silent at the end of bar 4.171 """172173 /// The answer for a request body: a changed copy of the shared script for Fix/Improve, a mapping for MIDI,174 /// prose for Explain, a new script otherwise.175 static func answer(forRequestBody body: Data) -> String {176 guard let object = try? JSONSerialization.jsonObject(with: body) as? [String: Any], let messages = object["messages"] as? [[String: Any]],177 let last = messages.last?["content"] as? String else { return scriptAnswer }178 if last.hasPrefix("Create a MIDI mapping") { return midiAnswer }179 if last.hasPrefix("Explain what the current script does") { return explainAnswer }180 if last.hasPrefix("The current script does not work") || last.hasPrefix("Improve the current script"),181 let open = last.range(of: "Current script:\n```orixdj\n"), let close = last.range(of: "\n```", range: open.upperBound ..< last.endIndex) {182 var script = String(last[open.upperBound ..< close.lowerBound])183 script = script.replacingOccurrences(of: "over 4 bars", with: "over 8 bars")184 if let pause = script.range(of: "deck.A.pause()") { script.replaceSubrange(pause, with: "deck.A.pause()\n deck.A.filter.highpass = 20Hz") }185 return "The fade was short for a breakdown, so it now takes eight bars, and the high-pass is reset after the deck stops.\n\n```orixdj\n\(script)\n```\n\nNothing else changed."186 }187 return scriptAnswer188 }189190 /// The Messages API server-sent-event stream for an answer, split into small text deltas.191 static func sseEvents(for text: String, model: String) -> [Data] {192 var events: [String] = []193 events.append("event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_stub\",\"model\":\"\(model)\",\"usage\":{\"input_tokens\":212,\"cache_read_input_tokens\":4096,\"cache_creation_input_tokens\":0}}}\n\n")194 events.append("event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n")195 var chunks: [String] = []196 var current = ""197 for c in text { current.append(c); if current.count >= 14, c == " " || c == "\n" { chunks.append(current); current = "" } }198 if !current.isEmpty { chunks.append(current) }199 for chunk in chunks {200 let payload: [String: Any] = ["type": "content_block_delta", "index": 0, "delta": ["type": "text_delta", "text": chunk]]201 guard let data = try? JSONSerialization.data(withJSONObject: payload) else { continue }202 events.append("event: content_block_delta\ndata: \(String(decoding: data, as: UTF8.self))\n\n")203 }204 events.append("event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n")205 events.append("event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":\(max(1, text.count / 4))}}\n\n")206 events.append("event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n")207 return events.map { Data($0.utf8) }208 }209}210211final class StubURLProtocol: URLProtocol, @unchecked Sendable {212 private let lock = NSLock()213 private var stopped = false214215 override class func canInit(with request: URLRequest) -> Bool { true }216 override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }217218 private func respond(status: Int, contentType: String) {219 guard let url = request.url, let response = HTTPURLResponse(url: url, statusCode: status, httpVersion: "HTTP/1.1", headerFields: ["content-type": contentType, "request-id": "req_stub"]) else { return }220 client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)221 }222223 override func startLoading() {224 var body = request.httpBody ?? Data()225 if let stream = request.httpBodyStream {226 stream.open(); var buffer = [UInt8](repeating: 0, count: 65536)227 while stream.hasBytesAvailable { let n = stream.read(&buffer, maxLength: buffer.count); if n <= 0 { break }; body.append(buffer, count: n) }228 stream.close()229 }230 let path = request.url?.path ?? ""231 if path.hasSuffix("/v1/models") {232 respond(status: 200, contentType: "application/json")233 client?.urlProtocol(self, didLoad: Data(ClaudeStub.models.utf8))234 client?.urlProtocolDidFinishLoading(self)235 return236 }237 let model = ((try? JSONSerialization.jsonObject(with: body)) as? [String: Any])?["model"] as? String ?? AnthropicSettings.defaultModel238 let events = ClaudeStub.sseEvents(for: ClaudeStub.answer(forRequestBody: body), model: model)239 respond(status: 200, contentType: "text/event-stream")240 // Deliver the events over time, as a network stream would.241 DispatchQueue.global(qos: .userInitiated).async { [self] in242 for event in events {243 if lock.withLock({ stopped }) { return }244 client?.urlProtocol(self, didLoad: event)245 usleep(18000)246 }247 if lock.withLock({ stopped }) { return }248 client?.urlProtocolDidFinishLoading(self)249 }250 }251252 override func stopLoading() { lock.withLock { stopped = true } }253}254#endif255