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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 159 additions & 0 deletions apps/contract/src/contract.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
import { optional } from "@codeworksh/schema/common";
import {
ConnectionConfig,
ConnectionSummary,
ConnectorCategory,
ConnectorError,
ConnectorKind,
ConnectorSpec,
DevicePollResult,
DeviceStartResult,
Ownership,
StoredAuthType,
} from "@codeworksh/schema/connector";
import { Machine } from "@codeworksh/schema/machine";
import { Schema } from "effect";
import { Rpc, RpcGroup } from "effect/rpc";
Expand All @@ -25,6 +37,47 @@ import { Event, EventTimeout, Publish, Request, Synced } from "@codeworksh/widge

export { CodeworkUnavailable, LineRequest, LineThread, SyncError, SyncThread, ThreadLine };

export class DesktopConnectorError extends Schema.TaggedError<DesktopConnectorError>()("Server.ConnectorError", {
message: Schema.String,
code: optional(Schema.String),
}) {}

export const ConnectorCatalogResponse = Schema.Struct({
schemaVersion: Schema.Literal(1),
generatedAt: Schema.String,
categories: Schema.Array(ConnectorCategory),
connectors: Schema.Array(ConnectorSpec),
});
export type ConnectorCatalogResponse = typeof ConnectorCatalogResponse.Type;

export const OAuthRunEvent = Schema.Union([
Schema.Struct({
_tag: Schema.Literal("Authorize"),
state: Schema.String,
authorizeUrl: Schema.String,
redirectUrl: Schema.String,
expiresAt: Schema.Finite,
}),
Schema.Struct({
_tag: Schema.Literal("Connected"),
connection: ConnectionSummary,
}),
]);
export type OAuthRunEvent = typeof OAuthRunEvent.Type;

export {
ConnectionConfig,
ConnectionSummary,
ConnectorCategory,
ConnectorError,
ConnectorKind,
ConnectorSpec,
DevicePollResult,
DeviceStartResult,
Ownership,
StoredAuthType,
};

