Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .swiftlint-baseline.json
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,6 @@
{"violation":{"ruleDescription":"Properties should have a type interface","ruleIdentifier":"explicit_type_interface","location":{"file":"Sources/ModelRelay/Models/Generation/DecisionByLanguageModel.swift","line":29,"character":21},"reason":"Properties should have a type interface","severity":"warning","ruleName":"Explicit Type Interface"},"text":" let text = field.textValue.trimmingCharacters(in: .whitespacesAndNewlines.union(CharacterSet(charactersIn: \"\\\"'\")))"},
{"violation":{"ruleDescription":"Properties should have a type interface","ruleIdentifier":"explicit_type_interface","location":{"file":"Sources/ModelRelay/Models/Generation/DecisionByLanguageModel.swift","line":35,"character":21},"reason":"Properties should have a type interface","severity":"warning","ruleName":"Explicit Type Interface"},"text":" let text = field.textValue.trimmingCharacters(in: .whitespacesAndNewlines.union(CharacterSet(charactersIn: \"\\\"'\")))"},
{"violation":{"ruleDescription":"Use `Self` to refer to the surrounding type name","ruleIdentifier":"prefer_self_in_static_references","location":{"file":"Sources/ModelRelay/Models/Generation/Field.swift","line":8,"character":28},"reason":"Use `Self` to refer to the surrounding type name","severity":"warning","ruleName":"Prefer Self in Static References"},"text":" indirect case list(Kind)"},
{"violation":{"ruleDescription":"Properties should have a type interface","ruleIdentifier":"explicit_type_interface","location":{"file":"Sources/ModelRelay/Models/Generation/SchemaBuilder.swift","line":18,"character":13},"reason":"Properties should have a type interface","severity":"warning","ruleName":"Explicit Type Interface"},"text":" let root = DynamicGenerationSchema(name: name, properties: fields.map { field in"},
{"violation":{"ruleDescription":"Enums should be explicitly assigned their raw values","ruleIdentifier":"explicit_enum_raw_value","location":{"file":"Sources/ModelRelay/Models/ModelCatalog.swift","line":7,"character":10},"reason":"Enums should be explicitly assigned their raw values","severity":"warning","ruleName":"Explicit Enum Raw Value"},"text":" case local, remote, unspecified"},
{"violation":{"ruleDescription":"Enums should be explicitly assigned their raw values","ruleIdentifier":"explicit_enum_raw_value","location":{"file":"Sources/ModelRelay/Models/ModelCatalog.swift","line":7,"character":17},"reason":"Enums should be explicitly assigned their raw values","severity":"warning","ruleName":"Explicit Enum Raw Value"},"text":" case local, remote, unspecified"},
{"violation":{"ruleDescription":"Enums should be explicitly assigned their raw values","ruleIdentifier":"explicit_enum_raw_value","location":{"file":"Sources/ModelRelay/Models/ModelCatalog.swift","line":7,"character":25},"reason":"Enums should be explicitly assigned their raw values","severity":"warning","ruleName":"Explicit Enum Raw Value"},"text":" case local, remote, unspecified"},
Expand Down Expand Up @@ -453,7 +452,7 @@
{"violation":{"ruleDescription":"Enums should be explicitly assigned their raw values","ruleIdentifier":"explicit_enum_raw_value","location":{"file":"Sources/ModelRelay/Workflow/Validation/Workflow+Validation.swift","line":6,"character":48},"reason":"Enums should be explicitly assigned their raw values","severity":"warning","ruleName":"Explicit Enum Raw Value"},"text":" case incompatibleModel, invalidSchema, unavailableTool, invalidContext, invalidVersion"},
{"violation":{"ruleDescription":"Enums should be explicitly assigned their raw values","ruleIdentifier":"explicit_enum_raw_value","location":{"file":"Sources/ModelRelay/Workflow/Validation/Workflow+Validation.swift","line":6,"character":65},"reason":"Enums should be explicitly assigned their raw values","severity":"warning","ruleName":"Explicit Enum Raw Value"},"text":" case incompatibleModel, invalidSchema, unavailableTool, invalidContext, invalidVersion"},
{"violation":{"ruleDescription":"Enums should be explicitly assigned their raw values","ruleIdentifier":"explicit_enum_raw_value","location":{"file":"Sources/ModelRelay/Workflow/Validation/Workflow+Validation.swift","line":6,"character":81},"reason":"Enums should be explicitly assigned their raw values","severity":"warning","ruleName":"Explicit Enum Raw Value"},"text":" case incompatibleModel, invalidSchema, unavailableTool, invalidContext, invalidVersion"},
{"violation":{"ruleDescription":"Function bodies should not span too many lines","ruleIdentifier":"function_body_length","location":{"file":"Sources/ModelRelay/Workflow/Validation/Workflow+Validation.swift","line":21,"character":5},"reason":"Function body should span 80 lines or less excluding comments and whitespace: currently spans 107 lines","severity":"error","ruleName":"Function Body Length"},"text":" func validationIssues(catalog: ModelCatalog, kits: [String: ToolKit]) -> [WorkflowValidationIssue] {"},
{"violation":{"ruleDescription":"Function bodies should not span too many lines","ruleIdentifier":"function_body_length","location":{"file":"Sources/ModelRelay/Workflow/Validation/Workflow+Validation.swift","line":21,"character":5},"reason":"Function body should span 80 lines or less excluding comments and whitespace: currently spans 94 lines","severity":"error","ruleName":"Function Body Length"},"text":" func validationIssues(catalog: ModelCatalog, kits: [String: ToolKit]) -> [WorkflowValidationIssue] {"},
{"violation":{"ruleDescription":"Properties should have a type interface","ruleIdentifier":"explicit_type_interface","location":{"file":"Sources/ModelRelay/Workflow/Validation/Workflow+Validation.swift","line":31,"character":13},"reason":"Properties should have a type interface","severity":"warning","ruleName":"Explicit Type Interface"},"text":" let knownModels = Set(catalog.ids)"},
{"violation":{"ruleDescription":"Complexity of function bodies should be limited.","ruleIdentifier":"cyclomatic_complexity","location":{"file":"Sources/ModelRelay/Workflow/Validation/Workflow+Validation.swift","line":50,"character":9},"reason":"Function should have complexity 8 or less; currently complexity is 33","severity":"error","ruleName":"Cyclomatic Complexity"},"text":" func visit(_ steps: [Step]) {"},
{"violation":{"ruleDescription":"Function bodies should not span too many lines","ruleIdentifier":"function_body_length","location":{"file":"Sources/ModelRelay/Workflow/Validation/Workflow+Validation.swift","line":50,"character":9},"reason":"Function body should span 40 lines or less excluding comments and whitespace: currently spans 72 lines","severity":"warning","ruleName":"Function Body Length"},"text":" func visit(_ steps: [Step]) {"},
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,14 @@
- A `modelrelay` agent skill and Claude Code plugin marketplace, so coding agents in host apps
add the package, use the docs of their resolved version and follow the SDK's safety contracts.
`make check-skill` keeps its guide links and API names in sync with the package.
- `Field.Kind.object` groups fields, so `extract` steps and tool parameters can ask for
lists of records such as `.list(.object([...]))`. Each object reads as a dictionary.
Exhaustive `switch`es over `Field.Kind` need a case for it.

