@gloaming/caw-plugin-sdk 0.0.0-stage → 1.0.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.
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@gloaming/caw-plugin-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "exports": {
6
+ "./ids": "./src/ids.ts",
7
+ "./channel": "./src/channel.ts",
8
+ "./harness": "./src/harness.ts",
9
+ "./tool": "./src/tool.ts",
10
+ "./profile": "./src/profile.ts",
11
+ "./conversation": "./src/conversation.ts",
12
+ "./events": "./src/events.ts",
13
+ "./interceptors": "./src/interceptors.ts",
14
+ "./plugin": "./src/plugin.ts",
15
+ "./cli-command": "./src/cli-command.ts",
16
+ "./setup": "./src/setup.ts"
17
+ },
18
+ "dependencies": {
19
+ "@effect/sql-sqlite-bun": "4.1.4",
20
+ "effect": "4.1.4"
21
+ },
22
+ "description": "The SDK for writing Caw plugins.",
23
+ "license": "UNLICENSED",
24
+ "files": [
25
+ "src"
26
+ ],
27
+ "engines": {
28
+ "bun": ">=1.4.4"
29
+ }
30
+ }
package/src/channel.ts ADDED
@@ -0,0 +1,104 @@
1
+ import type { DateTime, Effect, Option, Scope, Stream } from "effect";
2
+ import { Data, Schema } from "effect";
3
+ import type { ChannelMessageId, ChannelName, ExternalConversationId } from "./ids.ts";
4
+
5
+ /** Where a Conversation sits on its platform. A thread is a child Conversation of `parent`. */
6
+ export type ConversationPlace = Data.TaggedEnum<{
7
+ Room: {};
8
+ Thread: { readonly parent: ExternalConversationId };
9
+ Direct: {};
10
+ }>;
11
+
12
+ export const ConversationPlace = Data.taggedEnum<ConversationPlace>();
13
+
14
+ export interface Author {
15
+ readonly id: string;
16
+ readonly name: string;
17
+ }
18
+
19
+ export interface QuotedMessage {
20
+ readonly messageId: ChannelMessageId;
21
+ readonly author: Author;
22
+ readonly text: string;
23
+ }
24
+
25
+ export interface Attachment {
26
+ readonly name: string;
27
+ readonly url: string;
28
+ readonly contentType: Option.Option<string>;
29
+ }
30
+
31
+ /** One message as a Channel parsed it from its platform. */
32
+ export interface ChannelMessage {
33
+ readonly channel: ChannelName;
34
+ readonly conversation: ExternalConversationId;
35
+ readonly place: ConversationPlace;
36
+ readonly messageId: ChannelMessageId;
37
+ readonly author: Author;
38
+ readonly text: string;
39
+ readonly sentAt: DateTime.Utc;
40
+ readonly replyTo: Option.Option<QuotedMessage>;
41
+ readonly attachments: ReadonlyArray<Attachment>;
42
+ }
43
+
44
+ export type ChannelCommandName = "new" | "stop";
45
+
46
+ /** What a Channel delivers to core: a person's message, or a control command (`/new`, `/stop`). */
47
+ export type ChannelInput = Data.TaggedEnum<{
48
+ Message: { readonly message: ChannelMessage };
49
+ Command: {
50
+ readonly channel: ChannelName;
51
+ readonly conversation: ExternalConversationId;
52
+ readonly place: ConversationPlace;
53
+ readonly command: ChannelCommandName;
54
+ /** Answers the command on the platform (e.g. a Discord interaction reply). Call exactly once. */
55
+ readonly respond: (text: string) => Effect.Effect<void, ChannelError>;
56
+ };
57
+ }>;
58
+
59
+ export const ChannelInput = Data.taggedEnum<ChannelInput>();
60
+
61
+ export class ChannelError extends Schema.TaggedError<
62
+ ChannelError,
63
+ { readonly brand: unique symbol }
64
+ >()("ChannelError", {
65
+ channel: Schema.String,
66
+ operation: Schema.String,
67
+ cause: Schema.Defect(),
68
+ }) {}
69
+
70
+ /**
71
+ * An integration with a chat platform. Implementations own platform limits
72
+ * (message length chunking, typing refresh intervals) so core never sees them.
73
+ */
74
+ export interface Channel {
75
+ readonly name: ChannelName;
76
+ /** Text for the system prompt naming the markup this platform renders, e.g. "Discord markdown". */
77
+ readonly markup: string;
78
+ readonly inputs: Stream.Stream<ChannelInput, ChannelError>;
79
+ /** Posts `text`, split into as many platform messages as needed, in order. */
80
+ readonly send: (
81
+ conversation: ExternalConversationId,
82
+ text: string,
83
+ ) => Effect.Effect<ReadonlyArray<ChannelMessageId>, ChannelError>;
84
+ /** Opens a thread from an existing message and returns the thread's id. */
85
+ readonly openThread: (
86
+ conversation: ExternalConversationId,
87
+ from: ChannelMessageId,
88
+ name: string,
89
+ ) => Effect.Effect<ExternalConversationId, ChannelError>;
90
+ readonly react: (
91
+ conversation: ExternalConversationId,
92
+ message: ChannelMessageId,
93
+ emoji: string,
94
+ ) => Effect.Effect<void, ChannelError>;
95
+ /** Shows a typing indicator for as long as the surrounding scope stays open. */
96
+ readonly typing: (
97
+ conversation: ExternalConversationId,
98
+ ) => Effect.Effect<void, never, Scope.Scope>;
99
+ /** The most recent `limit` messages of a Conversation, oldest first. */
100
+ readonly history: (
101
+ conversation: ExternalConversationId,
102
+ limit: number,
103
+ ) => Effect.Effect<ReadonlyArray<ChannelMessage>, ChannelError>;
104
+ }
@@ -0,0 +1,127 @@
1
+ import {
2
+ Console,
3
+ Context,
4
+ Effect,
5
+ FileSystem,
6
+ Formatter,
7
+ Layer,
8
+ Path,
9
+ Predicate,
10
+ Stdio,
11
+ Terminal,
12
+ } from "effect";
13
+ import type { CliError, Command } from "effect/cli";
14
+ import { CliConfig, CliOutput, GlobalFlag, Command as Cli } from "effect/cli";
15
+ import { ChildProcessSpawner } from "effect/process";
16
+ import type { CliCommand, CliContext } from "./plugin.ts";
17
+ import { CliCommandError } from "./plugin.ts";
18
+
19
+ /** The `CliContext` of the invocation a command handler runs in. */
20
+ export class CurrentCliContext extends Context.Service<CurrentCliContext, CliContext>()(
21
+ "@gloaming/caw-plugin-sdk/CurrentCliContext",
22
+ ) {}
23
+
24
+ /**
25
+ * Runs inside the daemon, so nothing may touch the host terminal, process or
26
+ * files on the CLI's behalf. Only `--help` stays as a built-in flag.
27
+ */
28
+ const daemonEnvironment = Layer.mergeAll(
29
+ FileSystem.layerNoop({}),
30
+ Path.layer,
31
+ Stdio.layerTest({}),
32
+ Layer.succeed(
33
+ Terminal.Terminal,
34
+ Terminal.make({
35
+ columns: Effect.succeed(100),
36
+ rows: Effect.succeed(40),
37
+ size: Effect.die("A daemon CLI command has no terminal"),
38
+ readInput: Effect.die("A daemon CLI command has no terminal"),
39
+ readLine: Effect.die("A daemon CLI command has no terminal"),
40
+ display: () => Effect.die("A daemon CLI command has no terminal"),
41
+ }),
42
+ ),
43
+ Layer.succeed(
44
+ ChildProcessSpawner.ChildProcessSpawner,
45
+ ChildProcessSpawner.make(() => Effect.die("A daemon CLI command cannot spawn processes")),
46
+ ),
47
+ CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),
48
+ CliConfig.layer({ builtIns: [GlobalFlag.Help] }),
49
+ );
50
+
51
+ const formatLine = (parts: ReadonlyArray<unknown>): string =>
52
+ parts.map((part) => (Predicate.isString(part) ? part : Formatter.format(part))).join(" ");
53
+
54
+ const ignore = (): void => {};
55
+
56
+ /** A `Console` that keeps every printed line, stdout and stderr interleaved, in order. */
57
+ const makeBufferedConsole = () => {
58
+ const lines: Array<string> = [];
59
+
60
+ const record = (...parts: ReadonlyArray<unknown>): void => {
61
+ lines.push(formatLine(parts));
62
+ };
63
+
64
+ const console: Console.Console = {
65
+ assert: ignore,
66
+ clear: ignore,
67
+ count: ignore,
68
+ countReset: ignore,
69
+ debug: record,
70
+ dir: record,
71
+ dirxml: record,
72
+ error: record,
73
+ group: ignore,
74
+ groupCollapsed: ignore,
75
+ groupEnd: ignore,
76
+ info: record,
77
+ log: record,
78
+ table: record,
79
+ time: ignore,
80
+ timeEnd: ignore,
81
+ timeLog: ignore,
82
+ trace: record,
83
+ warn: record,
84
+ };
85
+
86
+ return { console, text: () => lines.join("\n") };
87
+ };
88
+
89
+ /**
90
+ * Turns an `effect/cli` command into a `CliCommand`. `run` parses `args`
91
+ * (everything after `caw <name>`) and returns everything the command printed:
92
+ * help, usage errors and handler output. Handlers print with `Console`, read
93
+ * the invocation through `CurrentCliContext`, and report domain failures as
94
+ * `CliCommandError`. Usage errors fail with the help and errors as the message.
95
+ */
96
+ export const fromCommand = <Name extends string, Input, ContextInput>(
97
+ command: Command.Command<Name, Input, ContextInput, CliCommandError, CurrentCliContext>,
98
+ summary: string,
99
+ ): CliCommand => ({
100
+ name: command.name,
101
+ summary,
102
+ run: (args, context) =>
103
+ Effect.suspend(() => {
104
+ const buffer = makeBufferedConsole();
105
+
106
+ // Help and usage errors are already in the output; other errors add their message.
107
+ const toCommandError = (error: CliCommandError | CliError.CliError) =>
108
+ new CliCommandError({
109
+ message: [buffer.text(), Predicate.isTagged(error, "ShowHelp") ? "" : error.message]
110
+ .filter((part) => part.length > 0)
111
+ .join("\n"),
112
+ });
113
+
114
+ return Cli.runWith(command, { version: "1.0.0" })(args).pipe(
115
+ Effect.map(() => buffer.text()),
116
+ // Without errors, help was shown for a command group that has no handler of its own.
117
+ Effect.catchTag("ShowHelp", (error) =>
118
+ error.errors.length === 0 ? Effect.succeed(buffer.text()) : Effect.fail(error),
119
+ ),
120
+ Effect.mapError(toCommandError),
121
+ Effect.provideService(CurrentCliContext, context),
122
+ Effect.provideService(Console.Console, buffer.console),
123
+ // oxlint-disable-next-line effecttsgo/strict-effect-provide -- SAFETY: each run is the entry point of a self-contained `effect/cli` program; the layer is pure stubs.
124
+ Effect.provide(daemonEnvironment),
125
+ );
126
+ }),
127
+ });
@@ -0,0 +1,42 @@
1
+ import { Schema } from "effect";
2
+ import {
3
+ ChannelName,
4
+ ConversationId,
5
+ ExternalConversationId,
6
+ HarnessName,
7
+ ProfileName,
8
+ SessionId,
9
+ } from "./ids.ts";
10
+
11
+ /**
12
+ * `threaded`: each top-level message opens a thread with its own Session.
13
+ * `inline`: the Conversation is one Session; a thread a person opens Forks it.
14
+ */
15
+ export const ReplyMode = Schema.Literals(["threaded", "inline"]);
16
+
17
+ export type ReplyMode = typeof ReplyMode.Type;
18
+
19
+ export class Conversation extends Schema.Class<Conversation, { readonly brand: unique symbol }>(
20
+ "Conversation",
21
+ )({
22
+ id: ConversationId,
23
+ channel: ChannelName,
24
+ externalId: ExternalConversationId,
25
+ /** Set for threads. Workspace, profile and Memory come from the top-level parent. */
26
+ parentId: Schema.Option(ConversationId),
27
+ replyMode: ReplyMode,
28
+ profile: Schema.Option(ProfileName),
29
+ }) {}
30
+
31
+ export const SessionStatus = Schema.Literals(["live", "idle", "lost", "closed"]);
32
+
33
+ export type SessionStatus = typeof SessionStatus.Type;
34
+
35
+ export class Session extends Schema.Class<Session, { readonly brand: unique symbol }>("Session")({
36
+ id: SessionId,
37
+ conversationId: ConversationId,
38
+ harness: HarnessName,
39
+ profile: ProfileName,
40
+ status: SessionStatus,
41
+ forkedFrom: Schema.Option(SessionId),
42
+ }) {}
package/src/events.ts ADDED
@@ -0,0 +1,38 @@
1
+ import { Data } from "effect";
2
+ import type { ChannelMessage } from "./channel.ts";
3
+ import type { Conversation, Session } from "./conversation.ts";
4
+ import type { HarnessEvent, SessionStart } from "./harness.ts";
5
+ import type { ChannelMessageId, ConversationId, PluginName, SessionId } from "./ids.ts";
6
+
7
+ export type SessionCloseReason =
8
+ | "idle"
9
+ | "evicted"
10
+ | "reset"
11
+ | "profile-changed"
12
+ | "plugins-changed"
13
+ | "shutdown";
14
+
15
+ export type TurnOutcome = "completed" | "interrupted" | "failed";
16
+
17
+ /** Everything core announces. Plugins observe these; they cannot change them. */
18
+ export type CawEvent = Data.TaggedEnum<{
19
+ DaemonStarted: {};
20
+ DaemonStopping: {};
21
+ MessageReceived: { readonly conversation: Conversation; readonly message: ChannelMessage };
22
+ ConversationCreated: { readonly conversation: Conversation };
23
+ SessionOpened: { readonly session: Session; readonly start: SessionStart };
24
+ SessionClosed: { readonly sessionId: SessionId; readonly reason: SessionCloseReason };
25
+ SessionLost: { readonly sessionId: SessionId; readonly replacement: SessionId };
26
+ TurnStarted: { readonly sessionId: SessionId };
27
+ TurnEnded: { readonly sessionId: SessionId; readonly outcome: TurnOutcome };
28
+ HarnessEventReceived: { readonly sessionId: SessionId; readonly event: HarnessEvent };
29
+ ReplySent: {
30
+ readonly conversationId: ConversationId;
31
+ readonly messageIds: ReadonlyArray<ChannelMessageId>;
32
+ readonly text: string;
33
+ };
34
+ PluginEnabled: { readonly plugin: PluginName };
35
+ PluginDisabled: { readonly plugin: PluginName };
36
+ }>;
37
+
38
+ export const CawEvent = Data.taggedEnum<CawEvent>();
package/src/harness.ts ADDED
@@ -0,0 +1,103 @@
1
+ import type { Effect, Scope, Stream } from "effect";
2
+ import { Data, Schema } from "effect";
3
+ import type { ConversationId, HarnessName, SessionId } from "./ids.ts";
4
+ import type { Profile } from "./profile.ts";
5
+ import type { ToolGroup } from "./tool.ts";
6
+
7
+ /**
8
+ * A Harness's opaque resume token, stored as `resume_cursor_json`. Each
9
+ * Harness decodes it with its own Schema at its boundary.
10
+ */
11
+ export const ResumeCursor = Schema.Json;
12
+
13
+ export type ResumeCursor = typeof ResumeCursor.Type;
14
+
15
+ export type SessionStart = Data.TaggedEnum<{
16
+ New: {};
17
+ Resume: { readonly cursor: ResumeCursor };
18
+ /** Starts a new Session from a copy of the history behind `cursor`. */
19
+ Fork: { readonly cursor: ResumeCursor };
20
+ }>;
21
+
22
+ export const SessionStart = Data.taggedEnum<SessionStart>();
23
+
24
+ export class HarnessError extends Schema.TaggedError<
25
+ HarnessError,
26
+ { readonly brand: unique symbol }
27
+ >()("HarnessError", {
28
+ harness: Schema.String,
29
+ message: Schema.String,
30
+ cause: Schema.Defect(),
31
+ }) {}
32
+
33
+ /** The Harness no longer knows the Session behind a cursor; core recovers it as `lost`. */
34
+ export class SessionNotFound extends Schema.TaggedError<
35
+ SessionNotFound,
36
+ { readonly brand: unique symbol }
37
+ >()("SessionNotFound", {
38
+ harness: Schema.String,
39
+ }) {}
40
+
41
+ export type HarnessEvent = Data.TaggedEnum<{
42
+ /** One finished assistant text block. */
43
+ Text: { readonly text: string };
44
+ ToolCall: { readonly id: string; readonly name: string; readonly input: Schema.Json };
45
+ ToolResult: { readonly id: string; readonly output: string; readonly isError: boolean };
46
+ /** The Turn stopped and the Harness waits for more input. */
47
+ TurnEnded: {};
48
+ /** The Turn failed; the Session stays usable unless the stream ends. */
49
+ Failed: { readonly error: HarnessError | SessionNotFound };
50
+ CursorUpdated: { readonly cursor: ResumeCursor };
51
+ }>;
52
+
53
+ export const HarnessEvent = Data.taggedEnum<HarnessEvent>();
54
+
55
+ /** What a ToolCall interceptor decided. */
56
+ export type ToolCallDecision = Data.TaggedEnum<{
57
+ Allow: {};
58
+ Block: { readonly reason: string };
59
+ Mutate: { readonly input: Schema.Json };
60
+ }>;
61
+
62
+ export const ToolCallDecision = Data.taggedEnum<ToolCallDecision>();
63
+
64
+ export interface ToolCallRequest {
65
+ readonly sessionId: SessionId;
66
+ readonly name: string;
67
+ readonly input: Schema.Json;
68
+ }
69
+
70
+ export interface OpenSession {
71
+ readonly start: SessionStart;
72
+ readonly conversationId: ConversationId;
73
+ /** The top-level Conversation that owns Workspace, profile and Memory (equals `conversationId` outside threads). */
74
+ readonly rootConversationId: ConversationId;
75
+ readonly sessionId: SessionId;
76
+ readonly profile: Profile;
77
+ readonly cwd: string;
78
+ /** Merged env: process env, profile env, plugin env, `CAW_CONVERSATION_ID`, `CAW_SESSION_ID`. */
79
+ readonly env: Readonly<Record<string, string>>;
80
+ /** Appended after the Harness's own system prompt, in order. Fixed for the Session's lifetime. */
81
+ readonly systemPrompt: ReadonlyArray<string>;
82
+ readonly tools: ReadonlyArray<ToolGroup>;
83
+ /** Skill directories to load (Caw's core skill and each Plugin's). */
84
+ readonly skillDirs: ReadonlyArray<string>;
85
+ /** Runs the ToolCall interceptor chain; the Harness calls it before every tool use. */
86
+ readonly interceptToolCall: (request: ToolCallRequest) => Effect.Effect<ToolCallDecision>;
87
+ }
88
+
89
+ /** One long-lived Harness session. It closes when the Scope `open` ran in closes. */
90
+ export interface LiveSession {
91
+ /** Starts a Turn, or Steers the Turn in progress. */
92
+ readonly send: (input: string) => Effect.Effect<void, HarnessError>;
93
+ readonly interrupt: Effect.Effect<void, HarnessError>;
94
+ /** Ends when the Session closes. */
95
+ readonly events: Stream.Stream<HarnessEvent>;
96
+ }
97
+
98
+ export interface Harness {
99
+ readonly name: HarnessName;
100
+ readonly open: (
101
+ request: OpenSession,
102
+ ) => Effect.Effect<LiveSession, HarnessError | SessionNotFound, Scope.Scope>;
103
+ }
package/src/ids.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { Schema } from "effect";
2
+
3
+ /** Caw's own id for a Conversation (a Discord channel, thread or DM). */
4
+ export const ConversationId = Schema.String.pipe(Schema.brand("ConversationId"));
5
+
6
+ export type ConversationId = typeof ConversationId.Type;
7
+
8
+ /** Caw's own id for a Session. Exposed to the agent as `CAW_SESSION_ID`. */
9
+ export const SessionId = Schema.String.pipe(Schema.brand("SessionId"));
10
+
11
+ export type SessionId = typeof SessionId.Type;
12
+
13
+ /** The registered name of a Channel, e.g. `discord`. */
14
+ export const ChannelName = Schema.String.pipe(Schema.brand("ChannelName"));
15
+
16
+ export type ChannelName = typeof ChannelName.Type;
17
+
18
+ /** The chat platform's id for a Conversation (a Discord channel or thread snowflake). */
19
+ export const ExternalConversationId = Schema.String.pipe(Schema.brand("ExternalConversationId"));
20
+
21
+ export type ExternalConversationId = typeof ExternalConversationId.Type;
22
+
23
+ /** The chat platform's id for one message. */
24
+ export const ChannelMessageId = Schema.String.pipe(Schema.brand("ChannelMessageId"));
25
+
26
+ export type ChannelMessageId = typeof ChannelMessageId.Type;
27
+
28
+ /** The registered name of a Harness, e.g. `claude`. */
29
+ export const HarnessName = Schema.String.pipe(Schema.brand("HarnessName"));
30
+
31
+ export type HarnessName = typeof HarnessName.Type;
32
+
33
+ /** A Plugin's name; also the suffix of its tables (`plugin_<name>_*`) and MCP server (`caw_<name>`). */
34
+ export const PluginName = Schema.String.check(Schema.isPattern(/^[a-z][a-z0-9_]*$/)).pipe(
35
+ Schema.brand("PluginName"),
36
+ );
37
+
38
+ export type PluginName = typeof PluginName.Type;
39
+
40
+ /** A Harness profile's name. `default` applies when a Conversation sets none. */
41
+ export const ProfileName = Schema.String.pipe(Schema.brand("ProfileName"));
42
+
43
+ export type ProfileName = typeof ProfileName.Type;
@@ -0,0 +1,83 @@
1
+ import type { Effect } from "effect";
2
+ import { Data } from "effect";
3
+ import type { ChannelMessage } from "./channel.ts";
4
+ import type { Conversation, Session } from "./conversation.ts";
5
+ import type { ToolCallDecision, ToolCallRequest } from "./harness.ts";
6
+ import type { Profile } from "./profile.ts";
7
+ import type { Tool } from "./tool.ts";
8
+
9
+ export type InboundDecision = Data.TaggedEnum<{
10
+ Continue: {};
11
+ Transform: { readonly message: ChannelMessage };
12
+ /** Ignore the message silently. */
13
+ Drop: {};
14
+ /** The interceptor took care of the message; core does nothing more. */
15
+ Handled: {};
16
+ }>;
17
+
18
+ export const InboundDecision = Data.taggedEnum<InboundDecision>();
19
+
20
+ export interface SessionOpeningContext {
21
+ readonly conversation: Conversation;
22
+ /** The top-level Conversation (equals `conversation` outside threads). */
23
+ readonly root: Conversation;
24
+ readonly session: Session;
25
+ readonly profile: Profile;
26
+ }
27
+
28
+ /** What a Plugin adds to a Session when it opens. Fixed for the live Session's lifetime. */
29
+ export interface SessionContribution {
30
+ readonly systemPrompt: ReadonlyArray<string>;
31
+ readonly tools: ReadonlyArray<Tool>;
32
+ readonly env: Readonly<Record<string, string>>;
33
+ }
34
+
35
+ export interface TurnInputContext {
36
+ readonly conversation: Conversation;
37
+ readonly session: Session;
38
+ }
39
+
40
+ export interface OutboundReplyContext {
41
+ readonly conversation: Conversation;
42
+ readonly session: Session;
43
+ }
44
+
45
+ export type OutboundDecision = Data.TaggedEnum<{
46
+ Continue: {};
47
+ Transform: { readonly text: string };
48
+ Drop: {};
49
+ }>;
50
+
51
+ export const OutboundDecision = Data.taggedEnum<OutboundDecision>();
52
+
53
+ /**
54
+ * A Plugin's handlers at core's interception points. Core runs every enabled
55
+ * Plugin's handler for a point in Plugin order and stops at the first
56
+ * `Drop`, `Handled` or `Block`.
57
+ */
58
+ export type Interceptor = Data.TaggedEnum<{
59
+ InboundMessage: {
60
+ readonly handle: (
61
+ message: ChannelMessage,
62
+ conversation: Conversation,
63
+ ) => Effect.Effect<InboundDecision>;
64
+ };
65
+ SessionOpening: {
66
+ readonly handle: (context: SessionOpeningContext) => Effect.Effect<SessionContribution>;
67
+ };
68
+ /** Rewrites the formatted input before it reaches the Harness. */
69
+ TurnInput: {
70
+ readonly handle: (input: string, context: TurnInputContext) => Effect.Effect<string>;
71
+ };
72
+ ToolCall: {
73
+ readonly handle: (request: ToolCallRequest) => Effect.Effect<ToolCallDecision>;
74
+ };
75
+ OutboundReply: {
76
+ readonly handle: (
77
+ text: string,
78
+ context: OutboundReplyContext,
79
+ ) => Effect.Effect<OutboundDecision>;
80
+ };
81
+ }>;
82
+
83
+ export const Interceptor = Data.taggedEnum<Interceptor>();
package/src/plugin.ts ADDED
@@ -0,0 +1,140 @@
1
+ import type { Effect, Layer, Option, PubSub, Scope, Stream } from "effect";
2
+ import { Context, Schema } from "effect";
3
+ import type { SqliteClient } from "@effect/sql-sqlite-bun";
4
+ import type { SqlClient, SqlError } from "effect/sql";
5
+ import type { Channel } from "./channel.ts";
6
+ import type { Conversation } from "./conversation.ts";
7
+ import type { CawEvent } from "./events.ts";
8
+ import type { Harness } from "./harness.ts";
9
+ import type { ConversationId, PluginName, ProfileName } from "./ids.ts";
10
+ import type { Interceptor } from "./interceptors.ts";
11
+ import type { Profile } from "./profile.ts";
12
+ import type { PluginSetup } from "./setup.ts";
13
+ import type { Tool } from "./tool.ts";
14
+
15
+ /** One page of `caw guide <topic>`. Pure data, readable without a running daemon. */
16
+ export interface GuidePage {
17
+ readonly topic: string;
18
+ readonly summary: string;
19
+ readonly body: string;
20
+ }
21
+
22
+ /** A numbered, idempotent migration for a Plugin's own `plugin_<name>_*` tables. */
23
+ export interface Migration {
24
+ readonly id: number;
25
+ readonly name: string;
26
+ readonly run: Effect.Effect<void, SqlError.SqlError, SqlClient.SqlClient>;
27
+ }
28
+
29
+ export interface CliContext {
30
+ /** From `CAW_CONVERSATION_ID` when the agent runs the CLI inside a Session. */
31
+ readonly conversationId: Option.Option<ConversationId>;
32
+ /** The invoking shell's working directory; resolve relative paths against it. */
33
+ readonly cwd: string;
34
+ }
35
+
36
+ /** A usage or domain error; the CLI prints `message` and exits non-zero. */
37
+ export class CliCommandError extends Schema.TaggedError<
38
+ CliCommandError,
39
+ { readonly brand: unique symbol }
40
+ >()("CliCommandError", {
41
+ message: Schema.String,
42
+ }) {}
43
+
44
+ /** `caw <name> ...args`, run inside the daemon. Returns what the CLI prints. */
45
+ export interface CliCommand {
46
+ readonly name: string;
47
+ readonly summary: string;
48
+ readonly run: (
49
+ args: ReadonlyArray<string>,
50
+ context: CliContext,
51
+ ) => Effect.Effect<string, CliCommandError>;
52
+ }
53
+
54
+ export type ProfileLookup = (name: ProfileName) => Effect.Effect<Option.Option<Profile>>;
55
+
56
+ /** A message between Plugins on the inter-plugin bus. */
57
+ export interface PluginMessage {
58
+ readonly from: PluginName;
59
+ readonly topic: string;
60
+ readonly payload: unknown;
61
+ }
62
+
63
+ export class ConversationNotFound extends Schema.TaggedError<
64
+ ConversationNotFound,
65
+ { readonly brand: unique symbol }
66
+ >()("ConversationNotFound", { conversationId: Schema.String }) {}
67
+
68
+ /**
69
+ * Core's services for Plugins. Every `register*` lasts for the calling scope:
70
+ * a Plugin's registrations disappear when the Plugin is disabled.
71
+ */
72
+ export class Caw extends Context.Service<
73
+ Caw,
74
+ {
75
+ readonly registerChannel: (channel: Channel) => Effect.Effect<void, never, Scope.Scope>;
76
+ readonly registerHarness: (harness: Harness) => Effect.Effect<void, never, Scope.Scope>;
77
+ /** Tools offered to every Session that opens while the Plugin is enabled. */
78
+ readonly registerTool: (tool: Tool) => Effect.Effect<void, never, Scope.Scope>;
79
+ readonly registerInterceptor: (
80
+ interceptor: Interceptor,
81
+ ) => Effect.Effect<void, never, Scope.Scope>;
82
+ readonly registerCliCommand: (command: CliCommand) => Effect.Effect<void, never, Scope.Scope>;
83
+ readonly registerProfiles: (lookup: ProfileLookup) => Effect.Effect<void, never, Scope.Scope>;
84
+ readonly events: Stream.Stream<CawEvent>;
85
+ readonly bus: PubSub.PubSub<PluginMessage>;
86
+ readonly conversation: (
87
+ id: ConversationId,
88
+ ) => Effect.Effect<Conversation, ConversationNotFound>;
89
+ /** Posts a message to a Conversation outside any Turn. */
90
+ readonly send: (
91
+ conversationId: ConversationId,
92
+ text: string,
93
+ ) => Effect.Effect<void, ConversationNotFound>;
94
+ /**
95
+ * Delivers a scheduled prompt as a `<task>` Turn, following the
96
+ * Conversation's Reply mode (a new thread when `threaded`).
97
+ */
98
+ readonly deliverTask: (
99
+ conversationId: ConversationId,
100
+ prompt: string,
101
+ ) => Effect.Effect<void, ConversationNotFound>;
102
+ }
103
+ >()("@gloaming/caw-plugin-sdk/Caw") {}
104
+
105
+ /** A Plugin's identity and key-value store, provided to its own layer only. */
106
+ export class PluginContext extends Context.Service<
107
+ PluginContext,
108
+ {
109
+ readonly name: PluginName;
110
+ readonly get: <A, I>(
111
+ key: string,
112
+ schema: Schema.Codec<A, I>,
113
+ ) => Effect.Effect<Option.Option<A>>;
114
+ readonly set: <A, I>(key: string, schema: Schema.Codec<A, I>, value: A) => Effect.Effect<void>;
115
+ }
116
+ >()("@gloaming/caw-plugin-sdk/PluginContext") {}
117
+
118
+ /** `SqliteClient` is what Drizzle's `effect-sqlite-bun` driver needs for a Plugin's own tables. */
119
+ export type PluginServices = Caw | PluginContext | SqlClient.SqlClient | SqliteClient.SqliteClient;
120
+
121
+ /**
122
+ * What a Plugin package default-exports. The layer's scope is the Plugin's
123
+ * lifetime: disabling the Plugin closes it.
124
+ */
125
+ export interface PluginDefinition<Settings> {
126
+ readonly name: PluginName;
127
+ /** Decodes `caw plugin set` values; must decode `{}` to the defaults. */
128
+ readonly settings: Schema.Codec<Settings, unknown>;
129
+ readonly migrations: ReadonlyArray<Migration>;
130
+ readonly guide: ReadonlyArray<GuidePage>;
131
+ /** A directory of agent skills loaded into every Session. */
132
+ readonly skillDir: Option.Option<string>;
133
+ /** The Plugin's part in `caw install`; leave it out for a feature Plugin. */
134
+ readonly setup?: PluginSetup;
135
+ readonly layer: (settings: Settings) => Layer.Layer<never, never, PluginServices>;
136
+ }
137
+
138
+ export const definePlugin = <Settings>(
139
+ definition: PluginDefinition<Settings>,
140
+ ): PluginDefinition<Settings> => definition;
package/src/profile.ts ADDED
@@ -0,0 +1,22 @@
1
+ import { Schema } from "effect";
2
+ import { HarnessName, ProfileName } from "./ids.ts";
3
+
4
+ /**
5
+ * The named Harness settings a Conversation uses. A Session stays bound to
6
+ * the profile it started with; changing a Conversation's profile makes its next
7
+ * message start a new Session.
8
+ */
9
+ export class Profile extends Schema.Class<Profile, { readonly brand: unique symbol }>("Profile")({
10
+ name: ProfileName,
11
+ harness: HarnessName,
12
+ env: Schema.Record(Schema.String, Schema.String),
13
+ model: Schema.Option(Schema.String),
14
+ /** The reasoning effort, e.g. `low` or `high`; `None` means the Harness default. */
15
+ effort: Schema.Option(Schema.String),
16
+ /** Overrides the Workspace directory as the Sessions' cwd. */
17
+ cwd: Schema.Option(Schema.String),
18
+ /** Claude `settingSources`; `None` means the Harness default (`user`, `project`, `local`). */
19
+ settingSources: Schema.Option(Schema.Array(Schema.String)),
20
+ }) {}
21
+
22
+ export const defaultProfileName = ProfileName.make("default");
package/src/setup.ts ADDED
@@ -0,0 +1,134 @@
1
+ import { Data, Effect, Option, Schema } from "effect";
2
+ import type { HttpClient } from "effect/http";
3
+ import type { HarnessName } from "./ids.ts";
4
+
5
+ /** One option of a `Choice` or `MultiChoice` question. */
6
+ export interface SetupChoice {
7
+ readonly value: string;
8
+ readonly title: string;
9
+ /** A few words shown beside the title. */
10
+ readonly hint?: string | undefined;
11
+ }
12
+
13
+ /**
14
+ * One answer `caw install` collects for a Plugin. It is prompted for, or read
15
+ * from `--<flag>` so the wizard also runs without a terminal. `flag` must be
16
+ * unique across Plugins, so prefix it with the Plugin's name when it is not
17
+ * obviously the Plugin's own.
18
+ */
19
+ export type SetupQuestion = Data.TaggedEnum<{
20
+ /** Hidden input. Non-interactively it is read from the file `--<flag>-file <path>` names. */
21
+ Secret: { readonly key: string; readonly flag: string; readonly message: string };
22
+ Choice: {
23
+ readonly key: string;
24
+ readonly flag: string;
25
+ readonly message: string;
26
+ readonly choices: ReadonlyArray<SetupChoice>;
27
+ /** The `value` taken by default. */
28
+ readonly initial: string;
29
+ };
30
+ /** Any number of `choices`; `--<flag>` takes them comma-separated. The answer is a list. */
31
+ MultiChoice: {
32
+ readonly key: string;
33
+ readonly flag: string;
34
+ readonly message: string;
35
+ readonly choices: ReadonlyArray<SetupChoice>;
36
+ /** The `value`s taken by default. */
37
+ readonly initial: ReadonlyArray<string>;
38
+ };
39
+ Text: {
40
+ readonly key: string;
41
+ readonly flag: string;
42
+ readonly message: string;
43
+ readonly initial: string;
44
+ };
45
+ }>;
46
+
47
+ export const SetupQuestion = Data.taggedEnum<SetupQuestion>();
48
+
49
+ /** A `MultiChoice` question's answer is `Many`; every other answer is `One`. */
50
+ export type SetupAnswer = Data.TaggedEnum<{
51
+ One: { readonly value: string };
52
+ Many: { readonly values: ReadonlyArray<string> };
53
+ }>;
54
+
55
+ export const SetupAnswer = Data.taggedEnum<SetupAnswer>();
56
+
57
+ /** Answers by question `key`; every question the Plugin asked has one. */
58
+ export type SetupAnswers = ReadonlyMap<string, SetupAnswer>;
59
+
60
+ /** The answers do not work (a rejected token, an unknown option). The wizard shows `message`. */
61
+ export class SetupError extends Schema.TaggedError<SetupError, { readonly brand: unique symbol }>()(
62
+ "SetupError",
63
+ { message: Schema.String },
64
+ ) {}
65
+
66
+ /** A Channel's checked config. */
67
+ export interface ChannelConfigured {
68
+ /** Lines the wizard prints, e.g. the bot's name and servers. */
69
+ readonly report: ReadonlyArray<string>;
70
+ /** Written into `<home>/.env`, keeping its other entries. */
71
+ readonly env: Readonly<Record<string, string>>;
72
+ }
73
+
74
+ /** A Harness's chosen options; they become the `default` Harness profile. */
75
+ export interface HarnessConfigured {
76
+ readonly report: ReadonlyArray<string>;
77
+ readonly harness: HarnessName;
78
+ readonly model: Option.Option<string>;
79
+ readonly effort: Option.Option<string>;
80
+ readonly settingSources: Option.Option<ReadonlyArray<string>>;
81
+ /**
82
+ * The installing shell's variables the Harness needs. The daemon does not run
83
+ * in that shell, so they are saved in the profile.
84
+ */
85
+ readonly env: Readonly<Record<string, string>>;
86
+ }
87
+
88
+ /**
89
+ * A Plugin's part in `caw install`. A Plugin without one is a feature: the
90
+ * wizard only asks whether to enable it.
91
+ */
92
+ export type PluginSetup = Data.TaggedEnum<{
93
+ Channel: {
94
+ /** The name people pick from, e.g. `Discord`. */
95
+ readonly title: string;
96
+ /** A few words shown beside the title, e.g. `Discord bot`. */
97
+ readonly hint?: string;
98
+ readonly questions: ReadonlyArray<SetupQuestion>;
99
+ readonly configure: (
100
+ answers: SetupAnswers,
101
+ ) => Effect.Effect<ChannelConfigured, SetupError, HttpClient.HttpClient>;
102
+ };
103
+ Harness: {
104
+ readonly title: string;
105
+ readonly hint?: string;
106
+ readonly questions: ReadonlyArray<SetupQuestion>;
107
+ readonly configure: (answers: SetupAnswers) => Effect.Effect<HarnessConfigured, SetupError>;
108
+ };
109
+ }>;
110
+
111
+ export const PluginSetup = Data.taggedEnum<PluginSetup>();
112
+
113
+ const missing = (key: string) => new SetupError({ message: `No answer for ${key}.` });
114
+
115
+ /** The answer to the single-answer question with `key`. */
116
+ export const answer = (answers: SetupAnswers, key: string): Effect.Effect<string, SetupError> =>
117
+ Option.fromNullishOr(answers.get(key)).pipe(
118
+ Option.filter(SetupAnswer.$is("One")),
119
+ Option.map(({ value }) => value),
120
+ Effect.fromOption,
121
+ Effect.mapError(() => missing(key)),
122
+ );
123
+
124
+ /** The answer to the `MultiChoice` question with `key`. */
125
+ export const answerList = (
126
+ answers: SetupAnswers,
127
+ key: string,
128
+ ): Effect.Effect<ReadonlyArray<string>, SetupError> =>
129
+ Option.fromNullishOr(answers.get(key)).pipe(
130
+ Option.filter(SetupAnswer.$is("Many")),
131
+ Option.map(({ values }) => values),
132
+ Effect.fromOption,
133
+ Effect.mapError(() => missing(key)),
134
+ );
package/src/tool.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { Effect, Schema } from "effect";
2
+ import type * as JsonSchema from "effect/JsonSchema";
3
+ import type { ConversationId, PluginName, SessionId } from "./ids.ts";
4
+
5
+ /** Who is calling a tool. Tools act on the caller's Conversation unless told otherwise. */
6
+ export interface ToolContext {
7
+ readonly conversationId: ConversationId;
8
+ /** The top-level Conversation that owns Workspace, profile and Memory (equals `conversationId` outside threads). */
9
+ readonly rootConversationId: ConversationId;
10
+ readonly sessionId: SessionId;
11
+ }
12
+
13
+ /** A failure the agent sees as the tool's error result. */
14
+ export class ToolError extends Schema.TaggedError<ToolError, { readonly brand: unique symbol }>()(
15
+ "ToolError",
16
+ {
17
+ message: Schema.String,
18
+ },
19
+ ) {}
20
+
21
+ /**
22
+ * A Harness-agnostic tool: Effect Schema parameters plus an Effect handler.
23
+ */
24
+ export interface Tool {
25
+ readonly name: string;
26
+ readonly description: string;
27
+ /**
28
+ * JSON Schema of the input, always an object (MCP requires one), with
29
+ * shared definitions under `$defs`. It describes the JSON form `run` decodes.
30
+ */
31
+ readonly inputSchema: JsonSchema.JsonSchema;
32
+ /** Decodes the raw input against `parameters`, then runs the handler. */
33
+ readonly run: (input: Schema.Json, context: ToolContext) => Effect.Effect<string, ToolError>;
34
+ }
35
+
36
+ /** Tools grouped by the Plugin that owns them; Claude maps each group to one `caw_<plugin>` MCP server. */
37
+ export interface ToolGroup {
38
+ readonly plugin: PluginName;
39
+ readonly tools: ReadonlyArray<Tool>;
40
+ }
41
+
42
+ /** Fields a tool can decode without extra services. */
43
+ type ToolFields = Record<string, Schema.Top & { readonly DecodingServices: never }>;
44
+
45
+ /**
46
+ * Effect renders an empty Struct as "any non-null value"; a tool without
47
+ * parameters still takes an (empty) object.
48
+ */
49
+ const objectSchema = (parameters: Schema.Struct<ToolFields>): JsonSchema.JsonSchema => {
50
+ if (Object.keys(parameters.fields).length === 0) {
51
+ return { type: "object", properties: {}, additionalProperties: false };
52
+ }
53
+
54
+ const document = Schema.toJsonSchemaDocument(parameters);
55
+
56
+ return { ...document.schema, $defs: document.definitions };
57
+ };
58
+
59
+ export const makeTool = <const Fields extends ToolFields>(definition: {
60
+ readonly name: string;
61
+ readonly description: string;
62
+ readonly parameters: Schema.Struct<Fields>;
63
+ readonly handler: (
64
+ params: Schema.Struct<Fields>["Type"],
65
+ context: ToolContext,
66
+ ) => Effect.Effect<string, ToolError>;
67
+ }): Tool => {
68
+ // Decode the JSON form: the model sees the JSON Schema of the JSON codec.
69
+ const decode = Schema.decodeUnknownEffect(Schema.toCodecJson(definition.parameters));
70
+
71
+ return {
72
+ name: definition.name,
73
+ description: definition.description,
74
+ inputSchema: objectSchema(definition.parameters),
75
+ run: (input, context) =>
76
+ decode(input).pipe(
77
+ Effect.mapError((issue) => new ToolError({ message: `Invalid input: ${issue.message}` })),
78
+ Effect.flatMap((params) => definition.handler(params, context)),
79
+ ),
80
+ };
81
+ };
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.