object

package
v1.803.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 9, 2026 License: Apache-2.0 Imports: 113 Imported by: 0

Documentation

Overview

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2024 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2024 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Direct ClickHouse datastore client — the OLAP ledger transport.

This is the ONE way the cloud runtime reaches the analytics datastore (ClickHouse, deployed as `datastore` / `insights-datastore` in-cluster). It backs the hanzo.cloud_usage usage ledger (console2 Overview + admin god-view) and the hanzo.observations trace ledger.

WHY NOT ZAP. The prior design routed these through a ZAP "datastore peer" (see object/zap.go), which required (a) object.InitZap() — a node the UNIFIED cloud binary deliberately never starts (its ZAP listener lives only in cmd/aid), and (b) a ZAP server on the datastore's :9999 — which does not exist (the datastore image is ClickHouse behind nginx on :8123/:9000, no ZAP bridge). So the peer never connected, DatastoreEnabled() was always false, and BOTH the read (get-cloud-usages) and write (zapWriteUsage/zapWriteTrace) paths were dead. The datastore speaks ClickHouse's own protocol; we speak it directly — the same clickhouse-go/v2 recipe cloud's audit OLAP mirror and the insights/o11y stack already uses. No sidecar, no bridge, one transport.

InitDatastore is called from the SHARED Bootstrap (bootstrap.go), so it runs identically in the standalone (cmd/aid) and the embedded unified cloud binary with no boot-order or listener coupling. It is opt-in: with no DATASTORE_ADDR the ledger stays honest-empty (DatastoreEnabled() == false) rather than fabricating zeros.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2024 The Hanzo Authors. All Rights Reserved. Portions Copyright 2024 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2025 The Hanzo Authors. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Memory is the cloud-resident backend of the unified memory interface. It is a peer to hanzo-mcp's on-disk local backend: same action surface (remember, search, list, recall, update, delete, facts), different storage. Memories are persisted in the same store (dbx/SQLite/Postgres) the rest of the AI core uses and reuse the existing embedding provider for semantic search — no new provider, no new secret, no standalone service.

SECURITY INVARIANT: every accessor is scoped by BOTH owner (org) and userId. The owner/userId are supplied by the controller from the gateway-injected IAM identity, never from the request body. A memory's primary key is (owner, name); userId is a separate column, so single-row lookups additionally verify userId to stop a caller in the same org from reading another user's memory by guessing its name.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2024 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2026 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2026 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2024 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2024 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2025 The Hanzo Authors. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2025 Hanzo AI, Inc.. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2024 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2024 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

OTel GenAI telemetry — the OTLP trace exporter that ships one gen_ai span per LLM call to o11y (SigNoz), following the OpenTelemetry GenAI semantic conventions. This is the ONE way the ai module emits per-request LLM traces. It is orthogonal to the two usage writers: the spend ledger (hanzo.cloud_usage, written by zapWriteUsage) and the o11y-owned observations table are separate concerns — see controllers/openai_api.go recordTrace.

Opt-in via OTEL_EXPORTER_OTLP_ENDPOINT (or OTEL_EXPORTER_OTLP_TRACES_ENDPOINT), mirroring InitDatastore's env-gated, background, non-fatal posture: with no endpoint the emitter stays honest-off (TelemetryEnabled() == false) and the span emit is a no-op, so local dev never ships to a nonexistent collector. The exporter itself self-configures from the standard OTEL_EXPORTER_OTLP_* env (endpoint, headers, per-scheme TLS, timeout) — never hard-coded.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2024 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2024 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2023 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2025 Hanzo AI Inc. All Rights Reserved. Portions Copyright 2025 The OpenAgent Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Copyright 2023-2026 Hanzo AI Inc. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Package object/zap.go — Native ZAP binary protocol node.

Cloud-api is a first-class ZAP node. NO gateways, NO proxies, NO sidecars, NO HTTP translation layers. Everything is ZAP-to-ZAP:

client → cloud-api:9999 (ZAP binary)
cloud-api → kv:9999     (ZAP binary)
cloud-api → sql:9999    (ZAP binary)

Service handlers are registered via RegisterCloudHandler() from the controllers package (avoids circular imports).

Index

Constants

View Source
const (
	StatusNotDeployed = "Not Deployed"
	StatusPending     = string(v1.PodPending) // "Pending"
	StatusRunning     = string(v1.PodRunning) // "Running"
	StatusUnknown     = string(v1.PodUnknown) // "Unknown"
	StatusFailed      = string(v1.PodFailed)
	StatusTerminating = "Terminating"
	NamespaceFormat   = "hanzo-cloud-%s"
)
View Source
const (
	NoConnect    = "no_connect"
	Connecting   = "connecting"
	Connected    = "connected"
	Disconnected = "disconnected"
)
View Source
const (
	MemoryKindUser      = "user"      // facts/preferences about the user
	MemoryKindFeedback  = "feedback"  // corrections the user gave the assistant
	MemoryKindProject   = "project"   // project/working context
	MemoryKindReference = "reference" // reference material to retain
	MemoryKindFact      = "fact"      // discrete facts (surfaced by /facts)
)

Memory kinds mirror the hanzo-mcp memory tool's taxonomy so the local and cloud backends present one interface.

View Source
const (
	AutoRoutingUnset    = ""
	AutoRoutingEnabled  = "enabled"
	AutoRoutingDisabled = "disabled"
)

Auto-routing preference values for OrgSettings.AutoRouting and OrgSettings.DefaultSessionRouting. The empty string means "unset" — resolution falls through to the "*" global-default row and then the conf file. See resolveAutoModel and effectiveAutoRouting.

View Source
const (
	ScaleStatePublic = "Public"
	ScaleStateHidden = "Hidden"
)

Scale state values for visibility (which scales are included in public lists).

View Source
const (
	// Cloud service — native binary RPC, NO HTTP.
	MsgTypeCloud uint16 = 100
	// Gateway → cloud-api (HTTP-over-ZAP from gateway proxy).
	// Request:  method(0:Text) + path(8:Text) + headers(16:Bytes) + body(24:Bytes) + query(32:Text)
	// Response: status(0:Uint32) + body(4:Bytes) + headers(12:Bytes)
	MsgTypeHTTPRequest uint16 = 200
	// Backend sidecar protocol (KV/SQL embedded servers).
	MsgTypeSQL   uint16 = 300
	MsgTypeKV    uint16 = 301
	MsgTypeDocdb uint16 = 303
	// ── Cloud service message layout ────────────────────────────────
	// Request:  method(0:Text) + auth(8:Text) + body(16:Bytes)
	// Response: status(0:Uint32) + body(4:Bytes) + error(12:Text)
	CloudReqMethod  = 0
	CloudReqAuth    = 8
	CloudReqBody    = 16
	CloudRespStatus = 0
	CloudRespBody   = 4
	CloudRespError  = 12
)

── Message types ───────────────────────────────────────────────────────

Cloud service types (100-199):

100 = Cloud service request (method dispatch)

Backend types (300-399, matches sidecar protocol):

300 = SQL query/exec
301 = KV get/set/cmd
View Source
const BalanceLedgerTTL = 30 * time.Second

BalanceLedgerTTL is how long a cached Commerce balance is considered fresh. It matches the router gate's cache window so both read one consistent clock.

View Source
const DefaultDocsStore = "docs"

DefaultDocsStore is the tenant's default documentation store/index slug. It is brand-NEUTRAL by design: every org (hanzo, lux, zoo, any customer) gets its own isolated index `{owner}-docs-docs` because the owner prefix — bound to the authenticated principal — is what separates tenants. Baking a brand here (the old "docs-hanzo-ai") would have shown Hanzo's slug on every org's store, so it is not.

View Source
const GlobalDefaultOwner = "*"

GlobalDefaultOwner is the reserved OrgSettings.Owner for the platform-wide default row. Its writes are RequireGlobalAdmin-gated exactly like any other org's; it is read as a fallback between a real org's row and the conf file. No real request ever resolves its org to "*" (GetEffectiveOrg derives the org from the verified principal), so this owner is never mistaken for a tenant.

View Source
const RagFileStore = "rag-files"

RagFileStore is the default store/index slug for uploaded-file RAG. It keeps per-file uploads in their own tenant index ({owner}-rag-files-docs) so a noisy upload set never pollutes the curated docs index, while still riding the exact same Search+Vector pipeline. Callers may override via the request `store`.

Variables

View Source
var (
	// ErrJWTBadIssuer is returned when a token's iss is not the trusted issuer.
	ErrJWTBadIssuer = errors.New("jwt: untrusted issuer")
	// ErrJWTBadAudience is returned when a token's aud is outside the allowlist.
	ErrJWTBadAudience = errors.New("jwt: audience not allowed")
	// ErrJWTMalformed is returned when the token payload cannot be decoded.
	ErrJWTMalformed = errors.New("jwt: malformed token")
)
View Source
var (
	// ApiThroughput uses *metric.GaugeVec directly because Reset() is needed
	ApiThroughput = metric.NewGaugeVec(metric.GaugeOpts{
		Name: "cloud_api_throughput",
		Help: "The throughput of each api access",
	}, []string{"path", "method"})
	ApiLatency = metric.NewHistogramVec(metric.HistogramOpts{
		Name: "cloud_api_latency",
		Help: "API processing latency in milliseconds",
	}, []string{"path", "method"})
	CpuUsage = metric.NewGaugeVec(metric.GaugeOpts{
		Name: "cloud_cpu_usage",
		Help: "Hanzo Cloud cpu usage",
	}, []string{"cpuNum"})
	MemoryUsage = metric.NewGaugeVec(metric.GaugeOpts{
		Name: "cloud_memory_usage",
		Help: "Hanzo Cloud memory usage in Byte",
	}, []string{"type"})
	TotalThroughput = metric.NewGauge(metric.GaugeOpts{
		Name: "cloud_total_throughput",
		Help: "The total throughput of Hanzo Cloud",
	})
)
View Source
var (
	WecomBotCache        = make(map[string]Provider)
	WecomBotMessageCache = make(map[string]string)
)
View Source
var CloudHost = ""
View Source
var ErrTasksNotConfigured = tasksNotConfigured{}