### Fixed

- Named schema nodes no longer share a definition when their names repeat (a tool and one of its
choice parameters, or fields in different objects), which let one replace the other's shape.

## [0.1.0] - 2026-10-18

Expand Down
28 changes: 26 additions & 2 deletions Documentation/Usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ Pick a recipe and add the integrations it needs. Models used by a step must
be available in your executor's catalog.

[🎯 Steps](#step-types) · [🔀 Branches](#composition) · [📦 Values](#values-and-input) ·
[🌐 HTTP](#http-requests-and-agent-tools) · [☁️ Cloud](#cloud-models) · [📷 Images](#images) ·
[👨‍💻 Swift](#custom-swift) · [🧰 MCP](#mcp-tools-and-oauth) · [🗳 Decisions](#decision-models)
[🧾 Nested fields](#nested-fields) · [🌐 HTTP](#http-requests-and-agent-tools) · [☁️ Cloud](#cloud-models) ·
[📷 Images](#images) · [👨‍💻 Swift](#custom-swift) · [🧰 MCP](#mcp-tools-and-oauth) · [🗳 Decisions](#decision-models)

<a name="step-types"></a>

Expand Down Expand Up @@ -87,6 +87,30 @@ Executions are independent. Opt into [conversation/handoff](ContextAndPolicies.m
for shared history or selected context. `stepTimeout` defaults to 30 seconds
per bounded operation, not per workflow; cancellation remains cooperative.

<a name="nested-fields"></a>

## 🧾 Extract lists of objects

Group fields with `.object`. A list of objects reads records such as the lines of an order:

```swift
let workflow = Workflow(
name: "Order from text"
) {
Step.extract("order", instruction: "Turn the order into lines.", model: .appleOnDevice) {
Field("lines", .list(.object([
Field("product", .choice(["Beer", "Cola", "Fries"])),
Field("quantity", .number),
Field("note", .text),
])))
}
}
```

Each object becomes a dictionary (`{{order.lines}}` inserts the list as JSON).
Objects work wherever fields do, including tool parameters. Nested field names
only need to be unique within their object.

<a name="http-requests-and-agent-tools"></a>

## 🌐 Call an HTTP API
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ private enum ServerArguments {
case let .list(item):
if let data = text.data(using: .utf8), let parsed = Value(json: data), case .list = parsed { return parsed }
return .list(text.split(whereSeparator: \.isNewline).map { value(String($0).trimmingCharacters(in: .whitespaces), as: item) })
case .text, .choice:
case .text, .choice, .object:
// A JSON object or list written into a text field is sent as one.
if text.hasPrefix("{") || text.hasPrefix("["), let data = text.data(using: .utf8), let parsed = Value(json: data) {
return parsed
Expand Down
3 changes: 3 additions & 0 deletions Sources/ModelRelay/Models/Generation/Field.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ public struct Field: Codable, Sendable, Hashable {
case text, number, bool
case choice([String])
indirect case list(Kind)
/// Named fields of their own, such as each line of an order in a
/// `.list(.object([...]))`. The result is a dictionary.
case object([Field])
}

public var name: String
Expand Down
57 changes: 39 additions & 18 deletions Sources/ModelRelay/Models/Generation/SchemaBuilder.swift
Original file line number Diff line number Diff line change
@@ -1,32 +1,53 @@
import AnyLanguageModel

extension Field.Kind {
func schema(named name: String) -> DynamicGenerationSchema {
switch self {
case .text: DynamicGenerationSchema(type: String.self)
case .number: DynamicGenerationSchema(type: Double.self)
case .bool: DynamicGenerationSchema(type: Bool.self)
case let .choice(options): DynamicGenerationSchema(name: name, anyOf: options)
case let .list(item): DynamicGenerationSchema(arrayOf: item.schema(named: name + "Item"))
}
}
}

enum SchemaBuilder {
/// A guided-generation schema for an object with `fields`.
static func object(named name: String, fields: [Field]) throws -> GenerationSchema {
let root = DynamicGenerationSchema(name: name, properties: fields.map { field in
var names: SchemaNames = .init()
return try GenerationSchema(root: names.object(named: name, fields: fields), dependencies: [])
}

/// A schema whose only valid output is one of `labels`.
static func label(from labels: [String]) throws -> GenerationSchema {
try GenerationSchema(root: DynamicGenerationSchema(name: "Label", anyOf: labels), dependencies: [])
}
}

/// Named nodes (objects and choices) become shared definitions keyed by name,
/// and a later node with the same name replaces an earlier one. Nested fields
/// often repeat names (`name`, `kind`), so each node gets its own.
private struct SchemaNames {
private var used: Set<String> = []

mutating func object(named name: String, fields: [Field]) -> DynamicGenerationSchema {
let name: String = unique(name)
return DynamicGenerationSchema(name: name, properties: fields.map { field in
DynamicGenerationSchema.Property(
name: field.name,
description: field.description,
schema: field.kind.schema(named: field.name)
schema: schema(field.kind, named: field.name)
)
})
return try GenerationSchema(root: root, dependencies: [])
}

/// A schema whose only valid output is one of `labels`.
static func label(from labels: [String]) throws -> GenerationSchema {
try GenerationSchema(root: DynamicGenerationSchema(name: "Label", anyOf: labels), dependencies: [])
private mutating func schema(_ kind: Field.Kind, named name: String) -> DynamicGenerationSchema {
switch kind {
case .text: DynamicGenerationSchema(type: String.self)
case .number: DynamicGenerationSchema(type: Double.self)
case .bool: DynamicGenerationSchema(type: Bool.self)
case let .choice(options): DynamicGenerationSchema(name: unique(name), anyOf: options)
case let .list(item): DynamicGenerationSchema(arrayOf: schema(item, named: name + "Item"))
case let .object(fields): object(named: name, fields: fields)
}
}

private mutating func unique(_ base: String) -> String {
var name: String = base
var suffix: Int = 2
while !used.insert(name).inserted {
name = "\(base)\(suffix)"
suffix += 1
}
return name
}
}
31 changes: 31 additions & 0 deletions Sources/ModelRelay/Workflow/Validation/Field+Validation.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import Foundation

extension [Field] {
/// Why these fields can't become a guided-generation schema, nested objects included.
var schemaProblems: [String] {
var problems: [String] = []
if Set(map(\.name)).count != count || contains(where: { $0.name.isEmpty }) {
problems.append("fields need unique nonempty names")
}
for field in self {
problems += field.kind.schemaProblems
}
return problems
}
}

extension Field.Kind {
var schemaProblems: [String] {
switch self {
case let .choice(options):
let blank: Bool = options.contains { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }
return options.isEmpty || blank || Set(options).count != options.count ? ["choices must be nonempty and unique"] : []
case let .list(item):
return item.schemaProblems
case let .object(fields):
return (fields.isEmpty ? ["objects need at least one field"] : []) + fields.schemaProblems
case .text, .number, .bool:
return []
}
}
}
19 changes: 3 additions & 16 deletions Sources/ModelRelay/Workflow/Validation/Workflow+Validation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,9 @@ extension Workflow {
}
var names: Set<String> = []
let knownModels = Set(catalog.ids)
func fields(_ fields: [Field], step: String) {
if Set(fields.map(\.name)).count != fields.count || fields.contains(where: { $0.name.isEmpty }) {
issue(step, .invalidSchema, "fields need unique nonempty names")
}
func kind(_ value: Field.Kind) {
switch value {
case let .choice(options):
if options.isEmpty || options.contains(where: { $0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }) || Set(options).count != options.count {
issue(step, .invalidSchema, "choices must be nonempty and unique")
}
case let .list(item): kind(item)
default: break
}
}
for field in fields {
kind(field.kind)
func fields(_ list: [Field], step: String) {
for problem in list.schemaProblems {
issue(step, .invalidSchema, problem)
}
}
func visit(_ steps: [Step]) {
Expand Down
14 changes: 14 additions & 0 deletions Tests/ModelRelayTests/Models/LiveAppleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,20 @@ struct LiveAppleTests {
#expect(report.output["queue"] == .text("shipping"))
}

@Test func onDeviceModelExtractsListsOfObjects() async throws {
let workflow: Workflow = .init(name: "Order", steps: [Step("order", .extract(instruction: "Turn the order into lines.", fields: [
Field("lines", .list(.object([
Field("product", .choice(["Beer", "Cola", "Fries"])),
Field("quantity", .number),
]))),
]), model: .appleOnDevice)])
let report: WorkflowExecutionReport = try await WorkflowExecutor().run(workflow, input: .text("Two beers and one portion of fries, please."))
print("LIVE order:", report.output["lines"]?.modelText ?? "", "|", report.duration)
let lines: [Value] = try #require(report.output["lines"].flatMap { if case let .list(items) = $0 { items } else { nil } })
#expect(lines.contains(.dictionary(["product": .text("Beer"), "quantity": .number(2)])))
#expect(lines.contains(.dictionary(["product": .text("Fries"), "quantity": .number(1)])))
}

/// Its first use in a process prepares the model, which can take a
/// minute on a Mac; later runs take a fraction of a second.
@Test func appleTextRecognitionReadsTheImageOnDevice() async throws {
Expand Down
Loading
Loading