@execution-associates/isb-alchemy 0.0.0-stage → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ import * as Provider from "alchemy/Provider";
2
+ import { Resource } from "alchemy/Resource";
3
+ import * as Redacted from "effect/Redacted";
4
+ export interface SecretProps {
5
+ /** The secret's name in the org's store. */
6
+ name: string;
7
+ /** Its value. Use `Redacted.make(...)` or `Config.redacted(...)`. */
8
+ value: Redacted.Redacted<string>;
9
+ }
10
+ export interface SecretAttributes {
11
+ name: string;
12
+ /** The version isb holds now. */
13
+ version: number;
14
+ /** SHA-256 of the value last written, to tell whether it changed. */
15
+ valueHash: string;
16
+ /** What an app's `env` takes to read this secret: `{ secret: name }`. */
17
+ ref: {
18
+ secret: string;
19
+ };
20
+ }
21
+ export type Secret = Resource<"Isb.Secret", SecretProps, SecretAttributes>;
22
+ /**
23
+ * A secret in the org's store. isb holds the value; apps and stacks name
24
+ * it, and it reaches them as the one variable or file that asks for it.
25
+ *
26
+ * ```typescript
27
+ * const dbUrl = yield* Isb.Secret("db-url", {
28
+ * name: "shop-db-url",
29
+ * value: yield* Config.redacted("DATABASE_URL"),
30
+ * });
31
+ * yield* Isb.App("web", { ..., env: { DATABASE_URL: dbUrl.ref } });
32
+ * ```
33
+ *
34
+ * A new value is a new version in isb, and the services that use the
35
+ * secret roll (or do what their `on_change` says). The same value again
36
+ * writes nothing.
37
+ */
38
+ export declare const Secret: import("alchemy/Resource").ResourceClass<Secret>;
39
+ export declare const SecretProvider: () => import("effect/Layer").Layer<Provider.Provider<Secret>, never, import("./Client.ts").Credentials>;
package/dist/Secret.js ADDED
@@ -0,0 +1,48 @@
1
+ import * as Provider from "alchemy/Provider";
2
+ import { Resource } from "alchemy/Resource";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Redacted from "effect/Redacted";
5
+ import { call, callFound } from "./Client.js";
6
+ import { replaceWhen } from "./Replace.js";
7
+ const sha256 = (text) => Effect.promise(async () => {
8
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
9
+ return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
10
+ });
11
+ const base64 = (text) => Buffer.from(text, "utf8").toString("base64");
12
+ /**
13
+ * A secret in the org's store. isb holds the value; apps and stacks name
14
+ * it, and it reaches them as the one variable or file that asks for it.
15
+ *
16
+ * ```typescript
17
+ * const dbUrl = yield* Isb.Secret("db-url", {
18
+ * name: "shop-db-url",
19
+ * value: yield* Config.redacted("DATABASE_URL"),
20
+ * });
21
+ * yield* Isb.App("web", { ..., env: { DATABASE_URL: dbUrl.ref } });
22
+ * ```
23
+ *
24
+ * A new value is a new version in isb, and the services that use the
25
+ * secret roll (or do what their `on_change` says). The same value again
26
+ * writes nothing.
27
+ */
28
+ export const Secret = Resource("Isb.Secret");
29
+ export const SecretProvider = () => Provider.succeed(Secret, {
30
+ stables: ["name", "ref"],
31
+ diff: replaceWhen((p) => p.name),
32
+ reconcile: Effect.fn(function* ({ news, output }) {
33
+ const valueHash = yield* sha256(Redacted.value(news.value));
34
+ const observed = yield* callFound("secret_inspect", {
35
+ name: news.name,
36
+ });
37
+ // The value cannot be read back, so what tells a change is the hash
38
+ // of what this resource last wrote.
39
+ if (observed === undefined || output?.valueHash !== valueHash) {
40
+ yield* call("secret_set", { name: news.name, value: base64(Redacted.value(news.value)) });
41
+ }
42
+ const now = yield* call("secret_inspect", { name: news.name });
43
+ return { name: news.name, version: now.version, valueHash, ref: { secret: news.name } };
44
+ }),
45
+ delete: Effect.fn(function* ({ output }) {
46
+ yield* callFound("secret_delete", { name: output.name });
47
+ }),
48
+ });
@@ -0,0 +1,52 @@
1
+ import * as Provider from "alchemy/Provider";
2
+ import { Resource } from "alchemy/Resource";
3
+ export interface StackProps {
4
+ /** The stack's name: lowercase letters, digits and `-`, at most 30. */
5
+ name: string;
6
+ /** The compose file, as YAML text. */
7
+ compose: string;
8
+ /** Values for `${VAR}` in the compose file. */
9
+ vars?: Record<string, string>;
10
+ /**
11
+ * The project a new stack belongs to. Default: one named like the stack,
12
+ * which isb makes and which is deleted with the stack.
13
+ */
14
+ project?: string;
15
+ /** The project's environment. Default: `production`. */
16
+ environment?: string;
17
+ /**
18
+ * Delete the stack's named volumes when the stack is destroyed.
19
+ * @default false
20
+ */
21
+ removeVolumes?: boolean;
22
+ /**
23
+ * How long the services may take to converge, in seconds.
24
+ * @default 600
25
+ */
26
+ timeoutSeconds?: number;
27
+ }
28
+ export interface StackAttributes {
29
+ name: string;
30
+ /** Each service's revision: it changes when the service is replaced. */
31
+ revisions: Record<string, string>;
32
+ }
33
+ export type Stack = Resource<"Isb.Stack", StackProps, StackAttributes>;
34
+ /**
35
+ * A compose file run as an isb stack: long-running services with
36
+ * replicas, health checks, a load balancer on published ports and rolling
37
+ * updates.
38
+ *
39
+ * ```typescript
40
+ * yield* Isb.Stack("wiki", {
41
+ * name: "wiki",
42
+ * compose: yield* Effect.promise(() => Bun.file("compose.yaml").text()),
43
+ * vars: { TAG: "1.27" },
44
+ * });
45
+ * ```
46
+ *
47
+ * A deploy replaces only the services whose settings or image digest
48
+ * changed, so deploying the same file again rolls nothing. A stack's name
49
+ * cannot change; changing it replaces the stack.
50
+ */
51
+ export declare const Stack: import("alchemy/Resource").ResourceClass<Stack>;
52
+ export declare const StackProvider: () => import("effect/Layer").Layer<Provider.Provider<Stack>, never, import("./Client.ts").Credentials>;
package/dist/Stack.js ADDED
@@ -0,0 +1,75 @@
1
+ import * as Provider from "alchemy/Provider";
2
+ import { Resource } from "alchemy/Resource";
3
+ import * as Effect from "effect/Effect";
4
+ import { call, callFound, IsbError } from "./Client.js";
5
+ import { replaceWhen } from "./Replace.js";
6
+ /** Poll until every service has converged, or one has given up. */
7
+ const settle = (name, timeoutSeconds) => Effect.gen(function* () {
8
+ const deadline = Date.now() + timeoutSeconds * 1000;
9
+ while (true) {
10
+ const status = yield* call("stack_status", { name });
11
+ if (status.converged)
12
+ return status;
13
+ const stuck = status.services.filter((s) => s.state === "paused" || s.state === "failing");
14
+ const late = Date.now() > deadline;
15
+ if (stuck.length > 0 || late) {
16
+ const why = (stuck.length > 0 ? stuck : status.services.filter((s) => s.state !== "converged"))
17
+ .map((s) => `${s.service}: ${s.state}${s.message ? ` (${s.message})` : ""}`)
18
+ .join("; ");
19
+ return yield* Effect.fail(new IsbError({
20
+ tool: "stack_deploy",
21
+ code: late && stuck.length === 0 ? "timeout" : "deploy_failed",
22
+ status: 0,
23
+ message: `isb: stack ${name} did not converge: ${why}`,
24
+ }));
25
+ }
26
+ yield* Effect.sleep("1 second");
27
+ }
28
+ });
29
+ /**
30
+ * A compose file run as an isb stack: long-running services with
31
+ * replicas, health checks, a load balancer on published ports and rolling
32
+ * updates.
33
+ *
34
+ * ```typescript
35
+ * yield* Isb.Stack("wiki", {
36
+ * name: "wiki",
37
+ * compose: yield* Effect.promise(() => Bun.file("compose.yaml").text()),
38
+ * vars: { TAG: "1.27" },
39
+ * });
40
+ * ```
41
+ *
42
+ * A deploy replaces only the services whose settings or image digest
43
+ * changed, so deploying the same file again rolls nothing. A stack's name
44
+ * cannot change; changing it replaces the stack.
45
+ */
46
+ export const Stack = Resource("Isb.Stack");
47
+ export const StackProvider = () => Provider.succeed(Stack, {
48
+ stables: ["name"],
49
+ diff: replaceWhen((p) => p.name),
50
+ reconcile: Effect.fn(function* ({ news }) {
51
+ yield* call("stack_deploy", {
52
+ name: news.name,
53
+ compose: news.compose,
54
+ ...(news.vars && { vars: news.vars }),
55
+ ...(news.project && { project: news.project }),
56
+ ...(news.environment && { environment: news.environment }),
57
+ });
58
+ const status = yield* settle(news.name, news.timeoutSeconds ?? 600);
59
+ return {
60
+ name: news.name,
61
+ revisions: Object.fromEntries(status.services.map((s) => [s.service, s.rev])),
62
+ };
63
+ }),
64
+ delete: Effect.fn(function* ({ olds, output }) {
65
+ yield* callFound("stack_remove", {
66
+ name: output.name,
67
+ volumes: olds.removeVolumes ?? false,
68
+ });
69
+ // A stack deployed without `project` got one of its own name from
70
+ // isb. It goes with the stack, unless something else moved in.
71
+ if (olds.project === undefined) {
72
+ yield* call("project_delete", { name: output.name }).pipe(Effect.catchTag("IsbError", () => Effect.void));
73
+ }
74
+ }),
75
+ });
@@ -0,0 +1,6 @@
1
+ export * from "./App.ts";
2
+ export * from "./Client.ts";
3
+ export * from "./Project.ts";
4
+ export * from "./Providers.ts";
5
+ export * from "./Secret.ts";
6
+ export * from "./Stack.ts";
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export * from "./App.js";
2
+ export * from "./Client.js";
3
+ export * from "./Project.js";
4
+ export * from "./Providers.js";
5
+ export * from "./Secret.js";
6
+ export * from "./Stack.js";
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@execution-associates/isb-alchemy",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.4.0",
4
+ "description": "Alchemy provider for isb: deploy apps, stacks and secrets to an isb host as infrastructure-as-code",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/execution-associates/isb.git",
11
+ "directory": "sdk/alchemy"
12
+ },
13
+ "homepage": "https://github.com/execution-associates/isb/tree/main/sdk/alchemy#readme",
14
+ "keywords": ["alchemy", "isb", "incus", "infrastructure-as-code", "effect", "paas"],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "bun": "./src/index.ts",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "files": ["dist", "src", "README.md", "LICENSE"],
26
+ "engines": {
27
+ "bun": ">=1.2",
28
+ "node": ">=24"
29
+ },
30
+ "scripts": {
31
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
32
+ "typecheck": "tsc --noEmit",
33
+ "lint": "biome check src test examples",
34
+ "format": "biome format --write src test examples",
35
+ "test": "bun test",
36
+ "prepack": "bun run build"
37
+ },
38
+ "peerDependencies": {
39
+ "alchemy": ">=2.0.0-beta.87",
40
+ "effect": "^4.1.4"
41
+ },
42
+ "devDependencies": {
43
+ "@alchemy.run/test": "2.0.0-beta.87",
44
+ "@biomejs/biome": "^2.2.0",
45
+ "@types/bun": "^1.2.0",
46
+ "alchemy": "2.0.0-beta.87",
47
+ "effect": "^4.1.4",
48
+ "typescript": "^5.9.0"
49
+ }
50
+ }
package/src/App.ts ADDED
@@ -0,0 +1,210 @@
1
+ import * as Provider from "alchemy/Provider";
2
+ import { Resource } from "alchemy/Resource";
3
+ import * as Effect from "effect/Effect";
4
+ import { call, callFound, IsbError } from "./Client.ts";
5
+ import { replaceWhen } from "./Replace.ts";
6
+
7
+ /** Where an app's image comes from. */
8
+ export type AppSource =
9
+ | { image: string }
10
+ | {
11
+ git: {
12
+ url: string;
13
+ ref?: string;
14
+ subdir?: string;
15
+ auth?: { token_secret?: string; ssh_key_secret?: string };
16
+ };
17
+ }
18
+ | { database: Record<string, unknown> };
19
+
20
+ /** A plain value, or a secret in the org's store (`Isb.Secret`'s `ref`). */
21
+ export type EnvValue = string | { secret: string };
22
+
23
+ /**
24
+ * An app as isb's `app_apply` takes it (the YAML of `isb app export`, as
25
+ * an object). The fields listed are the common ones; any other field of
26
+ * an app definition passes through as written.
27
+ */
28
+ export interface AppProps {
29
+ /** The app's name: its service, and how other apps reach it. */
30
+ name: string;
31
+ project: string;
32
+ /** @default "production" */
33
+ environment?: string;
34
+ source: AppSource;
35
+ build?: { builder: Record<string, unknown>; args?: Record<string, string> };
36
+ env?: Record<string, EnvValue>;
37
+ domains?: ({ host: string; path?: string; port?: number } & Record<string, unknown>)[];
38
+ /** `NAME:/path` named volumes. */
39
+ volumes?: string[];
40
+ /** `[IP:]PUBLISHED:TARGET` host ports. */
41
+ ports?: string[];
42
+ replicas?: number;
43
+ /** The port the app listens on, for domains and the health check. */
44
+ port?: number;
45
+ healthcheck?: Record<string, unknown>;
46
+ resources?: { cpus?: string; memory?: string };
47
+ command?: string | string[];
48
+ /**
49
+ * What a deploy does to instances that already run exactly this:
50
+ * `"if-changed"` leaves them running (the settings and the image digest
51
+ * are the same), `"always"` replaces them on every deploy.
52
+ * @default "if-changed"
53
+ */
54
+ redeploy?: "if-changed" | "always";
55
+ /**
56
+ * How long a deployment may take before the deploy fails, in seconds.
57
+ * @default 900
58
+ */
59
+ timeoutSeconds?: number;
60
+ [field: string]: unknown;
61
+ }
62
+
63
+ export interface AppAttributes {
64
+ name: string;
65
+ project: string;
66
+ environment: string;
67
+ /** The stack the app's service runs in: `<project>-<environment>`. */
68
+ stack: string;
69
+ /** The name other services in the org reach it by. */
70
+ serviceName: string;
71
+ /** The deployment that last ran, and what it deployed. */
72
+ deployment: number;
73
+ image: string | undefined;
74
+ digest: string | undefined;
75
+ /** The last deployment changed nothing, and the instances were left running. */
76
+ unchanged: boolean;
77
+ /** `https://<host><path>` for each of the app's domains. */
78
+ urls: string[];
79
+ }
80
+
81
+ export type App = Resource<"Isb.App", AppProps, AppAttributes>;
82
+
83
+ interface DeploymentRecord {
84
+ id: number;
85
+ status: string;
86
+ image?: string;
87
+ digest?: string;
88
+ error?: string;
89
+ unchanged?: boolean;
90
+ }
91
+
92
+ interface AppRecord {
93
+ name: string;
94
+ project: string;
95
+ environment: string;
96
+ stack: string;
97
+ service_name: string;
98
+ domains?: { host: string; path?: string }[];
99
+ }
100
+
101
+ /** Follow a deployment's log until it finishes; its record and the log. */
102
+ const follow = (name: string, id: number, timeoutSeconds: number) =>
103
+ Effect.gen(function* () {
104
+ let offset = 0;
105
+ let log = "";
106
+ const deadline = Date.now() + timeoutSeconds * 1000;
107
+ while (true) {
108
+ const page = yield* call<{
109
+ log: string;
110
+ offset: number;
111
+ finished: boolean;
112
+ deployment: DeploymentRecord;
113
+ }>("app_deployment_log", { name, deployment: id, offset });
114
+ log += page.log;
115
+ offset = page.offset;
116
+ if (page.finished) return { record: page.deployment, log };
117
+ if (Date.now() > deadline) {
118
+ return yield* Effect.fail(
119
+ new IsbError({
120
+ tool: "app_deployment_log",
121
+ code: "timeout",
122
+ status: 0,
123
+ message: `isb: deployment ${id} of app ${name} did not finish within ${timeoutSeconds}s`,
124
+ }),
125
+ );
126
+ }
127
+ yield* Effect.sleep("1 second");
128
+ }
129
+ });
130
+
131
+ /** The last lines of a deployment log, for an error message. */
132
+ const tail = (log: string, lines = 15) => log.trimEnd().split("\n").slice(-lines).join("\n");
133
+
134
+ /**
135
+ * An app on isb: an image (or a git repository isb builds), run as a
136
+ * health-checked service with rolling updates, domains, volumes and
137
+ * secrets.
138
+ *
139
+ * Each deploy applies the whole definition (`app_apply`), deploys it and
140
+ * waits for the service to converge. A deploy that changes nothing leaves
141
+ * the running instances alone: isb compares the settings and the image's
142
+ * digest, so a tag that moved on its registry still rolls out.
143
+ *
144
+ * ```typescript
145
+ * const web = yield* Isb.App("web", {
146
+ * name: "web",
147
+ * project: shop.name,
148
+ * source: { image: "ghcr:acme/shop:1.4.0" },
149
+ * port: 8080,
150
+ * replicas: 2,
151
+ * domains: [{ host: "shop.example.com" }],
152
+ * env: { LOG_LEVEL: "info", DATABASE_URL: dbUrl.ref },
153
+ * });
154
+ * ```
155
+ *
156
+ * The definition is the app's whole desired state: a domain, variable,
157
+ * volume or port left out of it is removed from the app. An app's `name`,
158
+ * `project` and `environment` cannot change, so changing one replaces the
159
+ * app. Destroying it keeps its named volumes.
160
+ */
161
+ export const App = Resource<App>("Isb.App");
162
+
163
+ export const AppProvider = () =>
164
+ Provider.succeed(App, {
165
+ stables: ["name", "project", "environment", "stack", "serviceName"],
166
+ // An app's name, project and environment cannot change. The old app
167
+ // goes first: the replacement takes its service name.
168
+ diff: replaceWhen<AppProps>((p) => [p.name, p.project, p.environment ?? "production"], {
169
+ deleteFirst: true,
170
+ }),
171
+ reconcile: Effect.fn(function* ({ news }) {
172
+ const { redeploy = "if-changed", timeoutSeconds = 900, ...definition } = news;
173
+ const applied = yield* call<{ deployment: { id: number } }>("app_apply", {
174
+ definition,
175
+ deploy: true,
176
+ if_changed: redeploy === "if-changed",
177
+ // The definition here is the source of truth, removals included.
178
+ allow_removals: true,
179
+ });
180
+ const { record, log } = yield* follow(news.name, applied.deployment.id, timeoutSeconds);
181
+ if (record.status !== "done") {
182
+ return yield* Effect.fail(
183
+ new IsbError({
184
+ tool: "app_deploy",
185
+ code: "deploy_failed",
186
+ status: 0,
187
+ message: `isb: deployment ${record.id} of app ${news.name} ${record.status}: ${
188
+ record.error ?? "no reason given"
189
+ }\n${tail(log)}`,
190
+ }),
191
+ );
192
+ }
193
+ const app = yield* call<AppRecord>("app_get", { name: news.name });
194
+ return {
195
+ name: app.name,
196
+ project: app.project,
197
+ environment: app.environment,
198
+ stack: app.stack,
199
+ serviceName: app.service_name,
200
+ deployment: record.id,
201
+ image: record.image,
202
+ digest: record.digest,
203
+ unchanged: record.unchanged ?? false,
204
+ urls: (app.domains ?? []).map((d) => `https://${d.host}${d.path ?? ""}`),
205
+ };
206
+ }),
207
+ delete: Effect.fn(function* ({ output }) {
208
+ yield* callFound("app_delete", { name: output.name });
209
+ }),
210
+ });
package/src/Client.ts ADDED
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The connection to an isb host: where it is, the org to act in and an API
3
+ * token, plus `call`, which runs one isb tool over its REST API
4
+ * (`POST /orgs/<org>/api/v1/tools/<tool>`).
5
+ */
6
+ import * as Context from "effect/Context";
7
+ import * as Data from "effect/Data";
8
+ import * as Effect from "effect/Effect";
9
+ import * as Layer from "effect/Layer";
10
+ import * as Redacted from "effect/Redacted";
11
+
12
+ export interface IsbConfig {
13
+ /** The isb server, e.g. `https://isb.example.com`. */
14
+ readonly url: string;
15
+ /** The org every resource lives in. */
16
+ readonly org: string;
17
+ /** An API token (`isb token create`), a member of `org` or above. */
18
+ readonly token: Redacted.Redacted<string>;
19
+ }
20
+
21
+ /** A tool call isb refused or that never reached it. */
22
+ export class IsbError extends Data.TaggedError("IsbError")<{
23
+ /** The tool that was called. */
24
+ readonly tool: string;
25
+ /** isb's error code (`invalid`, `not_found`, `forbidden`, ...), or `unreachable`. */
26
+ readonly code: string;
27
+ /** The HTTP status, 0 when there was no answer. */
28
+ readonly status: number;
29
+ readonly message: string;
30
+ readonly data?: unknown;
31
+ }> {}
32
+
33
+ /**
34
+ * The connection, resolved when a resource first needs it, so a stack that
35
+ * deploys nothing to isb never asks for a token.
36
+ */
37
+ export class Credentials extends Context.Service<Credentials, Effect.Effect<IsbConfig, IsbError>>()(
38
+ "IsbCredentials",
39
+ ) {}
40
+
41
+ export interface CredentialsInput {
42
+ readonly url: string;
43
+ readonly token: string | Redacted.Redacted<string>;
44
+ /** Default: `default`. */
45
+ readonly org?: string;
46
+ }
47
+
48
+ /** A connection given in code. */
49
+ export const fromConfig = (input: CredentialsInput): Layer.Layer<Credentials> =>
50
+ Layer.succeed(
51
+ Credentials,
52
+ Effect.succeed({
53
+ url: input.url,
54
+ org: input.org ?? "default",
55
+ token: typeof input.token === "string" ? Redacted.make(input.token) : input.token,
56
+ }),
57
+ );
58
+
59
+ /**
60
+ * A connection from the environment the isb CLI reads: `ISB_URL`,
61
+ * `ISB_TOKEN` and, optionally, `ISB_ORG` (default `default`).
62
+ */
63
+ export const fromEnv = (): Layer.Layer<Credentials> =>
64
+ Layer.succeed(
65
+ Credentials,
66
+ Effect.suspend(() => {
67
+ const { ISB_URL: url, ISB_TOKEN: token, ISB_ORG: org } = process.env;
68
+ if (!url || !token) {
69
+ return Effect.fail(
70
+ new IsbError({
71
+ tool: "",
72
+ code: "unauthorized",
73
+ status: 0,
74
+ message:
75
+ "isb: set ISB_URL (the server) and ISB_TOKEN (an API token from `isb token create`)",
76
+ }),
77
+ );
78
+ }
79
+ return Effect.succeed({ url, org: org || "default", token: Redacted.make(token) });
80
+ }),
81
+ );
82
+
83
+ /** Run one isb tool and return its result. */
84
+ export const call = <T = unknown>(
85
+ tool: string,
86
+ args: Record<string, unknown> = {},
87
+ ): Effect.Effect<T, IsbError, Credentials> =>
88
+ Effect.gen(function* () {
89
+ const config = yield* yield* Credentials;
90
+ const base = config.url.replace(/\/+$/, "");
91
+ const url = `${base}/orgs/${encodeURIComponent(config.org)}/api/v1/tools/${tool}`;
92
+ return yield* Effect.tryPromise({
93
+ try: async (signal) => {
94
+ const res = await fetch(url, {
95
+ method: "POST",
96
+ headers: {
97
+ authorization: `Bearer ${Redacted.value(config.token)}`,
98
+ "content-type": "application/json",
99
+ },
100
+ body: JSON.stringify(args),
101
+ signal,
102
+ });
103
+ const text = await res.text();
104
+ let body: { result?: unknown; error?: string; message?: string; data?: unknown };
105
+ try {
106
+ body = JSON.parse(text);
107
+ } catch {
108
+ body = { error: "bad_response", message: text.slice(0, 300) || res.statusText };
109
+ }
110
+ if (!res.ok || body.error !== undefined) {
111
+ throw new IsbError({
112
+ tool,
113
+ code: body.error ?? "error",
114
+ status: res.status,
115
+ message: `isb ${tool}: ${body.message ?? res.statusText}`,
116
+ data: body.data,
117
+ });
118
+ }
119
+ return body.result as T;
120
+ },
121
+ catch: (e) =>
122
+ e instanceof IsbError
123
+ ? e
124
+ : new IsbError({
125
+ tool,
126
+ code: "unreachable",
127
+ status: 0,
128
+ message: `isb ${tool}: ${config.url} did not answer (${String(e)})`,
129
+ }),
130
+ });
131
+ });
132
+
133
+ /** `call`, with "there is no such thing" as `undefined`. */
134
+ export const callFound = <T = unknown>(tool: string, args: Record<string, unknown> = {}) =>
135
+ call<T>(tool, args).pipe(
136
+ Effect.catchTag("IsbError", (e) =>
137
+ e.code === "not_found" ? Effect.succeed(undefined) : Effect.fail(e),
138
+ ),
139
+ );