pi-durable-bot 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 (71) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +274 -2
  3. package/dist/agent/agent.js +235 -0
  4. package/dist/agent/agent.js.map +1 -0
  5. package/dist/agent/judge.js +78 -0
  6. package/dist/agent/judge.js.map +1 -0
  7. package/dist/agent/models.js +41 -0
  8. package/dist/agent/models.js.map +1 -0
  9. package/dist/bot/bot.js +325 -0
  10. package/dist/bot/bot.js.map +1 -0
  11. package/dist/bot/control.js +67 -0
  12. package/dist/bot/control.js.map +1 -0
  13. package/dist/bot/definition.js +81 -0
  14. package/dist/bot/definition.js.map +1 -0
  15. package/dist/bot/machine.js +26 -0
  16. package/dist/bot/machine.js.map +1 -0
  17. package/dist/bot/prompt.js +168 -0
  18. package/dist/bot/prompt.js.map +1 -0
  19. package/dist/bot/timers.js +113 -0
  20. package/dist/bot/timers.js.map +1 -0
  21. package/dist/channels/load.js +21 -0
  22. package/dist/channels/load.js.map +1 -0
  23. package/dist/channels/slack/index.js +518 -0
  24. package/dist/channels/slack/index.js.map +1 -0
  25. package/dist/channels/slack/sdk.js +55 -0
  26. package/dist/channels/slack/sdk.js.map +1 -0
  27. package/dist/channels/terminal/index.js +19 -0
  28. package/dist/channels/terminal/index.js.map +1 -0
  29. package/dist/channels/test/index.js +197 -0
  30. package/dist/channels/test/index.js.map +1 -0
  31. package/dist/cli/agent.js +78 -0
  32. package/dist/cli/agent.js.map +1 -0
  33. package/dist/cli/ai.js +126 -0
  34. package/dist/cli/ai.js.map +1 -0
  35. package/dist/cli/bots.js +57 -0
  36. package/dist/cli/bots.js.map +1 -0
  37. package/dist/cli/chat.js +157 -0
  38. package/dist/cli/chat.js.map +1 -0
  39. package/dist/cli/control.js +52 -0
  40. package/dist/cli/control.js.map +1 -0
  41. package/dist/cli/init.js +103 -0
  42. package/dist/cli/init.js.map +1 -0
  43. package/dist/cli/pots.js +74 -0
  44. package/dist/cli/pots.js.map +1 -0
  45. package/dist/cli/service.js +228 -0
  46. package/dist/cli/service.js.map +1 -0
  47. package/dist/core/channel.js +4 -0
  48. package/dist/core/channel.js.map +1 -0
  49. package/dist/core/env-file.js +22 -0
  50. package/dist/core/env-file.js.map +1 -0
  51. package/dist/core/home.js +16 -0
  52. package/dist/core/home.js.map +1 -0
  53. package/dist/core/judge.js +3 -0
  54. package/dist/core/judge.js.map +1 -0
  55. package/dist/core/sql.js +2 -0
  56. package/dist/core/sql.js.map +1 -0
  57. package/dist/core/wake.js +2 -0
  58. package/dist/core/wake.js.map +1 -0
  59. package/dist/gateway/gateway.js +175 -0
  60. package/dist/gateway/gateway.js.map +1 -0
  61. package/dist/gateway/log.js +264 -0
  62. package/dist/gateway/log.js.map +1 -0
  63. package/dist/gateway/outbox.js +63 -0
  64. package/dist/gateway/outbox.js.map +1 -0
  65. package/dist/gateway/waker.js +168 -0
  66. package/dist/gateway/waker.js.map +1 -0
  67. package/dist/main.js +148 -0
  68. package/dist/main.js.map +1 -0
  69. package/docs/channels/slack-app-manifest.yaml +54 -0
  70. package/docs/channels/slack.md +22 -0
  71. package/package.json +55 -4
