@h1r-ai/croche-react-native 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +32 -0
  2. package/README.md +475 -2
  3. package/THIRD-PARTY-NOTICES +5824 -0
  4. package/android/build.gradle +47 -0
  5. package/android/src/main/AndroidManifest.xml +8 -0
  6. package/android/src/main/java/dev/croche/reactnative/AgentMemory.kt +25 -0
  7. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimeModule.kt +836 -0
  8. package/android/src/main/java/dev/croche/reactnative/CrocheRuntimePackage.kt +22 -0
  9. package/android/src/main/java/dev/croche/reactnative/ProjectAttestation.kt +17 -0
  10. package/android/src/test/java/dev/croche/reactnative/AgentMemoryTest.kt +49 -0
  11. package/android/src/test/java/dev/croche/reactnative/ProjectAttestationTest.kt +42 -0
  12. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/AndroidPlatform.kt +133 -0
  13. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/BitmapImageCodec.kt +47 -0
  14. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/CrocheProjectRecordProvider.kt +25 -0
  15. package/android/vendor/CrocheRuntimeSDK/android/dev/croche/android/WorkManagerScheduler.kt +146 -0
  16. package/android/vendor/CrocheRuntimeSDK/consumer-rules.pro +9 -0
  17. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/AppStreamBranch.kt +110 -0
  18. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Control.kt +178 -0
  19. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Core.kt +12 -0
  20. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/CrocheRuntime.kt +405 -0
  21. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Effects.kt +195 -0
  22. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Host.kt +368 -0
  23. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Images.kt +161 -0
  24. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/NativeCoreStreamPort.kt +173 -0
  25. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Platform.kt +105 -0
  26. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ProjectRecords.kt +87 -0
  27. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SendEncoding.kt +27 -0
  28. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/Storage.kt +181 -0
  29. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/StreamHub.kt +211 -0
  30. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/SubscriptionTypes.kt +74 -0
  31. package/android/vendor/CrocheRuntimeSDK/core/dev/croche/ffi/croche_ffi.kt +8316 -0
  32. package/android/vendor/jniLibs/arm64-v8a/libcroche_ffi.so +0 -0
  33. package/android/vendor/jniLibs/armeabi-v7a/libcroche_ffi.so +0 -0
  34. package/android/vendor/jniLibs/x86_64/libcroche_ffi.so +0 -0
  35. package/croche-react-native.podspec +28 -0
  36. package/ios/CrocheRuntimeBridge.swift +986 -0
  37. package/ios/RNCrocheRuntime.mm +221 -0
  38. package/ios/vendor/CrocheRuntimeSDK/Background.swift +59 -0
  39. package/ios/vendor/CrocheRuntimeSDK/Control.swift +192 -0
  40. package/ios/vendor/CrocheRuntimeSDK/Effects.swift +194 -0
  41. package/ios/vendor/CrocheRuntimeSDK/FFIStreamPort.swift +212 -0
  42. package/ios/vendor/CrocheRuntimeSDK/Host.swift +561 -0
  43. package/ios/vendor/CrocheRuntimeSDK/Images.swift +178 -0
  44. package/ios/vendor/CrocheRuntimeSDK/JSON.swift +63 -0
  45. package/ios/vendor/CrocheRuntimeSDK/Platform.swift +275 -0
  46. package/ios/vendor/CrocheRuntimeSDK/Runtime.swift +511 -0
  47. package/ios/vendor/CrocheRuntimeSDK/Storage.swift +345 -0
  48. package/ios/vendor/CrocheRuntimeSDK/StreamHub.swift +359 -0
  49. package/ios/vendor/CrocheRuntimeSDK/SubscriptionRuntime.swift +38 -0
  50. package/ios/vendor/CrocheRuntimeSDK/SubscriptionTypes.swift +323 -0
  51. package/ios/vendor/CrocheRuntimeSDK/croche_ffi.swift +5666 -0
  52. package/ios/vendor/croche_ffiFFI.xcframework/Info.plist +48 -0
  53. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/croche_ffiFFI.h +2006 -0
  54. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/Headers/module.modulemap +4 -0
  55. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64/libcroche_ffi.a +0 -0
  56. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/croche_ffiFFI.h +2006 -0
  57. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/Headers/module.modulemap +4 -0
  58. package/ios/vendor/croche_ffiFFI.xcframework/ios-arm64_x86_64-simulator/libcroche_ffi.a +0 -0
  59. package/package.json +40 -4
  60. package/scripts/vendor-native.sh +56 -0
  61. package/src/NativeCrocheRuntime.ts +162 -0
  62. package/src/index.ts +660 -0
  63. package/src/project-types.ts +35 -0
  64. package/src/project.ts +426 -0
  65. package/src/protocol.ts +28 -0
  66. package/src/types.ts +9 -0
