Skip to content
Open
20 changes: 20 additions & 0 deletions packages/opencode/src/altimate/api/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,26 @@ export namespace AltimateApi {
// altimate_change end
}

/**
* Calls an Altimate API endpoint with the stored credentials (Bearer key and x-tenant headers) and
* returns the parsed JSON body. Endpoint functions in other files go through this. Fails with a
* message naming the credentials file when none are stored or they can't be read.
*/
export async function apiRequest(method: string, endpoint: string, body?: unknown): Promise<any> {
let creds: AltimateCredentials
try {
creds = await getCredentials()
} catch (e) {
const p = credentialsPath()
if (!(await Filesystem.exists(p)))
throw new Error(
`No Altimate credentials are stored: sign in to Altimate in altimate-code first (they are saved to ${p}).`,
)
throw new Error(`The Altimate credentials in ${p} can't be used: ${e instanceof Error ? e.message : String(e)}`)
Comment thread
hkaltai marked this conversation as resolved.
Resolved
}
return request(creds, method, endpoint, body)
}

export async function listDatamates(creds?: AltimateCredentials) {
creds ??= await getCredentials()
const data = await request(creds, "GET", "/datamates/")
Expand Down
104 changes: 104 additions & 0 deletions packages/opencode/src/altimate/api/docs-share.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import z from "zod"
import { AltimateApi } from "./client"

// The shared-docs comment endpoints of the Altimate backend. Shapes follow what the backend returns for
// a docs share: its threads ("conversation groups") and the messages in each.

export interface DocsShareMessage {
conversation_id: number
message: string
timestamp: string
user_id: number
}

export interface DocsShareRange {
start: { line: number; character: number }
end?: { line: number; character: number }
}

export interface DocsShareThread {
conversation_group_id: number
owner?: number
/** "Pending" is open; any other value (e.g. "Resolved") is closed. */
status: string
meta?: {
field?: "description"
column?: string
highlight?: string
uniqueId?: string
filePath?: string
resource_type?: string
range?: DocsShareRange | null
} | null
conversations: DocsShareMessage[]
}

export interface DocsShare {
share_id: number
name?: string
description?: string
project_name?: string
conversation_group: DocsShareThread[]
}

export interface DocsShareUser {
id: number
display_name?: string
first_name?: string
last_name?: string
email?: string
}

// What a share and its threads must carry for the tool to read them: an answer without these is an
// error, so a changed or broken response is never shown as "no open comments".
const Range = z.object({
start: z.object({ line: z.number(), character: z.number() }),
end: z.object({ line: z.number(), character: z.number() }).optional(),
})
const SharesAnswer = z.array(
z.object({
share_id: z.number(),
name: z.string().nullish(),
project_name: z.string().nullish(),
conversation_group: z.array(
z.object({
conversation_group_id: z.number(),
status: z.string(),
meta: z.object({ range: Range.nullish() }).passthrough().nullish(),
conversations: z.array(
z.object({ conversation_id: z.number(), message: z.string(), timestamp: z.string(), user_id: z.number() }),
),
}),
),
}),
)

/** The shares of the given dbt projects, each with its comment threads. */
export async function listSharedDocs(projects: string[]): Promise<DocsShare[]> {
const params = new URLSearchParams()
for (const project of projects) params.append("projects", project)
const shares = await AltimateApi.apiRequest("GET", `/dbt/dbt_docs_share/all?${params.toString()}`)
// A paginated answer wraps the shares in `items`; a bare array is accepted too.
const list = shares && !Array.isArray(shares) && Array.isArray(shares.items) ? shares.items : shares

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[SUGGESTION]: A paginated answer is read one page deep, and total is discarded

Unwrapping items fixes the wrapper case, but nothing here handles more than the first page: total (returned alongside items in the fixture this PR adds) is stripped by SharesAnswer, so if the backend caps the page (e.g. 20 of 57 shares) list reports those threads as if the set were complete and can still answer "No open comment threads" while open threads exist on later pages. list is also the only way to discover the share_id/group_id that reply/resolve need, so hidden shares are unreachable. Either fetch the full set (largest page size, or loop until items.length >= total) or keep total in the schema and say the listing is partial when it exceeds items.length.

const parsed = SharesAnswer.safeParse(list)
if (!parsed.success) throw new Error("The shared docs service returned an unexpected answer for the shares.")
return parsed.data as DocsShare[]
Comment thread
hkaltai marked this conversation as resolved.
Resolved
}

/** The people in the tenant, for naming who wrote each message. */
export async function listTenantUsers(): Promise<DocsShareUser[]> {
const users = await AltimateApi.apiRequest("GET", "/users/chat")
return Array.isArray(users) ? users : []
}

export async function replyToThread(shareId: number, groupId: number, message: string): Promise<{ ok: boolean }> {
return AltimateApi.apiRequest("POST", `/dbt/dbt_docs_share/${shareId}/conversation_group/${groupId}/conversation`, {
message,
})
}

export async function resolveThread(shareId: number, groupId: number): Promise<{ ok: boolean }> {
return AltimateApi.apiRequest("POST", `/dbt/dbt_docs_share/${shareId}/conversation_group/${groupId}/resolve`, {
resolved: true,
})
}
18 changes: 18 additions & 0 deletions packages/opencode/src/altimate/tool-cli/allow-list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,19 @@ import { AltimateCoreTestgenTool } from "../tools/altimate-core-testgen"
import { AltimateCoreTrackLineageTool } from "../tools/altimate-core-track-lineage"
import { AltimateCoreValidateTool } from "../tools/altimate-core-validate"
import { DataDiffTool } from "../tools/data-diff"
import { DbtCostEstimateTool } from "../tools/dbt-cost-estimate"
import { DbtCteProfileTool } from "../tools/dbt-cte-profile"
import { DbtDeferStateTool } from "../tools/dbt-defer-state"
import { DbtDocsCoverageTool } from "../tools/dbt-docs-coverage"
import { DbtHealthTool } from "../tools/dbt-health"
import { DbtLineageTool } from "../tools/dbt-lineage"
import { DbtManifestTool } from "../tools/dbt-manifest"
import { DbtMapRelationsTool } from "../tools/dbt-map-relations"
import { DbtProfilesTool } from "../tools/dbt-profiles"
import { DbtRunResultsTool } from "../tools/dbt-run-results"
import { DbtSqlGraphTool } from "../tools/dbt-sql-graph"
import { DbtUnitTestGenTool } from "../tools/dbt-unit-test-gen"
import { DocsShareCommentsTool } from "../tools/docs-share-comments"
import { FinopsAnalyzeCreditsTool } from "../tools/finops-analyze-credits"
import { FinopsExpensiveQueriesTool } from "../tools/finops-expensive-queries"
import { FinopsQueryHistoryTool } from "../tools/finops-query-history"
Expand Down Expand Up @@ -106,10 +115,19 @@ export const EXPOSED: Record<string, Source> = {
altimate_core_track_lineage: AltimateCoreTrackLineageTool,
altimate_core_validate: AltimateCoreValidateTool,
data_diff: DataDiffTool,
dbt_cost_estimate: DbtCostEstimateTool,
Comment thread
hkaltai marked this conversation as resolved.
Resolved
dbt_cte_profile: DbtCteProfileTool,
dbt_defer_state: DbtDeferStateTool,
dbt_docs_coverage: DbtDocsCoverageTool,
dbt_health: DbtHealthTool,
dbt_lineage: DbtLineageTool,
dbt_manifest: DbtManifestTool,
dbt_map_relations: DbtMapRelationsTool,
dbt_profiles: DbtProfilesTool,
dbt_run_results: DbtRunResultsTool,
dbt_sql_graph: DbtSqlGraphTool,
dbt_unit_test_gen: DbtUnitTestGenTool,
docs_share_comments: DocsShareCommentsTool,
finops_analyze_credits: FinopsAnalyzeCreditsTool,
finops_expensive_queries: FinopsExpensiveQueriesTool,
finops_query_history: FinopsQueryHistoryTool,
Expand Down
103 changes: 103 additions & 0 deletions packages/opencode/src/altimate/tools/dbt-adapter-access.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import fs from "fs"
import path from "path"
import type { Tool } from "../../tool/tool"
import { projectRoot } from "../native/connections/registry"

/** Why a tool may not use the dbt adapter. */
export type DbtAdapterRefusal = "read_only" | "other_project" | "no_project" | "not_started" | "not_loaded"

/** The project's dbt adapter, or why this call may not use it (`reason` is a sentence for the user). */
export type DbtAdapterAccess =
| { adapter: any; refusal?: undefined; reason?: undefined }
| { adapter?: undefined; refusal: DbtAdapterRefusal; reason: string }

/** Test seams. */
export const dbtAdapterAccessInternals = {
/** How long a call waits for the dbt adapter to start before it gives up; the start goes on for the next call. */
adapterStartTimeoutMs: 120_000,
}

/**
* The dbt adapter for a tool call, which every adapter-backed tool goes through. Starting the adapter
* runs dbt deps and writes target/, and compiling renders Jinja, which can run SQL: a read-only call
* (no write permission, or plan mode) never starts or uses it. Nor does a session in a dbt project the
* adapter isn't set up for. The wait for the adapter to start is bounded and follows the call's abort.
*/
export async function dbtAdapterFor(ctx: Pick<Tool.Context, "abort" | "agent" | "extra">): Promise<DbtAdapterAccess> {
const signal = ctx.abort
// A call cancelled before it starts is cancelled, not refused.
signal.throwIfAborted()
if (ctx.extra?.forceReadOnly === true || ctx.agent === "plan")
Comment thread
hkaltai marked this conversation as resolved.
Resolved
return {
refusal: "read_only",
reason: "this needs the dbt adapter, which a read-only call (no write permission, or plan mode) doesn't start: re-run with --allow-write outside plan mode",
}
try {
const { getDbtAdapter, getDbtProjectRoot } = await import("../native/connections/register")
// The import yields: a call cancelled meanwhile starts nothing.
signal.throwIfAborted()
const project = await sessionProject()
signal.throwIfAborted()
if (project?.other) {
return {
refusal: "other_project",
reason: project.root
? `the dbt adapter is set up for ${project.root}, not ${project.other}`
: `the dbt adapter isn't set up for ${project.other}`,
}
}
let stop = () => {}
let timer: ReturnType<typeof setTimeout> | undefined
const waited = new Promise<never>((_, reject) => {
stop = () => reject(signal.reason)
signal.addEventListener("abort", stop, { once: true })
const seconds = dbtAdapterAccessInternals.adapterStartTimeoutMs / 1000
timer = setTimeout(
() => reject(new Error(`the dbt adapter didn't start within ${seconds} s`)),
dbtAdapterAccessInternals.adapterStartTimeoutMs,
)
})
const adapter = await Promise.race([getDbtAdapter(), waited]).finally(() => {
signal.removeEventListener("abort", stop)
clearTimeout(timer)
})
if (!adapter) {
// No adapter also when the project exists but the adapter failed to start: say which.
const root = await getDbtProjectRoot()
const found = !!root && fs.existsSync(path.join(root, "dbt_project.yml"))
return found
? { refusal: "not_started", reason: "the dbt adapter didn't start" }
: { refusal: "no_project", reason: "no dbt project here" }
}
if (adapter.isInitialized?.() === false)
return { refusal: "not_loaded", reason: "the dbt adapter didn't load the project" }
return { adapter }
} catch (e) {
if (signal.aborted) throw e
return { refusal: "not_started", reason: e instanceof Error ? e.message : String(e) }
}
}

/**
* The adapter's project root and, when the session's directory is in another dbt project, that one
* (`other`, both links resolved). Undefined when the session's directory is in no dbt project: the
* adapter's own discovery (a dbt.json, or a walk up from the working directory) decides then.
*/
async function sessionProject(): Promise<{ root?: string; other?: string } | undefined> {
Comment thread
hkaltai marked this conversation as resolved.
Resolved
Comment thread
hkaltai marked this conversation as resolved.
Resolved
const { findProjectRoot } = await import("../../../../dbt-tools/src/config")
const found = findProjectRoot(projectRoot())
if (!found) return undefined
const { getDbtProjectRoot } = await import("../native/connections/register")
const root = await getDbtProjectRoot()
const real = (p: string) => {
try {
return fs.realpathSync(p)
} catch {
return path.resolve(p)
}
}
const here = real(found)
// path.relative ignores case on win32.
if (!root) return { other: here }
return path.relative(real(root), here) ? { root: real(root), other: here } : { root }
}
17 changes: 17 additions & 0 deletions packages/opencode/src/altimate/tools/dbt-cost-estimate.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import z from "zod"
import { Tool } from "../../tool/tool"

export const DbtCostEstimateTool = Tool.define("dbt_cost_estimate", {
description: "Estimate the bytes a dbt model or a SQL query would scan, from a warehouse dry run (BigQuery).",
parameters: z.object({
model: z.string().optional().describe("Model name to compile and estimate"),
sql: z.string().optional().describe("SQL (may use Jinja) to compile and estimate"),
}),
async execute() {
return {
title: "dbt_cost_estimate: not implemented",
metadata: { success: false, error: "not implemented" },
output: "dbt_cost_estimate is not implemented in this build of altimate-code yet.",
}
},
})
17 changes: 17 additions & 0 deletions packages/opencode/src/altimate/tools/dbt-cte-profile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import z from "zod"
import { Tool } from "../../tool/tool"

export const DbtCteProfileTool = Tool.define("dbt_cte_profile", {
description: "List a dbt model's CTEs, or time one CTE with a row-count query.",
parameters: z.object({
model: z.string().describe("Model name"),
cte: z.string().optional().describe("CTE to time; without it, the CTE list is returned"),
}),
async execute() {
return {
title: "dbt_cte_profile: not implemented",
metadata: { success: false, error: "not implemented" },
output: "dbt_cte_profile is not implemented in this build of altimate-code yet.",
}
},
})
16 changes: 16 additions & 0 deletions packages/opencode/src/altimate/tools/dbt-defer-state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import z from "zod"
import { Tool } from "../../tool/tool"

export const DbtDeferStateTool = Tool.define("dbt_defer_state", {
description: "dbt Power User's defer-to-production setting for a dbt project, and the profile's default target.",
parameters: z.object({
project_dir: z.string().describe("dbt project folder"),
}),
async execute() {
return {
title: "dbt_defer_state: not implemented",
metadata: { success: false, error: "not implemented" },
output: "dbt_defer_state is not implemented in this build of altimate-code yet.",
}
},
})
21 changes: 21 additions & 0 deletions packages/opencode/src/altimate/tools/dbt-docs-coverage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import z from "zod"
import { Tool } from "../../tool/tool"

export const DbtDocsCoverageTool = Tool.define("dbt_docs_coverage", {
description:
"Documentation coverage of a dbt model: which output columns have a description, and whether the model has one.",
parameters: z.object({
model: z.string().describe("Model name"),
manifest_path: z
.string()
.optional()
.describe("manifest.json to read (default: the dbt project's target/manifest.json)"),
}),
async execute() {
return {
title: "dbt_docs_coverage: not implemented",
metadata: { success: false, error: "not implemented" },
output: "dbt_docs_coverage is not implemented in this build of altimate-code yet.",
}
},
})
16 changes: 16 additions & 0 deletions packages/opencode/src/altimate/tools/dbt-health.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import z from "zod"
import { Tool } from "../../tool/tool"

export const DbtHealthTool = Tool.define("dbt_health", {
description: "DataPilot project health insights for the dbt project.",
parameters: z.object({
config_path: z.string().optional().describe("DataPilot config file to use"),
}),
async execute() {
return {
title: "dbt_health: not implemented",
metadata: { success: false, error: "not implemented" },
output: "dbt_health is not implemented in this build of altimate-code yet.",
}
},
})
21 changes: 21 additions & 0 deletions packages/opencode/src/altimate/tools/dbt-map-relations.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import z from "zod"
import { Tool } from "../../tool/tool"

export const DbtMapRelationsTool = Tool.define("dbt_map_relations", {
description: "Map each table a raw SQL query reads to the dbt ref() or source() for it, from the manifest.",
parameters: z.object({
sql: z.string().describe("Raw SQL to map"),
dialect: z.string().optional().describe("SQL dialect of the query"),
manifest_path: z
.string()
.optional()
.describe("manifest.json to match against (default: the dbt project's target/manifest.json)"),
}),
async execute() {
return {
title: "dbt_map_relations: not implemented",
metadata: { success: false, error: "not implemented" },
output: "dbt_map_relations is not implemented in this build of altimate-code yet.",
}
},
})
Loading
Loading