@sedge-hq/kit 0.0.0-stage → 0.1.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.
Files changed (3) hide show
  1. package/package.json +32 -5
  2. package/src/index.ts +297 -0
  3. package/README.md +0 -3
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
- "name": "@sedge-hq/kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@sedge-hq/kit",
3
+ "version": "0.1.0",
4
+ "description": "Build channels and signals for sedge, the always-on agent.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/sedge-hq/sedge.git",
9
+ "directory": "packages/kit"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "!src/**/*.test.ts"
14
+ ],
15
+ "type": "module",
16
+ "exports": {
17
+ ".": "./src/index.ts"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "scripts": {
23
+ "typecheck": "tsc --noEmit"
24
+ },
25
+ "dependencies": {
26
+ "effect": "4.1.4"
27
+ },
28
+ "devDependencies": {
29
+ "@sedge-hq/config": "0.0.0",
30
+ "@types/bun": "1.4.4",
31
+ "typescript": "7.0.2"
32
+ }
33
+ }
package/src/index.ts ADDED
@@ -0,0 +1,297 @@
1
+ import {
2
+ Cause,
3
+ Effect,
4
+ Exit,
5
+ Fiber,
6
+ Option,
7
+ Redacted,
8
+ Schedule,
9
+ Schema,
10
+ SchemaAST,
11
+ Stream,
12
+ } from 'effect';
13
+ import type { Scope } from 'effect';
14
+
15
+ /**
16
+ * @sedge-hq/kit: build what connects sedge to the world.
17
+ *
18
+ * - A **signal** is something that happens: CI failed, a price moved, a page changed. It wakes the
19
+ * agent with the instruction the user gave for it. `watch` returns a Stream of what happened.
20
+ * - A **channel** is a conversation with the user: Telegram, Slack, email. Their messages reach the
21
+ * agent; its replies, and its questions with choices, go back.
22
+ *
23
+ * Settings are an Effect Schema. Use `secret(...)` for tokens and passwords: the user types them
24
+ * into a hidden field, sedge keeps them in the OS keychain, and your code gets a `Redacted`.
25
+ *
26
+ * ```ts
27
+ * import { defineSignal } from '@sedge-hq/kit';
28
+ * import { Schema, Stream } from 'effect';
29
+ *
30
+ * export default defineSignal({
31
+ * name: 'heartbeat',
32
+ * summary: 'a beat every few minutes',
33
+ * settings: { minutes: Schema.Number.annotate({ description: 'how often' }) },
34
+ * watch: ({ minutes }) =>
35
+ * Stream.tick(`${minutes} minutes`).pipe(Stream.map(() => ({ text: 'beat' }))),
36
+ * });
37
+ * ```
38
+ */
39
+
40
+ const SECRET = Symbol.for('sedge.kit.secret');
41
+
42
+ /** A secret setting: typed by the user in a hidden field, kept in the OS keychain. */
43
+ export const secret = (description: string) =>
44
+ Object.assign(Schema.RedactedFromValue(Schema.String).annotate({ description }), {
45
+ [SECRET]: true as const,
46
+ });
47
+
48
+ type Fields = Schema.Struct.Fields;
49
+ export type Settings<F extends Fields> = Schema.Struct<F>['Type'];
50
+
51
+ /** Something that happened. `text` is what the agent reads; `key` drops repeats. */
52
+ export interface Happening {
53
+ readonly text: string;
54
+ readonly key?: string;
55
+ readonly details?: unknown;
56
+ }
57
+
58
+ /** A message from the user on a channel. `from` is who wrote, `key` drops repeats. */
59
+ export interface Message {
60
+ readonly _tag: 'Message';
61
+ readonly from: string;
62
+ readonly text: string;
63
+ readonly key?: string;
64
+ }
65
+
66
+ /** The user picked one of the choices a reply offered (approve/deny, for example). */
67
+ export interface Picked {
68
+ readonly _tag: 'Picked';
69
+ readonly from: string;
70
+ readonly value: string;
71
+ readonly key?: string;
72
+ }
73
+
74
+ /**
75
+ * What the agent sends. `text` is Markdown; render what the channel can and fall back to plain
76
+ * text. `choices` are buttons (or a numbered list where there are none): the one the user picks
77
+ * comes back as `Picked`. `files` are local paths to send along, if the channel can.
78
+ */
79
+ export interface Reply {
80
+ readonly text: string;
81
+ readonly choices?: ReadonlyArray<{ readonly label: string; readonly value: string }>;
82
+ readonly files?: ReadonlyArray<{ readonly path: string; readonly caption?: string }>;
83
+ }
84
+
85
+ /** Small values that survive restarts: an offset, the accounts a channel is paired with. */
86
+ export interface Memo {
87
+ readonly get: (key: string) => Effect.Effect<Option.Option<string>>;
88
+ readonly set: (key: string, value: string) => Effect.Effect<void>;
89
+ }
90
+
91
+ export interface Kit {
92
+ readonly memo: Memo;
93
+ /** One line on how it is doing, shown wherever connections are listed. */
94
+ readonly status: (line: string) => Effect.Effect<void>;
95
+ }
96
+
97
+ export interface ChannelKit extends Kit {
98
+ /**
99
+ * Someone sent a pairing code (from the link `invite` made). True when it is the code sedge is
100
+ * waiting for: that account is the user's from now on. Codes are one-time and expire.
101
+ */
102
+ readonly claim: (code: string, account: string) => Effect.Effect<boolean>;
103
+ }
104
+
105
+ export interface Connection {
106
+ /** The user's messages and picks. Only paired accounts: the channel itself checks. */
107
+ readonly incoming: Stream.Stream<Message | Picked, unknown>;
108
+ /** Send a reply to `to`, or to the user's usual conversation. Refuse anyone unpaired. */
109
+ readonly deliver: (reply: Reply, to?: string) => Effect.Effect<void, unknown>;
110
+ /** A link that pairs whoever opens it, carrying `code` (e.g. t.me/bot?start=code). */
111
+ readonly invite: (code: string) => string;
112
+ /**
113
+ * Show that sedge is working on an answer (Telegram's "typing…"). Called every few seconds
114
+ * while a run lasts; leave it out if the channel has nothing like it.
115
+ */
116
+ readonly working?: (to?: string) => Effect.Effect<void, unknown>;
117
+ }
118
+
119
+ interface Common<F extends Fields> {
120
+ /** The kind's name, lowercase: `telegram`, `github-ci`. */
121
+ readonly name: string;
122
+ /** One line: what it is for. The agent chooses kinds by it. */
123
+ readonly summary: string;
124
+ readonly settings: F;
125
+ }
126
+
127
+ export interface SignalSpec<F extends Fields> extends Common<F> {
128
+ readonly watch: (settings: Settings<F>, kit: Kit) => Stream.Stream<Happening, unknown>;
129
+ }
130
+
131
+ export interface ChannelSpec<F extends Fields> extends Common<F> {
132
+ readonly connect: (
133
+ settings: Settings<F>,
134
+ kit: ChannelKit,
135
+ ) => Effect.Effect<Connection, unknown, Scope.Scope>;
136
+ }
137
+
138
+ // ── What sedge sees ────────────────────────────────────────────────────────────────────────────
139
+ // A plugin brings its own copy of Effect, so the daemon talks to it through plain functions only.
140
+
141
+ export interface Field {
142
+ readonly name: string;
143
+ readonly description: string;
144
+ readonly secret: boolean;
145
+ readonly optional: boolean;
146
+ }
147
+
148
+ export interface Host {
149
+ readonly status: (line: string) => void;
150
+ readonly memoGet: (key: string) => Promise<string | undefined>;
151
+ readonly memoSet: (key: string, value: string) => Promise<void>;
152
+ readonly happened: (happening: Happening) => Promise<void>;
153
+ readonly received: (event: Message | Picked) => Promise<void>;
154
+ readonly claim: (code: string, account: string) => Promise<boolean>;
155
+ }
156
+
157
+ export interface Running {
158
+ readonly stop: () => Promise<void>;
159
+ readonly deliver?: (reply: Reply, to?: string) => Promise<void>;
160
+ readonly invite?: (code: string) => Promise<string>;
161
+ readonly working?: (to?: string) => Promise<void>;
162
+ }
163
+
164
+ export interface Plugin {
165
+ readonly sedge: 1;
166
+ readonly kind: 'signal' | 'channel';
167
+ readonly name: string;
168
+ readonly summary: string;
169
+ readonly fields: ReadonlyArray<Field>;
170
+ /** Checks settings (secrets may be left out); an error message, or undefined when fine. */
171
+ readonly check: (settings: Record<string, unknown>) => string | undefined;
172
+ readonly start: (settings: Record<string, unknown>, host: Host) => Running;
173
+ }
174
+
175
+ const fieldsOf = (settings: Fields): Array<Field> =>
176
+ Object.entries(settings).map(([name, schema]) => ({
177
+ name,
178
+ description: SchemaAST.resolveDescription(schema.ast) ?? '',
179
+ secret: SECRET in schema,
180
+ optional: SchemaAST.isOptional(schema.ast),
181
+ }));
182
+
183
+ /** The settings struct as a plain decoder: settings schemas need no services to decode. */
184
+ const struct = (settings: Fields) =>
185
+ Schema.Struct(settings) as unknown as Schema.Codec<Record<string, unknown>, unknown>;
186
+
187
+ const checker = (settings: Fields, fields: ReadonlyArray<Field>) => {
188
+ const decode = Schema.decodeUnknownExit(struct(settings));
189
+ return (raw: Record<string, unknown>) => {
190
+ // Secrets are typed by the user later; a stand-in lets the rest be checked now.
191
+ const filled = { ...raw };
192
+ for (const field of fields)
193
+ if (field.secret && !(field.name in filled)) filled[field.name] = '•';
194
+ const exit = decode(filled);
195
+ return Exit.isSuccess(exit) ? undefined : Cause.pretty(exit.cause).split('\n')[0];
196
+ };
197
+ };
198
+
199
+ const kitFor = (host: Host): Kit => ({
200
+ memo: {
201
+ get: (key) =>
202
+ Effect.promise(() => host.memoGet(key)).pipe(Effect.map(Option.fromNullishOr)),
203
+ set: (key, value) => Effect.promise(() => host.memoSet(key, value)),
204
+ },
205
+ status: (line) => Effect.sync(() => host.status(line)),
206
+ });
207
+
208
+ /** Restarts after a failure, ten seconds apart, saying why in the status. */
209
+ const resilient = <E>(host: Host, effect: Effect.Effect<void, E>) =>
210
+ effect.pipe(
211
+ Effect.tapCause((cause: Cause.Cause<E>) =>
212
+ Effect.sync(() => host.status(`failed, retrying: ${String(Cause.squash(cause))}`)),
213
+ ),
214
+ Effect.retry({ schedule: Schedule.spaced('10 seconds') }),
215
+ );
216
+
217
+ export const defineSignal = <F extends Fields>(spec: SignalSpec<F>): Plugin => {
218
+ const fields = fieldsOf(spec.settings);
219
+ const decode = Schema.decodeUnknownSync(struct(spec.settings));
220
+ return {
221
+ sedge: 1,
222
+ kind: 'signal',
223
+ name: spec.name,
224
+ summary: spec.summary,
225
+ fields,
226
+ check: checker(spec.settings, fields),
227
+ start: (raw, host) => {
228
+ const settings = decode(raw) as Settings<F>;
229
+ const fiber = Effect.runFork(
230
+ resilient(
231
+ host,
232
+ Stream.runForEach(spec.watch(settings, kitFor(host)), (h) =>
233
+ Effect.promise(() => host.happened(h)),
234
+ ),
235
+ ),
236
+ );
237
+ return { stop: () => Effect.runPromise(Fiber.interrupt(fiber)).then(() => undefined) };
238
+ },
239
+ };
240
+ };
241
+
242
+ export const defineChannel = <F extends Fields>(spec: ChannelSpec<F>): Plugin => {
243
+ const fields = fieldsOf(spec.settings);
244
+ const decode = Schema.decodeUnknownSync(struct(spec.settings));
245
+ return {
246
+ sedge: 1,
247
+ kind: 'channel',
248
+ name: spec.name,
249
+ summary: spec.summary,
250
+ fields,
251
+ check: checker(spec.settings, fields),
252
+ start: (raw, host) => {
253
+ const settings = decode(raw) as Settings<F>;
254
+ const kit: ChannelKit = {
255
+ ...kitFor(host),
256
+ claim: (code, account) => Effect.promise(() => host.claim(code, account)),
257
+ };
258
+ let current: Connection | undefined;
259
+ const waiters: Array<(c: Connection) => void> = [];
260
+ const ready = () =>
261
+ current
262
+ ? Promise.resolve(current)
263
+ : new Promise<Connection>((resolve) => waiters.push(resolve));
264
+
265
+ const fiber = Effect.runFork(
266
+ resilient(
267
+ host,
268
+ Effect.scoped(
269
+ Effect.gen(function* () {
270
+ const connection = yield* spec.connect(settings, kit);
271
+ current = connection;
272
+ for (const wake of waiters.splice(0)) wake(connection);
273
+ yield* Stream.runForEach(connection.incoming, (event) =>
274
+ Effect.promise(() => host.received(event)),
275
+ );
276
+ }).pipe(Effect.ensuring(Effect.sync(() => (current = undefined)))),
277
+ ),
278
+ ),
279
+ );
280
+ return {
281
+ stop: () => Effect.runPromise(Fiber.interrupt(fiber)).then(() => undefined),
282
+ deliver: async (reply, to) => Effect.runPromise((await ready()).deliver(reply, to)),
283
+ invite: async (code) => (await ready()).invite(code),
284
+ working: async (to) => {
285
+ const connection = current;
286
+ if (connection?.working)
287
+ await Effect.runPromise(Effect.ignore(connection.working(to)));
288
+ },
289
+ };
290
+ },
291
+ };
292
+ };
293
+
294
+ export const isPlugin = (value: unknown): value is Plugin =>
295
+ typeof value === 'object' && value !== null && (value as { sedge?: unknown }).sedge === 1;
296
+
297
+ export { Redacted };
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.