Skip to content

armgit / uzu

Public Imported from GitHub
0

A high-performance inference engine for AI models

Bindings migration n/n (#367)

Aleksei Savin2f291b8140ef
diff --git a/.github/actions/setup/action.yml b/.github/actions/setup/action.yml
index 5fa87dfb0..47738470b 100644
--- a/.github/actions/setup/action.yml
+++ b/.github/actions/setup/action.yml
@@ -26,10 +26,25 @@ inputs:
description: "Install Node + pnpm"
required: false
default: 'false'
+ swift:
+ description: "Install cargo-swift CLI"
+ required: false
+ default: 'false'
runs:
using: composite
steps:
+ - if: inputs.target != ''
+ run: |
+ if ! command -v rustup >/dev/null 2>&1; then
+ echo "rustup not installed, skipping target reset"
+ exit 0
+ fi
+ rustup self update >/dev/null
+ rustup target remove "${{ inputs.target }}" 2>/dev/null || true
+ rm -rf "$(rustc --print sysroot)/lib/rustlib/${{ inputs.target }}"
+ shell: bash
+
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ inputs.target }}
@@ -84,3 +99,9 @@ runs:
uses: pnpm/action-setup@v4
with:
version: 10.33.0
+
+ # Please make sure to use compatible versions of the cargo-swift / uniffi pair.
+ # See: https://github.com/antoniusnaumann/cargo-swift?tab=readme-ov-file#installing-for-a-different-uniffi-version
+ - if: inputs.swift == 'true'
+ run: cargo install [email protected] -f
+ shell: bash
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 452999cc8..2de9c444e 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -112,6 +112,7 @@ jobs:
with:
metal: true
node: true
+ swift: true
- name: Prepare bindings
run: cargo run -p cli-release prepare-bindings
diff --git a/.gitignore b/.gitignore
index 8f588479b..49a373be5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,9 +20,6 @@
.cursor
.claude/settings.local.json
-# Models
-/models/
-
# Local-only dev tools
.env
.DS_Store
diff --git a/.swift-format b/.swift-format
new file mode 100644
index 000000000..8fd7730c0
--- /dev/null
+++ b/.swift-format
@@ -0,0 +1,79 @@
+{
+ "fileScopedDeclarationPrivacy" : {
+ "accessLevel" : "private"
+ },
+ "indentConditionalCompilationBlocks" : true,
+ "indentSwitchCaseLabels" : false,
+ "indentation" : {
+ "spaces" : 4
+ },
+ "lineBreakAroundMultilineExpressionChainComponents" : false,
+ "lineBreakBeforeControlFlowKeywords" : false,
+ "lineBreakBeforeEachArgument" : false,
+ "lineBreakBeforeEachGenericRequirement" : false,
+ "lineBreakBetweenDeclarationAttributes" : false,
+ "lineLength" : 100,
+ "maximumBlankLines" : 1,
+ "multiElementCollectionTrailingCommas" : true,
+ "noAssignmentInExpressions" : {
+ "allowedFunctions" : [
+ "XCTAssertNoThrow"
+ ]
+ },
+ "prioritizeKeepingFunctionOutputTogether" : false,
+ "reflowMultilineStringLiterals" : {
+ "never" : {
+
+ }
+ },
+ "respectsExistingLineBreaks" : true,
+ "rules" : {
+ "AllPublicDeclarationsHaveDocumentation" : false,
+ "AlwaysUseLiteralForEmptyCollectionInit" : false,
+ "AlwaysUseLowerCamelCase" : true,
+ "AmbiguousTrailingClosureOverload" : true,
+ "AvoidRetroactiveConformances" : true,
+ "BeginDocumentationCommentWithOneLineSummary" : false,
+ "DoNotUseSemicolons" : true,
+ "DontRepeatTypeInStaticProperties" : true,
+ "FileScopedDeclarationPrivacy" : true,
+ "FullyIndirectEnum" : true,
+ "GroupNumericLiterals" : true,
+ "IdentifiersMustBeASCII" : true,
+ "NeverForceUnwrap" : false,
+ "NeverUseForceTry" : false,
+ "NeverUseImplicitlyUnwrappedOptionals" : false,
+ "NoAccessLevelOnExtensionDeclaration" : true,
+ "NoAssignmentInExpressions" : true,
+ "NoBlockComments" : true,
+ "NoCasesWithOnlyFallthrough" : true,
+ "NoEmptyLinesOpeningClosingBraces" : false,
+ "NoEmptyTrailingClosureParentheses" : true,
+ "NoLabelsInCasePatterns" : true,
+ "NoLeadingUnderscores" : false,
+ "NoParensAroundConditions" : true,
+ "NoPlaygroundLiterals" : true,
+ "NoVoidReturnOnFunctionSignature" : true,
+ "OmitExplicitReturns" : false,
+ "OneCasePerLine" : true,
+ "OneVariableDeclarationPerLine" : true,
+ "OnlyOneTrailingClosureArgument" : true,
+ "OrderedImports" : true,
+ "ReplaceForEachWithForLoop" : true,
+ "ReturnVoidInsteadOfEmptyTuple" : true,
+ "TypeNamesShouldBeCapitalized" : true,
+ "UseEarlyExits" : false,
+ "UseExplicitNilCheckInConditions" : true,
+ "UseLetInEveryBoundCaseVariable" : true,
+ "UseShorthandTypeNames" : true,
+ "UseSingleLinePropertyGetter" : true,
+ "UseSynthesizedInitializer" : true,
+ "UseTripleSlashForDocumentationComments" : true,
+ "UseWhereClausesInForLoops" : false,
+ "ValidateDocumentationComments" : false
+ },
+ "spacesAroundRangeFormationOperators" : false,
+ "spacesBeforeEndOfLineComments" : 2,
+ "tabWidth" : 8,
+ "version" : 1
+}
diff --git a/CODEOWNERS b/CODEOWNERS
index fdec27ddf..c296890d2 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -1,4 +1,5 @@
/.github @uuuvn
+/apps/playground @alexxale
/crates/backend-remote @alexxale
/crates/backend-uzu/build @uuuvn
/crates/backend-uzu/src/backends/cpu @uuuvn
diff --git a/Cargo.lock b/Cargo.lock
index ddcd3f4e7..74d5f3d24 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -264,6 +264,19 @@ dependencies = [
"pin-project-lite",
]
+[[package]]
+name = "async-compat"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1ba85bc55464dcbf728b56d97e119d673f4cf9062be330a9a26f3acf504a590"
+dependencies = [
+ "futures-core",
+ "futures-io",
+ "once_cell",
+ "pin-project-lite",
+ "tokio",
+]
+
[[package]]
name = "async-fetcher"
version = "0.12.0"
@@ -821,6 +834,7 @@ dependencies = [
name = "bindings"
version = "0.1.9"
dependencies = [
+ "heck",
"proc-macro2",
"quote",
"syn 2.0.117",
@@ -1293,6 +1307,7 @@ dependencies = [
"ignore",
"regex",
"serde_json",
+ "syn 2.0.117",
"thiserror 2.0.18",
]
@@ -7681,6 +7696,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77baf5d539fe2e1ad6805e942dbc5dbdeb2b83eb5f2b3a6535d422ca4b02a12f"
dependencies = [
"anyhow",
+ "async-compat",
"bytes",
"once_cell",
"static_assertions",
diff --git a/Cargo.toml b/Cargo.toml
index ffbdbe89f..a39829fc4 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -128,7 +128,9 @@ crc32c = "0.6.8"
base64 = "0.22.1"
chrono = { version = "0.4.42", features = ["serde"] }
jsonschema = "0.46.0"
-uniffi = "0.31.0"
+# Please make sure to use compatible versions of the cargo-swift / uniffi pair.
+# See: https://github.com/antoniusnaumann/cargo-swift?tab=readme-ov-file#installing-for-a-different-uniffi-version
+uniffi = { version = "0.31.1", features = ["tokio"] }
napi = { version = "3.8.3", features = [
"napi10",
"object_indexmap",
diff --git a/apps/playground/.gitignore b/apps/playground/.gitignore
new file mode 100644
index 000000000..e0253c455
--- /dev/null
+++ b/apps/playground/.gitignore
@@ -0,0 +1,65 @@
+# Xcode
+#
+# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
+
+## User settings
+xcuserdata/
+
+## Obj-C/Swift specific
+*.hmap
+
+## App packaging
+*.ipa
+*.dSYM.zip
+*.dSYM
+
+## Playgrounds
+timeline.xctimeline
+playground.xcworkspace
+
+# Swift Package Manager
+#
+# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
+# Packages/
+# Package.pins
+# Package.resolved
+*.xcodeproj
+#
+# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
+# hence it is not needed unless you have added a package configuration file to your project
+.swiftpm
+
+.build/
+
+# CocoaPods
+#
+# We recommend against adding the Pods directory to your .gitignore. However
+# you should judge for yourself, the pros and cons are mentioned at:
+# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
+#
+# Pods/
+#
+# Add this line if you want to avoid checking in source code from the Xcode workspace
+*.xcworkspace
+
+# Carthage
+#
+# Add this line if you want to avoid checking in source code from Carthage dependencies.
+# Carthage/Checkouts
+
+Carthage/Build/
+
+# fastlane
+#
+# It is recommended to not store the screenshots in the git repo.
+# Instead, use fastlane to re-generate the screenshots whenever they are needed.
+# For more information about the recommended setup visit:
+# https://docs.fastlane.tools/best-practices/source-control/#source-control
+
+fastlane/report.xml
+fastlane/Preview.html
+fastlane/screenshots/**/*.png
+fastlane/test_output
+
+Derived/
+Generated/
\ No newline at end of file
diff --git a/apps/playground/.package.resolved b/apps/playground/.package.resolved
new file mode 100644
index 000000000..d038b81ee
--- /dev/null
+++ b/apps/playground/.package.resolved
@@ -0,0 +1,150 @@
+{
+ "originHash" : "7170308662a4f566d1da4d57058587bdd4db74f297c35e0093bd63399b429da3",
+ "pins" : [
+ {
+ "identity" : "abseil-cpp-binary",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/abseil-cpp-binary.git",
+ "state" : {
+ "revision" : "bbe8b69694d7873315fd3a4ad41efe043e1c07c5",
+ "version" : "1.2024072200.0"
+ }
+ },
+ {
+ "identity" : "app-check",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/app-check.git",
+ "state" : {
+ "revision" : "61b85103a1aeed8218f17c794687781505fbbef5",
+ "version" : "11.2.0"
+ }
+ },
+ {
+ "identity" : "firebase-ios-sdk",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/firebase/firebase-ios-sdk",
+ "state" : {
+ "revision" : "fdc352fabaf5916e7faa1f96ad02b1957e93e5a5",
+ "version" : "11.15.0"
+ }
+ },
+ {
+ "identity" : "google-ads-on-device-conversion-ios-sdk",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/googleads/google-ads-on-device-conversion-ios-sdk",
+ "state" : {
+ "revision" : "a2d0f1f1666de591eb1a811f40b1706f5c63a2ed",
+ "version" : "2.3.0"
+ }
+ },
+ {
+ "identity" : "googleappmeasurement",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/GoogleAppMeasurement.git",
+ "state" : {
+ "revision" : "45ce435e9406d3c674dd249a042b932bee006f60",
+ "version" : "11.15.0"
+ }
+ },
+ {
+ "identity" : "googledatatransport",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/GoogleDataTransport.git",
+ "state" : {
+ "revision" : "617af071af9aa1d6a091d59a202910ac482128f9",
+ "version" : "10.1.0"
+ }
+ },
+ {
+ "identity" : "googleutilities",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/GoogleUtilities.git",
+ "state" : {
+ "revision" : "60da361632d0de02786f709bdc0c4df340f7613e",
+ "version" : "8.1.0"
+ }
+ },
+ {
+ "identity" : "grpc-binary",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/grpc-binary.git",
+ "state" : {
+ "revision" : "75b31c842f664a0f46a2e590a570e370249fd8f6",
+ "version" : "1.69.1"
+ }
+ },
+ {
+ "identity" : "gtm-session-fetcher",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/gtm-session-fetcher.git",
+ "state" : {
+ "revision" : "c756a29784521063b6a1202907e2cc47f41b667c",
+ "version" : "4.5.0"
+ }
+ },
+ {
+ "identity" : "interop-ios-for-google-sdks",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/interop-ios-for-google-sdks.git",
+ "state" : {
+ "revision" : "040d087ac2267d2ddd4cca36c757d1c6a05fdbfe",
+ "version" : "101.0.0"
+ }
+ },
+ {
+ "identity" : "leveldb",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/firebase/leveldb.git",
+ "state" : {
+ "revision" : "a0bc79961d7be727d258d33d5a6b2f1023270ba1",
+ "version" : "1.22.5"
+ }
+ },
+ {
+ "identity" : "nanopb",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/firebase/nanopb.git",
+ "state" : {
+ "revision" : "b7e1104502eca3a213b46303391ca4d3bc8ddec1",
+ "version" : "2.30910.0"
+ }
+ },
+ {
+ "identity" : "promises",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/promises.git",
+ "state" : {
+ "revision" : "540318ecedd63d883069ae7f1ed811a2df00b6ac",
+ "version" : "2.4.0"
+ }
+ },
+ {
+ "identity" : "sfsymbols",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/Rspoon3/SFSymbols",
+ "state" : {
+ "revision" : "0860caebd6efd296b66cf128d58972b9c52800db",
+ "version" : "2.6.1"
+ }
+ },
+ {
+ "identity" : "swift-argument-parser",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-argument-parser",
+ "state" : {
+ "revision" : "626b5b7b2f45e1b0b1c6f4a309296d1d21d7311b",
+ "version" : "1.7.1"
+ }
+ },
+ {
+ "identity" : "swift-protobuf",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-protobuf.git",
+ "state" : {
+ "revision" : "e3f69fd321d0c9fcdc16fb576a0cdd956675face",
+ "version" : "1.31.0"
+ }
+ }
+ ],
+ "version" : 3
+}
diff --git a/apps/playground/.swift-format b/apps/playground/.swift-format
new file mode 100644
index 000000000..1e089a50d
--- /dev/null
+++ b/apps/playground/.swift-format
@@ -0,0 +1,81 @@
+{
+ "fileScopedDeclarationPrivacy" : {
+ "accessLevel" : "private"
+ },
+ "indentConditionalCompilationBlocks" : true,
+ "indentSwitchCaseLabels" : false,
+ "indentation" : {
+ "spaces" : 4
+ },
+ "lineBreakAroundMultilineExpressionChainComponents" : false,
+ "lineBreakBeforeControlFlowKeywords" : false,
+ "lineBreakBeforeEachArgument" : false,
+ "lineBreakBeforeEachGenericRequirement" : false,
+ "lineBreakBetweenDeclarationAttributes" : false,
+ "lineLength" : 100,
+ "maximumBlankLines" : 1,
+ "multiElementCollectionTrailingCommas" : true,
+ "noAssignmentInExpressions" : {
+ "allowedFunctions" : [
+ "XCTAssertNoThrow"
+ ]
+ },
+ "prioritizeKeepingFunctionOutputTogether" : false,
+ "reflowMultilineStringLiterals" : {
+ "never" : {
+
+ }
+ },
+ "respectsExistingLineBreaks" : true,
+ "rules" : {
+ "AllPublicDeclarationsHaveDocumentation" : false,
+ "AlwaysUseLiteralForEmptyCollectionInit" : false,
+ "AlwaysUseLowerCamelCase" : true,
+ "AmbiguousTrailingClosureOverload" : true,
+ "AvoidRetroactiveConformances" : true,
+ "BeginDocumentationCommentWithOneLineSummary" : false,
+ "DoNotUseSemicolons" : true,
+ "DontRepeatTypeInStaticProperties" : true,
+ "FileScopedDeclarationPrivacy" : true,
+ "FullyIndirectEnum" : true,
+ "GroupNumericLiterals" : true,
+ "IdentifiersMustBeASCII" : true,
+ "NeverForceUnwrap" : false,
+ "NeverUseForceTry" : false,
+ "NeverUseImplicitlyUnwrappedOptionals" : false,
+ "NoAccessLevelOnExtensionDeclaration" : true,
+ "NoAssignmentInExpressions" : true,
+ "NoBlockComments" : true,
+ "NoCasesWithOnlyFallthrough" : true,
+ "NoEmptyLinesOpeningClosingBraces" : false,
+ "NoEmptyTrailingClosureParentheses" : true,
+ "NoLabelsInCasePatterns" : true,
+ "NoLeadingUnderscores" : false,
+ "NoParensAroundConditions" : true,
+ "NoPlaygroundLiterals" : true,
+ "NoVoidReturnOnFunctionSignature" : true,
+ "OmitExplicitReturns" : false,
+ "OneCasePerLine" : true,
+ "OneVariableDeclarationPerLine" : true,
+ "OnlyOneTrailingClosureArgument" : true,
+ "OrderedImports" : true,
+ "ReplaceForEachWithForLoop" : true,
+ "ReturnVoidInsteadOfEmptyTuple" : true,
+ "TypeNamesShouldBeCapitalized" : true,
+ "UseEarlyExits" : false,
+ "UseExplicitNilCheckInConditions" : true,
+ "UseLetInEveryBoundCaseVariable" : true,
+ "UseShorthandTypeNames" : true,
+ "UseSingleLinePropertyGetter" : true,
+ "UseSynthesizedInitializer" : true,
+ "UseTripleSlashForDocumentationComments" : true,
+ "UseWhereClausesInForLoops" : false,
+ "ValidateDocumentationComments" : false
+ },
+ "spacesAroundRangeFormationOperators" : false,
+ "spacesBeforeEndOfLineComments" : 2,
+ "tabWidth" : 8,
+ "version" : 1
+}
+
+
diff --git a/apps/playground/Package.resolved b/apps/playground/Package.resolved
new file mode 100644
index 000000000..43f0f8da0
--- /dev/null
+++ b/apps/playground/Package.resolved
@@ -0,0 +1,149 @@
+{
+ "pins" : [
+ {
+ "identity" : "abseil-cpp-binary",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/abseil-cpp-binary.git",
+ "state" : {
+ "revision" : "bbe8b69694d7873315fd3a4ad41efe043e1c07c5",
+ "version" : "1.2024072200.0"
+ }
+ },
+ {
+ "identity" : "app-check",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/app-check.git",
+ "state" : {
+ "revision" : "61b85103a1aeed8218f17c794687781505fbbef5",
+ "version" : "11.2.0"
+ }
+ },
+ {
+ "identity" : "firebase-ios-sdk",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/firebase/firebase-ios-sdk",
+ "state" : {
+ "revision" : "fdc352fabaf5916e7faa1f96ad02b1957e93e5a5",
+ "version" : "11.15.0"
+ }
+ },
+ {
+ "identity" : "google-ads-on-device-conversion-ios-sdk",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/googleads/google-ads-on-device-conversion-ios-sdk",
+ "state" : {
+ "revision" : "a2d0f1f1666de591eb1a811f40b1706f5c63a2ed",
+ "version" : "2.3.0"
+ }
+ },
+ {
+ "identity" : "googleappmeasurement",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/GoogleAppMeasurement.git",
+ "state" : {
+ "revision" : "45ce435e9406d3c674dd249a042b932bee006f60",
+ "version" : "11.15.0"
+ }
+ },
+ {
+ "identity" : "googledatatransport",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/GoogleDataTransport.git",
+ "state" : {
+ "revision" : "617af071af9aa1d6a091d59a202910ac482128f9",
+ "version" : "10.1.0"
+ }
+ },
+ {
+ "identity" : "googleutilities",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/GoogleUtilities.git",
+ "state" : {
+ "revision" : "60da361632d0de02786f709bdc0c4df340f7613e",
+ "version" : "8.1.0"
+ }
+ },
+ {
+ "identity" : "grpc-binary",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/grpc-binary.git",
+ "state" : {
+ "revision" : "75b31c842f664a0f46a2e590a570e370249fd8f6",
+ "version" : "1.69.1"
+ }
+ },
+ {
+ "identity" : "gtm-session-fetcher",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/gtm-session-fetcher.git",
+ "state" : {
+ "revision" : "c756a29784521063b6a1202907e2cc47f41b667c",
+ "version" : "4.5.0"
+ }
+ },
+ {
+ "identity" : "interop-ios-for-google-sdks",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/interop-ios-for-google-sdks.git",
+ "state" : {
+ "revision" : "040d087ac2267d2ddd4cca36c757d1c6a05fdbfe",
+ "version" : "101.0.0"
+ }
+ },
+ {
+ "identity" : "leveldb",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/firebase/leveldb.git",
+ "state" : {
+ "revision" : "a0bc79961d7be727d258d33d5a6b2f1023270ba1",
+ "version" : "1.22.5"
+ }
+ },
+ {
+ "identity" : "nanopb",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/firebase/nanopb.git",
+ "state" : {
+ "revision" : "b7e1104502eca3a213b46303391ca4d3bc8ddec1",
+ "version" : "2.30910.0"
+ }
+ },
+ {
+ "identity" : "promises",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/google/promises.git",
+ "state" : {
+ "revision" : "540318ecedd63d883069ae7f1ed811a2df00b6ac",
+ "version" : "2.4.0"
+ }
+ },
+ {
+ "identity" : "sfsymbols",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/Rspoon3/SFSymbols",
+ "state" : {
+ "revision" : "0860caebd6efd296b66cf128d58972b9c52800db",
+ "version" : "2.6.1"
+ }
+ },
+ {
+ "identity" : "swift-protobuf",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-protobuf.git",
+ "state" : {
+ "revision" : "e3f69fd321d0c9fcdc16fb576a0cdd956675face",
+ "version" : "1.31.0"
+ }
+ },
+ {
+ "identity" : "uzu-swift",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/trymirai/uzu-swift.git",
+ "state" : {
+ "revision" : "f9be166de173de30e3eadf0e8a11f4e9706134cd",
+ "version" : "0.1.2"
+ }
+ }
+ ],
+ "version" : 2
+}
diff --git a/apps/playground/Project.swift b/apps/playground/Project.swift
new file mode 100644
index 000000000..85cb9481f
--- /dev/null
+++ b/apps/playground/Project.swift
@@ -0,0 +1,140 @@
+import ProjectDescription
+
+let projectName = "Mirai"
+
+let packages: [Package] = [
+ .package(path: "../../bindings/swift"),
+ .package(url: "https://github.com/Rspoon3/SFSymbols", .exact("2.6.1")),
+ .package(url: "https://github.com/firebase/firebase-ios-sdk", .exact("11.15.0")),
+]
+
+let settings: Settings = .settings(
+ base: [
+ "ARCHS": "arm64",
+ "ONLY_ACTIVE_ARCH": "YES",
+ "PRODUCT_BUNDLE_IDENTIFIER": "com.mirai.tech.playground",
+ "PRODUCT_NAME": "Mirai",
+ "CODE_SIGN_STYLE": "Automatic",
+ "DEVELOPMENT_TEAM": "C39GZ239GY",
+ "TARGETED_DEVICE_FAMILY": "1,2",
+ "SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD": "NO",
+ "MARKETING_VERSION": "2.0.0",
+ "CURRENT_PROJECT_VERSION": "1",
+ ],
+ configurations: [
+ .debug(
+ name: "Debug",
+ settings: [
+ "DEBUG_INFORMATION_FORMAT": "dwarf-with-dsym",
+ "SWIFT_COMPILATION_MODE": "incremental",
+ "GCC_OPTIMIZATION_LEVEL": "0",
+ ]),
+ .release(
+ name: "Release",
+ settings: [
+ "DEBUG_INFORMATION_FORMAT": "dwarf-with-dsym",
+ "SWIFT_COMPILATION_MODE": "wholemodule",
+ "GCC_OPTIMIZATION_LEVEL": "s",
+ ]),
+ ]
+)
+
+let crashlyticsScript = TargetScript.post(
+ script: """
+ # Upload dSYM files to Crashlytics for crash symbolication
+ SCRIPT="${BUILD_DIR%/Build/*}/SourcePackages/checkouts/firebase-ios-sdk/Crashlytics/run"
+
+ # Only run for Release builds or if explicitly requested
+ if [ "$CONFIGURATION" = "Release" ] || [ "${UPLOAD_SYMBOLS_TO_CRASHLYTICS:-NO}" = "YES" ]; then
+ if [ -f "$SCRIPT" ]; then
+ echo "Uploading dSYM to Crashlytics..."
+ "$SCRIPT" || echo "Warning: Crashlytics upload script failed"
+ else
+ echo "Crashlytics run script not found at: $SCRIPT"
+ fi
+ else
+ echo "Skipping Crashlytics dSYM upload for $CONFIGURATION build"
+ fi
+ """,
+ name: "Crashlytics dSYM Upload",
+ inputPaths: [
+ "$(DWARF_DSYM_FOLDER_PATH)/$(DWARF_DSYM_FILE_NAME)/Contents/Resources/DWARF/$(TARGET_NAME)",
+ "$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)",
+ ],
+ basedOnDependencyAnalysis: false
+)
+
+let appTarget: Target = .target(
+ name: projectName,
+ destinations: [.iPhone, .iPad, .mac],
+ product: .app,
+ bundleId: "com.mirai.tech.playground",
+ deploymentTargets: .multiplatform(iOS: "26.0", macOS: "26.0"),
+ infoPlist: .extendingDefault(with: [
+ "CFBundleShortVersionString": "$(MARKETING_VERSION)",
+ "CFBundleVersion": "$(CURRENT_PROJECT_VERSION)",
+ "ITSAppUsesNonExemptEncryption": false,
+ "LSApplicationCategoryType": "public.app-category.utilities",
+ "LSRequiresIPhoneOS": true,
+ "NSSupportsLiveActivities": true,
+ "UIApplicationSupportsIndirectInputEvents": true,
+ "UILaunchStoryboardName": "LaunchScreen",
+ "UIRequiresFullScreen": true,
+ "UIRequiredDeviceCapabilities": ["arm64"],
+ "UISupportedInterfaceOrientations": [
+ "UIInterfaceOrientationPortrait"
+ ],
+ ]),
+ sources: ["Sources/**"],
+ resources: [.glob(pattern: "Resources/**", excluding: ["Resources/Playground.entitlements"])],
+ scripts: [crashlyticsScript],
+ dependencies: [
+ .package(product: "Uzu"),
+ .package(product: "SFSymbols"),
+ .package(product: "FirebaseCrashlytics"),
+ .package(product: "FirebaseAnalytics"),
+ .sdk(name: "Metal", type: .framework),
+ ],
+ settings: .settings(base: [
+ "CODE_SIGN_ENTITLEMENTS": "Resources/Playground.entitlements",
+ "DERIVED_SOURCES_DIR": "$(SRCROOT)/Generated",
+ // Generate debug symbols for both the stub and the debug dylib
+ "COPY_PHASE_STRIP": "NO",
+ "STRIP_INSTALLED_PRODUCT": "NO",
+ ])
+)
+
+let appScheme: Scheme = .scheme(
+ name: projectName,
+ buildAction: .buildAction(
+ targets: [.init(stringLiteral: projectName)],
+ preActions: [
+ .executionAction(
+ title: "Update Uzu Package",
+ scriptText:
+ "/bin/bash \"$PROJECT_DIR/../../scripts/prepare_bindings.sh\" swift",
+ target: .init(stringLiteral: projectName)
+ )
+ ]
+ ),
+ runAction: .runAction(configuration: .release),
+ archiveAction: .archiveAction(configuration: .release),
+ profileAction: .profileAction(configuration: .release),
+ analyzeAction: .analyzeAction(configuration: .debug)
+)
+
+let project = Project(
+ name: projectName,
+ organizationName: "Mirai",
+ packages: packages,
+ settings: settings,
+ targets: [appTarget],
+ schemes: [appScheme],
+ resourceSynthesizers: [
+ .assets(),
+ .plists(),
+ .fonts(),
+ .strings(),
+ .files(extensions: ["json", "txt", "md"]),
+ ]
+)
diff --git a/apps/playground/README.md b/apps/playground/README.md
new file mode 100644
index 000000000..0fa3eb0f5
--- /dev/null
+++ b/apps/playground/README.md
@@ -0,0 +1,8 @@
+# Mirai Playground
+
+To generate an Xcode project, run:
+
+```bash
+brew install tuist
+tuist generate
+```
\ No newline at end of file
diff --git a/apps/playground/Resources/Assets.xcassets/AboutUsPodcast.dataset/Contents.json b/apps/playground/Resources/Assets.xcassets/AboutUsPodcast.dataset/Contents.json
new file mode 100644
index 000000000..f759d66fb
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/AboutUsPodcast.dataset/Contents.json
@@ -0,0 +1,13 @@
+{
+ "data" : [
+ {
+ "filename" : "about_us.mp3",
+ "idiom" : "universal",
+ "universal-type-identifier" : "public.mp3"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/apps/playground/Resources/Assets.xcassets/AboutUsPodcast.dataset/about_us.mp3 b/apps/playground/Resources/Assets.xcassets/AboutUsPodcast.dataset/about_us.mp3
new file mode 100644
index 000000000..2a3fba1b4
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AboutUsPodcast.dataset/about_us.mp3 differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/1024-mac.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/1024-mac.png
new file mode 100644
index 000000000..3173a39f2
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/1024-mac.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/128-mac.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/128-mac.png
new file mode 100644
index 000000000..6f8fb6d65
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/128-mac.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/16-mac.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/16-mac.png
new file mode 100644
index 000000000..1401fa896
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/16-mac.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/256-mac 1.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/256-mac 1.png
new file mode 100644
index 000000000..c54b0f3a0
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/256-mac 1.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/256-mac.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/256-mac.png
new file mode 100644
index 000000000..c54b0f3a0
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/256-mac.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/32-mac 1.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/32-mac 1.png
new file mode 100644
index 000000000..2becbb901
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/32-mac 1.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/32-mac.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/32-mac.png
new file mode 100644
index 000000000..2becbb901
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/32-mac.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/512-mac 1.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/512-mac 1.png
new file mode 100644
index 000000000..4f491c48d
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/512-mac 1.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/512-mac.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/512-mac.png
new file mode 100644
index 000000000..4f491c48d
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/512-mac.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/64-mac.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/64-mac.png
new file mode 100644
index 000000000..2088d2728
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/64-mac.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon 1.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon 1.png
new file mode 100644
index 000000000..2b56533ad
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon 1.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon 2.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon 2.png
new file mode 100644
index 000000000..2b56533ad
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon 2.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon.png b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon.png
new file mode 100644
index 000000000..2b56533ad
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/AppIcon.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json
new file mode 100644
index 000000000..c209265ba
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json
@@ -0,0 +1,98 @@
+{
+ "images" : [
+ {
+ "filename" : "AppIcon.png",
+ "idiom" : "universal",
+ "platform" : "ios",
+ "size" : "1024x1024"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "filename" : "AppIcon 1.png",
+ "idiom" : "universal",
+ "platform" : "ios",
+ "size" : "1024x1024"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "tinted"
+ }
+ ],
+ "filename" : "AppIcon 2.png",
+ "idiom" : "universal",
+ "platform" : "ios",
+ "size" : "1024x1024"
+ },
+ {
+ "filename" : "16-mac.png",
+ "idiom" : "mac",
+ "scale" : "1x",
+ "size" : "16x16"
+ },
+ {
+ "filename" : "32-mac.png",
+ "idiom" : "mac",
+ "scale" : "2x",
+ "size" : "16x16"
+ },
+ {
+ "filename" : "32-mac 1.png",
+ "idiom" : "mac",
+ "scale" : "1x",
+ "size" : "32x32"
+ },
+ {
+ "filename" : "64-mac.png",
+ "idiom" : "mac",
+ "scale" : "2x",
+ "size" : "32x32"
+ },
+ {
+ "filename" : "128-mac.png",
+ "idiom" : "mac",
+ "scale" : "1x",
+ "size" : "128x128"
+ },
+ {
+ "filename" : "256-mac.png",
+ "idiom" : "mac",
+ "scale" : "2x",
+ "size" : "128x128"
+ },
+ {
+ "filename" : "256-mac 1.png",
+ "idiom" : "mac",
+ "scale" : "1x",
+ "size" : "256x256"
+ },
+ {
+ "filename" : "512-mac.png",
+ "idiom" : "mac",
+ "scale" : "2x",
+ "size" : "256x256"
+ },
+ {
+ "filename" : "512-mac 1.png",
+ "idiom" : "mac",
+ "scale" : "1x",
+ "size" : "512x512"
+ },
+ {
+ "filename" : "1024-mac.png",
+ "idiom" : "mac",
+ "scale" : "2x",
+ "size" : "512x512"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/apps/playground/Resources/Assets.xcassets/Colors/AccentColor.colorset/Contents.json b/apps/playground/Resources/Assets.xcassets/Colors/AccentColor.colorset/Contents.json
new file mode 100644
index 000000000..d2e3c422e
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Colors/AccentColor.colorset/Contents.json
@@ -0,0 +1,44 @@
+{
+ "colors" : [
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "light"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0x00",
+ "green" : "0x00",
+ "blue" : "0x00",
+ "alpha" : "1.000"
+ }
+ }
+ },
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0xFF",
+ "green" : "0xFF",
+ "blue" : "0xFF",
+ "alpha" : "1.000"
+ }
+ }
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/apps/playground/Resources/Assets.xcassets/Colors/Background.colorset/Contents.json b/apps/playground/Resources/Assets.xcassets/Colors/Background.colorset/Contents.json
new file mode 100644
index 000000000..737e91097
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Colors/Background.colorset/Contents.json
@@ -0,0 +1,56 @@
+{
+ "colors" : [
+ {
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "alpha" : "1.000",
+ "blue" : "1.000",
+ "green" : "1.000",
+ "red" : "1.000"
+ }
+ },
+ "idiom" : "universal"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "light"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "alpha" : "1.000",
+ "blue" : "1.000",
+ "green" : "1.000",
+ "red" : "1.000"
+ }
+ },
+ "idiom" : "universal"
+ },
+ {
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "alpha" : "1.000",
+ "blue" : "0.000",
+ "green" : "0.000",
+ "red" : "0.000"
+ }
+ },
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/apps/playground/Resources/Assets.xcassets/Colors/Card.colorset/Contents.json b/apps/playground/Resources/Assets.xcassets/Colors/Card.colorset/Contents.json
new file mode 100644
index 000000000..9c72804d6
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Colors/Card.colorset/Contents.json
@@ -0,0 +1,44 @@
+{
+ "colors" : [
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "light"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0xF4",
+ "green" : "0xF5",
+ "blue" : "0xF5",
+ "alpha" : "1.000"
+ }
+ }
+ },
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0x1C",
+ "green" : "0x1C",
+ "blue" : "0x1E",
+ "alpha" : "1.000"
+ }
+ }
+ }
+ ],
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+}
\ No newline at end of file
diff --git a/apps/playground/Resources/Assets.xcassets/Colors/CardBorder.colorset/Contents.json b/apps/playground/Resources/Assets.xcassets/Colors/CardBorder.colorset/Contents.json
new file mode 100644
index 000000000..a34a2198f
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Colors/CardBorder.colorset/Contents.json
@@ -0,0 +1,44 @@
+{
+ "colors" : [
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "light"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0xE5",
+ "green" : "0xE5",
+ "blue" : "0xE5",
+ "alpha" : "1.000"
+ }
+ }
+ },
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0x38",
+ "green" : "0x38",
+ "blue" : "0x3A",
+ "alpha" : "1.000"
+ }
+ }
+ }
+ ],
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+}
\ No newline at end of file
diff --git a/apps/playground/Resources/Assets.xcassets/Colors/Contents.json b/apps/playground/Resources/Assets.xcassets/Colors/Contents.json
new file mode 100644
index 000000000..73c00596a
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Colors/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/apps/playground/Resources/Assets.xcassets/Colors/Contrast.colorset/Contents.json b/apps/playground/Resources/Assets.xcassets/Colors/Contrast.colorset/Contents.json
new file mode 100644
index 000000000..8d2245275
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Colors/Contrast.colorset/Contents.json
@@ -0,0 +1,44 @@
+{
+ "colors" : [
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "light"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0xFF",
+ "green" : "0xFF",
+ "blue" : "0xFF",
+ "alpha" : "1.000"
+ }
+ }
+ },
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0x00",
+ "green" : "0x00",
+ "blue" : "0x00",
+ "alpha" : "1.000"
+ }
+ }
+ }
+ ],
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+}
\ No newline at end of file
diff --git a/apps/playground/Resources/Assets.xcassets/Colors/Primary.colorset/Contents.json b/apps/playground/Resources/Assets.xcassets/Colors/Primary.colorset/Contents.json
new file mode 100644
index 000000000..1f73a192b
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Colors/Primary.colorset/Contents.json
@@ -0,0 +1,44 @@
+{
+ "colors" : [
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "light"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0x00",
+ "green" : "0x00",
+ "blue" : "0x00",
+ "alpha" : "1.000"
+ }
+ }
+ },
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0xFF",
+ "green" : "0xFF",
+ "blue" : "0xFF",
+ "alpha" : "1.000"
+ }
+ }
+ }
+ ],
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+}
\ No newline at end of file
diff --git a/apps/playground/Resources/Assets.xcassets/Colors/Secondary.colorset/Contents.json b/apps/playground/Resources/Assets.xcassets/Colors/Secondary.colorset/Contents.json
new file mode 100644
index 000000000..1d4f0d980
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Colors/Secondary.colorset/Contents.json
@@ -0,0 +1,44 @@
+{
+ "colors" : [
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "light"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0x3C",
+ "green" : "0x3C",
+ "blue" : "0x43",
+ "alpha" : "0.600"
+ }
+ }
+ },
+ {
+ "idiom" : "universal",
+ "appearances" : [
+ {
+ "appearance" : "luminosity",
+ "value" : "dark"
+ }
+ ],
+ "color" : {
+ "color-space" : "srgb",
+ "components" : {
+ "red" : "0xEB",
+ "green" : "0xEB",
+ "blue" : "0xF5",
+ "alpha" : "0.600"
+ }
+ }
+ }
+ ],
+ "info" : {
+ "version" : 1,
+ "author" : "xcode"
+ }
+}
\ No newline at end of file
diff --git a/apps/playground/Resources/Assets.xcassets/Contents.json b/apps/playground/Resources/Assets.xcassets/Contents.json
new file mode 100644
index 000000000..7f73912a4
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Contents.json
@@ -0,0 +1,9 @@
+{
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "compression-type" : "automatic"
+ }
+}
diff --git a/apps/playground/Resources/Assets.xcassets/Icons/Contents.json b/apps/playground/Resources/Assets.xcassets/Icons/Contents.json
new file mode 100644
index 000000000..73c00596a
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Icons/Contents.json
@@ -0,0 +1,6 @@
+{
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ }
+}
diff --git a/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/Contents.json b/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/Contents.json
new file mode 100644
index 000000000..fcaf90074
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/Contents.json
@@ -0,0 +1,26 @@
+{
+ "images" : [
+ {
+ "filename" : "arrow_up.png",
+ "idiom" : "universal",
+ "scale" : "1x"
+ },
+ {
+ "filename" : "[email protected]",
+ "idiom" : "universal",
+ "scale" : "2x"
+ },
+ {
+ "filename" : "[email protected]",
+ "idiom" : "universal",
+ "scale" : "3x"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/arrow_up.png b/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/arrow_up.png
new file mode 100644
index 000000000..b1ebbede8
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/arrow_up.png differ
diff --git a/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/[email protected] b/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/[email protected]
new file mode 100644
index 000000000..632f1030e
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/[email protected] differ
diff --git a/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/[email protected] b/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/[email protected]
new file mode 100644
index 000000000..d9cf08501
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/Icons/arrow_up.imageset/[email protected] differ
diff --git a/apps/playground/Resources/Assets.xcassets/Icons/logo.imageset/Contents.json b/apps/playground/Resources/Assets.xcassets/Icons/logo.imageset/Contents.json
new file mode 100644
index 000000000..e7b6ba739
--- /dev/null
+++ b/apps/playground/Resources/Assets.xcassets/Icons/logo.imageset/Contents.json
@@ -0,0 +1,15 @@
+{
+ "images" : [
+ {
+ "filename" : "mirai_logo.pdf",
+ "idiom" : "universal"
+ }
+ ],
+ "info" : {
+ "author" : "xcode",
+ "version" : 1
+ },
+ "properties" : {
+ "template-rendering-intent" : "template"
+ }
+}
diff --git a/apps/playground/Resources/Assets.xcassets/Icons/logo.imageset/logo.pdf b/apps/playground/Resources/Assets.xcassets/Icons/logo.imageset/logo.pdf
new file mode 100644
index 000000000..b00f02ee5
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/Icons/logo.imageset/logo.pdf differ
diff --git a/apps/playground/Resources/Assets.xcassets/Icons/logo.imageset/mirai_logo.pdf b/apps/playground/Resources/Assets.xcassets/Icons/logo.imageset/mirai_logo.pdf
new file mode 100644
index 000000000..b00f02ee5
Binary files /dev/null and b/apps/playground/Resources/Assets.xcassets/Icons/logo.imageset/mirai_logo.pdf differ
diff --git a/apps/playground/Resources/GoogleService-Info.plist b/apps/playground/Resources/GoogleService-Info.plist
new file mode 100644
index 000000000..f62a5deef
--- /dev/null
+++ b/apps/playground/Resources/GoogleService-Info.plist
@@ -0,0 +1,30 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>API_KEY</key>
+ <string>AIzaSyD9HZkvZqxyYvTkOpWf38Tf6YBkhKuEK-Q</string>
+ <key>GCM_SENDER_ID</key>
+ <string>630367726257</string>
+ <key>PLIST_VERSION</key>
+ <string>1</string>
+ <key>BUNDLE_ID</key>
+ <string>com.mirai.tech.playground</string>
+ <key>PROJECT_ID</key>
+ <string>playground-mirai</string>
+ <key>STORAGE_BUCKET</key>
+ <string>playground-mirai.firebasestorage.app</string>
+ <key>IS_ADS_ENABLED</key>
+ <false></false>
+ <key>IS_ANALYTICS_ENABLED</key>
+ <false></false>
+ <key>IS_APPINVITE_ENABLED</key>
+ <true></true>
+ <key>IS_GCM_ENABLED</key>
+ <true></true>
+ <key>IS_SIGNIN_ENABLED</key>
+ <true></true>
+ <key>GOOGLE_APP_ID</key>
+ <string>1:630367726257:ios:c7ab001cecac547e655090</string>
+</dict>
+</plist>
\ No newline at end of file
diff --git a/apps/playground/Resources/Playground.entitlements b/apps/playground/Resources/Playground.entitlements
new file mode 100644
index 000000000..29703bf54
--- /dev/null
+++ b/apps/playground/Resources/Playground.entitlements
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <key>com.apple.developer.kernel.increased-memory-limit</key>
+ <true/>
+ <key>com.apple.security.app-sandbox</key>
+ <true/>
+ <key>com.apple.security.network.client</key>
+ <true/>
+</dict>
+</plist>
diff --git a/apps/playground/Sources/AppDelegate.swift b/apps/playground/Sources/AppDelegate.swift
new file mode 100644
index 000000000..e941233bb
--- /dev/null
+++ b/apps/playground/Sources/AppDelegate.swift
@@ -0,0 +1,41 @@
+import Foundation
+import FirebaseCore
+import FirebaseCrashlytics
+
+#if os(iOS)
+import UIKit
+#elseif os(macOS)
+import AppKit
+#endif
+
+private func configureCrashlyticsOptions() {
+ #if os(macOS)
+ UserDefaults.standard.register(defaults: ["NSApplicationCrashOnExceptions": true])
+ #endif
+
+ Crashlytics.crashlytics().setCrashlyticsCollectionEnabled(true)
+
+ #if DEBUG
+ Crashlytics.crashlytics().setUserID("debug-user")
+ #endif
+}
+
+#if os(iOS)
+final class AppDelegate: UIResponder, UIApplicationDelegate {
+ func application(
+ _ application: UIApplication,
+ didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
+ ) -> Bool {
+ configureCrashlyticsOptions()
+ return true
+ }
+}
+#elseif os(macOS)
+final class AppDelegate: NSObject, NSApplicationDelegate {
+ func applicationDidFinishLaunching(_ notification: Notification) {
+ configureCrashlyticsOptions()
+ }
+}
+#endif
+
+
diff --git a/apps/playground/Sources/AudioController.swift b/apps/playground/Sources/AudioController.swift
new file mode 100644
index 000000000..8caee5d25
--- /dev/null
+++ b/apps/playground/Sources/AudioController.swift
@@ -0,0 +1,44 @@
+import AVFoundation
+import Foundation
+import Observation
+
+@Observable
+final class AudioController {
+
+ // Internal LoopPlayer instance, lazily created when an asset is set.
+ private var _player: LoopPlayer?
+
+ /// Read-only access to the underlying LoopPlayer (may be nil if no asset set).
+ var player: LoopPlayer? { _player }
+
+ var isPlaying: Bool {
+ _player?.isPlaying ?? false
+ }
+
+ /// Provide / update the audio asset to play in a loop.
+ func setAsset(_ asset: AVURLAsset?) {
+ if _player == nil {
+ _player = LoopPlayer()
+ }
+ _player?.update(asset: asset)
+ }
+
+ var url: URL? {
+ _player?.url
+ }
+
+ /// Start playback (no-op if already playing or no player set).
+ func play() {
+ _player?.play()
+ }
+
+ /// Pause playback (no-op if already paused or no player set).
+ func pause() {
+ _player?.pause()
+ }
+
+ /// Toggle between playing and paused states.
+ func toggle() {
+ isPlaying ? pause() : play()
+ }
+}
diff --git a/apps/playground/Sources/Extensions/AVURLAsset+Extensions.swift b/apps/playground/Sources/Extensions/AVURLAsset+Extensions.swift
new file mode 100644
index 000000000..ca957d826
--- /dev/null
+++ b/apps/playground/Sources/Extensions/AVURLAsset+Extensions.swift
@@ -0,0 +1,64 @@
+import AVFoundation
+import SwiftUI
+
+extension NSDataAsset: @retroactive AVAssetResourceLoaderDelegate {
+ @objc
+ public func resourceLoader(
+ _ resourceLoader: AVAssetResourceLoader,
+ shouldWaitForLoadingOfRequestedResource loadingRequest: AVAssetResourceLoadingRequest
+ ) -> Bool {
+ if let infoRequest = loadingRequest.contentInformationRequest {
+ infoRequest.contentType = typeIdentifier
+ infoRequest.contentLength = Int64(self.data.count)
+ infoRequest.isByteRangeAccessSupported = true
+ }
+
+ if let dataRequest = loadingRequest.dataRequest {
+ let subdataRange =
+ Int(dataRequest.requestedOffset)..<Int(dataRequest.requestedOffset)
+ + dataRequest.requestedLength
+ dataRequest.respond(with: self.data.subdata(in: subdataRange))
+ loadingRequest.finishLoading()
+ return true
+ }
+ return false
+ }
+
+ var url: URL? {
+ guard let name = self.name.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed),
+ let url = URL(string: "NSDataAsset://\(name))")
+ else { return nil }
+
+ return url
+ }
+}
+
+extension AVURLAsset {
+ enum Error: Swift.Error {
+ case loadingAssetFailed
+
+ var localizedDescription: String {
+ switch self {
+ case .loadingAssetFailed: return "Failed to load asset."
+ }
+ }
+
+ var recoverySuggestion: String? {
+ switch self {
+ case .loadingAssetFailed: return "Try using a different asset."
+ }
+ }
+ }
+
+ public convenience init?(_ dataAsset: NSDataAsset) {
+ guard let url = dataAsset.url
+ else { return nil }
+
+ self.init(url: url)
+ self.resourceLoader.setDelegate(dataAsset, queue: .main)
+ // Retain the weak delegate for the lifetime of AVURLAsset
+ objc_setAssociatedObject(
+ self, "AVURLAsset+NSDataAsset", dataAsset, .OBJC_ASSOCIATION_RETAIN
+ )
+ }
+}
diff --git a/apps/playground/Sources/Extensions/Font+Styles.swift b/apps/playground/Sources/Extensions/Font+Styles.swift
new file mode 100644
index 000000000..2e095e9ed
--- /dev/null
+++ b/apps/playground/Sources/Extensions/Font+Styles.swift
@@ -0,0 +1,43 @@
+import SwiftUI
+
+extension Font {
+ // MARK: - Monospaced
+
+ /// Body text, monospaced 16 pt, regular weight
+ static let monoBody16 = Font.system(size: 16, design: .monospaced)
+ /// Body text, monospaced 16 pt, semibold weight
+ static let monoBody16Semibold = Font.system(size: 16, weight: .semibold, design: .monospaced)
+
+ /// Caption text, monospaced 12 pt, regular weight
+ static let monoCaption12 = Font.system(size: 12, design: .monospaced)
+ /// Caption text, monospaced 12 pt, semibold weight
+ static let monoCaption12Semibold = Font.system(size: 12, weight: .semibold, design: .monospaced)
+
+ /// Heading text, monospaced 14 pt, bold weight
+ static let monoHeading14Bold = Font.system(size: 14, weight: .bold, design: .monospaced)
+ /// Heading text, monospaced 14 pt, medium weight
+ static let monoHeading14Medium = Font.system(size: 14, weight: .medium, design: .monospaced)
+ /// Heading text, monospaced 14 pt, semibold weight
+ static let monoHeading14Semibold = Font.system(size: 14, weight: .semibold, design: .monospaced)
+ /// Heading text, monospaced 14 pt, regular weight
+ static let monoHeading14 = Font.system(size: 14, weight: .regular, design: .monospaced)
+
+ // MARK: - Proportional (default) design
+
+ /// Body text, proportional 16 pt, semibold weight
+ static let body16Semibold = Font.system(size: 16, weight: .semibold)
+ /// Title text, proportional 20 pt, regular weight
+ static let title20 = Font.system(size: 20, weight: .regular)
+ /// Large number/title, proportional 24 pt, light weight
+ static let title24Light = Font.system(size: 24, weight: .light)
+
+ /// Caption, proportional 12 pt
+ static let caption12 = Font.system(size: 12, weight: .regular)
+ /// Caption, proportional 12 pt, semibold weight
+ static let caption12Semibold = Font.system(size: 12, weight: .semibold)
+
+ // MARK: - Badges / small text
+
+ /// Badge text, monospaced 10 pt, semibold weight
+ static let monoBadge10Semibold = Font.system(size: 10, weight: .semibold, design: .monospaced)
+}
diff --git a/apps/playground/Sources/Extensions/ProcessInfo+Extensions.swift b/apps/playground/Sources/Extensions/ProcessInfo+Extensions.swift
new file mode 100644
index 000000000..12297a5c2
--- /dev/null
+++ b/apps/playground/Sources/Extensions/ProcessInfo+Extensions.swift
@@ -0,0 +1,7 @@
+import Foundation
+
+extension ProcessInfo {
+ var isRunningForPreviews: Bool {
+ environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
+ }
+}
diff --git a/apps/playground/Sources/LoopPlayer.swift b/apps/playground/Sources/LoopPlayer.swift
new file mode 100644
index 000000000..db4fa3ae2
--- /dev/null
+++ b/apps/playground/Sources/LoopPlayer.swift
@@ -0,0 +1,80 @@
+import AVFoundation
+import Foundation
+import Observation
+
+#if os(macOS)
+ import AppKit
+#endif
+
+@Observable
+final class LoopPlayer {
+
+ var isPlaying = false
+
+ private let player: AVPlayer = {
+ let p = AVPlayer()
+ p.actionAtItemEnd = .none
+ return p
+ }()
+
+ private var endObserver: Any?
+
+ var url: URL? {
+ if
+ let item = player.currentItem,
+ let asset = item.asset as? AVURLAsset
+ {
+ let url = asset.url
+ return url
+ }
+ return nil
+ }
+
+ init() {
+ #if os(iOS)
+ try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [])
+ try? AVAudioSession.sharedInstance().setActive(true)
+ #endif
+ endObserver = NotificationCenter.default.addObserver(
+ forName: .AVPlayerItemDidPlayToEndTime,
+ object: nil,
+ queue: .main
+ ) { [weak self] note in
+ guard let self,
+ let item = note.object as? AVPlayerItem,
+ item == self.player.currentItem
+ else { return }
+
+ item.seek(to: .zero) { [weak self] _ in
+ guard let self else { return }
+ if self.isPlaying { self.player.play() }
+ }
+ }
+ }
+
+ deinit {
+ if let endObserver {
+ NotificationCenter.default.removeObserver(endObserver)
+ }
+ }
+
+ func update(asset: AVURLAsset?) {
+ if let asset {
+ player.replaceCurrentItem(with: AVPlayerItem(asset: asset))
+ } else {
+ player.replaceCurrentItem(with: nil)
+ }
+ }
+
+ func play() {
+ guard !isPlaying else { return }
+ player.play()
+ isPlaying = true
+ }
+
+ func pause() {
+ guard isPlaying else { return }
+ player.pause()
+ isPlaying = false
+ }
+}
diff --git a/apps/playground/Sources/PlaygroundApp.swift b/apps/playground/Sources/PlaygroundApp.swift
new file mode 100644
index 000000000..48afab3db
--- /dev/null
+++ b/apps/playground/Sources/PlaygroundApp.swift
@@ -0,0 +1,64 @@
+import Observation
+import SwiftUI
+import Uzu
+import Firebase
+#if os(iOS)
+import UIKit
+#endif
+
+@main
+struct PlaygroundApp: App {
+ #if os(iOS)
+ @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
+ #elseif os(macOS)
+ @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
+ #endif
+
+ @StateObject private var engineWrapper: EngineObservableWrapper
+ @State private var router: Router
+ @State private var audioController: AudioController
+
+ init() {
+ _ = _firebaseInitialized
+
+ let engineWrapper = EngineObservableWrapper(config: .create())
+ _engineWrapper = StateObject(wrappedValue: engineWrapper)
+
+ self.router = Router()
+ self.audioController = AudioController()
+ }
+
+ var body: some Scene {
+ WindowGroup {
+ NavigationStack(path: $router.navPath) {
+ HomeView()
+ .navigationDestination(for: Router.Destination.self) { destination in
+ switch destination {
+ case let .modelSelection(next):
+ ModelListView(mode: .choose(next: next))
+ case let .chat(identifier):
+ ChatView(identifier: identifier)
+ case let .classification(identifier):
+ ClassificationView(identifier: identifier)
+ case let .summarization(identifier):
+ SummarizationView(identifier: identifier)
+ case let .textToSpeech(identifier: identifier):
+ TextToSpeechView(identifier: identifier)
+ case .about:
+ AboutView()
+ case .modelManagement:
+ ModelListView(mode: .manage)
+ }
+ }
+ }
+ .environmentObject(engineWrapper)
+ .environment(router)
+ .environment(audioController)
+ .tint(MiraiAsset.primary.swiftUIColor)
+ }
+ }
+}
+
+private let _firebaseInitialized: Void = {
+ FirebaseApp.configure()
+}()
diff --git a/apps/playground/Sources/Router.swift b/apps/playground/Sources/Router.swift
new file mode 100644
index 000000000..d9329fa3f
--- /dev/null
+++ b/apps/playground/Sources/Router.swift
@@ -0,0 +1,88 @@
+import Observation
+import SwiftUI
+import Uzu
+
+@MainActor
+@Observable
+final class Router {
+ enum ModelListDestination: Hashable {
+ case classification
+ case summarization
+ case chat
+ case textToSpeech
+ }
+
+ enum Destination: Hashable {
+ case modelSelection(next: ModelListDestination)
+ case chat(identifier: String)
+ case classification(identifier: String)
+ case summarization(identifier: String)
+ case textToSpeech(identifier: String)
+ case about
+ case modelManagement
+
+ static func == (lhs: Destination, rhs: Destination) -> Bool {
+ switch (lhs, rhs) {
+ case let (.modelSelection(lhsNext), .modelSelection(rhsNext)):
+ return lhsNext == rhsNext
+ case let (.chat(lhsId), .chat(rhsId)):
+ return lhsId == rhsId
+ case let (.classification(lhsId), .classification(rhsId)):
+ return lhsId == rhsId
+ case let (.summarization(lhsId), .summarization(rhsId)):
+ return lhsId == rhsId
+ case let (.textToSpeech(lhsId), .textToSpeech(rhsId)):
+ return lhsId == rhsId
+ case (.about, .about):
+ return true
+ case (.modelManagement, .modelManagement):
+ return true
+ default:
+ return false
+ }
+ }
+
+ func hash(into hasher: inout Hasher) {
+ switch self {
+ case let .modelSelection(next):
+ hasher.combine(0)
+ hasher.combine(next)
+ case let .chat(identifier):
+ hasher.combine(1)
+ hasher.combine(identifier)
+ case let .classification(identifier):
+ hasher.combine(2)
+ hasher.combine(identifier)
+ case let .summarization(identifier):
+ hasher.combine(3)
+ hasher.combine(identifier)
+ case let .textToSpeech(identifier):
+ hasher.combine(4)
+ hasher.combine(identifier)
+ case .about:
+ hasher.combine(5)
+ case .modelManagement:
+ hasher.combine(6)
+ }
+ }
+ }
+
+ var navPath: [Destination] = []
+
+ func navigate(to destination: Destination) {
+ navPath.append(destination)
+ }
+
+ func navigateBack(_ count: Int? = nil) {
+ guard !navPath.isEmpty else { return }
+ if let count {
+ navPath.removeLast(min(count, navPath.count))
+ } else {
+ navPath.removeLast()
+ }
+ }
+
+ func reset() {
+ navPath.removeAll()
+ }
+}
diff --git a/apps/playground/Sources/ViewModels/ChatModel.swift b/apps/playground/Sources/ViewModels/ChatModel.swift
new file mode 100644
index 000000000..d1559d6a0
--- /dev/null
+++ b/apps/playground/Sources/ViewModels/ChatModel.swift
@@ -0,0 +1,164 @@
+import Foundation
+import Observation
+import Uzu
+
+// MARK: - Supporting Types
+
+extension ChatModel {
+ enum ViewState {
+ case loading
+ case idle
+ case generating
+ case error(Swift.Error)
+ }
+}
+
+@Observable
+final class ChatModel {
+
+ // MARK: - Publicly observed properties
+ var viewState: ViewState = .idle
+ var messages: [Message] = []
+ var inputText: String = ""
+
+ // MARK: - Private
+ private let identifier: String
+ private var session: ChatSession?
+ private var loadingTask: Task<Void, Never>?
+ private var generationTask: Task<Void, Never>?
+
+ init(identifier: String) {
+ self.identifier = identifier
+ }
+
+ @MainActor
+ func isCloud(engineWrapper: EngineObservableWrapper) -> Bool {
+ guard let model = engineWrapper.models.first(where: { $0.identifier == identifier }) else {
+ return false
+ }
+ return model.isRemote()
+ }
+
+ // MARK: - Lifecycle
+
+ @MainActor
+ func loadSession(using engineWrapper: EngineObservableWrapper, turbo: Bool) {
+ guard
+ case .idle = viewState,
+ let engine = engineWrapper.engine,
+ let model = engineWrapper.models.first(where: { $0.identifier == identifier }) else {
+ return
+ }
+
+ if self.session != nil {
+ tearDown()
+ }
+
+ self.viewState = .loading
+
+ loadingTask?.cancel()
+ loadingTask = Task.detached { [weak self] in
+ guard let self else { return }
+ let session: ChatSession?
+ let newState: ViewState
+ do {
+ let config = turbo ? ChatConfig.create().withSpeculationPreset(speculationPreset: .generalChat) : ChatConfig.create()
+ session = try await engine.chat(model: model, config: config)
+ newState = .idle
+ } catch {
+ session = nil
+ newState = .error(error)
+ }
+ await MainActor.run { [weak self] in
+ guard let self else { return }
+ self.session = session
+ self.viewState = newState
+ self.loadingTask = nil
+ }
+ }
+ }
+
+ // MARK: - User intents
+ func sendMessage() {
+ guard case .idle = viewState,
+ let session,
+ !inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else { return }
+
+ let userInput = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
+ inputText = ""
+
+ messages.append(Message(role: .user, content: userInput))
+ let assistantMessage = Message(role: .assistant, content: "")
+ messages.append(assistantMessage)
+ viewState = .generating
+
+ generationTask?.cancel()
+ generationTask = Task.detached { [weak self, assistantId = assistantMessage.id] in
+ guard let self else { return }
+ let inputMessages: [ChatMessage] = self.messages.dropLast().map { msg in
+ let role: ChatRole = (msg.role == .user) ? .user : .assistant
+ return ChatMessage.forRole(role: role).withText(text: msg.content)
+ }
+
+ do {
+ try await session.reset()
+ let stream = await session.replyWithStream(input: inputMessages, config: .create().withTokenLimit(tokenLimit: 1024))
+ for try await update in stream.iterator() {
+ if Task.isCancelled {
+ stream.cancelToken().cancel()
+ break
+ }
+
+ switch update {
+ case .replies(let replies):
+ if let reply = replies.last {
+ Task { @MainActor [weak self] in
+ guard let self, let idx = self.messages.firstIndex(where: { $0.id == assistantId }) else {
+ return
+ }
+
+ self.messages[idx].reasoning = reply.message.reasoning()?.trimmingCharacters(in: .whitespacesAndNewlines)
+ self.messages[idx].content = (reply.message.text() ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ self.messages[idx].stats = MessageStats(stats: reply.stats)
+ }
+ }
+ case .error(let error):
+ stream.cancelToken().cancel()
+ throw error
+ }
+ }
+
+ Task { @MainActor [weak self] in
+ guard let self else {
+ return
+ }
+ self.viewState = .idle
+ self.generationTask?.cancel()
+ self.generationTask = nil
+ }
+ } catch {
+ Task { @MainActor [weak self] in
+ guard let self else { return }
+ self.viewState = .error(error)
+ self.generationTask?.cancel()
+ self.generationTask = nil
+ }
+ }
+ }
+ }
+
+ func stopGeneration() {
+ generationTask?.cancel()
+ generationTask = nil
+ viewState = .idle
+ }
+
+ func tearDown() {
+ loadingTask?.cancel()
+ loadingTask = nil
+ generationTask?.cancel()
+ generationTask = nil
+ session = nil
+ }
+}
diff --git a/apps/playground/Sources/ViewModels/ClassificationModel.swift b/apps/playground/Sources/ViewModels/ClassificationModel.swift
new file mode 100644
index 000000000..89e7f1646
--- /dev/null
+++ b/apps/playground/Sources/ViewModels/ClassificationModel.swift
@@ -0,0 +1,168 @@
+import Foundation
+import Observation
+import Uzu
+
+@Observable
+final class ClassificationModel {
+ // MARK: - Nested Types
+ enum ViewState {
+ case loading
+ case idle
+ case generating
+ case error(Swift.Error)
+ }
+
+ struct GenerationStats: Equatable {
+ let timeToFirstToken: Double
+ let tokensPerSecond: Double
+ let totalTime: Double
+
+ init(stats: ChatReplyStats) {
+ self.timeToFirstToken = stats.timeToFirstToken ?? 0.0
+ self.tokensPerSecond = stats.generateTokensPerSecond ?? 0.0
+ self.totalTime = stats.duration
+ }
+ }
+
+ // MARK: - Observable Properties
+ var viewState: ViewState = .idle
+ var inputText: String = ""
+ var resultText: String = ""
+ var stats: GenerationStats? = nil
+
+ // MARK: - Private
+ private let identifier: String
+ private let feature: Feature
+ private var session: ChatSession?
+ private var loadingTask: Task<Void, Never>?
+ private var generationTask: Task<Void, Never>?
+
+ init(identifier: String, feature: Feature) {
+ self.identifier = identifier
+ self.feature = feature
+ }
+
+ // MARK: - Public API
+
+ @MainActor
+ func loadSession(using engineWrapper: EngineObservableWrapper) {
+ guard
+ case .idle = viewState,
+ let engine = engineWrapper.engine,
+ let model = engineWrapper.models.first(where: { $0.identifier == identifier }) else {
+ return
+ }
+
+ if self.session != nil {
+ tearDown()
+ }
+
+ self.viewState = .loading
+ let feature = self.feature
+
+ loadingTask?.cancel()
+ loadingTask = Task.detached { [weak self] in
+ guard let self else { return }
+ let session: ChatSession?
+ let newState: ViewState
+ do {
+ let config = ChatConfig.create().withSpeculationPreset(speculationPreset: .classification(feature: feature))
+ session = try await engine.chat(model: model, config: config)
+ newState = .idle
+ } catch {
+ session = nil
+ newState = .error(error)
+ }
+ await MainActor.run { [weak self] in
+ guard let self else { return }
+ self.session = session
+ self.viewState = newState
+ self.loadingTask = nil
+ }
+ }
+ }
+
+ func classify() {
+ guard case .idle = viewState,
+ let session,
+ !inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
+ return
+ }
+
+ resultText = ""
+ stats = nil
+ viewState = .generating
+ let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
+ let values = feature.values.joined(separator: ", ")
+ let prompt =
+ "Text is: \"\(text)\". Choose \(feature.name) from the list: \(values). Answer with one word. Dont't add dot at the end."
+
+ generationTask?.cancel()
+ generationTask = Task.detached { [weak self] in
+ guard let self else { return }
+ do {
+ try await session.reset()
+ let stream = await session.replyWithStream(
+ input: [
+ .system().withReasoningEffort(reasoningEffort: .disabled),
+ .user().withText(text: prompt)
+ ],
+ config: .create().withSamplingMethod(samplingMethod: .greedy).withTokenLimit(tokenLimit: 32)
+ )
+ for try await update in stream.iterator() {
+ if Task.isCancelled {
+ stream.cancelToken().cancel()
+ break
+ }
+
+ switch update {
+ case .replies(let replies):
+ if let reply = replies.last {
+ Task { @MainActor [weak self] in
+ guard let self else {
+ return
+ }
+ self.resultText = reply.message.text() ?? ""
+ self.stats = .init(stats: reply.stats)
+ }
+ }
+ case .error(let error):
+ stream.cancelToken().cancel()
+ throw error
+ }
+ }
+
+ Task { @MainActor [weak self] in
+ guard let self else {
+ return
+ }
+ self.viewState = .idle
+ self.generationTask?.cancel()
+ self.generationTask = nil
+ }
+ } catch {
+ Task { @MainActor [weak self] in
+ guard let self else { return }
+ self.viewState = .error(error)
+ self.generationTask?.cancel()
+ self.generationTask = nil
+ }
+ }
+ }
+ }
+
+ func stop() {
+ generationTask?.cancel()
+ generationTask = nil
+ viewState = .idle
+ }
+
+ func tearDown() {
+ loadingTask?.cancel()
+ loadingTask = nil
+ generationTask?.cancel()
+ generationTask = nil
+ session = nil
+ viewState = .loading
+ }
+}
diff --git a/apps/playground/Sources/ViewModels/SummarizationModel.swift b/apps/playground/Sources/ViewModels/SummarizationModel.swift
new file mode 100644
index 000000000..54f2f8df4
--- /dev/null
+++ b/apps/playground/Sources/ViewModels/SummarizationModel.swift
@@ -0,0 +1,164 @@
+import Foundation
+import Observation
+import Uzu
+
+@Observable
+final class SummarizationModel {
+
+ // MARK: - Nested Types
+ enum ViewState {
+ case loading
+ case idle
+ case generating
+ case error(Swift.Error)
+ }
+
+ struct GenerationStats: Equatable {
+ let timeToFirstToken: Double
+ let tokensPerSecond: Double
+ let totalTime: Double
+
+ init(stats: ChatReplyStats) {
+ self.timeToFirstToken = stats.timeToFirstToken ?? 0.0
+ self.tokensPerSecond = stats.generateTokensPerSecond ?? 0.0
+ self.totalTime = stats.duration
+ }
+ }
+
+ // MARK: - Observable Properties
+ var viewState: ViewState = .idle
+ var inputText: String = ""
+ var summaryText: String = ""
+ var stats: GenerationStats? = nil
+
+ // MARK: - Private
+ private let identifier: String
+ private var session: ChatSession?
+ private var loadingTask: Task<Void, Never>?
+ private var generationTask: Task<Void, Never>?
+
+ init(identifier: String) {
+ self.identifier = identifier
+ }
+
+ // MARK: - Public API
+
+ @MainActor
+ func loadSession(using engineWrapper: EngineObservableWrapper) {
+ guard
+ case .idle = viewState,
+ let engine = engineWrapper.engine,
+ let model = engineWrapper.models.first(where: { $0.identifier == identifier }) else {
+ return
+ }
+
+ if self.session != nil {
+ tearDown()
+ }
+
+ self.viewState = .loading
+
+ loadingTask?.cancel()
+ loadingTask = Task.detached { [weak self] in
+ guard let self else { return }
+ let session: ChatSession?
+ let newState: ViewState
+ do {
+ let config = ChatConfig.create().withSpeculationPreset(speculationPreset: .summarization)
+ session = try await engine.chat(model: model, config: config)
+ newState = .idle
+ } catch {
+ session = nil
+ newState = .error(error)
+ }
+ await MainActor.run { [weak self] in
+ guard let self else { return }
+ self.session = session
+ self.viewState = newState
+ self.loadingTask = nil
+ }
+ }
+ }
+
+ func summarise() {
+ guard case .idle = viewState,
+ let session,
+ !inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
+ return
+ }
+
+ summaryText = ""
+ stats = nil
+ viewState = .generating
+ let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
+ let prompt = "Text is: \"\(text)\". Write only summary itself."
+
+ generationTask?.cancel()
+ generationTask = Task.detached { [weak self] in
+ guard let self else { return }
+ do {
+ try await session.reset()
+ let stream = await session.replyWithStream(
+ input: [
+ .system().withReasoningEffort(reasoningEffort: .disabled),
+ .user().withText(text: prompt)
+ ],
+ config: .create().withSamplingMethod(samplingMethod: .greedy).withTokenLimit(tokenLimit: 1024)
+ )
+ for try await update in stream.iterator() {
+ if Task.isCancelled {
+ stream.cancelToken().cancel()
+ break
+ }
+
+ switch update {
+ case .replies(let replies):
+ if let reply = replies.last {
+ Task { @MainActor [weak self] in
+ guard let self else {
+ return
+ }
+ self.summaryText = reply.message.text() ?? ""
+ self.stats = .init(stats: reply.stats)
+ }
+ }
+ case .error(let error):
+ stream.cancelToken().cancel()
+ throw error
+ }
+ }
+
+ Task { @MainActor [weak self] in
+ guard let self else {
+ return
+ }
+ self.viewState = .idle
+ self.generationTask?.cancel()
+ self.generationTask = nil
+ }
+ } catch {
+ Task { @MainActor [weak self] in
+ guard let self else { return }
+ self.viewState = .error(error)
+ self.generationTask?.cancel()
+ self.generationTask = nil
+ }
+ }
+ }
+ }
+
+ func stop() {
+ generationTask?.cancel()
+ generationTask = nil
+ viewState = .idle
+ }
+
+ func tearDown() {
+ loadingTask?.cancel()
+ loadingTask = nil
+ generationTask?.cancel()
+ generationTask = nil
+ session = nil
+ viewState = .loading
+ }
+}
diff --git a/apps/playground/Sources/ViewModels/TextToSpeechModel.swift b/apps/playground/Sources/ViewModels/TextToSpeechModel.swift
new file mode 100644
index 000000000..5d9f8414a
--- /dev/null
+++ b/apps/playground/Sources/ViewModels/TextToSpeechModel.swift
@@ -0,0 +1,133 @@
+import Foundation
+import Observation
+import Uzu
+
+// MARK: - Supporting Types
+
+extension TextToSpeechModel {
+ enum ViewState {
+ case loading
+ case idle
+ case generating
+ case error(Swift.Error)
+ }
+}
+
+struct GenerationError: Swift.Error {
+ let message: String
+}
+
+@Observable
+final class TextToSpeechModel {
+
+ // MARK: - Publicly observed properties
+ var viewState: ViewState = .idle
+ var inputText: String = ""
+ var outputPath: URL?
+
+ // MARK: - Private
+ private let identifier: String
+ private var session: TextToSpeechSession?
+ private var loadingTask: Task<Void, Never>?
+ private var generationTask: Task<Void, Never>?
+
+ init(identifier: String) {
+ self.identifier = identifier
+ }
+
+ // MARK: - Lifecycle
+
+ @MainActor
+ func loadSession(using engineWrapper: EngineObservableWrapper) {
+ guard
+ case .idle = viewState,
+ let engine = engineWrapper.engine,
+ let model = engineWrapper.models.first(where: { $0.identifier == identifier }) else {
+ return
+ }
+
+ if self.session != nil {
+ tearDown()
+ }
+
+ self.viewState = .loading
+
+ loadingTask?.cancel()
+ loadingTask = Task.detached { [weak self] in
+ guard let self else { return }
+ let session: TextToSpeechSession?
+ let newState: ViewState
+ do {
+ session = try await engine.textToSpeech(model: model)
+ newState = .idle
+ } catch {
+ session = nil
+ newState = .error(error)
+ }
+ await MainActor.run { [weak self] in
+ guard let self else { return }
+ self.session = session
+ self.viewState = newState
+ self.loadingTask = nil
+ }
+ }
+ }
+
+ // MARK: - User intents
+ func generate() {
+ guard case .idle = viewState,
+ let session,
+ !inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ else { return }
+
+ let input = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
+ viewState = .generating
+ outputPath = nil
+
+ generationTask?.cancel()
+ generationTask = Task.detached { [weak self] in
+ guard let self else { return }
+
+ let resultPath = URL.documentsDirectory.appendingPathComponent("tts_output.wav")
+ var generationError: Swift.Error? = nil
+ do {
+ if FileManager.default.fileExists(atPath: resultPath.path) {
+ try FileManager.default.removeItem(at: resultPath)
+ }
+ let pcmBatch = try await session.synthesize(input: input)
+ try pcmBatch.saveAsWav(path: resultPath.path)
+ if !FileManager.default.fileExists(atPath: resultPath.path) {
+ generationError = GenerationError(message: "Generation failed")
+ }
+ } catch {
+ generationError = error
+ }
+
+ Task { @MainActor [weak self] in
+ guard let self else { return }
+ if let error = generationError {
+ self.viewState = .error(error)
+ } else {
+ self.viewState = .idle
+ self.outputPath = resultPath
+ }
+ self.generationTask = nil
+ }
+ }
+ }
+
+ func tearDown() {
+ loadingTask?.cancel()
+ loadingTask = nil
+ generationTask?.cancel()
+ generationTask = nil
+ session = nil
+ }
+
+ func stopGeneration() {
+ generationTask?.cancel()
+ generationTask = nil
+ viewState = .idle
+ outputPath = nil
+ }
+}
diff --git a/apps/playground/Sources/Views/AboutView.swift b/apps/playground/Sources/Views/AboutView.swift
new file mode 100644
index 000000000..af2e69832
--- /dev/null
+++ b/apps/playground/Sources/Views/AboutView.swift
@@ -0,0 +1,99 @@
+import SwiftUI
+import Uzu
+import FirebaseCrashlytics
+
+#if os(macOS)
+ import AppKit
+#endif
+
+struct AboutView: View {
+ func linkView(title: String, subtitle: String?) -> some View {
+ VStack(alignment: .leading, spacing: 4.0) {
+ Text(title)
+ .foregroundStyle(MiraiAsset.primary.swiftUIColor)
+ .font(.monoBody16)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ if let subtitle {
+ Text(subtitle)
+ .foregroundStyle(MiraiAsset.secondary.swiftUIColor)
+ .font(.monoBody16)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+ }
+ .padding(16.0)
+ .background(MiraiAsset.card.swiftUIColor)
+ .cornerRadius(16.0)
+ }
+
+ func linkButton(url: String, title: String, subtitle: String? = nil) -> some View {
+ Button(action: {
+ if let url = URL(string: url) {
+ #if os(iOS)
+ UIApplication.shared.open(url)
+ #else
+ NSWorkspace.shared.open(url)
+ #endif
+ }
+ }) {
+ linkView(title: title, subtitle: subtitle)
+ }
+ .buttonStyle(.plain)
+ }
+
+ var body: some View {
+ VStack(alignment: .center, spacing: 0.0) {
+ ScrollView {
+ VStack(alignment: .center, spacing: 16.0) {
+ linkButton(
+ url: "https://trymirai.com",
+ title: "Mirai",
+ subtitle:
+ "AI which run directly on your devices, bringing powerful capabilities closer to where decisions are made."
+ )
+ linkButton(
+ url: "https://saikollm.com",
+ title: "Saiko",
+ subtitle:
+ "A family of small AI models, highly optimized for on-device tasks. Zero cloud dependency, instant response times."
+ )
+ linkButton(
+ url: "https://trymirai.com/blog/deploying-llms-on-mobile",
+ title: "Introduction to Deploying LLMs on Mobile"
+ )
+ linkButton(
+ url: "https://trymirai.com/blog/how-to-understand-on-device-ai",
+ title: "How to Understand On-Device AI"
+ )
+ linkButton(
+ url: "https://trymirai.com/blog/iphone-hardware",
+ title: "iPhone Hardware",
+ subtitle: "How It Powers On-Device AI"
+ )
+ linkButton(
+ url: "https://trymirai.com/blog/brief-history-of-apple-ml-stack",
+ title: "Brief history of Apple ML Stack"
+ )
+
+ #if DEBUG
+ // Crashlytics test button (Debug only)
+ Button(action: {
+ Crashlytics.crashlytics().log("User triggered test crash")
+ Crashlytics.crashlytics().setCustomValue("test", forKey: "crash_source")
+ fatalError("Test crash triggered from About view")
+ }) {
+ linkView(title: "Test Crashlytics", subtitle: "⚠️ This will crash the app (Debug only)")
+ }
+ .buttonStyle(.plain)
+ #endif
+ }
+ }
+ .scrollIndicators(.hidden)
+ .safeAreaPadding(16.0)
+ }
+ .navigationTitle("About Us")
+ #if os(iOS)
+ .navigationBarTitleDisplayMode(.inline)
+ #endif
+ .toolbarRole(.editor)
+ }
+}
diff --git a/apps/playground/Sources/Views/ChatView.swift b/apps/playground/Sources/Views/ChatView.swift
new file mode 100644
index 000000000..d959a788b
--- /dev/null
+++ b/apps/playground/Sources/Views/ChatView.swift
@@ -0,0 +1,326 @@
+import Foundation
+import Observation
+import SFSymbols
+import SwiftUI
+import Uzu
+
+enum MessageRole {
+ case user
+ case assistant
+}
+
+struct MessageStats: Equatable {
+ let timeToFirstToken: Double
+ let tokensPerSecond: Double
+ let totalTime: Double
+
+ init(
+ timeToFirstToken: Double,
+ tokensPerSecond: Double,
+ totalTime: Double
+ ) {
+ self.timeToFirstToken = timeToFirstToken
+ self.tokensPerSecond = tokensPerSecond
+ self.totalTime = totalTime
+ }
+
+ init(stats: Uzu.ChatReplyStats) {
+ self.timeToFirstToken = stats.timeToFirstToken ?? 0.0
+ self.tokensPerSecond = stats.generateTokensPerSecond ?? 0.0
+ self.totalTime = stats.duration
+ }
+}
+
+struct Message: Identifiable, Equatable {
+ let id = UUID()
+ let role: MessageRole
+ var reasoning: String?
+ var content: String
+ var stats: MessageStats? = nil
+
+ static func == (lhs: Message, rhs: Message) -> Bool {
+ lhs.id == rhs.id && lhs.content == rhs.content && lhs.role == rhs.role
+ && lhs.stats == rhs.stats
+ }
+}
+
+struct ChatView: View {
+
+ // MARK: - Environment
+ @Environment(Router.self) var router
+ @EnvironmentObject private var engineWrapper: EngineObservableWrapper
+ @Environment(AudioController.self) private var audioController
+
+ // MARK: - State
+ @State private var viewModel: ChatModel
+ @FocusState private var inputFocused: Bool
+ @State private var turbo = false
+
+ // MARK: - Stored Properties
+ let identifier: String
+
+ init(identifier: String) {
+ self.identifier = identifier
+ _viewModel = State(initialValue: ChatModel(identifier: identifier))
+ }
+
+ fileprivate init(messages: [Message], identifier: String, viewState: ChatModel.ViewState) {
+ self.identifier = identifier
+ _viewModel = State(initialValue: ChatModel(identifier: identifier))
+ viewModel.messages = messages
+ viewModel.viewState = viewState
+ }
+
+ private var isInputDisabled: Bool {
+ switch viewModel.viewState {
+ case .loading, .generating, .error:
+ return true
+ case .idle:
+ return false
+ }
+ }
+
+ private var inputPlaceholder: String {
+ switch viewModel.viewState {
+ case .loading:
+ return "Loading..."
+ case .generating:
+ return "Generating..."
+ case .error(let error):
+ return "Error: \(error.localizedDescription)"
+ case .idle:
+ return "Message..."
+ }
+ }
+
+ private var isInputValid: Bool {
+ !viewModel.inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
+ private var turboEnabled: Bool {
+ switch(viewModel.viewState) {
+ case .idle:
+ return true
+ case .loading, .generating, .error(_):
+ return false
+ }
+ }
+
+ @ViewBuilder
+ private var turboView: some View {
+ HStack(alignment: .center) {
+ Spacer()
+ Button(action: {
+ turbo.toggle()
+ }) {
+ HStack(alignment: .center, spacing: 8.0) {
+ Text("Turbo")
+ .font(.monoHeading14)
+ .foregroundColor(MiraiAsset.primary.swiftUIColor)
+ Image(symbol: turbo ? .checkmarkCircleFill : .circle)
+ .font(.title24Light)
+ .foregroundColor(MiraiAsset.primary.swiftUIColor)
+ }
+ .opacity(turboEnabled ? 1.0 : 0.5)
+ }
+ }
+ .padding(EdgeInsets(top: 0.0, leading: 16.0, bottom: 0.0, trailing: 16.0))
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ ScrollViewReader { proxy in
+ ScrollView {
+ LazyVStack(spacing: 20) {
+ ForEach(viewModel.messages) { messageRow(message: $0) }
+ }
+ .padding()
+ }
+ .onChange(of: viewModel.messages) { _, _ in
+ if let last = viewModel.messages.last {
+ withAnimation {
+ proxy.scrollTo(last.id, anchor: .bottom)
+ }
+ }
+ }
+ }
+ Divider()
+ if !viewModel.isCloud(engineWrapper: engineWrapper) {
+ Spacer(minLength: 16.0)
+ turboView
+ .disabled(!turboEnabled)
+ }
+ inputView
+ .padding()
+ }
+ #if os(iOS)
+ .toolbar { MiraiToolbarModelName(identifier: identifier) }
+ #endif
+ .toolbarRole(.editor)
+ .onAppear {
+ viewModel.loadSession(using: engineWrapper, turbo: turbo)
+ }
+ .onChange(of: turbo) { _, _ in
+ viewModel.loadSession(using: engineWrapper, turbo: turbo)
+ }
+ .onDisappear {
+ viewModel.tearDown()
+ }
+ }
+
+ @ViewBuilder
+ private var sendMessageButton: some View {
+ if case .generating = viewModel.viewState {
+ Button(action: stopMessage) {
+ Image(systemName: "square.fill")
+ .font(.body16Semibold)
+ .foregroundStyle(.white)
+ .frame(width: 28, height: 28)
+ .background(Color.black)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ }
+ .buttonStyle(.plain)
+ } else {
+ Button(action: sendMessage) {
+ Image(symbol: .arrowUp)
+ .font(.body16Semibold)
+ .foregroundStyle(
+ isInputValid && !isInputDisabled
+ ? .white : MiraiAsset.secondary.swiftUIColor
+ )
+ .frame(width: 28, height: 28)
+ .background(
+ isInputValid && !isInputDisabled
+ ? .black : MiraiAsset.cardBorder.swiftUIColor
+ )
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ }
+ .disabled(!isInputValid || isInputDisabled)
+ .buttonStyle(.plain)
+ #if os(macOS)
+ .keyboardShortcut(.defaultAction)
+ #endif
+ }
+ }
+
+ @ViewBuilder
+ private var inputView: some View {
+ HStack(alignment: .center, spacing: 12) {
+ ZStack(alignment: .topLeading) {
+ SendTextView(text: $viewModel.inputText) {
+ if isInputValid && !isInputDisabled {
+ sendMessage()
+ }
+ }
+ .focused($inputFocused)
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .fixedSize(horizontal: false, vertical: true)
+ .disabled(isInputDisabled)
+
+ Text(inputPlaceholder)
+ .font(.monoBody16)
+ .foregroundStyle(MiraiAsset.secondary.swiftUIColor)
+ .opacity(viewModel.inputText.isEmpty ? 1.0 : 0.0)
+ .allowsHitTesting(false)
+ }
+ sendMessageButton
+ }
+ .padding(12)
+ .background(MiraiAsset.card.swiftUIColor)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ }
+
+ @ViewBuilder
+ private func messageRow(message: Message) -> some View {
+ if message.role == .user {
+ userMessageView(message: message)
+ } else {
+ assistantMessageView(message: message)
+ }
+ }
+
+ @ViewBuilder
+ private func userMessageView(message: Message) -> some View {
+ HStack {
+ Spacer(minLength: 64)
+ Text(LocalizedStringKey(message.content))
+ .font(.monoBody16)
+ .padding(.horizontal, 16)
+ .padding(.vertical, 12)
+ .background(MiraiAsset.card.swiftUIColor)
+ .foregroundStyle(.primary)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ .textSelection(.enabled)
+ }
+ }
+
+ @ViewBuilder
+ private func assistantMessageView(message: Message) -> some View {
+ HStack(alignment: .top) {
+ VStack(alignment: .leading, spacing: 4) {
+ if let reasoning = message.reasoning {
+ Text(LocalizedStringKey(reasoning))
+ .font(.monoCaption12)
+ .padding(.horizontal, 16)
+ .padding(.vertical, 12)
+ .background(MiraiAsset.card.swiftUIColor)
+ .foregroundStyle(.secondary)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ .textSelection(.enabled)
+ Spacer()
+ .frame(height: 8.0)
+ }
+ Text(LocalizedStringKey(message.content))
+ .font(.monoBody16)
+ .textSelection(.enabled)
+ if let stats = message.stats {
+ Rectangle()
+ .fill(MiraiAsset.cardBorder.swiftUIColor)
+ .frame(height: 1)
+ .padding(.vertical, 4)
+ VStack(alignment: .leading, spacing: 4) {
+ metricRow(
+ label: "Time to first token:",
+ value: String(format: "%.3f s", stats.timeToFirstToken)
+ )
+ if stats.tokensPerSecond > 0 {
+ metricRow(
+ label: "Tokens per second:",
+ value: String(format: "%.3f t/s", stats.tokensPerSecond)
+ )
+ }
+ metricRow(
+ label: "Total time:",
+ value: String(format: "%.3f s", stats.totalTime)
+ )
+ }
+ }
+ }
+ Spacer(minLength: 64)
+ }
+ }
+
+ private func stopMessage() {
+ viewModel.stopGeneration()
+ }
+
+ private func sendMessage() {
+ audioController.pause()
+ inputFocused = false
+ viewModel.sendMessage()
+ }
+
+ // MARK: - Metric row helper
+
+ @ViewBuilder
+ private func metricRow(label: String, value: String) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Text(label)
+ .font(.monoCaption12)
+ .foregroundStyle(MiraiAsset.secondary.swiftUIColor)
+ Text(value)
+ .font(.monoBody16)
+ }
+ }
+
+}
diff --git a/apps/playground/Sources/Views/ClassificationView.swift b/apps/playground/Sources/Views/ClassificationView.swift
new file mode 100644
index 000000000..0a3896808
--- /dev/null
+++ b/apps/playground/Sources/Views/ClassificationView.swift
@@ -0,0 +1,242 @@
+import Foundation
+import Observation
+import SFSymbols
+import SwiftUI
+import Uzu
+
+#if canImport(UIKit)
+ import UIKit
+#endif
+
+struct ClassificationView: View {
+
+ // MARK: - Type Definitions
+
+ // ViewState comes from ClassificationModel.ViewState
+
+ // MARK: - Environment
+
+ @Environment(Router.self) private var router
+ @EnvironmentObject private var engineWrapper: EngineObservableWrapper
+ @Environment(AudioController.self) private var audioController
+ @State private var viewModel: ClassificationModel
+
+ // MARK: - State
+
+ @FocusState private var inputFocused: Bool
+
+ // MARK: - Stored Properties
+
+ let identifier: String
+
+ static let textsToClassify = [
+ "Today's been awesome! Everything just feels right, and I can't stop smiling."
+ ]
+
+ static let sentiments = [
+ "Happy",
+ "Sad",
+ "Angry",
+ "Fearful",
+ "Surprised",
+ "Disgusted",
+ ]
+
+ private var feature: Feature {
+ Feature(name: "sentiment", values: Self.sentiments)
+ }
+
+ // MARK: - Body
+
+ var body: some View {
+ VStack(spacing: 0) {
+ ScrollViewReader { proxy in
+ ScrollView {
+ VStack(spacing: 20) {
+ input
+ if !viewModel.resultText.isEmpty {
+ result
+ }
+
+ Color.clear
+ .frame(height: 1)
+ .id("bottom")
+ }
+ .padding()
+ }
+ .onChange(of: viewModel.resultText) { _, _ in
+ withAnimation {
+ proxy.scrollTo("bottom", anchor: .bottom)
+ }
+ }
+ }
+ Divider()
+ bottomBar
+ .padding()
+ }
+ .background(MiraiAsset.background.swiftUIColor)
+ #if os(iOS)
+ .toolbar { MiraiToolbarModelName(identifier: identifier) }
+ #endif
+ .toolbarRole(.editor)
+ .onAppear {
+ viewModel.loadSession(using: engineWrapper)
+ }
+ .onDisappear {
+ viewModel.tearDown()
+ }
+ }
+
+ // MARK: - UI
+
+ private var input: some View {
+ ZStack(alignment: .topLeading) {
+ TextField("Enter text to classify…", text: $viewModel.inputText, axis: .vertical)
+ .textFieldStyle(.plain)
+ .focused($inputFocused)
+ .font(.monoBody16)
+ .disabled(isInputDisabled)
+ .lineLimit(10)
+ .padding(12)
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .background(MiraiAsset.card.swiftUIColor)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+
+ if viewModel.inputText.isEmpty {
+ Text("Enter text to classify…")
+ .font(.monoBody16)
+ .foregroundStyle(MiraiAsset.secondary.swiftUIColor)
+ .padding(.horizontal, 16)
+ .padding(.vertical, 12)
+ .allowsHitTesting(false)
+ }
+ }
+ }
+
+ private var result: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(LocalizedStringKey(viewModel.resultText))
+ .font(.monoBody16Semibold)
+ .textSelection(.enabled)
+
+ if let stats = viewModel.stats {
+ Rectangle()
+ .fill(MiraiAsset.cardBorder.swiftUIColor)
+ .frame(height: 1)
+ .padding(.vertical, 4)
+
+ VStack(alignment: .leading, spacing: 4) {
+ metricRow(
+ label: "Time to first token:",
+ value: String(format: "%.3f s", stats.timeToFirstToken)
+ )
+ if stats.tokensPerSecond > 0 {
+ metricRow(
+ label: "Tokens per second:",
+ value: String(format: "%.3f t/s", stats.tokensPerSecond)
+ )
+ }
+ metricRow(
+ label: "Total time:",
+ value: String(format: "%.3f s", stats.totalTime)
+ )
+ }
+ }
+ }
+ .padding(.leading, 16)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ private var bottomBar: some View {
+ HStack {
+ Spacer()
+ Button(action: {
+ if case .generating = viewModel.viewState {
+ viewModel.stop()
+ } else {
+ viewModel.classify()
+ }
+ }) {
+ Text(actionButtonTitle)
+ .font(.monoHeading14Bold)
+ .foregroundStyle(buttonTextColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(buttonBackgroundColor)
+ .cornerRadius(12)
+ }
+ .disabled(isActionDisabled)
+ Spacer()
+ }
+ }
+
+ // MARK: - Logic – Helpers
+
+ private var isActionDisabled: Bool {
+ if case .generating = viewModel.viewState {
+ return false
+ }
+ return !isInputValid || isInputDisabled
+ }
+
+ private var isInputDisabled: Bool {
+ switch viewModel.viewState {
+ case .loading, .generating, .error:
+ return true
+ case .idle:
+ return false
+ }
+ }
+
+ private var isInputValid: Bool {
+ !viewModel.inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
+ private var actionButtonTitle: String {
+ switch viewModel.viewState {
+ case .loading:
+ return "Loading…"
+ case .generating:
+ return "STOP"
+ case .error(let error):
+ return "Error: \(error.localizedDescription)"
+ case .idle:
+ return "CLASSIFY"
+ }
+ }
+
+ private var buttonTextColor: Color {
+ if case .generating = viewModel.viewState {
+ return MiraiAsset.contrast.swiftUIColor
+ }
+ return isInputDisabled || !isInputValid
+ ? MiraiAsset.secondary.swiftUIColor : MiraiAsset.contrast.swiftUIColor
+ }
+
+ private var buttonBackgroundColor: Color {
+ if case .generating = viewModel.viewState {
+ return MiraiAsset.primary.swiftUIColor
+ }
+ return isInputDisabled || !isInputValid
+ ? MiraiAsset.card.swiftUIColor : MiraiAsset.primary.swiftUIColor
+ }
+
+ // MARK: - Metric row helper
+
+ @ViewBuilder
+ private func metricRow(label: String, value: String) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Text(label)
+ .font(.monoCaption12)
+ Text(value)
+ .font(.monoBody16)
+ }
+ }
+
+ init(identifier: String) {
+ self.identifier = identifier
+ let feat = Feature(name: "sentiment", values: Self.sentiments)
+ _viewModel = State(initialValue: ClassificationModel(identifier: identifier, feature: feat))
+ viewModel.inputText = Self.textsToClassify.randomElement()!
+ }
+}
diff --git a/apps/playground/Sources/Views/HomeView.swift b/apps/playground/Sources/Views/HomeView.swift
new file mode 100644
index 000000000..fb1d6870b
--- /dev/null
+++ b/apps/playground/Sources/Views/HomeView.swift
@@ -0,0 +1,258 @@
+import AVFoundation
+import SFSymbols
+import SwiftUI
+import Uzu
+
+#if os(macOS)
+ import AppKit
+#endif
+
+struct HomeView: View {
+ // MARK: - Type Definitions
+ private struct Feature: Identifiable {
+ let id = UUID()
+ let icon: SFSymbol
+ let title: String
+ let destination: Router.Destination?
+
+ var isComingSoon: Bool { destination == nil }
+ }
+
+ // MARK: - Environment
+ @Environment(Router.self) private var router
+ @Environment(AudioController.self) private var audioController
+
+ // MARK: - Stored Properties
+ private var features: [Feature] {
+ [
+ Feature(
+ icon: .bubbleLeftAndBubbleRight,
+ title: "General Chat",
+ destination: .modelSelection(next: .chat)
+ ),
+ Feature(
+ icon: .circleLefthalfFilled,
+ title: "Classification",
+ destination: .modelSelection(next: .classification)
+ ),
+ Feature(
+ icon: .docText,
+ title: "Summarisation",
+ destination: .modelSelection(next: .summarization)
+ ),
+ Feature(
+ icon: .mic,
+ title: "Text To Speech",
+ destination: .modelSelection(next: .textToSpeech)
+ ),
+ // Disabled features – coming soon
+ Feature(
+ icon: .camera,
+ title: "Camera",
+ destination: nil
+ )
+ ]
+ }
+
+ init() {}
+
+ var body: some View {
+ VStack(spacing: 0) {
+ header
+ featureList
+ Spacer()
+ exploreModels
+ footer
+ .padding(.bottom, 20)
+ }
+ .background(MiraiAsset.background.swiftUIColor)
+ #if os(iOS)
+ .navigationBarTitleDisplayMode(.inline)
+ #endif
+ .toolbar {
+ MiraiToolbarLogo()
+ }
+ .toolbarBackground(MiraiAsset.background.swiftUIColor, for: .automatic)
+ .toolbarBackground(.visible, for: .automatic)
+ #if os(macOS)
+ .toolbarRole(.editor)
+ #endif
+ .onAppear {
+ if audioController.player == nil,
+ let asset = AVURLAsset(MiraiAsset.aboutUsPodcast.data)
+ {
+ audioController.setAsset(asset)
+ }
+ }
+ }
+
+ // MARK: - UI
+
+ // Header
+ private var header: some View {
+ VStack(spacing: 0) {
+ VStack(spacing: 8) {
+ Text("Choose AI Usecase")
+ .font(.monoBody16Semibold)
+ .textCase(.uppercase)
+ .foregroundColor(MiraiAsset.primary.swiftUIColor)
+ .accessibilityIdentifier("homeTitle")
+
+ Text("to see Mirai on-device possibilities")
+ .font(.monoCaption12)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ .multilineTextAlignment(.center)
+ }
+ }
+ .padding(.vertical, 28)
+ }
+
+ // Feature List
+ private var featureList: some View {
+ LazyVStack(spacing: 16) {
+ ForEach(features) { feature in
+ featureRow(feature)
+ }
+ }
+ .padding(.horizontal, 20)
+ }
+
+ @ViewBuilder
+ private func featureRow(_ feature: Feature) -> some View {
+ Button(action: {
+ if let dest = feature.destination {
+ router.navigate(to: dest)
+ }
+ }) {
+ HStack(spacing: 16) {
+ Image(symbol: feature.icon)
+ .font(.title20)
+ .foregroundStyle(
+ feature.isComingSoon
+ ? MiraiAsset.secondary.swiftUIColor
+ : MiraiAsset.primary.swiftUIColor)
+
+ Text(feature.title)
+ .font(.monoHeading14)
+ .foregroundStyle(MiraiAsset.primary.swiftUIColor)
+
+ Spacer()
+
+ if feature.isComingSoon {
+ Text("COMING SOON")
+ .font(.monoCaption12Semibold)
+ .foregroundStyle(MiraiAsset.secondary.swiftUIColor)
+ }
+ }
+ .padding(16)
+ .frame(maxWidth: .infinity)
+ .background(MiraiAsset.card.swiftUIColor)
+ .cornerRadius(12)
+ }
+ .buttonStyle(.plain)
+ .disabled(feature.isComingSoon)
+ }
+
+ // Explore Models CTA
+ private var exploreModels: some View {
+ Button(action: {
+ router.navigate(to: .modelManagement)
+ }) {
+ VStack(spacing: 8) {
+ Image(symbol: .chevronLeftChevronRight)
+ .font(.caption12Semibold)
+ .foregroundStyle(MiraiAsset.primary.swiftUIColor)
+
+ Text("Explore our available models")
+ .font(.monoCaption12)
+ .foregroundStyle(MiraiAsset.primary.swiftUIColor)
+ .padding(.bottom)
+ Rectangle()
+ .frame(height: 1)
+ .foregroundColor(MiraiAsset.primary.swiftUIColor.opacity(0.05))
+ }
+ }
+ .buttonStyle(.plain)
+ .padding(.vertical, 20)
+ .frame(maxWidth: .infinity)
+ .accessibilityIdentifier("exploreModelsButton")
+ }
+
+ // Footer Links
+ private var footer: some View {
+ HStack(alignment: .center) {
+ if audioController.player != nil {
+ ourVisionButton
+ Spacer()
+ }
+ aboutButton
+ Spacer()
+ footerLink(
+ title: "Contact us",
+ icon: .heartFill,
+ url: "mailto:[email protected],[email protected]?subject=Interested%20in%20Mirai")
+ }
+ .padding(.horizontal, 20)
+ }
+
+ @ViewBuilder
+ private var ourVisionButton: some View {
+ if audioController.player != nil {
+ Button(action: {
+ audioController.toggle()
+ }) {
+ VStack(alignment: .center, spacing: 8) {
+ Image(symbol: audioController.isPlaying ? .pauseFill : .playFill)
+ .font(.caption12)
+ .foregroundStyle(MiraiAsset.primary.swiftUIColor)
+ Text("Our vision")
+ .font(.monoCaption12)
+ .foregroundStyle(MiraiAsset.primary.swiftUIColor)
+ }
+ }
+ .padding(.horizontal)
+ .buttonStyle(.plain)
+ }
+ }
+
+ private var aboutButton: some View {
+ Button(action: {
+ router.navigate(to: .about)
+ }) {
+ VStack(alignment: .center, spacing: 8) {
+ Image(symbol: .infoCircleFill)
+ .font(.caption12)
+ .foregroundStyle(MiraiAsset.primary.swiftUIColor)
+ Text("About us")
+ .font(.monoCaption12)
+ .foregroundStyle(MiraiAsset.primary.swiftUIColor)
+ }
+ }
+ .padding(.horizontal)
+ .buttonStyle(.plain)
+ }
+
+ private func footerLink(title: String, icon: SFSymbol, url: String) -> some View {
+ Button(action: {
+ if let link = URL(string: url) {
+ #if os(iOS)
+ UIApplication.shared.open(link)
+ #else
+ NSWorkspace.shared.open(link)
+ #endif
+ }
+ }) {
+ VStack(alignment: .center, spacing: 8) {
+ Image(symbol: icon)
+ .font(.caption12)
+ .foregroundStyle(MiraiAsset.primary.swiftUIColor)
+ Text(title)
+ .font(.monoCaption12)
+ .foregroundStyle(MiraiAsset.primary.swiftUIColor)
+ }
+ }
+ .padding(.horizontal)
+ .buttonStyle(.plain)
+ }
+
+}
diff --git a/apps/playground/Sources/Views/MiraiToolbarLogo.swift b/apps/playground/Sources/Views/MiraiToolbarLogo.swift
new file mode 100644
index 000000000..937dc1403
--- /dev/null
+++ b/apps/playground/Sources/Views/MiraiToolbarLogo.swift
@@ -0,0 +1,48 @@
+import SwiftUI
+
+struct MiraiToolbarLogo: ToolbarContent {
+
+ struct Configuration {
+ let topPadding: CGFloat
+ let bottomPadding: CGFloat
+
+ static let `default` = Configuration(topPadding: 0, bottomPadding: 0)
+ }
+
+ let configuration: Configuration
+
+ init(configuration: Configuration = .default) {
+ self.configuration = configuration
+ }
+
+ var body: some ToolbarContent {
+ if #available(iOS 26, macOS 26, *) {
+ logoWithHiddenBackground
+ } else {
+ logoDefault
+ }
+ }
+
+ @available(iOS 26.0, macOS 26.0, *)
+ @ToolbarContentBuilder
+ private var logoWithHiddenBackground: some ToolbarContent {
+ ToolbarItem(placement: .principal) {
+ logoImage
+ }
+ .sharedBackgroundVisibility(.hidden)
+ }
+
+ @ToolbarContentBuilder
+ private var logoDefault: some ToolbarContent {
+ ToolbarItem(placement: .principal) {
+ logoImage
+ }
+ }
+
+ private var logoImage: some View {
+ Image(asset: MiraiAsset.logo)
+ .padding(.top, configuration.topPadding)
+ .padding(.bottom, configuration.bottomPadding)
+ }
+}
+
diff --git a/apps/playground/Sources/Views/MiraiToolbarModelName.swift b/apps/playground/Sources/Views/MiraiToolbarModelName.swift
new file mode 100644
index 000000000..f72d04b5c
--- /dev/null
+++ b/apps/playground/Sources/Views/MiraiToolbarModelName.swift
@@ -0,0 +1,51 @@
+import SwiftUI
+
+struct MiraiToolbarModelName: ToolbarContent {
+
+ let identifier: String
+
+ var body: some ToolbarContent {
+ if #available(iOS 26, macOS 26, *) {
+ withHiddenBackground
+ } else {
+ defaultContent
+ }
+ }
+
+ @available(iOS 26.0, macOS 26.0, *)
+ @ToolbarContentBuilder
+ private var withHiddenBackground: some ToolbarContent {
+ #if os(macOS)
+ ToolbarItem(placement: .automatic) {
+ label(padding: 18)
+ }
+ #else
+ ToolbarItem(placement: .topBarTrailing) {
+ label(padding: 18)
+ }
+ #endif
+ }
+
+ @ToolbarContentBuilder
+ private var defaultContent: some ToolbarContent {
+ #if os(macOS)
+ ToolbarItem(placement: .automatic) {
+ label(padding: 12)
+ }
+ #else
+ ToolbarItem(placement: .topBarTrailing) {
+ label(padding: 12)
+ }
+ #endif
+ }
+
+ private func label(padding: CGFloat) -> some View {
+ Text(identifier)
+ .font(.monoCaption12Semibold)
+ .foregroundColor(.secondary)
+ .lineLimit(1)
+ .truncationMode(.middle)
+ .padding(.horizontal, padding)
+ .padding(.vertical, 6)
+ }
+}
diff --git a/apps/playground/Sources/Views/ModelListView.swift b/apps/playground/Sources/Views/ModelListView.swift
new file mode 100644
index 000000000..437b626db
--- /dev/null
+++ b/apps/playground/Sources/Views/ModelListView.swift
@@ -0,0 +1,558 @@
+import Foundation
+import Observation
+import SFSymbols
+import SwiftUI
+import Uzu
+
+#if canImport(UIKit)
+ import UIKit
+#endif
+
+struct ModelListView: View {
+ // MARK: - Type Definitions
+ enum Mode {
+ case choose(next: Router.ModelListDestination)
+ case manage
+ }
+
+ // MARK: - Stored Properties
+ let mode: Mode
+
+ // MARK: - Environment
+ @EnvironmentObject var engineWrapper: EngineObservableWrapper
+ @Environment(Router.self) var router
+
+ // MARK: - State
+ @State var selectedIdentifier: String?
+ @State private var selectedModelSection: ModelSection?
+
+ var body: some View {
+ VStack(spacing: 0) {
+ header
+ modelList
+ Spacer()
+ bottomBar
+ .padding(20)
+ }
+ .background(MiraiAsset.background.swiftUIColor)
+ #if os(iOS)
+ .navigationBarTitleDisplayMode(.inline)
+ #endif
+ .toolbar {
+ MiraiToolbarLogo()
+ }
+ .toolbarBackground(MiraiAsset.background.swiftUIColor, for: .automatic)
+ .toolbarBackground(.visible, for: .automatic)
+ #if os(macOS)
+ .toolbarRole(.editor)
+ #endif
+ }
+
+ // MARK: - UI
+
+ // Header
+ private var header: some View {
+ VStack(spacing: 0) {
+ VStack(spacing: 8) {
+ Text("Available AI Models")
+ .font(.monoBody16Semibold)
+ .textCase(.uppercase)
+ .foregroundColor(MiraiAsset.primary.swiftUIColor)
+
+ Text("select a local model to install")
+ .font(.monoCaption12)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ }
+ .padding(.vertical, 28)
+ }
+ .accessibilityElement(children: .contain)
+ .accessibilityIdentifier("modelListHeaderContainer")
+ }
+
+ // Model List
+ private var modelList: some View {
+ let group = grouping
+ return ScrollViewReader { proxy in
+ ScrollView {
+ VStack(alignment: .leading, spacing: 24) {
+ // Cloud section (visible only when choosing a Chat model)
+ if case .choose(let next) = mode, next == .chat, !group.cloud.isEmpty {
+ VStack(alignment: .leading, spacing: 12) {
+ Text("Cloud")
+ .font(.monoCaption12Semibold)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ .textCase(.uppercase)
+ .padding(.horizontal, 4)
+ ForEach(group.cloud, id: \.identifier) { model in
+ CloudModelRow(
+ model: model, isSelected: selectedIdentifier == model.identifier
+ )
+ .id(model.identifier)
+ .onTapGesture {
+ selectedIdentifier = model.identifier
+ selectedModelSection = nil
+ }
+ }
+ }
+ }
+ ForEach(sectionOrder, id: \.self) { section in
+ let identifiers = group.bySection[section] ?? []
+ if !identifiers.isEmpty {
+ VStack(alignment: .leading, spacing: 12) {
+ Text(section.title)
+ .font(.monoCaption12Semibold)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ .textCase(.uppercase)
+ .padding(.horizontal, 4)
+ ForEach(identifiers, id: \.self) { identifier in
+ if let model = group.modelByIdentifier[identifier],
+ let state = engineWrapper.downloadStates[identifier] {
+ ModelRowView(
+ identifier: identifier,
+ model: model,
+ state: state,
+ isSelected: selectedIdentifier == identifier
+ )
+ .equatable()
+ .id(identifier)
+ .onTapGesture {
+ select(identifier: identifier)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ .padding(.horizontal, 20)
+ }
+ .onChange(of: engineWrapper.models) { _, _ in
+ guard
+ let selectedIdentifier,
+ let model = group.modelByIdentifier[selectedIdentifier],
+ model.isLocal(),
+ let state = engineWrapper.downloadStates[model.identifier]
+ else { return }
+
+ let newSection = section(for: state)
+
+ if newSection != selectedModelSection {
+ selectedModelSection = newSection
+ withAnimation {
+ proxy.scrollTo(selectedIdentifier, anchor: .center)
+ }
+ }
+ }
+ }
+ }
+
+ @ViewBuilder
+ private var bottomBar: some View {
+ switch mode {
+ case .choose:
+ chooseBottomBar
+ case .manage:
+ manageBottomBar
+ }
+ }
+
+ @ViewBuilder
+ private var chooseBottomBar: some View {
+ if let state = selectedModelState {
+ switch state.phase {
+ case .notDownloaded, .paused, .locked:
+ downloadButton
+ case .downloading:
+ waitingText
+ case .error:
+ retryButton
+ case .downloaded:
+ chooseButton
+ }
+ } else if
+ let selectedId = selectedIdentifier,
+ models()
+ .filter({ $0.isRemote() })
+ .contains(where: { $0.identifier == selectedId })
+ {
+ // Cloud models are selectable only for Chat
+ if case .choose(let next) = mode, next == .chat {
+ Button(action: { proceed() }) {
+ Text("CHOOSE CLOUD MODEL")
+ .font(.monoHeading14Bold)
+ .foregroundColor(MiraiAsset.contrast.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(MiraiAsset.primary.swiftUIColor)
+ .cornerRadius(12)
+ }
+ } else {
+ disabledChooseButton
+ }
+ } else {
+ disabledChooseButton
+ }
+ }
+ @ViewBuilder
+ private var manageBottomBar: some View {
+ if let state = selectedModelState {
+ switch state.phase {
+ case .notDownloaded, .error, .locked:
+ downloadButton
+ case .downloading:
+ pauseButton
+ case .paused:
+ resumeButton
+ case .downloaded:
+ deleteButton
+ }
+ } else if
+ let selectedId = selectedIdentifier,
+ models()
+ .filter({ $0.isRemote() })
+ .contains(where: { $0.identifier == selectedId })
+ {
+ disabledManageButton
+ } else {
+ disabledManageButton
+ }
+ }
+
+ // MARK: - Bottom bar buttons & texts
+
+ private var disabledChooseButton: some View {
+ Button(action: {}) {
+ Text("CHOOSE")
+ .font(.monoHeading14Bold)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(MiraiAsset.card.swiftUIColor)
+ .cornerRadius(12)
+ }
+ .disabled(true)
+ }
+
+ private var disabledManageButton: some View {
+ Button(action: {}) {
+ Text("SELECT MODEL")
+ .font(.monoHeading14Bold)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(MiraiAsset.card.swiftUIColor)
+ .cornerRadius(12)
+ }
+ .disabled(true)
+ }
+
+ private var downloadButton: some View {
+ Button(action: {
+ downloadSelectedModel()
+ }) {
+ Text("DOWNLOAD")
+ .font(.monoHeading14Bold)
+ .foregroundColor(MiraiAsset.contrast.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(MiraiAsset.primary.swiftUIColor)
+ .cornerRadius(12)
+ }
+ .accessibilityIdentifier("downloadButton")
+ }
+
+ private var retryButton: some View {
+ Button(action: {
+ downloadSelectedModel()
+ }) {
+ Text("RETRY DOWNLOAD")
+ .font(.monoHeading14Bold)
+ .foregroundColor(MiraiAsset.contrast.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(MiraiAsset.primary.swiftUIColor)
+ .cornerRadius(12)
+ }
+ }
+
+ private var chooseButton: some View {
+ Button(action: {
+ proceed()
+ }) {
+ Text("CHOOSE")
+ .font(.monoHeading14Bold)
+ .foregroundColor(MiraiAsset.contrast.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(MiraiAsset.primary.swiftUIColor)
+ .cornerRadius(12)
+ }
+ }
+
+ private var waitingText: some View {
+ Text("Wait for the models to be installed...")
+ .font(.monoHeading14Medium)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .multilineTextAlignment(.center)
+ }
+
+ private var deleteButton: some View {
+ Button(action: {
+ deleteSelectedModel()
+ }) {
+ Text("DELETE")
+ .font(.monoHeading14Bold)
+ .foregroundColor(MiraiAsset.contrast.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(MiraiAsset.primary.swiftUIColor)
+ .cornerRadius(12)
+ }
+ .accessibilityIdentifier("deleteButton")
+ }
+
+ private var pauseButton: some View {
+ Button(action: {
+ pauseSelectedModel()
+ }) {
+ Text("PAUSE")
+ .font(.monoHeading14Bold)
+ .foregroundColor(MiraiAsset.contrast.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(MiraiAsset.primary.swiftUIColor)
+ .cornerRadius(12)
+ }
+ .accessibilityIdentifier("pauseButton")
+ }
+
+ private var resumeButton: some View {
+ Button(action: {
+ resumeSelectedModel()
+ }) {
+ Text("RESUME")
+ .font(.monoHeading14Bold)
+ .foregroundColor(MiraiAsset.contrast.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(MiraiAsset.primary.swiftUIColor)
+ .cornerRadius(12)
+ }
+ .accessibilityIdentifier("resumeButton")
+ }
+
+ // MARK: - Helpers
+ private var selectedModelState: DownloadState? {
+ guard let selectedIdentifier else { return nil }
+ guard let model = models()
+ .filter({ $0.isLocal() })
+ .first(where: { $0.identifier == selectedIdentifier }) else {
+ return nil
+ }
+ let state = engineWrapper.downloadStates[model.identifier]
+ return state
+ }
+
+ private func select(identifier: String) {
+ selectedIdentifier = identifier
+ if let model = models()
+ .filter({ $0.isLocal() })
+ .first(where: { $0.identifier == selectedIdentifier }),
+ let state = engineWrapper.downloadStates[model.identifier] {
+ selectedModelSection = section(for: state)
+ }
+ }
+
+ private func downloadSelectedModel() {
+ guard
+ let selectedIdentifier,
+ let model = engineWrapper.models.first(where: {$0.identifier == selectedIdentifier}) else {
+ return
+ }
+ print("[ModelListView] downloadSelectedModel called for: \(selectedIdentifier)")
+ if let state = selectedModelState {
+ print("[ModelListView] Current state phase: \(state.phase)")
+ }
+ Task {
+ try? await engineWrapper.engine?.downloader(model: model).resume()
+ }
+ }
+
+ private func deleteSelectedModel() {
+ guard
+ let selectedIdentifier,
+ let model = engineWrapper.models.first(where: {$0.identifier == selectedIdentifier}) else {
+ return
+ }
+ Task {
+ try? await engineWrapper.engine?.downloader(model: model).delete()
+ }
+ }
+
+ private func proceed() {
+ guard let selectedIdentifier else { return }
+ guard case .choose(let next) = mode else { return }
+ switch next {
+ case .classification:
+ router.navigate(to: .classification(identifier: selectedIdentifier))
+ case .summarization:
+ router.navigate(to: .summarization(identifier: selectedIdentifier))
+ case .chat:
+ router.navigate(to: .chat(identifier: selectedIdentifier))
+ case .textToSpeech:
+ router.navigate(to: .textToSpeech(identifier: selectedIdentifier))
+ }
+ }
+
+ private func pauseSelectedModel() {
+ guard
+ let selectedIdentifier,
+ let model = engineWrapper.models.first(where: {$0.identifier == selectedIdentifier}) else {
+ return
+ }
+ Task {
+ try? await engineWrapper.engine?.downloader(model: model).pause()
+ }
+ }
+
+ private func resumeSelectedModel() {
+ guard
+ let selectedIdentifier,
+ let model = engineWrapper.models.first(where: {$0.identifier == selectedIdentifier}) else {
+ return
+ }
+ Task {
+ try? await engineWrapper.engine?.downloader(model: model).resume()
+ }
+ }
+
+ // MARK: - Section helpers
+
+ private enum ModelSection: Int {
+ case installed
+ case installing
+ case paused
+ case notInstalled
+
+ var title: String {
+ switch self {
+ case .installed: return "Installed"
+ case .installing: return "Installing"
+ case .paused: return "Paused"
+ case .notInstalled: return "Not Installed"
+ }
+ }
+ }
+
+ private var sectionOrder: [ModelSection] {
+ [.installed, .installing, .paused, .notInstalled]
+ }
+
+ private func models() -> [Uzu.Model] {
+ engineWrapper.models.filter({ model in
+ switch self.mode {
+ case .manage:
+ return true
+ case let .choose(next):
+ switch(next) {
+ case .chat, .classification, .summarization:
+ return model.specializations.contains(.chat)
+ case .textToSpeech:
+ return model.specializations.contains(.textToSpeech)
+ }
+ }
+ })
+ }
+
+ private typealias Grouping = (
+ cloud: [Uzu.Model],
+ local: [Uzu.Model],
+ modelByIdentifier: [String: Uzu.Model],
+ bySection: [ModelSection: [String]]
+ )
+
+ private var grouping: Grouping {
+ let all = engineWrapper.models.filter { model in
+ switch self.mode {
+ case .manage:
+ return true
+ case let .choose(next):
+ switch next {
+ case .chat, .classification, .summarization:
+ return model.specializations.contains(.chat)
+ case .textToSpeech:
+ return model.specializations.contains(.textToSpeech)
+ }
+ }
+ }
+ let cloud = all.filter { $0.isRemote() }.sorted { $0.name() < $1.name() }
+ let local = all.filter { $0.isLocal() }
+ let modelByIdentifier = Dictionary(uniqueKeysWithValues: all.map { ($0.identifier, $0) })
+
+ var bySection: [ModelSection: [String]] = [:]
+ for model in local {
+ guard let state = engineWrapper.downloadStates[model.identifier] else { continue }
+ bySection[section(for: state), default: []].append(model.identifier)
+ }
+ for key in bySection.keys { bySection[key]?.sort() }
+
+ return (cloud, local, modelByIdentifier, bySection)
+ }
+
+ private func section(for state: DownloadState) -> ModelSection {
+ switch state.phase {
+ case .downloaded: return .installed
+ case .downloading: return .installing
+ case .paused: return .paused
+ case .notDownloaded: return .notInstalled
+ case .error: return .notInstalled
+ case .locked: return .notInstalled
+ }
+ }
+
+}
+
+// MARK: - Cloud model row
+
+private struct CloudModelRow: View {
+ let model: Uzu.Model
+ let isSelected: Bool
+ @EnvironmentObject private var engineWrapper: EngineObservableWrapper
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ Image(systemName: isSelected ? "cloud.fill" : "cloud")
+ .foregroundColor(MiraiAsset.primary.swiftUIColor)
+ VStack(alignment: .leading, spacing: 4) {
+ Text(model.name())
+ .font(.monoHeading14)
+ .foregroundColor(MiraiAsset.primary.swiftUIColor)
+ HStack(spacing: 4) {
+ badge(text: model.family?.vendor.name() ?? model.registry.name())
+ }
+ }
+ Spacer()
+ Text("cloud")
+ .font(.monoCaption12)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ }
+ }
+ .padding(16)
+ .background(MiraiAsset.card.swiftUIColor)
+ .cornerRadius(12)
+ }
+
+ @ViewBuilder
+ private func badge(text: String) -> some View {
+ Text(text)
+ .font(.monoBadge10Semibold)
+ .padding(.horizontal, 6)
+ .padding(.vertical, 2)
+ .background(MiraiAsset.cardBorder.swiftUIColor)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous))
+ }
+}
diff --git a/apps/playground/Sources/Views/ModelRowView.swift b/apps/playground/Sources/Views/ModelRowView.swift
new file mode 100644
index 000000000..5d726e41f
--- /dev/null
+++ b/apps/playground/Sources/Views/ModelRowView.swift
@@ -0,0 +1,171 @@
+import SFSymbols
+import SwiftUI
+import Uzu
+
+struct ModelRowView: View, Equatable {
+
+ // MARK: - Stored Properties
+ let identifier: String
+ let model: Uzu.Model
+ let state: DownloadState
+ let isSelected: Bool
+
+ // MARK: - Equatable
+ static func == (lhs: ModelRowView, rhs: ModelRowView) -> Bool {
+ lhs.identifier == rhs.identifier &&
+ lhs.isSelected == rhs.isSelected &&
+ lhs.state == rhs.state
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ HStack(spacing: 8) {
+ statusIcon
+
+ VStack(alignment: .leading, spacing: 4) {
+ Text(modelNameOnly)
+ .font(.monoHeading14)
+ .foregroundColor(MiraiAsset.primary.swiftUIColor)
+ .lineLimit(2)
+
+ HStack(spacing: 4) {
+ if let vendor = vendor {
+ badge(text: vendor)
+ }
+ if let qlabel = quantizationLabel {
+ badge(text: qlabel)
+ }
+ }
+ }
+ .frame(maxWidth: .infinity, alignment: .leading)
+
+ Spacer()
+
+ VStack(spacing: 8) {
+ statusText
+ if let bytes = bytesInfo {
+ Text(bytes)
+ .font(.monoCaption12)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ }
+ }
+ }
+
+ if state.phase == .downloading || state.phase == .paused {
+ let progress = min(max(state.progress(), 0.0), 1.0)
+ VStack(alignment: .leading, spacing: 4) {
+ ProgressView(value: progress)
+ .progressViewStyle(
+ LinearProgressViewStyle(tint: MiraiAsset.primary.swiftUIColor)
+ )
+ .frame(height: 4)
+ .frame(maxWidth: .infinity)
+ .clipShape(Capsule())
+ .accessibilityIdentifier("modelProgressBar_\(identifier)")
+ }
+ }
+ }
+ .padding(16)
+ .background(MiraiAsset.card.swiftUIColor)
+ .cornerRadius(12)
+ .accessibilityIdentifier("modelRow_\(identifier)")
+ }
+
+ // MARK: - Status helpers
+
+ @ViewBuilder
+ private var statusIcon: some View {
+ Image(symbol: isSelected ? .checkmarkCircleFill : .circle)
+ .font(.title24Light)
+ .foregroundColor(MiraiAsset.primary.swiftUIColor)
+ }
+
+ @ViewBuilder
+ private var statusText: some View {
+ let statusFont = Font.monoHeading14
+ switch state.phase {
+ case .notDownloaded:
+ Text("not installed")
+ .font(statusFont)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ case .downloading:
+ Text("installing…")
+ .font(statusFont)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ case .downloaded:
+ Text("installed")
+ .font(statusFont)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ case .paused:
+ Text("paused")
+ .font(statusFont)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ case .error:
+ Text("error")
+ .font(statusFont)
+ .foregroundColor(.red)
+ case .locked:
+ Text("locked")
+ .font(statusFont)
+ .foregroundColor(.red)
+ }
+ }
+
+ // MARK: - Metadata helpers
+
+ private var vendor: String? {
+ model.family?.vendor.name()
+ }
+
+ private var quantizationLabel: String? {
+ model.quantization?.name()
+ }
+
+ private var modelNameOnly: String {
+ model.name()
+ }
+
+ // MARK: - Downloaded bytes info
+
+ private var bytesInfo: String? {
+ switch state.phase {
+ case .downloading, .paused:
+ return "\(formatBytes(state.downloadedBytes)) / \(formatBytes(state.totalBytes))"
+ case .notDownloaded:
+ return formatBytes(state.totalBytes)
+ default:
+ return nil
+ }
+ }
+
+ private func formatBytes(_ bytes: Int64) -> String {
+ let kb: Double = 1024
+ let mb = kb * 1024
+ let gb = mb * 1024
+
+ let value = Double(bytes)
+
+ if value >= gb {
+ return String(format: "%.1f GB", value / gb)
+ } else if value >= mb {
+ return String(format: "%.1f MB", value / mb)
+ } else if value >= kb {
+ return String(format: "%.0f KB", value / kb)
+ } else {
+ return "\(bytes) B"
+ }
+ }
+
+ // MARK: - Badge helper
+
+ @ViewBuilder
+ private func badge(text: String) -> some View {
+ Text(text)
+ .font(.monoBadge10Semibold)
+ .padding(.horizontal, 6)
+ .padding(.vertical, 2)
+ .background(MiraiAsset.cardBorder.swiftUIColor)
+ .foregroundColor(MiraiAsset.secondary.swiftUIColor)
+ .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous))
+ }
+}
diff --git a/apps/playground/Sources/Views/SendTextView.swift b/apps/playground/Sources/Views/SendTextView.swift
new file mode 100644
index 000000000..453ee32dc
--- /dev/null
+++ b/apps/playground/Sources/Views/SendTextView.swift
@@ -0,0 +1,53 @@
+import SwiftUI
+
+#if os(iOS)
+import UIKit
+#endif
+
+/// Multiline text input that expands vertically up to five lines and triggers `onSend` on the *Send* key.
+struct SendTextView: View {
+ @Binding var text: String
+ var onSend: () -> Void
+
+ var body: some View {
+ #if os(iOS)
+ IOSMultilineTextField(text: $text, onSend: onSend)
+ #else
+ MacMultilineTextField(text: $text)
+ #endif
+ }
+}
+
+#if os(iOS)
+// MARK: - iOS implementation (SwiftUI TextEditor)
+
+private struct IOSMultilineTextField: View {
+ @Binding var text: String
+ var onSend: () -> Void
+
+ var body: some View {
+ TextField("", text: $text, axis: .vertical)
+ .font(.monoBody16)
+ .lineLimit(5, reservesSpace: false)
+ .onSubmit {
+ onSend()
+ }
+ }
+}
+#endif
+
+#if os(macOS)
+// MARK: - macOS implementation
+
+private struct MacMultilineTextField: View {
+ @Binding var text: String
+
+ var body: some View {
+ TextField("", text: $text, axis: .vertical)
+ .textFieldStyle(.plain)
+ .font(.monoBody16)
+ .lineLimit(1...5)
+ .fixedSize(horizontal: false, vertical: true)
+ }
+}
+#endif
diff --git a/apps/playground/Sources/Views/SummarizationView.swift b/apps/playground/Sources/Views/SummarizationView.swift
new file mode 100644
index 000000000..6789532f2
--- /dev/null
+++ b/apps/playground/Sources/Views/SummarizationView.swift
@@ -0,0 +1,224 @@
+import Foundation
+import Observation
+import SFSymbols
+import SwiftUI
+import Uzu
+
+#if canImport(UIKit)
+ import UIKit
+#endif
+
+struct SummarizationView: View {
+
+ // MARK: - Environment
+ @Environment(Router.self) private var router
+ @EnvironmentObject private var engineWrapper: EngineObservableWrapper
+ @Environment(AudioController.self) private var audioController
+ @State private var viewModel: SummarizationModel
+
+ // MARK: - Stored Properties
+ let identifier: String
+
+ static let textsToSummarize =
+ "A Large Language Model (LLM) is a type of artificial intelligence that processes and generates human-like text. It is trained on vast datasets containing books, articles, and web content, allowing it to understand and predict language patterns. LLMs use deep learning, particularly transformer-based architectures, to analyze text, recognize context, and generate coherent responses. These models have a wide range of applications, including chatbots, content creation, translation, and code generation. One of the key strengths of LLMs is their ability to generate contextually relevant text based on prompts. They utilize self-attention mechanisms to weigh the importance of words within a sentence, improving accuracy and fluency. Examples of popular LLMs include OpenAI's GPT series, Google's BERT, and Meta's LLaMA. As these models grow in size and sophistication, they continue to enhance human-computer interactions, making AI-powered communication more natural and effective."
+
+ // MARK: - State
+
+ @FocusState private var inputFocused: Bool
+
+ // MARK: - Type Definitions
+ // ViewState provided by SummarizationModel.ViewState
+
+ // MARK: - Body
+ var body: some View {
+ VStack(spacing: 0) {
+ ScrollViewReader { proxy in
+ ScrollView {
+ VStack(spacing: 20) {
+ input
+ if !viewModel.summaryText.isEmpty {
+ summary
+ }
+
+ Color.clear
+ .frame(height: 1)
+ .id("bottom")
+ }
+ .padding()
+ }
+ .onChange(of: viewModel.summaryText) { _, _ in
+ withAnimation {
+ proxy.scrollTo("bottom", anchor: .bottom)
+ }
+ }
+ }
+ Divider()
+ bottomBar
+ .padding()
+ }
+ .background(MiraiAsset.background.swiftUIColor)
+ #if os(iOS)
+ .toolbar { MiraiToolbarModelName(identifier: identifier) }
+ #endif
+ .toolbarRole(.editor)
+ .onAppear {
+ viewModel.loadSession(using: engineWrapper)
+ }
+ .onDisappear {
+ viewModel.tearDown()
+ }
+ }
+
+ // MARK: - UI
+
+ private var input: some View {
+ ZStack(alignment: .topLeading) {
+ TextField("Enter text to summarise...", text: $viewModel.inputText, axis: .vertical)
+ .textFieldStyle(.plain)
+ .focused($inputFocused)
+ .font(.monoBody16)
+ .disabled(isInputDisabled)
+ .padding(12)
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .background(MiraiAsset.card.swiftUIColor)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+
+ if viewModel.inputText.isEmpty {
+ Text("Enter text to summarise...")
+ .font(.monoBody16)
+ .foregroundStyle(MiraiAsset.secondary.swiftUIColor)
+ .padding(.horizontal, 16)
+ .padding(.vertical, 12)
+ .allowsHitTesting(false)
+ }
+ }
+ }
+
+ private var summary: some View {
+ VStack(alignment: .leading, spacing: 8) {
+ Text(LocalizedStringKey(viewModel.summaryText))
+ .font(.monoBody16)
+ .textSelection(.enabled)
+
+ if let stats = viewModel.stats {
+ Rectangle()
+ .fill(MiraiAsset.cardBorder.swiftUIColor)
+ .frame(height: 1)
+ .padding(.vertical, 4)
+
+ VStack(alignment: .leading, spacing: 4) {
+ metricRow(
+ label: "Time to first token:",
+ value: String(format: "%.3f s", stats.timeToFirstToken)
+ )
+ if stats.tokensPerSecond > 0 {
+ metricRow(
+ label: "Tokens per second:",
+ value: String(format: "%.3f t/s", stats.tokensPerSecond)
+ )
+ }
+ metricRow(
+ label: "Total time:",
+ value: String(format: "%.3f s", stats.totalTime)
+ )
+ }
+ }
+ }
+ .padding(.leading, 16)
+ .frame(maxWidth: .infinity, alignment: .leading)
+ }
+
+ private var bottomBar: some View {
+ HStack {
+ Spacer()
+ Button(action: {
+ if case .generating = viewModel.viewState {
+ viewModel.stop()
+ } else {
+ viewModel.summarise()
+ }
+ }) {
+ Text(actionButtonTitle)
+ .font(.monoHeading14Bold)
+ .foregroundStyle(buttonTextColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(buttonBackgroundColor)
+ .cornerRadius(12)
+ }
+ .disabled(isActionDisabled)
+ Spacer()
+ }
+ }
+
+ // MARK: - Logic – Helpers
+
+ private var isActionDisabled: Bool {
+ if case .generating = viewModel.viewState {
+ return false
+ }
+ return !isInputValid || isInputDisabled
+ }
+
+ private var isInputDisabled: Bool {
+ switch viewModel.viewState {
+ case .loading, .generating, .error:
+ return true
+ case .idle:
+ return false
+ }
+ }
+
+ private var isInputValid: Bool {
+ !viewModel.inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
+ private var actionButtonTitle: String {
+ switch viewModel.viewState {
+ case .loading:
+ return "Loading..."
+ case .generating:
+ return "STOP"
+ case .error(let error):
+ return "Error: \(error.localizedDescription)"
+ case .idle:
+ return "SUMMARISE"
+ }
+ }
+
+ private var buttonTextColor: Color {
+ if case .generating = viewModel.viewState {
+ return MiraiAsset.contrast.swiftUIColor
+ }
+ return isInputDisabled || !isInputValid
+ ? MiraiAsset.secondary.swiftUIColor
+ : MiraiAsset.contrast.swiftUIColor
+ }
+
+ private var buttonBackgroundColor: Color {
+ if case .generating = viewModel.viewState {
+ return MiraiAsset.primary.swiftUIColor
+ }
+ return isInputDisabled || !isInputValid
+ ? MiraiAsset.card.swiftUIColor : MiraiAsset.primary.swiftUIColor
+ }
+
+ // MARK: - Metric row helper
+
+ @ViewBuilder
+ private func metricRow(label: String, value: String) -> some View {
+ HStack(alignment: .firstTextBaseline, spacing: 6) {
+ Text(label)
+ .font(.monoCaption12)
+ .foregroundStyle(MiraiAsset.secondary.swiftUIColor)
+ Text(value)
+ .font(.monoBody16)
+ }
+ }
+
+ init(identifier: String) {
+ self.identifier = identifier
+ _viewModel = State(initialValue: SummarizationModel(identifier: identifier))
+ viewModel.inputText = SummarizationView.textsToSummarize
+ }
+}
diff --git a/apps/playground/Sources/Views/TextToSpeechView.swift b/apps/playground/Sources/Views/TextToSpeechView.swift
new file mode 100644
index 000000000..00b15124b
--- /dev/null
+++ b/apps/playground/Sources/Views/TextToSpeechView.swift
@@ -0,0 +1,190 @@
+import Foundation
+import Observation
+import SFSymbols
+import SwiftUI
+import AVFoundation
+import Uzu
+
+#if canImport(UIKit)
+ import UIKit
+#endif
+
+struct TextToSpeechView: View {
+
+ // MARK: - Environment
+ @Environment(Router.self) private var router
+ @EnvironmentObject private var engineWrapper: EngineObservableWrapper
+ @Environment(AudioController.self) private var audioController
+ @State private var viewModel: TextToSpeechModel
+ @State private var isPlaying: Bool
+
+ // MARK: - Stored Properties
+ let identifier: String
+
+ static let textForSynthesis = "London is the capital of United Kingdom and one of the world’s most influential cities, known for its rich history, cultural diversity, and global significance in finance, politics, and the arts. Situated along the River Thames, the city blends historic landmarks like Tower of London and Buckingham Palace with modern architecture such as The Shard. London is also home to renowned institutions including the British Museum and vibrant areas like Covent Garden, offering a mix of history, entertainment, and innovation that attracts millions of visitors each year.";
+
+ // MARK: - State
+
+ @FocusState private var inputFocused: Bool
+
+ // MARK: - Type Definitions
+ // ViewState provided by SummarizationModel.ViewState
+
+ // MARK: - Body
+ var body: some View {
+ VStack(spacing: 0) {
+ ScrollViewReader { proxy in
+ ScrollView {
+ VStack(spacing: 20) {
+ input
+ Color.clear
+ .frame(height: 1)
+ .id("bottom")
+ }
+ .padding()
+ }
+ }
+ Divider()
+ bottomBar
+ .padding()
+ }
+ .background(MiraiAsset.background.swiftUIColor)
+ #if os(iOS)
+ .toolbar { MiraiToolbarModelName(identifier: identifier) }
+ #endif
+ .toolbarRole(.editor)
+ .onAppear {
+ viewModel.loadSession(using: engineWrapper)
+ }
+ .onDisappear {
+ viewModel.tearDown()
+ }
+ }
+
+ // MARK: - UI
+
+ private var input: some View {
+ ZStack(alignment: .topLeading) {
+ TextField("Enter text for synthesis...", text: $viewModel.inputText, axis: .vertical)
+ .textFieldStyle(.plain)
+ .focused($inputFocused)
+ .font(.monoBody16)
+ .disabled(isInputDisabled)
+ .padding(12)
+ .frame(maxWidth: .infinity, alignment: .topLeading)
+ .background(MiraiAsset.card.swiftUIColor)
+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))
+ }
+ }
+
+ private var bottomBar: some View {
+ HStack(alignment: .center, spacing: 16.0) {
+ Spacer()
+ Button(action: {
+ if case .generating = viewModel.viewState {
+ //viewModel.stopGeneration()
+ } else {
+ self.audioController.pause()
+ self.isPlaying = false
+ viewModel.generate()
+ }
+ }) {
+ Text(actionButtonTitle)
+ .font(.monoHeading14Bold)
+ .foregroundStyle(buttonTextColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(buttonBackgroundColor)
+ .cornerRadius(12)
+ }
+ .disabled(isActionDisabled)
+ Spacer()
+ Button(action: {
+ if let url = self.viewModel.outputPath {
+ self.toggleAudio(url: url)
+ }
+ }) {
+ Text(self.isPlaying ? "PAUSE" : "PLAY")
+ .font(.monoHeading14Bold)
+ .foregroundStyle(isPlayEnabled ? MiraiAsset.contrast.swiftUIColor : MiraiAsset.secondary.swiftUIColor)
+ .frame(maxWidth: .infinity)
+ .frame(height: 56)
+ .background(isPlayEnabled ? MiraiAsset.primary.swiftUIColor : MiraiAsset.card.swiftUIColor)
+ .cornerRadius(12)
+ }
+ .disabled(!isPlayEnabled)
+ Spacer()
+ }
+ }
+
+ // MARK: - Logic – Helpers
+
+ private var isActionDisabled: Bool {
+ if case .generating = viewModel.viewState {
+ return true
+ }
+ return !isInputValid || isInputDisabled
+ }
+
+ private var isPlayEnabled: Bool {
+ if case .generating = viewModel.viewState {
+ return false
+ }
+ return self.viewModel.outputPath != nil
+ }
+
+ private var isInputDisabled: Bool {
+ switch viewModel.viewState {
+ case .loading, .generating, .error:
+ return true
+ case .idle:
+ return false
+ }
+ }
+
+ private var isInputValid: Bool {
+ !viewModel.inputText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ }
+
+ private var actionButtonTitle: String {
+ switch viewModel.viewState {
+ case .loading:
+ return "Loading..."
+ case .generating:
+ return "STOP"
+ case .error(let error):
+ return "Error: \(error.localizedDescription)"
+ case .idle:
+ return "GENERATE"
+ }
+ }
+
+ private var buttonTextColor: Color {
+ return isActionDisabled
+ ? MiraiAsset.secondary.swiftUIColor
+ : MiraiAsset.contrast.swiftUIColor
+ }
+
+ private var buttonBackgroundColor: Color {
+ return isActionDisabled
+ ? MiraiAsset.card.swiftUIColor : MiraiAsset.primary.swiftUIColor
+ }
+
+ init(identifier: String) {
+ self.identifier = identifier
+ self.isPlaying = false
+ _viewModel = State(initialValue: TextToSpeechModel(identifier: identifier))
+ viewModel.inputText = TextToSpeechView.textForSynthesis
+ }
+
+ func toggleAudio(url: URL) {
+ if self.audioController.isPlaying {
+ self.audioController.pause()
+ self.isPlaying = false
+ } else {
+ self.audioController.setAsset(AVURLAsset(url: url))
+ self.audioController.play()
+ self.isPlaying = true
+ }
+ }
+}
diff --git a/bindings/.gitignore b/bindings/.gitignore
index 21f4bca49..dd634e093 100644
--- a/bindings/.gitignore
+++ b/bindings/.gitignore
@@ -1 +1 @@
-ts/src/napi/
\ No newline at end of file
+ts/src/napi/uzu.node
\ No newline at end of file
diff --git a/bindings/swift/.gitignore b/bindings/swift/.gitignore
new file mode 100644
index 000000000..305709958
--- /dev/null
+++ b/bindings/swift/.gitignore
@@ -0,0 +1,65 @@
+# Xcode
+#
+# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
+
+## User settings
+xcuserdata/
+
+## Obj-C/Swift specific
+*.hmap
+
+## App packaging
+*.ipa
+*.dSYM.zip
+*.dSYM
+
+## Playgrounds
+timeline.xctimeline
+playground.xcworkspace
+
+# Swift Package Manager
+#
+# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
+# Packages/
+# Package.pins
+# Package.resolved
+# *.xcodeproj
+#
+# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
+# hence it is not needed unless you have added a package configuration file to your project
+.swiftpm
+
+.build/
+
+# CocoaPods
+#
+# We recommend against adding the Pods directory to your .gitignore. However
+# you should judge for yourself, the pros and cons are mentioned at:
+# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
+#
+# Pods/
+#
+# Add this line if you want to avoid checking in source code from the Xcode workspace
+# *.xcworkspace
+
+# Carthage
+#
+# Add this line if you want to avoid checking in source code from Carthage dependencies.
+# Carthage/Checkouts
+
+Carthage/Build/
+
+# fastlane
+#
+# It is recommended to not store the screenshots in the git repo.
+# Instead, use fastlane to re-generate the screenshots whenever they are needed.
+# For more information about the recommended setup visit:
+# https://docs.fastlane.tools/best-practices/source-control/#source-control
+
+fastlane/report.xml
+fastlane/Preview.html
+fastlane/screenshots/**/*.png
+fastlane/test_output
+
+.release_build
+*.xcframework
\ No newline at end of file
diff --git a/bindings/swift/.ignore b/bindings/swift/.ignore
new file mode 100644
index 000000000..7d4e93eea
--- /dev/null
+++ b/bindings/swift/.ignore
@@ -0,0 +1,2 @@
+*.sh
+Package.resolved
\ No newline at end of file
diff --git a/bindings/swift/LICENSE b/bindings/swift/LICENSE
new file mode 100644
index 000000000..c869c80dd
--- /dev/null
+++ b/bindings/swift/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2025 Mirai Tech Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/bindings/swift/Package.resolved b/bindings/swift/Package.resolved
new file mode 100644
index 000000000..49d330429
--- /dev/null
+++ b/bindings/swift/Package.resolved
@@ -0,0 +1,14 @@
+{
+ "pins" : [
+ {
+ "identity" : "swift-argument-parser",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/apple/swift-argument-parser",
+ "state" : {
+ "revision" : "309a47b2b1d9b5e991f36961c983ecec72275be3",
+ "version" : "1.6.1"
+ }
+ }
+ ],
+ "version" : 2
+}
diff --git a/bindings/swift/Package.swift b/bindings/swift/Package.swift
new file mode 100644
index 000000000..27f4fcaeb
--- /dev/null
+++ b/bindings/swift/Package.swift
@@ -0,0 +1,44 @@
+// swift-tools-version: 5.9
+import PackageDescription
+
+let package = Package(
+ name: "Uzu",
+ platforms: [
+ .iOS("26.0"),
+ .macOS("26.0"),
+ ],
+ products: [
+ .library(name: "Uzu", targets: ["Uzu"]),
+ .executable(name: "examples", targets: ["Examples"]),
+ ],
+ dependencies: [
+ .package(url: "https://github.com/apple/swift-argument-parser", from: "1.6.1")
+ ],
+ targets: [
+ .binaryTarget(
+ name: "uzu",
+ path: "uzu.xcframework"
+ ),
+ .target(
+ name: "Uzu",
+ dependencies: ["uzu"],
+ linkerSettings: [
+ .linkedLibrary("c++"),
+ .linkedFramework("SystemConfiguration"),
+ .linkedFramework("Metal"),
+ .linkedFramework("MetalPerformanceShadersGraph"),
+ ]
+ ),
+ .executableTarget(
+ name: "Examples",
+ dependencies: [
+ "Uzu",
+ .product(name: "ArgumentParser", package: "swift-argument-parser"),
+ ]
+ ),
+ .testTarget(
+ name: "UzuTests",
+ dependencies: ["Uzu"],
+ ),
+ ]
+)
diff --git a/bindings/swift/README.md b/bindings/swift/README.md
new file mode 100644
index 000000000..e505c8f1d
--- /dev/null
+++ b/bindings/swift/README.md
@@ -0,0 +1,106 @@
+<p align="center">
+ <picture>
+ <img alt="Mirai" src="https://artifacts.trymirai.com/social/github/uzu-swift-header.jpg" style="max-width: 100%;">
+ </picture>
+</p>
+
+<a href="https://discord.com/invite/trymirai"><img src="https://img.shields.io/discord/1377764166764462120?label=Discord" alt="Discord"></a>
+<a href="mailto:[email protected]?subject=Interested%20in%20Mirai"><img src="https://img.shields.io/badge/Send-Email-green" alt="Contact us"></a>
+<a href="https://docs.trymirai.com/app-integration/overview"><img src="https://img.shields.io/badge/Read-Docs-blue" alt="Read docs"></a>
+[![Swift Version](https://img.shields.io/badge/Swift-5.9-blue)](https://swift.org)
+[![License](https://img.shields.io/badge/License-MIT-blue)](LICENSE)
+
+# uzu-swift
+
+Swift package for [uzu](https://github.com/trymirai/uzu), a **high-performance** inference engine for AI models on Apple Silicon. It allows you to deploy AI directly in your app with **zero latency**, **full data privacy**, and **no inference costs**. You don’t need an ML team or weeks of setup - one developer can handle everything in minutes. Key features:
+
+- Simple, high-level API
+- Specialized configurations with significant performance boosts for common use cases like classification and summarization
+- [Broad model support](https://trymirai.com/models)
+- Observable model manager
+
+## Quick Start
+
+Add the `uzu` dependency to your project:
+
+```swift
+dependencies: [
+ .package(url: "https://github.com/trymirai/uzu-swift.git", from: "{{VERSION}}")
+]
+```
+
+Run the snippet below:
+
+```swift
+// include:Sources/Examples/Snippets.swift#quick-start
+```
+
+Everything from model downloading to inference configuration is handled automatically. Refer to the [documentation](https://docs.trymirai.com) for details on how to customize each step of the process.
+
+## Examples
+
+Run it using one of the following commands:
+
+```bash
+swift run examples chat
+swift run examples summarization
+swift run examples classification
+swift run examples cloud
+swift run examples structured-output
+swift run examples classifier
+swift run examples text-to-speech
+```
+
+### Chat
+
+In this example, we will download a model and get a reply to a specific list of messages:
+
+```swift
+// include:Sources/Examples/Chat.swift
+```
+
+Once loaded, the same `ChatSession` can be reused for multiple requests until you drop it. Each model may consume a significant amount of RAM, so it's important to keep only one session loaded at a time. For iOS apps, we recommend adding the [Increased Memory Capability](https://developer.apple.com/documentation/bundleresources/entitlements/com.apple.developer.kernel.increased-memory-limit) entitlement to ensure your app can allocate the required memory.
+
+### Summarization
+
+In this example, we will use the `summarization` preset to generate a summary of the input text:
+
+```swift
+// include:Sources/Examples/Summarization.swift
+```
+
+You will notice that the model’s run count is lower than the actual number of generated tokens due to speculative decoding, which significantly improves generation speed.
+
+### Classification
+
+In this example, we will use the `classification` preset to determine the sentiment of the user's input:
+
+```swift
+// include:Sources/Examples/Classification.swift
+```
+
+You can view the stats to see that the answer will be ready immediately after the prefill step, and actual generation won’t even start due to speculative decoding, which significantly improves generation speed.
+
+### Cloud
+
+Sometimes you want to create a complex pipeline where some requests are processed on-device and the more complex ones are handled in the cloud using a larger model. With `uzu`, you can do this easily: just choose the cloud model you want to use and perform all requests through the same API:
+
+```swift
+// include:Sources/Examples/Cloud.swift
+```
+
+### Structured Output
+
+Sometimes you want the generated output to be valid JSON with predefined fields. You can use `Grammar` to manually specify a JSON schema, or use a struct annotated with `@Generable` from Apple’s FoundationModels framework.
+
+```swift
+// include:Sources/Examples/StructuredOutput.swift
+```
+
+## Troubleshooting
+
+If you experience any problems, please contact us via [Discord](https://discord.com/invite/trymirai) or [email](mailto:[email protected]).
+
+## License
+
+This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
diff --git a/bindings/swift/Sources/Examples/CLI.swift b/bindings/swift/Sources/Examples/CLI.swift
new file mode 100644
index 000000000..bfb5f2ede
--- /dev/null
+++ b/bindings/swift/Sources/Examples/CLI.swift
@@ -0,0 +1,45 @@
+import ArgumentParser
+import Foundation
+
+@available(macOS 26.0, iOS 26.0, *)
+@main
+struct Example: AsyncParsableCommand {
+ static var configuration = CommandConfiguration(
+ commandName: "examples",
+ abstract: "uzu examples",
+ version: "1.0.0"
+ )
+
+ @Argument(
+ help:
+ "Mode: chat | summarization | classification | quick-start | snippets | cloud | ssm | structured-output | classifier | text-to-speech",
+ transform: { $0.lowercased() })
+ var mode: String = "chat"
+
+ mutating func run() async throws {
+ switch mode {
+ case "chat":
+ try await runChat()
+ case "summarization":
+ try await runSummarization()
+ case "classification":
+ try await runClassification()
+ case "quick-start":
+ try await runQuickStart()
+ case "snippets":
+ try await runSnippets()
+ case "cloud":
+ try await runCloud()
+ case "ssm":
+ try await runSSM()
+ case "structured-output":
+ try await runStructuredOutput()
+ case "classifier":
+ try await runClassifier()
+ case "text-to-speech":
+ try await runTextToSpeech()
+ default:
+ throw ValidationError("Unknown mode: \(mode)")
+ }
+ }
+}
diff --git a/bindings/swift/Sources/Examples/Chat.swift b/bindings/swift/Sources/Examples/Chat.swift
new file mode 100644
index 000000000..6c42a9b91
--- /dev/null
+++ b/bindings/swift/Sources/Examples/Chat.swift
@@ -0,0 +1,33 @@
+import Uzu
+
+public func runChat() async throws {
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "Qwen/Qwen3-0.6B") else {
+ return
+ }
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ let messages = [
+ ChatMessage.system().withText(text: "You are a helpful assistant"),
+ ChatMessage.user().withText(text: "Tell me a short, funny story about a robot")
+ ]
+ let session = try await engine.chat(model: model, config: .create())
+ let stream = await session.replyWithStream(input: messages, config: .create())
+ var message: ChatMessage? = nil
+ for try await update in stream.iterator() {
+ switch update {
+ case .replies(let replies):
+ let reply = replies.last
+ message = reply?.message
+ print("Generated tokens: \(reply?.stats.tokensCountOutput ?? 0)")
+ case .error(let error):
+ print("Error: \(error)")
+ }
+ }
+ print("Reasoning: \(message?.reasoning() ?? "empty")")
+ print("Text: \(message?.text() ?? "empty")")
+}
diff --git a/bindings/swift/Sources/Examples/Classification.swift b/bindings/swift/Sources/Examples/Classification.swift
new file mode 100644
index 000000000..893dea15f
--- /dev/null
+++ b/bindings/swift/Sources/Examples/Classification.swift
@@ -0,0 +1,41 @@
+import Uzu
+
+public func runClassification() async throws {
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "Qwen/Qwen3-0.6B") else {
+ return
+ }
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ let feature = Feature(name: "sentiment", values: [
+ "Happy",
+ "Sad",
+ "Angry",
+ "Fearful",
+ "Surprised",
+ "Disgusted",
+ ])
+ let chatConfig = ChatConfig.create().withSpeculationPreset(speculationPreset: .classification(feature: feature))
+ let session = try await engine.chat(model: model, config: chatConfig)
+
+ let textToDetectFeature =
+ "Today's been awesome! Everything just feels right, and I can't stop smiling."
+ let prompt = "Text is: \"\(textToDetectFeature)\". Choose \(feature.name) from the list: \(feature.values.joined(separator: ", ")). Answer with one word. Don't add a dot at the end."
+ let messages = [
+ ChatMessage.system().withReasoningEffort(reasoningEffort: .disabled),
+ ChatMessage.user().withText(text: prompt)
+ ]
+
+ let chatReplyConfig = ChatReplyConfig.create().withTokenLimit(tokenLimit: 32).withSamplingMethod(samplingMethod: .greedy)
+ let replies = try await session.reply(input: messages, config: chatReplyConfig)
+ guard let reply = replies.last else {
+ return
+ }
+
+ print("Prediction: \(reply.message.text() ?? "empty")")
+ print("Generated tokens: \(reply.stats.tokensCountOutput ?? 0)")
+}
diff --git a/bindings/swift/Sources/Examples/Classifier.swift b/bindings/swift/Sources/Examples/Classifier.swift
new file mode 100644
index 000000000..b3ff3d0af
--- /dev/null
+++ b/bindings/swift/Sources/Examples/Classifier.swift
@@ -0,0 +1,20 @@
+import Uzu
+
+public func runClassifier() async throws {
+ let engine = try await Engine.create(config: .create())
+
+ guard let model = try await engine.model(identifier: "trymirai/chat-moderation-router") else {
+ return
+ }
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ let messages = [
+ ClassificationMessage.user(content: "Hi")
+ ]
+
+ let session = try await engine.classification(model: model)
+ let output = try await session.classify(input: messages)
+ print("Output: \(output.probabilities.values)")
+}
diff --git a/bindings/swift/Sources/Examples/Cloud.swift b/bindings/swift/Sources/Examples/Cloud.swift
new file mode 100644
index 000000000..768543f99
--- /dev/null
+++ b/bindings/swift/Sources/Examples/Cloud.swift
@@ -0,0 +1,24 @@
+import Uzu
+
+public func runCloud() async throws {
+ let engineConfig = EngineConfig.create().withOpenaiApiKey(openaiApiKey: "OPENAI_API_KEY")
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "Qwen/Qwen3-0.6B") else {
+ return
+ }
+
+ let messages = [
+ ChatMessage.system().withReasoningEffort(reasoningEffort: .low),
+ ChatMessage.user().withText(text: "How LLMs work")
+ ]
+
+ let session = try await engine.chat(model: model, config: .create())
+ let reply = try await session.reply(input: messages, config: .create())
+ guard let message = reply.last?.message else {
+ return
+ }
+
+ print("Reasoning: \(message.reasoning() ?? "empty")")
+ print("Text: \(message.text() ?? "empty")")
+}
diff --git a/bindings/swift/Sources/Examples/QuickStart.swift b/bindings/swift/Sources/Examples/QuickStart.swift
new file mode 100644
index 000000000..ec233d3f4
--- /dev/null
+++ b/bindings/swift/Sources/Examples/QuickStart.swift
@@ -0,0 +1,29 @@
+import Uzu
+
+public func runQuickStart() async throws {
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "Qwen/Qwen3-0.6B") else {
+ return
+ }
+
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ let session = try await engine.chat(model: model, config: .create())
+
+ let messages = [
+ ChatMessage.system().withText(text: "You are a helpful assistant"),
+ ChatMessage.user().withText(text: "Tell me a short, funny story about a robot")
+ ]
+
+ let reply = try await session.reply(input: messages, config: .create())
+ guard let message = reply.last?.message else {
+ return
+ }
+
+ print("Reasoning: \(message.reasoning() ?? "empty")")
+ print("Text: \(message.text() ?? "empty")")
+}
diff --git a/bindings/swift/Sources/Examples/SSM.swift b/bindings/swift/Sources/Examples/SSM.swift
new file mode 100644
index 000000000..75cb53052
--- /dev/null
+++ b/bindings/swift/Sources/Examples/SSM.swift
@@ -0,0 +1,25 @@
+import Uzu
+
+public func runSSM() async throws {
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "cartesia-ai/Llamba-1B-4bit-mlx") else {
+ return
+ }
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ let messages = [
+ ChatMessage.user().withText(text: "Tell me a short, funny story about a robot")
+ ]
+
+ let session = try await engine.chat(model: model, config: .create())
+ let reply = try await session.reply(input: messages, config: .create())
+ guard let message = reply.last?.message else {
+ return
+ }
+
+ print("Text: \(message.text() ?? "empty")")
+}
diff --git a/bindings/swift/Sources/Examples/Snippets.swift b/bindings/swift/Sources/Examples/Snippets.swift
new file mode 100644
index 000000000..05d43b26c
--- /dev/null
+++ b/bindings/swift/Sources/Examples/Snippets.swift
@@ -0,0 +1,161 @@
+import Uzu
+
+@MainActor public func exampleQuickStart() async throws {
+ // snippet:quick-start
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "Qwen/Qwen3-0.6B") else {
+ return
+ }
+
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ let session = try await engine.chat(model: model, config: .create())
+
+ let messages = [
+ ChatMessage.system().withText(text: "You are a helpful assistant"),
+ ChatMessage.user().withText(text: "Tell me a short, funny story about a robot")
+ ]
+
+ let reply = try await session.reply(input: messages, config: .create())
+ guard let message = reply.last?.message else {
+ return
+ }
+ // endsnippet:quick-start
+
+ print("Reasoning: \(message.reasoning() ?? "empty")")
+ print("Text: \(message.text() ?? "empty")")
+}
+
+@MainActor public func exampleChat() async throws {
+ // snippet:engine-create
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+ // endsnippet:engine-create
+
+ // snippet:model-choose
+ guard let model = try await engine.model(identifier: "Qwen/Qwen3-0.6B") else {
+ return
+ }
+ // endsnippet:model-choose
+
+ // snippet:model-download
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+ // endsnippet:model-download
+
+ // snippet:session-create-general
+ let session = try await engine.chat(model: model, config: .create())
+ // endsnippet:session-create-general
+
+ // snippet:session-input-general
+ let messages = [
+ ChatMessage.system().withText(text: "You are a helpful assistant"),
+ ChatMessage.user().withText(text: "Tell me a short, funny story about a robot")
+ ]
+ // endsnippet:session-input-general
+
+ // snippet:session-run-general
+ let reply = try await session.reply(input: messages, config: .create())
+ guard let message = reply.last?.message else {
+ return
+ }
+ // endsnippet:session-run-general
+
+ print("Reasoning: \(message.reasoning() ?? "empty")")
+ print("Text: \(message.text() ?? "empty")")
+}
+
+@MainActor public func exampleSummarization() async throws {
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "Qwen/Qwen3-0.6B") else {
+ return
+ }
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ // snippet:session-input-summarization
+ let textToSummarize = "A Large Language Model (LLM) is a type of artificial intelligence that processes and generates human-like text. It is trained on vast datasets containing books, articles, and web content, allowing it to understand and predict language patterns. LLMs use deep learning, particularly transformer-based architectures, to analyze text, recognize context, and generate coherent responses. These models have a wide range of applications, including chatbots, content creation, translation, and code generation. One of the key strengths of LLMs is their ability to generate contextually relevant text based on prompts. They utilize self-attention mechanisms to weigh the importance of words within a sentence, improving accuracy and fluency. Examples of popular LLMs include OpenAI's GPT series, Google's BERT, and Meta's LLaMA. As these models grow in size and sophistication, they continue to enhance human-computer interactions, making AI-powered communication more natural and effective.";
+ let prompt = "Text is: \"\(textToSummarize)\". Write only summary itself."
+ let messages = [
+ ChatMessage.system().withReasoningEffort(reasoningEffort: .disabled),
+ ChatMessage.user().withText(text: prompt)
+ ]
+ // endsnippet:session-input-summarization
+
+ // snippet:session-create-summarization
+ let chatConfig = ChatConfig.create().withSpeculationPreset(speculationPreset: .summarization)
+ let session = try await engine.chat(model: model, config: chatConfig)
+ // endsnippet:session-create-summarization
+
+ // snippet:session-run-summarization
+ let chatReplyConfig = ChatReplyConfig.create().withTokenLimit(tokenLimit: 256).withSamplingMethod(samplingMethod: .greedy)
+ let replies = try await session.reply(input: messages, config: chatReplyConfig)
+ guard let reply = replies.last else {
+ return
+ }
+ // endsnippet:session-run-summarization
+
+ print("Summary: \(reply.message.text() ?? "empty")")
+ print("Generation t\\s: \(reply.stats.generateTokensPerSecond ?? 0.0)")
+}
+
+@MainActor public func exampleClassification() async throws {
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "Qwen/Qwen3-0.6B") else {
+ return
+ }
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ // snippet:session-create-classification
+ let feature = Feature(name: "sentiment", values: [
+ "Happy",
+ "Sad",
+ "Angry",
+ "Fearful",
+ "Surprised",
+ "Disgusted",
+ ])
+ let chatConfig = ChatConfig.create().withSpeculationPreset(speculationPreset: .classification(feature: feature))
+ let session = try await engine.chat(model: model, config: chatConfig)
+ // endsnippet:session-create-classification
+
+ // snippet:session-input-classification
+ let textToDetectFeature =
+ "Today's been awesome! Everything just feels right, and I can't stop smiling."
+ let prompt = "Text is: \"\(textToDetectFeature)\". Choose \(feature.name) from the list: \(feature.values.joined(separator: ", ")). Answer with one word. Don't add a dot at the end."
+ let messages = [
+ ChatMessage.system().withReasoningEffort(reasoningEffort: .disabled),
+ ChatMessage.user().withText(text: prompt)
+ ]
+ // endsnippet:session-input-classification
+
+ // snippet:session-run-classification
+ let chatReplyConfig = ChatReplyConfig.create().withTokenLimit(tokenLimit: 32).withSamplingMethod(samplingMethod: .greedy)
+ let replies = try await session.reply(input: messages, config: chatReplyConfig)
+ guard let reply = replies.last else {
+ return
+ }
+ // endsnippet:session-run-classification
+
+ print("Prediction: \(reply.message.text() ?? "empty")")
+ print("Generated tokens: \(reply.stats.tokensCountOutput ?? 0)")
+}
+
+@MainActor public func runSnippets() async throws {
+ try await exampleQuickStart()
+ try await exampleChat()
+ try await exampleSummarization()
+ try await exampleClassification()
+}
diff --git a/bindings/swift/Sources/Examples/StructuredOutput.swift b/bindings/swift/Sources/Examples/StructuredOutput.swift
new file mode 100644
index 000000000..9ce54dc41
--- /dev/null
+++ b/bindings/swift/Sources/Examples/StructuredOutput.swift
@@ -0,0 +1,35 @@
+import FoundationModels
+import Uzu
+
+@Generable()
+struct Country: Codable {
+ let name: String
+ let capital: String
+}
+
+public func runStructuredOutput() async throws {
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "Qwen/Qwen3-0.6B") else {
+ return
+ }
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ let messages = [
+ ChatMessage.system().withReasoningEffort(reasoningEffort: .disabled),
+ ChatMessage.user().withText(text: "Give me a JSON object containing a list of 3 countries, where each country has name and capital fields")
+ ]
+
+ let session = try await engine.chat(model: model, config: .create())
+ let reply = try await session.reply(input: messages, config: .create().withGrammar(grammar: .fromType([Country].self)))
+ guard let message = reply.last?.message else {
+ return
+ }
+ guard let countries: [Country] = message.textDecoded() else {
+ return
+ }
+ print(countries)
+}
diff --git a/bindings/swift/Sources/Examples/Summarization.swift b/bindings/swift/Sources/Examples/Summarization.swift
new file mode 100644
index 000000000..b761aecc9
--- /dev/null
+++ b/bindings/swift/Sources/Examples/Summarization.swift
@@ -0,0 +1,32 @@
+import Uzu
+
+public func runSummarization() async throws {
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "Qwen/Qwen3-0.6B") else {
+ return
+ }
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ let textToSummarize = "A Large Language Model (LLM) is a type of artificial intelligence that processes and generates human-like text. It is trained on vast datasets containing books, articles, and web content, allowing it to understand and predict language patterns. LLMs use deep learning, particularly transformer-based architectures, to analyze text, recognize context, and generate coherent responses. These models have a wide range of applications, including chatbots, content creation, translation, and code generation. One of the key strengths of LLMs is their ability to generate contextually relevant text based on prompts. They utilize self-attention mechanisms to weigh the importance of words within a sentence, improving accuracy and fluency. Examples of popular LLMs include OpenAI's GPT series, Google's BERT, and Meta's LLaMA. As these models grow in size and sophistication, they continue to enhance human-computer interactions, making AI-powered communication more natural and effective.";
+ let prompt = "Text is: \"\(textToSummarize)\". Write only summary itself."
+ let messages = [
+ ChatMessage.system().withReasoningEffort(reasoningEffort: .disabled),
+ ChatMessage.user().withText(text: prompt)
+ ]
+
+ let chatConfig = ChatConfig.create().withSpeculationPreset(speculationPreset: .summarization)
+ let session = try await engine.chat(model: model, config: chatConfig)
+
+ let chatReplyConfig = ChatReplyConfig.create().withTokenLimit(tokenLimit: 256).withSamplingMethod(samplingMethod: .greedy)
+ let replies = try await session.reply(input: messages, config: chatReplyConfig)
+ guard let reply = replies.last else {
+ return
+ }
+
+ print("Summary: \(reply.message.text() ?? "empty")")
+ print("Generation t\\s: \(reply.stats.generateTokensPerSecond ?? 0.0)")
+}
diff --git a/bindings/swift/Sources/Examples/TextToSpeech.swift b/bindings/swift/Sources/Examples/TextToSpeech.swift
new file mode 100644
index 000000000..9e0883059
--- /dev/null
+++ b/bindings/swift/Sources/Examples/TextToSpeech.swift
@@ -0,0 +1,23 @@
+import Foundation
+import Uzu
+
+public func runTextToSpeech() async throws {
+ let engineConfig = EngineConfig.create()
+ let engine = try await Engine.create(config: engineConfig)
+
+ guard let model = try await engine.model(identifier: "fishaudio/s1-mini") else {
+ return
+ }
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ let text = "London is the capital of United Kingdom and one of the world’s most influential cities, known for its rich history, cultural diversity, and global significance in finance, politics, and the arts. Situated along the River Thames, the city blends historic landmarks like Tower of London and Buckingham Palace with modern architecture such as The Shard. London is also home to renowned institutions including the British Museum and vibrant areas like Covent Garden, offering a mix of history, entertainment, and innovation that attracts millions of visitors each year."
+ let outputPath = FileManager.default.homeDirectoryForCurrentUser
+ .appendingPathComponent("Desktop")
+ .appendingPathComponent("output.wav")
+ let session = try await engine.textToSpeech(model: model)
+ let pcmBatch = try await session.synthesize(input: text)
+ try pcmBatch.saveAsWav(path: outputPath.path())
+ print("Output saved to: \(outputPath.path())")
+}
diff --git a/bindings/swift/Sources/Uzu/EngineObservableWrapper.swift b/bindings/swift/Sources/Uzu/EngineObservableWrapper.swift
new file mode 100644
index 000000000..4437f6d27
--- /dev/null
+++ b/bindings/swift/Sources/Uzu/EngineObservableWrapper.swift
@@ -0,0 +1,35 @@
+import Observation
+import Foundation
+import uzuFFI
+
+public final class EngineObservableWrapper: @unchecked Sendable, ObservableObject {
+ @Published public private(set) var engine: Engine?
+ @Published public private(set) var models: [Model] = []
+ @Published public private(set) var downloadStates: [String: DownloadState] = [:]
+
+ public init(config: EngineConfig) {
+ Task { [weak self] in
+ do {
+ let engine = try await Engine.create(config: config)
+ try await engine.registerCallback(callback: .create { [weak self] in
+ self?.updateState()
+ })
+ await MainActor.run { [weak self] in
+ self?.engine = engine
+ self?.updateState()
+ }
+ } catch {}
+ }
+ }
+
+ func updateState() {
+ Task.detached { [weak self] in
+ let models = try await self?.engine?.models() ?? []
+ let downloadStates = await self?.engine?.downloadStates() ?? [:]
+ DispatchQueue.main.async { [weak self] in
+ self?.models = models
+ self?.downloadStates = downloadStates
+ }
+ }
+ }
+}
diff --git a/bindings/swift/Sources/Uzu/Extensions/ChatMessage.swift b/bindings/swift/Sources/Uzu/Extensions/ChatMessage.swift
new file mode 100644
index 000000000..43cbe022d
--- /dev/null
+++ b/bindings/swift/Sources/Uzu/Extensions/ChatMessage.swift
@@ -0,0 +1,13 @@
+import Foundation
+
+extension ChatMessage {
+ public func textDecoded<T: Decodable>() -> T? {
+ guard let text = self.text() else {
+ return nil
+ }
+ let decoder = JSONDecoder()
+ let jsonData = Data(text.utf8)
+ let entity = try? decoder.decode(T.self, from: jsonData)
+ return entity
+ }
+}
diff --git a/bindings/swift/Sources/Uzu/Extensions/Grammar.swift b/bindings/swift/Sources/Uzu/Extensions/Grammar.swift
new file mode 100644
index 000000000..2a157b6e6
--- /dev/null
+++ b/bindings/swift/Sources/Uzu/Extensions/Grammar.swift
@@ -0,0 +1,9 @@
+import FoundationModels
+
+extension Grammar {
+ public static func fromType<T: Generable>(_ type: T.Type) -> Self {
+ let schema = T.generationSchema.debugDescription
+ let result = Grammar.jsonSchema(schema: schema)
+ return result
+ }
+}
diff --git a/bindings/swift/Sources/Uzu/Generated/Extensions.swift b/bindings/swift/Sources/Uzu/Generated/Extensions.swift
new file mode 100644
index 000000000..f87870465
--- /dev/null
+++ b/bindings/swift/Sources/Uzu/Generated/Extensions.swift
@@ -0,0 +1,186 @@
+// Auto-generated by cli-release — do not edit.
+
+extension CancelToken {
+ public static func create() -> CancelToken {
+ cancelTokenCreate()
+ }
+}
+
+extension ChatConfig {
+ public static func create() -> ChatConfig {
+ chatConfigCreate()
+ }
+}
+
+extension ChatMessage {
+ public static func assistant() -> ChatMessage {
+ chatMessageAssistant()
+ }
+}
+
+extension ChatMessage {
+ public static func developer() -> ChatMessage {
+ chatMessageDeveloper()
+ }
+}
+
+extension ChatMessage {
+ public static func forRole(role: ChatRole) -> ChatMessage {
+ chatMessageForRole(role: role)
+ }
+}
+
+extension ChatMessage {
+ public static func system() -> ChatMessage {
+ chatMessageSystem()
+ }
+}
+
+extension ChatMessage {
+ public static func tool() -> ChatMessage {
+ chatMessageTool()
+ }
+}
+
+extension ChatMessage {
+ public static func user() -> ChatMessage {
+ chatMessageUser()
+ }
+}
+
+extension ChatReplyConfig {
+ public static func create() -> ChatReplyConfig {
+ chatReplyConfigCreate()
+ }
+}
+
+extension ClassificationMessage {
+ public static func assistant(content: String) -> ClassificationMessage {
+ classificationMessageAssistant(content: content)
+ }
+}
+
+extension ClassificationMessage {
+ public static func user(content: String) -> ClassificationMessage {
+ classificationMessageUser(content: content)
+ }
+}
+
+extension Device {
+ public static func create() throws -> Device {
+ try deviceCreate()
+ }
+}
+
+extension Engine {
+ public static func create(config: EngineConfig) async throws -> Engine {
+ try await engineCreate(config: config)
+ }
+}
+
+extension EngineConfig {
+ public static func create() -> EngineConfig {
+ engineConfigCreate()
+ }
+}
+
+extension Keyring {
+ public static func create() throws -> Keyring {
+ try keyringCreate()
+ }
+}
+
+extension Metadata {
+ public static func external(name: String) -> Metadata {
+ metadataExternal(name: name)
+ }
+}
+
+extension Model {
+ public static func external(identifier: String, registryIdentifier: String, registryName: String, backendIdentifier: String, backendName: String, backendVersion: String, specializations: [ModelSpecialization], accessibility: ModelAccessibility) -> Model {
+ modelExternal(identifier: identifier, registryIdentifier: registryIdentifier, registryName: registryName, backendIdentifier: backendIdentifier, backendName: backendName, backendVersion: backendVersion, specializations: specializations, accessibility: accessibility)
+ }
+}
+
+extension EngineCallback {
+ public typealias Closure = @Sendable () -> Void
+
+ private final class EngineCallbackHandlerClosureWrapper: Sendable, EngineCallbackHandler {
+ private let closure: Closure
+
+ init(closure: @escaping Closure) {
+ self.closure = closure
+ }
+
+ func onEvent() {
+ closure()
+ }
+ }
+
+ public static func create(closure: @escaping Closure) -> EngineCallback {
+ EngineCallback.create(handler: EngineCallbackHandlerClosureWrapper(closure: closure))
+ }
+}
+
+extension ChatSessionStream {
+ public func iterator() -> AsyncThrowingStream<ChatSessionStreamChunk, Swift.Error> {
+ AsyncThrowingStream<ChatSessionStreamChunk, Swift.Error> { continuation in
+ let task = Task {
+ while !Task.isCancelled {
+ let item = await self.next()
+ guard let item else {
+ continuation.finish()
+ break
+ }
+ continuation.yield(item)
+ }
+ }
+ continuation.onTermination = { [weak self] _ in
+ task.cancel()
+ self?.cancelToken().cancel()
+ }
+ }
+ }
+}
+
+extension DownloaderStream {
+ public func iterator() -> AsyncThrowingStream<DownloaderStreamUpdate, Swift.Error> {
+ AsyncThrowingStream<DownloaderStreamUpdate, Swift.Error> { continuation in
+ let task = Task {
+ while !Task.isCancelled {
+ let item = await self.next()
+ guard let item else {
+ continuation.finish()
+ break
+ }
+ continuation.yield(item)
+ }
+ }
+ continuation.onTermination = { _ in
+ task.cancel()
+ }
+ }
+ }
+}
+
+extension TextToSpeechSessionStream {
+ public func iterator() -> AsyncThrowingStream<TextToSpeechSessionStreamChunk, Swift.Error> {
+ AsyncThrowingStream<TextToSpeechSessionStreamChunk, Swift.Error> { continuation in
+ let task = Task {
+ while !Task.isCancelled {
+ let item = await self.next()
+ guard let item else {
+ continuation.finish()
+ break
+ }
+ continuation.yield(item)
+ }
+ }
+ continuation.onTermination = { [weak self] _ in
+ task.cancel()
+ self?.cancelToken().cancel()
+ }
+ }
+ }
+}
+
diff --git a/bindings/swift/Sources/Uzu/Generated/uzu/nagare.swift b/bindings/swift/Sources/Uzu/Generated/uzu/nagare.swift
new file mode 100644
index 000000000..a3f34e5e8
--- /dev/null
+++ b/bindings/swift/Sources/Uzu/Generated/uzu/nagare.swift
@@ -0,0 +1,2106 @@
+// This file was autogenerated by some hot garbage in the `uniffi` crate.
+// Trust me, you don't want to mess with it!
+
+// swiftlint:disable all
+import Foundation
+
+// Depending on the consumer's build setup, the low-level FFI code
+// might be in a separate module, or it might be compiled inline into
+// this module. This is a bit of light hackery to work with both.
+#if canImport(nagareFFI)
+import nagareFFI
+#endif
+
+fileprivate extension RustBuffer {
+ // Allocate a new buffer, copying the contents of a `UInt8` array.
+ init(bytes: [UInt8]) {
+ let rbuf = bytes.withUnsafeBufferPointer { ptr in
+ RustBuffer.from(ptr)
+ }
+ self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data)
+ }
+
+ static func empty() -> RustBuffer {
+ RustBuffer(capacity: 0, len:0, data: nil)
+ }
+
+ static func from(_ ptr: UnsafeBufferPointer<UInt8>) -> RustBuffer {
+ try! rustCall { ffi_nagare_rustbuffer_from_bytes(ForeignBytes(bufferPointer: ptr), $0) }
+ }
+
+ // Frees the buffer in place.
+ // The buffer must not be used after this is called.
+ func deallocate() {
+ try! rustCall { ffi_nagare_rustbuffer_free(self, $0) }
+ }
+}
+
+fileprivate extension ForeignBytes {
+ init(bufferPointer: UnsafeBufferPointer<UInt8>) {
+ self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress)
+ }
+}
+
+// For every type used in the interface, we provide helper methods for conveniently
+// lifting and lowering that type from C-compatible data, and for reading and writing
+// values of that type in a buffer.
+
+// Helper classes/extensions that don't change.
+// Someday, this will be in a library of its own.
+
+fileprivate extension Data {
+ init(rustBuffer: RustBuffer) {
+ self.init(
+ bytesNoCopy: rustBuffer.data!,
+ count: Int(rustBuffer.len),
+ deallocator: .none
+ )
+ }
+}
+
+// Define reader functionality. Normally this would be defined in a class or
+// struct, but we use standalone functions instead in order to make external
+// types work.
+//
+// With external types, one swift source file needs to be able to call the read
+// method on another source file's FfiConverter, but then what visibility
+// should Reader have?
+// - If Reader is fileprivate, then this means the read() must also
+// be fileprivate, which doesn't work with external types.
+// - If Reader is internal/public, we'll get compile errors since both source
+// files will try define the same type.
+//
+// Instead, the read() method and these helper functions input a tuple of data
+
+fileprivate func createReader(data: Data) -> (data: Data, offset: Data.Index) {
+ (data: data, offset: 0)
+}
+
+// Reads an integer at the current offset, in big-endian order, and advances
+// the offset on success. Throws if reading the integer would move the
+// offset past the end of the buffer.
+fileprivate func readInt<T: FixedWidthInteger>(_ reader: inout (data: Data, offset: Data.Index)) throws -> T {
+ let range = reader.offset..<reader.offset + MemoryLayout<T>.size
+ guard reader.data.count >= range.upperBound else {
+ throw UniffiInternalError.bufferOverflow
+ }
+ if T.self == UInt8.self {
+ let value = reader.data[reader.offset]
+ reader.offset += 1
+ return value as! T
+ }
+ var value: T = 0
+ let _ = withUnsafeMutableBytes(of: &value, { reader.data.copyBytes(to: $0, from: range)})
+ reader.offset = range.upperBound
+ return value.bigEndian
+}
+
+// Reads an arbitrary number of bytes, to be used to read
+// raw bytes, this is useful when lifting strings
+fileprivate func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> Array<UInt8> {
+ let range = reader.offset..<(reader.offset+count)
+ guard reader.data.count >= range.upperBound else {
+ throw UniffiInternalError.bufferOverflow
+ }
+ var value = [UInt8](repeating: 0, count: count)
+ value.withUnsafeMutableBufferPointer({ buffer in
+ reader.data.copyBytes(to: buffer, from: range)
+ })
+ reader.offset = range.upperBound
+ return value
+}
+
+// Reads a float at the current offset.
+fileprivate func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {
+ return Float(bitPattern: try readInt(&reader))
+}
+
+// Reads a float at the current offset.
+fileprivate func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {
+ return Double(bitPattern: try readInt(&reader))
+}
+
+// Indicates if the offset has reached the end of the buffer.
+fileprivate func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool {
+ return reader.offset < reader.data.count
+}
+
+// Define writer functionality. Normally this would be defined in a class or
+// struct, but we use standalone functions instead in order to make external
+// types work. See the above discussion on Readers for details.
+
+fileprivate func createWriter() -> [UInt8] {
+ return []
+}
+
+fileprivate func writeBytes<S>(_ writer: inout [UInt8], _ byteArr: S) where S: Sequence, S.Element == UInt8 {
+ writer.append(contentsOf: byteArr)
+}
+
+// Writes an integer in big-endian order.
+//
+// Warning: make sure what you are trying to write
+// is in the correct type!
+fileprivate func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {
+ var value = value.bigEndian
+ withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }
+}
+
+fileprivate func writeFloat(_ writer: inout [UInt8], _ value: Float) {
+ writeInt(&writer, value.bitPattern)
+}
+
+fileprivate func writeDouble(_ writer: inout [UInt8], _ value: Double) {
+ writeInt(&writer, value.bitPattern)
+}
+
+// Protocol for types that transfer other types across the FFI. This is
+// analogous to the Rust trait of the same name.
+fileprivate protocol FfiConverter {
+ associatedtype FfiType
+ associatedtype SwiftType
+
+ static func lift(_ value: FfiType) throws -> SwiftType
+ static func lower(_ value: SwiftType) -> FfiType
+ static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType
+ static func write(_ value: SwiftType, into buf: inout [UInt8])
+}
+
+// Types conforming to `Primitive` pass themselves directly over the FFI.
+fileprivate protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType { }
+
+extension FfiConverterPrimitive {
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ value: FfiType) throws -> SwiftType {
+ return value
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ value: SwiftType) -> FfiType {
+ return value
+ }
+}
+
+// Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`.
+// Used for complex types where it's hard to write a custom lift/lower.
+fileprivate protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {}
+
+extension FfiConverterRustBuffer {
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ buf: RustBuffer) throws -> SwiftType {
+ var reader = createReader(data: Data(rustBuffer: buf))
+ let value = try read(from: &reader)
+ if hasRemaining(reader) {
+ throw UniffiInternalError.incompleteData
+ }
+ buf.deallocate()
+ return value
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ value: SwiftType) -> RustBuffer {
+ var writer = createWriter()
+ write(value, into: &writer)
+ return RustBuffer(bytes: writer)
+ }
+}
+// An error type for FFI errors. These errors occur at the UniFFI level, not
+// the library level.
+fileprivate enum UniffiInternalError: LocalizedError {
+ case bufferOverflow
+ case incompleteData
+ case unexpectedOptionalTag
+ case unexpectedEnumCase
+ case unexpectedNullPointer
+ case unexpectedRustCallStatusCode
+ case unexpectedRustCallError
+ case unexpectedStaleHandle
+ case rustPanic(_ message: String)
+
+ public var errorDescription: String? {
+ switch self {
+ case .bufferOverflow: return "Reading the requested value would read past the end of the buffer"
+ case .incompleteData: return "The buffer still has data after lifting its containing value"
+ case .unexpectedOptionalTag: return "Unexpected optional tag; should be 0 or 1"
+ case .unexpectedEnumCase: return "Raw enum value doesn't match any cases"
+ case .unexpectedNullPointer: return "Raw pointer value was null"
+ case .unexpectedRustCallStatusCode: return "Unexpected RustCallStatus code"
+ case .unexpectedRustCallError: return "CALL_ERROR but no errorClass specified"
+ case .unexpectedStaleHandle: return "The object in the handle map has been dropped already"
+ case let .rustPanic(message): return message
+ }
+ }
+}
+
+fileprivate extension NSLock {
+ func withLock<T>(f: () throws -> T) rethrows -> T {
+ self.lock()
+ defer { self.unlock() }
+ return try f()
+ }
+}
+
+fileprivate let CALL_SUCCESS: Int8 = 0
+fileprivate let CALL_ERROR: Int8 = 1
+fileprivate let CALL_UNEXPECTED_ERROR: Int8 = 2
+fileprivate let CALL_CANCELLED: Int8 = 3
+
+fileprivate extension RustCallStatus {
+ init() {
+ self.init(
+ code: CALL_SUCCESS,
+ errorBuf: RustBuffer.init(
+ capacity: 0,
+ len: 0,
+ data: nil
+ )
+ )
+ }
+}
+
+private func rustCall<T>(_ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
+ let neverThrow: ((RustBuffer) throws -> Never)? = nil
+ return try makeRustCall(callback, errorHandler: neverThrow)
+}
+
+private func rustCallWithError<T, E: Swift.Error>(
+ _ errorHandler: @escaping (RustBuffer) throws -> E,
+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
+ try makeRustCall(callback, errorHandler: errorHandler)
+}
+
+private func makeRustCall<T, E: Swift.Error>(
+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T,
+ errorHandler: ((RustBuffer) throws -> E)?
+) throws -> T {
+ uniffiEnsureNagareInitialized()
+ var callStatus = RustCallStatus.init()
+ let returnedVal = callback(&callStatus)
+ try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler)
+ return returnedVal
+}
+
+private func uniffiCheckCallStatus<E: Swift.Error>(
+ callStatus: RustCallStatus,
+ errorHandler: ((RustBuffer) throws -> E)?
+) throws {
+ switch callStatus.code {
+ case CALL_SUCCESS:
+ return
+
+ case CALL_ERROR:
+ if let errorHandler = errorHandler {
+ throw try errorHandler(callStatus.errorBuf)
+ } else {
+ callStatus.errorBuf.deallocate()
+ throw UniffiInternalError.unexpectedRustCallError
+ }
+
+ case CALL_UNEXPECTED_ERROR:
+ // When the rust code sees a panic, it tries to construct a RustBuffer
+ // with the message. But if that code panics, then it just sends back
+ // an empty buffer.
+ if callStatus.errorBuf.len > 0 {
+ throw UniffiInternalError.rustPanic(try FfiConverterString.lift(callStatus.errorBuf))
+ } else {
+ callStatus.errorBuf.deallocate()
+ throw UniffiInternalError.rustPanic("Rust panic")
+ }
+
+ case CALL_CANCELLED:
+ fatalError("Cancellation not supported yet")
+
+ default:
+ throw UniffiInternalError.unexpectedRustCallStatusCode
+ }
+}
+
+private func uniffiTraitInterfaceCall<T>(
+ callStatus: UnsafeMutablePointer<RustCallStatus>,
+ makeCall: () throws -> T,
+ writeReturn: (T) -> ()
+) {
+ do {
+ try writeReturn(makeCall())
+ } catch let error {
+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR
+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
+ }
+}
+
+private func uniffiTraitInterfaceCallWithError<T, E>(
+ callStatus: UnsafeMutablePointer<RustCallStatus>,
+ makeCall: () throws -> T,
+ writeReturn: (T) -> (),
+ lowerError: (E) -> RustBuffer
+) {
+ do {
+ try writeReturn(makeCall())
+ } catch let error as E {
+ callStatus.pointee.code = CALL_ERROR
+ callStatus.pointee.errorBuf = lowerError(error)
+ } catch {
+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR
+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
+ }
+}
+// Initial value and increment amount for handles.
+// These ensure that SWIFT handles always have the lowest bit set
+fileprivate let UNIFFI_HANDLEMAP_INITIAL: UInt64 = 1
+fileprivate let UNIFFI_HANDLEMAP_DELTA: UInt64 = 2
+
+fileprivate final class UniffiHandleMap<T>: @unchecked Sendable {
+ // All mutation happens with this lock held, which is why we implement @unchecked Sendable.
+ private let lock = NSLock()
+ private var map: [UInt64: T] = [:]
+ private var currentHandle: UInt64 = UNIFFI_HANDLEMAP_INITIAL
+
+ func insert(obj: T) -> UInt64 {
+ lock.withLock {
+ return doInsert(obj)
+ }
+ }
+
+ // Low-level insert function, this assumes `lock` is held.
+ private func doInsert(_ obj: T) -> UInt64 {
+ let handle = currentHandle
+ currentHandle += UNIFFI_HANDLEMAP_DELTA
+ map[handle] = obj
+ return handle
+ }
+
+ func get(handle: UInt64) throws -> T {
+ try lock.withLock {
+ guard let obj = map[handle] else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return obj
+ }
+ }
+
+ func clone(handle: UInt64) throws -> UInt64 {
+ try lock.withLock {
+ guard let obj = map[handle] else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return doInsert(obj)
+ }
+ }
+
+ @discardableResult
+ func remove(handle: UInt64) throws -> T {
+ try lock.withLock {
+ guard let obj = map.removeValue(forKey: handle) else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return obj
+ }
+ }
+
+ var count: Int {
+ get {
+ map.count
+ }
+ }
+}
+
+
+// Public interface members begin here.
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterString: FfiConverter {
+ typealias SwiftType = String
+ typealias FfiType = RustBuffer
+
+ public static func lift(_ value: RustBuffer) throws -> String {
+ defer {
+ value.deallocate()
+ }
+ if value.data == nil {
+ return String()
+ }
+ let bytes = UnsafeBufferPointer<UInt8>(start: value.data!, count: Int(value.len))
+ return String(bytes: bytes, encoding: String.Encoding.utf8)!
+ }
+
+ public static func lower(_ value: String) -> RustBuffer {
+ return value.utf8CString.withUnsafeBufferPointer { ptr in
+ // The swift string gives us int8_t, we want uint8_t.
+ ptr.withMemoryRebound(to: UInt8.self) { ptr in
+ // The swift string gives us a trailing null byte, we don't want it.
+ let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1))
+ return RustBuffer.from(buf)
+ }
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {
+ let len: Int32 = try readInt(&buf)
+ return String(bytes: try readBytes(&buf, count: Int(len)), encoding: String.Encoding.utf8)!
+ }
+
+ public static func write(_ value: String, into buf: inout [UInt8]) {
+ let len = Int32(value.utf8.count)
+ writeInt(&buf, len)
+ writeBytes(&buf, value.utf8)
+ }
+}
+
+
+
+
+public protocol ChatSessionProtocol: AnyObject, Sendable {
+
+ func messages() async -> [ChatMessage]
+
+ func reply(input: [ChatMessage], config: ChatReplyConfig) async throws -> [ChatReply]
+
+ func replyWithStream(input: [ChatMessage], config: ChatReplyConfig) async -> ChatSessionStream
+
+ func reset() async throws
+
+ func state() async -> ChatSessionState
+
+}
+open class ChatSession: ChatSessionProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_nagare_fn_clone_chatsession(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_nagare_fn_free_chatsession(handle, $0) }
+ }
+
+
+
+
+open func messages()async -> [ChatMessage] {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_chatsession_messages(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_rust_buffer,
+ completeFunc: ffi_nagare_rust_future_complete_rust_buffer,
+ freeFunc: ffi_nagare_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeChatMessage.lift,
+ errorHandler: nil
+
+ )
+}
+
+open func reply(input: [ChatMessage], config: ChatReplyConfig)async throws -> [ChatReply] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_chatsession_reply(
+ self.uniffiCloneHandle(),
+ FfiConverterSequenceTypeChatMessage.lower(input),FfiConverterTypeChatReplyConfig_lower(config)
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_rust_buffer,
+ completeFunc: ffi_nagare_rust_future_complete_rust_buffer,
+ freeFunc: ffi_nagare_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeChatReply.lift,
+ errorHandler: FfiConverterTypeChatSessionError_lift
+ )
+}
+
+open func replyWithStream(input: [ChatMessage], config: ChatReplyConfig)async -> ChatSessionStream {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_chatsession_reply_with_stream(
+ self.uniffiCloneHandle(),
+ FfiConverterSequenceTypeChatMessage.lower(input),FfiConverterTypeChatReplyConfig_lower(config)
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_u64,
+ completeFunc: ffi_nagare_rust_future_complete_u64,
+ freeFunc: ffi_nagare_rust_future_free_u64,
+ liftFunc: FfiConverterTypeChatSessionStream_lift,
+ errorHandler: nil
+
+ )
+}
+
+open func reset()async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_chatsession_reset(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_void,
+ completeFunc: ffi_nagare_rust_future_complete_void,
+ freeFunc: ffi_nagare_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeChatSessionError_lift
+ )
+}
+
+open func state()async -> ChatSessionState {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_chatsession_state(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_rust_buffer,
+ completeFunc: ffi_nagare_rust_future_complete_rust_buffer,
+ freeFunc: ffi_nagare_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeChatSessionState_lift,
+ errorHandler: nil
+
+ )
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatSession: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = ChatSession
+
+ public static func lift(_ handle: UInt64) throws -> ChatSession {
+ return ChatSession(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: ChatSession) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatSession {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: ChatSession, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSession_lift(_ handle: UInt64) throws -> ChatSession {
+ return try FfiConverterTypeChatSession.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSession_lower(_ value: ChatSession) -> UInt64 {
+ return FfiConverterTypeChatSession.lower(value)
+}
+
+
+
+
+
+
+public protocol ChatSessionStreamProtocol: AnyObject, Sendable {
+
+ func cancelToken() -> CancelToken
+
+ func next() async -> ChatSessionStreamChunk?
+
+}
+open class ChatSessionStream: ChatSessionStreamProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_nagare_fn_clone_chatsessionstream(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_nagare_fn_free_chatsessionstream(handle, $0) }
+ }
+
+
+
+
+open func cancelToken() -> CancelToken {
+ return try! FfiConverterTypeCancelToken_lift(try! rustCall() {
+ uniffi_nagare_fn_method_chatsessionstream_cancel_token(
+ self.uniffiCloneHandle(),$0
+ )
+})
+}
+
+open func next()async -> ChatSessionStreamChunk? {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_chatsessionstream_next(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_rust_buffer,
+ completeFunc: ffi_nagare_rust_future_complete_rust_buffer,
+ freeFunc: ffi_nagare_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterOptionTypeChatSessionStreamChunk.lift,
+ errorHandler: nil
+
+ )
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatSessionStream: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = ChatSessionStream
+
+ public static func lift(_ handle: UInt64) throws -> ChatSessionStream {
+ return ChatSessionStream(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: ChatSessionStream) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatSessionStream {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: ChatSessionStream, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSessionStream_lift(_ handle: UInt64) throws -> ChatSessionStream {
+ return try FfiConverterTypeChatSessionStream.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSessionStream_lower(_ value: ChatSessionStream) -> UInt64 {
+ return FfiConverterTypeChatSessionStream.lower(value)
+}
+
+
+
+
+
+
+public protocol ClassificationSessionProtocol: AnyObject, Sendable {
+
+ func classify(input: [ClassificationMessage]) async throws -> ClassificationOutput
+
+ func state() async -> ClassificationSessionState
+
+}
+open class ClassificationSession: ClassificationSessionProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_nagare_fn_clone_classificationsession(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_nagare_fn_free_classificationsession(handle, $0) }
+ }
+
+
+
+
+open func classify(input: [ClassificationMessage])async throws -> ClassificationOutput {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_classificationsession_classify(
+ self.uniffiCloneHandle(),
+ FfiConverterSequenceTypeClassificationMessage.lower(input)
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_rust_buffer,
+ completeFunc: ffi_nagare_rust_future_complete_rust_buffer,
+ freeFunc: ffi_nagare_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeClassificationOutput_lift,
+ errorHandler: FfiConverterTypeClassificationSessionError_lift
+ )
+}
+
+open func state()async -> ClassificationSessionState {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_classificationsession_state(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_rust_buffer,
+ completeFunc: ffi_nagare_rust_future_complete_rust_buffer,
+ freeFunc: ffi_nagare_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeClassificationSessionState_lift,
+ errorHandler: nil
+
+ )
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClassificationSession: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = ClassificationSession
+
+ public static func lift(_ handle: UInt64) throws -> ClassificationSession {
+ return ClassificationSession(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: ClassificationSession) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClassificationSession {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: ClassificationSession, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationSession_lift(_ handle: UInt64) throws -> ClassificationSession {
+ return try FfiConverterTypeClassificationSession.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationSession_lower(_ value: ClassificationSession) -> UInt64 {
+ return FfiConverterTypeClassificationSession.lower(value)
+}
+
+
+
+
+
+
+public protocol TextToSpeechSessionProtocol: AnyObject, Sendable {
+
+ func state() async -> TextToSpeechSessionState
+
+ func synthesize(input: String) async throws -> PcmBatch
+
+}
+open class TextToSpeechSession: TextToSpeechSessionProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_nagare_fn_clone_texttospeechsession(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_nagare_fn_free_texttospeechsession(handle, $0) }
+ }
+
+
+
+
+open func state()async -> TextToSpeechSessionState {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_texttospeechsession_state(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_rust_buffer,
+ completeFunc: ffi_nagare_rust_future_complete_rust_buffer,
+ freeFunc: ffi_nagare_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypeTextToSpeechSessionState_lift,
+ errorHandler: nil
+
+ )
+}
+
+open func synthesize(input: String)async throws -> PcmBatch {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_texttospeechsession_synthesize(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(input)
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_rust_buffer,
+ completeFunc: ffi_nagare_rust_future_complete_rust_buffer,
+ freeFunc: ffi_nagare_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterTypePcmBatch_lift,
+ errorHandler: FfiConverterTypeTextToSpeechSessionError_lift
+ )
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeTextToSpeechSession: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = TextToSpeechSession
+
+ public static func lift(_ handle: UInt64) throws -> TextToSpeechSession {
+ return TextToSpeechSession(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: TextToSpeechSession) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> TextToSpeechSession {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: TextToSpeechSession, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechSession_lift(_ handle: UInt64) throws -> TextToSpeechSession {
+ return try FfiConverterTypeTextToSpeechSession.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechSession_lower(_ value: TextToSpeechSession) -> UInt64 {
+ return FfiConverterTypeTextToSpeechSession.lower(value)
+}
+
+
+
+
+
+
+public protocol TextToSpeechSessionStreamProtocol: AnyObject, Sendable {
+
+ func cancelToken() -> CancelToken
+
+ func next() async -> TextToSpeechSessionStreamChunk?
+
+}
+open class TextToSpeechSessionStream: TextToSpeechSessionStreamProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_nagare_fn_clone_texttospeechsessionstream(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_nagare_fn_free_texttospeechsessionstream(handle, $0) }
+ }
+
+
+
+
+open func cancelToken() -> CancelToken {
+ return try! FfiConverterTypeCancelToken_lift(try! rustCall() {
+ uniffi_nagare_fn_method_texttospeechsessionstream_cancel_token(
+ self.uniffiCloneHandle(),$0
+ )
+})
+}
+
+open func next()async -> TextToSpeechSessionStreamChunk? {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_nagare_fn_method_texttospeechsessionstream_next(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_nagare_rust_future_poll_rust_buffer,
+ completeFunc: ffi_nagare_rust_future_complete_rust_buffer,
+ freeFunc: ffi_nagare_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterOptionTypeTextToSpeechSessionStreamChunk.lift,
+ errorHandler: nil
+
+ )
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeTextToSpeechSessionStream: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = TextToSpeechSessionStream
+
+ public static func lift(_ handle: UInt64) throws -> TextToSpeechSessionStream {
+ return TextToSpeechSessionStream(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: TextToSpeechSessionStream) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> TextToSpeechSessionStream {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: TextToSpeechSessionStream, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechSessionStream_lift(_ handle: UInt64) throws -> TextToSpeechSessionStream {
+ return try FfiConverterTypeTextToSpeechSessionStream.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechSessionStream_lower(_ value: TextToSpeechSessionStream) -> UInt64 {
+ return FfiConverterTypeTextToSpeechSessionStream.lower(value)
+}
+
+
+
+
+public enum ChatSessionError: Swift.Error, Equatable, Hashable, Codable, Foundation.LocalizedError {
+
+
+
+ case Backend(message: String
+ )
+ case UnsupportedModel
+ case UnableToPerformOperationInCurrentState
+ case NoResponse
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension ChatSessionError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatSessionError: FfiConverterRustBuffer {
+ typealias SwiftType = ChatSessionError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatSessionError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .Backend(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 2: return .UnsupportedModel
+ case 3: return .UnableToPerformOperationInCurrentState
+ case 4: return .NoResponse
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ChatSessionError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .Backend(message):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case .UnsupportedModel:
+ writeInt(&buf, Int32(2))
+
+
+ case .UnableToPerformOperationInCurrentState:
+ writeInt(&buf, Int32(3))
+
+
+ case .NoResponse:
+ writeInt(&buf, Int32(4))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSessionError_lift(_ buf: RustBuffer) throws -> ChatSessionError {
+ return try FfiConverterTypeChatSessionError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSessionError_lower(_ value: ChatSessionError) -> RustBuffer {
+ return FfiConverterTypeChatSessionError.lower(value)
+}
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ChatSessionState: Equatable, Hashable, Codable {
+
+ case idle
+ case generation
+ case toolCalling
+ case resetting
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatSessionState: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatSessionState: FfiConverterRustBuffer {
+ typealias SwiftType = ChatSessionState
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatSessionState {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .idle
+
+ case 2: return .generation
+
+ case 3: return .toolCalling
+
+ case 4: return .resetting
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ChatSessionState, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .idle:
+ writeInt(&buf, Int32(1))
+
+
+ case .generation:
+ writeInt(&buf, Int32(2))
+
+
+ case .toolCalling:
+ writeInt(&buf, Int32(3))
+
+
+ case .resetting:
+ writeInt(&buf, Int32(4))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSessionState_lift(_ buf: RustBuffer) throws -> ChatSessionState {
+ return try FfiConverterTypeChatSessionState.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSessionState_lower(_ value: ChatSessionState) -> RustBuffer {
+ return FfiConverterTypeChatSessionState.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ChatSessionStreamChunk: Equatable, Hashable, Codable {
+
+ case replies(replies: [ChatReply]
+ )
+ case error(error: ChatSessionError
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatSessionStreamChunk: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatSessionStreamChunk: FfiConverterRustBuffer {
+ typealias SwiftType = ChatSessionStreamChunk
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatSessionStreamChunk {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .replies(replies: try FfiConverterSequenceTypeChatReply.read(from: &buf)
+ )
+
+ case 2: return .error(error: try FfiConverterTypeChatSessionError.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ChatSessionStreamChunk, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case let .replies(replies):
+ writeInt(&buf, Int32(1))
+ FfiConverterSequenceTypeChatReply.write(replies, into: &buf)
+
+
+ case let .error(error):
+ writeInt(&buf, Int32(2))
+ FfiConverterTypeChatSessionError.write(error, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSessionStreamChunk_lift(_ buf: RustBuffer) throws -> ChatSessionStreamChunk {
+ return try FfiConverterTypeChatSessionStreamChunk.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSessionStreamChunk_lower(_ value: ChatSessionStreamChunk) -> RustBuffer {
+ return FfiConverterTypeChatSessionStreamChunk.lower(value)
+}
+
+
+
+public enum ClassificationSessionError: Swift.Error, Equatable, Hashable, Codable, Foundation.LocalizedError {
+
+
+
+ case Backend(message: String
+ )
+ case UnsupportedModel
+ case UnableToPerformOperationInCurrentState
+ case NoResponse
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension ClassificationSessionError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClassificationSessionError: FfiConverterRustBuffer {
+ typealias SwiftType = ClassificationSessionError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClassificationSessionError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .Backend(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 2: return .UnsupportedModel
+ case 3: return .UnableToPerformOperationInCurrentState
+ case 4: return .NoResponse
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ClassificationSessionError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .Backend(message):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case .UnsupportedModel:
+ writeInt(&buf, Int32(2))
+
+
+ case .UnableToPerformOperationInCurrentState:
+ writeInt(&buf, Int32(3))
+
+
+ case .NoResponse:
+ writeInt(&buf, Int32(4))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationSessionError_lift(_ buf: RustBuffer) throws -> ClassificationSessionError {
+ return try FfiConverterTypeClassificationSessionError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationSessionError_lower(_ value: ClassificationSessionError) -> RustBuffer {
+ return FfiConverterTypeClassificationSessionError.lower(value)
+}
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ClassificationSessionState: Equatable, Hashable, Codable {
+
+ case idle
+ case classifying
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ClassificationSessionState: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClassificationSessionState: FfiConverterRustBuffer {
+ typealias SwiftType = ClassificationSessionState
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClassificationSessionState {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .idle
+
+ case 2: return .classifying
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ClassificationSessionState, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .idle:
+ writeInt(&buf, Int32(1))
+
+
+ case .classifying:
+ writeInt(&buf, Int32(2))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationSessionState_lift(_ buf: RustBuffer) throws -> ClassificationSessionState {
+ return try FfiConverterTypeClassificationSessionState.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationSessionState_lower(_ value: ClassificationSessionState) -> RustBuffer {
+ return FfiConverterTypeClassificationSessionState.lower(value)
+}
+
+
+
+public enum TextToSpeechSessionError: Swift.Error, Equatable, Hashable, Codable, Foundation.LocalizedError {
+
+
+
+ case Backend(message: String
+ )
+ case UnsupportedModel
+ case UnableToPerformOperationInCurrentState
+ case NoResponse
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension TextToSpeechSessionError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeTextToSpeechSessionError: FfiConverterRustBuffer {
+ typealias SwiftType = TextToSpeechSessionError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> TextToSpeechSessionError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .Backend(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 2: return .UnsupportedModel
+ case 3: return .UnableToPerformOperationInCurrentState
+ case 4: return .NoResponse
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: TextToSpeechSessionError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .Backend(message):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case .UnsupportedModel:
+ writeInt(&buf, Int32(2))
+
+
+ case .UnableToPerformOperationInCurrentState:
+ writeInt(&buf, Int32(3))
+
+
+ case .NoResponse:
+ writeInt(&buf, Int32(4))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechSessionError_lift(_ buf: RustBuffer) throws -> TextToSpeechSessionError {
+ return try FfiConverterTypeTextToSpeechSessionError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechSessionError_lower(_ value: TextToSpeechSessionError) -> RustBuffer {
+ return FfiConverterTypeTextToSpeechSessionError.lower(value)
+}
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum TextToSpeechSessionState: Equatable, Hashable, Codable {
+
+ case idle
+ case synthesizing
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension TextToSpeechSessionState: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeTextToSpeechSessionState: FfiConverterRustBuffer {
+ typealias SwiftType = TextToSpeechSessionState
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> TextToSpeechSessionState {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .idle
+
+ case 2: return .synthesizing
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: TextToSpeechSessionState, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .idle:
+ writeInt(&buf, Int32(1))
+
+
+ case .synthesizing:
+ writeInt(&buf, Int32(2))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechSessionState_lift(_ buf: RustBuffer) throws -> TextToSpeechSessionState {
+ return try FfiConverterTypeTextToSpeechSessionState.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechSessionState_lower(_ value: TextToSpeechSessionState) -> RustBuffer {
+ return FfiConverterTypeTextToSpeechSessionState.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum TextToSpeechSessionStreamChunk: Equatable, Hashable, Codable {
+
+ case pcmBatch(batch: PcmBatch
+ )
+ case error(error: TextToSpeechSessionError
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension TextToSpeechSessionStreamChunk: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeTextToSpeechSessionStreamChunk: FfiConverterRustBuffer {
+ typealias SwiftType = TextToSpeechSessionStreamChunk
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> TextToSpeechSessionStreamChunk {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .pcmBatch(batch: try FfiConverterTypePcmBatch.read(from: &buf)
+ )
+
+ case 2: return .error(error: try FfiConverterTypeTextToSpeechSessionError.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: TextToSpeechSessionStreamChunk, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case let .pcmBatch(batch):
+ writeInt(&buf, Int32(1))
+ FfiConverterTypePcmBatch.write(batch, into: &buf)
+
+
+ case let .error(error):
+ writeInt(&buf, Int32(2))
+ FfiConverterTypeTextToSpeechSessionError.write(error, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechSessionStreamChunk_lift(_ buf: RustBuffer) throws -> TextToSpeechSessionStreamChunk {
+ return try FfiConverterTypeTextToSpeechSessionStreamChunk.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechSessionStreamChunk_lower(_ value: TextToSpeechSessionStreamChunk) -> RustBuffer {
+ return FfiConverterTypeTextToSpeechSessionStreamChunk.lower(value)
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeChatSessionStreamChunk: FfiConverterRustBuffer {
+ typealias SwiftType = ChatSessionStreamChunk?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeChatSessionStreamChunk.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeChatSessionStreamChunk.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeTextToSpeechSessionStreamChunk: FfiConverterRustBuffer {
+ typealias SwiftType = TextToSpeechSessionStreamChunk?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeTextToSpeechSessionStreamChunk.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeTextToSpeechSessionStreamChunk.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeChatMessage: FfiConverterRustBuffer {
+ typealias SwiftType = [ChatMessage]
+
+ public static func write(_ value: [ChatMessage], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeChatMessage.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ChatMessage] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ChatMessage]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeChatMessage.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeChatReply: FfiConverterRustBuffer {
+ typealias SwiftType = [ChatReply]
+
+ public static func write(_ value: [ChatReply], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeChatReply.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ChatReply] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ChatReply]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeChatReply.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeClassificationMessage: FfiConverterRustBuffer {
+ typealias SwiftType = [ClassificationMessage]
+
+ public static func write(_ value: [ClassificationMessage], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeClassificationMessage.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ClassificationMessage] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ClassificationMessage]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeClassificationMessage.read(from: &buf))
+ }
+ return seq
+ }
+}
+private let UNIFFI_RUST_FUTURE_POLL_READY: Int8 = 0
+private let UNIFFI_RUST_FUTURE_POLL_WAKE: Int8 = 1
+
+fileprivate let uniffiContinuationHandleMap = UniffiHandleMap<UnsafeContinuation<Int8, Never>>()
+
+fileprivate func uniffiRustCallAsync<F, T>(
+ rustFutureFunc: () -> UInt64,
+ pollFunc: (UInt64, @escaping UniffiRustFutureContinuationCallback, UInt64) -> (),
+ completeFunc: (UInt64, UnsafeMutablePointer<RustCallStatus>) -> F,
+ freeFunc: (UInt64) -> (),
+ liftFunc: (F) throws -> T,
+ errorHandler: ((RustBuffer) throws -> Swift.Error)?
+) async throws -> T {
+ // Make sure to call the ensure init function since future creation doesn't have a
+ // RustCallStatus param, so doesn't use makeRustCall()
+ uniffiEnsureNagareInitialized()
+ let rustFuture = rustFutureFunc()
+ defer {
+ freeFunc(rustFuture)
+ }
+ var pollResult: Int8;
+ repeat {
+ pollResult = await withUnsafeContinuation {
+ pollFunc(
+ rustFuture,
+ { handle, pollResult in
+ uniffiFutureContinuationCallback(handle: handle, pollResult: pollResult)
+ },
+ uniffiContinuationHandleMap.insert(obj: $0)
+ )
+ }
+ } while pollResult != UNIFFI_RUST_FUTURE_POLL_READY
+
+ return try liftFunc(makeRustCall(
+ { completeFunc(rustFuture, $0) },
+ errorHandler: errorHandler
+ ))
+}
+
+// Callback handlers for an async calls. These are invoked by Rust when the future is ready. They
+// lift the return value or error and resume the suspended function.
+fileprivate func uniffiFutureContinuationCallback(handle: UInt64, pollResult: Int8) {
+ if let continuation = try? uniffiContinuationHandleMap.remove(handle: handle) {
+ continuation.resume(returning: pollResult)
+ } else {
+ print("uniffiFutureContinuationCallback invalid handle")
+ }
+}
+
+private enum InitializationResult {
+ case ok
+ case contractVersionMismatch
+ case apiChecksumMismatch
+}
+// Use a global variable to perform the versioning checks. Swift ensures that
+// the code inside is only computed once.
+private let initializationResult: InitializationResult = {
+ // Get the bindings contract version from our ComponentInterface
+ let bindings_contract_version = 30
+ // Get the scaffolding contract version by calling the into the dylib
+ let scaffolding_contract_version = ffi_nagare_uniffi_contract_version()
+ if bindings_contract_version != scaffolding_contract_version {
+ return InitializationResult.contractVersionMismatch
+ }
+ if (uniffi_nagare_checksum_method_chatsession_messages() != 35188) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_chatsession_reply() != 25677) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_chatsession_reply_with_stream() != 12378) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_chatsession_reset() != 1317) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_chatsession_state() != 61854) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_chatsessionstream_cancel_token() != 18598) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_chatsessionstream_next() != 38311) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_classificationsession_classify() != 62366) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_classificationsession_state() != 63891) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_texttospeechsession_state() != 12535) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_texttospeechsession_synthesize() != 10886) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_texttospeechsessionstream_cancel_token() != 440) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_nagare_checksum_method_texttospeechsessionstream_next() != 21181) {
+ return InitializationResult.apiChecksumMismatch
+ }
+
+ uniffiEnsureShojiInitialized()
+ return InitializationResult.ok
+}()
+
+// Make the ensure init function public so that other modules which have external type references to
+// our types can call it.
+public func uniffiEnsureNagareInitialized() {
+ switch initializationResult {
+ case .ok:
+ break
+ case .contractVersionMismatch:
+ fatalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
+ case .apiChecksumMismatch:
+ fatalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+}
+
+// swiftlint:enable all
\ No newline at end of file
diff --git a/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift b/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift
new file mode 100644
index 000000000..70c17a62e
--- /dev/null
+++ b/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift
@@ -0,0 +1,5681 @@
+// This file was autogenerated by some hot garbage in the `uniffi` crate.
+// Trust me, you don't want to mess with it!
+
+// swiftlint:disable all
+import Foundation
+
+// Depending on the consumer's build setup, the low-level FFI code
+// might be in a separate module, or it might be compiled inline into
+// this module. This is a bit of light hackery to work with both.
+#if canImport(shojiFFI)
+import shojiFFI
+#endif
+
+fileprivate extension RustBuffer {
+ // Allocate a new buffer, copying the contents of a `UInt8` array.
+ init(bytes: [UInt8]) {
+ let rbuf = bytes.withUnsafeBufferPointer { ptr in
+ RustBuffer.from(ptr)
+ }
+ self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data)
+ }
+
+ static func empty() -> RustBuffer {
+ RustBuffer(capacity: 0, len:0, data: nil)
+ }
+
+ static func from(_ ptr: UnsafeBufferPointer<UInt8>) -> RustBuffer {
+ try! rustCall { ffi_shoji_rustbuffer_from_bytes(ForeignBytes(bufferPointer: ptr), $0) }
+ }
+
+ // Frees the buffer in place.
+ // The buffer must not be used after this is called.
+ func deallocate() {
+ try! rustCall { ffi_shoji_rustbuffer_free(self, $0) }
+ }
+}
+
+fileprivate extension ForeignBytes {
+ init(bufferPointer: UnsafeBufferPointer<UInt8>) {
+ self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress)
+ }
+}
+
+// For every type used in the interface, we provide helper methods for conveniently
+// lifting and lowering that type from C-compatible data, and for reading and writing
+// values of that type in a buffer.
+
+// Helper classes/extensions that don't change.
+// Someday, this will be in a library of its own.
+
+fileprivate extension Data {
+ init(rustBuffer: RustBuffer) {
+ self.init(
+ bytesNoCopy: rustBuffer.data!,
+ count: Int(rustBuffer.len),
+ deallocator: .none
+ )
+ }
+}
+
+// Define reader functionality. Normally this would be defined in a class or
+// struct, but we use standalone functions instead in order to make external
+// types work.
+//
+// With external types, one swift source file needs to be able to call the read
+// method on another source file's FfiConverter, but then what visibility
+// should Reader have?
+// - If Reader is fileprivate, then this means the read() must also
+// be fileprivate, which doesn't work with external types.
+// - If Reader is internal/public, we'll get compile errors since both source
+// files will try define the same type.
+//
+// Instead, the read() method and these helper functions input a tuple of data
+
+fileprivate func createReader(data: Data) -> (data: Data, offset: Data.Index) {
+ (data: data, offset: 0)
+}
+
+// Reads an integer at the current offset, in big-endian order, and advances
+// the offset on success. Throws if reading the integer would move the
+// offset past the end of the buffer.
+fileprivate func readInt<T: FixedWidthInteger>(_ reader: inout (data: Data, offset: Data.Index)) throws -> T {
+ let range = reader.offset..<reader.offset + MemoryLayout<T>.size
+ guard reader.data.count >= range.upperBound else {
+ throw UniffiInternalError.bufferOverflow
+ }
+ if T.self == UInt8.self {
+ let value = reader.data[reader.offset]
+ reader.offset += 1
+ return value as! T
+ }
+ var value: T = 0
+ let _ = withUnsafeMutableBytes(of: &value, { reader.data.copyBytes(to: $0, from: range)})
+ reader.offset = range.upperBound
+ return value.bigEndian
+}
+
+// Reads an arbitrary number of bytes, to be used to read
+// raw bytes, this is useful when lifting strings
+fileprivate func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> Array<UInt8> {
+ let range = reader.offset..<(reader.offset+count)
+ guard reader.data.count >= range.upperBound else {
+ throw UniffiInternalError.bufferOverflow
+ }
+ var value = [UInt8](repeating: 0, count: count)
+ value.withUnsafeMutableBufferPointer({ buffer in
+ reader.data.copyBytes(to: buffer, from: range)
+ })
+ reader.offset = range.upperBound
+ return value
+}
+
+// Reads a float at the current offset.
+fileprivate func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {
+ return Float(bitPattern: try readInt(&reader))
+}
+
+// Reads a float at the current offset.
+fileprivate func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {
+ return Double(bitPattern: try readInt(&reader))
+}
+
+// Indicates if the offset has reached the end of the buffer.
+fileprivate func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool {
+ return reader.offset < reader.data.count
+}
+
+// Define writer functionality. Normally this would be defined in a class or
+// struct, but we use standalone functions instead in order to make external
+// types work. See the above discussion on Readers for details.
+
+fileprivate func createWriter() -> [UInt8] {
+ return []
+}
+
+fileprivate func writeBytes<S>(_ writer: inout [UInt8], _ byteArr: S) where S: Sequence, S.Element == UInt8 {
+ writer.append(contentsOf: byteArr)
+}
+
+// Writes an integer in big-endian order.
+//
+// Warning: make sure what you are trying to write
+// is in the correct type!
+fileprivate func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {
+ var value = value.bigEndian
+ withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }
+}
+
+fileprivate func writeFloat(_ writer: inout [UInt8], _ value: Float) {
+ writeInt(&writer, value.bitPattern)
+}
+
+fileprivate func writeDouble(_ writer: inout [UInt8], _ value: Double) {
+ writeInt(&writer, value.bitPattern)
+}
+
+// Protocol for types that transfer other types across the FFI. This is
+// analogous to the Rust trait of the same name.
+fileprivate protocol FfiConverter {
+ associatedtype FfiType
+ associatedtype SwiftType
+
+ static func lift(_ value: FfiType) throws -> SwiftType
+ static func lower(_ value: SwiftType) -> FfiType
+ static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType
+ static func write(_ value: SwiftType, into buf: inout [UInt8])
+}
+
+// Types conforming to `Primitive` pass themselves directly over the FFI.
+fileprivate protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType { }
+
+extension FfiConverterPrimitive {
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ value: FfiType) throws -> SwiftType {
+ return value
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ value: SwiftType) -> FfiType {
+ return value
+ }
+}
+
+// Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`.
+// Used for complex types where it's hard to write a custom lift/lower.
+fileprivate protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {}
+
+extension FfiConverterRustBuffer {
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ buf: RustBuffer) throws -> SwiftType {
+ var reader = createReader(data: Data(rustBuffer: buf))
+ let value = try read(from: &reader)
+ if hasRemaining(reader) {
+ throw UniffiInternalError.incompleteData
+ }
+ buf.deallocate()
+ return value
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ value: SwiftType) -> RustBuffer {
+ var writer = createWriter()
+ write(value, into: &writer)
+ return RustBuffer(bytes: writer)
+ }
+}
+// An error type for FFI errors. These errors occur at the UniFFI level, not
+// the library level.
+fileprivate enum UniffiInternalError: LocalizedError {
+ case bufferOverflow
+ case incompleteData
+ case unexpectedOptionalTag
+ case unexpectedEnumCase
+ case unexpectedNullPointer
+ case unexpectedRustCallStatusCode
+ case unexpectedRustCallError
+ case unexpectedStaleHandle
+ case rustPanic(_ message: String)
+
+ public var errorDescription: String? {
+ switch self {
+ case .bufferOverflow: return "Reading the requested value would read past the end of the buffer"
+ case .incompleteData: return "The buffer still has data after lifting its containing value"
+ case .unexpectedOptionalTag: return "Unexpected optional tag; should be 0 or 1"
+ case .unexpectedEnumCase: return "Raw enum value doesn't match any cases"
+ case .unexpectedNullPointer: return "Raw pointer value was null"
+ case .unexpectedRustCallStatusCode: return "Unexpected RustCallStatus code"
+ case .unexpectedRustCallError: return "CALL_ERROR but no errorClass specified"
+ case .unexpectedStaleHandle: return "The object in the handle map has been dropped already"
+ case let .rustPanic(message): return message
+ }
+ }
+}
+
+fileprivate extension NSLock {
+ func withLock<T>(f: () throws -> T) rethrows -> T {
+ self.lock()
+ defer { self.unlock() }
+ return try f()
+ }
+}
+
+fileprivate let CALL_SUCCESS: Int8 = 0
+fileprivate let CALL_ERROR: Int8 = 1
+fileprivate let CALL_UNEXPECTED_ERROR: Int8 = 2
+fileprivate let CALL_CANCELLED: Int8 = 3
+
+fileprivate extension RustCallStatus {
+ init() {
+ self.init(
+ code: CALL_SUCCESS,
+ errorBuf: RustBuffer.init(
+ capacity: 0,
+ len: 0,
+ data: nil
+ )
+ )
+ }
+}
+
+private func rustCall<T>(_ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
+ let neverThrow: ((RustBuffer) throws -> Never)? = nil
+ return try makeRustCall(callback, errorHandler: neverThrow)
+}
+
+private func rustCallWithError<T, E: Swift.Error>(
+ _ errorHandler: @escaping (RustBuffer) throws -> E,
+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
+ try makeRustCall(callback, errorHandler: errorHandler)
+}
+
+private func makeRustCall<T, E: Swift.Error>(
+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T,
+ errorHandler: ((RustBuffer) throws -> E)?
+) throws -> T {
+ uniffiEnsureShojiInitialized()
+ var callStatus = RustCallStatus.init()
+ let returnedVal = callback(&callStatus)
+ try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler)
+ return returnedVal
+}
+
+private func uniffiCheckCallStatus<E: Swift.Error>(
+ callStatus: RustCallStatus,
+ errorHandler: ((RustBuffer) throws -> E)?
+) throws {
+ switch callStatus.code {
+ case CALL_SUCCESS:
+ return
+
+ case CALL_ERROR:
+ if let errorHandler = errorHandler {
+ throw try errorHandler(callStatus.errorBuf)
+ } else {
+ callStatus.errorBuf.deallocate()
+ throw UniffiInternalError.unexpectedRustCallError
+ }
+
+ case CALL_UNEXPECTED_ERROR:
+ // When the rust code sees a panic, it tries to construct a RustBuffer
+ // with the message. But if that code panics, then it just sends back
+ // an empty buffer.
+ if callStatus.errorBuf.len > 0 {
+ throw UniffiInternalError.rustPanic(try FfiConverterString.lift(callStatus.errorBuf))
+ } else {
+ callStatus.errorBuf.deallocate()
+ throw UniffiInternalError.rustPanic("Rust panic")
+ }
+
+ case CALL_CANCELLED:
+ fatalError("Cancellation not supported yet")
+
+ default:
+ throw UniffiInternalError.unexpectedRustCallStatusCode
+ }
+}
+
+private func uniffiTraitInterfaceCall<T>(
+ callStatus: UnsafeMutablePointer<RustCallStatus>,
+ makeCall: () throws -> T,
+ writeReturn: (T) -> ()
+) {
+ do {
+ try writeReturn(makeCall())
+ } catch let error {
+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR
+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
+ }
+}
+
+private func uniffiTraitInterfaceCallWithError<T, E>(
+ callStatus: UnsafeMutablePointer<RustCallStatus>,
+ makeCall: () throws -> T,
+ writeReturn: (T) -> (),
+ lowerError: (E) -> RustBuffer
+) {
+ do {
+ try writeReturn(makeCall())
+ } catch let error as E {
+ callStatus.pointee.code = CALL_ERROR
+ callStatus.pointee.errorBuf = lowerError(error)
+ } catch {
+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR
+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
+ }
+}
+// Initial value and increment amount for handles.
+// These ensure that SWIFT handles always have the lowest bit set
+fileprivate let UNIFFI_HANDLEMAP_INITIAL: UInt64 = 1
+fileprivate let UNIFFI_HANDLEMAP_DELTA: UInt64 = 2
+
+fileprivate final class UniffiHandleMap<T>: @unchecked Sendable {
+ // All mutation happens with this lock held, which is why we implement @unchecked Sendable.
+ private let lock = NSLock()
+ private var map: [UInt64: T] = [:]
+ private var currentHandle: UInt64 = UNIFFI_HANDLEMAP_INITIAL
+
+ func insert(obj: T) -> UInt64 {
+ lock.withLock {
+ return doInsert(obj)
+ }
+ }
+
+ // Low-level insert function, this assumes `lock` is held.
+ private func doInsert(_ obj: T) -> UInt64 {
+ let handle = currentHandle
+ currentHandle += UNIFFI_HANDLEMAP_DELTA
+ map[handle] = obj
+ return handle
+ }
+
+ func get(handle: UInt64) throws -> T {
+ try lock.withLock {
+ guard let obj = map[handle] else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return obj
+ }
+ }
+
+ func clone(handle: UInt64) throws -> UInt64 {
+ try lock.withLock {
+ guard let obj = map[handle] else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return doInsert(obj)
+ }
+ }
+
+ @discardableResult
+ func remove(handle: UInt64) throws -> T {
+ try lock.withLock {
+ guard let obj = map.removeValue(forKey: handle) else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return obj
+ }
+ }
+
+ var count: Int {
+ get {
+ map.count
+ }
+ }
+}
+
+
+// Public interface members begin here.
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterUInt32: FfiConverterPrimitive {
+ typealias FfiType = UInt32
+ typealias SwiftType = UInt32
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt32 {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterInt64: FfiConverterPrimitive {
+ typealias FfiType = Int64
+ typealias SwiftType = Int64
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Int64 {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: Int64, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterDouble: FfiConverterPrimitive {
+ typealias FfiType = Double
+ typealias SwiftType = Double
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Double {
+ return try lift(readDouble(&buf))
+ }
+
+ public static func write(_ value: Double, into buf: inout [UInt8]) {
+ writeDouble(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterBool : FfiConverter {
+ typealias FfiType = Int8
+ typealias SwiftType = Bool
+
+ public static func lift(_ value: Int8) throws -> Bool {
+ return value != 0
+ }
+
+ public static func lower(_ value: Bool) -> Int8 {
+ return value ? 1 : 0
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Bool {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: Bool, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterString: FfiConverter {
+ typealias SwiftType = String
+ typealias FfiType = RustBuffer
+
+ public static func lift(_ value: RustBuffer) throws -> String {
+ defer {
+ value.deallocate()
+ }
+ if value.data == nil {
+ return String()
+ }
+ let bytes = UnsafeBufferPointer<UInt8>(start: value.data!, count: Int(value.len))
+ return String(bytes: bytes, encoding: String.Encoding.utf8)!
+ }
+
+ public static func lower(_ value: String) -> RustBuffer {
+ return value.utf8CString.withUnsafeBufferPointer { ptr in
+ // The swift string gives us int8_t, we want uint8_t.
+ ptr.withMemoryRebound(to: UInt8.self) { ptr in
+ // The swift string gives us a trailing null byte, we don't want it.
+ let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1))
+ return RustBuffer.from(buf)
+ }
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {
+ let len: Int32 = try readInt(&buf)
+ return String(bytes: try readBytes(&buf, count: Int(len)), encoding: String.Encoding.utf8)!
+ }
+
+ public static func write(_ value: String, into buf: inout [UInt8]) {
+ let len = Int32(value.utf8.count)
+ writeInt(&buf, len)
+ writeBytes(&buf, value.utf8)
+ }
+}
+
+
+
+
+public protocol CancelTokenProtocol: AnyObject, Sendable {
+
+ func cancel()
+
+ func isCancelled() -> Bool
+
+}
+open class CancelToken: CancelTokenProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_shoji_fn_clone_canceltoken(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_shoji_fn_free_canceltoken(handle, $0) }
+ }
+
+
+
+
+open func cancel() {try! rustCall() {
+ uniffi_shoji_fn_method_canceltoken_cancel(
+ self.uniffiCloneHandle(),$0
+ )
+}
+}
+
+open func isCancelled() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_shoji_fn_method_canceltoken_is_cancelled(
+ self.uniffiCloneHandle(),$0
+ )
+})
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeCancelToken: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = CancelToken
+
+ public static func lift(_ handle: UInt64) throws -> CancelToken {
+ return CancelToken(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: CancelToken) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> CancelToken {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: CancelToken, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCancelToken_lift(_ handle: UInt64) throws -> CancelToken {
+ return try FfiConverterTypeCancelToken.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeCancelToken_lower(_ value: CancelToken) -> UInt64 {
+ return FfiConverterTypeCancelToken.lower(value)
+}
+
+
+
+
+public struct ChatConfig: Equatable, Hashable, Codable {
+ public var contextLength: ContextLength
+ public var samplingSeed: SamplingSeed
+ public var speculationPreset: ChatSpeculationPreset?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(contextLength: ContextLength, samplingSeed: SamplingSeed, speculationPreset: ChatSpeculationPreset?) {
+ self.contextLength = contextLength
+ self.samplingSeed = samplingSeed
+ self.speculationPreset = speculationPreset
+ }
+
+
+public func withContextLength(contextLength: ContextLength) -> ChatConfig {
+ return try! FfiConverterTypeChatConfig_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatconfig_with_context_length(
+ FfiConverterTypeChatConfig_lower(self),
+ FfiConverterTypeContextLength_lower(contextLength),$0
+ )
+})
+}
+
+public func withSamplingSeed(samplingSeed: SamplingSeed) -> ChatConfig {
+ return try! FfiConverterTypeChatConfig_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatconfig_with_sampling_seed(
+ FfiConverterTypeChatConfig_lower(self),
+ FfiConverterTypeSamplingSeed_lower(samplingSeed),$0
+ )
+})
+}
+
+public func withSpeculationPreset(speculationPreset: ChatSpeculationPreset?) -> ChatConfig {
+ return try! FfiConverterTypeChatConfig_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatconfig_with_speculation_preset(
+ FfiConverterTypeChatConfig_lower(self),
+ FfiConverterOptionTypeChatSpeculationPreset.lower(speculationPreset),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatConfig: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatConfig: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatConfig {
+ return
+ try ChatConfig(
+ contextLength: FfiConverterTypeContextLength.read(from: &buf),
+ samplingSeed: FfiConverterTypeSamplingSeed.read(from: &buf),
+ speculationPreset: FfiConverterOptionTypeChatSpeculationPreset.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ChatConfig, into buf: inout [UInt8]) {
+ FfiConverterTypeContextLength.write(value.contextLength, into: &buf)
+ FfiConverterTypeSamplingSeed.write(value.samplingSeed, into: &buf)
+ FfiConverterOptionTypeChatSpeculationPreset.write(value.speculationPreset, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatConfig_lift(_ buf: RustBuffer) throws -> ChatConfig {
+ return try FfiConverterTypeChatConfig.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatConfig_lower(_ value: ChatConfig) -> RustBuffer {
+ return FfiConverterTypeChatConfig.lower(value)
+}
+
+
+public struct ChatMessage: Equatable, Hashable, Codable {
+ public var role: ChatRole
+ public var content: [ChatContentBlock]
+ public var metadata: ChatMessageMetadata
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(role: ChatRole, content: [ChatContentBlock], metadata: ChatMessageMetadata) {
+ self.role = role
+ self.content = content
+ self.metadata = metadata
+ }
+
+
+public func reasoning() -> String? {
+ return try! FfiConverterOptionString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_reasoning(
+ FfiConverterTypeChatMessage_lower(self),$0
+ )
+})
+}
+
+public func reasoningEffort() -> ReasoningEffort? {
+ return try! FfiConverterOptionTypeReasoningEffort.lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_reasoning_effort(
+ FfiConverterTypeChatMessage_lower(self),$0
+ )
+})
+}
+
+public func text() -> String? {
+ return try! FfiConverterOptionString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_text(
+ FfiConverterTypeChatMessage_lower(self),$0
+ )
+})
+}
+
+public func toolCalls() -> [ToolCall] {
+ return try! FfiConverterSequenceTypeToolCall.lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_tool_calls(
+ FfiConverterTypeChatMessage_lower(self),$0
+ )
+})
+}
+
+public func toolNamespaces() -> [ToolNamespace] {
+ return try! FfiConverterSequenceTypeToolNamespace.lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_tool_namespaces(
+ FfiConverterTypeChatMessage_lower(self),$0
+ )
+})
+}
+
+public func withBlock(block: ChatContentBlock) -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_with_block(
+ FfiConverterTypeChatMessage_lower(self),
+ FfiConverterTypeChatContentBlock_lower(block),$0
+ )
+})
+}
+
+public func withReasoning(reasoning: String) -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_with_reasoning(
+ FfiConverterTypeChatMessage_lower(self),
+ FfiConverterString.lower(reasoning),$0
+ )
+})
+}
+
+public func withReasoningEffort(reasoningEffort: ReasoningEffort) -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_with_reasoning_effort(
+ FfiConverterTypeChatMessage_lower(self),
+ FfiConverterTypeReasoningEffort_lower(reasoningEffort),$0
+ )
+})
+}
+
+public func withText(text: String) -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_with_text(
+ FfiConverterTypeChatMessage_lower(self),
+ FfiConverterString.lower(text),$0
+ )
+})
+}
+
+public func withToolCall(toolCall: ToolCall) -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_with_tool_call(
+ FfiConverterTypeChatMessage_lower(self),
+ FfiConverterTypeToolCall_lower(toolCall),$0
+ )
+})
+}
+
+public func withToolCallCandidate(value: Value) -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_with_tool_call_candidate(
+ FfiConverterTypeChatMessage_lower(self),
+ FfiConverterTypeValue_lower(value),$0
+ )
+})
+}
+
+public func withToolNamespaces(toolNamespaces: [ToolNamespace]) -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatmessage_with_tool_namespaces(
+ FfiConverterTypeChatMessage_lower(self),
+ FfiConverterSequenceTypeToolNamespace.lower(toolNamespaces),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatMessage: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatMessage: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatMessage {
+ return
+ try ChatMessage(
+ role: FfiConverterTypeChatRole.read(from: &buf),
+ content: FfiConverterSequenceTypeChatContentBlock.read(from: &buf),
+ metadata: FfiConverterTypeChatMessageMetadata.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ChatMessage, into buf: inout [UInt8]) {
+ FfiConverterTypeChatRole.write(value.role, into: &buf)
+ FfiConverterSequenceTypeChatContentBlock.write(value.content, into: &buf)
+ FfiConverterTypeChatMessageMetadata.write(value.metadata, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatMessage_lift(_ buf: RustBuffer) throws -> ChatMessage {
+ return try FfiConverterTypeChatMessage.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatMessage_lower(_ value: ChatMessage) -> RustBuffer {
+ return FfiConverterTypeChatMessage.lower(value)
+}
+
+
+public struct ChatMessageMetadata: Equatable, Hashable, Codable {
+ public var values: [String: Value]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(values: [String: Value]) {
+ self.values = values
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatMessageMetadata: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatMessageMetadata: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatMessageMetadata {
+ return
+ try ChatMessageMetadata(
+ values: FfiConverterDictionaryStringTypeValue.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ChatMessageMetadata, into buf: inout [UInt8]) {
+ FfiConverterDictionaryStringTypeValue.write(value.values, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatMessageMetadata_lift(_ buf: RustBuffer) throws -> ChatMessageMetadata {
+ return try FfiConverterTypeChatMessageMetadata.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatMessageMetadata_lower(_ value: ChatMessageMetadata) -> RustBuffer {
+ return FfiConverterTypeChatMessageMetadata.lower(value)
+}
+
+
+public struct ChatModelCapabilities: Equatable, Hashable, Codable {
+ public var supportsReasoning: Bool
+ public var supportsDisableReasoning: Bool
+ public var supportsTools: Bool
+ public var supportsMultipleToolCalls: Bool
+ public var requiresTools: Bool
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(supportsReasoning: Bool, supportsDisableReasoning: Bool, supportsTools: Bool, supportsMultipleToolCalls: Bool, requiresTools: Bool) {
+ self.supportsReasoning = supportsReasoning
+ self.supportsDisableReasoning = supportsDisableReasoning
+ self.supportsTools = supportsTools
+ self.supportsMultipleToolCalls = supportsMultipleToolCalls
+ self.requiresTools = requiresTools
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatModelCapabilities: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatModelCapabilities: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatModelCapabilities {
+ return
+ try ChatModelCapabilities(
+ supportsReasoning: FfiConverterBool.read(from: &buf),
+ supportsDisableReasoning: FfiConverterBool.read(from: &buf),
+ supportsTools: FfiConverterBool.read(from: &buf),
+ supportsMultipleToolCalls: FfiConverterBool.read(from: &buf),
+ requiresTools: FfiConverterBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ChatModelCapabilities, into buf: inout [UInt8]) {
+ FfiConverterBool.write(value.supportsReasoning, into: &buf)
+ FfiConverterBool.write(value.supportsDisableReasoning, into: &buf)
+ FfiConverterBool.write(value.supportsTools, into: &buf)
+ FfiConverterBool.write(value.supportsMultipleToolCalls, into: &buf)
+ FfiConverterBool.write(value.requiresTools, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatModelCapabilities_lift(_ buf: RustBuffer) throws -> ChatModelCapabilities {
+ return try FfiConverterTypeChatModelCapabilities.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatModelCapabilities_lower(_ value: ChatModelCapabilities) -> RustBuffer {
+ return FfiConverterTypeChatModelCapabilities.lower(value)
+}
+
+
+public struct ChatReply: Equatable, Hashable, Codable {
+ public var message: ChatMessage
+ public var stats: ChatReplyStats
+ public var finishReason: ChatReplyFinishReason?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(message: ChatMessage, stats: ChatReplyStats, finishReason: ChatReplyFinishReason?) {
+ self.message = message
+ self.stats = stats
+ self.finishReason = finishReason
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatReply: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatReply: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatReply {
+ return
+ try ChatReply(
+ message: FfiConverterTypeChatMessage.read(from: &buf),
+ stats: FfiConverterTypeChatReplyStats.read(from: &buf),
+ finishReason: FfiConverterOptionTypeChatReplyFinishReason.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ChatReply, into buf: inout [UInt8]) {
+ FfiConverterTypeChatMessage.write(value.message, into: &buf)
+ FfiConverterTypeChatReplyStats.write(value.stats, into: &buf)
+ FfiConverterOptionTypeChatReplyFinishReason.write(value.finishReason, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatReply_lift(_ buf: RustBuffer) throws -> ChatReply {
+ return try FfiConverterTypeChatReply.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatReply_lower(_ value: ChatReply) -> RustBuffer {
+ return FfiConverterTypeChatReply.lower(value)
+}
+
+
+public struct ChatReplyConfig: Equatable, Hashable, Codable {
+ public var tokenLimit: UInt32?
+ public var samplingPolicy: SamplingPolicy
+ public var grammar: Grammar?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(tokenLimit: UInt32?, samplingPolicy: SamplingPolicy, grammar: Grammar?) {
+ self.tokenLimit = tokenLimit
+ self.samplingPolicy = samplingPolicy
+ self.grammar = grammar
+ }
+
+
+public func withGrammar(grammar: Grammar?) -> ChatReplyConfig {
+ return try! FfiConverterTypeChatReplyConfig_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatreplyconfig_with_grammar(
+ FfiConverterTypeChatReplyConfig_lower(self),
+ FfiConverterOptionTypeGrammar.lower(grammar),$0
+ )
+})
+}
+
+public func withSamplingMethod(samplingMethod: SamplingMethod) -> ChatReplyConfig {
+ return try! FfiConverterTypeChatReplyConfig_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatreplyconfig_with_sampling_method(
+ FfiConverterTypeChatReplyConfig_lower(self),
+ FfiConverterTypeSamplingMethod_lower(samplingMethod),$0
+ )
+})
+}
+
+public func withSamplingPolicy(samplingPolicy: SamplingPolicy) -> ChatReplyConfig {
+ return try! FfiConverterTypeChatReplyConfig_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatreplyconfig_with_sampling_policy(
+ FfiConverterTypeChatReplyConfig_lower(self),
+ FfiConverterTypeSamplingPolicy_lower(samplingPolicy),$0
+ )
+})
+}
+
+public func withTokenLimit(tokenLimit: UInt32?) -> ChatReplyConfig {
+ return try! FfiConverterTypeChatReplyConfig_lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatreplyconfig_with_token_limit(
+ FfiConverterTypeChatReplyConfig_lower(self),
+ FfiConverterOptionUInt32.lower(tokenLimit),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatReplyConfig: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatReplyConfig: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatReplyConfig {
+ return
+ try ChatReplyConfig(
+ tokenLimit: FfiConverterOptionUInt32.read(from: &buf),
+ samplingPolicy: FfiConverterTypeSamplingPolicy.read(from: &buf),
+ grammar: FfiConverterOptionTypeGrammar.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ChatReplyConfig, into buf: inout [UInt8]) {
+ FfiConverterOptionUInt32.write(value.tokenLimit, into: &buf)
+ FfiConverterTypeSamplingPolicy.write(value.samplingPolicy, into: &buf)
+ FfiConverterOptionTypeGrammar.write(value.grammar, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatReplyConfig_lift(_ buf: RustBuffer) throws -> ChatReplyConfig {
+ return try FfiConverterTypeChatReplyConfig.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatReplyConfig_lower(_ value: ChatReplyConfig) -> RustBuffer {
+ return FfiConverterTypeChatReplyConfig.lower(value)
+}
+
+
+public struct ChatReplyStats: Equatable, Hashable, Codable {
+ public var duration: Double
+ public var timeToFirstToken: Double?
+ public var prefillTokensPerSecond: Double?
+ public var generateTokensPerSecond: Double?
+ public var tokensCountInput: UInt32?
+ public var tokensCountOutput: UInt32?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(duration: Double, timeToFirstToken: Double?, prefillTokensPerSecond: Double?, generateTokensPerSecond: Double?, tokensCountInput: UInt32?, tokensCountOutput: UInt32?) {
+ self.duration = duration
+ self.timeToFirstToken = timeToFirstToken
+ self.prefillTokensPerSecond = prefillTokensPerSecond
+ self.generateTokensPerSecond = generateTokensPerSecond
+ self.tokensCountInput = tokensCountInput
+ self.tokensCountOutput = tokensCountOutput
+ }
+
+
+public func tokensCount() -> UInt32? {
+ return try! FfiConverterOptionUInt32.lift(try! rustCall() {
+ uniffi_shoji_fn_method_chatreplystats_tokens_count(
+ FfiConverterTypeChatReplyStats_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatReplyStats: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatReplyStats: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatReplyStats {
+ return
+ try ChatReplyStats(
+ duration: FfiConverterDouble.read(from: &buf),
+ timeToFirstToken: FfiConverterOptionDouble.read(from: &buf),
+ prefillTokensPerSecond: FfiConverterOptionDouble.read(from: &buf),
+ generateTokensPerSecond: FfiConverterOptionDouble.read(from: &buf),
+ tokensCountInput: FfiConverterOptionUInt32.read(from: &buf),
+ tokensCountOutput: FfiConverterOptionUInt32.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ChatReplyStats, into buf: inout [UInt8]) {
+ FfiConverterDouble.write(value.duration, into: &buf)
+ FfiConverterOptionDouble.write(value.timeToFirstToken, into: &buf)
+ FfiConverterOptionDouble.write(value.prefillTokensPerSecond, into: &buf)
+ FfiConverterOptionDouble.write(value.generateTokensPerSecond, into: &buf)
+ FfiConverterOptionUInt32.write(value.tokensCountInput, into: &buf)
+ FfiConverterOptionUInt32.write(value.tokensCountOutput, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatReplyStats_lift(_ buf: RustBuffer) throws -> ChatReplyStats {
+ return try FfiConverterTypeChatReplyStats.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatReplyStats_lower(_ value: ChatReplyStats) -> RustBuffer {
+ return FfiConverterTypeChatReplyStats.lower(value)
+}
+
+
+public struct ClassificationLabel: Equatable, Hashable, Codable {
+ public var index: Int64
+ public var label: String
+ public var title: String
+ public var description: String
+ public var recommendedThreshold: Double
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(index: Int64, label: String, title: String, description: String, recommendedThreshold: Double) {
+ self.index = index
+ self.label = label
+ self.title = title
+ self.description = description
+ self.recommendedThreshold = recommendedThreshold
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ClassificationLabel: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClassificationLabel: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClassificationLabel {
+ return
+ try ClassificationLabel(
+ index: FfiConverterInt64.read(from: &buf),
+ label: FfiConverterString.read(from: &buf),
+ title: FfiConverterString.read(from: &buf),
+ description: FfiConverterString.read(from: &buf),
+ recommendedThreshold: FfiConverterDouble.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ClassificationLabel, into buf: inout [UInt8]) {
+ FfiConverterInt64.write(value.index, into: &buf)
+ FfiConverterString.write(value.label, into: &buf)
+ FfiConverterString.write(value.title, into: &buf)
+ FfiConverterString.write(value.description, into: &buf)
+ FfiConverterDouble.write(value.recommendedThreshold, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationLabel_lift(_ buf: RustBuffer) throws -> ClassificationLabel {
+ return try FfiConverterTypeClassificationLabel.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationLabel_lower(_ value: ClassificationLabel) -> RustBuffer {
+ return FfiConverterTypeClassificationLabel.lower(value)
+}
+
+
+public struct ClassificationMessage: Equatable, Hashable, Codable {
+ public var role: ClassificationRole
+ public var content: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(role: ClassificationRole, content: String) {
+ self.role = role
+ self.content = content
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ClassificationMessage: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClassificationMessage: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClassificationMessage {
+ return
+ try ClassificationMessage(
+ role: FfiConverterTypeClassificationRole.read(from: &buf),
+ content: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ClassificationMessage, into buf: inout [UInt8]) {
+ FfiConverterTypeClassificationRole.write(value.role, into: &buf)
+ FfiConverterString.write(value.content, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationMessage_lift(_ buf: RustBuffer) throws -> ClassificationMessage {
+ return try FfiConverterTypeClassificationMessage.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationMessage_lower(_ value: ClassificationMessage) -> RustBuffer {
+ return FfiConverterTypeClassificationMessage.lower(value)
+}
+
+
+public struct ClassificationOutput: Equatable, Hashable, Codable {
+ public var logits: [Double]
+ public var probabilities: ClassificationOutputProbabilities
+ public var stats: ClassificationStats
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(logits: [Double], probabilities: ClassificationOutputProbabilities, stats: ClassificationStats) {
+ self.logits = logits
+ self.probabilities = probabilities
+ self.stats = stats
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ClassificationOutput: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClassificationOutput: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClassificationOutput {
+ return
+ try ClassificationOutput(
+ logits: FfiConverterSequenceDouble.read(from: &buf),
+ probabilities: FfiConverterTypeClassificationOutputProbabilities.read(from: &buf),
+ stats: FfiConverterTypeClassificationStats.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ClassificationOutput, into buf: inout [UInt8]) {
+ FfiConverterSequenceDouble.write(value.logits, into: &buf)
+ FfiConverterTypeClassificationOutputProbabilities.write(value.probabilities, into: &buf)
+ FfiConverterTypeClassificationStats.write(value.stats, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationOutput_lift(_ buf: RustBuffer) throws -> ClassificationOutput {
+ return try FfiConverterTypeClassificationOutput.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationOutput_lower(_ value: ClassificationOutput) -> RustBuffer {
+ return FfiConverterTypeClassificationOutput.lower(value)
+}
+
+
+public struct ClassificationOutputProbabilities: Equatable, Hashable, Codable {
+ public var values: [String: Double]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(values: [String: Double]) {
+ self.values = values
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ClassificationOutputProbabilities: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClassificationOutputProbabilities: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClassificationOutputProbabilities {
+ return
+ try ClassificationOutputProbabilities(
+ values: FfiConverterDictionaryStringDouble.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ClassificationOutputProbabilities, into buf: inout [UInt8]) {
+ FfiConverterDictionaryStringDouble.write(value.values, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationOutputProbabilities_lift(_ buf: RustBuffer) throws -> ClassificationOutputProbabilities {
+ return try FfiConverterTypeClassificationOutputProbabilities.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationOutputProbabilities_lower(_ value: ClassificationOutputProbabilities) -> RustBuffer {
+ return FfiConverterTypeClassificationOutputProbabilities.lower(value)
+}
+
+
+public struct ClassificationStats: Equatable, Hashable, Codable {
+ public var preprocessingDuration: Double
+ public var forwardPassDuration: Double
+ public var postprocessingDuration: Double
+ public var totalDuration: Double
+ public var tokensCount: Int64
+ public var tokensPerSecond: Double
+ public var predictedLabel: String
+ public var confidence: Double
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(preprocessingDuration: Double, forwardPassDuration: Double, postprocessingDuration: Double, totalDuration: Double, tokensCount: Int64, tokensPerSecond: Double, predictedLabel: String, confidence: Double) {
+ self.preprocessingDuration = preprocessingDuration
+ self.forwardPassDuration = forwardPassDuration
+ self.postprocessingDuration = postprocessingDuration
+ self.totalDuration = totalDuration
+ self.tokensCount = tokensCount
+ self.tokensPerSecond = tokensPerSecond
+ self.predictedLabel = predictedLabel
+ self.confidence = confidence
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ClassificationStats: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClassificationStats: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClassificationStats {
+ return
+ try ClassificationStats(
+ preprocessingDuration: FfiConverterDouble.read(from: &buf),
+ forwardPassDuration: FfiConverterDouble.read(from: &buf),
+ postprocessingDuration: FfiConverterDouble.read(from: &buf),
+ totalDuration: FfiConverterDouble.read(from: &buf),
+ tokensCount: FfiConverterInt64.read(from: &buf),
+ tokensPerSecond: FfiConverterDouble.read(from: &buf),
+ predictedLabel: FfiConverterString.read(from: &buf),
+ confidence: FfiConverterDouble.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ClassificationStats, into buf: inout [UInt8]) {
+ FfiConverterDouble.write(value.preprocessingDuration, into: &buf)
+ FfiConverterDouble.write(value.forwardPassDuration, into: &buf)
+ FfiConverterDouble.write(value.postprocessingDuration, into: &buf)
+ FfiConverterDouble.write(value.totalDuration, into: &buf)
+ FfiConverterInt64.write(value.tokensCount, into: &buf)
+ FfiConverterDouble.write(value.tokensPerSecond, into: &buf)
+ FfiConverterString.write(value.predictedLabel, into: &buf)
+ FfiConverterDouble.write(value.confidence, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationStats_lift(_ buf: RustBuffer) throws -> ClassificationStats {
+ return try FfiConverterTypeClassificationStats.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationStats_lower(_ value: ClassificationStats) -> RustBuffer {
+ return FfiConverterTypeClassificationStats.lower(value)
+}
+
+
+public struct Feature: Equatable, Hashable, Codable {
+ public var name: String
+ public var values: [String]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(name: String, values: [String]) {
+ self.name = name
+ self.values = values
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Feature: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeFeature: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Feature {
+ return
+ try Feature(
+ name: FfiConverterString.read(from: &buf),
+ values: FfiConverterSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Feature, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterSequenceString.write(value.values, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeFeature_lift(_ buf: RustBuffer) throws -> Feature {
+ return try FfiConverterTypeFeature.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeFeature_lower(_ value: Feature) -> RustBuffer {
+ return FfiConverterTypeFeature.lower(value)
+}
+
+
+public struct File: Equatable, Hashable, Codable {
+ public var url: String
+ public var name: String
+ public var size: Int64
+ public var hashes: [Hash]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(url: String, name: String, size: Int64, hashes: [Hash]) {
+ self.url = url
+ self.name = name
+ self.size = size
+ self.hashes = hashes
+ }
+
+
+public func crc32c() -> String? {
+ return try! FfiConverterOptionString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_file_crc32c(
+ FfiConverterTypeFile_lower(self),$0
+ )
+})
+}
+
+public func md5() -> String? {
+ return try! FfiConverterOptionString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_file_md5(
+ FfiConverterTypeFile_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension File: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeFile: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> File {
+ return
+ try File(
+ url: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ size: FfiConverterInt64.read(from: &buf),
+ hashes: FfiConverterSequenceTypeHash.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: File, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.url, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterInt64.write(value.size, into: &buf)
+ FfiConverterSequenceTypeHash.write(value.hashes, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeFile_lift(_ buf: RustBuffer) throws -> File {
+ return try FfiConverterTypeFile.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeFile_lower(_ value: File) -> RustBuffer {
+ return FfiConverterTypeFile.lower(value)
+}
+
+
+public struct Hash: Equatable, Hashable, Codable {
+ public var method: HashMethod
+ public var value: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(method: HashMethod, value: String) {
+ self.method = method
+ self.value = value
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Hash: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeHash: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Hash {
+ return
+ try Hash(
+ method: FfiConverterTypeHashMethod.read(from: &buf),
+ value: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Hash, into buf: inout [UInt8]) {
+ FfiConverterTypeHashMethod.write(value.method, into: &buf)
+ FfiConverterString.write(value.value, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHash_lift(_ buf: RustBuffer) throws -> Hash {
+ return try FfiConverterTypeHash.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHash_lower(_ value: Hash) -> RustBuffer {
+ return FfiConverterTypeHash.lower(value)
+}
+
+
+public struct Image: Equatable, Hashable, Codable {
+ public var id: String
+ public var url: String
+ public var theme: ImageTheme
+ public var format: ImageFormat
+ public var description: String?
+ public var width: UInt32?
+ public var height: UInt32?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(id: String, url: String, theme: ImageTheme, format: ImageFormat, description: String?, width: UInt32?, height: UInt32?) {
+ self.id = id
+ self.url = url
+ self.theme = theme
+ self.format = format
+ self.description = description
+ self.width = width
+ self.height = height
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Image: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeImage: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Image {
+ return
+ try Image(
+ id: FfiConverterString.read(from: &buf),
+ url: FfiConverterString.read(from: &buf),
+ theme: FfiConverterTypeImageTheme.read(from: &buf),
+ format: FfiConverterTypeImageFormat.read(from: &buf),
+ description: FfiConverterOptionString.read(from: &buf),
+ width: FfiConverterOptionUInt32.read(from: &buf),
+ height: FfiConverterOptionUInt32.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Image, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.id, into: &buf)
+ FfiConverterString.write(value.url, into: &buf)
+ FfiConverterTypeImageTheme.write(value.theme, into: &buf)
+ FfiConverterTypeImageFormat.write(value.format, into: &buf)
+ FfiConverterOptionString.write(value.description, into: &buf)
+ FfiConverterOptionUInt32.write(value.width, into: &buf)
+ FfiConverterOptionUInt32.write(value.height, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeImage_lift(_ buf: RustBuffer) throws -> Image {
+ return try FfiConverterTypeImage.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeImage_lower(_ value: Image) -> RustBuffer {
+ return FfiConverterTypeImage.lower(value)
+}
+
+
+public struct Metadata: Equatable, Hashable, Codable {
+ public var identifier: String
+ public var name: String
+ public var description: String?
+ public var icons: [Image]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(identifier: String, name: String, description: String?, icons: [Image]) {
+ self.identifier = identifier
+ self.name = name
+ self.description = description
+ self.icons = icons
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Metadata: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeMetadata: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Metadata {
+ return
+ try Metadata(
+ identifier: FfiConverterString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ description: FfiConverterOptionString.read(from: &buf),
+ icons: FfiConverterSequenceTypeImage.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Metadata, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.identifier, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterOptionString.write(value.description, into: &buf)
+ FfiConverterSequenceTypeImage.write(value.icons, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeMetadata_lift(_ buf: RustBuffer) throws -> Metadata {
+ return try FfiConverterTypeMetadata.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeMetadata_lower(_ value: Metadata) -> RustBuffer {
+ return FfiConverterTypeMetadata.lower(value)
+}
+
+
+public struct Model: Equatable, Hashable, Codable {
+ public var identifier: String
+ public var registry: ModelRegistry
+ public var backends: [ModelBackend]
+ public var family: ModelFamily?
+ public var properties: ModelProperties?
+ public var quantization: ModelQuantization?
+ public var specializations: [ModelSpecialization]
+ public var accessibility: ModelAccessibility
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(identifier: String, registry: ModelRegistry, backends: [ModelBackend], family: ModelFamily?, properties: ModelProperties?, quantization: ModelQuantization?, specializations: [ModelSpecialization], accessibility: ModelAccessibility) {
+ self.identifier = identifier
+ self.registry = registry
+ self.backends = backends
+ self.family = family
+ self.properties = properties
+ self.quantization = quantization
+ self.specializations = specializations
+ self.accessibility = accessibility
+ }
+
+
+public func cacheIdentifier() -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_cache_identifier(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func checkpointVersion() -> String? {
+ return try! FfiConverterOptionString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_checkpoint_version(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func isChatCapable() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_is_chat_capable(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func isClassificationCapable() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_is_classification_capable(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func isDownloadable() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_is_downloadable(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func isLocal() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_is_local(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func isQuantized() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_is_quantized(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func isRemote() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_is_remote(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func isSpeculationCapable() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_is_speculation_capable(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func isTextToSpeechCapable() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_is_text_to_speech_capable(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func isTranslationCapable() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_is_translation_capable(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func localExternalPath() -> String? {
+ return try! FfiConverterOptionString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_local_external_path(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func name() -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_name(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func referenceName() -> String? {
+ return try! FfiConverterOptionString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_reference_name(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+public func repoIds() -> [String] {
+ return try! FfiConverterSequenceString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_model_repo_ids(
+ FfiConverterTypeModel_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension Model: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeModel: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Model {
+ return
+ try Model(
+ identifier: FfiConverterString.read(from: &buf),
+ registry: FfiConverterTypeModelRegistry.read(from: &buf),
+ backends: FfiConverterSequenceTypeModelBackend.read(from: &buf),
+ family: FfiConverterOptionTypeModelFamily.read(from: &buf),
+ properties: FfiConverterOptionTypeModelProperties.read(from: &buf),
+ quantization: FfiConverterOptionTypeModelQuantization.read(from: &buf),
+ specializations: FfiConverterSequenceTypeModelSpecialization.read(from: &buf),
+ accessibility: FfiConverterTypeModelAccessibility.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Model, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.identifier, into: &buf)
+ FfiConverterTypeModelRegistry.write(value.registry, into: &buf)
+ FfiConverterSequenceTypeModelBackend.write(value.backends, into: &buf)
+ FfiConverterOptionTypeModelFamily.write(value.family, into: &buf)
+ FfiConverterOptionTypeModelProperties.write(value.properties, into: &buf)
+ FfiConverterOptionTypeModelQuantization.write(value.quantization, into: &buf)
+ FfiConverterSequenceTypeModelSpecialization.write(value.specializations, into: &buf)
+ FfiConverterTypeModelAccessibility.write(value.accessibility, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModel_lift(_ buf: RustBuffer) throws -> Model {
+ return try FfiConverterTypeModel.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModel_lower(_ value: Model) -> RustBuffer {
+ return FfiConverterTypeModel.lower(value)
+}
+
+
+public struct ModelBackend: Equatable, Hashable, Codable {
+ public var identifier: String
+ public var version: String
+ public var metadata: Metadata
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(identifier: String, version: String, metadata: Metadata) {
+ self.identifier = identifier
+ self.version = version
+ self.metadata = metadata
+ }
+
+
+public func name() -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_modelbackend_name(
+ FfiConverterTypeModelBackend_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension ModelBackend: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeModelBackend: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelBackend {
+ return
+ try ModelBackend(
+ identifier: FfiConverterString.read(from: &buf),
+ version: FfiConverterString.read(from: &buf),
+ metadata: FfiConverterTypeMetadata.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ModelBackend, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.identifier, into: &buf)
+ FfiConverterString.write(value.version, into: &buf)
+ FfiConverterTypeMetadata.write(value.metadata, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelBackend_lift(_ buf: RustBuffer) throws -> ModelBackend {
+ return try FfiConverterTypeModelBackend.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelBackend_lower(_ value: ModelBackend) -> RustBuffer {
+ return FfiConverterTypeModelBackend.lower(value)
+}
+
+
+public struct ModelFamily: Equatable, Hashable, Codable {
+ public var identifier: String
+ public var vendor: ModelVendor
+ public var metadata: Metadata
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(identifier: String, vendor: ModelVendor, metadata: Metadata) {
+ self.identifier = identifier
+ self.vendor = vendor
+ self.metadata = metadata
+ }
+
+
+public func name() -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_modelfamily_name(
+ FfiConverterTypeModelFamily_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension ModelFamily: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeModelFamily: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelFamily {
+ return
+ try ModelFamily(
+ identifier: FfiConverterString.read(from: &buf),
+ vendor: FfiConverterTypeModelVendor.read(from: &buf),
+ metadata: FfiConverterTypeMetadata.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ModelFamily, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.identifier, into: &buf)
+ FfiConverterTypeModelVendor.write(value.vendor, into: &buf)
+ FfiConverterTypeMetadata.write(value.metadata, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelFamily_lift(_ buf: RustBuffer) throws -> ModelFamily {
+ return try FfiConverterTypeModelFamily.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelFamily_lower(_ value: ModelFamily) -> RustBuffer {
+ return FfiConverterTypeModelFamily.lower(value)
+}
+
+
+public struct ModelProperties: Equatable, Hashable, Codable {
+ public var identifier: String
+ public var size: Int64
+ public var version: String?
+ public var metadata: Metadata
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(identifier: String, size: Int64, version: String?, metadata: Metadata) {
+ self.identifier = identifier
+ self.size = size
+ self.version = version
+ self.metadata = metadata
+ }
+
+
+public func name() -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_modelproperties_name(
+ FfiConverterTypeModelProperties_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension ModelProperties: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeModelProperties: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelProperties {
+ return
+ try ModelProperties(
+ identifier: FfiConverterString.read(from: &buf),
+ size: FfiConverterInt64.read(from: &buf),
+ version: FfiConverterOptionString.read(from: &buf),
+ metadata: FfiConverterTypeMetadata.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ModelProperties, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.identifier, into: &buf)
+ FfiConverterInt64.write(value.size, into: &buf)
+ FfiConverterOptionString.write(value.version, into: &buf)
+ FfiConverterTypeMetadata.write(value.metadata, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelProperties_lift(_ buf: RustBuffer) throws -> ModelProperties {
+ return try FfiConverterTypeModelProperties.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelProperties_lower(_ value: ModelProperties) -> RustBuffer {
+ return FfiConverterTypeModelProperties.lower(value)
+}
+
+
+public struct ModelQuantization: Equatable, Hashable, Codable {
+ public var identifier: String
+ public var method: String
+ public var bitsPerWeight: UInt32
+ public var vendor: ModelVendor
+ public var metadata: Metadata
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(identifier: String, method: String, bitsPerWeight: UInt32, vendor: ModelVendor, metadata: Metadata) {
+ self.identifier = identifier
+ self.method = method
+ self.bitsPerWeight = bitsPerWeight
+ self.vendor = vendor
+ self.metadata = metadata
+ }
+
+
+public func name() -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_modelquantization_name(
+ FfiConverterTypeModelQuantization_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension ModelQuantization: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeModelQuantization: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelQuantization {
+ return
+ try ModelQuantization(
+ identifier: FfiConverterString.read(from: &buf),
+ method: FfiConverterString.read(from: &buf),
+ bitsPerWeight: FfiConverterUInt32.read(from: &buf),
+ vendor: FfiConverterTypeModelVendor.read(from: &buf),
+ metadata: FfiConverterTypeMetadata.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ModelQuantization, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.identifier, into: &buf)
+ FfiConverterString.write(value.method, into: &buf)
+ FfiConverterUInt32.write(value.bitsPerWeight, into: &buf)
+ FfiConverterTypeModelVendor.write(value.vendor, into: &buf)
+ FfiConverterTypeMetadata.write(value.metadata, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelQuantization_lift(_ buf: RustBuffer) throws -> ModelQuantization {
+ return try FfiConverterTypeModelQuantization.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelQuantization_lower(_ value: ModelQuantization) -> RustBuffer {
+ return FfiConverterTypeModelQuantization.lower(value)
+}
+
+
+public struct ModelRegistry: Equatable, Hashable, Codable {
+ public var identifier: String
+ public var metadata: Metadata
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(identifier: String, metadata: Metadata) {
+ self.identifier = identifier
+ self.metadata = metadata
+ }
+
+
+public func name() -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_modelregistry_name(
+ FfiConverterTypeModelRegistry_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension ModelRegistry: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeModelRegistry: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelRegistry {
+ return
+ try ModelRegistry(
+ identifier: FfiConverterString.read(from: &buf),
+ metadata: FfiConverterTypeMetadata.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ModelRegistry, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.identifier, into: &buf)
+ FfiConverterTypeMetadata.write(value.metadata, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelRegistry_lift(_ buf: RustBuffer) throws -> ModelRegistry {
+ return try FfiConverterTypeModelRegistry.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelRegistry_lower(_ value: ModelRegistry) -> RustBuffer {
+ return FfiConverterTypeModelRegistry.lower(value)
+}
+
+
+public struct ModelVendor: Equatable, Hashable, Codable {
+ public var identifier: String
+ public var metadata: Metadata
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(identifier: String, metadata: Metadata) {
+ self.identifier = identifier
+ self.metadata = metadata
+ }
+
+
+public func name() -> String {
+ return try! FfiConverterString.lift(try! rustCall() {
+ uniffi_shoji_fn_method_modelvendor_name(
+ FfiConverterTypeModelVendor_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension ModelVendor: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeModelVendor: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelVendor {
+ return
+ try ModelVendor(
+ identifier: FfiConverterString.read(from: &buf),
+ metadata: FfiConverterTypeMetadata.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ModelVendor, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.identifier, into: &buf)
+ FfiConverterTypeMetadata.write(value.metadata, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelVendor_lift(_ buf: RustBuffer) throws -> ModelVendor {
+ return try FfiConverterTypeModelVendor.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelVendor_lower(_ value: ModelVendor) -> RustBuffer {
+ return FfiConverterTypeModelVendor.lower(value)
+}
+
+
+public struct PcmBatch: Equatable, Hashable, Codable {
+ public var samples: [Double]
+ public var sampleRate: UInt32
+ public var channels: UInt32
+ public var lengths: [UInt32]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(samples: [Double], sampleRate: UInt32, channels: UInt32, lengths: [UInt32]) {
+ self.samples = samples
+ self.sampleRate = sampleRate
+ self.channels = channels
+ self.lengths = lengths
+ }
+
+
+public func batchSize() -> UInt32 {
+ return try! FfiConverterUInt32.lift(try! rustCall() {
+ uniffi_shoji_fn_method_pcmbatch_batch_size(
+ FfiConverterTypePcmBatch_lower(self),$0
+ )
+})
+}
+
+public func saveAsWav(path: String)throws {try rustCallWithError(FfiConverterTypePcmBatchError_lift) {
+ uniffi_shoji_fn_method_pcmbatch_save_as_wav(
+ FfiConverterTypePcmBatch_lower(self),
+ FfiConverterString.lower(path),$0
+ )
+}
+}
+
+public func totalFrames() -> UInt32 {
+ return try! FfiConverterUInt32.lift(try! rustCall() {
+ uniffi_shoji_fn_method_pcmbatch_total_frames(
+ FfiConverterTypePcmBatch_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension PcmBatch: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypePcmBatch: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PcmBatch {
+ return
+ try PcmBatch(
+ samples: FfiConverterSequenceDouble.read(from: &buf),
+ sampleRate: FfiConverterUInt32.read(from: &buf),
+ channels: FfiConverterUInt32.read(from: &buf),
+ lengths: FfiConverterSequenceUInt32.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: PcmBatch, into buf: inout [UInt8]) {
+ FfiConverterSequenceDouble.write(value.samples, into: &buf)
+ FfiConverterUInt32.write(value.sampleRate, into: &buf)
+ FfiConverterUInt32.write(value.channels, into: &buf)
+ FfiConverterSequenceUInt32.write(value.lengths, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePcmBatch_lift(_ buf: RustBuffer) throws -> PcmBatch {
+ return try FfiConverterTypePcmBatch.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePcmBatch_lower(_ value: PcmBatch) -> RustBuffer {
+ return FfiConverterTypePcmBatch.lower(value)
+}
+
+
+public struct Repository: Equatable, Hashable, Codable {
+ public var identifier: String
+ public var commitHash: String?
+ public var paths: [String]?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(identifier: String, commitHash: String?, paths: [String]?) {
+ self.identifier = identifier
+ self.commitHash = commitHash
+ self.paths = paths
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Repository: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeRepository: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Repository {
+ return
+ try Repository(
+ identifier: FfiConverterString.read(from: &buf),
+ commitHash: FfiConverterOptionString.read(from: &buf),
+ paths: FfiConverterOptionSequenceString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Repository, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.identifier, into: &buf)
+ FfiConverterOptionString.write(value.commitHash, into: &buf)
+ FfiConverterOptionSequenceString.write(value.paths, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRepository_lift(_ buf: RustBuffer) throws -> Repository {
+ return try FfiConverterTypeRepository.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRepository_lower(_ value: Repository) -> RustBuffer {
+ return FfiConverterTypeRepository.lower(value)
+}
+
+
+public struct TextToSpeechStats: Equatable, Hashable, Codable {
+ public var textLength: UInt32
+ public var firstChunkSeconds: Double
+ public var generationDuration: Double
+ public var audioDuration: Double
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(textLength: UInt32, firstChunkSeconds: Double, generationDuration: Double, audioDuration: Double) {
+ self.textLength = textLength
+ self.firstChunkSeconds = firstChunkSeconds
+ self.generationDuration = generationDuration
+ self.audioDuration = audioDuration
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension TextToSpeechStats: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeTextToSpeechStats: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> TextToSpeechStats {
+ return
+ try TextToSpeechStats(
+ textLength: FfiConverterUInt32.read(from: &buf),
+ firstChunkSeconds: FfiConverterDouble.read(from: &buf),
+ generationDuration: FfiConverterDouble.read(from: &buf),
+ audioDuration: FfiConverterDouble.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: TextToSpeechStats, into buf: inout [UInt8]) {
+ FfiConverterUInt32.write(value.textLength, into: &buf)
+ FfiConverterDouble.write(value.firstChunkSeconds, into: &buf)
+ FfiConverterDouble.write(value.generationDuration, into: &buf)
+ FfiConverterDouble.write(value.audioDuration, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechStats_lift(_ buf: RustBuffer) throws -> TextToSpeechStats {
+ return try FfiConverterTypeTextToSpeechStats.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTextToSpeechStats_lower(_ value: TextToSpeechStats) -> RustBuffer {
+ return FfiConverterTypeTextToSpeechStats.lower(value)
+}
+
+
+public struct Token: Equatable, Hashable, Codable {
+ public var id: UInt32
+ public var value: String
+ public var isSpecial: Bool
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(id: UInt32, value: String, isSpecial: Bool) {
+ self.id = id
+ self.value = value
+ self.isSpecial = isSpecial
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Token: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeToken: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Token {
+ return
+ try Token(
+ id: FfiConverterUInt32.read(from: &buf),
+ value: FfiConverterString.read(from: &buf),
+ isSpecial: FfiConverterBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Token, into buf: inout [UInt8]) {
+ FfiConverterUInt32.write(value.id, into: &buf)
+ FfiConverterString.write(value.value, into: &buf)
+ FfiConverterBool.write(value.isSpecial, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeToken_lift(_ buf: RustBuffer) throws -> Token {
+ return try FfiConverterTypeToken.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeToken_lower(_ value: Token) -> RustBuffer {
+ return FfiConverterTypeToken.lower(value)
+}
+
+
+public struct ToolCall: Equatable, Hashable, Codable {
+ public var identifier: String?
+ public var name: String
+ public var arguments: Value
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(identifier: String?, name: String, arguments: Value) {
+ self.identifier = identifier
+ self.name = name
+ self.arguments = arguments
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ToolCall: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeToolCall: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ToolCall {
+ return
+ try ToolCall(
+ identifier: FfiConverterOptionString.read(from: &buf),
+ name: FfiConverterString.read(from: &buf),
+ arguments: FfiConverterTypeValue.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ToolCall, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.identifier, into: &buf)
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterTypeValue.write(value.arguments, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeToolCall_lift(_ buf: RustBuffer) throws -> ToolCall {
+ return try FfiConverterTypeToolCall.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeToolCall_lower(_ value: ToolCall) -> RustBuffer {
+ return FfiConverterTypeToolCall.lower(value)
+}
+
+
+public struct ToolFunction: Equatable, Hashable, Codable {
+ public var name: String
+ public var description: String
+ public var parameters: Value?
+ public var returnDefinition: Value?
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(name: String, description: String, parameters: Value?, returnDefinition: Value?) {
+ self.name = name
+ self.description = description
+ self.parameters = parameters
+ self.returnDefinition = returnDefinition
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ToolFunction: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeToolFunction: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ToolFunction {
+ return
+ try ToolFunction(
+ name: FfiConverterString.read(from: &buf),
+ description: FfiConverterString.read(from: &buf),
+ parameters: FfiConverterOptionTypeValue.read(from: &buf),
+ returnDefinition: FfiConverterOptionTypeValue.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ToolFunction, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterString.write(value.description, into: &buf)
+ FfiConverterOptionTypeValue.write(value.parameters, into: &buf)
+ FfiConverterOptionTypeValue.write(value.returnDefinition, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeToolFunction_lift(_ buf: RustBuffer) throws -> ToolFunction {
+ return try FfiConverterTypeToolFunction.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeToolFunction_lower(_ value: ToolFunction) -> RustBuffer {
+ return FfiConverterTypeToolFunction.lower(value)
+}
+
+
+public struct ToolNamespace: Equatable, Hashable, Codable {
+ public var name: String
+ public var description: String?
+ public var tools: [ToolDescription]
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(name: String, description: String?, tools: [ToolDescription]) {
+ self.name = name
+ self.description = description
+ self.tools = tools
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ToolNamespace: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeToolNamespace: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ToolNamespace {
+ return
+ try ToolNamespace(
+ name: FfiConverterString.read(from: &buf),
+ description: FfiConverterOptionString.read(from: &buf),
+ tools: FfiConverterSequenceTypeToolDescription.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: ToolNamespace, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.name, into: &buf)
+ FfiConverterOptionString.write(value.description, into: &buf)
+ FfiConverterSequenceTypeToolDescription.write(value.tools, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeToolNamespace_lift(_ buf: RustBuffer) throws -> ToolNamespace {
+ return try FfiConverterTypeToolNamespace.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeToolNamespace_lower(_ value: ToolNamespace) -> RustBuffer {
+ return FfiConverterTypeToolNamespace.lower(value)
+}
+
+
+public struct Value: Equatable, Hashable, Codable {
+ public var json: String
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(json: String) {
+ self.json = json
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Value: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeValue: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Value {
+ return
+ try Value(
+ json: FfiConverterString.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Value, into buf: inout [UInt8]) {
+ FfiConverterString.write(value.json, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeValue_lift(_ buf: RustBuffer) throws -> Value {
+ return try FfiConverterTypeValue.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeValue_lower(_ value: Value) -> RustBuffer {
+ return FfiConverterTypeValue.lower(value)
+}
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ChatContentBlock: Equatable, Hashable, Codable {
+
+ case identity(value: String
+ )
+ case reasoningEffort(value: ReasoningEffort
+ )
+ case conversationStartDate(value: String
+ )
+ case knowledgeCutoff(value: String
+ )
+ case builtinTools(names: [String]
+ )
+ case tools(namespaces: [ToolNamespace]
+ )
+ case text(value: String
+ )
+ case image(url: String
+ )
+ case video(url: String
+ )
+ case audio(url: String
+ )
+ case file(url: String
+ )
+ case reasoning(value: String
+ )
+ case toolCall(value: ToolCall
+ )
+ case toolCallCandidate(value: Value
+ )
+ case toolCallResult(identifier: String?, name: String?, value: Value
+ )
+ case translation(payload: TranslationPayload, sourceLanguageCode: String, targetLanguageCode: String
+ )
+ case custom(value: Value
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatContentBlock: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatContentBlock: FfiConverterRustBuffer {
+ typealias SwiftType = ChatContentBlock
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatContentBlock {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .identity(value: try FfiConverterString.read(from: &buf)
+ )
+
+ case 2: return .reasoningEffort(value: try FfiConverterTypeReasoningEffort.read(from: &buf)
+ )
+
+ case 3: return .conversationStartDate(value: try FfiConverterString.read(from: &buf)
+ )
+
+ case 4: return .knowledgeCutoff(value: try FfiConverterString.read(from: &buf)
+ )
+
+ case 5: return .builtinTools(names: try FfiConverterSequenceString.read(from: &buf)
+ )
+
+ case 6: return .tools(namespaces: try FfiConverterSequenceTypeToolNamespace.read(from: &buf)
+ )
+
+ case 7: return .text(value: try FfiConverterString.read(from: &buf)
+ )
+
+ case 8: return .image(url: try FfiConverterString.read(from: &buf)
+ )
+
+ case 9: return .video(url: try FfiConverterString.read(from: &buf)
+ )
+
+ case 10: return .audio(url: try FfiConverterString.read(from: &buf)
+ )
+
+ case 11: return .file(url: try FfiConverterString.read(from: &buf)
+ )
+
+ case 12: return .reasoning(value: try FfiConverterString.read(from: &buf)
+ )
+
+ case 13: return .toolCall(value: try FfiConverterTypeToolCall.read(from: &buf)
+ )
+
+ case 14: return .toolCallCandidate(value: try FfiConverterTypeValue.read(from: &buf)
+ )
+
+ case 15: return .toolCallResult(identifier: try FfiConverterOptionString.read(from: &buf), name: try FfiConverterOptionString.read(from: &buf), value: try FfiConverterTypeValue.read(from: &buf)
+ )
+
+ case 16: return .translation(payload: try FfiConverterTypeTranslationPayload.read(from: &buf), sourceLanguageCode: try FfiConverterString.read(from: &buf), targetLanguageCode: try FfiConverterString.read(from: &buf)
+ )
+
+ case 17: return .custom(value: try FfiConverterTypeValue.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ChatContentBlock, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case let .identity(value):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(value, into: &buf)
+
+
+ case let .reasoningEffort(value):
+ writeInt(&buf, Int32(2))
+ FfiConverterTypeReasoningEffort.write(value, into: &buf)
+
+
+ case let .conversationStartDate(value):
+ writeInt(&buf, Int32(3))
+ FfiConverterString.write(value, into: &buf)
+
+
+ case let .knowledgeCutoff(value):
+ writeInt(&buf, Int32(4))
+ FfiConverterString.write(value, into: &buf)
+
+
+ case let .builtinTools(names):
+ writeInt(&buf, Int32(5))
+ FfiConverterSequenceString.write(names, into: &buf)
+
+
+ case let .tools(namespaces):
+ writeInt(&buf, Int32(6))
+ FfiConverterSequenceTypeToolNamespace.write(namespaces, into: &buf)
+
+
+ case let .text(value):
+ writeInt(&buf, Int32(7))
+ FfiConverterString.write(value, into: &buf)
+
+
+ case let .image(url):
+ writeInt(&buf, Int32(8))
+ FfiConverterString.write(url, into: &buf)
+
+
+ case let .video(url):
+ writeInt(&buf, Int32(9))
+ FfiConverterString.write(url, into: &buf)
+
+
+ case let .audio(url):
+ writeInt(&buf, Int32(10))
+ FfiConverterString.write(url, into: &buf)
+
+
+ case let .file(url):
+ writeInt(&buf, Int32(11))
+ FfiConverterString.write(url, into: &buf)
+
+
+ case let .reasoning(value):
+ writeInt(&buf, Int32(12))
+ FfiConverterString.write(value, into: &buf)
+
+
+ case let .toolCall(value):
+ writeInt(&buf, Int32(13))
+ FfiConverterTypeToolCall.write(value, into: &buf)
+
+
+ case let .toolCallCandidate(value):
+ writeInt(&buf, Int32(14))
+ FfiConverterTypeValue.write(value, into: &buf)
+
+
+ case let .toolCallResult(identifier,name,value):
+ writeInt(&buf, Int32(15))
+ FfiConverterOptionString.write(identifier, into: &buf)
+ FfiConverterOptionString.write(name, into: &buf)
+ FfiConverterTypeValue.write(value, into: &buf)
+
+
+ case let .translation(payload,sourceLanguageCode,targetLanguageCode):
+ writeInt(&buf, Int32(16))
+ FfiConverterTypeTranslationPayload.write(payload, into: &buf)
+ FfiConverterString.write(sourceLanguageCode, into: &buf)
+ FfiConverterString.write(targetLanguageCode, into: &buf)
+
+
+ case let .custom(value):
+ writeInt(&buf, Int32(17))
+ FfiConverterTypeValue.write(value, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatContentBlock_lift(_ buf: RustBuffer) throws -> ChatContentBlock {
+ return try FfiConverterTypeChatContentBlock.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatContentBlock_lower(_ value: ChatContentBlock) -> RustBuffer {
+ return FfiConverterTypeChatContentBlock.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ChatContentBlockType: Equatable, Hashable, Codable {
+
+ case identity
+ case reasoningEffort
+ case conversationStartDate
+ case knowledgeCutoff
+ case builtinTools
+ case tools
+ case text
+ case image
+ case video
+ case audio
+ case file
+ case reasoning
+ case toolCall
+ case toolCallCandidate
+ case toolCallResult
+ case translation
+ case custom
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatContentBlockType: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatContentBlockType: FfiConverterRustBuffer {
+ typealias SwiftType = ChatContentBlockType
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatContentBlockType {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .identity
+
+ case 2: return .reasoningEffort
+
+ case 3: return .conversationStartDate
+
+ case 4: return .knowledgeCutoff
+
+ case 5: return .builtinTools
+
+ case 6: return .tools
+
+ case 7: return .text
+
+ case 8: return .image
+
+ case 9: return .video
+
+ case 10: return .audio
+
+ case 11: return .file
+
+ case 12: return .reasoning
+
+ case 13: return .toolCall
+
+ case 14: return .toolCallCandidate
+
+ case 15: return .toolCallResult
+
+ case 16: return .translation
+
+ case 17: return .custom
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ChatContentBlockType, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .identity:
+ writeInt(&buf, Int32(1))
+
+
+ case .reasoningEffort:
+ writeInt(&buf, Int32(2))
+
+
+ case .conversationStartDate:
+ writeInt(&buf, Int32(3))
+
+
+ case .knowledgeCutoff:
+ writeInt(&buf, Int32(4))
+
+
+ case .builtinTools:
+ writeInt(&buf, Int32(5))
+
+
+ case .tools:
+ writeInt(&buf, Int32(6))
+
+
+ case .text:
+ writeInt(&buf, Int32(7))
+
+
+ case .image:
+ writeInt(&buf, Int32(8))
+
+
+ case .video:
+ writeInt(&buf, Int32(9))
+
+
+ case .audio:
+ writeInt(&buf, Int32(10))
+
+
+ case .file:
+ writeInt(&buf, Int32(11))
+
+
+ case .reasoning:
+ writeInt(&buf, Int32(12))
+
+
+ case .toolCall:
+ writeInt(&buf, Int32(13))
+
+
+ case .toolCallCandidate:
+ writeInt(&buf, Int32(14))
+
+
+ case .toolCallResult:
+ writeInt(&buf, Int32(15))
+
+
+ case .translation:
+ writeInt(&buf, Int32(16))
+
+
+ case .custom:
+ writeInt(&buf, Int32(17))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatContentBlockType_lift(_ buf: RustBuffer) throws -> ChatContentBlockType {
+ return try FfiConverterTypeChatContentBlockType.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatContentBlockType_lower(_ value: ChatContentBlockType) -> RustBuffer {
+ return FfiConverterTypeChatContentBlockType.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ChatReplyFinishReason: Equatable, Hashable, Codable {
+
+ case stop
+ case length
+ case cancelled
+ case contextLimitReached
+ case toolCalls
+ case rejected
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatReplyFinishReason: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatReplyFinishReason: FfiConverterRustBuffer {
+ typealias SwiftType = ChatReplyFinishReason
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatReplyFinishReason {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .stop
+
+ case 2: return .length
+
+ case 3: return .cancelled
+
+ case 4: return .contextLimitReached
+
+ case 5: return .toolCalls
+
+ case 6: return .rejected
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ChatReplyFinishReason, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .stop:
+ writeInt(&buf, Int32(1))
+
+
+ case .length:
+ writeInt(&buf, Int32(2))
+
+
+ case .cancelled:
+ writeInt(&buf, Int32(3))
+
+
+ case .contextLimitReached:
+ writeInt(&buf, Int32(4))
+
+
+ case .toolCalls:
+ writeInt(&buf, Int32(5))
+
+
+ case .rejected:
+ writeInt(&buf, Int32(6))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatReplyFinishReason_lift(_ buf: RustBuffer) throws -> ChatReplyFinishReason {
+ return try FfiConverterTypeChatReplyFinishReason.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatReplyFinishReason_lower(_ value: ChatReplyFinishReason) -> RustBuffer {
+ return FfiConverterTypeChatReplyFinishReason.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ChatRole: Equatable, Hashable, Codable {
+
+ case user
+ case assistant
+ case system
+ case developer
+ case tool
+ case custom(name: String
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatRole: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatRole: FfiConverterRustBuffer {
+ typealias SwiftType = ChatRole
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatRole {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .user
+
+ case 2: return .assistant
+
+ case 3: return .system
+
+ case 4: return .developer
+
+ case 5: return .tool
+
+ case 6: return .custom(name: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ChatRole, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .user:
+ writeInt(&buf, Int32(1))
+
+
+ case .assistant:
+ writeInt(&buf, Int32(2))
+
+
+ case .system:
+ writeInt(&buf, Int32(3))
+
+
+ case .developer:
+ writeInt(&buf, Int32(4))
+
+
+ case .tool:
+ writeInt(&buf, Int32(5))
+
+
+ case let .custom(name):
+ writeInt(&buf, Int32(6))
+ FfiConverterString.write(name, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatRole_lift(_ buf: RustBuffer) throws -> ChatRole {
+ return try FfiConverterTypeChatRole.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatRole_lower(_ value: ChatRole) -> RustBuffer {
+ return FfiConverterTypeChatRole.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ChatSpeculationPreset: Equatable, Hashable, Codable {
+
+ case generalChat
+ case summarization
+ case classification(feature: Feature
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ChatSpeculationPreset: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeChatSpeculationPreset: FfiConverterRustBuffer {
+ typealias SwiftType = ChatSpeculationPreset
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ChatSpeculationPreset {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .generalChat
+
+ case 2: return .summarization
+
+ case 3: return .classification(feature: try FfiConverterTypeFeature.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ChatSpeculationPreset, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .generalChat:
+ writeInt(&buf, Int32(1))
+
+
+ case .summarization:
+ writeInt(&buf, Int32(2))
+
+
+ case let .classification(feature):
+ writeInt(&buf, Int32(3))
+ FfiConverterTypeFeature.write(feature, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSpeculationPreset_lift(_ buf: RustBuffer) throws -> ChatSpeculationPreset {
+ return try FfiConverterTypeChatSpeculationPreset.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeChatSpeculationPreset_lower(_ value: ChatSpeculationPreset) -> RustBuffer {
+ return FfiConverterTypeChatSpeculationPreset.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ClassificationRole: Equatable, Hashable, Codable {
+
+ case user
+ case assistant
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ClassificationRole: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeClassificationRole: FfiConverterRustBuffer {
+ typealias SwiftType = ClassificationRole
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ClassificationRole {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .user
+
+ case 2: return .assistant
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ClassificationRole, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .user:
+ writeInt(&buf, Int32(1))
+
+
+ case .assistant:
+ writeInt(&buf, Int32(2))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationRole_lift(_ buf: RustBuffer) throws -> ClassificationRole {
+ return try FfiConverterTypeClassificationRole.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeClassificationRole_lower(_ value: ClassificationRole) -> RustBuffer {
+ return FfiConverterTypeClassificationRole.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ContextLength: Equatable, Hashable, Codable {
+
+ case `default`
+ case maximal
+ case custom(length: Int64
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ContextLength: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeContextLength: FfiConverterRustBuffer {
+ typealias SwiftType = ContextLength
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ContextLength {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .`default`
+
+ case 2: return .maximal
+
+ case 3: return .custom(length: try FfiConverterInt64.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ContextLength, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .`default`:
+ writeInt(&buf, Int32(1))
+
+
+ case .maximal:
+ writeInt(&buf, Int32(2))
+
+
+ case let .custom(length):
+ writeInt(&buf, Int32(3))
+ FfiConverterInt64.write(length, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeContextLength_lift(_ buf: RustBuffer) throws -> ContextLength {
+ return try FfiConverterTypeContextLength.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeContextLength_lower(_ value: ContextLength) -> RustBuffer {
+ return FfiConverterTypeContextLength.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum Grammar: Equatable, Hashable, Codable {
+
+ case jsonAny
+ case jsonSchema(schema: String
+ )
+ case regex(pattern: String
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Grammar: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeGrammar: FfiConverterRustBuffer {
+ typealias SwiftType = Grammar
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Grammar {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .jsonAny
+
+ case 2: return .jsonSchema(schema: try FfiConverterString.read(from: &buf)
+ )
+
+ case 3: return .regex(pattern: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: Grammar, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .jsonAny:
+ writeInt(&buf, Int32(1))
+
+
+ case let .jsonSchema(schema):
+ writeInt(&buf, Int32(2))
+ FfiConverterString.write(schema, into: &buf)
+
+
+ case let .regex(pattern):
+ writeInt(&buf, Int32(3))
+ FfiConverterString.write(pattern, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeGrammar_lift(_ buf: RustBuffer) throws -> Grammar {
+ return try FfiConverterTypeGrammar.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeGrammar_lower(_ value: Grammar) -> RustBuffer {
+ return FfiConverterTypeGrammar.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum HashMethod: Equatable, Hashable, Codable {
+
+ case crc32c
+ case md5
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension HashMethod: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeHashMethod: FfiConverterRustBuffer {
+ typealias SwiftType = HashMethod
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> HashMethod {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .crc32c
+
+ case 2: return .md5
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: HashMethod, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .crc32c:
+ writeInt(&buf, Int32(1))
+
+
+ case .md5:
+ writeInt(&buf, Int32(2))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHashMethod_lift(_ buf: RustBuffer) throws -> HashMethod {
+ return try FfiConverterTypeHashMethod.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeHashMethod_lower(_ value: HashMethod) -> RustBuffer {
+ return FfiConverterTypeHashMethod.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ImageFormat: Equatable, Hashable, Codable {
+
+ case png
+ case webp
+ case svg
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ImageFormat: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeImageFormat: FfiConverterRustBuffer {
+ typealias SwiftType = ImageFormat
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ImageFormat {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .png
+
+ case 2: return .webp
+
+ case 3: return .svg
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ImageFormat, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .png:
+ writeInt(&buf, Int32(1))
+
+
+ case .webp:
+ writeInt(&buf, Int32(2))
+
+
+ case .svg:
+ writeInt(&buf, Int32(3))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeImageFormat_lift(_ buf: RustBuffer) throws -> ImageFormat {
+ return try FfiConverterTypeImageFormat.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeImageFormat_lower(_ value: ImageFormat) -> RustBuffer {
+ return FfiConverterTypeImageFormat.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ImageTheme: Equatable, Hashable, Codable {
+
+ case light
+ case dark
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ImageTheme: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeImageTheme: FfiConverterRustBuffer {
+ typealias SwiftType = ImageTheme
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ImageTheme {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .light
+
+ case 2: return .dark
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ImageTheme, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .light:
+ writeInt(&buf, Int32(1))
+
+
+ case .dark:
+ writeInt(&buf, Int32(2))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeImageTheme_lift(_ buf: RustBuffer) throws -> ImageTheme {
+ return try FfiConverterTypeImageTheme.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeImageTheme_lower(_ value: ImageTheme) -> RustBuffer {
+ return FfiConverterTypeImageTheme.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ModelAccessibility: Equatable, Hashable, Codable {
+
+ case local(reference: ModelReference
+ )
+ case remote(repository: Repository?
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ModelAccessibility: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeModelAccessibility: FfiConverterRustBuffer {
+ typealias SwiftType = ModelAccessibility
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelAccessibility {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .local(reference: try FfiConverterTypeModelReference.read(from: &buf)
+ )
+
+ case 2: return .remote(repository: try FfiConverterOptionTypeRepository.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ModelAccessibility, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case let .local(reference):
+ writeInt(&buf, Int32(1))
+ FfiConverterTypeModelReference.write(reference, into: &buf)
+
+
+ case let .remote(repository):
+ writeInt(&buf, Int32(2))
+ FfiConverterOptionTypeRepository.write(repository, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelAccessibility_lift(_ buf: RustBuffer) throws -> ModelAccessibility {
+ return try FfiConverterTypeModelAccessibility.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelAccessibility_lower(_ value: ModelAccessibility) -> RustBuffer {
+ return FfiConverterTypeModelAccessibility.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ModelReference: Equatable, Hashable, Codable {
+
+ case mirai(toolchainVersion: String, repository: Repository?, sourceRepository: Repository?, files: [File]
+ )
+ case huggingFace(repository: Repository
+ )
+ case local(path: String
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ModelReference: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeModelReference: FfiConverterRustBuffer {
+ typealias SwiftType = ModelReference
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelReference {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .mirai(toolchainVersion: try FfiConverterString.read(from: &buf), repository: try FfiConverterOptionTypeRepository.read(from: &buf), sourceRepository: try FfiConverterOptionTypeRepository.read(from: &buf), files: try FfiConverterSequenceTypeFile.read(from: &buf)
+ )
+
+ case 2: return .huggingFace(repository: try FfiConverterTypeRepository.read(from: &buf)
+ )
+
+ case 3: return .local(path: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ModelReference, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case let .mirai(toolchainVersion,repository,sourceRepository,files):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(toolchainVersion, into: &buf)
+ FfiConverterOptionTypeRepository.write(repository, into: &buf)
+ FfiConverterOptionTypeRepository.write(sourceRepository, into: &buf)
+ FfiConverterSequenceTypeFile.write(files, into: &buf)
+
+
+ case let .huggingFace(repository):
+ writeInt(&buf, Int32(2))
+ FfiConverterTypeRepository.write(repository, into: &buf)
+
+
+ case let .local(path):
+ writeInt(&buf, Int32(3))
+ FfiConverterString.write(path, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelReference_lift(_ buf: RustBuffer) throws -> ModelReference {
+ return try FfiConverterTypeModelReference.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelReference_lower(_ value: ModelReference) -> RustBuffer {
+ return FfiConverterTypeModelReference.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ModelSpecialization: Equatable, Hashable, Codable {
+
+ case chat
+ case classification
+ case textToSpeech
+ case translation
+ case speculation
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ModelSpecialization: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeModelSpecialization: FfiConverterRustBuffer {
+ typealias SwiftType = ModelSpecialization
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ModelSpecialization {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .chat
+
+ case 2: return .classification
+
+ case 3: return .textToSpeech
+
+ case 4: return .translation
+
+ case 5: return .speculation
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ModelSpecialization, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .chat:
+ writeInt(&buf, Int32(1))
+
+
+ case .classification:
+ writeInt(&buf, Int32(2))
+
+
+ case .textToSpeech:
+ writeInt(&buf, Int32(3))
+
+
+ case .translation:
+ writeInt(&buf, Int32(4))
+
+
+ case .speculation:
+ writeInt(&buf, Int32(5))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelSpecialization_lift(_ buf: RustBuffer) throws -> ModelSpecialization {
+ return try FfiConverterTypeModelSpecialization.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeModelSpecialization_lower(_ value: ModelSpecialization) -> RustBuffer {
+ return FfiConverterTypeModelSpecialization.lower(value)
+}
+
+
+
+public enum PcmBatchError: Swift.Error, Equatable, Hashable, Codable, Foundation.LocalizedError {
+
+
+
+ case UnableToSaveAsWav(message: String
+ )
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension PcmBatchError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypePcmBatchError: FfiConverterRustBuffer {
+ typealias SwiftType = PcmBatchError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> PcmBatchError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .UnableToSaveAsWav(
+ message: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: PcmBatchError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .UnableToSaveAsWav(message):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(message, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePcmBatchError_lift(_ buf: RustBuffer) throws -> PcmBatchError {
+ return try FfiConverterTypePcmBatchError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypePcmBatchError_lower(_ value: PcmBatchError) -> RustBuffer {
+ return FfiConverterTypePcmBatchError.lower(value)
+}
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ReasoningEffort: Equatable, Hashable, Codable {
+
+ case disabled
+ case `default`
+ case low
+ case medium
+ case high
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ReasoningEffort: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeReasoningEffort: FfiConverterRustBuffer {
+ typealias SwiftType = ReasoningEffort
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ReasoningEffort {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .disabled
+
+ case 2: return .`default`
+
+ case 3: return .low
+
+ case 4: return .medium
+
+ case 5: return .high
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ReasoningEffort, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .disabled:
+ writeInt(&buf, Int32(1))
+
+
+ case .`default`:
+ writeInt(&buf, Int32(2))
+
+
+ case .low:
+ writeInt(&buf, Int32(3))
+
+
+ case .medium:
+ writeInt(&buf, Int32(4))
+
+
+ case .high:
+ writeInt(&buf, Int32(5))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeReasoningEffort_lift(_ buf: RustBuffer) throws -> ReasoningEffort {
+ return try FfiConverterTypeReasoningEffort.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeReasoningEffort_lower(_ value: ReasoningEffort) -> RustBuffer {
+ return FfiConverterTypeReasoningEffort.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum SamplingMethod: Equatable, Hashable, Codable {
+
+ case greedy
+ case stochastic(temperature: Double?, topK: Int64?, topP: Double?, minP: Double?
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SamplingMethod: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSamplingMethod: FfiConverterRustBuffer {
+ typealias SwiftType = SamplingMethod
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SamplingMethod {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .greedy
+
+ case 2: return .stochastic(temperature: try FfiConverterOptionDouble.read(from: &buf), topK: try FfiConverterOptionInt64.read(from: &buf), topP: try FfiConverterOptionDouble.read(from: &buf), minP: try FfiConverterOptionDouble.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: SamplingMethod, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .greedy:
+ writeInt(&buf, Int32(1))
+
+
+ case let .stochastic(temperature,topK,topP,minP):
+ writeInt(&buf, Int32(2))
+ FfiConverterOptionDouble.write(temperature, into: &buf)
+ FfiConverterOptionInt64.write(topK, into: &buf)
+ FfiConverterOptionDouble.write(topP, into: &buf)
+ FfiConverterOptionDouble.write(minP, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSamplingMethod_lift(_ buf: RustBuffer) throws -> SamplingMethod {
+ return try FfiConverterTypeSamplingMethod.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSamplingMethod_lower(_ value: SamplingMethod) -> RustBuffer {
+ return FfiConverterTypeSamplingMethod.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum SamplingPolicy: Equatable, Hashable, Codable {
+
+ case `default`
+ case custom(method: SamplingMethod
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SamplingPolicy: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSamplingPolicy: FfiConverterRustBuffer {
+ typealias SwiftType = SamplingPolicy
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SamplingPolicy {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .`default`
+
+ case 2: return .custom(method: try FfiConverterTypeSamplingMethod.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: SamplingPolicy, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .`default`:
+ writeInt(&buf, Int32(1))
+
+
+ case let .custom(method):
+ writeInt(&buf, Int32(2))
+ FfiConverterTypeSamplingMethod.write(method, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSamplingPolicy_lift(_ buf: RustBuffer) throws -> SamplingPolicy {
+ return try FfiConverterTypeSamplingPolicy.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSamplingPolicy_lower(_ value: SamplingPolicy) -> RustBuffer {
+ return FfiConverterTypeSamplingPolicy.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum SamplingSeed: Equatable, Hashable, Codable {
+
+ case `default`
+ case custom(seed: Int64
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension SamplingSeed: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeSamplingSeed: FfiConverterRustBuffer {
+ typealias SwiftType = SamplingSeed
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SamplingSeed {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .`default`
+
+ case 2: return .custom(seed: try FfiConverterInt64.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: SamplingSeed, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .`default`:
+ writeInt(&buf, Int32(1))
+
+
+ case let .custom(seed):
+ writeInt(&buf, Int32(2))
+ FfiConverterInt64.write(seed, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSamplingSeed_lift(_ buf: RustBuffer) throws -> SamplingSeed {
+ return try FfiConverterTypeSamplingSeed.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeSamplingSeed_lower(_ value: SamplingSeed) -> RustBuffer {
+ return FfiConverterTypeSamplingSeed.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum ToolDescription: Equatable, Hashable, Codable {
+
+ case function(toolFunction: ToolFunction
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension ToolDescription: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeToolDescription: FfiConverterRustBuffer {
+ typealias SwiftType = ToolDescription
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> ToolDescription {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .function(toolFunction: try FfiConverterTypeToolFunction.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: ToolDescription, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case let .function(toolFunction):
+ writeInt(&buf, Int32(1))
+ FfiConverterTypeToolFunction.write(toolFunction, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeToolDescription_lift(_ buf: RustBuffer) throws -> ToolDescription {
+ return try FfiConverterTypeToolDescription.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeToolDescription_lower(_ value: ToolDescription) -> RustBuffer {
+ return FfiConverterTypeToolDescription.lower(value)
+}
+
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum TranslationPayload: Equatable, Hashable, Codable {
+
+ case text(text: String
+ )
+ case image(url: String
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension TranslationPayload: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeTranslationPayload: FfiConverterRustBuffer {
+ typealias SwiftType = TranslationPayload
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> TranslationPayload {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .text(text: try FfiConverterString.read(from: &buf)
+ )
+
+ case 2: return .image(url: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: TranslationPayload, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case let .text(text):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(text, into: &buf)
+
+
+ case let .image(url):
+ writeInt(&buf, Int32(2))
+ FfiConverterString.write(url, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTranslationPayload_lift(_ buf: RustBuffer) throws -> TranslationPayload {
+ return try FfiConverterTypeTranslationPayload.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeTranslationPayload_lower(_ value: TranslationPayload) -> RustBuffer {
+ return FfiConverterTypeTranslationPayload.lower(value)
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionUInt32: FfiConverterRustBuffer {
+ typealias SwiftType = UInt32?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterUInt32.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterUInt32.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionInt64: FfiConverterRustBuffer {
+ typealias SwiftType = Int64?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterInt64.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterInt64.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionDouble: FfiConverterRustBuffer {
+ typealias SwiftType = Double?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterDouble.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterDouble.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionString: FfiConverterRustBuffer {
+ typealias SwiftType = String?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterString.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterString.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeModelFamily: FfiConverterRustBuffer {
+ typealias SwiftType = ModelFamily?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeModelFamily.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeModelFamily.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeModelProperties: FfiConverterRustBuffer {
+ typealias SwiftType = ModelProperties?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeModelProperties.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeModelProperties.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeModelQuantization: FfiConverterRustBuffer {
+ typealias SwiftType = ModelQuantization?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeModelQuantization.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeModelQuantization.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeRepository: FfiConverterRustBuffer {
+ typealias SwiftType = Repository?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeRepository.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeRepository.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeValue: FfiConverterRustBuffer {
+ typealias SwiftType = Value?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeValue.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeValue.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeChatReplyFinishReason: FfiConverterRustBuffer {
+ typealias SwiftType = ChatReplyFinishReason?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeChatReplyFinishReason.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeChatReplyFinishReason.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeChatSpeculationPreset: FfiConverterRustBuffer {
+ typealias SwiftType = ChatSpeculationPreset?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeChatSpeculationPreset.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeChatSpeculationPreset.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeGrammar: FfiConverterRustBuffer {
+ typealias SwiftType = Grammar?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeGrammar.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeGrammar.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeReasoningEffort: FfiConverterRustBuffer {
+ typealias SwiftType = ReasoningEffort?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeReasoningEffort.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeReasoningEffort.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionSequenceString: FfiConverterRustBuffer {
+ typealias SwiftType = [String]?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterSequenceString.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterSequenceString.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceUInt32: FfiConverterRustBuffer {
+ typealias SwiftType = [UInt32]
+
+ public static func write(_ value: [UInt32], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterUInt32.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [UInt32] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [UInt32]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterUInt32.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceDouble: FfiConverterRustBuffer {
+ typealias SwiftType = [Double]
+
+ public static func write(_ value: [Double], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterDouble.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [Double] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [Double]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterDouble.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceString: FfiConverterRustBuffer {
+ typealias SwiftType = [String]
+
+ public static func write(_ value: [String], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterString.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [String] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [String]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterString.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeFile: FfiConverterRustBuffer {
+ typealias SwiftType = [File]
+
+ public static func write(_ value: [File], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeFile.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [File] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [File]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeFile.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeHash: FfiConverterRustBuffer {
+ typealias SwiftType = [Hash]
+
+ public static func write(_ value: [Hash], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeHash.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [Hash] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [Hash]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeHash.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeImage: FfiConverterRustBuffer {
+ typealias SwiftType = [Image]
+
+ public static func write(_ value: [Image], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeImage.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [Image] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [Image]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeImage.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeModelBackend: FfiConverterRustBuffer {
+ typealias SwiftType = [ModelBackend]
+
+ public static func write(_ value: [ModelBackend], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeModelBackend.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ModelBackend] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ModelBackend]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeModelBackend.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeToolCall: FfiConverterRustBuffer {
+ typealias SwiftType = [ToolCall]
+
+ public static func write(_ value: [ToolCall], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeToolCall.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ToolCall] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ToolCall]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeToolCall.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeToolNamespace: FfiConverterRustBuffer {
+ typealias SwiftType = [ToolNamespace]
+
+ public static func write(_ value: [ToolNamespace], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeToolNamespace.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ToolNamespace] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ToolNamespace]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeToolNamespace.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeChatContentBlock: FfiConverterRustBuffer {
+ typealias SwiftType = [ChatContentBlock]
+
+ public static func write(_ value: [ChatContentBlock], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeChatContentBlock.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ChatContentBlock] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ChatContentBlock]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeChatContentBlock.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeModelSpecialization: FfiConverterRustBuffer {
+ typealias SwiftType = [ModelSpecialization]
+
+ public static func write(_ value: [ModelSpecialization], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeModelSpecialization.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ModelSpecialization] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ModelSpecialization]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeModelSpecialization.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeToolDescription: FfiConverterRustBuffer {
+ typealias SwiftType = [ToolDescription]
+
+ public static func write(_ value: [ToolDescription], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeToolDescription.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ToolDescription] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ToolDescription]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeToolDescription.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterDictionaryStringDouble: FfiConverterRustBuffer {
+ public static func write(_ value: [String: Double], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for (key, value) in value {
+ FfiConverterString.write(key, into: &buf)
+ FfiConverterDouble.write(value, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [String: Double] {
+ let len: Int32 = try readInt(&buf)
+ var dict = [String: Double]()
+ dict.reserveCapacity(Int(len))
+ for _ in 0..<len {
+ let key = try FfiConverterString.read(from: &buf)
+ let value = try FfiConverterDouble.read(from: &buf)
+ dict[key] = value
+ }
+ return dict
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterDictionaryStringTypeValue: FfiConverterRustBuffer {
+ public static func write(_ value: [String: Value], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for (key, value) in value {
+ FfiConverterString.write(key, into: &buf)
+ FfiConverterTypeValue.write(value, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [String: Value] {
+ let len: Int32 = try readInt(&buf)
+ var dict = [String: Value]()
+ dict.reserveCapacity(Int(len))
+ for _ in 0..<len {
+ let key = try FfiConverterString.read(from: &buf)
+ let value = try FfiConverterTypeValue.read(from: &buf)
+ dict[key] = value
+ }
+ return dict
+ }
+}
+public func cancelTokenCreate() -> CancelToken {
+ return try! FfiConverterTypeCancelToken_lift(try! rustCall() {
+ uniffi_shoji_fn_func_cancel_token_create($0
+ )
+})
+}
+public func metadataExternal(name: String) -> Metadata {
+ return try! FfiConverterTypeMetadata_lift(try! rustCall() {
+ uniffi_shoji_fn_func_metadata_external(
+ FfiConverterString.lower(name),$0
+ )
+})
+}
+public func modelExternal(identifier: String, registryIdentifier: String, registryName: String, backendIdentifier: String, backendName: String, backendVersion: String, specializations: [ModelSpecialization], accessibility: ModelAccessibility) -> Model {
+ return try! FfiConverterTypeModel_lift(try! rustCall() {
+ uniffi_shoji_fn_func_model_external(
+ FfiConverterString.lower(identifier),
+ FfiConverterString.lower(registryIdentifier),
+ FfiConverterString.lower(registryName),
+ FfiConverterString.lower(backendIdentifier),
+ FfiConverterString.lower(backendName),
+ FfiConverterString.lower(backendVersion),
+ FfiConverterSequenceTypeModelSpecialization.lower(specializations),
+ FfiConverterTypeModelAccessibility_lower(accessibility),$0
+ )
+})
+}
+public func chatConfigCreate() -> ChatConfig {
+ return try! FfiConverterTypeChatConfig_lift(try! rustCall() {
+ uniffi_shoji_fn_func_chat_config_create($0
+ )
+})
+}
+public func chatMessageAssistant() -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_func_chat_message_assistant($0
+ )
+})
+}
+public func chatMessageDeveloper() -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_func_chat_message_developer($0
+ )
+})
+}
+public func chatMessageForRole(role: ChatRole) -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_func_chat_message_for_role(
+ FfiConverterTypeChatRole_lower(role),$0
+ )
+})
+}
+public func chatMessageSystem() -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_func_chat_message_system($0
+ )
+})
+}
+public func chatMessageTool() -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_func_chat_message_tool($0
+ )
+})
+}
+public func chatMessageUser() -> ChatMessage {
+ return try! FfiConverterTypeChatMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_func_chat_message_user($0
+ )
+})
+}
+public func chatReplyConfigCreate() -> ChatReplyConfig {
+ return try! FfiConverterTypeChatReplyConfig_lift(try! rustCall() {
+ uniffi_shoji_fn_func_chat_reply_config_create($0
+ )
+})
+}
+public func classificationMessageAssistant(content: String) -> ClassificationMessage {
+ return try! FfiConverterTypeClassificationMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_func_classification_message_assistant(
+ FfiConverterString.lower(content),$0
+ )
+})
+}
+public func classificationMessageUser(content: String) -> ClassificationMessage {
+ return try! FfiConverterTypeClassificationMessage_lift(try! rustCall() {
+ uniffi_shoji_fn_func_classification_message_user(
+ FfiConverterString.lower(content),$0
+ )
+})
+}
+
+private enum InitializationResult {
+ case ok
+ case contractVersionMismatch
+ case apiChecksumMismatch
+}
+// Use a global variable to perform the versioning checks. Swift ensures that
+// the code inside is only computed once.
+private let initializationResult: InitializationResult = {
+ // Get the bindings contract version from our ComponentInterface
+ let bindings_contract_version = 30
+ // Get the scaffolding contract version by calling the into the dylib
+ let scaffolding_contract_version = ffi_shoji_uniffi_contract_version()
+ if bindings_contract_version != scaffolding_contract_version {
+ return InitializationResult.contractVersionMismatch
+ }
+ if (uniffi_shoji_checksum_func_cancel_token_create() != 2825) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_metadata_external() != 17881) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_model_external() != 53960) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_chat_config_create() != 48867) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_chat_message_assistant() != 14397) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_chat_message_developer() != 24284) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_chat_message_for_role() != 13608) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_chat_message_system() != 58558) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_chat_message_tool() != 43628) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_chat_message_user() != 17601) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_chat_reply_config_create() != 29041) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_classification_message_assistant() != 52835) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_func_classification_message_user() != 49384) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_method_canceltoken_cancel() != 25416) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_shoji_checksum_method_canceltoken_is_cancelled() != 36980) {
+ return InitializationResult.apiChecksumMismatch
+ }
+
+ return InitializationResult.ok
+}()
+
+// Make the ensure init function public so that other modules which have external type references to
+// our types can call it.
+public func uniffiEnsureShojiInitialized() {
+ switch initializationResult {
+ case .ok:
+ break
+ case .contractVersionMismatch:
+ fatalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
+ case .apiChecksumMismatch:
+ fatalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+}
+
+// swiftlint:enable all
\ No newline at end of file
diff --git a/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift b/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift
new file mode 100644
index 000000000..6f708bf0a
--- /dev/null
+++ b/bindings/swift/Sources/Uzu/Generated/uzu/uzu.swift
@@ -0,0 +1,3427 @@
+// This file was autogenerated by some hot garbage in the `uniffi` crate.
+// Trust me, you don't want to mess with it!
+
+// swiftlint:disable all
+import Foundation
+
+// Depending on the consumer's build setup, the low-level FFI code
+// might be in a separate module, or it might be compiled inline into
+// this module. This is a bit of light hackery to work with both.
+#if canImport(uzuFFI)
+import uzuFFI
+#endif
+
+fileprivate extension RustBuffer {
+ // Allocate a new buffer, copying the contents of a `UInt8` array.
+ init(bytes: [UInt8]) {
+ let rbuf = bytes.withUnsafeBufferPointer { ptr in
+ RustBuffer.from(ptr)
+ }
+ self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data)
+ }
+
+ static func empty() -> RustBuffer {
+ RustBuffer(capacity: 0, len:0, data: nil)
+ }
+
+ static func from(_ ptr: UnsafeBufferPointer<UInt8>) -> RustBuffer {
+ try! rustCall { ffi_uzu_rustbuffer_from_bytes(ForeignBytes(bufferPointer: ptr), $0) }
+ }
+
+ // Frees the buffer in place.
+ // The buffer must not be used after this is called.
+ func deallocate() {
+ try! rustCall { ffi_uzu_rustbuffer_free(self, $0) }
+ }
+}
+
+fileprivate extension ForeignBytes {
+ init(bufferPointer: UnsafeBufferPointer<UInt8>) {
+ self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress)
+ }
+}
+
+// For every type used in the interface, we provide helper methods for conveniently
+// lifting and lowering that type from C-compatible data, and for reading and writing
+// values of that type in a buffer.
+
+// Helper classes/extensions that don't change.
+// Someday, this will be in a library of its own.
+
+fileprivate extension Data {
+ init(rustBuffer: RustBuffer) {
+ self.init(
+ bytesNoCopy: rustBuffer.data!,
+ count: Int(rustBuffer.len),
+ deallocator: .none
+ )
+ }
+}
+
+// Define reader functionality. Normally this would be defined in a class or
+// struct, but we use standalone functions instead in order to make external
+// types work.
+//
+// With external types, one swift source file needs to be able to call the read
+// method on another source file's FfiConverter, but then what visibility
+// should Reader have?
+// - If Reader is fileprivate, then this means the read() must also
+// be fileprivate, which doesn't work with external types.
+// - If Reader is internal/public, we'll get compile errors since both source
+// files will try define the same type.
+//
+// Instead, the read() method and these helper functions input a tuple of data
+
+fileprivate func createReader(data: Data) -> (data: Data, offset: Data.Index) {
+ (data: data, offset: 0)
+}
+
+// Reads an integer at the current offset, in big-endian order, and advances
+// the offset on success. Throws if reading the integer would move the
+// offset past the end of the buffer.
+fileprivate func readInt<T: FixedWidthInteger>(_ reader: inout (data: Data, offset: Data.Index)) throws -> T {
+ let range = reader.offset..<reader.offset + MemoryLayout<T>.size
+ guard reader.data.count >= range.upperBound else {
+ throw UniffiInternalError.bufferOverflow
+ }
+ if T.self == UInt8.self {
+ let value = reader.data[reader.offset]
+ reader.offset += 1
+ return value as! T
+ }
+ var value: T = 0
+ let _ = withUnsafeMutableBytes(of: &value, { reader.data.copyBytes(to: $0, from: range)})
+ reader.offset = range.upperBound
+ return value.bigEndian
+}
+
+// Reads an arbitrary number of bytes, to be used to read
+// raw bytes, this is useful when lifting strings
+fileprivate func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> Array<UInt8> {
+ let range = reader.offset..<(reader.offset+count)
+ guard reader.data.count >= range.upperBound else {
+ throw UniffiInternalError.bufferOverflow
+ }
+ var value = [UInt8](repeating: 0, count: count)
+ value.withUnsafeMutableBufferPointer({ buffer in
+ reader.data.copyBytes(to: buffer, from: range)
+ })
+ reader.offset = range.upperBound
+ return value
+}
+
+// Reads a float at the current offset.
+fileprivate func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {
+ return Float(bitPattern: try readInt(&reader))
+}
+
+// Reads a float at the current offset.
+fileprivate func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {
+ return Double(bitPattern: try readInt(&reader))
+}
+
+// Indicates if the offset has reached the end of the buffer.
+fileprivate func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool {
+ return reader.offset < reader.data.count
+}
+
+// Define writer functionality. Normally this would be defined in a class or
+// struct, but we use standalone functions instead in order to make external
+// types work. See the above discussion on Readers for details.
+
+fileprivate func createWriter() -> [UInt8] {
+ return []
+}
+
+fileprivate func writeBytes<S>(_ writer: inout [UInt8], _ byteArr: S) where S: Sequence, S.Element == UInt8 {
+ writer.append(contentsOf: byteArr)
+}
+
+// Writes an integer in big-endian order.
+//
+// Warning: make sure what you are trying to write
+// is in the correct type!
+fileprivate func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {
+ var value = value.bigEndian
+ withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }
+}
+
+fileprivate func writeFloat(_ writer: inout [UInt8], _ value: Float) {
+ writeInt(&writer, value.bitPattern)
+}
+
+fileprivate func writeDouble(_ writer: inout [UInt8], _ value: Double) {
+ writeInt(&writer, value.bitPattern)
+}
+
+// Protocol for types that transfer other types across the FFI. This is
+// analogous to the Rust trait of the same name.
+fileprivate protocol FfiConverter {
+ associatedtype FfiType
+ associatedtype SwiftType
+
+ static func lift(_ value: FfiType) throws -> SwiftType
+ static func lower(_ value: SwiftType) -> FfiType
+ static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType
+ static func write(_ value: SwiftType, into buf: inout [UInt8])
+}
+
+// Types conforming to `Primitive` pass themselves directly over the FFI.
+fileprivate protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType { }
+
+extension FfiConverterPrimitive {
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ value: FfiType) throws -> SwiftType {
+ return value
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ value: SwiftType) -> FfiType {
+ return value
+ }
+}
+
+// Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`.
+// Used for complex types where it's hard to write a custom lift/lower.
+fileprivate protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {}
+
+extension FfiConverterRustBuffer {
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ buf: RustBuffer) throws -> SwiftType {
+ var reader = createReader(data: Data(rustBuffer: buf))
+ let value = try read(from: &reader)
+ if hasRemaining(reader) {
+ throw UniffiInternalError.incompleteData
+ }
+ buf.deallocate()
+ return value
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ value: SwiftType) -> RustBuffer {
+ var writer = createWriter()
+ write(value, into: &writer)
+ return RustBuffer(bytes: writer)
+ }
+}
+// An error type for FFI errors. These errors occur at the UniFFI level, not
+// the library level.
+fileprivate enum UniffiInternalError: LocalizedError {
+ case bufferOverflow
+ case incompleteData
+ case unexpectedOptionalTag
+ case unexpectedEnumCase
+ case unexpectedNullPointer
+ case unexpectedRustCallStatusCode
+ case unexpectedRustCallError
+ case unexpectedStaleHandle
+ case rustPanic(_ message: String)
+
+ public var errorDescription: String? {
+ switch self {
+ case .bufferOverflow: return "Reading the requested value would read past the end of the buffer"
+ case .incompleteData: return "The buffer still has data after lifting its containing value"
+ case .unexpectedOptionalTag: return "Unexpected optional tag; should be 0 or 1"
+ case .unexpectedEnumCase: return "Raw enum value doesn't match any cases"
+ case .unexpectedNullPointer: return "Raw pointer value was null"
+ case .unexpectedRustCallStatusCode: return "Unexpected RustCallStatus code"
+ case .unexpectedRustCallError: return "CALL_ERROR but no errorClass specified"
+ case .unexpectedStaleHandle: return "The object in the handle map has been dropped already"
+ case let .rustPanic(message): return message
+ }
+ }
+}
+
+fileprivate extension NSLock {
+ func withLock<T>(f: () throws -> T) rethrows -> T {
+ self.lock()
+ defer { self.unlock() }
+ return try f()
+ }
+}
+
+fileprivate let CALL_SUCCESS: Int8 = 0
+fileprivate let CALL_ERROR: Int8 = 1
+fileprivate let CALL_UNEXPECTED_ERROR: Int8 = 2
+fileprivate let CALL_CANCELLED: Int8 = 3
+
+fileprivate extension RustCallStatus {
+ init() {
+ self.init(
+ code: CALL_SUCCESS,
+ errorBuf: RustBuffer.init(
+ capacity: 0,
+ len: 0,
+ data: nil
+ )
+ )
+ }
+}
+
+private func rustCall<T>(_ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
+ let neverThrow: ((RustBuffer) throws -> Never)? = nil
+ return try makeRustCall(callback, errorHandler: neverThrow)
+}
+
+private func rustCallWithError<T, E: Swift.Error>(
+ _ errorHandler: @escaping (RustBuffer) throws -> E,
+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
+ try makeRustCall(callback, errorHandler: errorHandler)
+}
+
+private func makeRustCall<T, E: Swift.Error>(
+ _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T,
+ errorHandler: ((RustBuffer) throws -> E)?
+) throws -> T {
+ uniffiEnsureUzuInitialized()
+ var callStatus = RustCallStatus.init()
+ let returnedVal = callback(&callStatus)
+ try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler)
+ return returnedVal
+}
+
+private func uniffiCheckCallStatus<E: Swift.Error>(
+ callStatus: RustCallStatus,
+ errorHandler: ((RustBuffer) throws -> E)?
+) throws {
+ switch callStatus.code {
+ case CALL_SUCCESS:
+ return
+
+ case CALL_ERROR:
+ if let errorHandler = errorHandler {
+ throw try errorHandler(callStatus.errorBuf)
+ } else {
+ callStatus.errorBuf.deallocate()
+ throw UniffiInternalError.unexpectedRustCallError
+ }
+
+ case CALL_UNEXPECTED_ERROR:
+ // When the rust code sees a panic, it tries to construct a RustBuffer
+ // with the message. But if that code panics, then it just sends back
+ // an empty buffer.
+ if callStatus.errorBuf.len > 0 {
+ throw UniffiInternalError.rustPanic(try FfiConverterString.lift(callStatus.errorBuf))
+ } else {
+ callStatus.errorBuf.deallocate()
+ throw UniffiInternalError.rustPanic("Rust panic")
+ }
+
+ case CALL_CANCELLED:
+ fatalError("Cancellation not supported yet")
+
+ default:
+ throw UniffiInternalError.unexpectedRustCallStatusCode
+ }
+}
+
+private func uniffiTraitInterfaceCall<T>(
+ callStatus: UnsafeMutablePointer<RustCallStatus>,
+ makeCall: () throws -> T,
+ writeReturn: (T) -> ()
+) {
+ do {
+ try writeReturn(makeCall())
+ } catch let error {
+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR
+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
+ }
+}
+
+private func uniffiTraitInterfaceCallWithError<T, E>(
+ callStatus: UnsafeMutablePointer<RustCallStatus>,
+ makeCall: () throws -> T,
+ writeReturn: (T) -> (),
+ lowerError: (E) -> RustBuffer
+) {
+ do {
+ try writeReturn(makeCall())
+ } catch let error as E {
+ callStatus.pointee.code = CALL_ERROR
+ callStatus.pointee.errorBuf = lowerError(error)
+ } catch {
+ callStatus.pointee.code = CALL_UNEXPECTED_ERROR
+ callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
+ }
+}
+// Initial value and increment amount for handles.
+// These ensure that SWIFT handles always have the lowest bit set
+fileprivate let UNIFFI_HANDLEMAP_INITIAL: UInt64 = 1
+fileprivate let UNIFFI_HANDLEMAP_DELTA: UInt64 = 2
+
+fileprivate final class UniffiHandleMap<T>: @unchecked Sendable {
+ // All mutation happens with this lock held, which is why we implement @unchecked Sendable.
+ private let lock = NSLock()
+ private var map: [UInt64: T] = [:]
+ private var currentHandle: UInt64 = UNIFFI_HANDLEMAP_INITIAL
+
+ func insert(obj: T) -> UInt64 {
+ lock.withLock {
+ return doInsert(obj)
+ }
+ }
+
+ // Low-level insert function, this assumes `lock` is held.
+ private func doInsert(_ obj: T) -> UInt64 {
+ let handle = currentHandle
+ currentHandle += UNIFFI_HANDLEMAP_DELTA
+ map[handle] = obj
+ return handle
+ }
+
+ func get(handle: UInt64) throws -> T {
+ try lock.withLock {
+ guard let obj = map[handle] else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return obj
+ }
+ }
+
+ func clone(handle: UInt64) throws -> UInt64 {
+ try lock.withLock {
+ guard let obj = map[handle] else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return doInsert(obj)
+ }
+ }
+
+ @discardableResult
+ func remove(handle: UInt64) throws -> T {
+ try lock.withLock {
+ guard let obj = map.removeValue(forKey: handle) else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return obj
+ }
+ }
+
+ var count: Int {
+ get {
+ map.count
+ }
+ }
+}
+
+
+// Public interface members begin here.
+// Magic number for the Rust proxy to call using the same mechanism as every other method,
+// to free the callback once it's dropped by Rust.
+private let IDX_CALLBACK_FREE: Int32 = 0
+// Callback return codes
+private let UNIFFI_CALLBACK_SUCCESS: Int32 = 0
+private let UNIFFI_CALLBACK_ERROR: Int32 = 1
+private let UNIFFI_CALLBACK_UNEXPECTED_ERROR: Int32 = 2
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterInt64: FfiConverterPrimitive {
+ typealias FfiType = Int64
+ typealias SwiftType = Int64
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Int64 {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: Int64, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterFloat: FfiConverterPrimitive {
+ typealias FfiType = Float
+ typealias SwiftType = Float
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Float {
+ return try lift(readFloat(&buf))
+ }
+
+ public static func write(_ value: Float, into buf: inout [UInt8]) {
+ writeFloat(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterBool : FfiConverter {
+ typealias FfiType = Int8
+ typealias SwiftType = Bool
+
+ public static func lift(_ value: Int8) throws -> Bool {
+ return value != 0
+ }
+
+ public static func lower(_ value: Bool) -> Int8 {
+ return value ? 1 : 0
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Bool {
+ return try lift(readInt(&buf))
+ }
+
+ public static func write(_ value: Bool, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterString: FfiConverter {
+ typealias SwiftType = String
+ typealias FfiType = RustBuffer
+
+ public static func lift(_ value: RustBuffer) throws -> String {
+ defer {
+ value.deallocate()
+ }
+ if value.data == nil {
+ return String()
+ }
+ let bytes = UnsafeBufferPointer<UInt8>(start: value.data!, count: Int(value.len))
+ return String(bytes: bytes, encoding: String.Encoding.utf8)!
+ }
+
+ public static func lower(_ value: String) -> RustBuffer {
+ return value.utf8CString.withUnsafeBufferPointer { ptr in
+ // The swift string gives us int8_t, we want uint8_t.
+ ptr.withMemoryRebound(to: UInt8.self) { ptr in
+ // The swift string gives us a trailing null byte, we don't want it.
+ let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1))
+ return RustBuffer.from(buf)
+ }
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {
+ let len: Int32 = try readInt(&buf)
+ return String(bytes: try readBytes(&buf, count: Int(len)), encoding: String.Encoding.utf8)!
+ }
+
+ public static func write(_ value: String, into buf: inout [UInt8]) {
+ let len = Int32(value.utf8.count)
+ writeInt(&buf, len)
+ writeBytes(&buf, value.utf8)
+ }
+}
+
+
+
+
+public protocol DownloaderProtocol: AnyObject, Sendable {
+
+ func delete() async throws
+
+ func pause() async throws
+
+ func progress() async throws -> DownloaderStream
+
+ func resume() async throws
+
+ func state() async -> DownloadState?
+
+}
+open class Downloader: DownloaderProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_uzu_fn_clone_downloader(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_uzu_fn_free_downloader(handle, $0) }
+ }
+
+
+
+
+open func delete()async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_downloader_delete(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_void,
+ completeFunc: ffi_uzu_rust_future_complete_void,
+ freeFunc: ffi_uzu_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func pause()async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_downloader_pause(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_void,
+ completeFunc: ffi_uzu_rust_future_complete_void,
+ freeFunc: ffi_uzu_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func progress()async throws -> DownloaderStream {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_downloader_progress(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_u64,
+ completeFunc: ffi_uzu_rust_future_complete_u64,
+ freeFunc: ffi_uzu_rust_future_free_u64,
+ liftFunc: FfiConverterTypeDownloaderStream_lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func resume()async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_downloader_resume(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_void,
+ completeFunc: ffi_uzu_rust_future_complete_void,
+ freeFunc: ffi_uzu_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func state()async -> DownloadState? {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_downloader_state(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterOptionTypeDownloadState.lift,
+ errorHandler: nil
+
+ )
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeDownloader: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = Downloader
+
+ public static func lift(_ handle: UInt64) throws -> Downloader {
+ return Downloader(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: Downloader) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Downloader {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: Downloader, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloader_lift(_ handle: UInt64) throws -> Downloader {
+ return try FfiConverterTypeDownloader.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloader_lower(_ value: Downloader) -> UInt64 {
+ return FfiConverterTypeDownloader.lower(value)
+}
+
+
+
+
+
+
+public protocol DownloaderStreamProtocol: AnyObject, Sendable {
+
+ func next() async -> DownloaderStreamUpdate?
+
+}
+open class DownloaderStream: DownloaderStreamProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_uzu_fn_clone_downloaderstream(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_uzu_fn_free_downloaderstream(handle, $0) }
+ }
+
+
+
+
+open func next()async -> DownloaderStreamUpdate? {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_downloaderstream_next(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterOptionTypeDownloaderStreamUpdate.lift,
+ errorHandler: nil
+
+ )
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeDownloaderStream: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = DownloaderStream
+
+ public static func lift(_ handle: UInt64) throws -> DownloaderStream {
+ return DownloaderStream(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: DownloaderStream) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloaderStream {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: DownloaderStream, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloaderStream_lift(_ handle: UInt64) throws -> DownloaderStream {
+ return try FfiConverterTypeDownloaderStream.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloaderStream_lower(_ value: DownloaderStream) -> UInt64 {
+ return FfiConverterTypeDownloaderStream.lower(value)
+}
+
+
+
+
+
+
+public protocol EngineProtocol: AnyObject, Sendable {
+
+ func chat(model: Model, config: ChatConfig) async throws -> ChatSession
+
+ func classification(model: Model) async throws -> ClassificationSession
+
+ func download(model: Model) async throws -> DownloaderStream
+
+ func downloadState(model: Model) async -> DownloadState?
+
+ func downloadStates() async -> [String: DownloadState]
+
+ func downloader(model: Model) -> Downloader
+
+ func model(identifier: String) async throws -> Model?
+
+ func modelByIdentifier(identifier: String) async throws -> Model?
+
+ func modelByPath(path: String) async throws -> Model?
+
+ func modelByRepoId(repoId: String) async throws -> Model?
+
+ func modelFamilies() async throws -> [ModelFamily]
+
+ func modelPath(model: Model) async -> String?
+
+ func modelRegistries() async throws -> [ModelRegistry]
+
+ func modelVendors() async throws -> [ModelVendor]
+
+ func models() async throws -> [Model]
+
+ func modelsByFamily(familyIdentifier: String) async throws -> [Model]
+
+ func modelsByVendor(vendorIdentifier: String) async throws -> [Model]
+
+ func modelsDownloadable() async throws -> [Model]
+
+ func modelsForChat() async throws -> [Model]
+
+ func modelsForClassification() async throws -> [Model]
+
+ func modelsForSpeculation() async throws -> [Model]
+
+ func modelsForTextToSpeech() async throws -> [Model]
+
+ func modelsForTranslation() async throws -> [Model]
+
+ func modelsLocal() async throws -> [Model]
+
+ func modelsRemote() async throws -> [Model]
+
+ func registerCallback(callback: EngineCallback) async throws
+
+ func removeBackend(identifier: String) async
+
+ func removeRegistry(registryIdentifier: String) async throws
+
+ func textToSpeech(model: Model) async throws -> TextToSpeechSession
+
+}
+open class Engine: EngineProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_uzu_fn_clone_engine(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_uzu_fn_free_engine(handle, $0) }
+ }
+
+
+
+
+open func chat(model: Model, config: ChatConfig)async throws -> ChatSession {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_chat(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeModel_lower(model),FfiConverterTypeChatConfig_lower(config)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_u64,
+ completeFunc: ffi_uzu_rust_future_complete_u64,
+ freeFunc: ffi_uzu_rust_future_free_u64,
+ liftFunc: FfiConverterTypeChatSession_lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func classification(model: Model)async throws -> ClassificationSession {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_classification(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeModel_lower(model)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_u64,
+ completeFunc: ffi_uzu_rust_future_complete_u64,
+ freeFunc: ffi_uzu_rust_future_free_u64,
+ liftFunc: FfiConverterTypeClassificationSession_lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func download(model: Model)async throws -> DownloaderStream {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_download(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeModel_lower(model)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_u64,
+ completeFunc: ffi_uzu_rust_future_complete_u64,
+ freeFunc: ffi_uzu_rust_future_free_u64,
+ liftFunc: FfiConverterTypeDownloaderStream_lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func downloadState(model: Model)async -> DownloadState? {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_download_state(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeModel_lower(model)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterOptionTypeDownloadState.lift,
+ errorHandler: nil
+
+ )
+}
+
+open func downloadStates()async -> [String: DownloadState] {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_download_states(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterDictionaryStringTypeDownloadState.lift,
+ errorHandler: nil
+
+ )
+}
+
+open func downloader(model: Model) -> Downloader {
+ return try! FfiConverterTypeDownloader_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engine_downloader(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeModel_lower(model),$0
+ )
+})
+}
+
+open func model(identifier: String)async throws -> Model? {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_model(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(identifier)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterOptionTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelByIdentifier(identifier: String)async throws -> Model? {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_model_by_identifier(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(identifier)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterOptionTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelByPath(path: String)async throws -> Model? {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_model_by_path(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(path)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterOptionTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelByRepoId(repoId: String)async throws -> Model? {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_model_by_repo_id(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(repoId)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterOptionTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelFamilies()async throws -> [ModelFamily] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_model_families(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModelFamily.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelPath(model: Model)async -> String? {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_model_path(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeModel_lower(model)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterOptionString.lift,
+ errorHandler: nil
+
+ )
+}
+
+open func modelRegistries()async throws -> [ModelRegistry] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_model_registries(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModelRegistry.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelVendors()async throws -> [ModelVendor] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_model_vendors(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModelVendor.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func models()async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelsByFamily(familyIdentifier: String)async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models_by_family(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(familyIdentifier)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelsByVendor(vendorIdentifier: String)async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models_by_vendor(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(vendorIdentifier)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelsDownloadable()async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models_downloadable(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelsForChat()async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models_for_chat(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelsForClassification()async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models_for_classification(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelsForSpeculation()async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models_for_speculation(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelsForTextToSpeech()async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models_for_text_to_speech(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelsForTranslation()async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models_for_translation(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelsLocal()async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models_local(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func modelsRemote()async throws -> [Model] {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_models_remote(
+ self.uniffiCloneHandle()
+
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_rust_buffer,
+ completeFunc: ffi_uzu_rust_future_complete_rust_buffer,
+ freeFunc: ffi_uzu_rust_future_free_rust_buffer,
+ liftFunc: FfiConverterSequenceTypeModel.lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func registerCallback(callback: EngineCallback)async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_register_callback(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeEngineCallback_lower(callback)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_void,
+ completeFunc: ffi_uzu_rust_future_complete_void,
+ freeFunc: ffi_uzu_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func removeBackend(identifier: String)async {
+ return
+ try! await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_remove_backend(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(identifier)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_void,
+ completeFunc: ffi_uzu_rust_future_complete_void,
+ freeFunc: ffi_uzu_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: nil
+
+ )
+}
+
+open func removeRegistry(registryIdentifier: String)async throws {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_remove_registry(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(registryIdentifier)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_void,
+ completeFunc: ffi_uzu_rust_future_complete_void,
+ freeFunc: ffi_uzu_rust_future_free_void,
+ liftFunc: { $0 },
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+open func textToSpeech(model: Model)async throws -> TextToSpeechSession {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_method_engine_text_to_speech(
+ self.uniffiCloneHandle(),
+ FfiConverterTypeModel_lower(model)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_u64,
+ completeFunc: ffi_uzu_rust_future_complete_u64,
+ freeFunc: ffi_uzu_rust_future_free_u64,
+ liftFunc: FfiConverterTypeTextToSpeechSession_lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeEngine: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = Engine
+
+ public static func lift(_ handle: UInt64) throws -> Engine {
+ return Engine(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: Engine) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Engine {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: Engine, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeEngine_lift(_ handle: UInt64) throws -> Engine {
+ return try FfiConverterTypeEngine.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeEngine_lower(_ value: Engine) -> UInt64 {
+ return FfiConverterTypeEngine.lower(value)
+}
+
+
+
+
+
+
+public protocol EngineCallbackProtocol: AnyObject, Sendable {
+
+}
+open class EngineCallback: EngineCallbackProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_uzu_fn_clone_enginecallback(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_uzu_fn_free_enginecallback(handle, $0) }
+ }
+
+
+public static func create(handler: EngineCallbackHandler) -> EngineCallback {
+ return try! FfiConverterTypeEngineCallback_lift(try! rustCall() {
+ uniffi_uzu_fn_constructor_enginecallback_create(
+ FfiConverterCallbackInterfaceEngineCallbackHandler_lower(handler),$0
+ )
+})
+}
+
+
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeEngineCallback: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = EngineCallback
+
+ public static func lift(_ handle: UInt64) throws -> EngineCallback {
+ return EngineCallback(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: EngineCallback) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> EngineCallback {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: EngineCallback, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeEngineCallback_lift(_ handle: UInt64) throws -> EngineCallback {
+ return try FfiConverterTypeEngineCallback.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeEngineCallback_lower(_ value: EngineCallback) -> UInt64 {
+ return FfiConverterTypeEngineCallback.lower(value)
+}
+
+
+
+
+
+
+public protocol KeyringProtocol: AnyObject, Sendable {
+
+ func remove(key: String) throws
+
+ func retrieve(key: String) -> String?
+
+ func store(key: String, value: String) throws
+
+}
+open class Keyring: KeyringProtocol, @unchecked Sendable {
+ fileprivate let handle: UInt64
+
+ /// Used to instantiate a [FFIObject] without an actual handle, for fakes in tests, mostly.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public struct NoHandle {
+ public init() {}
+ }
+
+ // TODO: We'd like this to be `private` but for Swifty reasons,
+ // we can't implement `FfiConverter` without making this `required` and we can't
+ // make it `required` without making it `public`.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ required public init(unsafeFromHandle handle: UInt64) {
+ self.handle = handle
+ }
+
+ // This constructor can be used to instantiate a fake object.
+ // - Parameter noHandle: Placeholder value so we can have a constructor separate from the default empty one that may be implemented for classes extending [FFIObject].
+ //
+ // - Warning:
+ // Any object instantiated with this constructor cannot be passed to an actual Rust-backed object. Since there isn't a backing handle the FFI lower functions will crash.
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public init(noHandle: NoHandle) {
+ self.handle = 0
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public func uniffiCloneHandle() -> UInt64 {
+ return try! rustCall { uniffi_uzu_fn_clone_keyring(self.handle, $0) }
+ }
+ // No primary constructor declared for this class.
+
+ deinit {
+ if handle == 0 {
+ // Mock objects have handle=0 don't try to free them
+ return
+ }
+
+ try! rustCall { uniffi_uzu_fn_free_keyring(handle, $0) }
+ }
+
+
+
+
+open func remove(key: String)throws {try rustCallWithError(FfiConverterTypeKeyringError_lift) {
+ uniffi_uzu_fn_method_keyring_remove(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(key),$0
+ )
+}
+}
+
+open func retrieve(key: String) -> String? {
+ return try! FfiConverterOptionString.lift(try! rustCall() {
+ uniffi_uzu_fn_method_keyring_retrieve(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(key),$0
+ )
+})
+}
+
+open func store(key: String, value: String)throws {try rustCallWithError(FfiConverterTypeKeyringError_lift) {
+ uniffi_uzu_fn_method_keyring_store(
+ self.uniffiCloneHandle(),
+ FfiConverterString.lower(key),
+ FfiConverterString.lower(value),$0
+ )
+}
+}
+
+
+
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKeyring: FfiConverter {
+ typealias FfiType = UInt64
+ typealias SwiftType = Keyring
+
+ public static func lift(_ handle: UInt64) throws -> Keyring {
+ return Keyring(unsafeFromHandle: handle)
+ }
+
+ public static func lower(_ value: Keyring) -> UInt64 {
+ return value.uniffiCloneHandle()
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Keyring {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+ public static func write(_ value: Keyring, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(value))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKeyring_lift(_ handle: UInt64) throws -> Keyring {
+ return try FfiConverterTypeKeyring.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKeyring_lower(_ value: Keyring) -> UInt64 {
+ return FfiConverterTypeKeyring.lower(value)
+}
+
+
+
+
+public struct Device: Equatable, Hashable, Codable {
+ public var osName: String?
+ public var cpuName: String?
+ public var memoryTotal: Int64
+ public var homePath: String
+ public var applicationIdentifier: String
+ public var isEnvironmentSandboxed: Bool
+ public var isKeyringAvailable: Bool
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(osName: String?, cpuName: String?, memoryTotal: Int64, homePath: String, applicationIdentifier: String, isEnvironmentSandboxed: Bool, isKeyringAvailable: Bool) {
+ self.osName = osName
+ self.cpuName = cpuName
+ self.memoryTotal = memoryTotal
+ self.homePath = homePath
+ self.applicationIdentifier = applicationIdentifier
+ self.isEnvironmentSandboxed = isEnvironmentSandboxed
+ self.isKeyringAvailable = isKeyringAvailable
+ }
+
+
+
+
+}
+
+#if compiler(>=6)
+extension Device: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeDevice: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Device {
+ return
+ try Device(
+ osName: FfiConverterOptionString.read(from: &buf),
+ cpuName: FfiConverterOptionString.read(from: &buf),
+ memoryTotal: FfiConverterInt64.read(from: &buf),
+ homePath: FfiConverterString.read(from: &buf),
+ applicationIdentifier: FfiConverterString.read(from: &buf),
+ isEnvironmentSandboxed: FfiConverterBool.read(from: &buf),
+ isKeyringAvailable: FfiConverterBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: Device, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.osName, into: &buf)
+ FfiConverterOptionString.write(value.cpuName, into: &buf)
+ FfiConverterInt64.write(value.memoryTotal, into: &buf)
+ FfiConverterString.write(value.homePath, into: &buf)
+ FfiConverterString.write(value.applicationIdentifier, into: &buf)
+ FfiConverterBool.write(value.isEnvironmentSandboxed, into: &buf)
+ FfiConverterBool.write(value.isKeyringAvailable, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDevice_lift(_ buf: RustBuffer) throws -> Device {
+ return try FfiConverterTypeDevice.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDevice_lower(_ value: Device) -> RustBuffer {
+ return FfiConverterTypeDevice.lower(value)
+}
+
+
+public struct DownloadState: Equatable, Hashable, Codable {
+ public var totalBytes: Int64
+ public var downloadedBytes: Int64
+ public var phase: DownloadPhase
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(totalBytes: Int64, downloadedBytes: Int64, phase: DownloadPhase) {
+ self.totalBytes = totalBytes
+ self.downloadedBytes = downloadedBytes
+ self.phase = phase
+ }
+
+
+public func canDelete() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_uzu_fn_method_downloadstate_can_delete(
+ FfiConverterTypeDownloadState_lower(self),$0
+ )
+})
+}
+
+public func canPause() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_uzu_fn_method_downloadstate_can_pause(
+ FfiConverterTypeDownloadState_lower(self),$0
+ )
+})
+}
+
+public func isInProgress() -> Bool {
+ return try! FfiConverterBool.lift(try! rustCall() {
+ uniffi_uzu_fn_method_downloadstate_is_in_progress(
+ FfiConverterTypeDownloadState_lower(self),$0
+ )
+})
+}
+
+public func progress() -> Float {
+ return try! FfiConverterFloat.lift(try! rustCall() {
+ uniffi_uzu_fn_method_downloadstate_progress(
+ FfiConverterTypeDownloadState_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension DownloadState: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeDownloadState: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloadState {
+ return
+ try DownloadState(
+ totalBytes: FfiConverterInt64.read(from: &buf),
+ downloadedBytes: FfiConverterInt64.read(from: &buf),
+ phase: FfiConverterTypeDownloadPhase.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: DownloadState, into buf: inout [UInt8]) {
+ FfiConverterInt64.write(value.totalBytes, into: &buf)
+ FfiConverterInt64.write(value.downloadedBytes, into: &buf)
+ FfiConverterTypeDownloadPhase.write(value.phase, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloadState_lift(_ buf: RustBuffer) throws -> DownloadState {
+ return try FfiConverterTypeDownloadState.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloadState_lower(_ value: DownloadState) -> RustBuffer {
+ return FfiConverterTypeDownloadState.lower(value)
+}
+
+
+public struct DownloaderStreamUpdate: Equatable, Hashable, Codable {
+ public var bytesTotal: Int64
+ public var bytesDownloaded: Int64
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(bytesTotal: Int64, bytesDownloaded: Int64) {
+ self.bytesTotal = bytesTotal
+ self.bytesDownloaded = bytesDownloaded
+ }
+
+
+public func progress() -> Float {
+ return try! FfiConverterFloat.lift(try! rustCall() {
+ uniffi_uzu_fn_method_downloaderstreamupdate_progress(
+ FfiConverterTypeDownloaderStreamUpdate_lower(self),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension DownloaderStreamUpdate: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeDownloaderStreamUpdate: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloaderStreamUpdate {
+ return
+ try DownloaderStreamUpdate(
+ bytesTotal: FfiConverterInt64.read(from: &buf),
+ bytesDownloaded: FfiConverterInt64.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: DownloaderStreamUpdate, into buf: inout [UInt8]) {
+ FfiConverterInt64.write(value.bytesTotal, into: &buf)
+ FfiConverterInt64.write(value.bytesDownloaded, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloaderStreamUpdate_lift(_ buf: RustBuffer) throws -> DownloaderStreamUpdate {
+ return try FfiConverterTypeDownloaderStreamUpdate.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloaderStreamUpdate_lower(_ value: DownloaderStreamUpdate) -> RustBuffer {
+ return FfiConverterTypeDownloaderStreamUpdate.lower(value)
+}
+
+
+public struct EngineConfig: Equatable, Hashable, Codable {
+ public var miraiApiKey: String?
+ public var lalamoPath: String?
+ public var huggingfaceApiKey: String?
+ public var openaiApiKey: String?
+ public var anthropicApiKey: String?
+ public var geminiApiKey: String?
+ public var xaiApiKey: String?
+ public var basetenApiKey: String?
+ public var openrouterApiKey: String?
+ public var allowOllamaUsage: Bool
+ public var allowLmstudioUsage: Bool
+
+ // Default memberwise initializers are never public by default, so we
+ // declare one manually.
+ public init(miraiApiKey: String?, lalamoPath: String?, huggingfaceApiKey: String?, openaiApiKey: String?, anthropicApiKey: String?, geminiApiKey: String?, xaiApiKey: String?, basetenApiKey: String?, openrouterApiKey: String?, allowOllamaUsage: Bool, allowLmstudioUsage: Bool) {
+ self.miraiApiKey = miraiApiKey
+ self.lalamoPath = lalamoPath
+ self.huggingfaceApiKey = huggingfaceApiKey
+ self.openaiApiKey = openaiApiKey
+ self.anthropicApiKey = anthropicApiKey
+ self.geminiApiKey = geminiApiKey
+ self.xaiApiKey = xaiApiKey
+ self.basetenApiKey = basetenApiKey
+ self.openrouterApiKey = openrouterApiKey
+ self.allowOllamaUsage = allowOllamaUsage
+ self.allowLmstudioUsage = allowLmstudioUsage
+ }
+
+
+public func withAllowLmstudioUsage(allowLmstudioUsage: Bool) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_allow_lmstudio_usage(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterBool.lower(allowLmstudioUsage),$0
+ )
+})
+}
+
+public func withAllowOllamaUsage(allowOllamaUsage: Bool) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_allow_ollama_usage(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterBool.lower(allowOllamaUsage),$0
+ )
+})
+}
+
+public func withAnthropicApiKey(anthropicApiKey: String) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_anthropic_api_key(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterString.lower(anthropicApiKey),$0
+ )
+})
+}
+
+public func withBasetenApiKey(basetenApiKey: String) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_baseten_api_key(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterString.lower(basetenApiKey),$0
+ )
+})
+}
+
+public func withGeminiApiKey(geminiApiKey: String) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_gemini_api_key(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterString.lower(geminiApiKey),$0
+ )
+})
+}
+
+public func withHuggingfaceApiKey(huggingfaceApiKey: String) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_huggingface_api_key(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterString.lower(huggingfaceApiKey),$0
+ )
+})
+}
+
+public func withLalamoPath(lalamoPath: String) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_lalamo_path(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterString.lower(lalamoPath),$0
+ )
+})
+}
+
+public func withMiraiApiKey(miraiApiKey: String) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_mirai_api_key(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterString.lower(miraiApiKey),$0
+ )
+})
+}
+
+public func withOpenaiApiKey(openaiApiKey: String) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_openai_api_key(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterString.lower(openaiApiKey),$0
+ )
+})
+}
+
+public func withOpenrouterApiKey(openrouterApiKey: String) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_openrouter_api_key(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterString.lower(openrouterApiKey),$0
+ )
+})
+}
+
+public func withXaiApiKey(xaiApiKey: String) -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_method_engineconfig_with_xai_api_key(
+ FfiConverterTypeEngineConfig_lower(self),
+ FfiConverterString.lower(xaiApiKey),$0
+ )
+})
+}
+
+
+
+}
+
+#if compiler(>=6)
+extension EngineConfig: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeEngineConfig: FfiConverterRustBuffer {
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> EngineConfig {
+ return
+ try EngineConfig(
+ miraiApiKey: FfiConverterOptionString.read(from: &buf),
+ lalamoPath: FfiConverterOptionString.read(from: &buf),
+ huggingfaceApiKey: FfiConverterOptionString.read(from: &buf),
+ openaiApiKey: FfiConverterOptionString.read(from: &buf),
+ anthropicApiKey: FfiConverterOptionString.read(from: &buf),
+ geminiApiKey: FfiConverterOptionString.read(from: &buf),
+ xaiApiKey: FfiConverterOptionString.read(from: &buf),
+ basetenApiKey: FfiConverterOptionString.read(from: &buf),
+ openrouterApiKey: FfiConverterOptionString.read(from: &buf),
+ allowOllamaUsage: FfiConverterBool.read(from: &buf),
+ allowLmstudioUsage: FfiConverterBool.read(from: &buf)
+ )
+ }
+
+ public static func write(_ value: EngineConfig, into buf: inout [UInt8]) {
+ FfiConverterOptionString.write(value.miraiApiKey, into: &buf)
+ FfiConverterOptionString.write(value.lalamoPath, into: &buf)
+ FfiConverterOptionString.write(value.huggingfaceApiKey, into: &buf)
+ FfiConverterOptionString.write(value.openaiApiKey, into: &buf)
+ FfiConverterOptionString.write(value.anthropicApiKey, into: &buf)
+ FfiConverterOptionString.write(value.geminiApiKey, into: &buf)
+ FfiConverterOptionString.write(value.xaiApiKey, into: &buf)
+ FfiConverterOptionString.write(value.basetenApiKey, into: &buf)
+ FfiConverterOptionString.write(value.openrouterApiKey, into: &buf)
+ FfiConverterBool.write(value.allowOllamaUsage, into: &buf)
+ FfiConverterBool.write(value.allowLmstudioUsage, into: &buf)
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeEngineConfig_lift(_ buf: RustBuffer) throws -> EngineConfig {
+ return try FfiConverterTypeEngineConfig.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeEngineConfig_lower(_ value: EngineConfig) -> RustBuffer {
+ return FfiConverterTypeEngineConfig.lower(value)
+}
+
+
+public enum DeviceError: Swift.Error, Equatable, Hashable, Codable, Foundation.LocalizedError {
+
+
+
+ case UnsupportedDevice
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension DeviceError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeDeviceError: FfiConverterRustBuffer {
+ typealias SwiftType = DeviceError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DeviceError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .UnsupportedDevice
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: DeviceError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case .UnsupportedDevice:
+ writeInt(&buf, Int32(1))
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDeviceError_lift(_ buf: RustBuffer) throws -> DeviceError {
+ return try FfiConverterTypeDeviceError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDeviceError_lower(_ value: DeviceError) -> RustBuffer {
+ return FfiConverterTypeDeviceError.lower(value)
+}
+
+// Note that we don't yet support `indirect` for enums.
+// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
+
+public enum DownloadPhase: Equatable, Hashable, Codable {
+
+ case notDownloaded
+ case downloading
+ case paused
+ case downloaded
+ case locked
+ case error(message: String
+ )
+
+
+
+
+
+}
+
+#if compiler(>=6)
+extension DownloadPhase: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeDownloadPhase: FfiConverterRustBuffer {
+ typealias SwiftType = DownloadPhase
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> DownloadPhase {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+ case 1: return .notDownloaded
+
+ case 2: return .downloading
+
+ case 3: return .paused
+
+ case 4: return .downloaded
+
+ case 5: return .locked
+
+ case 6: return .error(message: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: DownloadPhase, into buf: inout [UInt8]) {
+ switch value {
+
+
+ case .notDownloaded:
+ writeInt(&buf, Int32(1))
+
+
+ case .downloading:
+ writeInt(&buf, Int32(2))
+
+
+ case .paused:
+ writeInt(&buf, Int32(3))
+
+
+ case .downloaded:
+ writeInt(&buf, Int32(4))
+
+
+ case .locked:
+ writeInt(&buf, Int32(5))
+
+
+ case let .error(message):
+ writeInt(&buf, Int32(6))
+ FfiConverterString.write(message, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloadPhase_lift(_ buf: RustBuffer) throws -> DownloadPhase {
+ return try FfiConverterTypeDownloadPhase.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeDownloadPhase_lower(_ value: DownloadPhase) -> RustBuffer {
+ return FfiConverterTypeDownloadPhase.lower(value)
+}
+
+
+
+public enum EngineError: Swift.Error, Equatable, Hashable, Codable, Foundation.LocalizedError {
+
+
+
+ case TokioError(message: String
+ )
+ case Device(DeviceError
+ )
+ case Keyring(KeyringError
+ )
+ case Storage(StorageError
+ )
+ case Registry(RegistryError
+ )
+ case UnableToCreateBackend
+ case BackendNotFound
+ case UnableToGetDownloaderProgressStream
+ case ChatSession(ChatSessionError
+ )
+ case ClassificationSession(ClassificationSessionError
+ )
+ case TextToSpeechSession(TextToSpeechSessionError
+ )
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension EngineError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeEngineError: FfiConverterRustBuffer {
+ typealias SwiftType = EngineError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> EngineError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .TokioError(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 2: return .Device(
+ try FfiConverterTypeDeviceError.read(from: &buf)
+ )
+ case 3: return .Keyring(
+ try FfiConverterTypeKeyringError.read(from: &buf)
+ )
+ case 4: return .Storage(
+ try FfiConverterTypeStorageError.read(from: &buf)
+ )
+ case 5: return .Registry(
+ try FfiConverterTypeRegistryError.read(from: &buf)
+ )
+ case 6: return .UnableToCreateBackend
+ case 7: return .BackendNotFound
+ case 8: return .UnableToGetDownloaderProgressStream
+ case 9: return .ChatSession(
+ try FfiConverterTypeChatSessionError.read(from: &buf)
+ )
+ case 10: return .ClassificationSession(
+ try FfiConverterTypeClassificationSessionError.read(from: &buf)
+ )
+ case 11: return .TextToSpeechSession(
+ try FfiConverterTypeTextToSpeechSessionError.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: EngineError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .TokioError(message):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case let .Device(v1):
+ writeInt(&buf, Int32(2))
+ FfiConverterTypeDeviceError.write(v1, into: &buf)
+
+
+ case let .Keyring(v1):
+ writeInt(&buf, Int32(3))
+ FfiConverterTypeKeyringError.write(v1, into: &buf)
+
+
+ case let .Storage(v1):
+ writeInt(&buf, Int32(4))
+ FfiConverterTypeStorageError.write(v1, into: &buf)
+
+
+ case let .Registry(v1):
+ writeInt(&buf, Int32(5))
+ FfiConverterTypeRegistryError.write(v1, into: &buf)
+
+
+ case .UnableToCreateBackend:
+ writeInt(&buf, Int32(6))
+
+
+ case .BackendNotFound:
+ writeInt(&buf, Int32(7))
+
+
+ case .UnableToGetDownloaderProgressStream:
+ writeInt(&buf, Int32(8))
+
+
+ case let .ChatSession(v1):
+ writeInt(&buf, Int32(9))
+ FfiConverterTypeChatSessionError.write(v1, into: &buf)
+
+
+ case let .ClassificationSession(v1):
+ writeInt(&buf, Int32(10))
+ FfiConverterTypeClassificationSessionError.write(v1, into: &buf)
+
+
+ case let .TextToSpeechSession(v1):
+ writeInt(&buf, Int32(11))
+ FfiConverterTypeTextToSpeechSessionError.write(v1, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeEngineError_lift(_ buf: RustBuffer) throws -> EngineError {
+ return try FfiConverterTypeEngineError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeEngineError_lower(_ value: EngineError) -> RustBuffer {
+ return FfiConverterTypeEngineError.lower(value)
+}
+
+
+public enum KeyringError: Swift.Error, Equatable, Hashable, Codable, Foundation.LocalizedError {
+
+
+
+ case BackendError(message: String
+ )
+ case Device(DeviceError
+ )
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension KeyringError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeKeyringError: FfiConverterRustBuffer {
+ typealias SwiftType = KeyringError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> KeyringError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .BackendError(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 2: return .Device(
+ try FfiConverterTypeDeviceError.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: KeyringError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .BackendError(message):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case let .Device(v1):
+ writeInt(&buf, Int32(2))
+ FfiConverterTypeDeviceError.write(v1, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKeyringError_lift(_ buf: RustBuffer) throws -> KeyringError {
+ return try FfiConverterTypeKeyringError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeKeyringError_lower(_ value: KeyringError) -> RustBuffer {
+ return FfiConverterTypeKeyringError.lower(value)
+}
+
+
+public enum RegistryError: Swift.Error, Equatable, Hashable, Codable, Foundation.LocalizedError {
+
+
+
+ case UnableToCreate(message: String
+ )
+ case UnableToGetModels(message: String
+ )
+ case UnableToAddRegistry(identifier: String
+ )
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension RegistryError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeRegistryError: FfiConverterRustBuffer {
+ typealias SwiftType = RegistryError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> RegistryError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .UnableToCreate(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 2: return .UnableToGetModels(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 3: return .UnableToAddRegistry(
+ identifier: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: RegistryError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .UnableToCreate(message):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case let .UnableToGetModels(message):
+ writeInt(&buf, Int32(2))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case let .UnableToAddRegistry(identifier):
+ writeInt(&buf, Int32(3))
+ FfiConverterString.write(identifier, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRegistryError_lift(_ buf: RustBuffer) throws -> RegistryError {
+ return try FfiConverterTypeRegistryError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeRegistryError_lower(_ value: RegistryError) -> RustBuffer {
+ return FfiConverterTypeRegistryError.lower(value)
+}
+
+
+public enum StorageError: Swift.Error, Equatable, Hashable, Codable, Foundation.LocalizedError {
+
+
+
+ case UnableToCreateDirectory(path: String
+ )
+ case UnableToCreateDownloadManager(message: String
+ )
+ case DownloadManager(message: String
+ )
+ case HashNotFound(identifier: String, name: String
+ )
+ case InvalidStateTransition(from: DownloadPhase, to: DownloadPhase
+ )
+ case Io(message: String
+ )
+ case ItemNotFound(identifier: String
+ )
+ case Registry(RegistryError
+ )
+ case UnsupportedItem(identifier: String
+ )
+
+
+
+
+
+
+ public var errorDescription: String? {
+ String(reflecting: self)
+ }
+
+}
+
+#if compiler(>=6)
+extension StorageError: Sendable {}
+#endif
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public struct FfiConverterTypeStorageError: FfiConverterRustBuffer {
+ typealias SwiftType = StorageError
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> StorageError {
+ let variant: Int32 = try readInt(&buf)
+ switch variant {
+
+
+
+
+ case 1: return .UnableToCreateDirectory(
+ path: try FfiConverterString.read(from: &buf)
+ )
+ case 2: return .UnableToCreateDownloadManager(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 3: return .DownloadManager(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 4: return .HashNotFound(
+ identifier: try FfiConverterString.read(from: &buf),
+ name: try FfiConverterString.read(from: &buf)
+ )
+ case 5: return .InvalidStateTransition(
+ from: try FfiConverterTypeDownloadPhase.read(from: &buf),
+ to: try FfiConverterTypeDownloadPhase.read(from: &buf)
+ )
+ case 6: return .Io(
+ message: try FfiConverterString.read(from: &buf)
+ )
+ case 7: return .ItemNotFound(
+ identifier: try FfiConverterString.read(from: &buf)
+ )
+ case 8: return .Registry(
+ try FfiConverterTypeRegistryError.read(from: &buf)
+ )
+ case 9: return .UnsupportedItem(
+ identifier: try FfiConverterString.read(from: &buf)
+ )
+
+ default: throw UniffiInternalError.unexpectedEnumCase
+ }
+ }
+
+ public static func write(_ value: StorageError, into buf: inout [UInt8]) {
+ switch value {
+
+
+
+
+
+ case let .UnableToCreateDirectory(path):
+ writeInt(&buf, Int32(1))
+ FfiConverterString.write(path, into: &buf)
+
+
+ case let .UnableToCreateDownloadManager(message):
+ writeInt(&buf, Int32(2))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case let .DownloadManager(message):
+ writeInt(&buf, Int32(3))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case let .HashNotFound(identifier,name):
+ writeInt(&buf, Int32(4))
+ FfiConverterString.write(identifier, into: &buf)
+ FfiConverterString.write(name, into: &buf)
+
+
+ case let .InvalidStateTransition(from,to):
+ writeInt(&buf, Int32(5))
+ FfiConverterTypeDownloadPhase.write(from, into: &buf)
+ FfiConverterTypeDownloadPhase.write(to, into: &buf)
+
+
+ case let .Io(message):
+ writeInt(&buf, Int32(6))
+ FfiConverterString.write(message, into: &buf)
+
+
+ case let .ItemNotFound(identifier):
+ writeInt(&buf, Int32(7))
+ FfiConverterString.write(identifier, into: &buf)
+
+
+ case let .Registry(v1):
+ writeInt(&buf, Int32(8))
+ FfiConverterTypeRegistryError.write(v1, into: &buf)
+
+
+ case let .UnsupportedItem(identifier):
+ writeInt(&buf, Int32(9))
+ FfiConverterString.write(identifier, into: &buf)
+
+ }
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeStorageError_lift(_ buf: RustBuffer) throws -> StorageError {
+ return try FfiConverterTypeStorageError.lift(buf)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterTypeStorageError_lower(_ value: StorageError) -> RustBuffer {
+ return FfiConverterTypeStorageError.lower(value)
+}
+
+
+
+
+public protocol EngineCallbackHandler: AnyObject, Sendable {
+
+ func onEvent()
+
+}
+
+
+// Put the implementation in a struct so we don't pollute the top-level namespace
+fileprivate struct UniffiCallbackInterfaceEngineCallbackHandler {
+
+ // Create the VTable using a series of closures.
+ // Swift automatically converts these into C callback functions.
+ //
+ // This creates 1-element array, since this seems to be the only way to construct a const
+ // pointer that we can pass to the Rust code.
+ static let vtable: [UniffiVTableCallbackInterfaceEngineCallbackHandler] = [UniffiVTableCallbackInterfaceEngineCallbackHandler(
+ uniffiFree: { (uniffiHandle: UInt64) -> () in
+ do {
+ try FfiConverterCallbackInterfaceEngineCallbackHandler.handleMap.remove(handle: uniffiHandle)
+ } catch {
+ print("Uniffi callback interface EngineCallbackHandler: handle missing in uniffiFree")
+ }
+ },
+ uniffiClone: { (uniffiHandle: UInt64) -> UInt64 in
+ do {
+ return try FfiConverterCallbackInterfaceEngineCallbackHandler.handleMap.clone(handle: uniffiHandle)
+ } catch {
+ fatalError("Uniffi callback interface EngineCallbackHandler: handle missing in uniffiClone")
+ }
+ },
+ onEvent: { (
+ uniffiHandle: UInt64,
+ uniffiOutReturn: UnsafeMutableRawPointer,
+ uniffiCallStatus: UnsafeMutablePointer<RustCallStatus>
+ ) in
+ let makeCall = {
+ () throws -> () in
+ guard let uniffiObj = try? FfiConverterCallbackInterfaceEngineCallbackHandler.handleMap.get(handle: uniffiHandle) else {
+ throw UniffiInternalError.unexpectedStaleHandle
+ }
+ return uniffiObj.onEvent(
+ )
+ }
+
+
+ let writeReturn = { () }
+ uniffiTraitInterfaceCall(
+ callStatus: uniffiCallStatus,
+ makeCall: makeCall,
+ writeReturn: writeReturn
+ )
+ }
+ )]
+}
+
+private func uniffiCallbackInitEngineCallbackHandler() {
+ uniffi_uzu_fn_init_callback_vtable_enginecallbackhandler(UniffiCallbackInterfaceEngineCallbackHandler.vtable)
+}
+
+// FfiConverter protocol for callback interfaces
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterCallbackInterfaceEngineCallbackHandler {
+ fileprivate static let handleMap = UniffiHandleMap<EngineCallbackHandler>()
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+extension FfiConverterCallbackInterfaceEngineCallbackHandler : FfiConverter {
+ typealias SwiftType = EngineCallbackHandler
+ typealias FfiType = UInt64
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lift(_ handle: UInt64) throws -> SwiftType {
+ try handleMap.get(handle: handle)
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ let handle: UInt64 = try readInt(&buf)
+ return try lift(handle)
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func lower(_ v: SwiftType) -> UInt64 {
+ return handleMap.insert(obj: v)
+ }
+
+#if swift(>=5.8)
+ @_documentation(visibility: private)
+#endif
+ public static func write(_ v: SwiftType, into buf: inout [UInt8]) {
+ writeInt(&buf, lower(v))
+ }
+}
+
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterCallbackInterfaceEngineCallbackHandler_lift(_ handle: UInt64) throws -> EngineCallbackHandler {
+ return try FfiConverterCallbackInterfaceEngineCallbackHandler.lift(handle)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+public func FfiConverterCallbackInterfaceEngineCallbackHandler_lower(_ v: EngineCallbackHandler) -> UInt64 {
+ return FfiConverterCallbackInterfaceEngineCallbackHandler.lower(v)
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionString: FfiConverterRustBuffer {
+ typealias SwiftType = String?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterString.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterString.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeModel: FfiConverterRustBuffer {
+ typealias SwiftType = Model?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeModel.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeModel.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeDownloadState: FfiConverterRustBuffer {
+ typealias SwiftType = DownloadState?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeDownloadState.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeDownloadState.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterOptionTypeDownloaderStreamUpdate: FfiConverterRustBuffer {
+ typealias SwiftType = DownloaderStreamUpdate?
+
+ public static func write(_ value: SwiftType, into buf: inout [UInt8]) {
+ guard let value = value else {
+ writeInt(&buf, Int8(0))
+ return
+ }
+ writeInt(&buf, Int8(1))
+ FfiConverterTypeDownloaderStreamUpdate.write(value, into: &buf)
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
+ switch try readInt(&buf) as Int8 {
+ case 0: return nil
+ case 1: return try FfiConverterTypeDownloaderStreamUpdate.read(from: &buf)
+ default: throw UniffiInternalError.unexpectedOptionalTag
+ }
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeModel: FfiConverterRustBuffer {
+ typealias SwiftType = [Model]
+
+ public static func write(_ value: [Model], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeModel.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [Model] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [Model]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeModel.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeModelFamily: FfiConverterRustBuffer {
+ typealias SwiftType = [ModelFamily]
+
+ public static func write(_ value: [ModelFamily], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeModelFamily.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ModelFamily] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ModelFamily]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeModelFamily.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeModelRegistry: FfiConverterRustBuffer {
+ typealias SwiftType = [ModelRegistry]
+
+ public static func write(_ value: [ModelRegistry], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeModelRegistry.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ModelRegistry] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ModelRegistry]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeModelRegistry.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterSequenceTypeModelVendor: FfiConverterRustBuffer {
+ typealias SwiftType = [ModelVendor]
+
+ public static func write(_ value: [ModelVendor], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for item in value {
+ FfiConverterTypeModelVendor.write(item, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [ModelVendor] {
+ let len: Int32 = try readInt(&buf)
+ var seq = [ModelVendor]()
+ seq.reserveCapacity(Int(len))
+ for _ in 0 ..< len {
+ seq.append(try FfiConverterTypeModelVendor.read(from: &buf))
+ }
+ return seq
+ }
+}
+
+#if swift(>=5.8)
+@_documentation(visibility: private)
+#endif
+fileprivate struct FfiConverterDictionaryStringTypeDownloadState: FfiConverterRustBuffer {
+ public static func write(_ value: [String: DownloadState], into buf: inout [UInt8]) {
+ let len = Int32(value.count)
+ writeInt(&buf, len)
+ for (key, value) in value {
+ FfiConverterString.write(key, into: &buf)
+ FfiConverterTypeDownloadState.write(value, into: &buf)
+ }
+ }
+
+ public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> [String: DownloadState] {
+ let len: Int32 = try readInt(&buf)
+ var dict = [String: DownloadState]()
+ dict.reserveCapacity(Int(len))
+ for _ in 0..<len {
+ let key = try FfiConverterString.read(from: &buf)
+ let value = try FfiConverterTypeDownloadState.read(from: &buf)
+ dict[key] = value
+ }
+ return dict
+ }
+}
+private let UNIFFI_RUST_FUTURE_POLL_READY: Int8 = 0
+private let UNIFFI_RUST_FUTURE_POLL_WAKE: Int8 = 1
+
+fileprivate let uniffiContinuationHandleMap = UniffiHandleMap<UnsafeContinuation<Int8, Never>>()
+
+fileprivate func uniffiRustCallAsync<F, T>(
+ rustFutureFunc: () -> UInt64,
+ pollFunc: (UInt64, @escaping UniffiRustFutureContinuationCallback, UInt64) -> (),
+ completeFunc: (UInt64, UnsafeMutablePointer<RustCallStatus>) -> F,
+ freeFunc: (UInt64) -> (),
+ liftFunc: (F) throws -> T,
+ errorHandler: ((RustBuffer) throws -> Swift.Error)?
+) async throws -> T {
+ // Make sure to call the ensure init function since future creation doesn't have a
+ // RustCallStatus param, so doesn't use makeRustCall()
+ uniffiEnsureUzuInitialized()
+ let rustFuture = rustFutureFunc()
+ defer {
+ freeFunc(rustFuture)
+ }
+ var pollResult: Int8;
+ repeat {
+ pollResult = await withUnsafeContinuation {
+ pollFunc(
+ rustFuture,
+ { handle, pollResult in
+ uniffiFutureContinuationCallback(handle: handle, pollResult: pollResult)
+ },
+ uniffiContinuationHandleMap.insert(obj: $0)
+ )
+ }
+ } while pollResult != UNIFFI_RUST_FUTURE_POLL_READY
+
+ return try liftFunc(makeRustCall(
+ { completeFunc(rustFuture, $0) },
+ errorHandler: errorHandler
+ ))
+}
+
+// Callback handlers for an async calls. These are invoked by Rust when the future is ready. They
+// lift the return value or error and resume the suspended function.
+fileprivate func uniffiFutureContinuationCallback(handle: UInt64, pollResult: Int8) {
+ if let continuation = try? uniffiContinuationHandleMap.remove(handle: handle) {
+ continuation.resume(returning: pollResult)
+ } else {
+ print("uniffiFutureContinuationCallback invalid handle")
+ }
+}
+public func deviceCreate()throws -> Device {
+ return try FfiConverterTypeDevice_lift(try rustCallWithError(FfiConverterTypeDeviceError_lift) {
+ uniffi_uzu_fn_func_device_create($0
+ )
+})
+}
+public func engineCreate(config: EngineConfig)async throws -> Engine {
+ return
+ try await uniffiRustCallAsync(
+ rustFutureFunc: {
+ uniffi_uzu_fn_func_engine_create(FfiConverterTypeEngineConfig_lower(config)
+ )
+ },
+ pollFunc: ffi_uzu_rust_future_poll_u64,
+ completeFunc: ffi_uzu_rust_future_complete_u64,
+ freeFunc: ffi_uzu_rust_future_free_u64,
+ liftFunc: FfiConverterTypeEngine_lift,
+ errorHandler: FfiConverterTypeEngineError_lift
+ )
+}
+public func engineConfigCreate() -> EngineConfig {
+ return try! FfiConverterTypeEngineConfig_lift(try! rustCall() {
+ uniffi_uzu_fn_func_engine_config_create($0
+ )
+})
+}
+public func keyringCreate()throws -> Keyring {
+ return try FfiConverterTypeKeyring_lift(try rustCallWithError(FfiConverterTypeKeyringError_lift) {
+ uniffi_uzu_fn_func_keyring_create($0
+ )
+})
+}
+
+private enum InitializationResult {
+ case ok
+ case contractVersionMismatch
+ case apiChecksumMismatch
+}
+// Use a global variable to perform the versioning checks. Swift ensures that
+// the code inside is only computed once.
+private let initializationResult: InitializationResult = {
+ // Get the bindings contract version from our ComponentInterface
+ let bindings_contract_version = 30
+ // Get the scaffolding contract version by calling the into the dylib
+ let scaffolding_contract_version = ffi_uzu_uniffi_contract_version()
+ if bindings_contract_version != scaffolding_contract_version {
+ return InitializationResult.contractVersionMismatch
+ }
+ if (uniffi_uzu_checksum_func_device_create() != 25038) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_func_engine_create() != 53665) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_func_engine_config_create() != 64749) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_func_keyring_create() != 18990) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_chat() != 2862) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_classification() != 6465) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_download() != 25329) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_download_state() != 15736) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_download_states() != 7129) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_downloader() != 59345) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_model() != 59757) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_model_by_identifier() != 55868) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_model_by_path() != 9095) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_model_by_repo_id() != 34455) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_model_families() != 8277) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_model_path() != 49820) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_model_registries() != 31153) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_model_vendors() != 11354) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models() != 12021) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models_by_family() != 17221) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models_by_vendor() != 45624) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models_downloadable() != 16443) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models_for_chat() != 55387) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models_for_classification() != 8401) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models_for_speculation() != 36111) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models_for_text_to_speech() != 10176) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models_for_translation() != 56970) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models_local() != 2150) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_models_remote() != 36115) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_register_callback() != 18383) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_remove_backend() != 2857) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_remove_registry() != 48480) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_engine_text_to_speech() != 62782) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_downloader_delete() != 65010) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_downloader_pause() != 36380) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_downloader_progress() != 21048) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_downloader_resume() != 13815) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_downloader_state() != 23876) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_downloaderstream_next() != 54036) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_keyring_remove() != 4600) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_keyring_retrieve() != 45777) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_keyring_store() != 51749) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_constructor_enginecallback_create() != 1654) {
+ return InitializationResult.apiChecksumMismatch
+ }
+ if (uniffi_uzu_checksum_method_enginecallbackhandler_on_event() != 36847) {
+ return InitializationResult.apiChecksumMismatch
+ }
+
+ uniffiCallbackInitEngineCallbackHandler()
+ uniffiEnsureNagareInitialized()
+ uniffiEnsureShojiInitialized()
+ return InitializationResult.ok
+}()
+
+// Make the ensure init function public so that other modules which have external type references to
+// our types can call it.
+public func uniffiEnsureUzuInitialized() {
+ switch initializationResult {
+ case .ok:
+ break
+ case .contractVersionMismatch:
+ fatalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
+ case .apiChecksumMismatch:
+ fatalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
+ }
+}
+
+// swiftlint:enable all
\ No newline at end of file
diff --git a/bindings/swift/Tests/UzuTests/EngineTests.swift b/bindings/swift/Tests/UzuTests/EngineTests.swift
new file mode 100644
index 000000000..913e6a835
--- /dev/null
+++ b/bindings/swift/Tests/UzuTests/EngineTests.swift
@@ -0,0 +1,33 @@
+import XCTest
+@testable import Uzu
+
+final class EngineTests: XCTestCase {
+ override func setUp() {
+ super.setUp()
+ executionTimeAllowance = 600
+ }
+
+ func testChatReplyProducesText() async throws {
+ let engine = try await Engine.create(config: .create())
+
+ let maybeModel = try await engine.model(identifier: "Qwen/Qwen3-0.6B")
+ let model = try XCTUnwrap(maybeModel, "Model not found")
+
+ for try await update in try await engine.download(model: model).iterator() {
+ print("Download progress: \(update.progress())")
+ }
+
+ let session = try await engine.chat(model: model, config: .create())
+
+ let messages = [
+ ChatMessage.system().withText(text: "You are a helpful assistant"),
+ ChatMessage.user().withText(text: "Hi"),
+ ]
+
+ let reply = try await session.reply(input: messages, config: .create())
+ let message = try XCTUnwrap(reply.last?.message, "Reply has no messages")
+
+ XCTAssertNotNil(message.reasoning())
+ XCTAssertNotNil(message.text())
+ }
+}
diff --git a/bindings/swift/build_release_xcframework.sh b/bindings/swift/build_release_xcframework.sh
new file mode 100755
index 000000000..87695b279
--- /dev/null
+++ b/bindings/swift/build_release_xcframework.sh
@@ -0,0 +1,82 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# build_release_xcframework.sh
+# Builds the Uzu Swift package in Release configuration for macOS,
+# iOS device and iOS simulator slices and combines them into a single
+# universal `uzu.xcframework` ready for distribution (e.g. publishing
+# to a private or public SwiftPM registry).
+#
+# The script relies on `update_uzu.sh` (which itself wraps `cargo swift`)
+# for per-platform builds and on `xcodebuild -create-xcframework` to
+# merge the individual static libraries.
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+SOURCE_PKG_DIR="$SCRIPT_DIR" # root of Swift package (update_uzu.sh writes here)
+
+# Default destination equals the source package location but can be overridden
+DEST_PKG_DIR="$SOURCE_PKG_DIR"
+
+# Parse CLI options
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --destination|-d)
+ DEST_PKG_DIR="$2"; shift 2;;
+ *)
+ echo "Unknown option: $1" >&2; exit 1;;
+ esac
+done
+
+UNIVERSAL_XCFRAMEWORK="$SOURCE_PKG_DIR/uzu.xcframework"
+
+BUILD_ROOT="$SCRIPT_DIR/.release_build"
+SLICES_DIR="$BUILD_ROOT/slices"
+
+rm -rf "$BUILD_ROOT"
+mkdir -p "$SLICES_DIR"
+
+# 1. Build each platform slice in Release mode
+# Allow overriding platforms via env var UZU_SWIFT_PLATFORMS (e.g., "macos" for local)
+PLATFORMS=${UZU_SWIFT_PLATFORMS:-"ios ios-sim macos"}
+for platform in $PLATFORMS; do
+ echo "\n=== Building Uzu for $platform (Release) ==="
+ bash "$SCRIPT_DIR/update_uzu.sh" --platform "$platform" --configuration Release
+ # Preserve the generated xcframework for later merging
+ cp -R "$UNIVERSAL_XCFRAMEWORK" "$SLICES_DIR/${platform}.xcframework"
+done
+
+# 2. Combine slices into a single universal xcframework
+echo "\n=== Creating universal xcframework ==="
+rm -rf "$UNIVERSAL_XCFRAMEWORK"
+
+LIB_ARGS=()
+for platform in $PLATFORMS; do
+ SLICE="$SLICES_DIR/${platform}.xcframework"
+ LIB_PATH="$(find "$SLICE" -name 'libuzu.a' | head -n 1)"
+ HEADERS_PATH="$(dirname "$LIB_PATH")/Headers"
+ LIB_ARGS+=("-library" "$LIB_PATH" "-headers" "$HEADERS_PATH")
+done
+
+xcodebuild -create-xcframework "${LIB_ARGS[@]}" -output "$UNIVERSAL_XCFRAMEWORK" | cat
+
+# Sign the universal xcframework
+echo "\n=== Signing universal xcframework ==="
+# Try to sign with developer certificate, fall back to ad-hoc signing
+if security find-identity -v -p codesigning | grep -q "Apple Development"; then
+ SIGNING_IDENTITY=$(security find-identity -v -p codesigning | grep "Apple Development" | head -n 1 | awk '{print $2}')
+ echo "Signing with identity: $SIGNING_IDENTITY"
+ codesign --force --sign "$SIGNING_IDENTITY" --timestamp "$UNIVERSAL_XCFRAMEWORK"
+else
+ echo "No developer certificate found, applying ad-hoc signing"
+ codesign --force --sign - "$UNIVERSAL_XCFRAMEWORK"
+fi
+
+# 3. Copy the finished Swift package to destination if it differs from source
+if [[ "$DEST_PKG_DIR" != "$SOURCE_PKG_DIR" ]]; then
+ echo "\n=== Copying Swift package to $DEST_PKG_DIR ==="
+ rm -rf "$DEST_PKG_DIR"
+ mkdir -p "$(dirname "$DEST_PKG_DIR")"
+ rsync -a --delete "$SOURCE_PKG_DIR/" "$DEST_PKG_DIR/"
+fi
+
+echo "\n✅ Release Swift package ready at $DEST_PKG_DIR"
diff --git a/bindings/swift/update_uzu.sh b/bindings/swift/update_uzu.sh
new file mode 100755
index 000000000..f5cce09d4
--- /dev/null
+++ b/bindings/swift/update_uzu.sh
@@ -0,0 +1,245 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+# update_uzu.sh
+# Regenerates the Uzu Swift package (binary target + generated bindings)
+# for the requested Apple platform/configuration using cargo-swift.
+# This script is invoked from Xcode scheme pre-actions so it MUST stay fast:
+# Xcode passes the effective PLATFORM name (ios, iphonesimulator, macosx, …)
+# and CONFIGURATION (Debug / Release).
+#
+# Requires: `cargo swift` to be installed (`cargo install cargo-swift`).
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+WORKSPACE_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
+RUST_CRATE_DIR="$WORKSPACE_ROOT/crates/uzu"
+
+# Destination Swift package (checked in to the repo and referenced by Xcode)
+DEST_PKG_DIR="$SCRIPT_DIR"
+DEST_SRC_DIR="$DEST_PKG_DIR/Sources"
+
+PLATFORM="${PLATFORM:-ios}"
+CONFIGURATION="${CONFIGURATION:-Debug}"
+
+# Capture Xcode-provided deployment targets before we unset them later.
+# These come from Project.swift deploymentTargets and are the source of truth.
+XCODE_IPHONEOS_DEPLOYMENT_TARGET="${IPHONEOS_DEPLOYMENT_TARGET:-26.0}"
+XCODE_MACOSX_DEPLOYMENT_TARGET="${MACOSX_DEPLOYMENT_TARGET:-26.0}"
+
+# Ensure Rust, Homebrew, etc. binaries are on PATH when called from Xcode (which resets PATH)
+if [ -d "/opt/homebrew/bin" ]; then
+ export PATH="/opt/homebrew/bin:$PATH"
+fi
+if [ -d "/usr/local/bin" ]; then
+ export PATH="/usr/local/bin:$PATH"
+fi
+if [ -d "$HOME/.cargo/bin" ]; then
+ export PATH="$HOME/.cargo/bin:$PATH"
+fi
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --platform)
+ if [[ -z "${2:-}" ]]; then
+ echo "Error: --platform requires a value"
+ exit 1
+ fi
+ PLATFORM="$2"
+ shift 2
+ ;;
+ --configuration)
+ if [[ -z "${2:-}" ]]; then
+ echo "Error: --configuration requires a value"
+ exit 1
+ fi
+ CONFIGURATION="$2"
+ shift 2
+ ;;
+ *)
+ shift
+ ;;
+ esac
+done
+
+# Normalise PLATFORM value (xcode passes like -iphonesimulator etc.)
+PLATFORM="$(echo "$PLATFORM" | tr '[:upper:]' '[:lower:]')"
+[[ "$PLATFORM" == "iphonesimulator" ]] && PLATFORM="ios-sim"
+[[ "$PLATFORM" == "macosx" ]] && PLATFORM="macos"
+[[ "$PLATFORM" == "iphoneos" ]] && PLATFORM="ios"
+
+if [[ -z "$PLATFORM" ]]; then
+ # Fallback to PLATFORM_NAME provided by Xcode (e.g. macosx, iphoneos, iphonesimulator)
+ PLATFORM="$(echo "${PLATFORM_NAME:-}" | tr '[:upper:]' '[:lower:]')"
+ [[ "$PLATFORM" == "macosx" ]] && PLATFORM="macos"
+ [[ "$PLATFORM" == "iphoneos" ]] && PLATFORM="ios"
+ [[ "$PLATFORM" == "iphonesimulator" ]] && PLATFORM="ios-sim"
+fi
+
+# Validate platform value
+case "$PLATFORM" in
+ ios|ios-sim|macos) ;;
+ *)
+ echo "Error: Invalid platform '$PLATFORM'"
+ echo "Valid platforms: ios, ios-sim, macos"
+ exit 1
+ ;;
+esac
+
+echo "↪︎ Rebuilding Uzu Swift package for $PLATFORM ($CONFIGURATION)"
+
+#####################################
+# 1. Generate Swift package with cargo-swift
+#####################################
+# Map platform to cargo-swift target triple list (cargo-swift supports multi-target but
+# we only build the slice we currently need to speed things up).
+case "$PLATFORM" in
+ ios) CS_TARGET="aarch64-apple-ios";;
+ ios-sim) CS_TARGET="aarch64-apple-ios-sim";;
+ macos) CS_TARGET="aarch64-apple-darwin";;
+ *) echo "Unsupported platform $PLATFORM"; exit 1;;
+esac
+
+CS_RELEASE_FLAG=""
+if [[ "$CONFIGURATION" == "Release" ]]; then
+ CS_RELEASE_FLAG="--release"
+fi
+
+# Determine swift platform flag
+case "$PLATFORM" in
+ ios) CS_SWIFT_PLATFORM="ios";;
+ ios-sim) CS_SWIFT_PLATFORM="ios";;
+ macos) CS_SWIFT_PLATFORM="macos";;
+ *) CS_SWIFT_PLATFORM="ios";;
+esac
+
+# Run cargo-swift inside crate directory
+
+pushd "$RUST_CRATE_DIR" >/dev/null
+
+# Xcode exports deployment targets for ALL platforms, which can confuse C/C++ builds.
+# Unset ALL deployment targets first, then set only the one we need.
+unset MACOSX_DEPLOYMENT_TARGET
+unset IPHONEOS_DEPLOYMENT_TARGET
+unset XROS_DEPLOYMENT_TARGET
+unset TVOS_DEPLOYMENT_TARGET
+unset WATCHOS_DEPLOYMENT_TARGET
+unset DRIVERKIT_DEPLOYMENT_TARGET
+
+# Xcode sets SDKROOT to the iOS SDK during iOS builds. That confuses the host-side
+# build of procedural-macro crates (which must link against the macOS SDK).
+# For iOS builds we unset it; for macOS builds we point it explicitly to the macOS SDK
+# so Rust's linker can find system libs like libobjc.
+case "$PLATFORM" in
+ ios|ios-sim)
+ unset SDKROOT
+ ;;
+ macos)
+ export SDKROOT="$(xcrun --sdk macosx --show-sdk-path)"
+ # Help rustc locate system libraries when using -nodefaultlibs by passing the sysroot
+ export RUSTFLAGS="${RUSTFLAGS:-} -C link-arg=-isysroot -C link-arg=$SDKROOT"
+ ;;
+esac
+
+unset SWIFT_DEBUG_INFORMATION_FORMAT
+unset SWIFT_DEBUG_INFORMATION_VERSION
+
+#####################################
+# Set explicit Apple deployment targets for native objects
+# Values come from Xcode (Project.swift is source of truth)
+# Must be done AFTER unsetting conflicting environment variables above
+#
+# Note: We do NOT set CFLAGS/CXXFLAGS globally as they affect host builds
+# (build scripts, proc-macros) and cause conflicts with cross-compilation.
+# cargo-swift handles target-specific flags internally.
+#####################################
+case "$PLATFORM" in
+ macos)
+ export MACOSX_DEPLOYMENT_TARGET="$XCODE_MACOSX_DEPLOYMENT_TARGET"
+ ;;
+ ios)
+ export IPHONEOS_DEPLOYMENT_TARGET="$XCODE_IPHONEOS_DEPLOYMENT_TARGET"
+ ;;
+ ios-sim)
+ export IPHONEOS_DEPLOYMENT_TARGET="$XCODE_IPHONEOS_DEPLOYMENT_TARGET"
+ ;;
+esac
+
+cargo swift package \
+ --name uzu \
+ --xcframework-name uzu \
+ --target "$CS_TARGET" \
+ -p "$CS_SWIFT_PLATFORM" \
+ --features "bindings-uniffi" \
+ $CS_RELEASE_FLAG \
+ -y >/dev/null
+
+popd >/dev/null
+
+# The generated package lives at $RUST_CRATE_DIR/uzu
+PKG_OUT_DIR="$RUST_CRATE_DIR/uzu"
+
+#####################################
+# 2. Copy artefacts into the repository's Swift package wrapper
+#####################################
+
+# Ensure wrapper package skeleton exists (Package.swift, Sources folder, etc.)
+mkdir -p "$DEST_PKG_DIR"
+mkdir -p "$DEST_SRC_DIR/Uzu"
+
+# Package.swift manifest generation has been moved to setup.sh
+
+# Copy generated FFI Swift sources
+SRC_GEN_DIR="$PKG_OUT_DIR/Sources"
+if [[ -d "$SRC_GEN_DIR" ]]; then
+ echo "• Updating generated swift sources"
+ rm -rf "$DEST_SRC_DIR/Uzu/Generated"
+ mkdir -p "$DEST_SRC_DIR/Uzu/Generated"
+ rsync -a --delete "$SRC_GEN_DIR/" "$DEST_SRC_DIR/Uzu/Generated/"
+fi
+
+# Copy xcframework
+XC_PATH="$PKG_OUT_DIR/uzu.xcframework"
+if [[ -d "$XC_PATH" ]]; then
+ echo "• Copying xcframework to package root"
+ rm -rf "$DEST_PKG_DIR/uzu.xcframework"
+ cp -R "$XC_PATH" "$DEST_PKG_DIR/uzu.xcframework"
+
+ # Flatten headers: cargo-swift nests them under Headers/<name>/ but SPM expects
+ # the modulemap directly inside Headers/
+ for slice_dir in "$DEST_PKG_DIR/uzu.xcframework"/*/; do
+ headers_dir="${slice_dir}Headers"
+ [[ -d "$headers_dir" ]] || continue
+ for nested_modulemap in "$headers_dir"/*/module.modulemap; do
+ [[ -f "$nested_modulemap" ]] || continue
+ nested_dir="$(dirname "$nested_modulemap")"
+ mv "$nested_dir"/* "$headers_dir/"
+ rmdir "$nested_dir"
+ done
+ done
+
+ # Sign the xcframework with the current development team
+ # For Release builds, this ensures the framework is properly signed for distribution
+ if [[ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" && "$EXPANDED_CODE_SIGN_IDENTITY" != "-" ]]; then
+ echo "• Signing xcframework with identity: $EXPANDED_CODE_SIGN_IDENTITY"
+ codesign --force --sign "$EXPANDED_CODE_SIGN_IDENTITY" \
+ --timestamp \
+ --preserve-metadata=identifier,entitlements,flags \
+ "$DEST_PKG_DIR/uzu.xcframework" 2>/dev/null || true
+ elif [[ "$CONFIGURATION" == "Release" ]]; then
+ # For Release builds outside of Xcode, try to use ad-hoc signing
+ echo "• Applying ad-hoc signing to xcframework"
+ codesign --force --sign - "$DEST_PKG_DIR/uzu.xcframework" 2>/dev/null || true
+ fi
+fi
+
+# Clean up generated Swift package directory created by cargo-swift
+if [[ -d "$PKG_OUT_DIR" ]]; then
+ rm -rf "$PKG_OUT_DIR"
+fi
+
+# Also remove crate-local generated directory if present
+if [[ -d "$RUST_CRATE_DIR/generated" ]]; then
+ rm -rf "$RUST_CRATE_DIR/generated"
+fi
+
+echo "✓ Uzu package refreshed"
diff --git a/bindings/ts/README.md b/bindings/ts/README.md
index cd49c6f02..9b182ada7 100644
--- a/bindings/ts/README.md
+++ b/bindings/ts/README.md
@@ -28,7 +28,7 @@ Add the `uzu` dependency to your project's `package.json`:
}
```
-Set up your project through [Platform](https://platform.trymirai.com) and obtain an `API_KEY`. Then, choose the model you want from the [library](https://platform.trymirai.com/models) and run it with the following snippet using the corresponding identifier:
+Run the snippet below:
```ts
// include:examples/snippets.ts#quick-start
@@ -38,7 +38,7 @@ Everything from model downloading to inference configuration is handled automati
## Examples
-Place the `API_KEY` you obtained earlier in the corresponding example file, and then run it using one of the following commands:
+Run it using one of the following commands:
```bash
pnpm run tsn examples/chat.ts
@@ -88,7 +88,7 @@ Sometimes you want to create a complex pipeline where some requests are processe
### Structured Output
-Sometimes you want the generated output to be valid JSON with predefined fields. You can use `GrammarConfig` to manually specify a JSON schema, or define the schema using [Zod](https://github.com/colinhacks/zod).
+Sometimes you want the generated output to be valid JSON with predefined fields. You can use `Grammar` to manually specify a JSON schema, or define the schema using [Zod](https://github.com/colinhacks/zod).
```ts
// include:examples/structuredOutput.ts
diff --git a/bindings/ts/src/napi/uzu.d.ts b/bindings/ts/src/napi/uzu.d.ts
new file mode 100644
index 000000000..a30dec38c
--- /dev/null
+++ b/bindings/ts/src/napi/uzu.d.ts
@@ -0,0 +1,974 @@
+/* auto-generated by NAPI-RS */
+/* eslint-disable */
+export declare class ChatSession {
+ get state(): Promise<ChatSessionState>
+ get messages(): Promise<Array<ChatMessage>>
+ reset(): Promise<void>
+ reply(input: Array<ChatMessage>, config: ChatReplyConfig): Promise<Array<ChatReply>>
+ replyWithStream(input: Array<ChatMessage>, config: ChatReplyConfig): Promise<ChatSessionStream>
+}
+
+/**
+ * This type implements JavaScript's async iterable protocol.
+ * It can be used with `for await...of` loops.
+ *
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols
+ */
+export declare class ChatSessionStream {
+ next(): Promise<ChatSessionStreamChunk | null>
+ get cancelToken(): CancelToken
+ [Symbol.asyncIterator](): AsyncGenerator<ChatSessionStreamChunk, void, undefined>
+}
+
+export declare class ChatSessionStreamChunkError {
+ error: ChatSessionError
+ constructor(error: ChatSessionError)
+}
+
+export declare class ChatSessionStreamChunkReplies {
+ replies: Array<ChatReply>
+ constructor(replies: Array<ChatReply>)
+}
+
+export declare class ClassificationSession {
+ get state(): Promise<ClassificationSessionState>
+ classify(input: Array<ClassificationMessage>): Promise<ClassificationOutput>
+}
+
+export declare class TextToSpeechSession {
+ get state(): Promise<TextToSpeechSessionState>
+ synthesize(input: string): Promise<PcmBatch>
+}
+
+/**
+ * This type implements JavaScript's async iterable protocol.
+ * It can be used with `for await...of` loops.
+ *
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols
+ */
+export declare class TextToSpeechSessionStream {
+ next(): Promise<TextToSpeechSessionStreamChunk | null>
+ get cancelToken(): CancelToken
+ [Symbol.asyncIterator](): AsyncGenerator<TextToSpeechSessionStreamChunk, void, undefined>
+}
+
+export declare class TextToSpeechSessionStreamChunkError {
+ error: TextToSpeechSessionError
+ constructor(error: TextToSpeechSessionError)
+}
+
+export declare class TextToSpeechSessionStreamChunkPcmBatch {
+ batch: PcmBatch
+ constructor(batch: PcmBatch)
+}
+
+export type ChatSessionError =
+ | { type: 'Backend', message: string }
+ | { type: 'UnsupportedModel' }
+ | { type: 'UnableToPerformOperationInCurrentState' }
+ | { type: 'NoResponse' }
+
+export declare const enum ChatSessionState {
+ Idle = 'Idle',
+ Generation = 'Generation',
+ ToolCalling = 'ToolCalling',
+ Resetting = 'Resetting'
+}
+
+export type ChatSessionStreamChunk =
+ ChatSessionStreamChunkReplies | ChatSessionStreamChunkError
+
+export type ClassificationSessionError =
+ | { type: 'Backend', message: string }
+ | { type: 'UnsupportedModel' }
+ | { type: 'UnableToPerformOperationInCurrentState' }
+ | { type: 'NoResponse' }
+
+export declare const enum ClassificationSessionState {
+ Idle = 'Idle',
+ Classifying = 'Classifying'
+}
+
+export type TextToSpeechSessionError =
+ | { type: 'Backend', message: string }
+ | { type: 'UnsupportedModel' }
+ | { type: 'UnableToPerformOperationInCurrentState' }
+ | { type: 'NoResponse' }
+
+export declare const enum TextToSpeechSessionState {
+ Idle = 'Idle',
+ Synthesizing = 'Synthesizing'
+}
+
+export type TextToSpeechSessionStreamChunk =
+ TextToSpeechSessionStreamChunkPcmBatch | TextToSpeechSessionStreamChunkError
+export declare class CancelToken {
+ cancel(): void
+ get isCancelled(): boolean
+ static create(): CancelToken
+}
+
+export declare class ChatConfig {
+ contextLength: ContextLength
+ samplingSeed: SamplingSeed
+ speculationPreset?: ChatSpeculationPreset
+ constructor(contextLength: ContextLength, samplingSeed: SamplingSeed, speculationPreset?: ChatSpeculationPreset)
+
+ static create(): ChatConfig
+ withContextLength(contextLength: ContextLength): ChatConfig
+ withSamplingSeed(samplingSeed: SamplingSeed): ChatConfig
+ withSpeculationPreset(speculationPreset?: ChatSpeculationPreset | undefined | null): ChatConfig
+}
+
+export declare class ChatContentBlockAudio {
+ url: string
+ constructor(url: string)
+}
+
+export declare class ChatContentBlockBuiltinTools {
+ names: Array<string>
+ constructor(names: Array<string>)
+}
+
+export declare class ChatContentBlockConversationStartDate {
+ value: string
+ constructor(value: string)
+}
+
+export declare class ChatContentBlockCustom {
+ value: any
+ constructor(value: any)
+}
+
+export declare class ChatContentBlockFile {
+ url: string
+ constructor(url: string)
+}
+
+export declare class ChatContentBlockIdentity {
+ value: string
+ constructor(value: string)
+}
+
+export declare class ChatContentBlockImage {
+ url: string
+ constructor(url: string)
+}
+
+export declare class ChatContentBlockKnowledgeCutoff {
+ value: string
+ constructor(value: string)
+}
+
+export declare class ChatContentBlockReasoning {
+ value: string
+ constructor(value: string)
+}
+
+export declare class ChatContentBlockReasoningEffort {
+ value: ReasoningEffort
+ constructor(value: ReasoningEffort)
+}
+
+export declare class ChatContentBlockText {
+ value: string
+ constructor(value: string)
+}
+
+export declare class ChatContentBlockToolCall {
+ value: ToolCall
+ constructor(value: ToolCall)
+}
+
+export declare class ChatContentBlockToolCallCandidate {
+ value: any
+ constructor(value: any)
+}
+
+export declare class ChatContentBlockToolCallResult {
+ identifier?: string
+ name?: string
+ value: any
+ constructor(identifier?: string, name?: string, value: any)
+}
+
+export declare class ChatContentBlockTools {
+ namespaces: Array<ToolNamespace>
+ constructor(namespaces: Array<ToolNamespace>)
+}
+
+export declare class ChatContentBlockTranslation {
+ payload: TranslationPayload
+ sourceLanguageCode: string
+ targetLanguageCode: string
+ constructor(payload: TranslationPayload, sourceLanguageCode: string, targetLanguageCode: string)
+}
+
+export declare class ChatContentBlockVideo {
+ url: string
+ constructor(url: string)
+}
+
+export declare class ChatMessage {
+ role: ChatRole
+ content: Array<ChatContentBlock>
+ metadata: ChatMessageMetadata
+ constructor(role: ChatRole, content: Array<ChatContentBlock>, metadata: ChatMessageMetadata)
+
+ static for_role(role: ChatRole): ChatMessage
+ static system(): ChatMessage
+ static developer(): ChatMessage
+ static user(): ChatMessage
+ static assistant(): ChatMessage
+ static tool(): ChatMessage
+ withBlock(block: ChatContentBlock): ChatMessage
+ withReasoningEffort(reasoningEffort: ReasoningEffort): ChatMessage
+ withToolNamespaces(toolNamespaces: Array<ToolNamespace>): ChatMessage
+ withText(text: string): ChatMessage
+ withReasoning(reasoning: string): ChatMessage
+ withToolCall(toolCall: ToolCall): ChatMessage
+ withToolCallCandidate(value: any): ChatMessage
+ get reasoningEffort(): ReasoningEffort | null
+ get text(): string | null
+ get reasoning(): string | null
+ get toolNamespaces(): Array<ToolNamespace>
+ get toolCalls(): Array<ToolCall>
+}
+
+export declare class ChatModelCapabilities {
+ supportsReasoning: boolean
+ supportsDisableReasoning: boolean
+ supportsTools: boolean
+ supportsMultipleToolCalls: boolean
+ requiresTools: boolean
+ constructor(supportsReasoning: boolean, supportsDisableReasoning: boolean, supportsTools: boolean, supportsMultipleToolCalls: boolean, requiresTools: boolean)
+}
+
+export declare class ChatReply {
+ message: ChatMessage
+ stats: ChatReplyStats
+ finishReason?: ChatReplyFinishReason
+ constructor(message: ChatMessage, stats: ChatReplyStats, finishReason?: ChatReplyFinishReason)
+}
+
+export declare class ChatReplyConfig {
+ tokenLimit?: number
+ samplingPolicy: SamplingPolicy
+ grammar?: Grammar
+ constructor(tokenLimit?: number, samplingPolicy: SamplingPolicy, grammar?: Grammar)
+
+ static create(): ChatReplyConfig
+ withTokenLimit(tokenLimit?: number | undefined | null): ChatReplyConfig
+ withSamplingPolicy(samplingPolicy: SamplingPolicy): ChatReplyConfig
+ withSamplingMethod(samplingMethod: SamplingMethod): ChatReplyConfig
+ withGrammar(grammar?: Grammar | undefined | null): ChatReplyConfig
+}
+
+export declare class ChatReplyStats {
+ duration: number
+ timeToFirstToken?: number
+ prefillTokensPerSecond?: number
+ generateTokensPerSecond?: number
+ tokensCountInput?: number
+ tokensCountOutput?: number
+ constructor(duration: number, timeToFirstToken?: number, prefillTokensPerSecond?: number, generateTokensPerSecond?: number, tokensCountInput?: number, tokensCountOutput?: number)
+ get tokensCount(): number | null
+}
+
+export declare class ChatRoleAssistant {
+
+ constructor()
+}
+
+export declare class ChatRoleCustom {
+ name: string
+ constructor(name: string)
+}
+
+export declare class ChatRoleDeveloper {
+
+ constructor()
+}
+
+export declare class ChatRoleSystem {
+
+ constructor()
+}
+
+export declare class ChatRoleTool {
+
+ constructor()
+}
+
+export declare class ChatRoleUser {
+
+ constructor()
+}
+
+export declare class ChatSpeculationPresetClassification {
+ feature: Feature
+ constructor(feature: Feature)
+}
+
+export declare class ChatSpeculationPresetGeneralChat {
+
+ constructor()
+}
+
+export declare class ChatSpeculationPresetSummarization {
+
+ constructor()
+}
+
+export declare class ClassificationLabel {
+ index: number
+ label: string
+ title: string
+ description: string
+ recommendedThreshold: number
+ constructor(index: number, label: string, title: string, description: string, recommendedThreshold: number)
+}
+
+export declare class ClassificationMessage {
+ role: ClassificationRole
+ content: string
+ constructor(role: ClassificationRole, content: string)
+
+ static user(content: string): ClassificationMessage
+ static assistant(content: string): ClassificationMessage
+}
+
+export declare class ClassificationOutput {
+ logits: Array<number>
+ probabilities: ClassificationOutputProbabilities
+ stats: ClassificationStats
+ constructor(logits: Array<number>, probabilities: ClassificationOutputProbabilities, stats: ClassificationStats)
+}
+
+export declare class ClassificationStats {
+ preprocessingDuration: number
+ forwardPassDuration: number
+ postprocessingDuration: number
+ totalDuration: number
+ tokensCount: number
+ tokensPerSecond: number
+ predictedLabel: string
+ confidence: number
+ constructor(preprocessingDuration: number, forwardPassDuration: number, postprocessingDuration: number, totalDuration: number, tokensCount: number, tokensPerSecond: number, predictedLabel: string, confidence: number)
+}
+
+export declare class ContextLengthCustom {
+ length: number
+ constructor(length: number)
+}
+
+export declare class ContextLengthDefault {
+
+ constructor()
+}
+
+export declare class ContextLengthMaximal {
+
+ constructor()
+}
+
+export declare class Feature {
+ name: string
+ values: Array<string>
+ constructor(name: string, values: Array<string>)
+}
+
+export declare class File {
+ url: string
+ name: string
+ size: number
+ hashes: Array<Hash>
+ constructor(url: string, name: string, size: number, hashes: Array<Hash>)
+ get crc32C(): string | null
+ get md5(): string | null
+}
+
+export declare class GrammarJsonAny {
+
+ constructor()
+}
+
+export declare class GrammarJsonSchema {
+ schema: string
+ constructor(schema: string)
+}
+
+export declare class GrammarRegex {
+ pattern: string
+ constructor(pattern: string)
+}
+
+export declare class Hash {
+ method: HashMethod
+ value: string
+ constructor(method: HashMethod, value: string)
+}
+
+export declare class Image {
+ id: string
+ url: string
+ theme: ImageTheme
+ format: ImageFormat
+ description?: string
+ width?: number
+ height?: number
+ constructor(id: string, url: string, theme: ImageTheme, format: ImageFormat, description?: string, width?: number, height?: number)
+}
+
+export declare class Metadata {
+ identifier: string
+ name: string
+ description?: string
+ icons: Array<Image>
+ constructor(identifier: string, name: string, description?: string, icons: Array<Image>)
+
+ static external(name: string): Metadata
+}
+
+export declare class Model {
+ identifier: string
+ registry: ModelRegistry
+ backends: Array<ModelBackend>
+ family?: ModelFamily
+ properties?: ModelProperties
+ quantization?: ModelQuantization
+ specializations: Array<ModelSpecialization>
+ accessibility: ModelAccessibility
+ constructor(identifier: string, registry: ModelRegistry, backends: Array<ModelBackend>, family?: ModelFamily, properties?: ModelProperties, quantization?: ModelQuantization, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility)
+ get name(): string
+ get isLocal(): boolean
+ get isRemote(): boolean
+ get isDownloadable(): boolean
+ get isQuantized(): boolean
+ get cacheIdentifier(): string
+ get repoIds(): Array<string>
+ get localExternalPath(): string | null
+ get referenceName(): string | null
+ get checkpointVersion(): string | null
+
+ static external(identifier: string, registryIdentifier: string, registryName: string, backendIdentifier: string, backendName: string, backendVersion: string, specializations: Array<ModelSpecialization>, accessibility: ModelAccessibility): Model
+ get isChatCapable(): boolean
+ get isClassificationCapable(): boolean
+ get isTextToSpeechCapable(): boolean
+ get isTranslationCapable(): boolean
+ get isSpeculationCapable(): boolean
+}
+
+export declare class ModelAccessibilityLocal {
+ reference: ModelReference
+ constructor(reference: ModelReference)
+}
+
+export declare class ModelAccessibilityRemote {
+ repository?: Repository
+ constructor(repository?: Repository)
+}
+
+export declare class ModelBackend {
+ identifier: string
+ version: string
+ metadata: Metadata
+ constructor(identifier: string, version: string, metadata: Metadata)
+ get name(): string
+}
+
+export declare class ModelFamily {
+ identifier: string
+ vendor: ModelVendor
+ metadata: Metadata
+ constructor(identifier: string, vendor: ModelVendor, metadata: Metadata)
+ get name(): string
+}
+
+export declare class ModelProperties {
+ identifier: string
+ size: number
+ version?: string
+ metadata: Metadata
+ constructor(identifier: string, size: number, version?: string, metadata: Metadata)
+ get name(): string
+}
+
+export declare class ModelQuantization {
+ identifier: string
+ method: string
+ bitsPerWeight: number
+ vendor: ModelVendor
+ metadata: Metadata
+ constructor(identifier: string, method: string, bitsPerWeight: number, vendor: ModelVendor, metadata: Metadata)
+ get name(): string
+}
+
+export declare class ModelReferenceHuggingFace {
+ repository: Repository
+ constructor(repository: Repository)
+}
+
+export declare class ModelReferenceLocal {
+ path: string
+ constructor(path: string)
+}
+
+export declare class ModelReferenceMirai {
+ toolchainVersion: string
+ repository?: Repository
+ sourceRepository?: Repository
+ files: Array<File>
+ constructor(toolchainVersion: string, repository?: Repository, sourceRepository?: Repository, files: Array<File>)
+}
+
+export declare class ModelRegistry {
+ identifier: string
+ metadata: Metadata
+ constructor(identifier: string, metadata: Metadata)
+ get name(): string
+}
+
+export declare class ModelSpecializationChat {
+
+ constructor()
+}
+
+export declare class ModelSpecializationClassification {
+
+ constructor()
+}
+
+export declare class ModelSpecializationSpeculation {
+
+ constructor()
+}
+
+export declare class ModelSpecializationTextToSpeech {
+
+ constructor()
+}
+
+export declare class ModelSpecializationTranslation {
+
+ constructor()
+}
+
+export declare class ModelVendor {
+ identifier: string
+ metadata: Metadata
+ constructor(identifier: string, metadata: Metadata)
+ get name(): string
+}
+
+export declare class PcmBatch {
+ samples: Array<number>
+ sampleRate: number
+ channels: number
+ lengths: Array<number>
+ constructor(samples: Array<number>, sampleRate: number, channels: number, lengths: Array<number>)
+ get batchSize(): number
+ get totalFrames(): number
+ saveAsWav(path: string): void
+}
+
+export declare class Repository {
+ identifier: string
+ commitHash?: string
+ paths?: Array<string>
+ constructor(identifier: string, commitHash?: string, paths?: Array<string>)
+}
+
+export declare class SamplingMethodGreedy {
+
+ constructor()
+}
+
+export declare class SamplingMethodStochastic {
+ temperature?: number
+ topK?: number
+ topP?: number
+ minP?: number
+ constructor(temperature?: number, topK?: number, topP?: number, minP?: number)
+}
+
+export declare class SamplingPolicyCustom {
+ method: SamplingMethod
+ constructor(method: SamplingMethod)
+}
+
+export declare class SamplingPolicyDefault {
+
+ constructor()
+}
+
+export declare class SamplingSeedCustom {
+ seed: number
+ constructor(seed: number)
+}
+
+export declare class SamplingSeedDefault {
+
+ constructor()
+}
+
+export declare class TextToSpeechStats {
+ textLength: number
+ firstChunkSeconds: number
+ generationDuration: number
+ audioDuration: number
+ constructor(textLength: number, firstChunkSeconds: number, generationDuration: number, audioDuration: number)
+}
+
+export declare class Token {
+ id: TokenId
+ value: TokenValue
+ isSpecial: boolean
+ constructor(id: TokenId, value: TokenValue, isSpecial: boolean)
+}
+
+export declare class ToolCall {
+ identifier?: string
+ name: string
+ arguments: any
+ constructor(identifier?: string, name: string, arguments: any)
+}
+
+export declare class ToolDescriptionFunction {
+ toolFunction: ToolFunction
+ constructor(toolFunction: ToolFunction)
+}
+
+export declare class ToolFunction {
+ name: string
+ description: string
+ parameters?: any
+ returnDefinition?: any
+ constructor(name: string, description: string, parameters?: any, returnDefinition?: any)
+}
+
+export declare class ToolNamespace {
+ name: string
+ description?: string
+ tools: Array<ToolDescription>
+ constructor(name: string, description?: string, tools: Array<ToolDescription>)
+}
+
+export declare class TranslationPayloadImage {
+ url: string
+ constructor(url: string)
+}
+
+export declare class TranslationPayloadText {
+ text: string
+ constructor(text: string)
+}
+
+export declare class Value {
+ json: string
+ constructor(json: string)
+}
+
+export type ChatContentBlock =
+ ChatContentBlockIdentity | ChatContentBlockReasoningEffort | ChatContentBlockConversationStartDate | ChatContentBlockKnowledgeCutoff | ChatContentBlockBuiltinTools | ChatContentBlockTools | ChatContentBlockText | ChatContentBlockImage | ChatContentBlockVideo | ChatContentBlockAudio | ChatContentBlockFile | ChatContentBlockReasoning | ChatContentBlockToolCall | ChatContentBlockToolCallCandidate | ChatContentBlockToolCallResult | ChatContentBlockTranslation | ChatContentBlockCustom
+
+export declare const enum ChatContentBlockType {
+ Identity = 'Identity',
+ ReasoningEffort = 'ReasoningEffort',
+ ConversationStartDate = 'ConversationStartDate',
+ KnowledgeCutoff = 'KnowledgeCutoff',
+ BuiltinTools = 'BuiltinTools',
+ Tools = 'Tools',
+ Text = 'Text',
+ Image = 'Image',
+ Video = 'Video',
+ Audio = 'Audio',
+ File = 'File',
+ Reasoning = 'Reasoning',
+ ToolCall = 'ToolCall',
+ ToolCallCandidate = 'ToolCallCandidate',
+ ToolCallResult = 'ToolCallResult',
+ Translation = 'Translation',
+ Custom = 'Custom'
+}
+
+export interface ChatMessageMetadata {
+ values: Record<string, any>
+}
+
+export declare const enum ChatReplyFinishReason {
+ Stop = 'Stop',
+ Length = 'Length',
+ Cancelled = 'Cancelled',
+ ContextLimitReached = 'ContextLimitReached',
+ ToolCalls = 'ToolCalls',
+ Rejected = 'Rejected'
+}
+
+export type ChatRole =
+ ChatRoleUser | ChatRoleAssistant | ChatRoleSystem | ChatRoleDeveloper | ChatRoleTool | ChatRoleCustom
+
+export type ChatSpeculationPreset =
+ ChatSpeculationPresetGeneralChat | ChatSpeculationPresetSummarization | ChatSpeculationPresetClassification
+
+export interface ClassificationOutputProbabilities {
+ values: Record<string, number>
+}
+
+export declare const enum ClassificationRole {
+ User = 'User',
+ Assistant = 'Assistant'
+}
+
+export type ContextLength =
+ ContextLengthDefault | ContextLengthMaximal | ContextLengthCustom
+
+export type Grammar =
+ GrammarJsonAny | GrammarJsonSchema | GrammarRegex
+
+export declare const enum HashMethod {
+ CRC32C = 'CRC32C',
+ MD5 = 'MD5'
+}
+
+export declare const enum ImageFormat {
+ Png = 'Png',
+ Webp = 'Webp',
+ Svg = 'Svg'
+}
+
+export declare const enum ImageTheme {
+ Light = 'Light',
+ Dark = 'Dark'
+}
+
+export type ModelAccessibility =
+ ModelAccessibilityLocal | ModelAccessibilityRemote
+
+export type ModelReference =
+ ModelReferenceMirai | ModelReferenceHuggingFace | ModelReferenceLocal
+
+export type ModelSpecialization =
+ ModelSpecializationChat | ModelSpecializationClassification | ModelSpecializationTextToSpeech | ModelSpecializationTranslation | ModelSpecializationSpeculation
+
+export type PcmBatchError =
+ | { type: 'UnableToSaveAsWav', message: string }
+
+export declare const enum ReasoningEffort {
+ Disabled = 'Disabled',
+ Default = 'Default',
+ Low = 'Low',
+ Medium = 'Medium',
+ High = 'High'
+}
+
+export type SamplingMethod =
+ SamplingMethodGreedy | SamplingMethodStochastic
+
+export type SamplingPolicy =
+ SamplingPolicyDefault | SamplingPolicyCustom
+
+export type SamplingSeed =
+ SamplingSeedDefault | SamplingSeedCustom
+
+export type TokenId =
+ number
+
+export type TokenValue =
+ string
+
+export type ToolDescription =
+ ToolDescriptionFunction
+
+export type TranslationPayload =
+ TranslationPayloadText | TranslationPayloadImage
+export declare class Device {
+ osName?: string
+ cpuName?: string
+ memoryTotal: number
+ homePath: string
+ applicationIdentifier: string
+ isEnvironmentSandboxed: boolean
+ isKeyringAvailable: boolean
+ constructor(osName?: string, cpuName?: string, memoryTotal: number, homePath: string, applicationIdentifier: string, isEnvironmentSandboxed: boolean, isKeyringAvailable: boolean)
+
+ static create(): Device
+}
+
+export declare class Downloader {
+ get state(): Promise<DownloadState | null>
+ resume(): Promise<void>
+ pause(): Promise<void>
+ delete(): Promise<void>
+ progress(): Promise<DownloaderStream>
+}
+
+/**
+ * This type implements JavaScript's async iterable protocol.
+ * It can be used with `for await...of` loops.
+ *
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols
+ */
+export declare class DownloaderStream {
+ next(): Promise<DownloaderStreamUpdate | null>
+ [Symbol.asyncIterator](): AsyncGenerator<DownloaderStreamUpdate, void, undefined>
+}
+
+export declare class DownloaderStreamUpdate {
+ bytesTotal: number
+ bytesDownloaded: number
+ constructor(bytesTotal: number, bytesDownloaded: number)
+ get progress(): number
+}
+
+export declare class DownloadPhaseDownloaded {
+
+ constructor()
+}
+
+export declare class DownloadPhaseDownloading {
+
+ constructor()
+}
+
+export declare class DownloadPhaseError {
+ message: string
+ constructor(message: string)
+}
+
+export declare class DownloadPhaseLocked {
+
+ constructor()
+}
+
+export declare class DownloadPhaseNotDownloaded {
+
+ constructor()
+}
+
+export declare class DownloadPhasePaused {
+
+ constructor()
+}
+
+export declare class DownloadState {
+ totalBytes: number
+ downloadedBytes: number
+ phase: DownloadPhase
+ constructor(totalBytes: number, downloadedBytes: number, phase: DownloadPhase)
+ get progress(): number
+ get isInProgress(): boolean
+ get canPause(): boolean
+ get canDelete(): boolean
+}
+
+export declare class Engine {
+ static create(config: EngineConfig): Promise<Engine>
+ registerCallback(callback: EngineCallback): Promise<void>
+ removeRegistry(registryIdentifier: string): Promise<void>
+ removeBackend(identifier: string): Promise<void>
+ get models(): Promise<Array<Model>>
+ get modelsLocal(): Promise<Array<Model>>
+ get modelsRemote(): Promise<Array<Model>>
+ get modelsDownloadable(): Promise<Array<Model>>
+ get modelsForChat(): Promise<Array<Model>>
+ get modelsForClassification(): Promise<Array<Model>>
+ get modelsForTextToSpeech(): Promise<Array<Model>>
+ get modelsForTranslation(): Promise<Array<Model>>
+ get modelsForSpeculation(): Promise<Array<Model>>
+ get modelRegistries(): Promise<Array<ModelRegistry>>
+ get modelVendors(): Promise<Array<ModelVendor>>
+ modelsByVendor(vendorIdentifier: string): Promise<Array<Model>>
+ get modelFamilies(): Promise<Array<ModelFamily>>
+ modelsByFamily(familyIdentifier: string): Promise<Array<Model>>
+ model(identifier: string): Promise<Model | null>
+ modelByIdentifier(identifier: string): Promise<Model | null>
+ modelByRepoId(repoId: string): Promise<Model | null>
+ modelByPath(path: string): Promise<Model | null>
+ modelPath(model: Model): Promise<string | null>
+ downloader(model: Model): Downloader
+ download(model: Model): Promise<DownloaderStream>
+ downloadState(model: Model): Promise<DownloadState | null>
+ get downloadStates(): Promise<Record<string, DownloadState>>
+ chat(model: Model, config: ChatConfig): Promise<ChatSession>
+ classification(model: Model): Promise<ClassificationSession>
+ textToSpeech(model: Model): Promise<TextToSpeechSession>
+}
+
+export declare class EngineCallback {
+ static create(callback: () => void): EngineCallback
+}
+
+export declare class EngineConfig {
+ miraiApiKey?: string
+ lalamoPath?: string
+ huggingfaceApiKey?: string
+ openaiApiKey?: string
+ anthropicApiKey?: string
+ geminiApiKey?: string
+ xaiApiKey?: string
+ basetenApiKey?: string
+ openrouterApiKey?: string
+ allowOllamaUsage: boolean
+ allowLmstudioUsage: boolean
+ constructor(miraiApiKey?: string, lalamoPath?: string, huggingfaceApiKey?: string, openaiApiKey?: string, anthropicApiKey?: string, geminiApiKey?: string, xaiApiKey?: string, basetenApiKey?: string, openrouterApiKey?: string, allowOllamaUsage: boolean, allowLmstudioUsage: boolean)
+
+ static create(): EngineConfig
+ withMiraiApiKey(miraiApiKey: string): EngineConfig
+ withLalamoPath(lalamoPath: string): EngineConfig
+ withHuggingfaceApiKey(huggingfaceApiKey: string): EngineConfig
+ withOpenaiApiKey(openaiApiKey: string): EngineConfig
+ withAnthropicApiKey(anthropicApiKey: string): EngineConfig
+ withGeminiApiKey(geminiApiKey: string): EngineConfig
+ withXaiApiKey(xaiApiKey: string): EngineConfig
+ withBasetenApiKey(basetenApiKey: string): EngineConfig
+ withOpenrouterApiKey(openrouterApiKey: string): EngineConfig
+ withAllowOllamaUsage(allowOllamaUsage: boolean): EngineConfig
+ withAllowLmstudioUsage(allowLmstudioUsage: boolean): EngineConfig
+}
+
+export declare class Keyring {
+ store(key: string, value: string): void
+ retrieve(key: string): string | null
+ remove(key: string): void
+ static create(): Keyring
+}
+
+export type DeviceError =
+ | { type: 'UnsupportedDevice' }
+
+export type DownloadPhase =
+ DownloadPhaseNotDownloaded | DownloadPhaseDownloading | DownloadPhasePaused | DownloadPhaseDownloaded | DownloadPhaseLocked | DownloadPhaseError
+
+export type EngineError =
+ | { type: 'TokioError', message: string }
+ | { type: 'Device', field0: DeviceError }
+ | { type: 'Keyring', field0: KeyringError }
+ | { type: 'Storage', field0: StorageError }
+ | { type: 'Registry', field0: RegistryError }
+ | { type: 'UnableToCreateBackend' }
+ | { type: 'BackendNotFound' }
+ | { type: 'UnableToGetDownloaderProgressStream' }
+ | { type: 'ChatSession', field0: ChatSessionError }
+ | { type: 'ClassificationSession', field0: ClassificationSessionError }
+ | { type: 'TextToSpeechSession', field0: TextToSpeechSessionError }
+
+export type KeyringError =
+ | { type: 'BackendError', message: string }
+ | { type: 'Device', field0: DeviceError }
+
+export type RegistryError =
+ | { type: 'UnableToCreate', message: string }
+ | { type: 'UnableToGetModels', message: string }
+ | { type: 'UnableToAddRegistry', identifier: string }
+
+export type StorageError =
+ | { type: 'UnableToCreateDirectory', path: string }
+ | { type: 'UnableToCreateDownloadManager', message: string }
+ | { type: 'DownloadManager', message: string }
+ | { type: 'HashNotFound', identifier: string, name: string }
+ | { type: 'InvalidStateTransition', from: DownloadPhase, to: DownloadPhase }
+ | { type: 'IO', message: string }
+ | { type: 'ItemNotFound', identifier: string }
+ | { type: 'Registry', field0: RegistryError }
+ | { type: 'UnsupportedItem', identifier: string }
diff --git a/bindings/ts/src/napi/uzu.js b/bindings/ts/src/napi/uzu.js
new file mode 100644
index 000000000..6ead57beb
--- /dev/null
+++ b/bindings/ts/src/napi/uzu.js
@@ -0,0 +1,317 @@
+// Auto-generated NAPI wrapper for uzu native module
+// Currently supports only Apple Silicon (arm64) on macOS
+// Other platforms may be added in future releases
+
+const { createRequire } = require('module');
+
+const require_ = createRequire(__filename);
+
+// Check for Apple Silicon support only
+if (process.platform !== 'darwin' || process.arch !== 'arm64') {
+ throw new Error(`This package only supports Apple Silicon (arm64) on macOS. Current platform: ${process.platform}-${process.arch}`);
+}
+
+let nativeBinding = null;
+
+try {
+ nativeBinding = require_('./uzu.node');
+} catch (e) {
+ throw new Error(`Failed to load native binding: ${e.message}`);
+}
+
+// Re-export all runtime exports
+const {
+ ChatSession,
+ ChatSessionStream,
+ ChatSessionStreamChunkError,
+ ChatSessionStreamChunkReplies,
+ ClassificationSession,
+ TextToSpeechSession,
+ TextToSpeechSessionStream,
+ TextToSpeechSessionStreamChunkError,
+ TextToSpeechSessionStreamChunkPcmBatch,
+ CancelToken,
+ ChatConfig,
+ ChatContentBlockAudio,
+ ChatContentBlockBuiltinTools,
+ ChatContentBlockConversationStartDate,
+ ChatContentBlockCustom,
+ ChatContentBlockFile,
+ ChatContentBlockIdentity,
+ ChatContentBlockImage,
+ ChatContentBlockKnowledgeCutoff,
+ ChatContentBlockReasoning,
+ ChatContentBlockReasoningEffort,
+ ChatContentBlockText,
+ ChatContentBlockToolCall,
+ ChatContentBlockToolCallCandidate,
+ ChatContentBlockToolCallResult,
+ ChatContentBlockTools,
+ ChatContentBlockTranslation,
+ ChatContentBlockVideo,
+ ChatMessage,
+ ChatModelCapabilities,
+ ChatReply,
+ ChatReplyConfig,
+ ChatReplyStats,
+ ChatRoleAssistant,
+ ChatRoleCustom,
+ ChatRoleDeveloper,
+ ChatRoleSystem,
+ ChatRoleTool,
+ ChatRoleUser,
+ ChatSpeculationPresetClassification,
+ ChatSpeculationPresetGeneralChat,
+ ChatSpeculationPresetSummarization,
+ ClassificationLabel,
+ ClassificationMessage,
+ ClassificationOutput,
+ ClassificationStats,
+ ContextLengthCustom,
+ ContextLengthDefault,
+ ContextLengthMaximal,
+ Feature,
+ File,
+ GrammarJsonAny,
+ GrammarJsonSchema,
+ GrammarRegex,
+ Hash,
+ Image,
+ Metadata,
+ Model,
+ ModelAccessibilityLocal,
+ ModelAccessibilityRemote,
+ ModelBackend,
+ ModelFamily,
+ ModelProperties,
+ ModelQuantization,
+ ModelReferenceHuggingFace,
+ ModelReferenceLocal,
+ ModelReferenceMirai,
+ ModelRegistry,
+ ModelSpecializationChat,
+ ModelSpecializationClassification,
+ ModelSpecializationSpeculation,
+ ModelSpecializationTextToSpeech,
+ ModelSpecializationTranslation,
+ ModelVendor,
+ PcmBatch,
+ Repository,
+ SamplingMethodGreedy,
+ SamplingMethodStochastic,
+ SamplingPolicyCustom,
+ SamplingPolicyDefault,
+ SamplingSeedCustom,
+ SamplingSeedDefault,
+ TextToSpeechStats,
+ Token,
+ ToolCall,
+ ToolDescriptionFunction,
+ ToolFunction,
+ ToolNamespace,
+ TranslationPayloadImage,
+ TranslationPayloadText,
+ Value,
+ Device,
+ Downloader,
+ DownloaderStream,
+ DownloaderStreamUpdate,
+ DownloadPhaseDownloaded,
+ DownloadPhaseDownloading,
+ DownloadPhaseError,
+ DownloadPhaseLocked,
+ DownloadPhaseNotDownloaded,
+ DownloadPhasePaused,
+ DownloadState,
+ Engine,
+ EngineCallback,
+ EngineConfig,
+ Keyring,
+ ChatSessionState,
+ ClassificationSessionState,
+ TextToSpeechSessionState,
+ ChatContentBlockType,
+ ChatReplyFinishReason,
+ ClassificationRole,
+ HashMethod,
+ ImageFormat,
+ ImageTheme,
+ ReasoningEffort,
+ ChatMessageMetadata,
+ ClassificationOutputProbabilities,
+ ChatSessionError,
+ ChatSessionStreamChunk,
+ ClassificationSessionError,
+ TextToSpeechSessionError,
+ TextToSpeechSessionStreamChunk,
+ ChatContentBlock,
+ ChatRole,
+ ChatSpeculationPreset,
+ ContextLength,
+ Grammar,
+ ModelAccessibility,
+ ModelReference,
+ ModelSpecialization,
+ PcmBatchError,
+ SamplingMethod,
+ SamplingPolicy,
+ SamplingSeed,
+ TokenId,
+ TokenValue,
+ ToolDescription,
+ TranslationPayload,
+ DeviceError,
+ DownloadPhase,
+ EngineError,
+ KeyringError,
+ RegistryError,
+ StorageError
+} = nativeBinding;
+
+module.exports = {
+ ChatSession,
+ ChatSessionStream,
+ ChatSessionStreamChunkError,
+ ChatSessionStreamChunkReplies,
+ ClassificationSession,
+ TextToSpeechSession,
+ TextToSpeechSessionStream,
+ TextToSpeechSessionStreamChunkError,
+ TextToSpeechSessionStreamChunkPcmBatch,
+ CancelToken,
+ ChatConfig,
+ ChatContentBlockAudio,
+ ChatContentBlockBuiltinTools,
+ ChatContentBlockConversationStartDate,
+ ChatContentBlockCustom,
+ ChatContentBlockFile,
+ ChatContentBlockIdentity,
+ ChatContentBlockImage,
+ ChatContentBlockKnowledgeCutoff,
+ ChatContentBlockReasoning,
+ ChatContentBlockReasoningEffort,
+ ChatContentBlockText,
+ ChatContentBlockToolCall,
+ ChatContentBlockToolCallCandidate,
+ ChatContentBlockToolCallResult,
+ ChatContentBlockTools,
+ ChatContentBlockTranslation,
+ ChatContentBlockVideo,
+ ChatMessage,
+ ChatModelCapabilities,
+ ChatReply,
+ ChatReplyConfig,
+ ChatReplyStats,
+ ChatRoleAssistant,
+ ChatRoleCustom,
+ ChatRoleDeveloper,
+ ChatRoleSystem,
+ ChatRoleTool,
+ ChatRoleUser,
+ ChatSpeculationPresetClassification,
+ ChatSpeculationPresetGeneralChat,
+ ChatSpeculationPresetSummarization,
+ ClassificationLabel,
+ ClassificationMessage,
+ ClassificationOutput,
+ ClassificationStats,
+ ContextLengthCustom,
+ ContextLengthDefault,
+ ContextLengthMaximal,
+ Feature,
+ File,
+ GrammarJsonAny,
+ GrammarJsonSchema,
+ GrammarRegex,
+ Hash,
+ Image,
+ Metadata,
+ Model,
+ ModelAccessibilityLocal,
+ ModelAccessibilityRemote,
+ ModelBackend,
+ ModelFamily,
+ ModelProperties,
+ ModelQuantization,
+ ModelReferenceHuggingFace,
+ ModelReferenceLocal,
+ ModelReferenceMirai,
+ ModelRegistry,
+ ModelSpecializationChat,
+ ModelSpecializationClassification,
+ ModelSpecializationSpeculation,
+ ModelSpecializationTextToSpeech,
+ ModelSpecializationTranslation,
+ ModelVendor,
+ PcmBatch,
+ Repository,
+ SamplingMethodGreedy,
+ SamplingMethodStochastic,
+ SamplingPolicyCustom,
+ SamplingPolicyDefault,
+ SamplingSeedCustom,
+ SamplingSeedDefault,
+ TextToSpeechStats,
+ Token,
+ ToolCall,
+ ToolDescriptionFunction,
+ ToolFunction,
+ ToolNamespace,
+ TranslationPayloadImage,
+ TranslationPayloadText,
+ Value,
+ Device,
+ Downloader,
+ DownloaderStream,
+ DownloaderStreamUpdate,
+ DownloadPhaseDownloaded,
+ DownloadPhaseDownloading,
+ DownloadPhaseError,
+ DownloadPhaseLocked,
+ DownloadPhaseNotDownloaded,
+ DownloadPhasePaused,
+ DownloadState,
+ Engine,
+ EngineCallback,
+ EngineConfig,
+ Keyring,
+ ChatSessionState,
+ ClassificationSessionState,
+ TextToSpeechSessionState,
+ ChatContentBlockType,
+ ChatReplyFinishReason,
+ ClassificationRole,
+ HashMethod,
+ ImageFormat,
+ ImageTheme,
+ ReasoningEffort,
+ ChatMessageMetadata,
+ ClassificationOutputProbabilities,
+ ChatSessionError,
+ ChatSessionStreamChunk,
+ ClassificationSessionError,
+ TextToSpeechSessionError,
+ TextToSpeechSessionStreamChunk,
+ ChatContentBlock,
+ ChatRole,
+ ChatSpeculationPreset,
+ ContextLength,
+ Grammar,
+ ModelAccessibility,
+ ModelReference,
+ ModelSpecialization,
+ PcmBatchError,
+ SamplingMethod,
+ SamplingPolicy,
+ SamplingSeed,
+ TokenId,
+ TokenValue,
+ ToolDescription,
+ TranslationPayload,
+ DeviceError,
+ DownloadPhase,
+ EngineError,
+ KeyringError,
+ RegistryError,
+ StorageError
+};
\ No newline at end of file
diff --git a/bindings/ts/src/napi/uzu.mjs b/bindings/ts/src/napi/uzu.mjs
new file mode 100644
index 000000000..fc67c2f03
--- /dev/null
+++ b/bindings/ts/src/napi/uzu.mjs
@@ -0,0 +1,172 @@
+// Auto-generated NAPI wrapper for uzu native module
+// Currently supports only Apple Silicon (arm64) on macOS
+// Other platforms may be added in future releases
+
+import { createRequire } from 'module';
+
+const require = createRequire(import.meta.url);
+
+// Check for Apple Silicon support only
+if (process.platform !== 'darwin' || process.arch !== 'arm64') {
+ throw new Error(`This package only supports Apple Silicon (arm64) on macOS. Current platform: ${process.platform}-${process.arch}`);
+}
+
+let nativeBinding = null;
+
+try {
+ nativeBinding = require('./uzu.node');
+} catch (e) {
+ throw new Error(`Failed to load native binding: ${e.message}`);
+}
+
+// Re-export all runtime exports as named exports
+export const {
+ ChatSession,
+ ChatSessionStream,
+ ChatSessionStreamChunkError,
+ ChatSessionStreamChunkReplies,
+ ClassificationSession,
+ TextToSpeechSession,
+ TextToSpeechSessionStream,
+ TextToSpeechSessionStreamChunkError,
+ TextToSpeechSessionStreamChunkPcmBatch,
+ CancelToken,
+ ChatConfig,
+ ChatContentBlockAudio,
+ ChatContentBlockBuiltinTools,
+ ChatContentBlockConversationStartDate,
+ ChatContentBlockCustom,
+ ChatContentBlockFile,
+ ChatContentBlockIdentity,
+ ChatContentBlockImage,
+ ChatContentBlockKnowledgeCutoff,
+ ChatContentBlockReasoning,
+ ChatContentBlockReasoningEffort,
+ ChatContentBlockText,
+ ChatContentBlockToolCall,
+ ChatContentBlockToolCallCandidate,
+ ChatContentBlockToolCallResult,
+ ChatContentBlockTools,
+ ChatContentBlockTranslation,
+ ChatContentBlockVideo,
+ ChatMessage,
+ ChatModelCapabilities,
+ ChatReply,
+ ChatReplyConfig,
+ ChatReplyStats,
+ ChatRoleAssistant,
+ ChatRoleCustom,
+ ChatRoleDeveloper,
+ ChatRoleSystem,
+ ChatRoleTool,
+ ChatRoleUser,
+ ChatSpeculationPresetClassification,
+ ChatSpeculationPresetGeneralChat,
+ ChatSpeculationPresetSummarization,
+ ClassificationLabel,
+ ClassificationMessage,
+ ClassificationOutput,
+ ClassificationStats,
+ ContextLengthCustom,
+ ContextLengthDefault,
+ ContextLengthMaximal,
+ Feature,
+ File,
+ GrammarJsonAny,
+ GrammarJsonSchema,
+ GrammarRegex,
+ Hash,
+ Image,
+ Metadata,
+ Model,
+ ModelAccessibilityLocal,
+ ModelAccessibilityRemote,
+ ModelBackend,
+ ModelFamily,
+ ModelProperties,
+ ModelQuantization,
+ ModelReferenceHuggingFace,
+ ModelReferenceLocal,
+ ModelReferenceMirai,
+ ModelRegistry,
+ ModelSpecializationChat,
+ ModelSpecializationClassification,
+ ModelSpecializationSpeculation,
+ ModelSpecializationTextToSpeech,
+ ModelSpecializationTranslation,
+ ModelVendor,
+ PcmBatch,
+ Repository,
+ SamplingMethodGreedy,
+ SamplingMethodStochastic,
+ SamplingPolicyCustom,
+ SamplingPolicyDefault,
+ SamplingSeedCustom,
+ SamplingSeedDefault,
+ TextToSpeechStats,
+ Token,
+ ToolCall,
+ ToolDescriptionFunction,
+ ToolFunction,
+ ToolNamespace,
+ TranslationPayloadImage,
+ TranslationPayloadText,
+ Value,
+ Device,
+ Downloader,
+ DownloaderStream,
+ DownloaderStreamUpdate,
+ DownloadPhaseDownloaded,
+ DownloadPhaseDownloading,
+ DownloadPhaseError,
+ DownloadPhaseLocked,
+ DownloadPhaseNotDownloaded,
+ DownloadPhasePaused,
+ DownloadState,
+ Engine,
+ EngineCallback,
+ EngineConfig,
+ Keyring,
+ ChatSessionState,
+ ClassificationSessionState,
+ TextToSpeechSessionState,
+ ChatContentBlockType,
+ ChatReplyFinishReason,
+ ClassificationRole,
+ HashMethod,
+ ImageFormat,
+ ImageTheme,
+ ReasoningEffort,
+ ChatMessageMetadata,
+ ClassificationOutputProbabilities,
+ ChatSessionError,
+ ChatSessionStreamChunk,
+ ClassificationSessionError,
+ TextToSpeechSessionError,
+ TextToSpeechSessionStreamChunk,
+ ChatContentBlock,
+ ChatRole,
+ ChatSpeculationPreset,
+ ContextLength,
+ Grammar,
+ ModelAccessibility,
+ ModelReference,
+ ModelSpecialization,
+ PcmBatchError,
+ SamplingMethod,
+ SamplingPolicy,
+ SamplingSeed,
+ TokenId,
+ TokenValue,
+ ToolDescription,
+ TranslationPayload,
+ DeviceError,
+ DownloadPhase,
+ EngineError,
+ KeyringError,
+ RegistryError,
+ StorageError
+} = nativeBinding;
+
+// Also provide default export
+export default nativeBinding;
\ No newline at end of file
diff --git a/crates/bindings/Cargo.toml b/crates/bindings/Cargo.toml
index ea68a8d42..1409b2a86 100644
--- a/crates/bindings/Cargo.toml
+++ b/crates/bindings/Cargo.toml
@@ -11,6 +11,7 @@ repository.workspace = true
proc-macro = true
[dependencies]
+heck.workspace = true
proc-macro2.workspace = true
quote.workspace = true
syn.workspace = true
diff --git a/crates/bindings/src/lib.rs b/crates/bindings/src/lib.rs
index 09f6a9495..0352b8bd4 100644
--- a/crates/bindings/src/lib.rs
+++ b/crates/bindings/src/lib.rs
@@ -202,6 +202,17 @@ pub fn export(
_ => true,
});
+ let mut factories: Vec<syn::ImplItemFn> = Vec::new();
+ item_implementation.items.retain(|item| match item {
+ ImplItem::Fn(method) if method_has_factory(method) => {
+ let mut stripped = method.clone();
+ strip_bindings_export_attrs(&mut stripped.attrs);
+ factories.push(stripped);
+ false
+ },
+ _ => true,
+ });
+
let mut stream_next_methods: Vec<syn::ImplItemFn> = Vec::new();
for item in &item_implementation.items {
if let ImplItem::Fn(method) = item {
@@ -232,8 +243,32 @@ pub fn export(
let stream_expansions: Vec<proc_macro2::TokenStream> =
stream_next_methods.iter().map(|method| napi::stream_next_generator(&self_type, method)).collect();
+ let factory_expansions: Vec<proc_macro2::TokenStream> = factories
+ .iter()
+ .map(|method| {
+ let plain_impl = quote! {
+ impl #self_type {
+ #method
+ }
+ };
+ let napi_expansion = napi::factory(&self_type, method);
+ let uniffi_expansion = uniffi::factory(&self_type, method);
+ let pyo3_expansion = pyo3::factory(&self_type, method);
+ quote! {
+ #plain_impl
+ #napi_expansion
+ #uniffi_expansion
+ #pyo3_expansion
+ }
+ })
+ .collect();
+
+ let has_async_methods = item_implementation
+ .items
+ .iter()
+ .any(|item| matches!(item, ImplItem::Fn(method) if method.sig.asyncness.is_some()));
let napi = napi::attributes(&kind);
- let uniffi = uniffi::attributes(&kind);
+ let uniffi = uniffi::implementation_attribute(has_async_methods);
let pyo3 = pyo3::attributes(&kind);
let wasm = wasm::attributes(&kind);
quote! {
@@ -244,6 +279,7 @@ pub fn export(
#item_implementation
#( #callback_expansions )*
#( #stream_expansions )*
+ #( #factory_expansions )*
}
.into()
},
@@ -337,6 +373,22 @@ fn method_flavor(attribute: &Attribute) -> Option<MethodFlavor> {
}
}
+fn method_has_factory(method: &syn::ImplItemFn) -> bool {
+ method.attrs.iter().any(|attribute| {
+ if !is_exportable_attribute(attribute) {
+ return false;
+ }
+ let Ok(arguments): syn::Result<ExportArguments> = attribute.parse_args() else {
+ return false;
+ };
+ matches!(arguments.kind, BindingKind::Factory)
+ })
+}
+
+fn strip_bindings_export_attrs(attrs: &mut Vec<Attribute>) {
+ attrs.retain(|attribute| !is_exportable_attribute(attribute));
+}
+
fn method_has_stream_next(method: &syn::ImplItemFn) -> bool {
method.attrs.iter().any(|attribute| {
if !is_exportable_attribute(attribute) {
diff --git a/crates/bindings/src/napi.rs b/crates/bindings/src/napi.rs
index 72979e3e6..e8b455a33 100644
--- a/crates/bindings/src/napi.rs
+++ b/crates/bindings/src/napi.rs
@@ -384,19 +384,73 @@ fn extract_option_inner_type(output: &syn::ReturnType) -> Option<syn::Type> {
None
}
+pub fn factory(
+ self_type: &syn::Type,
+ method: &syn::ImplItemFn,
+) -> proc_macro2::TokenStream {
+ let method_ident = &method.sig.ident;
+ let method_name = method_ident.to_string();
+ let wrapper_ident = format_ident!("{}_bindings_napi", method_ident);
+ let inputs = &method.sig.inputs;
+ let output = &method.sig.output;
+ let asyncness = &method.sig.asyncness;
+ let arg_idents = factory_arg_idents(inputs);
+ let forward_await = asyncness.as_ref().map(|_| quote! { .await });
+
+ quote! {
+ #[cfg(feature = "bindings-napi")]
+ #[napi_derive::napi]
+ impl #self_type {
+ #[napi(js_name = #method_name)]
+ pub #asyncness fn #wrapper_ident( #inputs ) #output {
+ <#self_type>::#method_ident( #( #arg_idents ),* )#forward_await
+ }
+ }
+ }
+}
+
+fn factory_arg_idents(inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::Token![,]>) -> Vec<syn::Ident> {
+ inputs
+ .iter()
+ .filter_map(|arg| match arg {
+ syn::FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {
+ syn::Pat::Ident(pat_ident) => Some(pat_ident.ident.clone()),
+ _ => None,
+ },
+ syn::FnArg::Receiver(_) => None,
+ })
+ .collect()
+}
+
pub fn factory_with_callback(
self_type: &syn::Type,
method: &syn::ImplItemFn,
) -> proc_macro2::TokenStream {
let method_ident = &method.sig.ident;
let body = &method.block;
+ let callback_inputs = match extract_callback_inputs(method) {
+ Some(inputs) => inputs,
+ None => {
+ return syn::Error::new_spanned(
+ &method.sig,
+ "bindings::export(FactoryWithCallback) requires a parameter of type \
+ `Box<dyn Fn(..) + Send + Sync>` (return type must be `()`)",
+ )
+ .to_compile_error();
+ },
+ };
+ let synthetic_idents: Vec<syn::Ident> =
+ (0..callback_inputs.len()).map(|index| format_ident!("arg{index}")).collect();
+ let napi_args_type = napi_args_tuple(&callback_inputs);
+ let napi_call_value = napi_call_tuple(&synthetic_idents);
+
quote! {
#[cfg(feature = "bindings-napi")]
#[napi_derive::napi]
impl #self_type {
#[napi(factory)]
pub fn #method_ident(
- callback: napi::bindgen_prelude::Function<'static, (), ()>,
+ callback: napi::bindgen_prelude::Function<'static, #napi_args_type, ()>,
) -> napi::Result<Self> {
let threadsafe_function = callback
.build_threadsafe_function()
@@ -404,18 +458,103 @@ pub fn factory_with_callback(
.weak::<true>()
.build()
.map_err(|error| napi::Error::from_reason(error.to_string()))?;
- let callback: Box<dyn Fn() + Send + Sync> = Box::new(move || {
- let _ = threadsafe_function.call(
- (),
- napi::threadsafe_function::ThreadsafeFunctionCallMode::NonBlocking,
- );
- });
+ let callback: Box<dyn Fn( #( #callback_inputs ),* ) + Send + Sync> =
+ Box::new(move | #( #synthetic_idents: #callback_inputs ),* | {
+ let _ = threadsafe_function.call(
+ #napi_call_value,
+ napi::threadsafe_function::ThreadsafeFunctionCallMode::NonBlocking,
+ );
+ });
Ok(#body)
}
}
}
}
+fn napi_args_tuple(inputs: &[syn::Type]) -> proc_macro2::TokenStream {
+ match inputs.len() {
+ 0 => quote! { () },
+ 1 => {
+ let single = &inputs[0];
+ quote! { #single }
+ },
+ _ => quote! { ( #( #inputs ),* ) },
+ }
+}
+
+fn napi_call_tuple(idents: &[syn::Ident]) -> proc_macro2::TokenStream {
+ match idents.len() {
+ 0 => quote! { () },
+ 1 => {
+ let single = &idents[0];
+ quote! { #single }
+ },
+ _ => quote! { ( #( #idents ),* ) },
+ }
+}
+
+pub(crate) fn extract_callback_inputs(method: &syn::ImplItemFn) -> Option<Vec<syn::Type>> {
+ for input in &method.sig.inputs {
+ let syn::FnArg::Typed(pat_type) = input else {
+ continue;
+ };
+ if let Some(inputs) = extract_void_fn_inputs(&pat_type.ty) {
+ return Some(inputs);
+ }
+ }
+ None
+}
+
+fn extract_void_fn_inputs(ty: &syn::Type) -> Option<Vec<syn::Type>> {
+ let inner = extract_box_inner(ty)?;
+ let syn::Type::TraitObject(trait_object) = inner else {
+ return None;
+ };
+ for bound in &trait_object.bounds {
+ let syn::TypeParamBound::Trait(trait_bound) = bound else {
+ continue;
+ };
+ let segment = trait_bound.path.segments.last()?;
+ if segment.ident != "Fn" && segment.ident != "FnMut" && segment.ident != "FnOnce" {
+ continue;
+ }
+ let syn::PathArguments::Parenthesized(paren) = &segment.arguments else {
+ continue;
+ };
+ let returns_unit = match &paren.output {
+ syn::ReturnType::Default => true,
+ syn::ReturnType::Type(_, ty) => match ty.as_ref() {
+ syn::Type::Tuple(tuple) => tuple.elems.is_empty(),
+ _ => false,
+ },
+ };
+ if !returns_unit {
+ return None;
+ }
+ return Some(paren.inputs.iter().cloned().collect());
+ }
+ None
+}
+
+fn extract_box_inner(ty: &syn::Type) -> Option<&syn::Type> {
+ let syn::Type::Path(type_path) = ty else {
+ return None;
+ };
+ let segment = type_path.path.segments.last()?;
+ if segment.ident != "Box" {
+ return None;
+ }
+ let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
+ return None;
+ };
+ for argument in &args.args {
+ if let syn::GenericArgument::Type(inner) = argument {
+ return Some(inner);
+ }
+ }
+ None
+}
+
pub fn error_implementations(type_name: &Ident) -> proc_macro2::TokenStream {
quote! {
#[cfg(feature = "bindings-napi")]
diff --git a/crates/bindings/src/pyo3.rs b/crates/bindings/src/pyo3.rs
index 516b7fb9e..fd43a3563 100644
--- a/crates/bindings/src/pyo3.rs
+++ b/crates/bindings/src/pyo3.rs
@@ -33,6 +33,45 @@ pub fn method_attribute(flavor: &MethodFlavor) -> Option<Attribute> {
}
}
+pub fn factory(
+ self_type: &syn::Type,
+ method: &syn::ImplItemFn,
+) -> proc_macro2::TokenStream {
+ let method_ident = &method.sig.ident;
+ let method_name = method_ident.to_string();
+ let wrapper_ident = quote::format_ident!("{}_bindings_pyo3", method_ident);
+ let inputs = &method.sig.inputs;
+ let output = &method.sig.output;
+ let asyncness = &method.sig.asyncness;
+ let arg_idents = factory_arg_idents(inputs);
+ let forward_await = asyncness.as_ref().map(|_| quote! { .await });
+
+ quote! {
+ #[cfg(feature = "bindings-pyo3")]
+ #[pyo3::pymethods]
+ impl #self_type {
+ #[staticmethod]
+ #[pyo3(name = #method_name)]
+ pub #asyncness fn #wrapper_ident( #inputs ) #output {
+ <#self_type>::#method_ident( #( #arg_idents ),* )#forward_await
+ }
+ }
+ }
+}
+
+fn factory_arg_idents(inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::Token![,]>) -> Vec<syn::Ident> {
+ inputs
+ .iter()
+ .filter_map(|arg| match arg {
+ syn::FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {
+ syn::Pat::Ident(pat_ident) => Some(pat_ident.ident.clone()),
+ _ => None,
+ },
+ syn::FnArg::Receiver(_) => None,
+ })
+ .collect()
+}
+
pub fn error_implementations(type_name: &Ident) -> proc_macro2::TokenStream {
quote! {
#[cfg(feature = "bindings-pyo3")]
diff --git a/crates/bindings/src/uniffi.rs b/crates/bindings/src/uniffi.rs
index a8ba3ddf8..c87e3ee97 100644
--- a/crates/bindings/src/uniffi.rs
+++ b/crates/bindings/src/uniffi.rs
@@ -17,22 +17,111 @@ pub fn attributes(kind: &BindingKind) -> proc_macro2::TokenStream {
BindingKind::ClassCloneable => quote! {
#[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Record))]
},
- BindingKind::Implementation => quote! {
- #[cfg_attr(feature = "bindings-uniffi", uniffi::export)]
- },
+ BindingKind::Implementation => quote! {},
_ => quote! {},
}
}
+pub fn implementation_attribute(has_async: bool) -> proc_macro2::TokenStream {
+ if has_async {
+ quote! {
+ #[cfg_attr(feature = "bindings-uniffi", uniffi::export(async_runtime = "tokio"))]
+ }
+ } else {
+ quote! {
+ #[cfg_attr(feature = "bindings-uniffi", uniffi::export)]
+ }
+ }
+}
+
pub fn method_attribute(flavor: &MethodFlavor) -> Option<Attribute> {
match flavor {
- MethodFlavor::Plain | MethodFlavor::Getter | MethodFlavor::Setter => None,
- MethodFlavor::Constructor | MethodFlavor::Factory => Some(parse_quote! {
+ MethodFlavor::Plain | MethodFlavor::Getter | MethodFlavor::Setter | MethodFlavor::Factory => None,
+ MethodFlavor::Constructor => Some(parse_quote! {
#[cfg_attr(feature = "bindings-uniffi", uniffi::constructor)]
}),
}
}
+pub fn factory(
+ self_type: &syn::Type,
+ method: &syn::ImplItemFn,
+) -> proc_macro2::TokenStream {
+ let method_ident = &method.sig.ident;
+ let self_ident = match self_type_ident(self_type) {
+ Some(ident) => ident,
+ None => {
+ return syn::Error::new_spanned(self_type, "bindings::export(Factory) requires a named self type")
+ .to_compile_error();
+ },
+ };
+ let fn_name = format_ident!("{}_{}", heck::AsSnakeCase(self_ident.to_string()).to_string(), method_ident,);
+ let inputs = &method.sig.inputs;
+ let output = replace_self_in_return(&method.sig.output, self_type);
+ let asyncness = &method.sig.asyncness;
+ let arg_idents = factory_arg_idents(inputs);
+ let forward_await = asyncness.as_ref().map(|_| quote! { .await });
+ let export_attr = if asyncness.is_some() {
+ quote! { #[uniffi::export(async_runtime = "tokio")] }
+ } else {
+ quote! { #[uniffi::export] }
+ };
+
+ quote! {
+ #[cfg(feature = "bindings-uniffi")]
+ #export_attr
+ pub #asyncness fn #fn_name( #inputs ) #output {
+ <#self_type>::#method_ident( #( #arg_idents ),* )#forward_await
+ }
+ }
+}
+
+fn replace_self_in_return(
+ output: &syn::ReturnType,
+ self_type: &syn::Type,
+) -> syn::ReturnType {
+ use syn::fold::Fold;
+ let mut folder = SelfReplacer {
+ self_type: self_type.clone(),
+ };
+ folder.fold_return_type(output.clone())
+}
+
+struct SelfReplacer {
+ self_type: syn::Type,
+}
+
+impl syn::fold::Fold for SelfReplacer {
+ fn fold_type(
+ &mut self,
+ ty: syn::Type,
+ ) -> syn::Type {
+ if let syn::Type::Path(path) = &ty {
+ if path.qself.is_none()
+ && path.path.segments.len() == 1
+ && path.path.segments[0].ident == "Self"
+ && path.path.segments[0].arguments.is_empty()
+ {
+ return self.self_type.clone();
+ }
+ }
+ syn::fold::fold_type(self, ty)
+ }
+}
+
+fn factory_arg_idents(inputs: &syn::punctuated::Punctuated<syn::FnArg, syn::Token![,]>) -> Vec<syn::Ident> {
+ inputs
+ .iter()
+ .filter_map(|arg| match arg {
+ syn::FnArg::Typed(pat_type) => match pat_type.pat.as_ref() {
+ syn::Pat::Ident(pat_ident) => Some(pat_ident.ident.clone()),
+ _ => None,
+ },
+ syn::FnArg::Receiver(_) => None,
+ })
+ .collect()
+}
+
pub fn error_attribute() -> proc_macro2::TokenStream {
quote! {
#[cfg_attr(feature = "bindings-uniffi", derive(uniffi::Error))]
@@ -62,12 +151,24 @@ pub fn factory_with_callback(
},
};
let handler_ident = format_ident!("{}Handler", self_ident);
+ let callback_inputs = match crate::napi::extract_callback_inputs(method) {
+ Some(inputs) => inputs,
+ None => {
+ return syn::Error::new_spanned(
+ &method.sig,
+ "bindings::export(FactoryWithCallback) requires a parameter of type \
+ `Box<dyn Fn(..) + Send + Sync>` (return type must be `()`)",
+ )
+ .to_compile_error();
+ },
+ };
+ let arg_idents: Vec<syn::Ident> = (0..callback_inputs.len()).map(|index| format_ident!("arg{index}")).collect();
quote! {
#[cfg(feature = "bindings-uniffi")]
#[uniffi::export(callback_interface)]
pub trait #handler_ident: Send + Sync {
- fn on_event(&self);
+ fn on_event(&self, #( #arg_idents: #callback_inputs ),*);
}
#[cfg(feature = "bindings-uniffi")]
@@ -76,7 +177,10 @@ pub fn factory_with_callback(
#[uniffi::constructor]
pub fn #method_ident(handler: Box<dyn #handler_ident>) -> std::sync::Arc<Self> {
let handler: std::sync::Arc<dyn #handler_ident> = std::sync::Arc::from(handler);
- let callback: Box<dyn Fn() + Send + Sync> = Box::new(move || handler.on_event());
+ let callback: Box<dyn Fn( #( #callback_inputs ),* ) + Send + Sync> =
+ Box::new(move | #( #arg_idents: #callback_inputs ),* | {
+ handler.on_event( #( #arg_idents ),* );
+ });
std::sync::Arc::new(#body)
}
}
diff --git a/crates/cli-release/Cargo.toml b/crates/cli-release/Cargo.toml
index 177c0c5b7..523dbe17f 100644
--- a/crates/cli-release/Cargo.toml
+++ b/crates/cli-release/Cargo.toml
@@ -18,3 +18,4 @@ ignore.workspace = true
serde_json.workspace = true
regex.workspace = true
heck.workspace = true
+syn.workspace = true
diff --git a/crates/cli-release/src/handlers/generate_swift_extensions.rs b/crates/cli-release/src/handlers/generate_swift_extensions.rs
new file mode 100644
index 000000000..edbd07abd
--- /dev/null
+++ b/crates/cli-release/src/handlers/generate_swift_extensions.rs
@@ -0,0 +1,573 @@
+use std::{fs, path::Path};
+
+use heck::{AsLowerCamelCase, AsSnakeCase};
+use ignore::WalkBuilder;
+
+use crate::types::{Environment, Error};
+
+pub fn generate_swift_extensions(environment: &Environment) -> Result<(), Error> {
+ let (factories, callback_factories, stream_bridges) = collect_all(&environment.crates_path())?;
+ let swift_source = render_extensions_file(&factories, &callback_factories, &stream_bridges);
+
+ let destination =
+ environment.bindings().swift_path().join("Sources").join("Uzu").join("Generated").join("Extensions.swift");
+
+ if let Some(parent) = destination.parent() {
+ fs::create_dir_all(parent).map_err(|_| Error::UnableToPrepareBindingsSwift)?;
+ }
+ fs::write(&destination, swift_source).map_err(|_| Error::UnableToPrepareBindingsSwift)?;
+
+ Ok(())
+}
+
+#[derive(Debug, Clone)]
+struct Factory {
+ type_name: String,
+ method_name: String,
+ is_async: bool,
+ throws: bool,
+ optional: bool,
+ arguments: Vec<FactoryArgument>,
+}
+
+#[derive(Debug, Clone)]
+struct FactoryArgument {
+ name: String,
+ swift_type: String,
+}
+
+#[derive(Debug, Clone)]
+struct CallbackFactory {
+ type_name: String,
+ method_name: String,
+ callback_arg_types: Vec<String>,
+}
+
+#[derive(Debug, Clone)]
+struct StreamBridge {
+ type_name: String,
+ next_method_name: String,
+ item_swift_type: String,
+ cancel_getter_name: Option<String>,
+}
+
+fn collect_all(crates_path: &Path) -> Result<(Vec<Factory>, Vec<CallbackFactory>, Vec<StreamBridge>), Error> {
+ let mut factories: Vec<Factory> = Vec::new();
+ let mut callback_factories: Vec<CallbackFactory> = Vec::new();
+ let mut stream_bridges: Vec<StreamBridge> = Vec::new();
+
+ for entry in WalkBuilder::new(crates_path).build().flatten() {
+ let path = entry.path();
+ if path.extension().and_then(|ext| ext.to_str()) != Some("rs") {
+ continue;
+ }
+ let Ok(source) = fs::read_to_string(path) else {
+ continue;
+ };
+ let Ok(file) = syn::parse_file(&source) else {
+ continue;
+ };
+ collect_from_items(&file.items, &mut factories, &mut callback_factories, &mut stream_bridges);
+ }
+
+ factories.sort_by(|lhs, rhs| lhs.type_name.cmp(&rhs.type_name).then_with(|| lhs.method_name.cmp(&rhs.method_name)));
+ factories.dedup_by(|lhs, rhs| lhs.type_name == rhs.type_name && lhs.method_name == rhs.method_name);
+ callback_factories
+ .sort_by(|lhs, rhs| lhs.type_name.cmp(&rhs.type_name).then_with(|| lhs.method_name.cmp(&rhs.method_name)));
+ callback_factories.dedup_by(|lhs, rhs| lhs.type_name == rhs.type_name && lhs.method_name == rhs.method_name);
+ stream_bridges.sort_by(|lhs, rhs| lhs.type_name.cmp(&rhs.type_name));
+ stream_bridges.dedup_by(|lhs, rhs| lhs.type_name == rhs.type_name);
+
+ Ok((factories, callback_factories, stream_bridges))
+}
+
+fn collect_from_items(
+ items: &[syn::Item],
+ factories: &mut Vec<Factory>,
+ callback_factories: &mut Vec<CallbackFactory>,
+ stream_bridges: &mut Vec<StreamBridge>,
+) {
+ for item in items {
+ match item {
+ syn::Item::Impl(item_impl) => collect_from_impl(item_impl, factories, callback_factories, stream_bridges),
+ syn::Item::Mod(item_mod) => {
+ if let Some((_, nested)) = &item_mod.content {
+ collect_from_items(nested, factories, callback_factories, stream_bridges);
+ }
+ },
+ _ => {},
+ }
+ }
+}
+
+fn collect_from_impl(
+ item_impl: &syn::ItemImpl,
+ factories: &mut Vec<Factory>,
+ callback_factories: &mut Vec<CallbackFactory>,
+ stream_bridges: &mut Vec<StreamBridge>,
+) {
+ if !impl_is_bindings_implementation(item_impl) {
+ return;
+ }
+ let Some(type_name) = impl_self_type_ident(item_impl) else {
+ return;
+ };
+
+ let cancel_getter_name = item_impl.items.iter().find_map(|impl_item| {
+ let syn::ImplItem::Fn(method) = impl_item else {
+ return None;
+ };
+ if !is_cancel_token_getter(method) {
+ return None;
+ }
+ Some(method.sig.ident.to_string())
+ });
+
+ for impl_item in &item_impl.items {
+ let syn::ImplItem::Fn(method) = impl_item else {
+ continue;
+ };
+ if method_is_stream_next(method) {
+ if let Some(bridge) = extract_stream_bridge(method, &type_name, cancel_getter_name.clone()) {
+ stream_bridges.push(bridge);
+ }
+ continue;
+ }
+ if method_has_receiver(method) {
+ continue;
+ }
+ if method_is_factory_with_callback(method) {
+ let callback_arg_types = extract_callback_arg_swift_types(method, &type_name).unwrap_or_default();
+ callback_factories.push(CallbackFactory {
+ type_name: type_name.clone(),
+ method_name: method.sig.ident.to_string(),
+ callback_arg_types,
+ });
+ continue;
+ }
+ if !method_is_factory(method) {
+ continue;
+ }
+ let Some(factory) = extract_factory(method, &type_name) else {
+ continue;
+ };
+ factories.push(factory);
+ }
+}
+
+fn method_is_stream_next(method: &syn::ImplItemFn) -> bool {
+ method.attrs.iter().any(|attribute| is_bindings_export_with(attribute, "StreamNext"))
+}
+
+fn extract_stream_bridge(
+ method: &syn::ImplItemFn,
+ type_name: &str,
+ cancel_getter_name: Option<String>,
+) -> Option<StreamBridge> {
+ let syn::ReturnType::Type(_, return_type) = &method.sig.output else {
+ return None;
+ };
+ let inner = path_generic(return_type.as_ref(), "Option")?;
+ let swift_type = rust_type_to_swift(inner, type_name)?;
+ Some(StreamBridge {
+ type_name: type_name.to_string(),
+ next_method_name: method.sig.ident.to_string(),
+ item_swift_type: swift_type,
+ cancel_getter_name,
+ })
+}
+
+fn is_cancel_token_getter(method: &syn::ImplItemFn) -> bool {
+ let has_getter_attr = method.attrs.iter().any(|attribute| is_bindings_export_with(attribute, "Getter"));
+ if !has_getter_attr {
+ return false;
+ }
+ let syn::ReturnType::Type(_, return_type) = &method.sig.output else {
+ return false;
+ };
+ let syn::Type::Path(type_path) = return_type.as_ref() else {
+ return false;
+ };
+ type_path.path.segments.last().map(|segment| segment.ident == "CancelToken").unwrap_or(false)
+}
+
+fn method_is_factory_with_callback(method: &syn::ImplItemFn) -> bool {
+ method.attrs.iter().any(|attribute| is_bindings_export_with(attribute, "FactoryWithCallback"))
+}
+
+fn extract_callback_arg_swift_types(
+ method: &syn::ImplItemFn,
+ self_type_name: &str,
+) -> Option<Vec<String>> {
+ for input in &method.sig.inputs {
+ let syn::FnArg::Typed(pat_type) = input else {
+ continue;
+ };
+ let Some(inputs) = extract_box_fn_inputs(&pat_type.ty) else {
+ continue;
+ };
+ let swift_types: Vec<String> = inputs
+ .iter()
+ .map(|ty| rust_type_to_swift(ty, self_type_name).unwrap_or_else(|| "Any".to_string()))
+ .collect();
+ return Some(swift_types);
+ }
+ None
+}
+
+fn extract_box_fn_inputs(ty: &syn::Type) -> Option<Vec<syn::Type>> {
+ let inner = path_generic(ty, "Box")?;
+ let syn::Type::TraitObject(trait_object) = inner else {
+ return None;
+ };
+ for bound in &trait_object.bounds {
+ let syn::TypeParamBound::Trait(trait_bound) = bound else {
+ continue;
+ };
+ let segment = trait_bound.path.segments.last()?;
+ if segment.ident != "Fn" && segment.ident != "FnMut" && segment.ident != "FnOnce" {
+ continue;
+ }
+ let syn::PathArguments::Parenthesized(paren) = &segment.arguments else {
+ continue;
+ };
+ return Some(paren.inputs.iter().cloned().collect());
+ }
+ None
+}
+
+fn extract_factory(
+ method: &syn::ImplItemFn,
+ type_name: &str,
+) -> Option<Factory> {
+ let (throws, optional, is_self_return) = classify_return(&method.sig.output, type_name)?;
+ if !is_self_return {
+ return None;
+ }
+
+ let mut arguments = Vec::with_capacity(method.sig.inputs.len());
+ for input in &method.sig.inputs {
+ let syn::FnArg::Typed(pat_type) = input else {
+ return None;
+ };
+ let syn::Pat::Ident(pat_ident) = pat_type.pat.as_ref() else {
+ return None;
+ };
+ let swift_type = rust_type_to_swift(&pat_type.ty, type_name)?;
+ arguments.push(FactoryArgument {
+ name: pat_ident.ident.to_string(),
+ swift_type,
+ });
+ }
+
+ Some(Factory {
+ type_name: type_name.to_string(),
+ method_name: method.sig.ident.to_string(),
+ is_async: method.sig.asyncness.is_some(),
+ throws,
+ optional,
+ arguments,
+ })
+}
+
+fn classify_return(
+ output: &syn::ReturnType,
+ self_type_name: &str,
+) -> Option<(bool, bool, bool)> {
+ let syn::ReturnType::Type(_, return_type) = output else {
+ return None;
+ };
+ let mut current = return_type.as_ref();
+ let mut throws = false;
+ let mut optional = false;
+
+ if let Some(inner) = path_generic(current, "Result") {
+ throws = true;
+ current = inner;
+ }
+ if let Some(inner) = path_generic(current, "Option") {
+ optional = true;
+ current = inner;
+ }
+
+ let syn::Type::Path(type_path) = current else {
+ return None;
+ };
+ let segment = type_path.path.segments.last()?;
+ let is_self_return = segment.ident == "Self" || segment.ident == self_type_name;
+ if !is_self_return {
+ return None;
+ }
+ Some((throws, optional, true))
+}
+
+fn path_generic<'t>(
+ ty: &'t syn::Type,
+ expected: &str,
+) -> Option<&'t syn::Type> {
+ let syn::Type::Path(type_path) = ty else {
+ return None;
+ };
+ let segment = type_path.path.segments.last()?;
+ if segment.ident != expected {
+ return None;
+ }
+ let syn::PathArguments::AngleBracketed(args) = &segment.arguments else {
+ return None;
+ };
+ for argument in &args.args {
+ if let syn::GenericArgument::Type(inner) = argument {
+ return Some(inner);
+ }
+ }
+ None
+}
+
+fn rust_type_to_swift(
+ ty: &syn::Type,
+ self_type_name: &str,
+) -> Option<String> {
+ if let Some(inner) = path_generic(ty, "Option") {
+ let inner_swift = rust_type_to_swift(inner, self_type_name)?;
+ return Some(format!("{}?", inner_swift));
+ }
+ if let Some(inner) = path_generic(ty, "Vec") {
+ let inner_swift = rust_type_to_swift(inner, self_type_name)?;
+ return Some(format!("[{}]", inner_swift));
+ }
+ let syn::Type::Path(type_path) = ty else {
+ return None;
+ };
+ let segment = type_path.path.segments.last()?;
+ let name = segment.ident.to_string();
+ Some(match name.as_str() {
+ "Self" => self_type_name.to_string(),
+ "String" => "String".to_string(),
+ "bool" => "Bool".to_string(),
+ "i8" => "Int8".to_string(),
+ "i16" => "Int16".to_string(),
+ "i32" => "Int32".to_string(),
+ "i64" => "Int64".to_string(),
+ "u8" => "UInt8".to_string(),
+ "u16" => "UInt16".to_string(),
+ "u32" => "UInt32".to_string(),
+ "u64" => "UInt64".to_string(),
+ "f32" => "Float".to_string(),
+ "f64" => "Double".to_string(),
+ _ => name,
+ })
+}
+
+fn impl_is_bindings_implementation(item_impl: &syn::ItemImpl) -> bool {
+ item_impl.attrs.iter().any(|attribute| is_bindings_export_with(attribute, "Implementation"))
+}
+
+fn impl_self_type_ident(item_impl: &syn::ItemImpl) -> Option<String> {
+ let syn::Type::Path(type_path) = item_impl.self_ty.as_ref() else {
+ return None;
+ };
+ let segment = type_path.path.segments.last()?;
+ Some(segment.ident.to_string())
+}
+
+fn method_is_factory(method: &syn::ImplItemFn) -> bool {
+ method.attrs.iter().any(|attribute| is_bindings_export_with(attribute, "Factory"))
+}
+
+fn method_has_receiver(method: &syn::ImplItemFn) -> bool {
+ method.sig.inputs.iter().any(|arg| matches!(arg, syn::FnArg::Receiver(_)))
+}
+
+fn is_bindings_export_with(
+ attribute: &syn::Attribute,
+ kind: &str,
+) -> bool {
+ let path = attribute.path();
+ let segments: Vec<String> = path.segments.iter().map(|segment| segment.ident.to_string()).collect();
+ let matches_path = segments == ["bindings", "export"] || segments == ["export"];
+ if !matches_path {
+ return false;
+ }
+ attribute.parse_args::<syn::Ident>().map(|ident| ident == kind).unwrap_or(false)
+}
+
+fn render_extensions_file(
+ factories: &[Factory],
+ callback_factories: &[CallbackFactory],
+ stream_bridges: &[StreamBridge],
+) -> String {
+ let mut output = String::new();
+ output.push_str("// Auto-generated by cli-release — do not edit.\n\n");
+ for factory in factories {
+ output.push_str(&render_factory(factory));
+ output.push('\n');
+ }
+ for callback_factory in callback_factories {
+ output.push_str(&render_callback_factory(callback_factory));
+ output.push('\n');
+ }
+ for stream_bridge in stream_bridges {
+ output.push_str(&render_stream_bridge(stream_bridge));
+ output.push('\n');
+ }
+ output
+}
+
+fn render_stream_bridge(bridge: &StreamBridge) -> String {
+ let swift_next = AsLowerCamelCase(&bridge.next_method_name).to_string();
+ let type_name = &bridge.type_name;
+ let item_type = &bridge.item_swift_type;
+ let (capture, cancel_hook) = match &bridge.cancel_getter_name {
+ Some(getter) => {
+ let swift_getter = AsLowerCamelCase(getter).to_string();
+ ("[weak self] ", format!("\n self?.{swift_getter}().cancel()"))
+ },
+ None => ("", String::new()),
+ };
+ format!(
+ r#"extension {type_name} {{
+ public func iterator() -> AsyncThrowingStream<{item_type}, Swift.Error> {{
+ AsyncThrowingStream<{item_type}, Swift.Error> {{ continuation in
+ let task = Task {{
+ while !Task.isCancelled {{
+ let item = await self.{swift_next}()
+ guard let item else {{
+ continuation.finish()
+ break
+ }}
+ continuation.yield(item)
+ }}
+ }}
+ continuation.onTermination = {{ {capture}_ in
+ task.cancel(){cancel_hook}
+ }}
+ }}
+ }}
+}}
+"#,
+ )
+}
+
+fn render_callback_factory(factory: &CallbackFactory) -> String {
+ let type_name = &factory.type_name;
+ let swift_method = AsLowerCamelCase(&factory.method_name).to_string();
+ let handler_protocol = format!("{}Handler", type_name);
+ let wrapper_class = format!("{}HandlerClosureWrapper", type_name);
+
+ let closure_args_signature = factory
+ .callback_arg_types
+ .iter()
+ .enumerate()
+ .map(|(index, ty)| {
+ let label = format!("arg{index}");
+ format!("{label}: {ty}")
+ })
+ .collect::<Vec<_>>()
+ .join(", ");
+
+ let closure_args_forward_positional = factory
+ .callback_arg_types
+ .iter()
+ .enumerate()
+ .map(|(index, _)| format!("arg{index}"))
+ .collect::<Vec<_>>()
+ .join(", ");
+
+ let closure_type_signature = format!("({}) -> Void", factory.callback_arg_types.join(", "),);
+
+ format!(
+ r#"extension {type_name} {{
+ public typealias Closure = @Sendable {closure_type_signature}
+
+ private final class {wrapper_class}: Sendable, {handler_protocol} {{
+ private let closure: Closure
+
+ init(closure: @escaping Closure) {{
+ self.closure = closure
+ }}
+
+ func onEvent({closure_args_signature}) {{
+ closure({closure_args_forward_positional})
+ }}
+ }}
+
+ public static func {swift_method}(closure: @escaping Closure) -> {type_name} {{
+ {type_name}.{swift_method}(handler: {wrapper_class}(closure: closure))
+ }}
+}}
+"#,
+ closure_type_signature = closure_type_signature,
+ wrapper_class = wrapper_class,
+ handler_protocol = handler_protocol,
+ closure_args_signature = closure_args_signature,
+ closure_args_forward_positional = closure_args_forward_positional,
+ type_name = type_name,
+ swift_method = swift_method,
+ )
+}
+
+fn render_factory(factory: &Factory) -> String {
+ let swift_method = AsLowerCamelCase(&factory.method_name).to_string();
+ let free_function = format!(
+ "{}{}",
+ AsLowerCamelCase(AsSnakeCase(&factory.type_name).to_string()).to_string(),
+ capitalize_first(&swift_method),
+ );
+
+ let args_signature = factory
+ .arguments
+ .iter()
+ .map(|arg| format!("{label}: {ty}", label = AsLowerCamelCase(&arg.name).to_string(), ty = arg.swift_type,))
+ .collect::<Vec<_>>()
+ .join(", ");
+
+ let args_forward = factory
+ .arguments
+ .iter()
+ .map(|arg| {
+ let label = AsLowerCamelCase(&arg.name).to_string();
+ format!("{label}: {label}")
+ })
+ .collect::<Vec<_>>()
+ .join(", ");
+
+ let mut return_type = factory.type_name.clone();
+ if factory.optional {
+ return_type.push('?');
+ }
+
+ let mut modifiers = String::new();
+ if factory.is_async {
+ modifiers.push_str("async ");
+ }
+ if factory.throws {
+ modifiers.push_str("throws ");
+ }
+
+ let mut invocation = String::new();
+ if factory.throws {
+ invocation.push_str("try ");
+ }
+ if factory.is_async {
+ invocation.push_str("await ");
+ }
+ invocation.push_str(&format!("{free_function}({args_forward})"));
+
+ format!(
+ "extension {type_name} {{\n public static func {method}({args}) {modifiers}-> {ret} {{\n {invocation}\n }}\n}}\n",
+ type_name = factory.type_name,
+ method = swift_method,
+ args = args_signature,
+ modifiers = modifiers,
+ ret = return_type,
+ invocation = invocation,
+ )
+}
+
+fn capitalize_first(input: &str) -> String {
+ let mut characters = input.chars();
+ match characters.next() {
+ Some(first) => first.to_ascii_uppercase().to_string() + characters.as_str(),
+ None => String::new(),
+ }
+}
diff --git a/crates/cli-release/src/handlers/mod.rs b/crates/cli-release/src/handlers/mod.rs
index 9829ab6dc..f9ec2dd94 100644
--- a/crates/cli-release/src/handlers/mod.rs
+++ b/crates/cli-release/src/handlers/mod.rs
@@ -1,3 +1,4 @@
+mod generate_swift_extensions;
mod prepare_bindings_swift;
mod prepare_bindings_ts;
mod prepare_docs;
@@ -8,6 +9,7 @@ mod prepare_workspace_ts;
mod prepare_workspace_ts_napi;
mod sync_into_repo;
+pub use generate_swift_extensions::generate_swift_extensions;
pub use prepare_bindings_swift::prepare_bindings_swift;
pub use prepare_bindings_ts::prepare_bindings_ts;
pub use prepare_docs::prepare_docs;
diff --git a/crates/cli-release/src/handlers/prepare_bindings_swift.rs b/crates/cli-release/src/handlers/prepare_bindings_swift.rs
index 2fc24e878..b60ed0750 100644
--- a/crates/cli-release/src/handlers/prepare_bindings_swift.rs
+++ b/crates/cli-release/src/handlers/prepare_bindings_swift.rs
@@ -1,6 +1,9 @@
use std::process::{Command, Stdio};
-use crate::types::{Environment, Error};
+use crate::{
+ handlers::generate_swift_extensions,
+ types::{Environment, Error},
+};
pub fn prepare_bindings_swift(environment: &Environment) -> Result<(), Error> {
let scripts_build_path = environment.bindings().swift_build_script_path();
@@ -22,5 +25,7 @@ pub fn prepare_bindings_swift(environment: &Environment) -> Result<(), Error> {
return Err(Error::UnableToPrepareBindingsSwift);
}
+ generate_swift_extensions(environment)?;
+
Ok(())
}
diff --git a/crates/cli-release/src/handlers/prepare_workspace_swift.rs b/crates/cli-release/src/handlers/prepare_workspace_swift.rs
index 1869cd376..3ca3fcaee 100644
--- a/crates/cli-release/src/handlers/prepare_workspace_swift.rs
+++ b/crates/cli-release/src/handlers/prepare_workspace_swift.rs
@@ -32,7 +32,7 @@ pub fn prepare_workspace_swift(
let package_swift_path = workspace_swift_path.join("Package.swift");
update_package_swift(package_swift_path.clone(), version.clone(), checksum.clone())?;
- let examples_path = workspace_swift_path.join("Sources").join("Example");
+ let examples_path = workspace_swift_path.join("Sources").join("Examples");
let snippets = extract_snippets(examples_path.clone())?;
let examples = extract_examples(examples_path.clone(), workspace_swift_path.clone())?;
diff --git a/crates/cli-release/src/main.rs b/crates/cli-release/src/main.rs
index 6aba957a9..e765aeed0 100644
--- a/crates/cli-release/src/main.rs
+++ b/crates/cli-release/src/main.rs
@@ -1,10 +1,10 @@
use std::path::PathBuf;
-use clap::{CommandFactory, Parser, Subcommand};
+use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use cli_release::{
handlers::{
- SyncSource, /*prepare_bindings_swift,*/ prepare_bindings_ts, /*prepare_workspace_swift,*/
- /*prepare_workspace_swift_spm,*/ prepare_workspace_ts, prepare_workspace_ts_napi, sync_into_repo,
+ SyncSource, prepare_bindings_swift, prepare_bindings_ts, prepare_workspace_swift, prepare_workspace_swift_spm,
+ prepare_workspace_ts, prepare_workspace_ts_napi, sync_into_repo,
},
types::{Environment, Error},
};
@@ -18,7 +18,11 @@ struct Cli {
#[derive(Subcommand)]
enum Commands {
/// Prepare bindings
- PrepareBindings,
+ PrepareBindings {
+ /// Optional language filter (prepare only that language)
+ #[arg(value_enum)]
+ language: Option<BindingLanguage>,
+ },
/// Prepare workspace
PrepareWorkspace {
/// Package version
@@ -33,10 +37,28 @@ enum Commands {
},
}
-fn prepare_bindings(environment: &Environment) -> Result<(), Error> {
- prepare_workspace_ts_napi(environment)?;
- prepare_bindings_ts(environment)?;
- //prepare_bindings_swift(environment)?;
+#[derive(ValueEnum, Clone, Copy)]
+enum BindingLanguage {
+ Swift,
+ Ts,
+}
+
+fn prepare_bindings(
+ environment: &Environment,
+ language: Option<BindingLanguage>,
+) -> Result<(), Error> {
+ match language {
+ Some(BindingLanguage::Swift) => prepare_bindings_swift(environment)?,
+ Some(BindingLanguage::Ts) => {
+ prepare_workspace_ts_napi(environment)?;
+ prepare_bindings_ts(environment)?;
+ },
+ None => {
+ prepare_workspace_ts_napi(environment)?;
+ prepare_bindings_ts(environment)?;
+ prepare_bindings_swift(environment)?;
+ },
+ }
Ok(())
}
@@ -44,10 +66,10 @@ fn prepare_workspace(
environment: &Environment,
version: String,
) -> Result<(), Error> {
- prepare_bindings(&environment)?;
+ prepare_bindings(&environment, None)?;
prepare_workspace_ts(environment, version.clone())?;
- //let swift_spm_checksum = prepare_workspace_swift_spm(environment, version.clone())?;
- //prepare_workspace_swift(environment, version.clone(), swift_spm_checksum)?;
+ let swift_spm_checksum = prepare_workspace_swift_spm(environment, version.clone())?;
+ prepare_workspace_swift(environment, version.clone(), swift_spm_checksum)?;
Ok(())
}
@@ -56,8 +78,10 @@ fn main() -> Result<(), Error> {
let environment = Environment::new()?;
match cli.command {
- Some(Commands::PrepareBindings) => {
- prepare_bindings(&environment)?;
+ Some(Commands::PrepareBindings {
+ language,
+ }) => {
+ prepare_bindings(&environment, language)?;
},
Some(Commands::PrepareWorkspace {
version,
diff --git a/crates/nagare/src/chat/mod.rs b/crates/nagare/src/chat/mod.rs
index 2c8e1420a..0a28bec05 100644
--- a/crates/nagare/src/chat/mod.rs
+++ b/crates/nagare/src/chat/mod.rs
@@ -14,7 +14,7 @@ use shoji::{
backend::chat_message::{Output as BackendOutput, ToolCallState},
},
types::{
- basic::{CancellationToken, ToolCall, Value},
+ basic::{CancelToken, ToolCall, Value},
model::{Model, ModelSpecialization},
session::chat::{ChatConfig, ChatMessage, ChatReply, ChatReplyConfig},
},
@@ -36,7 +36,7 @@ pub enum ChatSessionStreamChunk {
#[derive(Clone)]
pub struct ChatSessionStream {
receiver: Arc<Mutex<mpsc::UnboundedReceiver<Result<Vec<ChatReply>, ChatSessionError>>>>,
- cancel_token: CancellationToken,
+ cancel_token: CancelToken,
}
#[bindings::export(Implementation)]
@@ -55,7 +55,7 @@ impl ChatSessionStream {
}
#[bindings::export(Getter)]
- pub fn cancel_token(&self) -> CancellationToken {
+ pub fn cancel_token(&self) -> CancelToken {
self.cancel_token.clone()
}
}
@@ -176,7 +176,7 @@ impl ChatSession {
input: Vec<ChatMessage>,
config: ChatReplyConfig,
) -> ChatSessionStream {
- let cancel_token_to_return = CancellationToken::new();
+ let cancel_token_to_return = CancelToken::new();
let (sender, receiver) = mpsc::unbounded_channel::<Result<Vec<ChatReply>, ChatSessionError>>();
let instance = self.instance.clone();
diff --git a/crates/nagare/src/classification/mod.rs b/crates/nagare/src/classification/mod.rs
index 8c98a50a0..da4a685ea 100644
--- a/crates/nagare/src/classification/mod.rs
+++ b/crates/nagare/src/classification/mod.rs
@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use shoji::{
traits::{Backend, State as StateTrait, backend::classification::Instance},
types::{
- basic::CancellationToken,
+ basic::CancelToken,
model::{Model, ModelSpecialization},
session::classification::{ClassificationMessage, ClassificationOutput},
},
@@ -75,7 +75,7 @@ impl ClassificationSession {
&self,
input: Vec<ClassificationMessage>,
) -> Result<ClassificationOutput, ClassificationSessionError> {
- let cancel_token_to_return = CancellationToken::new();
+ let cancel_token_to_return = CancelToken::new();
let (sender, mut receiver) =
mpsc::unbounded_channel::<Result<ClassificationOutput, ClassificationSessionError>>();
diff --git a/crates/nagare/src/lib.rs b/crates/nagare/src/lib.rs
index 9d800aed4..daefce84a 100644
--- a/crates/nagare/src/lib.rs
+++ b/crates/nagare/src/lib.rs
@@ -1,6 +1,4 @@
#[cfg(feature = "bindings-uniffi")]
-shoji::uniffi_reexport_scaffolding!();
-#[cfg(feature = "bindings-uniffi")]
uniffi::setup_scaffolding!();
pub mod api;
diff --git a/crates/nagare/src/text_to_speech/mod.rs b/crates/nagare/src/text_to_speech/mod.rs
index 79d6b2e83..f205d28e6 100644
--- a/crates/nagare/src/text_to_speech/mod.rs
+++ b/crates/nagare/src/text_to_speech/mod.rs
@@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use shoji::{
traits::{Backend, State as StateTrait, backend::text_to_speech::Instance},
types::{
- basic::{CancellationToken, PcmBatch},
+ basic::{CancelToken, PcmBatch},
model::{Model, ModelSpecialization},
},
};
@@ -29,7 +29,7 @@ pub enum TextToSpeechSessionStreamChunk {
#[derive(Clone)]
pub struct TextToSpeechSessionStream {
receiver: Arc<Mutex<mpsc::UnboundedReceiver<Result<PcmBatch, TextToSpeechSessionError>>>>,
- cancel_token: CancellationToken,
+ cancel_token: CancelToken,
}
#[bindings::export(Implementation)]
@@ -48,7 +48,7 @@ impl TextToSpeechSessionStream {
}
#[bindings::export(Getter)]
- pub fn cancel_token(&self) -> CancellationToken {
+ pub fn cancel_token(&self) -> CancelToken {
self.cancel_token.clone()
}
}
@@ -137,7 +137,7 @@ impl TextToSpeechSession {
&self,
input: String,
) -> TextToSpeechSessionStream {
- let cancel_token_to_return = CancellationToken::new();
+ let cancel_token_to_return = CancelToken::new();
let (sender, receiver) = mpsc::unbounded_channel::<Result<PcmBatch, TextToSpeechSessionError>>();
let holder = self.holder.clone();
diff --git a/crates/nagare/uniffi.toml b/crates/nagare/uniffi.toml
new file mode 100644
index 000000000..7f3df2ee1
--- /dev/null
+++ b/crates/nagare/uniffi.toml
@@ -0,0 +1,2 @@
+[bindings.swift]
+generate_codable_conformance = true
diff --git a/crates/shoji/src/types/basic/cancellation_token.rs b/crates/shoji/src/types/basic/cancel_token.rs
similarity index 77%
rename from crates/shoji/src/types/basic/cancellation_token.rs
rename to crates/shoji/src/types/basic/cancel_token.rs
index b6452a7d3..9247086c7 100644
--- a/crates/shoji/src/types/basic/cancellation_token.rs
+++ b/crates/shoji/src/types/basic/cancel_token.rs
@@ -2,11 +2,11 @@ use tokio_util::sync::CancellationToken as TokioCancellationToken;
#[bindings::export(Class)]
#[derive(Debug, Clone, Default)]
-pub struct CancellationToken {
+pub struct CancelToken {
inner: TokioCancellationToken,
}
-impl CancellationToken {
+impl CancelToken {
pub fn new() -> Self {
Self {
inner: TokioCancellationToken::new(),
@@ -15,7 +15,7 @@ impl CancellationToken {
}
#[bindings::export(Implementation)]
-impl CancellationToken {
+impl CancelToken {
#[bindings::export(Factory)]
pub fn create() -> Self {
Self::new()
@@ -32,7 +32,7 @@ impl CancellationToken {
}
}
-impl CancellationToken {
+impl CancelToken {
pub fn inner(&self) -> &TokioCancellationToken {
&self.inner
}
@@ -42,7 +42,7 @@ impl CancellationToken {
}
}
-impl From<TokioCancellationToken> for CancellationToken {
+impl From<TokioCancellationToken> for CancelToken {
fn from(inner: TokioCancellationToken) -> Self {
Self {
inner,
@@ -50,8 +50,8 @@ impl From<TokioCancellationToken> for CancellationToken {
}
}
-impl From<CancellationToken> for TokioCancellationToken {
- fn from(token: CancellationToken) -> Self {
+impl From<CancelToken> for TokioCancellationToken {
+ fn from(token: CancelToken) -> Self {
token.inner
}
}
diff --git a/crates/shoji/src/types/basic/mod.rs b/crates/shoji/src/types/basic/mod.rs
index 90245aa96..09e536325 100644
--- a/crates/shoji/src/types/basic/mod.rs
+++ b/crates/shoji/src/types/basic/mod.rs
@@ -1,4 +1,4 @@
-mod cancellation_token;
+mod cancel_token;
mod context_length;
mod feature;
mod file;
@@ -20,7 +20,7 @@ mod tool_namespace;
mod translation_payload;
mod value;
-pub use cancellation_token::CancellationToken;
+pub use cancel_token::CancelToken;
pub use context_length::ContextLength;
pub use feature::Feature;
pub use file::File;
diff --git a/crates/shoji/uniffi.toml b/crates/shoji/uniffi.toml
new file mode 100644
index 000000000..7f3df2ee1
--- /dev/null
+++ b/crates/shoji/uniffi.toml
@@ -0,0 +1,2 @@
+[bindings.swift]
+generate_codable_conformance = true
diff --git a/crates/uzu/.gitignore b/crates/uzu/.gitignore
new file mode 100644
index 000000000..426d3a4cf
--- /dev/null
+++ b/crates/uzu/.gitignore
@@ -0,0 +1,3 @@
+# UniFFI artifacts
+/uzu/
+/generated/
\ No newline at end of file
diff --git a/crates/uzu/src/device/mod.rs b/crates/uzu/src/device/mod.rs
index 54840a1fa..553906794 100644
--- a/crates/uzu/src/device/mod.rs
+++ b/crates/uzu/src/device/mod.rs
@@ -2,7 +2,7 @@ mod error;
mod os;
pub use error::DeviceError;
-use os::{home_path, is_environment_sandboxed, is_keyring_available};
+use os::{application_identifier, home_path, is_environment_sandboxed, is_keyring_available};
use serde::{Deserialize, Serialize};
use sysinfo::System;
@@ -14,6 +14,7 @@ pub struct Device {
pub cpu_name: Option<String>,
pub memory_total: i64,
pub home_path: String,
+ pub application_identifier: String,
pub is_environment_sandboxed: bool,
pub is_keyring_available: bool,
}
@@ -27,6 +28,7 @@ impl Device {
let cpu_name = system_info.cpus().first().map(|cpu| cpu.brand().to_string());
let memory_total = system_info.total_memory();
let home_path = home_path().ok_or(DeviceError::UnsupportedDevice {})?;
+ let application_identifier = application_identifier();
let is_environment_sandboxed = is_environment_sandboxed();
let is_keyring_available = is_keyring_available();
@@ -35,6 +37,7 @@ impl Device {
cpu_name,
memory_total: memory_total as i64,
home_path: home_path.to_string_lossy().to_string(),
+ application_identifier,
is_environment_sandboxed,
is_keyring_available,
})
diff --git a/crates/uzu/src/device/os.rs b/crates/uzu/src/device/os.rs
index f01167bca..65e06b3a6 100644
--- a/crates/uzu/src/device/os.rs
+++ b/crates/uzu/src/device/os.rs
@@ -2,6 +2,21 @@ use std::path::PathBuf;
#[allow(unreachable_code)]
pub fn home_path() -> Option<PathBuf> {
+ #[cfg(target_os = "ios")]
+ {
+ use objc2::rc::autoreleasepool;
+ use objc2_foundation::{NSFileManager, NSSearchPathDirectory, NSSearchPathDomainMask};
+
+ let path = autoreleasepool(|_| {
+ let file_manager = NSFileManager::defaultManager();
+ let urls = file_manager.URLsForDirectory_inDomains(
+ NSSearchPathDirectory::CachesDirectory,
+ NSSearchPathDomainMask::UserDomainMask,
+ );
+ urls.firstObject().and_then(|url| url.path().map(|path| PathBuf::from(path.to_string())))
+ });
+ return path;
+ }
#[cfg(target_vendor = "apple")]
{
use objc2_foundation::NSHomeDirectory;
@@ -31,6 +46,25 @@ pub fn is_environment_sandboxed() -> bool {
false
}
+#[allow(unreachable_code)]
+pub fn application_identifier() -> String {
+ #[cfg(target_vendor = "apple")]
+ {
+ use objc2_foundation::NSBundle;
+
+ let bundle = NSBundle::mainBundle();
+ if let Some(identifier) = bundle.bundleIdentifier() {
+ return identifier.to_string();
+ }
+ }
+ if let Ok(path) = std::env::current_exe() {
+ if let Some(name) = path.file_name() {
+ return name.to_string_lossy().into_owned();
+ }
+ }
+ "default".to_string()
+}
+
#[allow(unreachable_code)]
pub fn is_keyring_available() -> bool {
#[cfg(target_vendor = "apple")]
diff --git a/crates/uzu/src/engine/mod.rs b/crates/uzu/src/engine/mod.rs
index 2d88d608a..3eebb9d97 100644
--- a/crates/uzu/src/engine/mod.rs
+++ b/crates/uzu/src/engine/mod.rs
@@ -3,7 +3,10 @@ mod config;
mod downloader;
mod error;
-use std::{collections::HashMap, sync::Arc};
+use std::{
+ collections::{HashMap, HashSet},
+ sync::Arc,
+};
use backend_remote::openai::Backend as OpenAIBackend;
use backend_uzu::inference::Backend as UzuBackend;
@@ -14,7 +17,10 @@ pub use error::EngineError;
use nagare::{chat::ChatSession, classification::ClassificationSession, text_to_speech::TextToSpeechSession};
use shoji::{
traits::{Backend, Registry},
- types::{model::Model, session::chat::ChatConfig},
+ types::{
+ model::{Model, ModelFamily, ModelRegistry, ModelVendor},
+ session::chat::ChatConfig,
+ },
};
use tokio::runtime::Handle;
use tokio_stream::{StreamExt, wrappers::BroadcastStream};
@@ -241,6 +247,34 @@ impl Engine {
Ok(self.models().await?.into_iter().filter(|model| model.is_speculation_capable()).collect())
}
+ #[bindings::export(Getter)]
+ pub async fn model_registries(&self) -> Result<Vec<ModelRegistry>, EngineError> {
+ let mut registries: Vec<_> = self
+ .models()
+ .await?
+ .into_iter()
+ .map(|model| model.registry.clone())
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect();
+ registries.sort_by(|first, second| first.name().cmp(&second.name()));
+ Ok(registries)
+ }
+
+ #[bindings::export(Getter)]
+ pub async fn model_vendors(&self) -> Result<Vec<ModelVendor>, EngineError> {
+ let mut vendors: Vec<_> = self
+ .model_families()
+ .await?
+ .into_iter()
+ .map(|family| family.vendor.clone())
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect();
+ vendors.sort_by(|first, second| first.name().cmp(&second.name()));
+ Ok(vendors)
+ }
+
#[bindings::export(Method)]
pub async fn models_by_vendor(
&self,
@@ -256,6 +290,20 @@ impl Engine {
.collect())
}
+ #[bindings::export(Getter)]
+ pub async fn model_families(&self) -> Result<Vec<ModelFamily>, EngineError> {
+ let mut families: Vec<_> = self
+ .models()
+ .await?
+ .into_iter()
+ .filter_map(|model| model.family.clone())
+ .collect::<HashSet<_>>()
+ .into_iter()
+ .collect();
+ families.sort_by(|first, second| first.name().cmp(&second.name()));
+ Ok(families)
+ }
+
#[bindings::export(Method)]
pub async fn models_by_family(
&self,
@@ -386,6 +434,11 @@ impl Engine {
) -> Option<DownloadState> {
self.downloader(model).state().await
}
+
+ #[bindings::export(Getter)]
+ pub async fn download_states(&self) -> HashMap<String, DownloadState> {
+ self.storage.lock().await.states().await
+ }
}
#[bindings::export(Implementation)]
diff --git a/crates/uzu/src/keyring/mod.rs b/crates/uzu/src/keyring/mod.rs
index 55d851336..a6669dcee 100644
--- a/crates/uzu/src/keyring/mod.rs
+++ b/crates/uzu/src/keyring/mod.rs
@@ -7,29 +7,33 @@ use keyring::{Entry, Error as BackendError};
use crate::device::Device;
-const SERVICE_NAME: &str = "com.trymirai.keyring";
+const SERVICE_PREFIX: &str = "com.trymirai.keyring";
const BASE_KEY: &str = "keys";
#[bindings::export(Class)]
pub struct Keyring {
device: Device,
+ service_name: String,
}
impl Keyring {
pub fn new() -> Result<Self, KeyringError> {
+ let device = Device::new()?;
+ let service_name = format!("{SERVICE_PREFIX}.{}", device.application_identifier);
Ok(Self {
- device: Device::new()?,
+ device,
+ service_name,
})
}
- fn entry() -> Result<Entry, KeyringError> {
- Entry::new(SERVICE_NAME, BASE_KEY).map_err(|error| KeyringError::BackendError {
+ fn entry(&self) -> Result<Entry, KeyringError> {
+ Entry::new(&self.service_name, BASE_KEY).map_err(|error| KeyringError::BackendError {
message: error.to_string(),
})
}
- fn load() -> Result<HashMap<String, String>, KeyringError> {
- let entry = Self::entry()?;
+ fn load(&self) -> Result<HashMap<String, String>, KeyringError> {
+ let entry = self.entry()?;
match entry.get_password() {
Ok(value) => serde_json::from_str(&value).map_err(|error| KeyringError::BackendError {
message: error.to_string(),
@@ -41,8 +45,11 @@ impl Keyring {
}
}
- fn save(entries: &HashMap<String, String>) -> Result<(), KeyringError> {
- let entry = Self::entry()?;
+ fn save(
+ &self,
+ entries: &HashMap<String, String>,
+ ) -> Result<(), KeyringError> {
+ let entry = self.entry()?;
let value = serde_json::to_string(entries).map_err(|error| KeyringError::BackendError {
message: error.to_string(),
})?;
@@ -68,9 +75,9 @@ impl Keyring {
if !self.device.is_keyring_available {
return Ok(());
}
- let mut entries = Self::load()?;
+ let mut entries = self.load()?;
entries.insert(key, value);
- Self::save(&entries)
+ self.save(&entries)
}
#[bindings::export(Method)]
@@ -81,7 +88,7 @@ impl Keyring {
if !self.device.is_keyring_available {
return None;
}
- Self::load().ok()?.get(&key).cloned()
+ self.load().ok()?.get(&key).cloned()
}
#[bindings::export(Method)]
@@ -92,9 +99,9 @@ impl Keyring {
if !self.device.is_keyring_available {
return Ok(());
}
- let mut entries = Self::load()?;
+ let mut entries = self.load()?;
if entries.remove(&key).is_some() {
- Self::save(&entries)?;
+ self.save(&entries)?;
}
Ok(())
}
diff --git a/crates/uzu/src/lib.rs b/crates/uzu/src/lib.rs
index 3909b5212..eaf09e2ac 100644
--- a/crates/uzu/src/lib.rs
+++ b/crates/uzu/src/lib.rs
@@ -1,8 +1,4 @@
#[cfg(feature = "bindings-uniffi")]
-shoji::uniffi_reexport_scaffolding!();
-#[cfg(feature = "bindings-uniffi")]
-nagare::uniffi_reexport_scaffolding!();
-#[cfg(feature = "bindings-uniffi")]
uniffi::setup_scaffolding!();
#[cfg(not(target_family = "wasm"))]
diff --git a/crates/uzu/src/storage/mod.rs b/crates/uzu/src/storage/mod.rs
index ffd1223ed..07c62e8f3 100644
--- a/crates/uzu/src/storage/mod.rs
+++ b/crates/uzu/src/storage/mod.rs
@@ -13,6 +13,7 @@ use download_manager::{
FileCheck, FileDownloadManager, FileDownloadManagerType, FileDownloadPhase, create_download_manager,
};
pub use error::StorageError;
+use futures_util::future::join_all;
use shoji::types::{
basic::File,
model::{Model, ModelAccessibility, ModelReference},
@@ -218,6 +219,15 @@ impl Storage {
Some(state)
}
+ pub async fn states(&self) -> HashMap<String, DownloadState> {
+ let items = self.items.lock().await;
+ let state_futures = items.iter().map(|(identifier, item)| {
+ let identifier = identifier.clone();
+ async move { (identifier, item.state().await) }
+ });
+ join_all(state_futures).await.into_iter().collect()
+ }
+
pub async fn download(
&self,
model_identifier: &String,
diff --git a/crates/uzu/uniffi.toml b/crates/uzu/uniffi.toml
new file mode 100644
index 000000000..7f3df2ee1
--- /dev/null
+++ b/crates/uzu/uniffi.toml
@@ -0,0 +1,2 @@
+[bindings.swift]
+generate_codable_conformance = true
diff --git a/deny.toml b/deny.toml
index ef133f6f3..0519c8b89 100644
--- a/deny.toml
+++ b/deny.toml
@@ -6,7 +6,6 @@ ignore = [
"RUSTSEC-2025-0057", # fxhash - no longer maintained
"RUSTSEC-2024-0384", # instant is unmaintained
"RUSTSEC-2025-0012", # backoff is unmaintained
- "RUSTSEC-2026-0104", # reachable panic in certificate revocation list parsing
]
[licenses]
diff --git a/scripts/prepare_bindings.sh b/scripts/prepare_bindings.sh
new file mode 100755
index 000000000..1b3421730
--- /dev/null
+++ b/scripts/prepare_bindings.sh
@@ -0,0 +1,15 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+ROOT_PATH="$(cd "$(dirname "$0")/.." && pwd)"
+
+if [ -d "$HOME/.cargo/bin" ]; then
+ export PATH="$HOME/.cargo/bin:$PATH"
+fi
+if [ -d "/opt/homebrew/bin" ]; then
+ export PATH="/opt/homebrew/bin:$PATH"
+fi
+
+cd "$ROOT_PATH"
+cargo run -p cli-release prepare-bindings "$@"