@@ -0,0 +1,181 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.*
4
+ import java.io.File
5
+ import java.io.FileOutputStream
6
+ import java.io.RandomAccessFile
7
+ import java.nio.channels.FileLock
8
+ import java.nio.file.Files
9
+ import java.nio.file.StandardCopyOption.*
10
+
11
+ /** Storage owns its namespace exclusively until release; save must be atomic and never
12
+ * interrupted by Runtime cancellation. Snapshots contain private Runtime credentials. */
13
+ interface RuntimeStorage {
14
+ fun acquire()
15
+ fun load(): JsonElement
16
+ fun save(state: JsonElement)
17
+ /** Delete the snapshot for real; an absent snapshot is already removed. */
18
+ fun remove()
19
+ fun release()
20
+ }
21
+
22
+ /** A RuntimeStorage that also keeps named entries beside the snapshot, such as `held`: the sends
23
+ * waiting behind a running turn (F19). Each entry is replaced atomically and independently of the
24
+ * snapshot, under the same ownership. `load(entry)` returns JsonNull for an entry never saved.
25
+ * A storage without entries still works; the Runtime then cannot keep sends that arrive while a
26
+ * turn runs, and refuses them (`storage_error`) rather than overwrite the snapshot. */
27
+ interface KeyedRuntimeStorage : RuntimeStorage {
28
+ fun load(entry: String): JsonElement
29
+ fun save(entry: String, value: JsonElement)
30
+ /** Delete this entry for real; an absent entry is already removed. */
31
+ fun remove(entry: String)
32
+ }
33
+
34
+ /** A RuntimeStorage that also keeps the turn archive (F20.6): every finished turn in full, as JSON
35
+ * lines in entries named `archive<NNNN>` (100 turns each) beside the snapshot. Opt-in and separate
36
+ * from [KeyedRuntimeStorage]: a storage without it keeps no archive, typed (`archive_unavailable`),
37
+ * and everything else works. The Runtime keeps the rules (segments, the byte bound, the last record
38
+ * per turn); the storage keeps lines:
39
+ * - `appendLine` writes a newline first when the entry does not end with one, and is durable when
40
+ * it returns;
41
+ * - `readLines` returns complete lines only: a torn last line (a crash mid-append) is not one;
42
+ * - `replaceLines` is atomic: after a crash the entry holds every old line or every new one, never
43
+ * a mix and never none; an empty list deletes the entry;
44
+ * - `remove` deletes for real; an absent entry is not an error;
45
+ * - `entries` lists the entries whose names start with `prefix`, with their sizes in bytes. */
46
+ interface ArchiveRuntimeStorage : RuntimeStorage {
47
+ fun appendLine(entry: String, line: String)
48
+ fun readLines(entry: String): List<String>
49
+ fun replaceLines(entry: String, lines: List<String>)
50
+ fun remove(entry: String)
51
+ fun entries(prefix: String): Map<String, Long>
52
+ }
53
+
54
+ private val ENTRY = Regex("[a-z0-9]+")
55
+ /** Line entries: the archive's segments, and the message log's (S1). */
56
+ private val SEGMENT = Regex("archive[0-9]{4}|log[0-9]{6}")
57
+ internal fun isLineStorageEntry(entry: String) = SEGMENT.matches(entry)
58
+ private val STALE = Regex("(archive[0-9]{4}|log[0-9]{6})\\.tmp-[0-9a-f-]+")
59
+
60
+ /** Application-private file storage. Java NIO file operations require Android API 26+. Entries are
61
+ * sidecar files beside the snapshot (`<file>.held`), each replaced atomically. The turn archive is
62
+ * sidecars too (`<file>.archive0001`, JSON lines), under the same lock; a segment is rewritten to
63
+ * `<file>.archive0001.tmp-<nonce>` and moved over it, and stale temporaries are deleted when the
64
+ * storage is acquired. */
65
+ class FileRuntimeStorage(private val file: File) : KeyedRuntimeStorage, ArchiveRuntimeStorage {
66
+ private var handle: RandomAccessFile? = null
67
+ private var lock: FileLock? = null
68
+ /** Runs after a segment's temporary is complete and before the move (tests inject a crash). */
69
+ internal var beforeCommit: ((File) -> Unit)? = null
70
+ @Synchronized override fun acquire() {
71
+ if (handle != null) throw CrocheException("store_busy", "Storage is already owned")
72
+ file.absoluteFile.parentFile.mkdirs()
73
+ val opened = RandomAccessFile(File(file.path + ".lock"), "rw")
74
+ try {
75
+ val acquired = opened.channel.tryLock() ?: throw CrocheException("store_busy", "Storage is already owned")
76
+ handle = opened; lock = acquired
77
+ } catch (error: Exception) {
78
+ opened.close(); throw CrocheException("store_busy", "Could not acquire storage ownership")
79
+ }
80
+ removeStaleTemporaries()
81
+ }
82
+ @Synchronized override fun load(): JsonElement {
83
+ check(handle != null) { "Storage is not owned" }
84
+ if (!file.exists()) return JsonNull.INSTANCE
85
+ val saved = JsonParser.parseString(file.readText(Charsets.UTF_8))
86
+ if (!saved.isJsonObject) throw CrocheException("storage_error", "Existing Runtime snapshot must be an object")
87
+ return saved
88
+ }
89
+ @Synchronized override fun save(state: JsonElement) {
90
+ check(handle != null) { "Storage is not owned" }
91
+ replace(file, state)
92
+ }
93
+ @Synchronized override fun load(entry: String): JsonElement {
94
+ val sidecar = sidecar(entry)
95
+ if (!sidecar.exists()) return JsonNull.INSTANCE
96
+ return JsonParser.parseString(sidecar.readText(Charsets.UTF_8))
97
+ }
98
+ @Synchronized override fun save(entry: String, value: JsonElement) = replace(sidecar(entry), value)
99
+ private fun sidecar(entry: String): File {
100
+ check(handle != null) { "Storage is not owned" }
101
+ if (!Regex("[a-z0-9]+").matches(entry)) throw CrocheException("storage_error", "Invalid storage entry")
102
+ return File(file.path + "." + entry)
103
+ }
104
+ private fun replace(target: File, value: JsonElement) {
105
+ val temporary = File.createTempFile("croche-", ".tmp", target.absoluteFile.parentFile)
106
+ try {
107
+ FileOutputStream(temporary).use { output ->
108
+ output.write(value.toString().toByteArray(Charsets.UTF_8)); output.fd.sync()
109
+ }
110
+ Files.move(temporary.toPath(), target.toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
111
+ } finally { temporary.delete() }
112
+ }
113
+ // The turn archive (F20.6)
114
+ @Synchronized override fun appendLine(entry: String, line: String) {
115
+ val target = segment(entry)
116
+ if (line.contains('\n')) throw CrocheException("storage_error", "An archive line holds no newline")
117
+ RandomAccessFile(target, "rw").use { output ->
118
+ val size = output.length()
119
+ val bytes = java.io.ByteArrayOutputStream()
120
+ if (size > 0) {
121
+ output.seek(size - 1)
122
+ if (output.read() != '\n'.code) bytes.write('\n'.code) // a torn line never swallows this record
123
+ }
124
+ bytes.write(line.toByteArray(Charsets.UTF_8)); bytes.write('\n'.code)
125
+ output.seek(size)
126
+ output.write(bytes.toByteArray())
127
+ output.fd.sync()
128
+ }
129
+ }
130
+ @Synchronized override fun readLines(entry: String): List<String> {
131
+ val target = segment(entry)
132
+ if (!target.exists()) return emptyList()
133
+ val lines = target.readText(Charsets.UTF_8).split('\n')
134
+ // The piece after the last newline: a torn line, or "" when the file ends whole.
135
+ return lines.dropLast(1).filter { it.isNotEmpty() }
136
+ }
137
+ @Synchronized override fun replaceLines(entry: String, lines: List<String>) {
138
+ val target = segment(entry)
139
+ if (lines.isEmpty()) { Files.deleteIfExists(target.toPath()); return }
140
+ if (lines.any { it.contains('\n') }) throw CrocheException("storage_error", "An archive line holds no newline")
141
+ // '.' and '-' are outside the entry rule: a temporary is never an entry, `held` or `lock`.
142
+ val temporary = File(target.path + ".tmp-" + java.util.UUID.randomUUID().toString())
143
+ try {
144
+ FileOutputStream(temporary).use { output ->
145
+ output.write(lines.joinToString("") { it + "\n" }.toByteArray(Charsets.UTF_8)); output.fd.sync()
146
+ }
147
+ beforeCommit?.invoke(temporary)
148
+ Files.move(temporary.toPath(), target.toPath(), ATOMIC_MOVE, REPLACE_EXISTING)
149
+ } finally { temporary.delete() }
150
+ }
151
+ @Synchronized override fun remove() {
152
+ check(handle != null) { "Storage is not owned" }
153
+ Files.deleteIfExists(file.toPath())
154
+ }
155
+ @Synchronized override fun remove(entry: String) { Files.deleteIfExists(sidecar(entry).toPath()) }
156
+ @Synchronized override fun entries(prefix: String): Map<String, Long> {
157
+ check(handle != null) { "Storage is not owned" }
158
+ return siblings().filter { (name, _) -> ENTRY.matches(name) && name.startsWith(prefix) }
159
+ .associate { (name, path) -> name to path.length() }
160
+ }
161
+ /** The archive's entries are segments only (`archive` and four digits): never the snapshot's
162
+ * own sidecars (`held`) or its lock file (`lock`). */
163
+ private fun segment(entry: String): File {
164
+ if (!SEGMENT.matches(entry)) throw CrocheException("storage_error", "Invalid archive entry")
165
+ return sidecar(entry)
166
+ }
167
+ /** The files beside the snapshot, `<file>.<suffix>`, as (suffix, file). */
168
+ private fun siblings(): List<Pair<String, File>> {
169
+ val directory = file.absoluteFile.parentFile ?: return emptyList()
170
+ val base = file.name + "."
171
+ return (directory.listFiles() ?: emptyArray()).filter { it.name.startsWith(base) }
172
+ .map { it.name.substring(base.length) to it }
173
+ }
174
+ /** Segment rewrites a crash interrupted (`archive<NNNN>.tmp-<nonce>`): deleted by the owner. */
175
+ private fun removeStaleTemporaries() {
176
+ for ((suffix, path) in siblings()) if (STALE.matches(suffix)) path.delete()
177
+ }
178
+ @Synchronized override fun release() {
179
+ try { lock?.release() } finally { lock = null; handle?.close(); handle = null }
180
+ }
181
+ }
@@ -0,0 +1,211 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.JsonArray
4
+ import com.google.gson.JsonObject
5
+ import kotlinx.coroutines.*
6
+ import kotlinx.coroutines.flow.Flow
7
+ import kotlinx.coroutines.flow.flow
8
+
9
+ /** Proposed SDK adapter only, not a Rust ABI. Core owns all projection and durable reads. */
10
+ internal interface CoreStreamPort {
11
+ val logId: String
12
+ val state: RuntimeEvent.State
13
+ fun observe(event: (RuntimeEvent) -> Unit, end: (Throwable?) -> Unit): AutoCloseable
14
+ fun select(initialMessages: Int?, after: Cursor?, event: (RuntimeEvent) -> Unit): Projection
15
+ suspend fun send(input: JsonObject, options: SendOptions): Receipt
16
+ suspend fun readOutcome(id: String, fromSeq: Long, captured: (CapturedOutcome) -> Unit): RetainedEnds
17
+ suspend fun cancel(id: String)
18
+ suspend fun clearHistory()
19
+ fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>)
20
+ fun close()
21
+ interface Projection : AutoCloseable {
22
+ /** Joins Core's synchronous listener, not buffered Flow/UI consumers. A synchronous
23
+ * close from that listener itself fences without waiting for its own stack.
24
+ * An app callback that waits for work on the closer's thread deadlocks under any
25
+ * wait-for-callback fence. */
26
+ override fun close()
27
+ suspend fun history(before: Long?, limit: Int)
28
+ }
29
+ }
30
+ /** Typed fake-port failure; the future native adapter supplies the flag, never a code heuristic. */
31
+ internal class CoreStreamFailure(val code: String, override val message: String, val poisoned: Boolean) : RuntimeException(message)
32
+ internal fun streamEnd(cause: Throwable?): RuntimeEvent.StreamError {
33
+ val typed = cause as? CoreStreamFailure
34
+ val code = typed?.code ?: (cause as? CrocheException)?.code ?: "closed"
35
+ return RuntimeEvent.StreamError(code, cause?.message ?: "Runtime is closed", typed?.poisoned ?: false)
36
+ }
37
+ internal data class CapturedOutcome(val head: Long, val floor: Long, val status: InputStatus, val idle: Boolean)
38
+ internal data class RetainedEnds(val messages: List<RuntimeEvent.MessageEnd>, val gap: Boolean = false)
39
+ internal fun InputStatus.terminal(): Boolean = this in setOf(InputStatus.ANSWERED, InputStatus.NO_REPLY,
40
+ InputStatus.FAILED, InputStatus.CANCELLED, InputStatus.SETTLED_BEFORE_UPGRADE)
41
+ internal fun maintenanceInterval(value: Long): Long = value.coerceAtLeast(1000)
42
+
43
+ /** No app code executes on the canonical callback stack. All bookkeeping is monitor-protected. */
44
+ internal class StreamHub(private val port: CoreStreamPort) : AutoCloseable {
45
+ private val lock = Any()
46
+ private val waiters = linkedSetOf<Waiter>()
47
+ private var ended = false
48
+ private var app: AppStreamBranch? = null
49
+ private var projection: CoreStreamPort.Projection? = null
50
+ private val observation = port.observe({ event ->
51
+ synchronized(lock) { waiters.toList().forEach { it.event(event) } }
52
+ }, { cause -> end(cause) })
53
+ val logId get() = port.logId
54
+ val state get() = port.state
55
+
56
+ fun events(initialMessages: Int? = 50, after: Cursor? = null): Flow<RuntimeEvent> = flow {
57
+ val branch = AppStreamBranch()
58
+ val selected = synchronized(lock) {
59
+ if (ended) null else {
60
+ projection?.close()
61
+ projection = null
62
+ app?.end(RuntimeEvent.Replaced)
63
+ app = branch
64
+ // A new collection replaces its predecessor even when its options are invalid,
65
+ // matching S2. The error-only branch never selects Core.
66
+ if (initialMessages != null && initialMessages !in 0..256) {
67
+ branch.push(RuntimeEvent.StreamError("invalid_configuration", "initialMessages must be in 0..256", false))
68
+ null
69
+ } else try {
70
+ port.select(initialMessages, after, branch::push).also { projection = it }
71
+ } catch (failure: Exception) {
72
+ branch.end(streamEnd(failure))
73
+ null
74
+ }
75
+ }
76
+ }
77
+ if (selected == null && !branch.isEnded) branch.end(RuntimeEvent.StreamError("closed", "Runtime is closed", false))
78
+ try { branch.deliver { emit(it) } }
79
+ finally {
80
+ branch.close()
81
+ selected?.close()
82
+ synchronized(lock) { if (app === branch) { app = null; projection = null } }
83
+ }
84
+ }
85
+
86
+ suspend fun send(input: SendInput, options: SendOptions): Receipt {
87
+ currentCoroutineContext().ensureActive()
88
+ synchronized(lock) { if (ended) throw CrocheException("closed", "Runtime is closed") }
89
+ return port.send(input.encoded(options), options.owned())
90
+ }
91
+
92
+ suspend fun request(input: SendInput, options: SendOptions, wait: RequestWait?): RequestResult = coroutineScope {
93
+ ensureActive()
94
+ val owned = input.owned()
95
+ val waiter = Waiter(owned.id, wait)
96
+ synchronized(lock) {
97
+ if (ended) throw CrocheException("closed", "Runtime is closed")
98
+ waiters.add(waiter) // Before send: immediate canonical progress must not outrun registration.
99
+ }
100
+ val read = launch(start = CoroutineStart.UNDISPATCHED) {
101
+ try {
102
+ val encoded = owned.encoded(options)
103
+ val receipt = port.send(encoded, options.owned())
104
+ val proceed = synchronized(lock) {
105
+ waiter.receipt = receipt
106
+ // Terminal same-id retries emit no new input event. Seed before idle
107
+ // overtakes capture, without regressing an already observed disposition.
108
+ if (waiter.status == null || (waiter.status?.terminal() != true && receipt.status.terminal())) {
109
+ waiter.status = receipt.status
110
+ }
111
+ if (waiter.lost) { waiter.failLost(); false } else true
112
+ }
113
+ if (!proceed) return@launch
114
+ if (receipt.seq == null) {
115
+ waiter.result.complete(RequestResult(receipt.id, receipt.status, emptyList(), false, true))
116
+ return@launch
117
+ }
118
+ var captured = false
119
+ val retained = port.readOutcome(receipt.id, receipt.seq) { snapshot ->
120
+ synchronized(lock) {
121
+ captured = true
122
+ if (waiter.status?.terminal() != true) waiter.status = snapshot.status
123
+ waiter.gap = receipt.seq < snapshot.floor
124
+ if (completion(waiter.status, snapshot.idle, waiter.wait)) waiter.complete = true
125
+ }
126
+ }
127
+ check(captured) { "Core outcome read omitted its ordered capture" }
128
+ synchronized(lock) {
129
+ waiter.gap = waiter.gap || retained.gap
130
+ retained.messages.filter { receipt.id in it.causedBy }.forEach { waiter.add(it) }
131
+ waiter.reading = false
132
+ waiter.finish()
133
+ }
134
+ } catch (cancelled: CancellationException) {
135
+ throw cancelled
136
+ } catch (failure: Exception) {
137
+ synchronized(lock) {
138
+ waiter.result.completeExceptionally(if (waiter.receipt != null)
139
+ CrocheException("observation_lost", "Observation ended after acceptance", waiter.receipt) else failure)
140
+ }
141
+ }
142
+ }
143
+ try { waiter.result.await() }
144
+ finally {
145
+ synchronized(lock) { waiters.remove(waiter) }
146
+ read.cancel() // Stops observation/storage wait only; never calls port.cancel.
147
+ }
148
+ }
149
+
150
+ // Keel #361 6071161214: Both forms require an attached stream; pin its projection generation.
151
+ suspend fun history(before: Long?, limit: Int) {
152
+ if (limit !in 1..256) throw CrocheException("invalid_configuration", "history limit must be 1..256")
153
+ val selected = synchronized(lock) { projection }
154
+ ?: throw CrocheException("invalid_configuration", "history requires an app collection")
155
+ selected.history(before, limit)
156
+ }
157
+ suspend fun cancel(id: String) = port.cancel(id)
158
+ suspend fun clearHistory() = port.clearHistory()
159
+ fun setTools(tools: JsonArray, handlers: Map<String, ToolHandler>) = port.setTools(tools, handlers)
160
+ override fun close() { try { port.close() } finally { end(); observation.close() } }
161
+ private fun end(cause: Throwable? = null) = synchronized(lock) {
162
+ if (!ended) {
163
+ ended = true
164
+ projection?.close()
165
+ val terminal = streamEnd(cause)
166
+ app?.end(terminal)
167
+ waiters.toList().forEach { it.lost = true; if (it.receipt != null) it.failLost() }
168
+ }
169
+ }
170
+
171
+ // OPEN(§18.24.D): Default stays S2 terminal-plus-idle until Atlas rules on consuming-unit
172
+ // evidence. IDLE explicitly selects the same behavior; no unit-end heuristic or pending.
173
+ // One predicate is the replacement point; do not infer a unit end from state/turn/answered.
174
+ private fun completion(status: InputStatus?, idle: Boolean, wait: RequestWait?): Boolean = when (wait) {
175
+ null -> status?.terminal() == true && idle
176
+ RequestWait.IDLE -> status?.terminal() == true && idle
177
+ }
178
+
179
+ private inner class Waiter(val id: String, val wait: RequestWait?) {
180
+ val result = CompletableDeferred<RequestResult>()
181
+ var receipt: Receipt? = null
182
+ var status: InputStatus? = null
183
+ var complete = false
184
+ var reading = true
185
+ var lost = false
186
+ var gap = false
187
+ val messages = linkedMapOf<Pair<String, Long>, RuntimeEvent.MessageEnd>()
188
+ fun add(event: RuntimeEvent.MessageEnd) { messages[event.id to event.seq] = event.owned() as RuntimeEvent.MessageEnd }
189
+ fun event(event: RuntimeEvent) {
190
+ if (complete || result.isCompleted) return
191
+ when (event) {
192
+ is RuntimeEvent.Input -> if (event.id == id && status?.terminal() != true) status = event.status
193
+ is RuntimeEvent.MessageEnd -> if (id in event.causedBy) add(event)
194
+ is RuntimeEvent.State -> if (completion(status, event.status == AgentStatus.IDLE, wait)) complete = true
195
+ else -> Unit
196
+ }
197
+ finish()
198
+ }
199
+ fun finish() {
200
+ val accepted = receipt ?: return
201
+ val disposition = status ?: return
202
+ if (!reading && complete) result.complete(RequestResult(accepted.id, disposition,
203
+ messages.values.sortedBy { it.seq }, gap, false))
204
+ }
205
+ fun failLost() { result.completeExceptionally(CrocheException("observation_lost", "Reopen and retry the same id and input", receipt)) }
206
+ }
207
+ }
208
+
209
+ internal fun SendInput.owned() = copy(images = images.toList(), context = context?.deepCopy(),
210
+ inputs = inputs.map { it.copy(images = it.images.toList()) })
211
+ internal fun SendOptions.owned() = copy(responseFormat = responseFormat?.deepCopy())
@@ -0,0 +1,74 @@
1
+ package dev.croche
2
+
3
+ import com.google.gson.JsonElement
4
+ import com.google.gson.JsonObject
5
+ import java.time.Instant
6
+
7
+ /** Subscription API preview; native binding is deliberately not installed in Phase 1. */
8
+ data class StackedInput(val kind: InputKind = InputKind.USER, val text: String? = null,
9
+ val images: List<InputImage> = emptyList())
10
+ data class SendInput(val id: String, val text: String = "", val kind: InputKind = InputKind.USER,
11
+ val images: List<InputImage> = emptyList(), val context: JsonElement? = null,
12
+ val inputs: List<StackedInput> = emptyList())
13
+ data class SendOptions(val responseFormat: JsonObject? = null, val imageResolution: ImageResolution? = null)
14
+ data class Receipt(val id: String, val status: InputStatus, val seq: Long?)
15
+ // OPEN(§18.24.D): No pending field until Atlas approves the consuming-unit contract.
16
+ enum class RequestWait { IDLE }
17
+ data class RequestResult(val id: String, val status: InputStatus, val messages: List<RuntimeEvent.MessageEnd>,
18
+ val gap: Boolean, val legacy: Boolean)
19
+ data class Cursor(val logId: String, val seq: Long)
20
+ data class RuntimeError(val code: String, val message: String)
21
+ data class Streaming(val messageId: String, val firstSeq: Long, val text: String)
22
+ data class ImageSummary(val alt: String?, val mime: String?, val bytes: Long?)
23
+ data class ToolSource(val command: String, val callId: String)
24
+ enum class InputKind { USER, EVENT, UNKNOWN }
25
+ enum class InputStatus { QUEUED, SEEN, ANSWERED, NO_REPLY, FAILED, CANCELLED, SETTLED_BEFORE_UPGRADE, UNKNOWN }
26
+ enum class MessageStatus { COMPLETED, FAILED, CANCELLED, INTERRUPTED, UNKNOWN }
27
+ enum class AgentStatus { RUNNING, WAITING, IDLE, UNKNOWN }
28
+ /** The stream `state`'s `activity`: a model call, a summary call (held before the reply), or a
29
+ * tool round. A value this SDK does not know yet is UNKNOWN, never a stream error. */
30
+ enum class AgentActivity { MODEL, SUMMARY, TOOL, UNKNOWN }
31
+ enum class CostStatus { REPORTED, ESTIMATED, NONE, UNKNOWN }
32
+ enum class GapReason { CLEARED, LIMIT, UNKNOWN }
33
+ enum class ImageMime { PNG, JPEG, WEBP, GIF }
34
+
35
+ class InputImage {
36
+ internal val json: JsonObject
37
+ constructor(data: ByteArray, mime: ImageMime, alt: String? = null, resolution: ImageResolution? = null) {
38
+ json = JsonObject().apply {
39
+ addProperty("data", java.util.Base64.getEncoder().encodeToString(data))
40
+ addProperty("mime", "image/${mime.name.lowercase()}")
41
+ alt?.let { addProperty("alt", it) }
42
+ resolution?.let { addProperty("resolution", it.name.lowercase()) }
43
+ }
44
+ }
45
+ constructor(url: String, alt: String? = null) {
46
+ json = JsonObject().apply { addProperty("url", url); alt?.let { addProperty("alt", it) } }
47
+ }
48
+ }
49
+
50
+ sealed class RuntimeEvent {
51
+ open val seq: Long? get() = null
52
+ data class Input(override val seq: Long, val firstSeq: Long, val id: String, val kind: InputKind, val text: String?,
53
+ val images: List<ImageSummary>, val status: InputStatus, val error: RuntimeError?, val at: Instant) : RuntimeEvent()
54
+ data class MessageStart(override val seq: Long, val firstSeq: Long, val id: String, val at: Instant) : RuntimeEvent()
55
+ data class MessageEnd(override val seq: Long, val firstSeq: Long, val id: String, val status: MessageStatus,
56
+ val text: String, val markers: List<String>, val output: JsonElement?, val inReplyTo: List<String>, val causedBy: List<String>,
57
+ val error: RuntimeError?, val at: Instant) : RuntimeEvent()
58
+ data class Cleared(override val seq: Long, val id: String, val at: Instant) : RuntimeEvent()
59
+ data class App(override val seq: Long, val id: String, val name: String, val data: JsonElement, val source: ToolSource, val at: Instant) : RuntimeEvent()
60
+ data class Turn(override val seq: Long, val id: String, val causedBy: List<String>, val inputs: List<String>, val purpose: String, val usage: Map<String, Long>, val costUsd: Double,
61
+ val costStatus: CostStatus, val model: String, val imagesOmitted: Int?, val at: Instant) : RuntimeEvent()
62
+ data class Error(override val seq: Long, val id: String, val code: String, val message: String, val inputs: List<String>, val at: Instant) : RuntimeEvent()
63
+ data class MessageDelta(val id: String, val text: String) : RuntimeEvent()
64
+ /** `activity` is set exactly while `status` is RUNNING; `tools` only with TOOL: the command keys
65
+ * the round runs, in call order, never arguments. */
66
+ data class State(val status: AgentStatus, val queued: Int, val typing: Boolean,
67
+ val activity: AgentActivity? = null, val tools: List<String>? = null) : RuntimeEvent()
68
+ data class Page(val messages: List<RuntimeEvent>, val reachedFloor: Boolean, val logId: String, val clearedSeq: Long) : RuntimeEvent()
69
+ data class Gap(val afterSeq: Long, val throughSeq: Long, val reason: GapReason) : RuntimeEvent()
70
+ data class Snapshot(val logId: String, val state: State, val streaming: Streaming?) : RuntimeEvent()
71
+ data class StreamError(val code: String, val message: String, val poisoned: Boolean) : RuntimeEvent()
72
+ data object Replaced : RuntimeEvent()
73
+ data class Unknown(val type: String) : RuntimeEvent()
74
+ }