@@ -0,0 +1,168 @@
1
+ import { LOG_SCHEMA } from "../gateway/log.js";
2
+ export function identitySection(facts, persona) {
3
+ return `# Who you are\nYou are ${facts.name}.\n\n${persona.trim()}`;
4
+ }
5
+ export function workSection(facts) {
6
+ const accounts = facts.accounts.map((account) => ` - ${account.channel}: ${account.me ? account.me.address : "(not connected yet)"}`).join("\n");
7
+ return `# How you work
8
+ - You are a coworker on a team. You listen to every message in the places you were invited to (channels, DMs, group chats). Every event goes into the message log: messages that do not mention you, edits, deletions, reactions, people joining, and your own messages.
9
+ - You are woken when there is something for you: someone mentions you or sends you a DM; the judge finds that people are talking about something you are responsible for and you need to respond (with the judge off, every message that does not mention you comes to you); a time you set comes; or the fallback check-in. A wake message tells you only where, who, why, the time of each new event and the time now. Read the content yourself in the log.
10
+ - While you are working on a place, new events there come to you as "[new events]".
11
+ - You decide whether to speak, what to say, where and when. You also decide whether a message is out of date and whether it still needs anything. A coworker does not need to answer in seconds: you can think and do the work first, then reply.
12
+ - Your answer text is not sent to anyone. To speak in a channel, use send. To add a reaction, use react. For other platform features, use call.
13
+
14
+ # Addresses
15
+ - An address is an opaque string that points to a place, thread, message or person. It starts with the channel account. Copy addresses from wake messages or the log; do not build them yourself.
16
+ - The "to" of send: a place gives a new message; a thread or message gives a reply in that thread; a person gives a DM.
17
+ - To mention a person in text, put their address in angle brackets: <person address>.
18
+ - Your own address in each channel account:
19
+ ${accounts}
20
+
21
+ # Tools and command line
22
+ - Tools: read, write, edit, bash, and send, react, call.
23
+ - The command line pots does the same channel actions, and also handles timed wakes, turning the page and context use. Your scripts and scheduled jobs can use it too:
24
+ pots send <address> <text, or - to read stdin> [--id <send ID>] a send ID is sent only once; use the same ID when you redo
25
+ pots react <message address> <emoji> [--remove]
26
+ pots call <channel> <method> [JSON params, or -]
27
+ pots wake --in 30m | --at "2026-10-28 09:00" [--note <text>] timed wake; with no time it is now
28
+ pots wake --list | --cancel <id>
29
+ pots context
30
+ pots turn-page --note <text>
31
+ Outside your own bash (for example in cron), write it in full: ${facts.pots} <command> --bot ${facts.id}
32
+
33
+ # This computer
34
+ - It is yours to work on: ${facts.machine.os}, host ${facts.machine.hostname}, user ${facts.machine.user}. The bash tool runs ${facts.machine.shell}.
35
+ - You have all the permissions of this user${facts.machine.sudo ? ", and sudo works without a password" : ""}. Your actions need no approval. You can install what you need and drive a browser or the desktop to do work that has no API.
36
+ - Working directory: ${facts.paths.workspace}`;
37
+ }
38
+ export function logSection(facts) {
39
+ const db = facts.paths.db;
40
+ return `# Message log
41
+ - SQLite file: ${db}. Open it read-only. For example:
42
+ node -e 'const {DatabaseSync}=require("node:sqlite");const db=new DatabaseSync(process.argv[1],{readOnly:true});console.log(db.prepare(process.argv[2]).all())' ${db} "SELECT ..."
43
+ - Tables:
44
+ ${LOG_SCHEMA}
45
+ - bot_wakes(id, at, reason, place, text, submission): each time you were woken, with the full wake message.
46
+ - bot_timers(id, due_at, note, state, set_by, created_at, fired_at): timed wakes. set_by is agent (you set it) or fallback.
47
+ - Tables that start with pi_ are your conversation storage (pi-durable).`;
48
+ }
49
+ export function folderSection(facts) {
50
+ const paths = facts.paths;
51
+ return `# Your folder: ${paths.dir}
52
+ - bot.json: your definition: name, model, thinking, judge, channels (channel accounts), settings. model is "provider/modelId". judge decides which messages that do not mention you wake you: "main" (your own model judges), "off" (all of them), or a classifier "provider/modelId" such as typesafe/jev-latest. Models and logins are pi's: ~/.pi/agent/auth.json, and ~/.pi/agent/models.json for OpenAI-compatible and local endpoints. Changes take effect within a few seconds. If it has an error, the error goes into bot.json.error and the old definition stays in use.
53
+ - persona.md: your personality and how you talk. It is read before each request, so changes take effect at once.
54
+ - responsibilities.md: what you are responsible for. The judge uses it to decide whether an event that does not mention you is about you. When your responsibilities change, update it.
55
+ - notes.md: your notes. After you turn the page, you find what you need again from them and the message log.
56
+ - workspace/: your working directory.
57
+ - Channel types: slack, terminal (the person who set you up, in their terminal), test. How to connect a new chat app yourself is in ${facts.docs}/channels/; put its tokens in ${facts.secretsDir}, readable only by this user.
58
+ - Other bots are in ${facts.botsDir}, one subfolder per bot. You can change their definitions. A new folder with a bot.json is a new bot.`;
59
+ }
60
+ export function memorySection(facts) {
61
+ return `# Context and turning the page
62
+ - You have one long-lived conversation. Events from all channels go into it.
63
+ - Each wake tells you how many tokens the context uses, how large the window is, and at what point pi compacts it automatically. You can also check at any time with pots context.
64
+ - Automatic compaction turns the old conversation into a summary written by pi, and details are lost. You decide when to turn the page. To turn the page: first write what you will need into ${facts.paths.notes}, then run pots turn-page --note "<a message to yourself in the new context>". The first message of the new context is that message and the full notes. After you turn the page you cannot see the old conversation; the message log stays.
65
+ - Turning the page takes effect when the current round of tool calls ends, and that round ends with it.
66
+
67
+ # Timed wakes
68
+ - Use pots wake to set timed wakes. You can have several at once, and you choose the times: look in now and then at what people are talking about, or do something you promised when its time comes.
69
+ - When you have no timed wake, a fallback check-in comes every ${facts.fallbackWakeMinutes} minutes.`;
70
+ }
71
+ /** "2026-10-27 17:04:07 Tuesday (GMT+11)", in the machine's time zone. */
72
+ export function formatTime(ms) {
73
+ const parts = Object.fromEntries(new Intl.DateTimeFormat("en-US", {
74
+ year: "numeric",
75
+ month: "2-digit",
76
+ day: "2-digit",
77
+ hour: "2-digit",
78
+ minute: "2-digit",
79
+ second: "2-digit",
80
+ weekday: "long",
81
+ hourCycle: "h23",
82
+ timeZoneName: "short",
83
+ })
84
+ .formatToParts(new Date(ms))
85
+ .map((part) => [part.type, part.value]));
86
+ return `${parts.year}-${parts.month}-${parts.day} ${parts.hour}:${parts.minute}:${parts.second} ${parts.weekday} (${parts.timeZoneName})`;
87
+ }
88
+ export function renderContext(status) {
89
+ const k = (tokens) => `${Math.round(tokens / 1000)}k`;
90
+ return `Context: about ${k(status.used)} tokens used, window ${k(status.window)}; pi compacts automatically at about ${k(status.compactAt)}.`;
91
+ }
92
+ const KINDS = {
93
+ message: "message",
94
+ edit: "edit",
95
+ delete: "delete",
96
+ reaction_added: "reaction added",
97
+ reaction_removed: "reaction removed",
98
+ join: "joined",
99
+ leave: "left",
100
+ update: "message changed (not the text)",
101
+ };
102
+ const PLACE_KINDS = { channel: "channel", dm: "DM", group: "group chat" };
103
+ function renderEvent(event) {
104
+ const parts = [`${formatTime(event.at)} ${KINDS[event.kind] ?? event.kind}`];
105
+ if (event.person)
106
+ parts.push(`${event.person.name ?? "?"} (${event.person.address})`);
107
+ if (event.message)
108
+ parts.push(`message ${event.message}`);
109
+ if (event.thread && event.thread !== event.message)
110
+ parts.push(`thread ${event.thread}`);
111
+ if (event.mentionsMe)
112
+ parts.push("mentions you");
113
+ return `- ${parts.join(", ")}`;
114
+ }
115
+ export function renderPlaceWake(wake, status) {
116
+ let why;
117
+ switch (wake.reason) {
118
+ case "mention":
119
+ why = "someone mentioned you";
120
+ break;
121
+ case "dm":
122
+ why = "DM";
123
+ break;
124
+ case "steer":
125
+ why = "new events in the place you are working on";
126
+ break;
127
+ case "relevant":
128
+ why =
129
+ wake.judged && "error" in wake.judged
130
+ ? `no mention. The judge could not decide this time (${wake.judged.error}), so it comes to you`
131
+ : `no mention. The judge found that it is about what you are responsible for and you need to respond (related ${wake.judged?.related.toFixed(2)}, respond ${wake.judged?.respond.toFixed(2)})`;
132
+ break;
133
+ case "heard":
134
+ why = "no mention. You have no judge set, so every message comes to you";
135
+ break;
136
+ }
137
+ const place = wake.place;
138
+ const lines = [
139
+ `${wake.reason === "steer" ? "[new events]" : "[wake]"} ${why}`,
140
+ `Now: ${formatTime(Date.now())}`,
141
+ `Place: ${place.name ?? "?"} (${place.address}, ${PLACE_KINDS[place.kind]})`,
142
+ `New events (${wake.events.length}):`,
143
+ ...wake.events.map(renderEvent),
144
+ renderContext(status),
145
+ ];
146
+ return lines.join("\n");
147
+ }
148
+ export function renderTimerWake(timer, status, fallbackMinutes) {
149
+ const why = timer.set_by === "fallback"
150
+ ? `fallback check-in: you have no timed wake, so one comes every ${fallbackMinutes} minutes`
151
+ : `timed wake (you set it at ${formatTime(timer.created_at)})`;
152
+ const lines = [`[wake] ${why}`, `Now: ${formatTime(Date.now())}`, `Due: ${formatTime(timer.due_at)}`];
153
+ if (timer.note)
154
+ lines.push(`Note: ${timer.note}`);
155
+ lines.push(renderContext(status));
156
+ return lines.join("\n");
157
+ }
158
+ export function renderHandoff(note, notes, notesPath) {
159
+ return `[turned the page] A new context starts here. You ended the previous context yourself.
160
+ Now: ${formatTime(Date.now())}
161
+
162
+ ## What you wrote to yourself when you turned the page
163
+ ${note.trim() || "(empty)"}
164
+
165
+ ## Full notes (${notesPath})
166
+ ${notes.trim() || "(the notes are empty)"}`;
167
+ }
168
+ //# sourceMappingURL=prompt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt.js","sourceRoot":"","sources":["../../src/bot/prompt.ts"],"names":[],"mappings":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AC,IAAI,CAAC,CAAC;AAC1B,CAAC;AAED,MAAM,UAAU,eAAe,CAAC,KAAY,EAAE,MAAqB,EAAE,eAAuB;IAC1F,MAAM,GAAG,GACP,KAAK,CAAC,MAAM,KAAK,UAAU;QACzB,CAAC,CAAC,iEAAiE,eAAe,UAAU;QAC5F,CAAC,CAAC,6BAA6B,UAAU,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;IACnE,MAAM,KAAK,GAAG,CAAC,UAAU,GAAG,EAAE,EAAE,QAAQ,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,QAAQ,UAAU,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IACtG,IAAI,KAAK,CAAC,IAAI;QAAE,KAAK,CAAC,IAAI,CAAC,SAAS,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IAClD,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC;IAClC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,IAAY,EAAE,KAAa,EAAE,SAAiB;IAC1E,OAAO;OACF,UAAU,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;;;EAG3B,IAAI,CAAC,IAAI,EAAE,IAAI,SAAS;;iBAET,SAAS;EACxB,KAAK,CAAC,IAAI,EAAE,IAAI,uBAAuB,EAAE,CAAC;AAC5C,CAAC"}
@@ -0,0 +1,113 @@
1
+ const SCHEMA = `
2
+ CREATE TABLE IF NOT EXISTS bot_timers (
3
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
4
+ due_at INTEGER NOT NULL,
5
+ note TEXT NOT NULL DEFAULT '',
6
+ state TEXT NOT NULL,
7
+ set_by TEXT NOT NULL,
8
+ created_at INTEGER NOT NULL,
9
+ fired_at INTEGER
10
+ );
11
+ CREATE INDEX IF NOT EXISTS bot_timers_pending ON bot_timers (due_at) WHERE state = 'pending';
12
+ `;
13
+ const CHECK_MS = 30_000;
14
+ /**
15
+ * Timed wakes. The agent sets as many as it likes. While it has none pending, one fallback wake is kept,
16
+ * fallbackMinutes after the moment it had none left (the start, the last firing, or a cancel).
17
+ */
18
+ export class Timers {
19
+ #sql;
20
+ #fallbackMinutes;
21
+ #fire;
22
+ #log;
23
+ #timer;
24
+ #check = Promise.resolve();
25
+ #stopped = false;
26
+ constructor(sql, fallbackMinutes, fire, log) {
27
+ this.#sql = sql;
28
+ this.#fallbackMinutes = fallbackMinutes;
29
+ this.#fire = fire;
30
+ this.#log = log;
31
+ }
32
+ static async open(sql, fallbackMinutes, fire, log) {
33
+ await sql.exec(SCHEMA);
34
+ return new Timers(sql, fallbackMinutes, fire, log);
35
+ }
36
+ async start() {
37
+ await this.#ensureFallback();
38
+ this.#schedule();
39
+ }
40
+ async stop() {
41
+ this.#stopped = true;
42
+ clearTimeout(this.#timer);
43
+ await this.#check;
44
+ }
45
+ async add(dueAt, note) {
46
+ if (!Number.isFinite(dueAt))
47
+ throw new Error("bad time");
48
+ const timer = await this.#sql.transaction(async (tx) => {
49
+ await tx.run("UPDATE bot_timers SET state = 'replaced' WHERE state = 'pending' AND set_by = 'fallback'");
50
+ await tx.run("INSERT INTO bot_timers (due_at, note, state, set_by, created_at) VALUES (?, ?, 'pending', 'agent', ?)", dueAt, note, Date.now());
51
+ return (await tx.get("SELECT id, due_at, note, set_by, created_at FROM bot_timers WHERE id = last_insert_rowid()"));
52
+ });
53
+ this.#schedule();
54
+ return timer;
55
+ }
56
+ async cancel(id) {
57
+ const found = await this.#sql.get("SELECT 1 AS x FROM bot_timers WHERE id = ? AND state = 'pending'", id);
58
+ if (!found)
59
+ return false;
60
+ await this.#sql.run("UPDATE bot_timers SET state = 'cancelled' WHERE id = ?", id);
61
+ await this.#ensureFallback();
62
+ this.#schedule();
63
+ return true;
64
+ }
65
+ /** The fallback interval changed: put the pending fallback wake at the new interval from now. */
66
+ async resetFallback() {
67
+ await this.#sql.run("UPDATE bot_timers SET state = 'replaced' WHERE state = 'pending' AND set_by = 'fallback'");
68
+ await this.#ensureFallback();
69
+ this.#schedule();
70
+ }
71
+ pending() {
72
+ return this.#sql.all("SELECT id, due_at, note, set_by, created_at FROM bot_timers WHERE state = 'pending' ORDER BY due_at");
73
+ }
74
+ /** Keep a fallback wake while the agent has none of its own. */
75
+ async #ensureFallback() {
76
+ const pending = await this.pending();
77
+ if (pending.length > 0)
78
+ return;
79
+ const dueAt = Date.now() + this.#fallbackMinutes() * 60_000;
80
+ await this.#sql.run("INSERT INTO bot_timers (due_at, note, state, set_by, created_at) VALUES (?, '', 'pending', 'fallback', ?)", dueAt, Date.now());
81
+ }
82
+ #schedule() {
83
+ if (this.#stopped)
84
+ return;
85
+ clearTimeout(this.#timer);
86
+ this.#check = this.#check
87
+ .then(async () => {
88
+ const next = (await this.pending())[0];
89
+ const wait = next ? Math.max(0, Math.min(CHECK_MS, next.due_at - Date.now())) : CHECK_MS;
90
+ if (this.#stopped)
91
+ return;
92
+ this.#timer = setTimeout(() => void this.#fireDue(), wait);
93
+ })
94
+ .catch((error) => this.#log("timer schedule failed", { error: String(error) }));
95
+ }
96
+ async #fireDue() {
97
+ this.#check = this.#check
98
+ .then(async () => {
99
+ for (const timer of await this.pending()) {
100
+ if (this.#stopped || timer.due_at > Date.now())
101
+ break;
102
+ await this.#fire(timer);
103
+ await this.#sql.run("UPDATE bot_timers SET state = 'fired', fired_at = ? WHERE id = ?", Date.now(), timer.id);
104
+ this.#log("timer fired", { id: timer.id, setBy: timer.set_by });
105
+ }
106
+ await this.#ensureFallback();
107
+ })
108
+ .catch((error) => this.#log("timer failed", { error: String(error) }));
109
+ await this.#check;
110
+ this.#schedule();
111
+ }
112
+ }
113
+ //# sourceMappingURL=timers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"timers.js","sourceRoot":"","sources":["../../src/bot/timers.ts"],"names":[],"mappings":"AAEA,MAAM,MAAM,GAAG;;;;;;;;;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Q,IAAI,KAAK,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,EAAE;oBAAE,MAAM;gBACtD,MAAM,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;gBACxB,MAAM,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,kEAAkE,EAAE,IAAI,CAAC,GAAG,EAAE,EAAE,KAAK,CAAC,EAAE,CAAC,CAAC;gBAC9G,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,EAAE,EAAE,EAAE,KAAK,CAAC,EAAE,EAAE,KAAK,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAAC;YAClE,CAAC;YACD,MAAM,IAAI,CAAC,eAAe,EAAE,CAAC;QAC/B,CAAC,CAAC;aACD,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;QACzE,MAAM,IAAI,CAAC,MAAM,CAAC;QAClB,IAAI,CAAC,SAAS,EAAE,CAAC;IACnB,CAAC;CACF"}
@@ -0,0 +1,21 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /** ".ts" when running from source, ".js" when running the built package. */
10
+ const extension = import.meta.url.slice(import.meta.url.lastIndexOf("."));
11
+ /**
12
+ * Make the adapter for one channel entry of a bot. The type names a folder next to this file: "slack" loads
13
+ * ./slack/index.ts. Adding a channel type is adding a folder; nothing else changes.
14
+ */
15
+ export async function loadChannel(config, env) {
16
+ if (!/^[a-z0-9-]+$/.test(config.type))
17
+ throw new Error(`bad channel type ${JSON.stringify(config.type)}`);
18
+ const module = (await import(__rewriteRelativeImportExtension(new URL(`./${config.type}/index${extension}`, import.meta.url).href)));
19
+ return module.createChannel(config, env);
20
+ }
21
+ //# sourceMappingURL=load.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load.js","sourceRoot":"","sources":["../../src/channels/load.ts"],"names":[],"mappings":";;;;;;;;AAEA,4EAA4E;AAC5E,MAAM,SAAS,GAAG,OAAO,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC;AAE1E;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,MAAqB,EAAE,GAAe;IACtE,IAAI,CAAC,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,oBAAoB,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC1G,MAAM,MAAM,GAAG,CAAC,MAAM,MAAM,kCAAC,IAAI,GAAG,CAAC,KAAK,MAAM,CAAC,IAAI,SAAS,SAAS,EAAE,EAAE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,IAAI,EAAC,CAAkB,CAAC;IACpH,OAAO,MAAM,CAAC,aAAa,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;AAC3C,CAAC"}