/**
* Where a thread's work is, as Linear's workflow states. `enqueued` and `working` follow its runs: a
* run starting sets `working`, which stays when it ends; prompts parked before a run set `enqueued`.
Expand Down Expand Up @@ -1178,6 +1231,112 @@ export const Api = RpcGroup.make(
success: Schema.Void,
error: TrackingError,
}),
Rpc.make("connectors.catalog", {
payload: {
...OnMachine,
kind: optional(ConnectorKind),
category: optional(Schema.String),
query: optional(Schema.String),
refresh: optional(Schema.Boolean),
},
success: ConnectorCatalogResponse,
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
Rpc.make("connections.list", {
payload: {
...OnMachine,
kind: optional(ConnectorKind),
connectorId: optional(Schema.String),
enabled: optional(Schema.Boolean),
includeEnv: optional(Schema.Boolean),
},
success: Schema.Array(ConnectionSummary),
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
Rpc.make("connections.get", {
payload: { ...OnMachine, ref: Schema.String },
success: ConnectionSummary,
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
Rpc.make("connections.create", {
payload: {
...OnMachine,
connector: Schema.String,
slug: optional(Schema.String),
label: optional(Schema.String),
authType: optional(StoredAuthType),
ownership: optional(Ownership),
enabled: optional(Schema.Boolean),
isDefault: optional(Schema.Boolean),
config: optional(ConnectionConfig),
},
success: ConnectionSummary,
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
Rpc.make("connections.update", {
payload: {
...OnMachine,
ref: Schema.String,
uid: optional(Schema.String),
label: optional(Schema.NullOr(Schema.String)),
ownership: optional(Ownership),
enabled: optional(Schema.Boolean),
isDefault: optional(Schema.Boolean),
config: optional(ConnectionConfig),
},
success: ConnectionSummary,
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
Rpc.make("connections.remove", {
payload: { ...OnMachine, ref: Schema.String },
success: Schema.Struct({ removed: Schema.Boolean }),
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
Rpc.make("connections.setApiKey", {
payload: { ...OnMachine, ref: Schema.String, apiKey: Schema.String },
success: ConnectionSummary,
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
Rpc.make("connections.disconnect", {
payload: { ...OnMachine, ref: Schema.String },
success: ConnectionSummary,
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
/**
* Runs a client-side loopback OAuth callback flow against the target machine: emits `Authorize`
* with the consent URL, waits for the browser redirect on localhost, exchanges the code on the
* host machine, and emits `Connected`. Closing the stream cancels and closes the loopback server.
*/
Rpc.make("connections.oauth.run", {
payload: {
...OnMachine,
ref: Schema.String,
scopes: optional(Schema.Array(Schema.String)),
isCodex: optional(Schema.Boolean),
},
success: OAuthRunEvent,
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
stream: true,
}),
Rpc.make("connections.oauth.finish", {
payload: { ...OnMachine, state: Schema.String, code: Schema.String },
success: ConnectionSummary,
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
Rpc.make("connections.oauth.deviceStart", {
payload: {
...OnMachine,
ref: Schema.String,
enterpriseUrl: optional(Schema.String),
},
success: DeviceStartResult,
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
Rpc.make("connections.oauth.devicePoll", {
payload: { ...OnMachine, state: Schema.String },
success: DevicePollResult,
error: Schema.Union([CodeworkUnavailable, DesktopConnectorError]),
}),
Rpc.make("kv.get", {
payload: KvKey,
success: Schema.OptionFromNullOr(Schema.Json),
Expand Down
107 changes: 107 additions & 0 deletions apps/server/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ import {
type CliAction,
CodeworkUnavailable,
Contract,
DesktopConnectorError,
ModelsError,
type OAuthRunEvent,
ProjectError,
type ServerAdd,
ServersError,
Expand All @@ -24,6 +26,7 @@ import { Event } from "./event.ts";
import { Health } from "./health.ts";
import { Kv } from "./kv.ts";
import { Metrics } from "./metrics.ts";
import { acquireLoopback } from "./oauth-loopback.ts";
import { Reads } from "./reads.ts";
import { Skills } from "./skills.ts";
import { Servers } from "./servers.ts";
Expand Down Expand Up @@ -159,6 +162,36 @@ export const layer = Contract.Api.toLayer(
).pipe(
Effect.flatMap((reply) => ("failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.value))),
);
const connectorErrorTags: ReadonlyArray<string> = [
"Connector.NotFoundError",
"Connection.NotFoundError",
"Connection.ConflictError",
"Connector.ValidationError",
"Connector.AuthRequiredError",
"Connector.HostNotAllowedError",
"Connector.AuthError",
];
const isConnectorFailure = (error: unknown): error is { readonly _tag: string; readonly message: string } =>
Predicate.hasProperty(error, "_tag") &&
typeof error._tag === "string" &&
connectorErrorTags.includes(error._tag) &&
Predicate.hasProperty(error, "message") &&
typeof error.message === "string";
const connectorCall = <A, E>(use: Parameters<typeof Codework.call<A, E>>[0]) =>
call((client) =>
use(client).pipe(
Effect.map((value) => ({ value })),
Effect.catch((error) =>
isConnectorFailure(error)
? Effect.succeed({
failed: new DesktopConnectorError({ message: error.message, code: error._tag }),
})
: Effect.fail(error),
),
),
).pipe(
Effect.flatMap((reply) => ("failed" in reply ? Effect.fail(reply.failed) : Effect.succeed(reply.value))),
);
/**
* The connection to a paired machine, in the app's own words when there is none: refused once it is
* not paired any more, its address answers as another machine or its clock is apart, or not answering.
Expand Down Expand Up @@ -452,6 +485,80 @@ export const layer = Contract.Api.toLayer(
"sync.close": (ref) => sync.close(ref),
"sync.page": (input) => sync.page(input),

"connectors.catalog": ({ machineId, ...input }) =>
onMachine(machineId)(connectorCall((client) => client("connectors.catalog", input))),
"connections.list": ({ machineId, ...input }) =>
onMachine(machineId)(connectorCall((client) => client("connections.list", input))),
"connections.get": ({ machineId, ref }) =>
onMachine(machineId)(connectorCall((client) => client("connections.get", { ref }))),
"connections.create": ({ machineId, ...input }) =>
onMachine(machineId)(connectorCall((client) => client("connections.create", input))),
"connections.update": ({ machineId, ...input }) =>
onMachine(machineId)(connectorCall((client) => client("connections.update", input))),
"connections.remove": ({ machineId, ref }) =>
onMachine(machineId)(connectorCall((client) => client("connections.remove", { ref }))),
"connections.setApiKey": ({ machineId, ref, apiKey }) =>
onMachine(machineId)(connectorCall((client) => client("connections.setApiKey", { ref, apiKey }))),
"connections.disconnect": ({ machineId, ref }) =>
onMachine(machineId)(connectorCall((client) => client("connections.disconnect", { ref }))),
"connections.oauth.run": ({ machineId, ref, scopes, isCodex }) =>
Stream.unwrap(
Effect.gen(function* () {
const loopback = yield* acquireLoopback(
isCodex
? { host: "127.0.0.1", redirectHost: "localhost", port: 1455, path: "/auth/callback" }
: { host: "127.0.0.1", redirectHost: "127.0.0.1", port: 0, path: "/oauth/callback" },
).pipe(Effect.mapError((message) => new DesktopConnectorError({ message })));

const started = yield* onMachine(machineId)(
connectorCall((client) =>
client("connections.oauth.start", {
ref,
redirectUrl: loopback.redirectUrl,
...(scopes === undefined ? {} : { scopes }),
}),
),
);

const authorizeEvent: OAuthRunEvent = {
_tag: "Authorize",
state: started.state,
authorizeUrl: started.authorizeUrl,
redirectUrl: started.redirectUrl,
expiresAt: started.expiresAt,
};

const completion = Stream.fromEffect(
Effect.gen(function* () {
const code = yield* loopback
.wait(started.state)
.pipe(Effect.mapError((message) => new DesktopConnectorError({ message })));
const connection = yield* onMachine(machineId)(
connectorCall((client) =>
client("connections.oauth.finish", { state: started.state, code }),
),
);
return { _tag: "Connected", connection } satisfies OAuthRunEvent;
}),
);

return Stream.make(authorizeEvent).pipe(Stream.concat(completion));
}),
),
"connections.oauth.finish": ({ machineId, state, code }) =>
onMachine(machineId)(connectorCall((client) => client("connections.oauth.finish", { state, code }))),
"connections.oauth.deviceStart": ({ machineId, ref, enterpriseUrl }) =>
onMachine(machineId)(
connectorCall((client) =>
client("connections.oauth.deviceStart", {
ref,
...(enterpriseUrl === undefined ? {} : { enterpriseUrl }),
}),
),
),
"connections.oauth.devicePoll": ({ machineId, state }) =>
onMachine(machineId)(connectorCall((client) => client("connections.oauth.devicePoll", { state }))),

"kv.get": ({ package: pkg, key }) => kv.get(pkg, key),
"kv.set": ({ package: pkg, key, value }) => kv.set(pkg, key, value),

Expand Down
Loading