Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
94 commits
Select commit Hold shift + click to select a range
18e72ea
feat: experiment: model-free `tool` CLI and MCP server on one adapter
hkaltai Oct 28, 2026
fc33c2e
feat: experiment: workspace tools on by default for linked projects
hkaltai Oct 28, 2026
06223f4
feat: experiment: mirror workspace skills into Claude Code project sk…
hkaltai Oct 28, 2026
2f45bc4
Merge remote-tracking branch 'origin/main' into tool-cli-daemon
hkaltai Oct 29, 2026
7d5d12c
fix: harden tool daemon startup, lock release, MCP write gate and ski…
hkaltai Oct 29, 2026
ef54882
feat: altimate integrations command for GitHub, Jira and Linear
hkaltai Oct 29, 2026
8822f29
test: restore shared dispatcher handlers and MCP SDK modules after mo…
hkaltai Oct 30, 2026
bd1f98e
fix: share the Claude Code plugin's skill-copy safeguards in the work…
hkaltai Oct 30, 2026
7f1230a
Merge remote-tracking branch 'origin/main' into tool-cli-daemon
hkaltai Oct 30, 2026
4e523b0
fix: reload daemon connections on edit, release locks in mcp serve, g…
hkaltai Oct 30, 2026
615f88b
fix: keep the workspace skill mirror in step with the plugin's sync u…
hkaltai Oct 30, 2026
9108070
feat: connect integrations with the workspace's own credential fields
hkaltai Oct 30, 2026
39525e4
Merge remote-tracking branch 'origin/main' into tool-cli-daemon
hkaltai Oct 30, 2026
c8a46b9
fix: publish skill copies only for an unchanged, still-owned snapshot…
hkaltai Oct 30, 2026
8ed972d
refactor: sync integrations through the existing connections API
hkaltai Nov 2, 2026
f87d128
fix: keep workspace skill copies when a SKILL.md disappears between i…
hkaltai Nov 2, 2026
6f03803
feat: attach synced integration connections to the linked workspace
hkaltai Nov 2, 2026
b139685
test: a SKILL.md that disappears between its check and its read keeps…
hkaltai Nov 2, 2026
1040986
feat: report whether the project is linked in integrations status
hkaltai Nov 2, 2026
024e58f
Merge remote-tracking branch 'origin/tool-cli-daemon' into feat-local…
hkaltai Nov 2, 2026
853bfa0
fix: address review findings in the tool CLI, MCP server and workspac…
hkaltai Nov 2, 2026
7109869
fix: never send a doubled quote to BigQuery or Databricks in batch re…
hkaltai Nov 2, 2026
4652bed
fix: keep data_diff and the tool daemon within read-only and release …
hkaltai Nov 2, 2026
fcc3c44
Merge remote-tracking branch 'origin/main' into tool-cli-daemon
hkaltai Nov 2, 2026
b7ce612
fix: harden integrations state, locking and credential lifecycle
hkaltai Nov 2, 2026
b52d686
Merge remote-tracking branch 'origin/tool-cli-daemon' into feat-local…
hkaltai Nov 2, 2026
c6d1aa3
fix: validate before sync, keep local copies safe, record expiry
hkaltai Nov 2, 2026
fdeddbf
fix: dialect-aware hard blocks, failed data_diff reported as an error…
hkaltai Nov 2, 2026
d500243
fix: hard blocks classify with each warehouse's dialect; daemon liste…
hkaltai Nov 2, 2026
6b54087
fix: data_diff checks an omitted source in the default warehouse's di…
hkaltai Nov 2, 2026
20fb04e
fix: data_diff treats an empty warehouse name as the default, as the …
hkaltai Nov 2, 2026
88f03f4
fix: read sql_execute SQL in every dialect an omitted warehouse can r…
hkaltai Nov 2, 2026
1311bf7
fix: uncertain SQL is hard-blocked on the words alone; dbt adapter ty…
hkaltai Nov 2, 2026
c9a9cf9
fix: Oracle, Trino and Fabric keep their reads; TRUNCATE /* c */ ( is…
hkaltai Nov 2, 2026
ee2190b
fix: offer a credential again when its workspace copy was deleted
hkaltai Nov 3, 2026
e0f8735
fix: project MCP config never supplies credentials; remove the token …
hkaltai Nov 3, 2026
ce84016
Merge remote-tracking branch 'origin/tool-cli-daemon' into feat-local…
hkaltai Nov 3, 2026
63024e6
fix: tell MCP sources apart by scope and report a kept workspace conn…
hkaltai Nov 3, 2026
4a373dc
fix: keep shared workspace connections and hold the lock for attach-only
hkaltai Nov 3, 2026
f7ecf8a
fix: delete secrets before the record, and read attach-only state und…
hkaltai Nov 3, 2026
d9fbfcd
fix: clean text output, normalise typed Jira sites, read the catalog …
hkaltai Nov 3, 2026
68728c9
fix: clean the masked secret tail and the hostname in text output
hkaltai Nov 3, 2026
e44e2f5
Merge remote-tracking branch 'origin/main' into feat-local-integratio…
hkaltai Nov 4, 2026
4cc4549
fix: report workspace and local state truthfully after partial failures
hkaltai Nov 4, 2026
beafa4b
fix: never write back a workspace list built from a bad answer; refus…
hkaltai Nov 4, 2026
2bdd65f
fix: keychain calls no longer block the lock heartbeat; workspace int…
hkaltai Nov 4, 2026
319d210
fix: a workspace that is not private gets a connection only with --share
hkaltai Nov 5, 2026
71d670c
fix: failed results report where the credential is, sync keeps an exp…
hkaltai Nov 5, 2026
8f64c00
fix: a draft that cannot be cleared no longer stops Keep local, and a…
hkaltai Nov 5, 2026
8172391
Merge remote-tracking branch 'origin/main' into feat-local-integratio…
hkaltai Nov 5, 2026
f0061d0
fix: a shared workspace is checked again right before writing, a conn…
hkaltai Nov 5, 2026
ecf9ec7
fix: a connection is reported shared only when the workspace entry us…
hkaltai Nov 5, 2026
9d64d5d
fix: an attach that would share nothing is not refused, and the CLI w…
hkaltai Nov 5, 2026
13328df
Merge remote-tracking branch 'origin/main' into feat-local-integratio…
hkaltai Nov 13, 2026
a74b173
fix: an already-shared connection is not rewritten without --share, a…
hkaltai Nov 13, 2026
509b64d
fix: an attach failure after a shared rewrite says who has the new cr…
hkaltai Nov 13, 2026
35ba475
fix: an attach-only failure on a shared connection no longer says its…
hkaltai Nov 13, 2026
6dee11c
fix: the gh token is read for github.com only, failures after a share…
hkaltai Nov 14, 2026
c1b639e
fix: a GitHub token beside an enterprise host is never read, and a sy…
hkaltai Nov 14, 2026
c2cc1bb
fix: gh is not asked for a token while GH_TOKEN or GITHUB_TOKEN sits …
hkaltai Nov 14, 2026
4507154
fix: any GitHub host setting in an MCP server's arguments blocks its …
hkaltai Nov 14, 2026
2072595
Merge remote-tracking branch 'origin/main' into feat-local-integratio…
hkaltai Nov 14, 2026
956b966
fix: the sync a cleanup failure names removes the leftover, failed sy…
hkaltai Nov 14, 2026
1b05168
refactor: one local cleanup helper for the upload and attach-only paths
hkaltai Nov 14, 2026
3adced5
chore: drop a comment the cleanup helper already carries
hkaltai Nov 14, 2026
432238b
fix: a GitHub token is read only from a source confirmed for github.c…
hkaltai Nov 17, 2026
862be29
fix: an enterprise server in the repository or holding the shell toke…
hkaltai Nov 17, 2026
47d5af6
fix: a server is confirmed for github.com only when every hostname in…
hkaltai Nov 17, 2026
f02edcb
fix: an MCP server is a github.com token source only in one of GitHub…
hkaltai Nov 17, 2026
7c45c16
fix: docker's other ways of passing a token and other-host servers th…
hkaltai Nov 17, 2026
85d0747
fix: a leftover is tied to the backend it was recorded for, Claude Co…
hkaltai Nov 17, 2026
23d3791
fix: the shell's, the server's and each Claude Code settings file's h…
hkaltai Nov 17, 2026
94fcf69
fix: Claude Code's config directory, managed MCP config and this tool…
hkaltai Nov 17, 2026
8a93737
fix: this tool's {env:NAME} references, remote headers and .altimate-…
hkaltai Nov 17, 2026
b830b11
fix: GitHub tokens are no longer read from the shell's GITHUB_TOKEN o…
hkaltai Nov 17, 2026
fb21141
fix: Keep local keeps the recorded workspace connection until it is r…
hkaltai Nov 17, 2026
b66c126
fix: docker or npx must run GitHub's server as their first program, a…
hkaltai Nov 17, 2026
9ecf8bd
fix: disconnect and Keep local refuse while the workspace copy is on …
hkaltai Nov 17, 2026
2a3c636
fix: only each command's own leading words are skipped before GitHub'…
hkaltai Nov 17, 2026
de4aaad
fix: connect and sync do not upload while the recorded workspace copy…
hkaltai Nov 17, 2026
a466290
fix: every purge removes a recorded leftover's fields, and sync and s…
hkaltai Nov 17, 2026
bbc7af3
test: status for a connection on another sign-in shows this machine's…
hkaltai Nov 17, 2026
8bc60b8
Merge remote-tracking branch 'origin/main' into feat-local-integratio…
hkaltai Nov 17, 2026
a01fec4
Merge remote-tracking branch 'origin/main' into feat-local-integratio…
hkaltai Nov 17, 2026
994c3ed
fix: disconnect --local-only clears this machine when the recorded si…
hkaltai Nov 17, 2026
51f9ae5
fix: transport errors never print a credential, an official GitHub MC…
hkaltai Nov 17, 2026
daeffb3
fix: docker's and Windows' leading words count once, a GitHub token n…
hkaltai Nov 17, 2026
29b2b86
fix: an update renames the recorded connection to this machine's name…
hkaltai Nov 17, 2026
92066b0
fix: keychain writes and deletes run under the store lock, a save rem…
hkaltai Nov 17, 2026
b98d71e
fix: credentials are redacted from errors even when quoted trimmed or…
hkaltai Nov 17, 2026
3da1f52
fix: a save keeps a non-secret value typed again while it ran
hkaltai Nov 17, 2026
2b2e8b1
fix: a connected provider keeps its variant, npx and docker each acce…
hkaltai Nov 17, 2026
9884b1a
fix: one variant rule in resolve for connect, update, fields and the …
hkaltai Nov 17, 2026
6a68750
fix: the jira-cli type is complete for tsgo, validation never follows…
hkaltai Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 208 additions & 0 deletions packages/opencode/src/altimate/integrations/backend.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
// altimate_change - new file
//
// Client for the workspace connections API of the Altimate backend: list, create, update and delete
// the caller's own connections, plus the integrations catalog. Credentials come from the existing
// Altimate login; the integrations-only environment variables point this client at another backend.
import { AltimateApi } from "../api/client"

export interface BackendConfig {
apiUrl: string
tenant: string
token: string
}

export class BackendError extends Error {
constructor(
message: string,
readonly status: number,
readonly code: string | null,
) {
super(message)
this.name = "BackendError"
}
}

/** A connection as the connections API returns it. */
export interface Connection {
id: number
name: string
integration_id: string
config?: Record<string, unknown>
is_valid: boolean
last_validated_at?: string | null
created_at?: string | null
updated_at?: string | null
is_owner?: boolean
/** Who besides the owner can use it; anything but "private" (or none) counts as shared. */
privacy?: string
}

/**
* Takes credentials out of an error message before it goes anywhere. An error can quote a value trimmed or cut at a control
* character (Bun's invalid-header error does), so each such piece is taken out as well as the whole value.
*/
export function redactSecrets(text: string, secrets: string[]): string {
const pieces = secrets.flatMap((v) => [v, v.trim(), ...v.split(/[\s\x00-\x1f]+/)]).filter((v) => v.length >= 6)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: redactSecrets skips credentials shorter than six characters, but backendConfig accepts any non-empty backend token. A short token can therefore be echoed by a transport error; redact the complete secret regardless of length and apply any minimum only to incidental fragments.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/integrations/backend.ts, line 45:

<comment>`redactSecrets` skips credentials shorter than six characters, but `backendConfig` accepts any non-empty backend token. A short token can therefore be echoed by a transport error; redact the complete secret regardless of length and apply any minimum only to incidental fragments.</comment>

<file context>
@@ -37,6 +37,15 @@ export interface Connection {
+ * character (Bun's invalid-header error does), so each such piece is taken out as well as the whole value.
+ */
+export function redactSecrets(text: string, secrets: string[]): string {
+  const pieces = secrets.flatMap((v) => [v, v.trim(), ...v.split(/[\s\x00-\x1f]+/)]).filter((v) => v.length >= 6)
+  return [...new Set(pieces)].sort((a, b) => b.length - a.length).reduce((m, v) => m.split(v).join("<redacted>"), text)
+}
</file context>
Suggested change
const pieces = secrets.flatMap((v) => [v, v.trim(), ...v.split(/[\s\x00-\x1f]+/)]).filter((v) => v.length >= 6)
const pieces = secrets.flatMap((v) => [v, v.trim(), ...v.split(/[\s\x00-\x1f]+/)]).filter(Boolean)

return [...new Set(pieces)].sort((a, b) => b.length - a.length).reduce((m, v) => m.split(v).join("<redacted>"), text)
}

/** The login used for backend calls, or null when there is none. */
export async function backendConfig(): Promise<BackendConfig | null> {
const env = { url: process.env.ALTIMATE_INTEGRATIONS_API_URL, tenant: process.env.ALTIMATE_INTEGRATIONS_TENANT, token: process.env.ALTIMATE_INTEGRATIONS_TOKEN }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The environment-selected backend is not used by workspace binding resolution. With only ALTIMATE_INTEGRATIONS_* configured, connections can be saved successfully but cannot be attached to the linked workspace; pass the selected backend credentials through binding lookup.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/integrations/backend.ts, line 40:

<comment>The environment-selected backend is not used by workspace binding resolution. With only `ALTIMATE_INTEGRATIONS_*` configured, connections can be saved successfully but cannot be attached to the linked workspace; pass the selected backend credentials through binding lookup.</comment>

<file context>
@@ -0,0 +1,155 @@
+
+/** The login used for backend calls, or null when there is none. */
+export async function backendConfig(): Promise<BackendConfig | null> {
+  const env = { url: process.env.ALTIMATE_INTEGRATIONS_API_URL, tenant: process.env.ALTIMATE_INTEGRATIONS_TENANT, token: process.env.ALTIMATE_INTEGRATIONS_TOKEN }
+  if (env.url && env.tenant && env.token) return { apiUrl: env.url.replace(/\/+$/, ""), tenant: env.tenant, token: env.token }
+  const creds = await AltimateApi.getCredentials().catch(() => null)
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not changed: the ALTIMATE_INTEGRATIONS_* variables are a development and test override of the backend, not a documented configuration. Binding lookup is a property of the signed-in Altimate account, and with only those variables set there is no account to look a link up with, so the connection is saved and reported as not linked.

if (env.url && env.tenant && env.token) return { apiUrl: env.url.replace(/\/+$/, ""), tenant: env.tenant, token: env.token }
const creds = await AltimateApi.getCredentials().catch((e) => {
if (e instanceof Error && /credentials not found/i.test(e.message)) return null
throw new Error(`Could not read your Altimate login (${e instanceof Error ? e.message : e}). Fix or remove the credentials file, then sign in again.`)
})
const apiUrl = (creds?.altimateUrl || "").replace(/\/+$/, "")
const token = creds?.altimateApiKey || ""
const tenant = creds?.altimateInstanceName || ""
if (!apiUrl || !token || !tenant) return null
return { apiUrl, tenant, token }
}

/** The entries of a catalog response: a bare list, or one wrapped in `items`, `integrations` or `data`. */
export function catalogEntries(data: unknown): any[] {
const list = Array.isArray(data) ? data : isObject(data) ? (data.items ?? data.integrations ?? data.data ?? []) : []
return Array.isArray(list) ? list : []
}

const FAILURE_TEXT: Record<number, string> = {
400: "The request was rejected",
404: "The requested resource was not found",
409: "The saved credential changed, reload and try again",
422: "The connection details were not accepted",
}

const isObject = (v: unknown): v is Record<string, any> => typeof v === "object" && v !== null && !Array.isArray(v)

/** The backend's error code: `detail.code`, or the type of the first validation error. */
export function failureCode(data: any): string | null {
const detail = data?.detail ?? data
if (Array.isArray(detail)) {
const first = detail.find(isObject)
return typeof first?.type === "string" ? first.type : null
}
return typeof detail?.code === "string" ? detail.code : null
}

/** The backend's own message and code when it sends them, so the user sees why a call failed. */
export function describeFailure(status: number, data: any): string {
const detail = data?.detail ?? data
const code = failureCode(data)
const listed = Array.isArray(detail) ? detail.filter(isObject).map((e) => (typeof e.msg === "string" ? e.msg : "")).filter(Boolean) : []
const text = listed.length
? listed.join("; ")
: typeof detail?.message === "string" && detail.message
? detail.message

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: describeFailure forwards backend error text verbatim, so an API validation or conflict response that echoes a token, key, or secret can print it in CLI errors. Redact credential-bearing values before returning this message, especially text associated with credential field names.

(Based on your team's feedback about masking credential-bearing error text.)

View Feedback

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/integrations/backend.ts, line 77:

<comment>`describeFailure` forwards backend error text verbatim, so an API validation or conflict response that echoes a token, key, or secret can print it in CLI errors. Redact credential-bearing values before returning this message, especially text associated with credential field names.

(Based on your team's feedback about masking credential-bearing error text.) </comment>

<file context>
@@ -0,0 +1,155 @@
+  const text = listed.length
+    ? listed.join("; ")
+    : typeof detail?.message === "string" && detail.message
+      ? detail.message
+      : typeof detail === "string" && detail
+        ? detail
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Not changed: describeFailure only prints the backend's msg, message or string detail and the error code; it never prints the request body or the validation entry's input field, and the tokens we send are not echoed by those fields. No evidence that the backend echoes credentials, so redaction would be speculative.

: typeof detail === "string" && detail
? detail
: (FAILURE_TEXT[status] ?? `status ${status}`)
return code ? `${text} (${code})` : text
}

async function call<T>(cfg: BackendConfig, method: string, path: string, body?: unknown): Promise<T> {
const controller = new AbortController()
const timer = setTimeout(() => controller.abort(), 20_000)
try {
const res = await fetch(`${cfg.apiUrl}${path}`, {
method,
signal: controller.signal,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${cfg.token}`,
"x-tenant": cfg.tenant,
...AltimateApi.clientHeaders(),
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
})
const text = await res.text()
let data: any = null
let unreadable = false
try {
data = text ? JSON.parse(text) : null

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: call accepts a successful empty body as null, so list calls look empty and workspace attachment can replace existing integrations with an incomplete list. Reject empty 2xx responses for JSON endpoints, while explicitly allowing 204 deletes.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/opencode/src/altimate/integrations/backend.ts, line 112:

<comment>`call` accepts a successful empty body as `null`, so list calls look empty and workspace attachment can replace existing integrations with an incomplete list. Reject empty 2xx responses for JSON endpoints, while explicitly allowing 204 deletes.</comment>

<file context>
@@ -0,0 +1,175 @@
+    let data: any = null
+    let unreadable = false
+    try {
+      data = text ? JSON.parse(text) : null
+    } catch {
+      unreadable = true
</file context>

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in beafa4b: an answer without a connections list, including an empty 200 body, is now an error for both list calls, and an empty or non-record workspace answer is an error before any integrations list is built. 204 and empty DELETE answers are untouched. Tests added.

} catch {
unreadable = true
}
// A success that cannot be read is not an empty answer: an empty list would read as "no connections".
if (res.ok && unreadable) throw new BackendError(`The Altimate API answered ${res.status} with a body that is not JSON`, res.status, null)
if (!res.ok) {
throw new BackendError(describeFailure(res.status, data), res.status, failureCode(data))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
return data as T
} catch (e) {
if (e instanceof BackendError) throw e
// A transport error can quote the request, the key in its header included (Bun's invalid-header error does).
const text = redactSecrets(e instanceof Error ? e.message : String(e), [cfg.token])
throw new BackendError(`Could not reach the Altimate API: ${text}`, 0, null)
} finally {
clearTimeout(timer)
}
}

/** Every connection the caller can see, their own and those shared with them. */
export async function listVisibleConnections(cfg: BackendConfig): Promise<Connection[]> {
return connectionList(await call<{ connections?: Connection[] }>(cfg, "GET", "/connections/?include_shared=true"))
}
/** The list in a connections answer. An answer without one is an error: an empty list would read as "no connections". */
function connectionList(res: { connections?: Connection[] } | null): Connection[] {
if (!Array.isArray(res?.connections)) throw new BackendError("The Altimate API answered without a list of connections", 200, null)
return res.connections
}
/** The caller's own connections only: nothing shared with them. */
export const ownConnections = (all: Connection[]): Connection[] => all.filter((c) => c.is_owner !== false)
export async function listOwnConnections(cfg: BackendConfig): Promise<Connection[]> {
return ownConnections(connectionList(await call<{ connections?: Connection[] }>(cfg, "GET", "/connections/?include_shared=false")))
}
export const createConnection = (cfg: BackendConfig, body: { name: string; integration_id: string; config: Record<string, unknown> }) =>
call<Connection>(cfg, "POST", "/connections/", body)
export const updateConnection = (cfg: BackendConfig, id: number, body: { config: Record<string, unknown>; name?: string }) =>
call<Connection>(cfg, "PATCH", `/connections/${id}`, body)
export const deleteConnection = (cfg: BackendConfig, id: number) => call<unknown>(cfg, "DELETE", `/connections/${id}`)
/** The workspace integrations catalog: what each provider's web form asks for. */
export const integrationsCatalog = (cfg: BackendConfig) => call<unknown>(cfg, "GET", "/datamate_integrations/")

/** One integration entry of a workspace, as the datamates API stores it. */
export interface DatamateIntegrationEntry {
id: string
tools: Array<{ key: string }>
connection_id?: string | number | null
connection_ids?: string[] | null
[extra: string]: unknown
}
export interface DatamateRecord {
id: string
name: string
integrations: DatamateIntegrationEntry[]
/** False when the caller is not the workspace's owner: only the owner can change its integrations. */
is_owner?: boolean
/** "private" keeps an attached connection to its owner; any other value lets the workspace's members use it. */
privacy?: string
}

/** A workspace with its integrations list. */
export async function getDatamate(cfg: BackendConfig, id: string): Promise<DatamateRecord> {
let d: any
try {
const res = await call<any>(cfg, "GET", `/datamates/${encodeURIComponent(id)}/summary`)
d = res?.datamate ?? res
} catch (e) {
if (!(e instanceof BackendError) || e.status !== 404) throw e
// A backend without the summary route still lists its workspaces. The integrations list is replaced whole, so a listed workspace without one is not trusted.
const res = await call<any>(cfg, "GET", "/datamates/")
const all = Array.isArray(res) ? res : (res?.datamates ?? res?.data ?? [])
d = Array.isArray(all) ? all.find((x: any) => String(x?.id) === id) : undefined
if (!d) throw e
if (!Array.isArray(d.integrations)) throw new BackendError("The Altimate API listed the workspace without its integrations", 200, null)
}
// An answer that is not a workspace record is an error: building the next list from it could drop the workspace's integrations.
if (!isObject(d) || (d.id == null && d.name == null && !("integrations" in d))) throw new BackendError("The Altimate API answered without the workspace record", 200, null)
// The list is required in the workspace record and written back whole, so a missing or null one is as malformed as a non-list.
if (!Array.isArray(d.integrations)) throw new BackendError("The Altimate API answered with workspace integrations that are not a list", 200, null)
return { ...d, id: String(d.id ?? id), name: d.name ?? "", integrations: d.integrations }
}
/** Replaces the workspace's whole integrations list. */
export const updateDatamateIntegrations = (cfg: BackendConfig, id: string, integrations: DatamateIntegrationEntry[]) =>
call<unknown>(cfg, "PATCH", `/datamates/${encodeURIComponent(id)}`, { integrations })

export * as IntegrationsBackend from "./backend"
Loading
Loading