ErrTasksNotConfigured signals no dialer was injected (the composition root hasn't wired the tasks engine). The handler treats it as "fall back to inline ingest" so ingest still works before/without a tasks rollout — graceful, not a second async system.

View Source
var GlobalBalanceLedger = NewBalanceLedger(BalanceLedgerTTL)

GlobalBalanceLedger is the process-wide singleton shared by the router gate (reserve / balance cache) and the controller debit path (settle).

SINGLE-POD INVARIANT: this ledger is in-pod (per-process) memory. Reserve/Settle are correct ONLY when cloud-api runs as a SINGLE replica — two pods each reserve against their own cached Commerce balance and would double-spend. The deployment enforces this with strategy=Recreate AND HPA min=max=1 (universe services.hanzo.ai/cloud-api CR); SinglePodReplicaHint lets the process ALSO assert it at boot. Scaling out REQUIRES a Commerce-atomic conditional reserve (move Reserve/Settle behind a Commerce endpoint) — until then, do not raise replicas. See LLM.md "Balance ledger — single-pod invariant".

Functions

func AddApplication

func AddApplication(application *Application) (bool, error)

func AddArticle

func AddArticle(article *Article) (bool, error)

func AddAsset

func AddAsset(asset *Asset) (bool, error)

func AddCaase

func AddCaase(caase *Caase) (bool, error)

func AddChat

func AddChat(chat *Chat) (bool, error)

func AddConnection

func AddConnection(connection *Connection) (bool, error)

func AddConsultation

func AddConsultation(consultation *Consultation) (bool, error)

func AddContainer

func AddContainer(container *Container) (bool, error)

func AddDetails

func AddDetails(apps []*Application, lang string)

func AddDoctor

func AddDoctor(doctor *Doctor) (bool, error)

func AddFile

func AddFile(file *File) (bool, error)

func AddForm

func AddForm(form *Form) (bool, error)

func AddGraph

func AddGraph(graph *Graph) (bool, error)

func AddHospital

func AddHospital(hospital *Hospital) (bool, error)

func AddImage

func AddImage(image *Image) (bool, error)

func AddMachine

func AddMachine(machine *Machine) (bool, error)

func AddMemory added in v1.785.11

func AddMemory(memory *Memory) (bool, error)

AddMemory inserts a memory. The caller must have set Owner and UserId from the authenticated identity. Missing timestamps/name/kind are filled in here.

func AddMessage

func AddMessage(message *Message) (bool, error)

func AddModelRoute

func AddModelRoute(route *ModelRoute) (bool, error)

func AddNode

func AddNode(node *Node) (bool, error)

func AddOrgSettings added in v1.802.0

func AddOrgSettings(s *OrgSettings) (bool, error)

func AddPatient

func AddPatient(patient *Patient) (bool, error)

func AddPod

func AddPod(pod *Pod) (bool, error)

func AddProvider

func AddProvider(provider *Provider) (bool, error)

func AddRecord

func AddRecord(record *Record, lang string) (bool, interface{}, error)

func AddRecords

func AddRecords(records []*Record, syncEnabled bool, lang string) (bool, interface{}, error)

func AddRoutingEvent added in v1.802.0

func AddRoutingEvent(e *RoutingEvent) error

AddRoutingEvent persists a routing decision. It fills in the id and created time when unset. Callers invoke this best-effort (off the request hot path) — a nil adapter or insert error must never surface to the chat request, so the error is returned for logging but the caller ignores it.

func AddScale

func AddScale(scale *Scale) (bool, error)

func AddScan

func AddScan(scan *Scan) (bool, error)

func AddSession

func AddSession(session *Session) (bool, error)

func AddStore

func AddStore(store *Store) (bool, error)

func AddTask

func AddTask(task *Task) (bool, error)

func AddTemplate

func AddTemplate(template *Template) (bool, error)

func AddTransactionForMessage

func AddTransactionForMessage(message *Message) error

AddTransactionForMessage creates a withdraw transaction in Commerce for a message with price, sets the message's TransactionId, and if transaction creation fails, updates the message's ErrorText field in the database and returns an error.

func AddTreeFile

func AddTreeFile(storeId string, userName string, key string, isLeaf bool, filename string, file multipart.File, lang string) (bool, []byte, error)

func AddVector

func AddVector(vector *Vector) (bool, error)

func AddVectorsForFile

func AddVectorsForFile(store *Store, fileName string, fileUrl string, lang string) (bool, error)

AddVectorsForFile ingests a single store file into the unified Vector+Search index (replaces the deprecated SQL-vector write).

func AddVideo

func AddVideo(video *Video) (bool, error)

func AddWorkflow

func AddWorkflow(workflow *Workflow, lang string) (bool, error)

func ArchiveCrawlResult

func ArchiveCrawlResult(owner, jobID string, results []ScrapeResult, rawResults []Crawl4AIResult) error

ArchiveCrawlResult uploads crawl results as JSON to Hanzo Storage. The results are stored at {bucket}/{owner}/{jobID}/results.json.

func AtomicClaimScan

func AtomicClaimScan(owner, name, hostname string) (int64, error)

AtomicClaimScan atomically updates a scan's state from "Pending" to "Running" This operation will only succeed for one instance due to the WHERE condition on state Returns the number of affected rows

func BillingSubject added in v1.785.10

func BillingSubject(owner, name string) string

BillingSubject returns the canonical Commerce billing subject for an IAM (owner, name) identity — the value passed as ?user= / posted as the usage `user` / granted to as DestinationId. The namespace (X-Org-Id) is always `owner`; this is only the subject WITHIN that namespace:

  • personal-billing org → "owner/name" (per-user)
  • pooled org → "owner" (per-org)

Always lowercased: the read paths lowercase ?user=, and RecordUsage stores SourceId verbatim, so an un-lowercased subject would record usage that never nets against the balance (a silent leak). Lowercasing at the single source of the subject closes that.

Empty owner yields "" (caller fails open / cannot bill).

func BillingSubjectForPrincipal added in v1.789.0

func BillingSubjectForPrincipal(owner, name, userType string) string

BillingSubjectForPrincipal returns the billing subject for an authenticated principal, accounting for machine (M2M) identities. A client_credentials / application principal — Casdoor User.Type == "application", e.g. the hanzo-cloud service token minted for cloud→cloud calls — is billed to its OWNER ORG, never to a per-app "owner/app-name" subject: the app name is not a funded account, so in a personal-billing org (the "hanzo" catch-all) it would resolve to the unfunded "hanzo/hanzo-cloud" and 402 legitimate service traffic. Human principals resolve exactly as BillingSubject (per-user for a personal-billing org, else the org). This is the ONE place the M2M carve-out lives, shared by the router gate and the controller backstop so they can never disagree on who a service token bills.

func BillingSubjectFromUserKey added in v1.785.10

func BillingSubjectFromUserKey(owner, userKey string) string

BillingSubjectFromUserKey is BillingSubject for callers that already hold the "owner/name" user key as a single string (e.g. usage records, ZAP params, searchAuth.UserID). If owner is empty it is derived from the key's prefix.

func BuildCloudResponse

func BuildCloudResponse(status uint32, body []byte, errMsg string) (*zap.Message, error)

── Cloud service response builder ────────────────────────────────────── BuildCloudResponse creates a native ZAP cloud service response. Used by controllers to build responses for incoming cloud requests.

func BuildGatewayResponse

func BuildGatewayResponse(status uint32, body []byte, headers []byte) (*zap.Message, error)

── Gateway response builder ───────────────────────────────────────────── BuildGatewayResponse creates a response in the gateway's expected format. Layout: status(0:Uint32) + body(4:Bytes) + headers(12:Bytes)

func CanEditPatient

func CanEditPatient(user *iam.User, patient *Patient) bool

func ClearThroughputPerSecond

func ClearThroughputPerSecond()

func CloseConnection

func CloseConnection(id string, code int, msg string) error

func CloseDbSession

func CloseDbSession(id string, code int, msg string) error

func CommitRecord

func CommitRecord(record *Record, lang string) (bool, map[string]interface{}, error)

func CommitRecordSecond

func CommitRecordSecond(record *Record, lang string) (bool, error)

func CommitRecords

func CommitRecords(records []*Record, lang string) (int, []map[string]interface{})

CommitRecords commits multiple records to the blockchain.

func CountMemories added in v1.785.11

func CountMemories(owner, userId string) (int64, error)

CountMemories counts the caller's memories.

func CreateTables

func CreateTables()

func DatastoreEnabled

func DatastoreEnabled() bool

DatastoreEnabled reports whether the ClickHouse ledger connection is live. The read path gates on it to return an honest "unavailable" (not fake zeros) and the write path gates on it to skip the insert when the warehouse is absent.

func DatastoreExec added in v1.789.1

func DatastoreExec(ctx context.Context, stmt string, args ...interface{}) error

DatastoreExec runs a DDL or INSERT against ClickHouse. `?` placeholders are bound positionally from args (clickhouse-go renders them into the statement).

func DatastoreQuery added in v1.789.1

func DatastoreQuery(ctx context.Context, query string, args ...interface{}) ([]map[string]interface{}, error)

DatastoreQuery runs a SELECT and returns rows as column→value maps, decoding each column into its native ClickHouse scan type (uint64, string, time.Time, float64, …). The cloud_usage read layer's cu* coercers accept those native types, so callers never touch reflect. Symmetric to DatastoreExec.

func DeleteAllLaterMessages

func DeleteAllLaterMessages(messageId string) error

func DeleteApplication

func DeleteApplication(application *Application, lang string) (bool, error)

func DeleteArticle

func DeleteArticle(article *Article) (bool, error)

func DeleteAsset

func DeleteAsset(asset *Asset) (bool, error)

func DeleteBeegoSession

func DeleteBeegoSession(sessionIds []string)

func DeleteCaase

func DeleteCaase(caase *Caase) (bool, error)

func DeleteChat

func DeleteChat(chat *Chat) (bool, error)

func DeleteConnection

func DeleteConnection(connection *Connection) (bool, error)

func DeleteConnectionById

func DeleteConnectionById(id string) (bool, error)

func DeleteConsultation

func DeleteConsultation(consultation *Consultation) (bool, error)

func DeleteContainer

func DeleteContainer(container *Container) (bool, error)

func DeleteDoctor

func DeleteDoctor(doctor *Doctor) (bool, error)

func DeleteFile

func DeleteFile(file *File, lang string) (bool, error)

func DeleteForm

func DeleteForm(form *Form) (bool, error)

func DeleteGraph

func DeleteGraph(graph *Graph) (bool, error)

func DeleteHospital

func DeleteHospital(hospital *Hospital) (bool, error)

func DeleteImage

func DeleteImage(image *Image) (bool, error)

func DeleteMachine

func DeleteMachine(machine *Machine) (bool, error)

func DeleteMemoryScoped added in v1.785.11

func DeleteMemoryScoped(owner, userId, name string) (bool, error)

DeleteMemoryScoped removes the caller's memory. The where-clause includes user_id, so a caller can never delete another user's memory.

func DeleteMessage

func DeleteMessage(message *Message) (bool, error)

func DeleteMessagesByChat

func DeleteMessagesByChat(message *Message) (bool, error)

func DeleteModelRoute

func DeleteModelRoute(route *ModelRoute) (bool, error)

func DeleteNode

func DeleteNode(node *Node) (bool, error)

func DeleteOrgSettings added in v1.802.0

func DeleteOrgSettings(s *OrgSettings) (bool, error)

func DeletePatient

func DeletePatient(patient *Patient) (bool, error)

func DeletePod

func DeletePod(pod *Pod) (bool, error)

func DeleteProvider

func DeleteProvider(provider *Provider) (bool, error)

func DeleteRagFile added in v1.790.2

func DeleteRagFile(owner, store, fileID, lang string) error

DeleteRagFile removes all chunks of a file_id from BOTH Hanzo Search and Hanzo Vector for the owner's index. Best-effort per product: a failure to reach one product is returned, but does not prevent attempting the other.

func DeleteRecord

func DeleteRecord(record *Record) (bool, error)

func DeleteScale

func DeleteScale(scale *Scale) (bool, error)

func DeleteScan

func DeleteScan(scan *Scan) (bool, error)

func DeleteSession

func DeleteSession(id string) (bool, error)

func DeleteSessionId

func DeleteSessionId(id string, sessionId string) (bool, error)

func DeleteStore

func DeleteStore(store *Store) (bool, error)

func DeleteTask

func DeleteTask(task *Task) (bool, error)

func DeleteTemplate

func DeleteTemplate(template *Template) (bool, error)

func DeleteTreeFile

func DeleteTreeFile(storeId string, key string, isLeaf bool, lang string) (bool, error)

func DeleteVector

func DeleteVector(vector *Vector) (bool, error)

func DeleteVectorsByFile

func DeleteVectorsByFile(owner string, storeName string, fileKey string) (bool, error)

func DeleteVectorsByStore

func DeleteVectorsByStore(owner string, storeName string) (bool, error)

func DeleteVideo

func DeleteVideo(video *Video) (bool, error)

func DeleteWorkflow

func DeleteWorkflow(workflow *Workflow) (bool, error)

func DeployApplication

func DeployApplication(application *Application, lang string) (bool, error)

func DeployApplicationSync

func DeployApplicationSync(application *Application, lang string) (bool, error)

func DocdbEnabled

func DocdbEnabled() bool

DocdbEnabled returns true if the docdb peer is connected.

func EmbedMemory added in v1.785.11

func EmbedMemory(memory *Memory, lang string)

EmbedMemory fills in Embedding/Dimension best-effort. On failure the memory is stored without an embedding and remains searchable by text.

func EnqueueIngest added in v1.796.2

func EnqueueIngest(ctx context.Context, owner string, req *IngestRequest, lang string) (string, error)

EnqueueIngest submits a long ingest as a durable workflow in the OWNER's namespace (CONTRACT §6) and returns its id immediately — the caller never blocks on the clone/chunk/embed. Returns ErrTasksNotConfigured when no dialer is wired so the handler falls back to inline.

func EnsureCloudUsageTable added in v1.786.0

func EnsureCloudUsageTable(ctx context.Context) error

EnsureCloudUsageTable creates hanzo.cloud_usage if it does not exist, then applies the additive column migrations so a pre-existing table gains the byo/fee_cents/account columns. It is idempotent and only latches success, so a transient datastore outage at boot does not permanently poison later attempts.

func GenAITracer added in v1.790.0

func GenAITracer() trace.Tracer

GenAITracer returns the named tracer for GenAI spans. Safe before init: the global provider is a no-op until initTelemetry latches, and emit callers gate on TelemetryEnabled anyway.

func GenerateWordCloudData

func GenerateWordCloudData(messages []*Message, density int) (string, error)

func GetActivities

func GetActivities(days int, user string, fieldNames []string, lang string) (map[string][]*Activity, error)

func GetAgentClients

func GetAgentClients(agentProviderObj agent.AgentProvider) (*agent.AgentClients, error)

func GetAnswer

func GetAnswer(provider string, question string, lang string) (string, *model.ModelResult, error)

func GetAnswerFake

func GetAnswerFake(provider string, question string, lang string) (string, *model.ModelResult, error)

GetAnswerFake returns a hardcoded string without calling the LLM API, for fast local debugging. Switch between GetAnswer and GetAnswerFake by commenting one of the two call sites (e.g. in task_analyze.go). Replace fakeAnswer below with your real API response (multi-line raw string is fine).

func GetAnswerWithContext

func GetAnswerWithContext(provider string, question string, history []*model.RawMessage, knowledge []*model.RawMessage, prompt string, lang string) (string, *model.ModelResult, error)

func GetApplicationCount

func GetApplicationCount(owner, field, value string) (int64, error)

func GetApplicationFailureReason

func GetApplicationFailureReason(namespace string, lang string) (string, error)

GetApplicationFailureReason returns the failure reason for an application deployment

func GetApplicationStatus

func GetApplicationStatus(owner, name, namespace string, lang string) (string, error)

GetApplicationStatus returns application status as string

func GetArticleCount

func GetArticleCount(owner, field, value string) (int64, error)

func GetAssetCount

func GetAssetCount(owner, field, value string) (int64, error)

func GetCaaseCount

func GetCaaseCount(owner, field, value string) (int64, error)

func GetCachedOrgAutoRouting added in v1.802.0

func GetCachedOrgAutoRouting(owner string) string

GetCachedOrgAutoRouting returns the org's auto-routing preference ("", "enabled", "disabled"). Falls back to unset ("") on any missing row or error, so a lookup failure never changes routing behavior from the global default.

func GetCachedOrgSessionRouting added in v1.802.0

func GetCachedOrgSessionRouting(owner string) string

GetCachedOrgSessionRouting returns the org's default-session-routing preference ("", "enabled", "disabled") from the 60s-cached settings row. Falls back to unset ("") on any missing row or error, so a lookup failure is fail-safe (the caller then folds in the "*" row and the conf default).

func GetChatCount

func GetChatCount(owner string, field string, value string, store string) (int64, error)

func GetConnectionCount

func GetConnectionCount(owner, status, field, value string) (int64, error)

func GetConsultationCount

func GetConsultationCount(owner, field, value string) (int64, error)

func GetContainerCount

func GetContainerCount(owner, field, value string) (int64, error)

func GetDbQuery

func GetDbQuery(owner string, offset, limit int, field, value, sortField, sortOrder string) *dbx.SelectQuery

GetDbQuery builds a SelectQuery with pagination, filtering, and sorting. This replaces the old GetDbSession which returned an xorm.Session.

func GetDocChatAnswer

func GetDocChatAnswer(owner, store string, req *DocChatRequest, lang string) (string, *model.ModelResult, error)

GetDocChatAnswer performs RAG: searches for relevant docs, then generates an answer.

func GetDoctorCount

func GetDoctorCount(owner, field, value string) (int64, error)

func GetFileCount

func GetFileCount(owner, field, value string) (int64, error)

func GetFormCount

func GetFormCount(owner string, field, value string) (int64, error)

func GetGraphCount

func GetGraphCount(owner string, field, value string) (int64, error)

func GetHospitalCount

func GetHospitalCount(owner, field, value string) (int64, error)

func GetImageCount

func GetImageCount(owner, field, value string) (int64, error)

func GetK8sStatus

func GetK8sStatus(lang string) (string, error)

func GetKMSSecret

func GetKMSSecret(name string) (string, error)

GetKMSSecret fetches a secret by name from KMS using the default system project. This is a convenience function for non-provider secrets.

func GetMachineCount

func GetMachineCount(owner, field, value string) (int64, error)

func GetMessageCount

func GetMessageCount(owner string, field string, value string, store string) (int64, error)

func GetModelProviderByProviderKey

func GetModelProviderByProviderKey(providerKey string, lang string) (model.ModelProvider, error)

GetModelProviderByProviderKey retrieves both the provider and its model provider by API key

func GetModelRouteCount

func GetModelRouteCount(owner, field, value string) (int64, error)

func GetNearMessageCount

func GetNearMessageCount(user string, limitMinutes int) (int, error)

func GetNodeCount

func GetNodeCount(owner, field, value string) (int64, error)

func GetOrgKMSSecret

func GetOrgKMSSecret(name string, orgProjectID string) (string, error)

GetOrgKMSSecret fetches a secret scoped to an organization's KMS project.

func GetPatientCount

func GetPatientCount(owner, field, value string) (int64, error)

func GetPodCount

func GetPodCount(owner, field, value string) (int64, error)

func GetProviderCount

func GetProviderCount(owner, storeName, field, value string) (int64, error)

func GetRecentRawMessages

func GetRecentRawMessages(chat string, createdTime string, memoryLimit int) ([]*model.RawMessage, error)

func GetRecordCount

func GetRecordCount(owner, field, value string) (int64, error)

func GetRefinedQuestion

func GetRefinedQuestion(prompt string, knowledge string, question string) string

func GetScaleCount

func GetScaleCount(owner string, field, value string) (int64, error)

func GetScanCount

func GetScanCount(owner, field, value string) (int64, error)

func GetSearchIndexName

func GetSearchIndexName(owner, store string) string

GetSearchIndexName returns the Hanzo Search index name for a given owner/store.

func GetSessionCount

func GetSessionCount(owner, field, value string) (int64, error)

func GetStoreCount

func GetStoreCount(name, field, value string) (int64, error)

func GetTaskCount

func GetTaskCount(owner string, field, value string) (int64, error)

func GetTaskEffectiveScale

func GetTaskEffectiveScale(task *Task) (string, error)

GetTaskEffectiveScale returns rubric text: from referenced Scale.Text when Task.Scale is set.

func GetTemplateCount

func GetTemplateCount(owner, field, value string) (int64, error)

func GetTwoActiveBlockchainProvider

func GetTwoActiveBlockchainProvider(owner string) (*Provider, *Provider, error)

func GetURL

func GetURL(namespace string, lang string) (string, error)

GetURL retrieves the access URL for an application

func GetUsers

func GetUsers(storeName, user string) ([]string, error)

func GetVectorCount

func GetVectorCount(owner string, storeName string, field string, value string) (int64, error)

func GetVideoCount

func GetVideoCount(owner string, field string, value string) (int64, error)

func GetWecomBotTokenAndKey

func GetWecomBotTokenAndKey(botID string) (string, string, error)

func GetWorkflowCount

func GetWorkflowCount(owner string, field, value string) (int64, error)

func GetZapNode

func GetZapNode() *zap.Node

GetZapNode returns the ZAP node for handler registration. Used by controllers package to register service handlers.

func IndexDocuments

func IndexDocuments(owner, store string, req *DocIndexRequest, lang string) (int, error)

IndexDocuments is the single ingest fan-out: it writes every document to BOTH Hanzo Search (keyword) AND Hanzo Vector (semantic) under the per-tenant index {owner}-{store}-docs — the EXACT index SearchDocuments (and therefore /v1/chat retrieval) reads. Keyword indexing is authoritative; semantic indexing is best-effort so a missing embedding provider never drops the document.

func IngestStoreStorage added in v1.786.0

func IngestStoreStorage(store *Store, prefix, lang string) (int, int, error)

IngestStoreStorage lists a store's backing object storage (Hanzo S3 / IAM provider) under an optional prefix and ingests each supported file into the unified Vector+Search index. Shared by RefreshStoreVectors (whole store) and the source:"s3" ingest path (prefix-scoped). Ingestion is additive and idempotent (deterministic chunk IDs); it does NOT wipe the index, so docs from other sources (crawl, framework) in the same store survive a refresh. Returns (filesIngested, documentsIndexed).

func InitAdapter

func InitAdapter()

func InitCleanupChats

func InitCleanupChats()

func InitCommitRecordsTask

func InitCommitRecordsTask()

func InitConfig

func InitConfig()

func InitDatastore added in v1.789.1

func InitDatastore()

InitDatastore opens the ClickHouse connection that backs the usage + observability ledgers. Opt-in via DATASTORE_ADDR (host:port of the native port, default 9000). Non-fatal and asynchronous: a transient datastore outage at boot must never take down the cloud process, so it retries in the background and only latches ready once a Ping succeeds. Until then DatastoreEnabled() reports false and the ledger surfaces an honest "unavailable" instead of blocking boot.

Config (all from env / KMS-injected secrets, never hard-coded):

DATASTORE_ADDR      host:9000 of the datastore native port (enables the ledger)
DATASTORE_DB        database (default "hanzo")
DATASTORE_USER      user     (default "default")
DATASTORE_PASSWORD  password (KMS-backed secret)

func InitDb

func InitDb()

func InitFlag

func InitFlag()

func InitMessageTransactionRetry

func InitMessageTransactionRetry()

func InitScanJobProcessor

func InitScanJobProcessor()

InitScanJobProcessor initializes the scan job processor with a cron job

func InitStoreCount

func InitStoreCount()

func InitTelemetry added in v1.790.0

func InitTelemetry()

InitTelemetry opens the OTLP trace exporter that emits OTel GenAI spans to o11y. Opt-in via OTEL_EXPORTER_OTLP_ENDPOINT (or the traces-specific variant). Non-fatal and asynchronous: a collector outage at boot must never take down the cloud process, so it builds in the background and only latches ready once the provider is set. Until then TelemetryEnabled() reports false and the emit path is skipped. Runs identically in cmd/aid and the embedded cloud binary.

func InitZap

func InitZap()

── Initialization ────────────────────────────────────────────────────── InitZap starts the ZAP node and connects to KV and SQL peers.

func InvalidateProviderNameCache added in v1.790.5

func InvalidateProviderNameCache(name string)

InvalidateProviderNameCache evicts a provider (by admin name) from the hot-path resolution caches so a mutation — e.g. an admin enable/disable or set-primary via /v1/admin/providers — takes effect IMMEDIATELY instead of after the 60s TTL. The global (admin) entry is keyed by name; per-org BYOK entries are keyed "org/name", so all org overrides of that provider name are dropped too. Passing an empty name flushes everything (used when a bulk change touched many records).

func IsAdmin

func IsAdmin(user *iam.User) bool

func IsAsyncIngestSource added in v1.796.2

func IsAsyncIngestSource(source string) bool

IsAsyncIngestSource reports whether a source runs as a durable workflow (long) vs inline (fast). Upload/empty = inline; github/crawl/s3 = workflow.

func IsCrawl4AIAvailable

func IsCrawl4AIAvailable() bool

IsCrawl4AIAvailable checks whether the Hanzo Crawl service is reachable.

func IsCrawlStorageConfigured

func IsCrawlStorageConfigured() bool

IsCrawlStorageConfigured returns true if the crawl storage credentials are set.

func IsDoctor

func IsDoctor(user *iam.User) bool

func IsPatient

func IsPatient(user *iam.User) bool

func IsPersonalBillingOrg added in v1.785.10

func IsPersonalBillingOrg(owner string) bool

IsPersonalBillingOrg reports whether members of org are billed individually (per-user) rather than sharing one org-pooled balance.

func IsSessionDuplicated

func IsSessionDuplicated(id string, sessionId string) (bool, error)

func JSONScan

func JSONScan(dst interface{}, src interface{}) error

JSONScan is a helper for fields that are scanned-from-JSON-text via a pointer-receiver Scan method. Use it inside per-type Scanner impls so they all share the same string/bytes/nil handling.

func JSONValue

func JSONValue(v interface{}) (driver.Value, error)

JSONValue marshals v as a JSON string for driver.Valuer impls.

func MakeMsgResponse

func MakeMsgResponse(content string, streamId string) (string, error)

func MetricsHandler added in v1.800.8

func MetricsHandler() http.Handler

MetricsHandler returns the Prometheus text-exposition handler for GET /v1/metrics, bound to the SAME DefaultRegistry the metric vars above register into (the package-level metric.NewGaugeVec / NewHistogramVec helpers delegate to DefaultRegistry). This must NOT use metric.Handler(): that convenience wrapper binds a fresh, throwaway registry, so it exposes an EMPTY scrape regardless of what has been recorded — the endpoint would answer 200 with a zero-length body forever. Binding DefaultRegistry mirrors GetPrometheusInfo, which reads the same registry: one registry, one source of truth.

func ModelProviderUsable added in v1.790.5

func ModelProviderUsable(p *Provider) bool

ModelProviderUsable reports whether a Model-category provider is currently eligible to serve traffic. A Model provider is usable only when its admin toggle (State) is "Active" — a "Disabled"/paused provider is treated as unavailable so the /v1/admin/providers toggle actually takes effect on the hot path. Non-Model providers (Storage, Embedding config records, etc.) are governed by their own callers and are not affected by this gate.

This is the ONE place the "is this provider allowed to route?" policy lives: GetModelProviderByName (the completion/embeddings/image chokepoint) and GetModelProviderByNameForOrg (the per-org BYOK seam) both consult it, so a disabled provider is uniformly unavailable to every caller (chat, anthropic, embeddings, message_answer, widget, failover) without duplicating the check.

func NewMemoryName added in v1.785.11

func NewMemoryName() string

NewMemoryName mints a unique per-owner memory name.

func NormalizeMemoryKind added in v1.785.11

func NormalizeMemoryKind(kind string) string

NormalizeMemoryKind returns a valid kind, defaulting unknown/empty to "user".

func ParseAndValidateJWT added in v1.785.11

func ParseAndValidateJWT(token string) (*iam.Claims, error)

ParseAndValidateJWT verifies the token signature via IAM AND enforces the cloud-api issuer/audience policy. This is the ONE JWT entry point for cloud-api request auth — handlers and filters must never call iam.ParseJwtToken directly, so iss/aud are checked on every JWT auth path.

func PopulateStoreCounts

func PopulateStoreCounts(stores []*Store) error

func PrepareTextToSpeech

func PrepareTextToSpeech(storeId, providerId, messageId, text string, lang string) (*Message, *Chat, tts.TextToSpeechProvider, context.Context, error)

PrepareTextToSpeech prepares the text-to-speech conversion

func ProviderKeyPresent added in v1.790.5

func ProviderKeyPresent(provider *Provider) bool

ProviderKeyPresent reports whether a provider's ClientSecret resolves to a non-empty value — WITHOUT ever returning the value itself. It resolves on a COPY so the caller's provider is never mutated (the raw/resolved key must not leak into a response object). A "kms://…" reference that resolves to a real secret (via env-first or a live KMS fetch) counts as present; an empty or unresolved reference counts as absent. This is the ONLY key signal the admin management view is allowed to expose (keyPresent boolean).

Fail-closed for the admin view: if KMS is not configured, a "kms://…" ref cannot be confirmed and is reported as NOT present (so the operator sees the key is unavailable rather than a false-positive). A plaintext/non-kms value (dev only) is reported present when non-empty.

func QueryRecord

func QueryRecord(id string, lang string) (string, error)

func QueryRecordSecond

func QueryRecordSecond(id string, lang string) (string, error)

func RedactClaimsSecrets added in v1.785.11

func RedactClaimsSecrets(c *iam.Claims)

RedactClaimsSecrets scrubs both the embedded user and the claims-level token material from an IAM claims object before it is returned to a client.

func RedactUserSecrets added in v1.785.11

func RedactUserSecrets(u *iam.User)

RedactUserSecrets scrubs every credential-bearing field on an IAM user before it is serialized to a client. This is the ONE place cloud-api scrubs a user; the default read path (e.g. /v1/get-account) must call it so a browser never receives the password hash/salt, MFA seed, recovery codes, access/refresh tokens, or any other credential. It is an ALLOWLIST projection over string and []string fields (redactNonExposableStrings) so a future secret field is fail-secure, plus explicit clearing of the credential-bearing STRUCT slices the string projection cannot reach.

func RefineMessageFiles

func RefineMessageFiles(message *Message, origin string, lang string) error

func RefreshFileVectors

func RefreshFileVectors(file *File, lang string) (bool, error)

func RefreshMcpTools

func RefreshMcpTools(provider *Provider) error

func RefreshStoreVectors

func RefreshStoreVectors(store *Store, lang string) (bool, error)

RefreshStoreVectors re-ingests every file in the store's object storage into the unified Vector+Search index — the SAME index /v1/chat retrieval reads. It NO LONGER writes the deprecated SQL `vector` table (see store_ingest.go / vector_embedding.go); this is the crossed-wire fix, so an uploaded store file actually powers chat RAG. Re-ingest is additive + idempotent (deterministic chunk IDs), so it preserves docs from other sources in the same store index.

func ResolveCloudUsageWindow added in v1.786.0

func ResolveCloudUsageWindow(rangeLabel, startStr, endStr string, now time.Time) (start, end time.Time, interval string, err error)

ResolveCloudUsageWindow maps a range label (plus optional custom start/end) to an absolute [start, end) window and a bucket interval. Pure: `now` is injected so the test is deterministic.

func ResolveProviderSecret

func ResolveProviderSecret(provider *Provider) error

── Public API ────────────────────────────────────────────────────────────── ResolveProviderSecret resolves KMS-backed secret fields for a provider. If KMS is configured and provider fields start with "kms://", each secret is fetched from KMS. Otherwise, DB values are used as-is.

Supported provider fields:

  • ClientSecret
  • UserKey
  • SignKey

Convention: store "kms://SECRET_NAME" in these fields in the database. At runtime, they are resolved to actual secret values.

Multi-tenant scoping:

  • Admin-owned providers use the default KMS_PROJECT_ID
  • Org-owned providers can set "kms-project:{projectId}" in ConfigText to scope secrets to the org's own KMS project

func ScanAssetsFromProvider

func ScanAssetsFromProvider(owner string, providerName string) (bool, error)

func ScanNeedCommitRecords

func ScanNeedCommitRecords()

ScanNeedCommitRecords scans the database table for records that need to be committed but have not yet been committed.

func SetDefaultVodClient

func SetDefaultVodClient(lang string) error

func SetIngestDialer added in v1.796.4

func SetIngestDialer(d func(org string) (tasksclient.Client, error))

SetIngestDialer injects the per-org dialer. Called once at boot by cloud.

func SetPrimaryModelProvider added in v1.790.5

func SetPrimaryModelProvider(name string) error

SetPrimaryModelProvider makes `name` the sole primary (is_default=true) among admin-owned Model providers and clears is_default on every other, atomically and with NO window in which zero primaries exist (see primaryRepointSteps). Each step is a single set-wide UPDATE — never a per-row loop. The caller validates the target exists and State=="Active" before calling.

func ShutdownTelemetry added in v1.790.0

func ShutdownTelemetry(ctx context.Context)

ShutdownTelemetry flushes buffered spans and stops the exporter. Non-fatal and a no-op when telemetry was never enabled; the atomic gate establishes the happens-before with initTelemetry, so telemetryProvider is safely observed.

func SinglePodReplicaHint added in v1.785.11

func SinglePodReplicaHint() (count int, ok bool)

SinglePodReplicaHint parses the optional CLOUD_API_REPLICAS deployment hint, which the operator stamps with the replica count it deploys. ok=false when the hint is unset or unparseable (the invariant is then logged, not enforced). A returned count > 1 means the in-pod ledger is unsafe and the process must refuse to start — the boot path (bootstrap.go) treats >1 as fatal.

func SplitLastN

func SplitLastN(s, sep string, n int) []string

func StopZap

func StopZap()

StopZap gracefully shuts down the ZAP node.

func StoreProviderSecret added in v1.786.0

func StoreProviderSecret(name, value string) (string, error)

StoreProviderSecret securely stores a tenant-supplied (BYOK) provider key in KMS under the default project and returns the "kms://NAME" reference to persist in the provider record — so a raw key NEVER lands in the database as plaintext. FAILS CLOSED: if KMS is not configured, it errors rather than letting the caller store the raw key. The secret name is caller-namespaced (e.g. by org) to avoid cross-tenant collision.

func SyncDefaultProvidersToStore

func SyncDefaultProvidersToStore(store *Store) error

func SyncDockerContainers

func SyncDockerContainers(owner string) (bool, error)

func SyncImagesCloud

func SyncImagesCloud(owner string, lang string) (bool, error)

func SyncKubernetesPods

func SyncKubernetesPods(owner string) (bool, error)

func SyncMachinesCloud

func SyncMachinesCloud(owner string, lang string) (bool, error)

func TelemetryEnabled added in v1.790.0

func TelemetryEnabled() bool

TelemetryEnabled reports whether the OTLP trace exporter is live. The emit path gates on it to skip span construction entirely when telemetry is off.

func UndeployApplication

func UndeployApplication(owner, name, namespace string, lang string) (bool, error)

func UndeployApplicationSync

func UndeployApplicationSync(owner, name, namespace string, lang string) (bool, error)

UndeployApplicationSync undeploys application and waits for it to be completely removed

func UpdateApplication

func UpdateApplication(id string, application *Application, lang string) (bool, error)

func UpdateApplicationStatus

func UpdateApplicationStatus(owner string, name string, status string, lang string) error

func UpdateArticle

func UpdateArticle(id string, article *Article) (bool, error)

func UpdateAsset

func UpdateAsset(id string, asset *Asset) (bool, error)

func UpdateCaase

func UpdateCaase(id string, caase *Caase) (bool, error)

func UpdateChat

func UpdateChat(id string, chat *Chat) (bool, error)

func UpdateChatStats

func UpdateChatStats(chat *Chat, ttsResult *tts.TextToSpeechResult) error

func UpdateConnection

func UpdateConnection(id string, connection *Connection, columns ...string) (bool, error)

func UpdateConsultation

func UpdateConsultation(id string, consultation *Consultation) (bool, error)

func UpdateContainer

func UpdateContainer(id string, container *Container, lang string) (bool, error)

func UpdateDoctor

func UpdateDoctor(id string, doctor *Doctor) (bool, error)

func UpdateFile

func UpdateFile(id string, file *File) (bool, error)

func UpdateFilesStatusByStore

func UpdateFilesStatusByStore(owner string, storeName string, status FileStatus) error

func UpdateForm

func UpdateForm(id string, form *Form, lang string) (bool, error)

func UpdateGraph

func UpdateGraph(id string, graph *Graph) (bool, error)

func UpdateHospital

func UpdateHospital(id string, hospital *Hospital) (bool, error)

func UpdateImage

func UpdateImage(id string, image *Image) (bool, error)

func UpdateMachine

func UpdateMachine(id string, machine *Machine) (bool, error)

func UpdateMemoryScoped added in v1.785.11

func UpdateMemoryScoped(owner, userId, name string, patch *Memory, lang string) (bool, error)

UpdateMemoryScoped applies a patch to the caller's memory. Returns false if the memory does not exist or is not owned by this user. When the content changes the embedding is recomputed (best-effort).

func UpdateMessage

func UpdateMessage(id string, message *Message, isHitOnly bool) (bool, error)

func UpdateModelRoute

func UpdateModelRoute(owner string, modelName string, route *ModelRoute) (bool, error)

func UpdateNode

func UpdateNode(id string, node *Node) (bool, error)

func UpdateOrgSettings added in v1.802.0

func UpdateOrgSettings(owner string, s *OrgSettings) (bool, error)

func UpdatePatient

func UpdatePatient(id string, patient *Patient) (bool, error)

func UpdatePod

func UpdatePod(id string, pod *Pod, lang string) (bool, error)

func UpdateProvider

func UpdateProvider(id string, provider *Provider) (bool, error)

func UpdateRecord

func UpdateRecord(id string, record *Record, lang string) (bool, error)

func UpdateRecordFields

func UpdateRecordFields(id string, fields map[string]interface{}, lang string) (bool, error)

func UpdateRecordInternal

func UpdateRecordInternal(id int, record Record) error

func UpdateScale

func UpdateScale(id string, scale *Scale) (bool, error)

func UpdateScan

func UpdateScan(id string, scan *Scan) (bool, error)

func UpdateSession

func UpdateSession(id string, session *Session) (bool, error)

func UpdateStore

func UpdateStore(id string, store *Store) (bool, error)

func UpdateTask

func UpdateTask(id string, task *Task) (bool, error)

func UpdateTemplate

func UpdateTemplate(id string, template *Template) (bool, error)

func UpdateTreeFile

func UpdateTreeFile(storeId string, key string, file *TreeFile) bool

func UpdateVector

func UpdateVector(id string, vector *Vector, lang string) (bool, error)

func UpdateVideo

func UpdateVideo(id string, video *Video) (bool, error)

func UpdateWorkflow

func UpdateWorkflow(id string, workflow *Workflow, lang string) (bool, error)

func UploadFileToStorageSafe

func UploadFileToStorageSafe(user string, tag string, parent string, fullFilePath string, fileBytes []byte) (string, error)

func ValidateJWTIssAud added in v1.785.11

func ValidateJWTIssAud(token string) error

ValidateJWTIssAud enforces the cloud-api issuer/audience policy on a token string. Call AFTER the signature has been verified (the claims are read from the raw payload, so a forged unsigned token would still be caught here on iss/aud, but signature verification remains mandatory upstream).

func ValidateTransactionForMessage

func ValidateTransactionForMessage(message *Message) error

ValidateTransactionForMessage validates that the user has sufficient balance before committing an expensive AI generation. Checks balance via Commerce.

func WidgetKeyOwner added in v1.800.4

func WidgetKeyOwner(token string) string

WidgetKeyOwner resolves a widget key (hz_*) to the IAM org it bills and whose data it may read. The owner is taken from the widget KEY itself — a per-tenant credential — via the WIDGET_KEY_OWNERS config (KMS first, env fallback) mapping key->owner. An unmapped key falls back to WIDGET_DEFAULT_OWNER (a single configured tenant), NEVER a header/Origin-derived org (that trust let widget callers read another tenant's RAG store). An empty return means the key is unattributable: callers MUST fail secure — refuse the request rather than spend the shared upstream for free, and read no tenant data.

This is the ONE resolver shared by the controllers (RAG tenant isolation + per-org billing of widget inference) and the router balance gate, so a widget key means exactly the same org everywhere.

func WriteCloseMessage

func WriteCloseMessage(guacSession *guacamole.Session, mode string, code int, msg string)

func ZapDocdbExec

func ZapDocdbExec(ctx context.Context, sql string, args ...interface{}) error

ZapDocdbExec executes a write query on DocDB via native ZAP binary.

func ZapDocdbQuery

func ZapDocdbQuery(ctx context.Context, sql string, args ...interface{}) ([]map[string]interface{}, error)

── DocDB client (native ZAP-to-ZAP → FerretDB) ───────────────────────── ZapDocdbQuery executes a read query on DocDB via native ZAP binary.

func ZapEnabled

func ZapEnabled() bool

ZapEnabled returns true if the ZAP node is running.

func ZapKVDel

func ZapKVDel(ctx context.Context, key string) error

ZapKVDel deletes a key via native ZAP binary.

func ZapKVGet

func ZapKVGet(ctx context.Context, key string) (string, error)

── KV client (native ZAP-to-ZAP) ────────────────────────────────────── ZapKVGet fetches a key from KV via native ZAP binary.

func ZapKVSet

func ZapKVSet(ctx context.Context, key, value string) error

ZapKVSet stores a key/value pair via native ZAP binary.

func ZapKVSetEx

func ZapKVSetEx(ctx context.Context, key, value string, ttlSeconds int) error

ZapKVSetEx stores a key/value with TTL via native ZAP binary.

func ZapSQLExec

func ZapSQLExec(ctx context.Context, sql string, args ...interface{}) error

ZapSQLExec executes a write query via native ZAP binary.

func ZapSQLQuery

func ZapSQLQuery(ctx context.Context, sql string, args ...interface{}) ([]map[string]interface{}, error)

── SQL client (native ZAP-to-ZAP) ───────────────────────────────────── ZapSQLQuery executes a read query via native ZAP binary.

Types

type Activity

type Activity struct {
	Date       string `json:"date"`
	FieldCount map[string]int
}

type Adapter

type Adapter struct {
	DbName string
	// contains filtered or unexported fields
}

Adapter represents the database adapter for storage.

func NewAdapter

func NewAdapter(driverName string, dataSourceName string) *Adapter

NewAdapter is the constructor for Adapter.

func NewAdapterWithDbName

func NewAdapterWithDbName(driverName string, dataSourceName string, dbName string) *Adapter

func (*Adapter) CreateDatabase

func (a *Adapter) CreateDatabase() error

func (*Adapter) RawDB

func (a *Adapter) RawDB() *sql.DB

RawDB returns the underlying *sql.DB for direct access when needed.

type AlibabaCloudParser

type AlibabaCloudParser struct{}

AlibabaCloudParser implements CloudParser for Alibaba Cloud

func (*AlibabaCloudParser) ScanAssets

func (p *AlibabaCloudParser) ScanAssets(owner string, provider *Provider) ([]*Asset, error)

ScanAssets scans all resources from Alibaba Cloud

type Application

type Application struct {
	Owner              string                    `db:"pk" json:"owner"`
	Name               string                    `db:"pk" json:"name"`
	CreatedTime        string                    `json:"createdTime"`
	UpdatedTime        string                    `json:"updatedTime"`
	DisplayName        string                    `json:"displayName"`
	Description        string                    `json:"description"`
	Template           string                    `json:"template"` // Reference to Template.Name
	Parameters         string                    `json:"parameters"`
	Manifest           string                    `json:"manifest"`  // Deployment manifest
	Status             string                    `json:"status"`    // Running, Pending, Failed, Not Deployed
	Namespace          string                    `json:"namespace"` // Kubernetes namespace (auto-generated)
	URL                string                    `json:"url"`       // Available service URL
	Details            *ApplicationView          `db:"-" json:"details,omitempty"`
	BasicConfigOptions []applicationConfigOption `json:"basicConfigOptions"`
}

func GetApplication

func GetApplication(id string) (*Application, error)

func GetApplications

func GetApplications(owner string) ([]*Application, error)

func GetPaginationApplications

func GetPaginationApplications(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Application, error)

type ApplicationEvent

type ApplicationEvent struct {
	Name           string `json:"name"`           // Event name
	Type           string `json:"type"`           // Event type: Normal, Warning
	Reason         string `json:"reason"`         // Event reason
	Message        string `json:"message"`        // Event message
	InvolvedObject string `json:"involvedObject"` // Related object
	Source         string `json:"source"`         // Event source
	Count          int    `json:"count"`          // Event occurrence count
	FirstTime      string `json:"firstTime"`      // First occurrence time
	LastTime       string `json:"lastTime"`       // Last occurrence time
}

type ApplicationView

type ApplicationView struct {
	Services    []ServiceDetail    `json:"services"`
	Credentials []EnvVariable      `json:"credentials"`
	Deployments []DeploymentDetail `json:"deployments"`
	Events      []ApplicationEvent `json:"events"`
	Status      string             `json:"status"`
	CreatedTime string             `json:"createdTime"`
	Namespace   string             `json:"namespace"`
	Metrics     *ResourceMetrics   `json:"metrics,omitempty"`
}

func GetApplicationView

func GetApplicationView(namespace string, lang string) (*ApplicationView, error)

GetApplicationView retrieves application view from cache with fallback

type Article

type Article struct {
	Owner       string     `db:"pk" json:"owner"`
	Name        string     `db:"pk" json:"name"`
	CreatedTime string     `json:"createdTime"`
	DisplayName string     `json:"displayName"`
	Workflow    string     `json:"workflow"`
	Type        string     `json:"type"`
	Text        string     `json:"text"`
	Content     []*Block   `json:"content"`
	Glossary    StringList `json:"glossary"`
}

func GetArticle

func GetArticle(id string) (*Article, error)

func GetArticles

func GetArticles(owner string) ([]*Article, error)

func GetGlobalArticles

func GetGlobalArticles() ([]*Article, error)

func GetMaskedArticle

func GetMaskedArticle(article *Article, isMaskEnabled bool) *Article

func GetMaskedArticles

func GetMaskedArticles(articles []*Article, isMaskEnabled bool) []*Article

func GetPaginationArticles

func GetPaginationArticles(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Article, error)

func (*Article) GetId

func (article *Article) GetId() string

type Asset

type Asset struct {
	Owner       string `db:"pk" json:"owner"`
	Name        string `db:"pk" json:"name"`
	CreatedTime string `json:"createdTime"`
	UpdatedTime string `json:"updatedTime"`
	DisplayName string `json:"displayName"`
	Provider    string `json:"provider"`
	Id          string `json:"id"`
	Type        string `json:"type"`
	Region      string `json:"region"`
	Zone        string `json:"zone"`
	State       string `json:"state"`
	Tag         string `json:"tag"`
	Username    string `json:"username"`
	Password    string `json:"password"`
	Properties  string `json:"properties"`
}

func GetAsset

func GetAsset(id string) (*Asset, error)

func GetAssets

func GetAssets(owner string) ([]*Asset, error)

func GetMaskedAsset

func GetMaskedAsset(asset *Asset, isMaskEnabled bool) *Asset

func GetMaskedAssets

func GetMaskedAssets(assets []*Asset, isMaskEnabled bool) []*Asset

func GetPaginationAssets

func GetPaginationAssets(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Asset, error)

func (*Asset) GetId

func (asset *Asset) GetId() string

func (*Asset) GetScanTarget

func (asset *Asset) GetScanTarget() (string, error)

type BalanceExemptSet added in v1.785.11

type BalanceExemptSet struct {
	// contains filtered or unexported fields
}

BalanceExemptSet matches the BALANCE_EXEMPT_USERS allowlist with the SAME granularity in every caller — the router balance gate and the controller backstop — so the two can never drift. Entry semantics:

  • "owner/name" (contains '/') → exempts ONLY that exact billing subject, an individually-named service account (e.g. "admin/hanzo-cloud").
  • "owner" (no '/') → exempts the WHOLE org.

This is the fix for the prior gate behavior, which collapsed EVERY entry to its owner-part: "hanzo/z" wrongly exempted ALL of org "hanzo", so every catch-all signup fail-OPENed during a Commerce outage. The controller already matched per-user-exact OR per-org (openai_api.go); the gate now matches identically via this one shared definition.

func BalanceExempt added in v1.785.11

func BalanceExempt() *BalanceExemptSet

BalanceExempt returns the process exemption set parsed from BALANCE_EXEMPT_USERS. The env is tiny and fixed at deploy, so it is parsed per call; hot-path callers may keep the parsed set (the router gate does, at init).

func ParseBalanceExempt added in v1.785.11

func ParseBalanceExempt(raw string) *BalanceExemptSet

ParseBalanceExempt parses a comma-separated BALANCE_EXEMPT_USERS list into the exact-subject and whole-org sets. Entries are lowercased to match the casing of BillingSubject / IAM owner slugs.

func (*BalanceExemptSet) Matches added in v1.785.11

func (s *BalanceExemptSet) Matches(owner, name string) bool

Matches reports whether the (owner, name) identity is exempt: the exact "owner/name" subject or the bare org.

func (*BalanceExemptSet) MatchesKey added in v1.785.11

func (s *BalanceExemptSet) MatchesKey(userKey, org string) bool

MatchesKey reports whether the "owner/name" userKey (exact) or its org is exempt — mirroring the controller's `entry == userKey || entry == orgKey`.

type BalanceLedger added in v1.785.11

type BalanceLedger struct {
	// contains filtered or unexported fields
}

BalanceLedger is the in-pod source of truth for a billing subject's SPENDABLE balance: the last-known Commerce balance MINUS outstanding reservations for in-flight requests. The router balance gate reserves an estimated (upper-bound) cost before a paid request runs; the debit path settles the real cost after.

Reserve and Settle are atomic under one mutex, so concurrent requests for the same subject can neither double-spend the same balance nor drive it negative — each in-flight request's worst-case cost is held until it settles. Applying the actual spend locally on Settle also closes the stale-cache window: a balance read that is up to TTL old no longer over-grants, because every settled request has already decremented the cached balance.

func NewBalanceLedger added in v1.785.11

func NewBalanceLedger(ttl time.Duration) *BalanceLedger

NewBalanceLedger creates an empty ledger with the given freshness TTL.

func (*BalanceLedger) Available added in v1.785.11

func (l *BalanceLedger) Available(subject string) (cents int64, known bool)

Available returns balance - reserved for a subject, and whether the subject is known. A cold subject returns (0, false).

func (*BalanceLedger) EvictIdle added in v1.785.11

func (l *BalanceLedger) EvictIdle(maxIdle time.Duration)

EvictIdle removes entries whose balance is older than maxIdle AND have no outstanding reservations, to bound memory. An entry with live holds is never evicted (that would lose an in-flight reservation).

func (*BalanceLedger) Reserve added in v1.785.11

func (l *BalanceLedger) Reserve(subject string, estCents int64) bool

Reserve atomically holds estCents against the subject's available balance. It records the hold and returns true ONLY if the subject is known AND available (balance - reserved) >= estCents. A cold subject (no cached balance) cannot be reserved against — the caller must SetBalance first (fetch from Commerce), so the gate never reserves blind. estCents <= 0 holds nothing but still requires a known, non-overdrawn balance.

func (*BalanceLedger) SetBalance added in v1.785.11

func (l *BalanceLedger) SetBalance(subject string, cents int64)

SetBalance records a freshly-fetched Commerce balance for a subject and resets the freshness clock. Outstanding reservations are PRESERVED — a fresh read of the upstream balance does not cancel in-flight holds.

func (*BalanceLedger) Settle added in v1.785.11

func (l *BalanceLedger) Settle(subject string, estCents, actualCents int64)

Settle releases a prior reservation of estCents and applies the actual spend locally (balance -= actualCents) so subsequent reads reflect it immediately, without waiting for the async Commerce refresh. Pass the SAME estCents used at Reserve time. actualCents may be 0 (a failed/empty request that still reserved). Reserved never goes below zero (defensive against a double-settle).

func (*BalanceLedger) Snapshot added in v1.785.11

func (l *BalanceLedger) Snapshot(subject string) (balance, reserved int64, fresh, known bool)

Snapshot returns the cached balance, outstanding reservations, whether the cached balance is fresh (within TTL), and whether the subject is known.

type Block

type Block struct {
	Type   string `json:"type"`
	Text   string `json:"text"`
	TextEn string `json:"textEn"`
	Prompt string `json:"prompt"`
	State  string `json:"state"`
}

type Caase

type Caase struct {
	Owner                        string `db:"pk" json:"owner"`
	Name                         string `db:"pk" json:"name"`
	CreatedTime                  string `json:"createdTime"`
	UpdatedTime                  string `json:"updatedTime"`
	DisplayName                  string `json:"displayName"`
	Symptoms                     string `json:"symptoms"`
	Diagnosis                    string `json:"diagnosis"`
	DiagnosisDate                string `json:"diagnosisDate"`
	Prescription                 string `json:"prescription"`
	FollowUp                     string `json:"followUp"`
	Variation                    bool   `json:"variation"`
	HISInterfaceInfo             string `json:"hisInterfaceInfo"`
	PrimaryCarePhysician         string `json:"primaryCarePhysician"`
	Type                         string `json:"type"`
	PatientName                  string `json:"patientName"`
	DoctorName                   string `json:"doctorName"`
	HospitalName                 string `json:"hospitalName"`
	SpecialistAllianceId         string `json:"specialistAllianceId"`
	IntegratedCareOrganizationId string `json:"integratedCareOrganizationId"`
}

func FilterCaasesByUser

func FilterCaasesByUser(user *iam.User, caases []*Caase) []*Caase

func GetCaase

func GetCaase(id string) (*Caase, error)

func GetCaases

func GetCaases(owner string) ([]*Caase, error)

func GetMaskedCaase

func GetMaskedCaase(caase *Caase, errs ...error) (*Caase, error)

func GetMaskedCaases

func GetMaskedCaases(caases []*Caase, errs ...error) ([]*Caase, error)

func GetPaginationCaases

func GetPaginationCaases(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Caase, error)

type CacheManager

type CacheManager struct {
	// contains filtered or unexported fields
}

func (*CacheManager) Start

func (cm *CacheManager) Start(lang string) error

Start begins the cache manager

func (*CacheManager) Stop

func (cm *CacheManager) Stop()

Stop stops the cache manager

type CachedMetrics

type CachedMetrics struct {
	TotalCPU         resource.Quantity `json:"totalCPU"`
	TotalMemory      resource.Quantity `json:"totalMemory"`
	PodCount         int               `json:"podCount"`
	CPUPercentage    float64           `json:"cpuPercentage"`
	MemoryPercentage float64           `json:"memoryPercentage"`
	LastUpdated      time.Time         `json:"lastUpdated"`
}

type Chat

type Chat struct {
	Owner         string     `db:"pk" json:"owner"`
	Name          string     `db:"pk" json:"name"`
	CreatedTime   string     `json:"createdTime"`
	UpdatedTime   string     `json:"updatedTime"`
	Organization  string     `json:"organization"`
	DisplayName   string     `json:"displayName"`
	Store         string     `json:"store"`
	ModelProvider string     `json:"modelProvider"`
	Category      string     `json:"category"`
	Type          string     `json:"type"`
	User          string     `json:"user"`
	User1         string     `json:"user1"`
	User2         string     `json:"user2"`
	Users         StringList `json:"users"`
	ClientIp      string     `json:"clientIp"`
	UserAgent     string     `json:"userAgent"`
	ClientIpDesc  string     `json:"clientIpDesc"`
	UserAgentDesc string     `json:"userAgentDesc"`
	MessageCount  int        `json:"messageCount"`
	TokenCount    int        `json:"tokenCount"`
	Price         float64    `json:"price"`
	Currency      string     `json:"currency"`
	IsHidden      bool       `json:"isHidden"`
	IsDeleted     bool       `json:"isDeleted"`
	NeedTitle     bool       `json:"needTitle"`
}

func FilterChatsByTimeRange

func FilterChatsByTimeRange(chats []*Chat, startTime, endTime string) []*Chat

func GetChat

func GetChat(id string) (*Chat, error)

func GetChats

func GetChats(owner string, storeName string, user string) ([]*Chat, error)

func GetGlobalChats

func GetGlobalChats() ([]*Chat, error)

func GetPaginationChats

func GetPaginationChats(owner string, offset, limit int, field, value, sortField, sortOrder string, store string) ([]*Chat, error)

func (*Chat) GetId

func (chat *Chat) GetId() string

type CloudParser

type CloudParser interface {
	// ScanAssets scans all resources from the cloud provider and returns them as Asset objects
	ScanAssets(owner string, provider *Provider) ([]*Asset, error)
}

CloudParser defines the interface for cloud resource scanning

func NewCloudParser

func NewCloudParser(providerType string) (CloudParser, error)

NewCloudParser creates a new CloudParser instance based on the provider type

type CloudUsageActivity added in v1.786.0

type CloudUsageActivity struct {
	Items  []CloudUsageActivityRow `json:"items"`
	Limit  int                     `json:"limit"`
	Offset int                     `json:"offset"`
	Total  int64                   `json:"total"`
	Type   string                  `json:"type"`
}

type CloudUsageActivityRow added in v1.786.0

type CloudUsageActivityRow struct {
	Time             string `json:"time"` // RFC3339 (UTC)
	Model            string `json:"model"`
	Provider         string `json:"provider"`
	Type             string `json:"type"` // "inference" — the only event class in this ledger
	Status           string `json:"status"`
	Tokens           int64  `json:"tokens"`
	PromptTokens     int64  `json:"promptTokens"`
	CompletionTokens int64  `json:"completionTokens"`
	CostCents        int64  `json:"costCents"`
	Stream           bool   `json:"stream"`
	Premium          bool   `json:"premium"`
	RequestID        string `json:"requestId"`
	Org              string `json:"org"`
	User             string `json:"user"`
}

type CloudUsageByModel added in v1.786.0

type CloudUsageByModel struct {
	Items      []CloudUsageModelSpend `json:"items"`
	Other      *CloudUsageModelOther  `json:"other"`
	TotalCents int64                  `json:"totalCents"`
}

type CloudUsageDelta added in v1.786.0

type CloudUsageDelta struct {
	Current int64    `json:"current"`
	Prior   int64    `json:"prior"`
	Pct     *float64 `json:"pct"`
}

CloudUsageDelta is one card's "vs prior period" comparison. Pct is nil when the prior period had no basis (prior == 0), so the client shows "—"/"new" instead of a fabricated ratio.

type CloudUsageModelOther added in v1.786.0

type CloudUsageModelOther struct {
	SpendCents int64   `json:"spendCents"`
	Tokens     int64   `json:"tokens"`
	Requests   int64   `json:"requests"`
	Pct        float64 `json:"pct"`
	ModelCount int     `json:"modelCount"`
}

type CloudUsageModelSpend added in v1.786.0

type CloudUsageModelSpend struct {
	Model      string  `json:"model"`
	Provider   string  `json:"provider"`
	SpendCents int64   `json:"spendCents"`
	Tokens     int64   `json:"tokens"`
	Requests   int64   `json:"requests"`
	Pct        float64 `json:"pct"` // share of total spend, 0..100
}

type CloudUsageOverview added in v1.786.0

type CloudUsageOverview struct {
	Range    string                     `json:"range"`
	Start    string                     `json:"start"` // RFC3339 (UTC)
	End      string                     `json:"end"`   // RFC3339 (UTC)
	Interval string                     `json:"interval"`
	Scope    CloudUsageScope            `json:"scope"`
	Totals   CloudUsageTotals           `json:"totals"`
	Deltas   map[string]CloudUsageDelta `json:"deltas"` // keys: tokens, spendCents, requests, models
	Series   []CloudUsageSeriesPoint    `json:"series"`
	ByModel  CloudUsageByModel          `json:"byModel"`
	Activity CloudUsageActivity         `json:"activity"`
}

func GetCloudUsageOverview added in v1.786.0

func GetCloudUsageOverview(ctx context.Context, p CloudUsageParams) (*CloudUsageOverview, error)

GetCloudUsageOverview runs the aggregate queries against the ClickHouse ledger and assembles the Overview. Errors are surfaced (not swallowed) so the client can show an honest "unavailable" state rather than fabricated zeros.

type CloudUsageParams added in v1.786.0

type CloudUsageParams struct {
	RangeLabel     string // echoed back ("24h"|"7d"|"30d"|"custom")
	Start          time.Time
	End            time.Time
	Interval       string // "hour" | "day" — time-series bucket width
	Org            string // organization slug; ignored when AllOrgs is true
	AllOrgs        bool   // global-admin all-orgs view (no organization filter)
	TopModels      int    // spend-by-model: keep top N, fold the rest into "other"
	ActivityType   string // "all" | "inference" (others → honest-empty feed)
	ActivityLimit  int
	ActivityOffset int
}

CloudUsageParams is the resolved, already-authorized query for one Overview. The controller fills Org/AllOrgs from the session (a tenant is pinned to its own org; a global admin may target one org or omit for all orgs). Start/End/ Interval come from ResolveCloudUsageWindow. The only field that reaches SQL un-parameterized is Interval, a closed server-chosen enum ("hour"|"day"); Org is always passed as a bound parameter.

type CloudUsageScope added in v1.786.0

type CloudUsageScope struct {
	Org     string `json:"org"` // "" when allOrgs
	AllOrgs bool   `json:"allOrgs"`
}

type CloudUsageSeriesPoint added in v1.786.0

type CloudUsageSeriesPoint struct {
	T          string `json:"t"` // RFC3339 bucket start (UTC)
	Tokens     int64  `json:"tokens"`
	SpendCents int64  `json:"spendCents"`
	Requests   int64  `json:"requests"`
	Models     int64  `json:"models"`
}

type CloudUsageTotals added in v1.786.0

type CloudUsageTotals struct {
	Tokens           int64 `json:"tokens"`
	PromptTokens     int64 `json:"promptTokens"`
	CompletionTokens int64 `json:"completionTokens"`
	Requests         int64 `json:"requests"`
	SpendCents       int64 `json:"spendCents"`
	Models           int64 `json:"models"`
	Providers        int64 `json:"providers"`
}

type Connection

type Connection struct {
	Owner         string     `db:"pk" json:"owner"`
	Name          string     `db:"pk" json:"name"`
	CreatedTime   string     `json:"createdTime"`
	StartTime     string     `json:"startTime"`
	EndTime       string     `json:"endTime"`
	Protocol      string     `json:"protocol"`
	ConnectionId  string     `json:"connectionId"`
	Node          string     `json:"node"`
	Creator       string     `json:"creator"`
	ClientIp      string     `json:"clientIp"`
	UserAgent     string     `json:"userAgent"`
	ClientIpDesc  string     `json:"clientIpDesc"`
	UserAgentDesc string     `json:"userAgentDesc"`
	Width         int        `json:"width"`
	Height        int        `json:"height"`
	Status        string     `json:"status"`
	Recording     string     `json:"recording"`
	Code          int        `json:"code"`
	Message       string     `json:"message"`
	Mode          string     `json:"mode"`
	Operations    StringList `db:"json varchar(1000)" json:"operations"`
	Reviewed      bool       `json:"reviewed"`
	CommandCount  int64      `json:"commandCount"`
}

func CreateConnection

func CreateConnection(connection *Connection, nodeId string, mode string) (*Connection, error)

func GetConnection

func GetConnection(id string) (*Connection, error)

func GetConnections

func GetConnections(owner string) ([]*Connection, error)

func GetPaginationConnections

func GetPaginationConnections(owner, status string, offset, limit int, field, value, sortField, sortOrder string) ([]*Connection, error)

func GetSessionsByStatus

func GetSessionsByStatus(statuses []string) ([]*Connection, error)

func (*Connection) GetId

func (s *Connection) GetId() string

type Consultation

type Consultation struct {
	Owner       string     `db:"pk" json:"owner"`
	Name        string     `db:"pk" json:"name"`
	CreatedTime string     `json:"createdTime"`
	UpdatedTime string     `json:"updatedTime"`
	DisplayName string     `json:"displayName"`
	PatientName string     `json:"patientName"`
	DoctorNames StringList `json:"doctorNames"`
	ExpiredTime string     `json:"expiredTime"`
	State       string     `json:"state"`
}

func FilterConsultationsByUser

func FilterConsultationsByUser(user *iam.User, consultations []*Consultation) []*Consultation

func GetConsultation

func GetConsultation(id string) (*Consultation, error)

func GetConsultations

func GetConsultations(owner string) ([]*Consultation, error)

func GetMaskedConsultation

func GetMaskedConsultation(consultation *Consultation, errs ...error) (*Consultation, error)

func GetMaskedConsultations

func GetMaskedConsultations(consultations []*Consultation, errs ...error) ([]*Consultation, error)

func GetPaginationConsultations

func GetPaginationConsultations(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Consultation, error)

type Container

type Container struct {
	Owner       string `db:"pk" json:"owner"`
	Name        string `db:"pk" json:"name"`
	DisplayName string `json:"displayName"`
	Provider    string `json:"provider"`
	CreatedTime string `json:"createdTime"`
	Image       string `json:"image"`
	ImageId     string `json:"imageId"`
	Command     string `json:"command"`
	SizeRw      int64  `json:"sizeRw,omitempty"`
	SizeRootFs  int64  `json:"sizeRootFs,omitempty"`
	// Labels      map[string]string
	State  string `json:"state"`
	Status string `json:"status"`
	Ports  string `json:"ports"`
}

func GetContainer

func GetContainer(id string) (*Container, error)

func GetContainers

func GetContainers(owner string) ([]*Container, error)

func GetMaskedContainer

func GetMaskedContainer(container *Container, errs ...error) (*Container, error)

func GetMaskedContainers

func GetMaskedContainers(containers []*Container, errs ...error) ([]*Container, error)

func GetPaginationContainers

func GetPaginationContainers(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Container, error)

func (*Container) GetId

func (container *Container) GetId() string

type ContainerDetail

type ContainerDetail struct {
	Name      string           `json:"name"`
	Image     string           `json:"image"`
	Resources ResourceRequests `json:"resources"`
}

type ContentBlock

type ContentBlock struct {
	Type    string `json:"type"` // "paragraph", "code", "list"
	Text    string `json:"text"`
	Section string `json:"section,omitempty"`
}

ContentBlock represents a block of extracted content (paragraph, code, list).

type Crawl4AIBrowserConfig

type Crawl4AIBrowserConfig struct {
	Headless bool `json:"headless"`
}

Crawl4AIBrowserConfig controls the headless browser settings.

type Crawl4AICrawlerParams

type Crawl4AICrawlerParams struct {
	WordCountThreshold   int  `json:"word_count_threshold"`
	ExcludeExternalLinks bool `json:"exclude_external_links"`
	ProcessIframes       bool `json:"process_iframes"`
}

Crawl4AICrawlerParams controls the crawl extraction behavior.

type Crawl4AIRequest

type Crawl4AIRequest struct {
	Urls          StringList             `json:"urls"`
	BrowserConfig *Crawl4AIBrowserConfig `json:"browser_config,omitempty"`
	CrawlerParams *Crawl4AICrawlerParams `json:"crawler_params,omitempty"`
}

Crawl4AIRequest is the request body for the Hanzo Crawl /crawl endpoint.

type Crawl4AIResponse

type Crawl4AIResponse struct {
	TaskID  string           `json:"task_id"`
	Status  string           `json:"status"`
	Success bool             `json:"success"`
	Results []Crawl4AIResult `json:"results,omitempty"`
}

Crawl4AIResponse is the response from the Hanzo Crawl /crawl endpoint. The field that signals batch success differs by service version — older builds set a top-level status:"completed" string, 0.8.x/0.9.x set a boolean success — so both are accepted and neither is required: the per-result Success is authoritative and inline Results are returned whenever present.

type Crawl4AIResult

type Crawl4AIResult struct {
	URL      string        `json:"url"`
	Markdown MarkdownField `json:"markdown"`
	Success  bool          `json:"success"`
	// Links/Media are per-URL object lists whose fields are heterogeneous across
	// Crawl4AI versions — 0.8.x link objects carry strings (href/text) alongside
	// floats (intrinsic_score) and nulls (head_data). A map-of-string value errors
	// the whole decode, so the values are typed interface{} and read with an
	// assertion where needed.
	Links    map[string][]map[string]interface{} `json:"links,omitempty"`
	Media    map[string][]map[string]interface{} `json:"media,omitempty"`
	Metadata map[string]interface{}              `json:"metadata,omitempty"`
}

Crawl4AIResult holds the crawl output for a single URL.

func CrawlWithCrawl4AI

func CrawlWithCrawl4AI(urls []string) ([]Crawl4AIResult, error)

CrawlWithCrawl4AI sends URLs to the Hanzo Crawl service for JS-rendered crawling. It submits a crawl job, polls for completion, and returns the results.

type CrawlArchive

type CrawlArchive struct {
	Owner      string           `json:"owner"`
	JobID      string           `json:"job_id"`
	Timestamp  string           `json:"timestamp"`
	Results    []ScrapeResult   `json:"results"`
	RawResults []Crawl4AIResult `json:"raw_results,omitempty"`
}

CrawlArchive is the envelope stored in Hanzo Storage for a crawl job's results. It stores both the converted ScrapeResult data and the raw Crawl4AIResult data when available, to preserve the full fidelity of crawl output.

func GetArchivedCrawlResult

func GetArchivedCrawlResult(owner, jobID string) (*CrawlArchive, error)

GetArchivedCrawlResult retrieves previously archived crawl results from Hanzo Storage.

type CrawlResult added in v1.790.4

type CrawlResult struct {
	URL         string                 `json:"url"`
	Title       string                 `json:"title,omitempty"`
	Description string                 `json:"description,omitempty"`
	Markdown    string                 `json:"markdown"`
	Success     bool                   `json:"success"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

CrawlResult is the canonical, clean output of POST /v1/crawl for one URL: the fetched page as LLM-ready markdown plus lightweight metadata. It is the ONE crawl result shape — distinct from ScrapeResult (docs-structured, for search ingest) and from the raw upstream Crawl4AIResult.

func Crawl added in v1.790.4

func Crawl(urls []string) ([]CrawlResult, error)

Crawl is the canonical crawl operation backing POST /v1/crawl: it fetches each URL via the self-hosted Hanzo Crawl (Crawl4AI) service and returns clean, LLM-ready markdown. It is the single "crawl a URL, get content back" path; /v1/scrape (crawl-and-index) and the cloud websearch firecrawl leg reuse the SAME Crawl4AI backend through CrawlWithCrawl4AI, never a parallel client.

type DefaultSearchProvider

type DefaultSearchProvider struct {
	// contains filtered or unexported fields
}

func NewDefaultSearchProvider

func NewDefaultSearchProvider(owner string) (*DefaultSearchProvider, error)

func (*DefaultSearchProvider) Search

func (p *DefaultSearchProvider) Search(relatedStores []string, embeddingProviderName string, embeddingProviderObj embedding.EmbeddingProvider, modelProviderName string, text string, knowledgeCount int, lang string) ([]Vector, *embedding.EmbeddingResult, error)

type DeploymentDetail

type DeploymentDetail struct {
	Name          string            `json:"name"`
	Replicas      int32             `json:"replicas"`
	ReadyReplicas int32             `json:"readyReplicas"`
	Containers    []ContainerDetail `json:"containers"`
	CreatedTime   string            `json:"createdTime"`
	Status        string            `json:"status"`
}

type DiskDetail

type DiskDetail struct {
	DiskId             string
	Size               int32
	Category           string
	Type               string
	Encrypted          bool
	InstanceId         string
	DiskChargeType     string
	DeleteWithInstance bool
	Status             string
}

DiskDetail holds detailed information for a disk

type DocChatRequest

type DocChatRequest struct {
	Query  string `json:"query"`
	Tag    string `json:"tag,omitempty"`
	Stream bool   `json:"stream,omitempty"`
	Prompt string `json:"prompt,omitempty"` // Custom system prompt (set by client)
}

DocChatRequest is the request body for RAG chat over documentation.

type DocIndex

type DocIndex struct {
	ID          string     `json:"id"`
	PageID      string     `json:"page_id"`
	Title       string     `json:"title"`
	URL         string     `json:"url"`
	Content     string     `json:"content"`
	Section     string     `json:"section,omitempty"`
	SectionID   string     `json:"section_id,omitempty"`
	Tag         string     `json:"tag,omitempty"`
	Breadcrumbs StringList `json:"breadcrumbs,omitempty"`

	// FileID scopes a chunk to a single uploaded file (the retired rag-api's
	// LibreChat contract). It is a filterable dimension on the SAME unified
	// index — file-scoped retrieval is a filter over {owner}-{store}-docs, not
	// a parallel store. Empty for doc/crawl/github chunks.
	FileID string `json:"file_id,omitempty"`
}

DocIndex represents a single indexed documentation chunk.

type DocIndexRequest

type DocIndexRequest struct {
	Documents []DocIndex `json:"documents"`
	Replace   bool       `json:"replace,omitempty"`
}

DocIndexRequest is the request body for indexing documents.

type DocSearchRequest

type DocSearchRequest struct {
	Query string `json:"query"`
	Tag   string `json:"tag,omitempty"`
	Limit int    `json:"limit,omitempty"`
	Mode  string `json:"mode,omitempty"` // "hybrid", "fulltext", "vector"

	// FileIDs restricts results to chunks of the given uploaded files. Empty
	// means unrestricted (doc-wide search). Powers the file-scoped RAG surface
	// (/v1/rag/query, /v1/rag/query-multiple) without a separate index.
	FileIDs []string `json:"file_ids,omitempty"`
}

DocSearchRequest is the request body for searching documents.

type DocSearchResult

type DocSearchResult struct {
	ID          string     `json:"id"`
	URL         string     `json:"url"`
	Type        string     `json:"type"` // "page", "heading", "text"
	Content     string     `json:"content"`
	Breadcrumbs StringList `json:"breadcrumbs,omitempty"`
	FileID      string     `json:"file_id,omitempty"`
	Title       string     `json:"title,omitempty"`
}

DocSearchResult is a single result returned by SearchDocuments.

func RagFileContext added in v1.790.2

func RagFileContext(owner, store, fileID string) ([]DocSearchResult, error)

RagFileContext returns every chunk of a file_id (ordered as stored), for the "load full document context" use case (rag-api's /documents/{id}/context).

func RagQuery added in v1.790.2

func RagQuery(owner string, req *RagQueryRequest, lang string) ([]DocSearchResult, error)

RagQuery retrieves the top-K chunks relevant to the query, scoped to the given file(s), via the unified hybrid retrieval path.

func SearchDocuments

func SearchDocuments(owner, store string, req *DocSearchRequest, lang string) ([]DocSearchResult, error)

SearchDocuments performs hybrid retrieval over the SAME unified index that IndexDocuments writes — Hanzo Search (keyword) + Hanzo Vector (semantic), fused with RRF. The two products are queried through independent seams and never conflated.

type DocStatsResponse

type DocStatsResponse struct {
	DocumentCount int              `json:"documentCount"`
	IsIndexing    bool             `json:"isIndexing"`
	Fields        map[string]int64 `json:"fields,omitempty"`
}

DocStatsResponse contains index statistics.

func GetDocIndexStats

func GetDocIndexStats(owner, store string) (*DocStatsResponse, error)

GetDocIndexStats returns statistics about the Meilisearch index.

type Doctor

type Doctor struct {
	Owner        string `db:"pk" json:"owner"`
	Name         string `db:"pk" json:"name"`
	CreatedTime  string `json:"createdTime"`
	UpdatedTime  string `json:"updatedTime"`
	DisplayName  string `json:"displayName"`
	Department   string `json:"department"`
	Gender       string `json:"gender"`
	AccessLevel  string `json:"accessLevel"`
	HospitalName string `json:"hospitalName"`
}

func GetDoctor

func GetDoctor(id string) (*Doctor, error)

func GetDoctors

func GetDoctors(owner string) ([]*Doctor, error)

func GetMaskedDoctor

func GetMaskedDoctor(doctor *Doctor, errs ...error) (*Doctor, error)

func GetMaskedDoctors

func GetMaskedDoctors(doctors []*Doctor, errs ...error) ([]*Doctor, error)

func GetPaginationDoctors

func GetPaginationDoctors(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Doctor, error)

type EcsInstanceDetail

type EcsInstanceDetail struct {
	InstanceId         string
	InstanceType       string
	ImageId            string
	OSName             string
	Cpu                int32
	Memory             int32
	PublicIp           string
	PrivateIp          string
	InstanceChargeType string
	Status             string
}

EcsInstanceDetail holds detailed information for an ECS instance

type EnvVariable

type EnvVariable struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

type EventCache

type EventCache struct {
	Namespace string               `json:"namespace"` // Namespace name
	Events    map[string]*v1.Event `json:"events"`    // Event name -> Event object
}

EventCache represents namespace-level event cache

type ExampleQuestion

type ExampleQuestion struct {
	Title string `json:"title"`
	Text  string `json:"text"`
	Image string `json:"image"`
}

type ExampleQuestionList

type ExampleQuestionList []ExampleQuestion

ExampleQuestionList implements sql.Scanner for slice-of-ExampleQuestion, stored as JSON in a TEXT column.

func (*ExampleQuestionList) Scan

func (l *ExampleQuestionList) Scan(src interface{}) error

func (ExampleQuestionList) Value

func (l ExampleQuestionList) Value() (driver.Value, error)

type File

type File struct {
	Owner           string     `db:"pk" json:"owner"`
	Name            string     `db:"pk" json:"name"`
	CreatedTime     string     `json:"createdTime"`
	Filename        string     `json:"filename"`
	Size            int64      `json:"size"`
	Store           string     `json:"store"`
	StorageProvider string     `json:"storageProvider"`
	Url             string     `json:"url"`
	TokenCount      int        `json:"tokenCount"`
	Status          FileStatus `json:"status"`
	ErrorText       string     `json:"errorText"`
}

func GetFile

func GetFile(id string) (*File, error)

func GetFiles

func GetFiles(owner string) ([]*File, error)

func GetFilesByStore

func GetFilesByStore(owner string, store string) ([]*File, error)

func GetGlobalFiles

func GetGlobalFiles() ([]*File, error)

func GetPaginationFiles

func GetPaginationFiles(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*File, error)

func (*File) GetId

func (file *File) GetId() string

type FileStatus

type FileStatus string
const (
	FileStatusPending    FileStatus = "Pending"
	FileStatusProcessing FileStatus = "Processing"
	FileStatusFinished   FileStatus = "Finished"
	FileStatusError      FileStatus = "Error"
)

type Form

type Form struct {
	Owner       string      `db:"pk" json:"owner"`
	Name        string      `db:"pk" json:"name"`
	CreatedTime string      `json:"createdTime"`
	DisplayName string      `json:"displayName"`
	Position    string      `json:"position"`
	Category    string      `json:"category"`
	Type        string      `json:"type"`
	Tag         string      `json:"tag"`
	Url         string      `json:"url"`
	FormItems   []*FormItem `json:"formItems"`
}

func GetForm

func GetForm(id string) (*Form, error)

func GetForms

func GetForms(owner string) ([]*Form, error)

func GetGlobalForms

func GetGlobalForms() ([]*Form, error)

func GetMaskedForm

func GetMaskedForm(form *Form, isMaskEnabled bool) *Form

func GetMaskedForms

func GetMaskedForms(forms []*Form, isMaskEnabled bool) []*Form

func GetPaginationForms

func GetPaginationForms(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Form, error)

func (*Form) GetId

func (form *Form) GetId() string

type FormItem

type FormItem struct {
	Name    string `json:"name"`
	Label   string `json:"label"`
	Type    string `json:"type"`
	Visible bool   `json:"visible"`
	Width   string `json:"width"`
}

type FromUser

type FromUser struct {
	UserId string `json:"userid"`
}

type GaugeVecInfo

type GaugeVecInfo struct {
	Method     string  `json:"method"`
	Name       string  `json:"name"`
	Throughput float64 `json:"throughput"`
}

type GitHubIngestRequest added in v1.786.0

type GitHubIngestRequest struct {
	Repo        string   `json:"repo"`                  // "owner/name"
	Ref         string   `json:"ref,omitempty"`         // branch/tag/sha; default = repo default branch
	Paths       []string `json:"paths,omitempty"`       // include only blobs under these path prefixes
	Token       string   `json:"token,omitempty"`       // BYO token; else env/KMS GITHUB_TOKEN
	IncludeExts []string `json:"includeExts,omitempty"` // override the default text/code extension allowlist
	MaxFiles    int      `json:"maxFiles,omitempty"`    // cap (default githubDefaultMaxFiles)
	MaxFileSize int      `json:"maxFileSize,omitempty"` // per-file byte cap (default githubDefaultMaxFileSize)
}

GitHubIngestRequest selects a repo (and optional ref/paths) to index.

type Graph

type Graph struct {
	Owner       string `db:"pk" json:"owner"`
	Name        string `db:"pk" json:"name"`
	CreatedTime string `json:"createdTime"`
	DisplayName string `json:"displayName"`
	Category    string `json:"category"`
	Layout      string `json:"layout"`
	Density     int    `json:"density"`
	Store       string `json:"store"`
	StartTime   string `json:"startTime"`
	EndTime     string `json:"endTime"`
	Text        string `json:"text"`
	ErrorText   string `json:"errorText"`
}

func GetGlobalGraphs

func GetGlobalGraphs() ([]*Graph, error)

func GetGraph

func GetGraph(id string) (*Graph, error)

func GetGraphs

func GetGraphs(owner string) ([]*Graph, error)

func GetMaskedGraph

func GetMaskedGraph(graph *Graph, isMaskEnabled bool) *Graph

func GetMaskedGraphs

func GetMaskedGraphs(graphs []*Graph, isMaskEnabled bool) []*Graph

func GetPaginationGraphs

func GetPaginationGraphs(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Graph, error)

func (*Graph) GetId

func (graph *Graph) GetId() string

type GraphNode

type GraphNode struct {
	Id     string `json:"id"`
	Name   string `json:"name"`
	Value  int    `json:"val"`
	Color  string `json:"color"`
	Tag    string `json:"tag"`
	Weight int    `json:"weight"`
}

type Heading

type Heading struct {
	Level int    `json:"level"`
	ID    string `json:"id,omitempty"`
	Text  string `json:"text"`
}

Heading represents a single heading element with its hierarchy level and anchor.

type HierarchySearchProvider

type HierarchySearchProvider struct {
	// contains filtered or unexported fields
}

func NewHierarchySearchProvider

func NewHierarchySearchProvider(owner string) (*HierarchySearchProvider, error)

func (*HierarchySearchProvider) Search

func (p *HierarchySearchProvider) Search(relatedStores []string, embeddingProviderName string, embeddingProviderObj embedding.EmbeddingProvider, modelProviderName string, text string, knowledgeCount int, lang string) ([]Vector, *embedding.EmbeddingResult, error)

type HistogramVecInfo

type HistogramVecInfo struct {
	Method  string `json:"method"`
	Name    string `json:"name"`
	Count   uint64 `json:"count"`
	Latency string `json:"latency"`
}

type Hospital

type Hospital struct {
	Owner       string `db:"pk" json:"owner"`
	Name        string `db:"pk" json:"name"`
	CreatedTime string `json:"createdTime"`
	UpdatedTime string `json:"updatedTime"`
	DisplayName string `json:"displayName"`
	Address     string `json:"address"`
}

func GetHospital

func GetHospital(id string) (*Hospital, error)

func GetHospitals

func GetHospitals(owner string) ([]*Hospital, error)

func GetMaskedHospital

func GetMaskedHospital(hospital *Hospital, errs ...error) (*Hospital, error)

func GetMaskedHospitals

func GetMaskedHospitals(hospitals []*Hospital, errs ...error) ([]*Hospital, error)

func GetPaginationHospitals

func GetPaginationHospitals(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Hospital, error)

type Image

type Image struct {
	Owner                   string `db:"pk" json:"owner"`
	Name                    string `db:"pk" json:"name"`
	CreatedTime             string `json:"createdTime"`
	DisplayName             string `json:"displayName"`
	Provider                string `json:"provider"`
	Category                string `json:"category"`
	BootMode                string `json:"bootMode" xml:"bootMode"`
	ImageId                 string `json:"imageId" xml:"imageId"`
	ImageOwnerAlias         string `json:"ImageOwnerAlias" xml:"ImageOwnerAlias"`
	OSName                  string `json:"os" xml:"os"`
	OSNameEn                string `json:"OSNameEn" xml:"OSNameEn"`
	ImageFamily             string `json:"ImageFamily" xml:"ImageFamily"`
	Architecture            string `json:"systemArchitecture" xml:"systemArchitecture"`
	IsSupportIoOptimized    bool   `json:"IsSupportIoOptimized" xml:"IsSupportIoOptimized"`
	Size                    string `json:"size" xml:"size"`
	ResourceGroupId         string `json:"ResourceGroupId" xml:"ResourceGroupId"`
	SupplierName            string `json:"SupplierName" xml:"SupplierName"`
	Description             string `json:"description" xml:"description"`
	Usage                   string `json:"Usage" xml:"Usage"`
	IsCopied                bool   `json:"IsCopied" xml:"IsCopied"`
	LoginAsNonRootSupported bool   `json:"LoginAsNonRootSupported" xml:"LoginAsNonRootSupported"`
	ImageVersion            string `json:"ImageVersion" xml:"ImageVersion"`
	OSType                  string `json:"OSType" xml:"OSType"`
	IsSubscribed            bool   `json:"IsSubscribed" xml:"IsSubscribed"`
	IsSupportCloudinit      bool   `json:"IsSupportCloudinit" xml:"IsSupportCloudinit"`
	CreationTime            string `json:"creationTime" xml:"creationTime"`
	ProductCode             string `json:"ProductCode" xml:"ProductCode"`
	Progress                string `json:"progress" xml:"progress"`
	Platform                string `json:"platform" xml:"platform"`
	IsSelfShared            string `json:"IsSelfShared" xml:"IsSelfShared"`
	ImageName               string `json:"ImageName" xml:"ImageName"`
	Status                  string `json:"state" xml:"state"`
	ImageOwnerId            int64  `json:"ImageOwnerId" xml:"ImageOwnerId"`
	IsPublic                bool   `json:"IsPublic" xml:"IsPublic"`
	// DetectionOptions        DetectionOptions                            `json:"DetectionOptions" xml:"DetectionOptions"`
	// Features                Features                                    `json:"Features" xml:"Features"`
	// Tags                    TagsInDescribeImageFromFamily               `json:"Tags" xml:"Tags"`
	// DiskDeviceMappings      DiskDeviceMappingsInDescribeImageFromFamily `json:"DiskDeviceMappings" xml:"DiskDeviceMappings"`
	// DB info
	RemoteProtocol string `json:"remoteProtocol"`
	RemotePort     int    `json:"remotePort"`
	RemoteUsername string `json:"remoteUsername"`
	RemotePassword string `json:"remotePassword"`
}

func GetImage

func GetImage(id string) (*Image, error)

func GetImages

func GetImages(owner string) ([]*Image, error)

func GetMaskedImage

func GetMaskedImage(image *Image, errs ...error) (*Image, error)

func GetMaskedImages

func GetMaskedImages(images []*Image, errs ...error) ([]*Image, error)

func GetPaginationImages

func GetPaginationImages(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Image, error)

func (*Image) GetId

func (image *Image) GetId() string

type ImageItem

type ImageItem struct {
	Base64 string `json:"base64"`
	Md5    string `json:"md5"`
}

type ImageMessage

type ImageMessage struct {
	Url string `json:"url"`
}

type IngestFile added in v1.786.0

type IngestFile struct {
	Name    string `json:"name"`
	Content string `json:"content,omitempty"`
	URL     string `json:"url,omitempty"`
	Tag     string `json:"tag,omitempty"`
}

IngestFile is a single raw document supplied inline (upload source). Provide either Content (UTF-8 text) or URL (fetched + parsed server-side). The Name's extension selects the parser and splitter (.md -> Markdown, etc).

type IngestRequest added in v1.786.0

type IngestRequest struct {
	Store   string `json:"store,omitempty"`  // tenant store slug; default DefaultDocsStore
	Source  string `json:"source,omitempty"` // upload | github | crawl | s3 (default: upload)
	Replace bool   `json:"replace,omitempty"`
	Tag     string `json:"tag,omitempty"` // default tag applied to indexed docs

	// source=upload
	Documents []DocIndex   `json:"documents,omitempty"` // pre-chunked passthrough (same shape as /v1/index)
	Files     []IngestFile `json:"files,omitempty"`     // raw files: parsed -> split -> indexed

	// source=github
	GitHub *GitHubIngestRequest `json:"github,omitempty"`

	// source=crawl
	Crawl *ScrapeRequest `json:"crawl,omitempty"`

	// source=s3
	S3 *S3IngestRequest `json:"s3,omitempty"`
}

IngestRequest is the source-pluggable body for POST /v1/docs/ingest. Exactly one source is selected by the `source` discriminator; its matching sub-object supplies the inputs. All sources land in the same Vector+Search index.

type IngestStats added in v1.786.0

type IngestStats struct {
	Source           string   `json:"source"`
	Store            string   `json:"store"`
	IndexName        string   `json:"indexName"`
	FilesIngested    int      `json:"filesIngested"`
	FilesSkipped     int      `json:"filesSkipped"`
	DocumentsIndexed int      `json:"documentsIndexed"`
	Skipped          []string `json:"skipped,omitempty"`
	Errors           []string `json:"errors,omitempty"`

	// Async + WorkflowID are set when a long source (github/crawl/s3) was enqueued as
	// a durable tasks workflow instead of run inline. The caller tracks progress in
	// the Tasks product by this workflow id — there is no bespoke job entity.
	Async      bool   `json:"async,omitempty"`
	WorkflowID string `json:"workflowId,omitempty"`
}

IngestStats summarizes one ingest operation.

func IngestGitHub added in v1.786.0

func IngestGitHub(owner, store string, gh *GitHubIngestRequest, replace bool, tag, lang string) (*IngestStats, error)

IngestGitHub walks a repo's tree and ingests each matching file into the unified Vector+Search index. owner/store scope the tenant index; the repo is fetched read-only over HTTP.

func IngestSource added in v1.786.0

func IngestSource(owner string, req *IngestRequest, lang string) (*IngestStats, error)

IngestSource is the dispatcher behind POST /v1/docs/ingest. The owner is the authenticated principal (tenant isolation); never trust client-supplied owner.

func IngestWorkflow added in v1.796.2

func IngestWorkflow(ctx workflow.Context, in IngestWorkflowInput) (*IngestStats, error)

IngestWorkflow is the durable ingest job. It runs the whole clone→chunk→embed as one retried activity with a generous timeout; on a worker crash the engine re-runs it. The activity is idempotent (deterministic chunk IDs overwrite their own docs), so a retry re-indexes cleanly rather than duplicating.

type IngestWorkflowInput added in v1.796.2

type IngestWorkflowInput struct {
	Owner   string        `json:"owner"`
	Request IngestRequest `json:"request"`
	Lang    string        `json:"lang"`
}

IngestWorkflowInput is the durable workflow's typed input — the owner (bound to the authenticated principal, never client-trusted), the ingest request, and the accept language. JSON-serializable, no funcs/channels (CONTRACT §2).

type JSONList added in v1.785.10

type JSONList[T any] []T

JSONList[T] is a []T that persists as a JSON-array text column.

The data layer (github.com/hanzoai/dbx) writes/reads columns through database/sql. database/sql converts a Go value via driver.DefaultParameterConverter unless the value implements driver.Valuer — and that converter rejects a slice-of-struct outright with "unsupported type []T, a slice of struct". So a bare []struct field (e.g. message.SearchResults, message.ToolCalls) fails EVERY insert/update that touches the row — even when the slice is nil/empty, because the rejection is by TYPE, not value. That broke OAuth sign-in (the welcome-message insert) and every AI message save (which carries populated ToolCalls/SearchResults).

JSONList is the slice-of-struct analogue of StringList: one generic type that implements sql.Scanner + driver.Valuer over JSON, so dbx routes any such column through JSON without per-type boilerplate or ORM changes. Its underlying type is []T, so it is assignable to/from []T and marshals to the same JSON array — call sites and the wire format are unchanged.

func (*JSONList[T]) Scan added in v1.785.10

func (l *JSONList[T]) Scan(src interface{}) error

Scan decodes a stored column into the list. It accepts a JSON array ([{...}]), NULL (→ nil), and empty/"" (→ nil) — so existing rows (which the previous xorm-based store already persisted as JSON) load without a migration.

func (JSONList[T]) Value added in v1.785.10

func (l JSONList[T]) Value() (driver.Value, error)

Value encodes the list as JSON text for storage. nil/empty persist as "[]", matching StringList so NULL/empty round-trips are consistent across columns.

type K8sClient

type K8sClient struct {
	// contains filtered or unexported fields
}

type Label

type Label struct {
	Id        string  `json:"id"`
	User      string  `json:"user"`
	Type      string  `json:"type"`
	StartTime float64 `json:"startTime"`
	EndTime   float64 `json:"endTime"`
	Text      string  `json:"text"`
	Speaker   string  `json:"speaker"`
	Tag1      string  `json:"tag1"`
	Tag2      string  `json:"tag2"`
	Tag3      string  `json:"tag3"`
}

type Machine

type Machine struct {
	Owner       string `db:"pk" json:"owner"`
	Name        string `db:"pk" json:"name"`
	Id          string `json:"id"`
	Provider    string `json:"provider"`
	CreatedTime string `json:"createdTime"`
	UpdatedTime string `json:"updatedTime"`
	ExpireTime  string `json:"expireTime"`
	DisplayName string `json:"displayName"`
	Region      string `json:"region"`
	Zone        string `json:"zone"`
	Category    string `json:"category"`
	Type        string `json:"type"`
	Size        string `json:"size"`
	Tag         string `json:"tag"`
	State       string `json:"state"`
	Image       string `json:"image"`
	Os          string `json:"os"`
	PublicIp    string `json:"publicIp"`
	PrivateIp   string `json:"privateIp"`
	CpuSize     string `json:"cpuSize"`
	MemSize     string `json:"memSize"`
	// DB info
	RemoteProtocol string `json:"remoteProtocol"`
	RemotePort     int    `json:"remotePort"`
	RemoteUsername string `json:"remoteUsername"`
	RemotePassword string `json:"remotePassword"`
}

func GetMachine

func GetMachine(id string) (*Machine, error)

func GetMachines

func GetMachines(owner string) ([]*Machine, error)

func GetMaskedMachine

func GetMaskedMachine(machine *Machine, errs ...error) (*Machine, error)

func GetMaskedMachines

func GetMaskedMachines(machines []*Machine, errs ...error) ([]*Machine, error)

func GetPaginationMachines

func GetPaginationMachines(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Machine, error)

func (*Machine) GetId

func (machine *Machine) GetId() string

type MarkdownField added in v1.790.4

type MarkdownField string

MarkdownField decodes Crawl4AI's `markdown`, which is shape-polymorphic across service versions: a bare JSON string on older builds, and an OBJECT {raw_markdown, fit_markdown, markdown_with_citations, …} on 0.8.x/0.9.x (the deployed hanzoai/crawl). A plain string field errors the whole json.Decode on the object form — the reason a crawl silently returned empty content — so this unmarshaler accepts either, preferring fit_markdown (the noise-reduced, LLM-oriented variant) with raw_markdown as fallback.

func (*MarkdownField) UnmarshalJSON added in v1.790.4

func (m *MarkdownField) UnmarshalJSON(b []byte) error

type Memory added in v1.785.11

type Memory struct {
	Owner       string          `db:"pk" json:"owner"`
	Name        string          `db:"pk" json:"name"`
	UserId      string          `json:"userId"`
	CreatedTime string          `json:"createdTime"`
	UpdatedTime string          `json:"updatedTime"`
	Kind        string          `json:"kind"`
	Content     string          `json:"content"`
	Metadata    MemoryMetadata  `json:"metadata"`
	Embedding   MemoryEmbedding `json:"embedding"`
	Dimension   int             `json:"dimension"`
	Score       float32         `db:"-" json:"score"`
}

Memory is one stored memory. Owner+Name is the primary key; UserId is the per-user scoping column (column name "user_id" — never "user", which is a reserved word in Postgres).

func GetFacts added in v1.785.11

func GetFacts(owner, userId string, limit int) ([]*Memory, error)

GetFacts returns the caller's fact-kind memories, newest first, capped at limit.

func GetMemories added in v1.785.11

func GetMemories(owner, userId string) ([]*Memory, error)

GetMemories returns all of the caller's memories, newest first.

func GetMemoryByIdScoped added in v1.785.11

func GetMemoryByIdScoped(owner, userId, id string) (*Memory, error)

GetMemoryByIdScoped resolves an owner/name id, enforces it matches the caller's org, then applies the user scope.

func GetMemoryScoped added in v1.785.11

func GetMemoryScoped(owner, userId, name string) (*Memory, error)

GetMemoryScoped fetches one memory and enforces ownership: it returns nil unless the row belongs to BOTH this owner and this userId. This is the guard that prevents same-org cross-user reads via a guessed name.

func RecallMemories added in v1.785.11

func RecallMemories(owner, userId, kind string, limit int) ([]*Memory, error)

RecallMemories returns the caller's most recent memories (optionally a single kind), capped at limit.

func SearchMemories added in v1.785.11

func SearchMemories(owner, userId, query, kind string, limit int, lang string) ([]*Memory, error)

SearchMemories returns the caller's memories most relevant to query. If the embedding provider is available and candidates carry embeddings of matching dimension, results are ranked by cosine similarity; otherwise it falls back to a case-insensitive text match. Always scoped to (owner, userId).

func (*Memory) GetId added in v1.785.11

func (m *Memory) GetId() string

GetId returns the owner/name identifier.

type MemoryEmbedding added in v1.785.11

type MemoryEmbedding []float32

MemoryEmbedding is []float32 persisted as JSON in a TEXT column. database/sql can't bind a bare []float32, so — like StringSlice — it carries its own Scanner/Valuer so it round-trips on every driver (SQLite, Postgres, MySQL).

func (*MemoryEmbedding) Scan added in v1.785.11

func (e *MemoryEmbedding) Scan(src interface{}) error

func (MemoryEmbedding) Value added in v1.785.11

func (e MemoryEmbedding) Value() (driver.Value, error)

type MemoryMetadata added in v1.785.11

type MemoryMetadata map[string]string

MemoryMetadata is a free-form string map persisted as JSON in a TEXT column.

func (*MemoryMetadata) Scan added in v1.785.11

func (m *MemoryMetadata) Scan(src interface{}) error

func (MemoryMetadata) Value added in v1.785.11

func (m MemoryMetadata) Value() (driver.Value, error)

type Message

type Message struct {
	Owner             string                       `db:"pk" json:"owner"`
	Name              string                       `db:"pk" json:"name"`
	CreatedTime       string                       `json:"createdTime"`
	Organization      string                       `json:"organization"`
	Store             string                       `json:"store"`
	User              string                       `json:"user"`
	Chat              string                       `json:"chat"`
	ReplyTo           string                       `json:"replyTo"`
	Author            string                       `json:"author"`
	Text              string                       `json:"text"`
	ReasonText        string                       `json:"reasonText"`
	ErrorText         string                       `json:"errorText"`
	FileName          string                       `json:"fileName"`
	Comment           string                       `json:"comment"`
	TokenCount        int                          `json:"tokenCount"`
	TextTokenCount    int                          `json:"textTokenCount"`
	Price             float64                      `json:"price"`
	Currency          string                       `json:"currency"`
	IsHidden          bool                         `json:"isHidden"`
	IsDeleted         bool                         `json:"isDeleted"`
	NeedNotify        bool                         `json:"needNotify"`
	IsAlerted         bool                         `json:"isAlerted"`
	IsRegenerated     bool                         `json:"isRegenerated"`
	WebSearchEnabled  bool                         `json:"webSearchEnabled"`
	ModelProvider     string                       `json:"modelProvider"`
	EmbeddingProvider string                       `json:"embeddingProvider"`
	VectorScores      JSONList[VectorScore]        `json:"vectorScores"`
	LikeUsers         StringList                   `json:"likeUsers"`
	DisLikeUsers      StringList                   `json:"dislikeUsers"`
	Suggestions       JSONList[Suggestion]         `json:"suggestions"`
	ToolCalls         JSONList[model.ToolCall]     `json:"toolCalls"`
	SearchResults     JSONList[model.SearchResult] `json:"searchResults"`
	TransactionId     string                       `json:"transactionId"`
}

func GetChatMessages

func GetChatMessages(chat string) ([]*Message, error)

func GetGlobalFailMessages

func GetGlobalFailMessages() ([]*Message, error)

func GetGlobalMessages

func GetGlobalMessages() ([]*Message, error)

func GetGlobalMessagesByStoreName

func GetGlobalMessagesByStoreName(storeName string) ([]*Message, error)

func GetMessage

func GetMessage(id string) (*Message, error)

func GetMessages

func GetMessages(owner string, user string, storeName string) ([]*Message, error)

func GetMessagesForChats

func GetMessagesForChats(chats []*Chat) ([]*Message, error)

func GetPaginationMessages

func GetPaginationMessages(owner string, offset, limit int, field, value, sortField, sortOrder, store string) ([]*Message, error)

func (*Message) GetId

func (message *Message) GetId() string

func (*Message) SendEmail

func (message *Message) SendEmail(lang string, orgName ...string) error

func (*Message) SendErrorEmail

func (message *Message) SendErrorEmail(errorText string, lang string, orgName ...string) error

type ModelRoute

type ModelRoute struct {
	Owner       string  `db:"pk" json:"owner"`     // org ID ("built-in" = global default)
	ModelName   string  `db:"pk" json:"modelName"` // e.g. "claude-sonnet-4-6"
	CreatedTime string  `json:"createdTime"`
	UpdatedTime string  `json:"updatedTime"`
	Provider    string  `json:"provider"`             // primary provider name
	Upstream    string  `json:"upstream"`             // upstream model name
	Fallback1   string  `json:"fallback1Provider"`    // fallback provider 1
	Fallback1Up string  `json:"fallback1Upstream"`    // fallback upstream 1
	Fallback2   string  `json:"fallback2Provider"`    // fallback provider 2
	Fallback2Up string  `json:"fallback2Upstream"`    // fallback upstream 2
	OwnedBy     string  `json:"ownedBy"`              // owned_by override for /api/models listing
	Premium     bool    `json:"premium"`              // requires paid balance
	Hidden      bool    `json:"hidden"`               // excluded from /api/models listing
	InputPrice  float64 `json:"inputPricePerMillion"` // custom pricing (0 = use default)
	OutputPrice float64 `json:"outputPricePerMillion"`
	Enabled     bool    `json:"enabled"`
}

func GetCachedModelRoutes

func GetCachedModelRoutes(owner string) ([]*ModelRoute, error)

GetCachedModelRoutes returns all model routes for an owner with 60s TTL caching.

func GetModelRoute

func GetModelRoute(owner string, modelName string) (*ModelRoute, error)

func GetModelRoutes

func GetModelRoutes(owner string) ([]*ModelRoute, error)

func GetPaginationModelRoutes

func GetPaginationModelRoutes(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*ModelRoute, error)

func ResolveModelRouteFromDB

func ResolveModelRouteFromDB(modelName string, orgId string) (*ModelRoute, error)

ResolveModelRouteFromDB looks up a model route from the database. Resolution order: org-specific route -> global ("built-in") route. Returns nil if no DB route found (caller should fall back to YAML).

func (*ModelRoute) GetId

func (r *ModelRoute) GetId() string

type MsgItem

type MsgItem struct {
	MsgType string     `json:"msgtype"`
	Image   *ImageItem `json:"image,omitempty"`
}

type MsgResponse

type MsgResponse struct {
	MsgType string      `json:"msgtype"`
	Stream  *StreamSend `json:"stream"`
}

type MyWriter

type MyWriter struct {
	bytes.Buffer
}

func (*MyWriter) Flush

func (w *MyWriter) Flush()

func (*MyWriter) Write

func (w *MyWriter) Write(p []byte) (n int, err error)

type Node

type Node struct {
	Owner           string       `db:"pk" json:"owner"`
	Name            string       `db:"pk" json:"name"`
	CreatedTime     string       `json:"createdTime"`
	UpdatedTime     string       `json:"updatedTime"`
	DisplayName     string       `json:"displayName"`
	Description     string       `json:"description"`
	Category        string       `json:"category"`
	Type            string       `json:"type"`
	Tag             string       `json:"tag"`
	MachineName     string       `json:"machineName"`
	Os              string       `json:"os"`
	PublicIp        string       `json:"publicIp"`
	PrivateIp       string       `json:"privateIp"`
	Size            string       `json:"size"`
	CpuSize         string       `json:"cpuSize"`
	MemSize         string       `json:"memSize"`
	RemoteProtocol  string       `json:"remoteProtocol"`
	RemotePort      int          `json:"remotePort"`
	RemoteUsername  string       `json:"remoteUsername"`
	RemotePassword  string       `json:"remotePassword"`
	AutoQuery       bool         `json:"autoQuery"`
	IsPermanent     bool         `json:"isPermanent"`
	Language        string       `json:"language"`
	EnableRemoteApp bool         `json:"enableRemoteApp"`
	RemoteApps      []*RemoteApp `json:"remoteApps"`
	Services        []*Service   `json:"services"`
	Patches         []*Patch     `json:"patches"`
}

func GetMaskedNode

func GetMaskedNode(node *Node, errs ...error) (*Node, error)

func GetMaskedNodes

func GetMaskedNodes(nodes []*Node, errs ...error) ([]*Node, error)

func GetNode

func GetNode(id string) (*Node, error)

func GetNodes

func GetNodes(owner string) ([]*Node, error)

func GetPaginationNodes

func GetPaginationNodes(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Node, error)

type OrgSettings added in v1.802.0

type OrgSettings struct {
	Owner       string `db:"pk" json:"owner"` // org ID
	CreatedTime string `json:"createdTime"`
	UpdatedTime string `json:"updatedTime"`

	// AutoRouting overrides the global auto-routing flag for this org:
	// "" (unset) → "*" row then global flag decides, "enabled" → opt in even if
	// global off (when router config is present), "disabled" → opt out.
	AutoRouting string `json:"autoRouting"`

	// DefaultSessionRouting is the admin-settable default for whether new chat
	// sessions default to auto-routing in the client (console/chat/app/desktop
	// read it via /v1/get-routing-defaults). Same three-state as AutoRouting:
	// "" (unset) → "*" row then conf default (disabled), "enabled", "disabled".
	DefaultSessionRouting string `json:"defaultSessionRouting"`
}

OrgSettings holds per-org overrides for platform features. One row per org (Owner is the sole primary key), mirroring the ModelRoute storage pattern.

func GetCachedOrgSettings added in v1.802.0

func GetCachedOrgSettings(owner string) (*OrgSettings, error)

GetCachedOrgSettings returns an org's settings row (nil if none) with 60s TTL caching.

func GetOrgSettings added in v1.802.0

func GetOrgSettings(owner string) (*OrgSettings, error)

func GetOrgSettingsList added in v1.802.0

func GetOrgSettingsList(owner string) ([]*OrgSettings, error)

type Param

type Param struct {
	Key   string `json:"key"`
	Field string `json:"field"`
	Value string `json:"value"`
}

type Patch

type Patch struct {
	Name           string `json:"name"`
	Category       string `json:"category"`
	Title          string `json:"title"`
	Url            string `json:"url"`
	Size           string `json:"size"`
	ExpectedStatus string `json:"expectedStatus"`
	Status         string `json:"status"`
	InstallTime    string `json:"installTime"`
	Message        string `json:"message"`
}

type Patient

type Patient struct {
	Owner        string     `db:"pk" json:"owner"`
	Name         string     `db:"pk" json:"name"`
	CreatedTime  string     `json:"createdTime"`
	UpdatedTime  string     `json:"updatedTime"`
	DisplayName  string     `json:"displayName"`
	Gender       string     `json:"gender"`
	Address      string     `json:"address"`
	Email        string     `json:"email"`
	BloodType    string     `json:"bloodType"`
	Allergies    string     `json:"allergies"`
	Owners       StringList `json:"owners"`
	HospitalName string     `json:"hospitalName"`
}

func FilterPatientsByUser

func FilterPatientsByUser(user *iam.User, patients []*Patient) []*Patient

func GetMaskedPatient

func GetMaskedPatient(patient *Patient, errs ...error) (*Patient, error)

func GetMaskedPatients

func GetMaskedPatients(patients []*Patient, errs ...error) ([]*Patient, error)

func GetPaginationPatients

func GetPaginationPatients(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Patient, error)

func GetPatient

func GetPatient(id string) (*Patient, error)

func GetPatients

func GetPatients(owner string) ([]*Patient, error)

type Pod

type Pod struct {
	Owner       string `db:"pk" json:"owner"`
	Name        string `db:"pk" json:"name"`
	Provider    string `json:"provider"`
	Namespace   string `json:"namespace"`
	CreatedTime string `json:"createdTime"`
	HostIP      string `json:"hostIP"`
	PodIP       string `json:"podIP"`
	Labels      string `json:"labels"`
	Status      string `json:"status"`
}

func GetMaskedPod

func GetMaskedPod(pod *Pod, errs ...error) (*Pod, error)

func GetMaskedPods

func GetMaskedPods(pods []*Pod, errs ...error) ([]*Pod, error)

func GetPaginationPods

func GetPaginationPods(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Pod, error)

func GetPod

func GetPod(id string) (*Pod, error)

func GetPods

func GetPods(owner string) ([]*Pod, error)

func (*Pod) GetId

func (pod *Pod) GetId() string

type PrometheusInfo

type PrometheusInfo struct {
	ApiThroughput   []GaugeVecInfo     `json:"apiThroughput"`
	ApiLatency      []HistogramVecInfo `json:"apiLatency"`
	TotalThroughput float64            `json:"totalThroughput"`
}

func GetPrometheusInfo

func GetPrometheusInfo() (*PrometheusInfo, error)

type Properties

type Properties struct {
	CollectedTime string `json:"collectedTime"`
	Subject       string `json:"subject"`
}

type PropertiesMapJSON

type PropertiesMapJSON map[string]*Properties

PropertiesMap implements sql.Scanner for map[string]*Properties.

func (*PropertiesMapJSON) Scan

func (m *PropertiesMapJSON) Scan(src interface{}) error

func (PropertiesMapJSON) Value

func (m PropertiesMapJSON) Value() (driver.Value, error)

type Provider

type Provider struct {
	Owner                        string             `db:"pk" json:"owner"`
	Name                         string             `db:"pk" json:"name"`
	CreatedTime                  string             `json:"createdTime"`
	DisplayName                  string             `json:"displayName"`
	Category                     string             `json:"category"`
	Type                         string             `json:"type"`
	SubType                      string             `json:"subType"`
	Flavor                       string             `json:"flavor"`
	ClientId                     string             `json:"clientId"`
	ClientSecret                 string             `json:"clientSecret"`
	Region                       string             `json:"region"`
	ProviderKey                  string             `json:"providerKey"`
	ProviderUrl                  string             `json:"providerUrl"`
	ApiVersion                   string             `json:"apiVersion"`
	CompatibleProvider           string             `json:"compatibleProvider"`
	McpTools                     agent.McpToolsList `json:"mcpTools"`
	Text                         string             `json:"text"`
	ConfigText                   string             `json:"configText"`
	RawText                      string             `json:"rawText"` // Raw result from scan (for Scan category providers)
	EnableThinking               bool               `json:"enableThinking"`
	Temperature                  float32            `json:"temperature"`
	TopP                         float32            `json:"topP"`
	TopK                         int                `json:"topK"`
	FrequencyPenalty             float32            `json:"frequencyPenalty"`
	PresencePenalty              float32            `json:"presencePenalty"`
	InputPricePerThousandTokens  float64            `json:"inputPricePerThousandTokens"`
	OutputPricePerThousandTokens float64            `json:"outputPricePerThousandTokens"`
	Currency                     string             `json:"currency"`
	UserKey                      string             `json:"userKey"`
	UserCert                     string             `json:"userCert"`
	SignKey                      string             `json:"signKey"`
	SignCert                     string             `json:"signCert"`
	ContractName                 string             `json:"contractName"`
	ContractMethod               string             `json:"contractMethod"`
	Network                      string             `json:"network"`
	Chain                        string             `json:"chain"`
	TestContent                  string             `json:"testContent"`
	// New fields for unified scan widget (for Scan category providers)
	TargetMode    string `json:"targetMode"`    // "Manual Input" or "Asset"
	Target        string `json:"target"`        // Manual input target (IP address or network range)
	Asset         string `json:"asset"`         // Selected asset for scan
	Runner        string `json:"runner"`        // Hostname about who runs the scan job
	ErrorText     string `json:"errorText"`     // Error message for the job execution
	ResultSummary string `json:"resultSummary"` // Short summary of scan results
	IsDefault     bool   `json:"isDefault"`
	IsRemote      bool   `json:"isRemote"`
	State         string `json:"state"`
	BrowserUrl    string `json:"browserUrl"`
}

func GetActiveBlockchainProvider

func GetActiveBlockchainProvider(owner string) (*Provider, error)

func GetAgentProviderFromContext

func GetAgentProviderFromContext(owner string, name string, lang string) (*Provider, agent.AgentProvider, error)

func GetDefaultAgentProvider

func GetDefaultAgentProvider() (*Provider, error)

func GetDefaultBlockchainProvider

func GetDefaultBlockchainProvider() (*Provider, error)

func GetDefaultEmbeddingProvider

func GetDefaultEmbeddingProvider() (*Provider, error)

func GetDefaultKubernetesProvider

func GetDefaultKubernetesProvider(lang string) (*Provider, error)

func GetDefaultModelProvider

func GetDefaultModelProvider() (*Provider, error)

func GetDefaultSpeechToTextProvider

func GetDefaultSpeechToTextProvider() (*Provider, error)

func GetDefaultStorageProvider

func GetDefaultStorageProvider() (*Provider, error)

func GetDefaultTextToSpeechProvider

func GetDefaultTextToSpeechProvider() (*Provider, error)

func GetDefaultVideoProvider

func GetDefaultVideoProvider() (*Provider, error)

func GetEmbeddingProviderFromContext

func GetEmbeddingProviderFromContext(owner string, name string, lang string) (*Provider, embedding.EmbeddingProvider, error)

func GetGlobalProviders

func GetGlobalProviders() ([]*Provider, error)

func GetMaskedProvider

func GetMaskedProvider(provider *Provider, isMaskEnabled bool, user *iam.User) *Provider

func GetMaskedProviders

func GetMaskedProviders(providers []*Provider, isMaskEnabled bool, user *iam.User) []*Provider

func GetModelProviderByName

func GetModelProviderByName(name string) (*Provider, error)

GetModelProviderByName retrieves a Model-category provider by its Name field (e.g. "do-ai", "fireworks", "openai-direct"). Results are cached for 60 seconds.

A provider whose admin toggle is disabled (State != "Active") resolves to (nil, nil) — the SAME shape as a missing provider — so every completion path (chat, anthropic, embeddings, images, message_answer, widget) sees a disabled provider as "not configured" and fails/falls-back uniformly. See ModelProviderUsable for the single-point policy.

func GetModelProviderByNameForOrg added in v1.786.0

func GetModelProviderByNameForOrg(orgId, name string) (*Provider, error)

GetModelProviderByNameForOrg resolves the provider an org's request should use: the org's OWN custom provider (BYOK) if it has configured one under its slug, otherwise the global built-in provider on api.hanzo.ai (the universal router). This is the per-tenant override seam — "let people add their own providers to route through" — with the global default inherited until they do. An empty or "admin" org has no override and takes the global path directly.

func GetModelProviderByType

func GetModelProviderByType(providerType string) (*Provider, error)

GetModelProviderByType retrieves a model provider by its type (e.g. "OpenAI", "Claude", "Fireworks").

func GetModelProviderFromContext

func GetModelProviderFromContext(owner string, name string, lang string) (*Provider, model.ModelProvider, error)

func GetPaginationProviders

func GetPaginationProviders(owner, storeName string, offset, limit int, field, value, sortField, sortOrder string) ([]*Provider, error)

func GetProvider

func GetProvider(id string) (*Provider, error)

func GetProviderByProviderKey

func GetProviderByProviderKey(providerKey string, lang string) (*Provider, error)

GetProviderByProviderKey retrieves a provider using the Provider key

func GetProviders

func GetProviders(owner string) ([]*Provider, error)

func (*Provider) GetAgentProvider

func (p *Provider) GetAgentProvider(lang string) (agent.AgentProvider, error)

func (*Provider) GetEmbeddingProvider

func (p *Provider) GetEmbeddingProvider(lang string) (embedding.EmbeddingProvider, error)

func (*Provider) GetId

func (provider *Provider) GetId() string

func (*Provider) GetModelProvider

func (p *Provider) GetModelProvider(lang string) (model.ModelProvider, error)

func (*Provider) GetScanProvider

func (p *Provider) GetScanProvider(lang string) (scan.ScanProvider, error)

func (*Provider) GetSpeechToTextProvider

func (p *Provider) GetSpeechToTextProvider(lang string) (stt.SpeechToTextProvider, error)

func (*Provider) GetStorageProviderObj

func (p *Provider) GetStorageProviderObj(vectorStoreId string, lang string) (storage.StorageProvider, error)

func (*Provider) GetTextToSpeechProvider

func (p *Provider) GetTextToSpeechProvider(lang string) (tts.TextToSpeechProvider, error)

type RagEmbedRequest added in v1.790.2

type RagEmbedRequest struct {
	FileID       string `json:"file_id"`
	Filename     string `json:"filename,omitempty"`
	Content      string `json:"content,omitempty"`
	URL          string `json:"url,omitempty"`
	Store        string `json:"store,omitempty"`
	Tag          string `json:"tag,omitempty"`
	ChunkSize    int    `json:"chunk_size,omitempty"`
	ChunkOverlap int    `json:"chunk_overlap,omitempty"`
}

RagEmbedRequest ingests one file's text under a file_id. Supply exactly one of Content (inline UTF-8/text) or URL (fetched + parsed server-side). Filename's extension selects the parser (PDF/CSV/XLSX/… via txt.GetParsedTextFromUrl).

type RagEmbedResult added in v1.790.2

type RagEmbedResult struct {
	FileID    string `json:"file_id"`
	Filename  string `json:"filename,omitempty"`
	Store     string `json:"store"`
	IndexName string `json:"index_name"`
	Chunks    int    `json:"chunks"`
}

RagEmbedResult reports the outcome of embedding one file.

func RagEmbedFile added in v1.790.2

func RagEmbedFile(owner string, req *RagEmbedRequest, lang string) (*RagEmbedResult, error)

RagEmbedFile parses + chunks + indexes one file under its file_id into the unified Search+Vector index, scoped to the authenticated owner. Re-embedding the same file_id replaces its chunks (idempotent) so a re-upload doesn't duplicate. Returns the chunk count indexed.

type RagQueryRequest added in v1.790.2

type RagQueryRequest struct {
	Query   string   `json:"query"`
	FileID  string   `json:"file_id,omitempty"`
	FileIDs []string `json:"file_ids,omitempty"`
	K       int      `json:"k,omitempty"`
	Store   string   `json:"store,omitempty"`
	Mode    string   `json:"mode,omitempty"` // hybrid (default) | fulltext | vector
}

RagQueryRequest retrieves chunks scoped to one or more uploaded files. Set FileID for the single-file case or FileIDs for the multi-file case; at least one is required (an unrestricted query belongs on /v1/search, not here).

type Record

type Record struct {
	Id           int    `db:"pk" json:"id"`
	Owner        string `json:"owner"`
	Name         string `json:"name"`
	CreatedTime  string `json:"createdTime"`
	Organization string `json:"organization"`
	ClientIp     string `json:"clientIp"`
	UserAgent    string `json:"userAgent"`
	User         string `json:"user"`
	Method       string `json:"method"`
	RequestUri   string `json:"requestUri"`
	Action       string `json:"action"`
	Language     string `json:"language"`
	Query        string `json:"query"`
	Region       string `json:"region"`
	City         string `json:"city"`
	Unit         string `json:"unit"`
	Section      string `json:"section"`
	Object       string `json:"object"`
	Response     string `json:"response"`
	ErrorText    string `json:"errorText"`
	// ExtendedUser *User  `db:"-" json:"extendedUser"`
	Provider     string `json:"provider"`
	Block        string `json:"block"`
	BlockHash    string `json:"blockHash"`
	Transaction  string `json:"transaction"`
	Provider2    string `json:"provider2"`
	Block2       string `json:"block2"`
	BlockHash2   string `json:"blockHash2"`
	Transaction2 string `json:"transaction2"`
	// For cross-chain records
	Count       int  `json:"count"`
	IsTriggered bool `json:"isTriggered"`
	NeedCommit  bool `db:"index" json:"needCommit"`
}

func GetPaginationRecords

func GetPaginationRecords(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Record, error)

func GetRecord

func GetRecord(id string, lang string) (*Record, error)

GetRecord retrieves a record by its ID or owner/name format.

func GetRecords

func GetRecords(owner string) ([]*Record, error)

func NewRecord

func NewRecord(ctx *context.Context) (*Record, error)

type Remark

type Remark struct {
	Timestamp string `json:"timestamp"`
	User      string `json:"user"`
	Score     string `json:"score"`
	Text      string `json:"text"`
	IsPublic  bool   `json:"isPublic"`
}

type RemoteApp

type RemoteApp struct {
	No            int    `json:"no"`
	RemoteAppName string `json:"remoteAppName"`
	RemoteAppDir  string `json:"remoteAppDir"`
	RemoteAppArgs string `json:"remoteAppArgs"`
}

type ResourceMetrics

type ResourceMetrics struct {
	CPUUsage         string  `json:"cpuUsage"`         // CPU usage (e.g., "120m" for 120 millicores)
	CPUPercentage    float64 `json:"cpuPercentage"`    // CPU usage percentage (0-100)
	MemoryUsage      string  `json:"memoryUsage"`      // Memory usage (e.g., "256Mi" for 256 mebibyte)
	MemoryPercentage float64 `json:"memoryPercentage"` // Memory usage percentage (0-100)
	PodCount         int     `json:"podCount"`         // Number of active pods
}

ResourceMetrics represents resource usage metrics

type ResourceRequests

type ResourceRequests struct {
	CPU    string `json:"cpu"`
	Memory string `json:"memory"`
}

type Response

type Response struct {
	Status string `json:"status"`
	Msg    string `json:"msg"`
}

type RoutingEvent added in v1.802.0

type RoutingEvent struct {
	Id             string  `db:"pk" json:"id"`
	CreatedTime    string  `json:"createdTime"`
	Owner          string  `json:"owner"` // org
	User           string  `json:"user"`  // owner/name of the caller, "" if unauthenticated
	Task           string  `json:"task"`
	RequestedModel string  `json:"requestedModel"` // the virtual alias, e.g. "auto"
	RoutedModel    string  `json:"routedModel"`    // the concrete model that served
	Confidence     float64 `json:"confidence"`
	Source         string  `json:"source"`   // "engine" | "heuristic"
	Features       string  `json:"features"` // serialized JSON array; "" when the engine gave none
}

RoutingEvent is a privacy-preserving record of one `auto`/`zen-router` resolution: which task the request was classified as and which concrete model it was routed to, plus the confidence and whether the decision came from the engine or the local heuristic. It NEVER stores prompt text or any hash of it — the only content-derived value it may carry is the engine's opaque feature vector (Features, serialized JSON, nullable), which is the frozen-backbone embedding produced at inference time, not the prompt. This is the ledger that feeds router data-refinement and heads-fit training (see universe/docs/architecture/personal-router-training.md).

func GetRoutingEvents added in v1.802.0

func GetRoutingEvents(org, since string) ([]*RoutingEvent, error)

GetRoutingEvents returns routing events for training export, oldest first, optionally filtered by org (owner) and a since timestamp (RFC3339; events with created_time >= since). Empty filters return all events.

type S3IngestRequest added in v1.786.0

type S3IngestRequest struct {
	Prefix string `json:"prefix,omitempty"` // object-key prefix within the store's space
}

S3IngestRequest scopes an ingest of the store's backing Hanzo S3 space.

type Scale

type Scale struct {
	Owner       string `db:"pk" json:"owner"`
	Name        string `db:"pk" json:"name"`
	CreatedTime string `json:"createdTime"`
	DisplayName string `json:"displayName"`
	Text        string `json:"text"`
	State       string `json:"state"`
}

Scale is a reusable rubric / evaluation scale (量表), referenced by tasks via Task.Scale (owner/name id).

func GetGlobalScales

func GetGlobalScales() ([]*Scale, error)

func GetMaskedScale

func GetMaskedScale(scale *Scale, isMaskEnabled bool) *Scale

func GetMaskedScales

func GetMaskedScales(scales []*Scale, isMaskEnabled bool) []*Scale

func GetPaginationScales

func GetPaginationScales(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Scale, error)

func GetPublicScales

func GetPublicScales(owner string) ([]*Scale, error)

GetPublicScales returns scales visible to non-admins (Public or empty state).

func GetScale

func GetScale(id string) (*Scale, error)

func GetScales

func GetScales(owner string) ([]*Scale, error)

func (*Scale) GetId

func (s *Scale) GetId() string

type Scan

type Scan struct {
	Owner         string `db:"pk" json:"owner"`
	Name          string `db:"pk" json:"name"`
	CreatedTime   string `json:"createdTime"`
	UpdatedTime   string `json:"updatedTime"`
	DisplayName   string `json:"displayName"`
	TargetMode    string `json:"targetMode"`
	Target        string `json:"target"`
	Asset         string `json:"asset"`
	Provider      string `json:"provider"`
	State         string `json:"state"`
	Runner        string `json:"runner"`
	ErrorText     string `json:"errorText"`
	Command       string `json:"command"`
	RawResult     string `json:"rawResult"`
	Result        string `json:"result"`
	ResultSummary string `json:"resultSummary"`
}

func GetPaginationScans

func GetPaginationScans(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Scan, error)

func GetPendingScans

func GetPendingScans() ([]*Scan, error)

GetPendingScans returns all scans with state "Pending"

func GetScan

func GetScan(id string) (*Scan, error)

func GetScans

func GetScans(owner string) ([]*Scan, error)

func GetScansByAsset

func GetScansByAsset(owner string, assetName string) ([]*Scan, error)

func (*Scan) GetId

func (scan *Scan) GetId() string

type ScanResult

type ScanResult struct {
	RawResult     string `json:"rawResult"`
	Result        string `json:"result"`
	ResultSummary string `json:"resultSummary"`
	Runner        string `json:"runner"`
}

ScanResult represents the result of a scan operation

func ScanAsset

func ScanAsset(provider, scanParam, targetMode, target, asset, command string, saveToScan bool, lang string) (*ScanResult, error)

ScanAsset performs a scan on an asset @param provider: The provider ID (owner/name) for scan provider @param scan: Optional scan ID (owner/name) for saving results to existing scan @param targetMode: "Manual Input" or "Asset" @param target: IP address or network range (for Manual Input mode) @param asset: Asset name for Asset mode @param command: Scan command with optional %s placeholder for target @param saveToScan: Whether to save results to scan object (true for scan edit page, false for provider edit page)

type ScrapeRequest

type ScrapeRequest struct {
	URL      string `json:"url"`
	Depth    int    `json:"depth,omitempty"`
	MaxPages int    `json:"maxPages,omitempty"`
	Selector string `json:"selector,omitempty"`
	Tag      string `json:"tag,omitempty"`
	Store    string `json:"store,omitempty"`
	Engine   string `json:"engine,omitempty"` // "fast" (Go scraper), "browser" (crawl4ai), or "" (auto)
}

ScrapeRequest is the request body for web scraping operations.

type ScrapeResult

type ScrapeResult struct {
	URL         string         `json:"url"`
	Title       string         `json:"title"`
	Description string         `json:"description"`
	Content     string         `json:"content"`
	Headings    []Heading      `json:"headings"`
	Links       StringList     `json:"links"`
	Structured  StructuredData `json:"structured"`
}

ScrapeResult holds the extracted content from a single page.

func Crawl4AIResultToScrapeResult

func Crawl4AIResultToScrapeResult(result Crawl4AIResult) ScrapeResult

Crawl4AIResultToScrapeResult converts a Hanzo Crawl result to our ScrapeResult format. It parses the markdown output to extract title, headings, and structured content blocks.

func CrawlSite

func CrawlSite(req *ScrapeRequest) (results []ScrapeResult, crawlErrors []string, engine string)

CrawlSite performs a crawl starting from req.URL and returns scraped pages. Engine selection:

  • "browser": always use crawl4ai (errors if unavailable)
  • "fast": always use the Go HTML scraper
  • "" (auto): try crawl4ai first, fall back to Go scraper if unreachable

The returned engine string indicates which engine was actually used.

func ScrapePage

func ScrapePage(pageURL string) (*ScrapeResult, error)

ScrapePage fetches a single URL and extracts structured content.

type ScrapeStats

type ScrapeStats struct {
	PagesScraped     int        `json:"pagesScraped"`
	DocumentsIndexed int        `json:"documentsIndexed"`
	Engine           string     `json:"engine"`
	Errors           StringList `json:"errors,omitempty"`
}

ScrapeStats is the summary returned after a scrape-and-index operation.

func ScrapeAndIndex

func ScrapeAndIndex(owner string, req *ScrapeRequest, lang string) (*ScrapeStats, error)

ScrapeAndIndex crawls a site and indexes the results into the owner's search index. The owner parameter determines tenant isolation -- each org gets its own index namespace. If Hanzo Storage is configured, crawl results are archived asynchronously for persistence.

type SearchProvider

type SearchProvider interface {
	Search(relatedStores []string, embeddingProviderName string, embeddingProviderObj embedding.EmbeddingProvider, modelProviderName string, text string, knowledgeCount int, lang string) ([]Vector, *embedding.EmbeddingResult, error)
}

func GetSearchProvider

func GetSearchProvider(typ string, owner string) (SearchProvider, error)

type Service

type Service struct {
	No             int    `json:"no"`
	Name           string `json:"name"`
	Path           string `json:"path"`
	Port           int    `json:"port"`
	ProcessId      int    `json:"processId"`
	ExpectedStatus string `json:"expectedStatus"`
	Status         string `json:"status"`
	SubStatus      string `json:"subStatus"`
	Message        string `json:"message"`
}

type ServiceDetail

type ServiceDetail struct {
	Name         string        `json:"name"`
	Type         string        `json:"type"`
	ClusterIP    string        `json:"clusterIP"`
	ExternalIP   string        `json:"externalIP"`
	Ports        []ServicePort `json:"ports"`
	InternalHost string        `json:"internalHost"`
	ExternalHost string        `json:"externalHost"`
	CreatedTime  string        `json:"createdTime"`
}

type ServicePort

type ServicePort struct {
	Name     string `json:"name"`
	Port     int32  `json:"port"`
	NodePort int32  `json:"nodePort,omitempty"`
	Protocol string `json:"protocol"`
	URL      string `json:"url,omitempty"`
}

type Session

type Session struct {
	Owner       string     `db:"pk" json:"owner"`
	Name        string     `db:"pk" json:"name"`
	CreatedTime string     `json:"createdTime"`
	SessionId   StringList `json:"sessionId"`
}

func GetPaginationSessions

func GetPaginationSessions(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Session, error)

func GetSession

func GetSession(id string) (*Session, error)

func GetSessions

func GetSessions(owner string) ([]*Session, error)

func (*Session) GetId

func (session *Session) GetId() string

type SimilarityIndex

type SimilarityIndex struct {
	Similarity float32
	Index      int
}

type Store

type Store struct {
	Owner                string              `db:"pk" json:"owner"`
	Name                 string              `db:"pk" json:"name"`
	CreatedTime          string              `json:"createdTime"`
	DisplayName          string              `json:"displayName"`
	StorageProvider      string              `json:"storageProvider"`
	StorageSubpath       string              `json:"storageSubpath"`
	ImageProvider        string              `json:"imageProvider"`
	SplitProvider        string              `json:"splitProvider"`
	SearchProvider       string              `json:"searchProvider"`
	ModelProvider        string              `json:"modelProvider"`
	EmbeddingProvider    string              `json:"embeddingProvider"`
	TextToSpeechProvider string              `json:"textToSpeechProvider"`
	EnableTtsStreaming   bool                `json:"enableTtsStreaming"`
	SpeechToTextProvider string              `json:"speechToTextProvider"`
	AgentProvider        string              `json:"agentProvider"`
	VectorStoreId        string              `json:"vectorStoreId"`
	BuiltinTools         StringSlice         `json:"builtinTools"`
	MemoryLimit          int                 `json:"memoryLimit"`
	Frequency            int                 `json:"frequency"`
	LimitMinutes         int                 `json:"limitMinutes"`
	KnowledgeCount       int                 `json:"knowledgeCount"`
	SuggestionCount      int                 `json:"suggestionCount"`
	Welcome              string              `json:"welcome"`
	WelcomeTitle         string              `json:"welcomeTitle"`
	WelcomeText          string              `json:"welcomeText"`
	Prompt               string              `json:"prompt"`
	ExampleQuestions     ExampleQuestionList `json:"exampleQuestions"`
	ThemeColor           string              `json:"themeColor"`
	Avatar               string              `json:"avatar"`
	Title                string              `json:"title"`
	HtmlTitle            string              `json:"htmlTitle"`
	FaviconUrl           string              `json:"faviconUrl"`
	LogoUrl              string              `json:"logoUrl"`
	FooterHtml           string              `json:"footerHtml"`
	NavItems             StringSlice         `json:"navItems"`
	VectorStores         StringSlice         `json:"vectorStores"`
	ChildStores          StringSlice         `json:"childStores"`
	ChildModelProviders  StringSlice         `json:"childModelProviders"`
	ForbiddenWords       StringSlice         `json:"forbiddenWords"`
	ShowAutoRead         bool                `json:"showAutoRead"`
	DisableFileUpload    bool                `json:"disableFileUpload"`
	HideThinking         bool                `json:"hideThinking"`
	IsDefault            bool                `json:"isDefault"`
	State                string              `json:"state"`
	ChatCount            int                 `db:"-" json:"chatCount"`
	MessageCount         int                 `db:"-" json:"messageCount"`
	FileTree             *TreeFile           `json:"fileTree"`
	PropertiesMap        PropertiesMapJSON   `json:"propertiesMap"`
}

func GetDefaultStore

func GetDefaultStore(owner string) (*Store, error)

func GetGlobalStores

func GetGlobalStores() ([]*Store, error)

func GetPaginationStores

func GetPaginationStores(offset, limit int, name, field, value, sortField, sortOrder string) ([]*Store, error)

func GetStore

func GetStore(id string) (*Store, error)

func GetStores

func GetStores(owner string) ([]*Store, error)

func GetStoresByFields

func GetStoresByFields(owner string, fields ...string) ([]*Store, error)

func (*Store) ContainsForbiddenWords

func (store *Store) ContainsForbiddenWords(text string) (bool, string)

func (*Store) GetEmbeddingProvider

func (store *Store) GetEmbeddingProvider() (*Provider, error)

func (*Store) GetId

func (store *Store) GetId() string

func (*Store) GetImageProviderObj

func (store *Store) GetImageProviderObj(lang string) (storage.StorageProvider, error)

func (*Store) GetModelProvider

func (store *Store) GetModelProvider() (*Provider, error)

func (*Store) GetSpeechToTextProvider

func (store *Store) GetSpeechToTextProvider() (*Provider, error)

func (*Store) GetStorageProviderObj

func (store *Store) GetStorageProviderObj(lang string) (storage.StorageProvider, error)

func (*Store) GetTextToSpeechProvider

func (store *Store) GetTextToSpeechProvider() (*Provider, error)

func (*Store) GetVideoData

func (store *Store) GetVideoData(lang string) ([]string, error)

func (*Store) Populate

func (store *Store) Populate(origin string, lang string) error

type StreamRecv

type StreamRecv struct {
	Id string `json:"id"`
}

type StreamResponse

type StreamResponse struct {
	MsgType string      `json:"msgtype"`
	Stream  *StreamSend `json:"stream"`
}

type StreamSend

type StreamSend struct {
	ID      string    `json:"id,omitempty"`
	Finish  bool      `json:"finish"`
	Content string    `json:"content,omitempty"`
	MsgItem []MsgItem `json:"msg_item,omitempty"`
}

type StringList added in v1.785.9

type StringList []string

StringList is a []string that persists as a JSON-array text column.

The data layer (github.com/hanzoai/dbx) scans a text/varchar column into a struct field via database/sql. A bare []string field is not scannable, so any row holding such a column fails with "unsupported Scan ... string into *[]string". StringList implements sql.Scanner + driver.Valuer so dbx routes these columns through JSON — one type fixes every list column (chat.Users, message.LikeUsers, …) without touching the ORM.

Its underlying type is []string, so it is assignable to/from []string and marshals to the same JSON array — callers and the wire format are unchanged.

func (*StringList) Scan added in v1.785.9

func (l *StringList) Scan(src interface{}) error

Scan decodes a stored column into the list. It accepts the modern JSON-array form (["a","b"]), the legacy comma-separated/single-value form written by the previous xorm-based store, and NULL/empty (→ nil) — so existing rows load without a migration.

func (StringList) Value added in v1.785.9

func (l StringList) Value() (driver.Value, error)

Value encodes the list as JSON text for storage. nil/empty persist as "[]".

type StringSlice

type StringSlice []string

StringSlice is []string with JSON marshalling for SQL TEXT columns.

func (*StringSlice) Scan

func (s *StringSlice) Scan(src interface{}) error

func (StringSlice) Value

func (s StringSlice) Value() (driver.Value, error)

type StructuredData

type StructuredData struct {
	Headings []Heading      `json:"headings"`
	Contents []ContentBlock `json:"contents"`
}

StructuredData mirrors the docs framework format for search indexing.

type SubpathStorageProvider

type SubpathStorageProvider struct {
	// contains filtered or unexported fields
}

func NewSubpathStorageProvider

func NewSubpathStorageProvider(provider storage.StorageProvider, subpath string) *SubpathStorageProvider

func (*SubpathStorageProvider) DeleteObject

func (w *SubpathStorageProvider) DeleteObject(key string) error

func (*SubpathStorageProvider) ListObjects

func (w *SubpathStorageProvider) ListObjects(prefix string) ([]*storage.Object, error)

ListObjects Implements the StorageProvider interface, automatically prepending the subpath prefix in each method

func (*SubpathStorageProvider) PutObject

func (w *SubpathStorageProvider) PutObject(user string, parent string, key string, fileBuffer *bytes.Buffer) (string, error)

type Suggestion

type Suggestion struct {
	Text  string `json:"text"`
	IsHit bool   `json:"isHit"`
}

type Task

type Task struct {
	Owner        string     `db:"pk" json:"owner"`
	Name         string     `db:"pk" json:"name"`
	CreatedTime  string     `json:"createdTime"`
	DisplayName  string     `json:"displayName"`
	Provider     string     `json:"provider"`
	Type         string     `json:"type"`
	Subject      string     `json:"subject"`
	Topic        string     `json:"topic"`
	Score        float64    `json:"score"`
	Activity     string     `json:"activity"`
	Grade        string     `json:"grade"`
	Path         string     `json:"path"`
	Scale        string     `json:"scale"`
	Example      string     `json:"example"`
	Labels       StringList `json:"labels"`
	Log          string     `json:"log"`
	Result       string     `json:"result"`
	DocumentUrl  string     `json:"documentUrl"`
	DocumentText string     `json:"documentText"`
}

func GetGlobalTasks

func GetGlobalTasks(owner string) ([]*Task, error)

func GetMaskedTask

func GetMaskedTask(task *Task, isMaskEnabled bool) *Task

func GetMaskedTasks

func GetMaskedTasks(tasks []*Task, isMaskEnabled bool) []*Task

func GetPaginationTasks

func GetPaginationTasks(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Task, error)

func GetTask

func GetTask(id string) (*Task, error)

func GetTasks

func GetTasks(owner string) ([]*Task, error)

func (*Task) GetId

func (task *Task) GetId() string

type TaskResult

type TaskResult struct {
	Title         string                `json:"title"`
	Designer      string                `json:"designer"`
	Stage         string                `json:"stage"`
	Participants  string                `json:"participants"`
	Grade         string                `json:"grade"`
	Instructor    string                `json:"instructor"`
	Subject       string                `json:"subject"`
	School        string                `json:"school"`
	OtherSubjects string                `json:"otherSubjects"`
	Textbook      string                `json:"textbook"`
	Score         float64               `json:"score"`
	Categories    []*TaskResultCategory `json:"categories"`
}

func AnalyzeTask

func AnalyzeTask(task *Task, lang string) (*TaskResult, error)

type TaskResultCategory

type TaskResultCategory struct {
	Name  string            `json:"name"`
	Score float64           `json:"score"`
	Items []*TaskResultItem `json:"items"`
}

type TaskResultItem

type TaskResultItem struct {
	Name         string  `json:"name"`
	Score        float64 `json:"score"`
	Advantage    string  `json:"advantage"`
	Disadvantage string  `json:"disadvantage"`
	Suggestion   string  `json:"suggestion"`
}

type Template

type Template struct {
	Owner              string                 `db:"pk" json:"owner"`
	Name               string                 `db:"pk" json:"name"`
	CreatedTime        string                 `json:"createdTime"`
	UpdatedTime        string                 `json:"updatedTime"`
	DisplayName        string                 `json:"displayName"`
	Description        string                 `json:"description"`
	Version            string                 `json:"version"`
	Icon               string                 `json:"icon"`
	Manifest           string                 `json:"manifest"`
	Readme             string                 `json:"readme"`
	EnableBasicConfig  bool                   `json:"enableBasicConfig"`
	BasicConfigOptions []templateConfigOption `db:"json" json:"basicConfigOptions"`
}

func GetPaginationTemplates

func GetPaginationTemplates(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Template, error)

func GetTemplate

func GetTemplate(id string) (*Template, error)

func GetTemplates

func GetTemplates(owner string) ([]*Template, error)

func (*Template) Render

func (t *Template) Render(data map[string]interface{}) (string, error)

Render the template with the given data.

type TextMessage

type TextMessage struct {
	Content string `json:"content"`
}

type TreeFile

type TreeFile struct {
	Key         string               `json:"key"`
	Title       string               `json:"title"`
	Size        int64                `json:"size"`
	CreatedTime string               `json:"createdTime"`
	IsLeaf      bool                 `json:"isLeaf"`
	Url         string               `json:"url"`
	Children    []*TreeFile          `json:"children"`
	ChildrenMap map[string]*TreeFile `db:"-" json:"-"`
}

func (*TreeFile) Scan

func (t *TreeFile) Scan(src interface{}) error

Scan on *TreeFile so Store.FileTree round-trips JSON<->struct.

func (*TreeFile) Value

func (t *TreeFile) Value() (driver.Value, error)

type TxtLabel

type TxtLabel struct {
	Type      string  `json:"type"`
	StartTime float64 `json:"startTime"`
	EndTime   float64 `json:"endTime"`
	Speaker   string  `json:"speaker"`
	Text      string  `json:"text"`
}

type Usage

type Usage struct {
	Date         string  `json:"date"`
	UserCount    int     `json:"userCount"`
	ChatCount    int     `json:"chatCount"`
	MessageCount int     `json:"messageCount"`
	TokenCount   int     `json:"tokenCount"`
	Price        float64 `json:"price"`
	Currency     string  `json:"currency"`
}

func GetRangeUsages

func GetRangeUsages(rangeType string, count int, user string, storeName string, lang string) ([]*Usage, error)

func GetUsage

func GetUsage(date string) (*Usage, error)

func GetUsages

func GetUsages(days int, user string, storeName string) ([]*Usage, error)

type UsageInfo

type UsageInfo struct {
	Provider   string    `json:"provider"`
	TokenCount int       `json:"tokenCount"`
	StartTime  time.Time `json:"startTime"`
}

type UsageMetadata

type UsageMetadata struct {
	Organization string `json:"organization"`
	Application  string `json:"application"`
}

func GetUsageMetadata

func GetUsageMetadata(lang string, orgName ...string) (*UsageMetadata, error)

type UserUsage

type UserUsage struct {
	User         string  `json:"user"`
	Chats        int     `json:"chats"`
	MessageCount int     `json:"messageCount"`
	TokenCount   int     `json:"tokenCount"`
	Price        float64 `json:"price"`
}

func GetUserTableInfos

func GetUserTableInfos(storeName, user string) ([]*UserUsage, error)

type Vector

type Vector struct {
	Owner       string    `db:"pk" json:"owner"`
	Name        string    `db:"pk" json:"name"`
	CreatedTime string    `json:"createdTime"`
	DisplayName string    `json:"displayName"`
	Store       string    `json:"store"`
	Provider    string    `json:"provider"`
	File        string    `json:"file"`
	Index       int       `json:"index"`
	Text        string    `json:"text"`
	TokenCount  int       `json:"tokenCount"`
	Price       float64   `json:"price"`
	Currency    string    `json:"currency"`
	Score       float32   `json:"score"`
	Data        []float32 `json:"data"`
	Dimension   int       `json:"dimension"`
}

func GetGlobalVectors

func GetGlobalVectors() ([]*Vector, error)

func GetPaginationVectors

func GetPaginationVectors(owner string, storeName string, offset, limit int, field, value, sortField, sortOrder string) ([]*Vector, error)

func GetVector

func GetVector(id string) (*Vector, error)

func GetVectors

func GetVectors(owner string) ([]*Vector, error)

func (*Vector) GetId

func (vector *Vector) GetId() string

type VectorScore

type VectorScore struct {
	Vector string  `json:"vector"`
	Score  float32 `json:"score"`
}

func GetNearestKnowledge

func GetNearestKnowledge(storeName string, vectorStores []string, searchProviderType string, embeddingProvider *Provider, embeddingProviderObj embedding.EmbeddingProvider, modelProvider *Provider, owner string, text string, knowledgeCount int, lang string) ([]*model.RawMessage, []VectorScore, *embedding.EmbeddingResult, error)

type Video

type Video struct {
	Owner          string         `db:"pk" json:"owner"`
	Name           string         `db:"pk" json:"name"`
	CreatedTime    string         `json:"createdTime"`
	DisplayName    string         `json:"displayName"`
	Description    string         `json:"description"`
	Tag            string         `json:"tag"`
	Type           string         `json:"type"`
	VideoId        string         `json:"videoId"`
	VideoLength    string         `json:"videoLength"`
	CoverUrl       string         `json:"coverUrl"`
	DownloadUrl    string         `json:"downloadUrl"`
	AudioUrl       string         `json:"audioUrl"`
	EditMode       string         `json:"editMode"`
	Labels         []*Label       `json:"labels"`
	Segments       []*Label       `json:"segments"`
	LabelCount     int            `db:"-" json:"labelCount"`
	SegmentCount   int            `db:"-" json:"segmentCount"`
	WordCountMap   map[string]int `json:"wordCountMap"`
	DataUrls       StringList     `json:"dataUrls"`
	DataUrl        string         `json:"dataUrl"`
	TagOnPause     bool           `json:"tagOnPause"`
	Remarks        []*Remark      `json:"remarks"`
	Remarks2       []*Remark      `json:"remarks2"`
	ExcellentCount int            `json:"excellentCount"`
	State          string         `json:"state"`
	ReviewState    string         `json:"reviewState"`
	IsPublic       bool           `json:"isPublic"`
	School         string         `json:"school"`
	Stage          string         `json:"stage"`
	Grade          string         `json:"grade"`
	Unit           string         `json:"unit"`
	Lesson         string         `json:"lesson"`
	Class          string         `json:"class"`
	Subject        string         `json:"subject"`
	Topic          string         `json:"topic"`
	Grade2         string         `json:"grade2"`
	Keywords       StringList     `json:"keywords"`
	Template       string         `json:"template"`
	Task1          string         `json:"task1"`
	Task2          string         `json:"task2"`
	Task3          string         `json:"task3"`
	PlayAuth       string         `db:"-" json:"playAuth"`
}

func GetGlobalVideos

func GetGlobalVideos() ([]*Video, error)

func GetPaginationVideos

func GetPaginationVideos(owner string, offset int, limit int, field string, value string, sortField string, sortOrder string, lang string) ([]*Video, error)

func GetVideo

func GetVideo(id string, lang string) (*Video, error)

func GetVideos

func GetVideos(owner string, lang string) ([]*Video, error)

func (*Video) GetId

func (video *Video) GetId() string

func (*Video) Populate

func (video *Video) Populate(lang string) error

func (*Video) PopulateWordCountMap

func (v *Video) PopulateWordCountMap(lang string) error

type VpcDetail

type VpcDetail struct {
	VpcId       string
	CidrBlock   string
	VRouterId   string
	IsDefault   bool
	Status      string
	Description string
}

VpcDetail holds detailed information for a VPC

type WecomBotMessage

type WecomBotMessage struct {
	MsgId    string        `json:"msgid"`
	AIBotId  string        `json:"aibotid"`
	ChatId   string        `json:"chatid,omitempty"`
	ChatType string        `json:"chattype"`
	From     *FromUser     `json:"from"`
	MsgType  string        `json:"msgtype"`
	Text     *TextMessage  `json:"text,omitempty"`
	Image    *ImageMessage `json:"image,omitempty"`
	Stream   *StreamRecv   `json:"stream,omitempty"`
}

type Workflow

type Workflow struct {
	Owner       string `db:"pk" json:"owner"`
	Name        string `db:"pk" json:"name"`
	CreatedTime string `json:"createdTime"`
	DisplayName string `json:"displayName"`

	Text             string `json:"text"`
	Text2            string `json:"text2"`
	Message          string `json:"message"`
	QuestionTemplate string `json:"questionTemplate"`
}

func GetGlobalWorkflows

func GetGlobalWorkflows() ([]*Workflow, error)

func GetMaskedWorkflow

func GetMaskedWorkflow(workflow *Workflow, isMaskEnabled bool) *Workflow

func GetMaskedWorkflows

func GetMaskedWorkflows(workflows []*Workflow, isMaskEnabled bool) []*Workflow

func GetPaginationWorkflows

func GetPaginationWorkflows(owner string, offset, limit int, field, value, sortField, sortOrder string) ([]*Workflow, error)

func GetWorkflow

func GetWorkflow(id string) (*Workflow, error)

func GetWorkflows

func GetWorkflows(owner string) ([]*Workflow, error)

func (*Workflow) GetId

func (workflow *Workflow) GetId() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL