skill-monster 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.
- package/LICENSE +202 -0
- package/README.md +155 -2
- package/desk-ui/app.css +73 -0
- package/desk-ui/app.js +182 -0
- package/desk-ui/fonts/bricolage-grotesque-800.woff2 +0 -0
- package/desk-ui/fonts/ibm-plex-mono-400.woff2 +0 -0
- package/desk-ui/fonts/ibm-plex-mono-600.woff2 +0 -0
- package/desk-ui/fonts/ibm-plex-sans-400.woff2 +0 -0
- package/desk-ui/fonts/silkscreen-400.woff2 +0 -0
- package/desk-ui/fonts.css +70 -0
- package/desk-ui/index.html +29 -0
- package/desk-ui/mascot.svg +1 -0
- package/dist/build.json +1 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.js +640 -0
- package/dist/cli/ui.d.ts +18 -0
- package/dist/cli/ui.js +120 -0
- package/dist/core/checkup.d.ts +14 -0
- package/dist/core/checkup.js +69 -0
- package/dist/core/corrections.d.ts +54 -0
- package/dist/core/corrections.js +138 -0
- package/dist/core/digest.d.ts +36 -0
- package/dist/core/digest.js +91 -0
- package/dist/core/export.d.ts +8 -0
- package/dist/core/export.js +28 -0
- package/dist/core/external.d.ts +48 -0
- package/dist/core/external.js +127 -0
- package/dist/core/guard.d.ts +10 -0
- package/dist/core/guard.js +48 -0
- package/dist/core/mirror.d.ts +37 -0
- package/dist/core/mirror.js +148 -0
- package/dist/core/release.d.ts +69 -0
- package/dist/core/release.js +173 -0
- package/dist/core/report.d.ts +10 -0
- package/dist/core/report.js +65 -0
- package/dist/core/scrub.d.ts +20 -0
- package/dist/core/scrub.js +67 -0
- package/dist/core/sign.d.ts +25 -0
- package/dist/core/sign.js +86 -0
- package/dist/core/skill.d.ts +26 -0
- package/dist/core/skill.js +68 -0
- package/dist/core/starters.d.ts +54 -0
- package/dist/core/starters.js +184 -0
- package/dist/core/types.d.ts +187 -0
- package/dist/core/types.js +1 -0
- package/dist/core/version.d.ts +4 -0
- package/dist/core/version.js +17 -0
- package/dist/core/workspace.d.ts +23 -0
- package/dist/core/workspace.js +79 -0
- package/dist/desk/server.d.ts +10 -0
- package/dist/desk/server.js +140 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/mcp/server.d.ts +8 -0
- package/dist/mcp/server.js +112 -0
- package/dist/providers/index.d.ts +15 -0
- package/dist/providers/index.js +123 -0
- package/dist/slack/api.d.ts +6 -0
- package/dist/slack/api.js +18 -0
- package/dist/slack/app.d.ts +70 -0
- package/dist/slack/app.js +387 -0
- package/dist/slack/manifest.d.ts +50 -0
- package/dist/slack/manifest.js +71 -0
- package/dist/slack/messages.d.ts +414 -0
- package/dist/slack/messages.js +226 -0
- package/dist/slack/socket.d.ts +24 -0
- package/dist/slack/socket.js +84 -0
- package/dist/stores/airtable.d.ts +26 -0
- package/dist/stores/airtable.js +52 -0
- package/dist/stores/confluence-format.d.ts +34 -0
- package/dist/stores/confluence-format.js +458 -0
- package/dist/stores/confluence.d.ts +55 -0
- package/dist/stores/confluence.js +204 -0
- package/dist/stores/index.d.ts +30 -0
- package/dist/stores/index.js +53 -0
- package/dist/stores/notion.d.ts +43 -0
- package/dist/stores/notion.js +313 -0
- package/docs/SECURITY.md +45 -0
- package/docs/slack.md +78 -0
- package/package.json +48 -4
- package/starters/_core/SKILL.md +30 -0
- package/starters/customer-support-answers/starter.yaml +98 -0
- package/starters/data-warehouse-kb/starter.yaml +119 -0
- package/starters/engineering-house-rules/starter.yaml +106 -0
- package/starters/people-policies/starter.yaml +89 -0
- package/starters/pricing-and-packaging/starter.yaml +90 -0
- package/starters/product-analytics-kb/starter.yaml +109 -0
- package/starters/security-questionnaire-answers/starter.yaml +94 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
export class MissingKeyError extends Error {
|
|
6
|
+
}
|
|
7
|
+
export async function ask(m, chat) {
|
|
8
|
+
const key = m.key_env ? process.env[m.key_env] : undefined;
|
|
9
|
+
if (m.provider !== 'offline' && m.provider !== 'openai-compatible' && m.provider !== 'command' && m.provider !== 'answers' && !key)
|
|
10
|
+
throw new MissingKeyError(`${m.key_env} is not set`);
|
|
11
|
+
const max = chat.maxTokens ?? 600;
|
|
12
|
+
switch (m.provider) {
|
|
13
|
+
case 'anthropic': {
|
|
14
|
+
const r = await post('https://api.anthropic.com/v1/messages', {
|
|
15
|
+
'x-api-key': key, 'anthropic-version': '2023-06-01',
|
|
16
|
+
}, { model: m.model, max_tokens: max, system: chat.system, messages: [{ role: 'user', content: chat.user }] });
|
|
17
|
+
return (r.content ?? []).filter((c) => c.type === 'text').map((c) => c.text).join('');
|
|
18
|
+
}
|
|
19
|
+
case 'openai':
|
|
20
|
+
case 'openai-compatible': {
|
|
21
|
+
const base = (m.base_url ?? 'https://api.openai.com/v1').replace(/\/$/, '');
|
|
22
|
+
const r = await post(`${base}/chat/completions`, key ? { Authorization: `Bearer ${key}` } : {}, {
|
|
23
|
+
model: m.model, max_completion_tokens: max,
|
|
24
|
+
messages: [{ role: 'system', content: chat.system }, { role: 'user', content: chat.user }],
|
|
25
|
+
});
|
|
26
|
+
return r.choices?.[0]?.message?.content ?? '';
|
|
27
|
+
}
|
|
28
|
+
case 'gemini': {
|
|
29
|
+
const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(m.model)}:generateContent`;
|
|
30
|
+
const r = await post(url, { 'x-goog-api-key': key }, {
|
|
31
|
+
systemInstruction: { parts: [{ text: chat.system }] },
|
|
32
|
+
contents: [{ role: 'user', parts: [{ text: chat.user }] }],
|
|
33
|
+
generationConfig: { maxOutputTokens: max },
|
|
34
|
+
});
|
|
35
|
+
return (r.candidates?.[0]?.content?.parts ?? []).map((p) => p.text ?? '').join('');
|
|
36
|
+
}
|
|
37
|
+
case 'command':
|
|
38
|
+
return runCommand(m, chat);
|
|
39
|
+
case 'answers':
|
|
40
|
+
throw new MissingKeyError('answered outside Skill Monster: use test --emit-prompts, then --answers');
|
|
41
|
+
case 'offline':
|
|
42
|
+
return offlineAnswer(chat);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/** Runs a local program (for example Claude Code in print mode) with the prompt on stdin. */
|
|
46
|
+
export async function runCommand(m, chat) {
|
|
47
|
+
const cmd = m.command;
|
|
48
|
+
if (!cmd?.length)
|
|
49
|
+
throw new Error(`Model ${m.name} uses provider "command" but has no command, e.g. command: ["claude", "-p"]`);
|
|
50
|
+
const usesFile = cmd.some(a => a.includes('{system_file}'));
|
|
51
|
+
let tmp;
|
|
52
|
+
if (usesFile) {
|
|
53
|
+
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-sys-'));
|
|
54
|
+
fs.writeFileSync(path.join(tmp, 'system.txt'), chat.system, { mode: 0o600 });
|
|
55
|
+
}
|
|
56
|
+
const args = cmd.slice(1).map(a => a.replaceAll('{system_file}', tmp ? path.join(tmp, 'system.txt') : ''));
|
|
57
|
+
const input = usesFile ? chat.user : `${chat.system}\n\n---\n\nQuestion: ${chat.user}\n`;
|
|
58
|
+
try {
|
|
59
|
+
return await new Promise((resolve, reject) => {
|
|
60
|
+
const child = spawn(cmd[0], args, { stdio: ['pipe', 'pipe', 'pipe'] });
|
|
61
|
+
let out = '', err = '';
|
|
62
|
+
const timer = setTimeout(() => { child.kill('SIGKILL'); reject(new Error(`${cmd[0]} took longer than ${m.timeout ?? 180}s`)); }, (m.timeout ?? 180) * 1000);
|
|
63
|
+
child.stdout.on('data', d => (out += d));
|
|
64
|
+
child.stderr.on('data', d => (err += d));
|
|
65
|
+
child.on('error', e => { clearTimeout(timer); reject(new Error(`Could not run ${cmd[0]}: ${e.message}`)); });
|
|
66
|
+
child.on('close', code => {
|
|
67
|
+
clearTimeout(timer);
|
|
68
|
+
if (code === 0)
|
|
69
|
+
resolve(out.trim());
|
|
70
|
+
else
|
|
71
|
+
reject(new Error(`${cmd[0]} exited with ${code}: ${err.trim().slice(0, 300)}`));
|
|
72
|
+
});
|
|
73
|
+
child.stdin.end(input);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
finally {
|
|
77
|
+
if (tmp)
|
|
78
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
async function post(url, headers, body) {
|
|
82
|
+
for (let attempt = 0;; attempt++) {
|
|
83
|
+
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(body) });
|
|
84
|
+
if (r.ok)
|
|
85
|
+
return r.json();
|
|
86
|
+
if ((r.status === 429 || r.status >= 500) && attempt < 3) {
|
|
87
|
+
await new Promise(res => setTimeout(res, 1000 * 2 ** attempt));
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
throw new Error(`${r.status} ${(await r.text()).slice(0, 300)}`);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* A deterministic stand-in used by demos and CI without keys: it answers by quoting the
|
|
95
|
+
* skill line that best matches the question. It proves the plumbing, not a real model.
|
|
96
|
+
*/
|
|
97
|
+
function offlineAnswer(chat) {
|
|
98
|
+
if (/Reply with exactly PASS or FAIL/.test(chat.system))
|
|
99
|
+
return 'PASS';
|
|
100
|
+
const STOP = new Set(['what', 'which', 'when', 'where', 'does', 'that', 'this', 'with', 'from', 'have', 'there', 'about', 'should', 'would', 'could', 'your', 'show', 'tell', 'give', 'last', 'week']);
|
|
101
|
+
const words = (s) => new Set((s.toLowerCase().match(/[a-z0-9]{4,}/g) ?? []).filter(w => !STOP.has(w)).map(w => w.replace(/(ies|es|s)$/, m => (m === 'ies' ? 'y' : ''))));
|
|
102
|
+
const q = words(chat.user);
|
|
103
|
+
let best = '', score = 0;
|
|
104
|
+
for (const line of chat.system.split('\n')) {
|
|
105
|
+
if (!line.trim() || line.startsWith('<!--') || line.startsWith('#') || /→ section|^\s*-?\s*Always |^You /.test(line))
|
|
106
|
+
continue;
|
|
107
|
+
const w = words(line);
|
|
108
|
+
let s = 0;
|
|
109
|
+
for (const x of q)
|
|
110
|
+
if (w.has(x))
|
|
111
|
+
s++;
|
|
112
|
+
if (s > score) {
|
|
113
|
+
score = s;
|
|
114
|
+
best = line.trim();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const footer = chat.system.match(/"(Answered from [^"]+)"/)?.[1];
|
|
118
|
+
const refuse = /\b(e-?mails?|card numbers?|salar(y|ies)|passwords?|api keys?|phone numbers?|home address(es)?)\b/i.test(chat.user);
|
|
119
|
+
const ans = refuse ? "I can't share that. It is sensitive and not in this skill."
|
|
120
|
+
: score < 2 || /Not defined yet/.test(best) ? `I don't know: that is not defined yet in this skill. ${best.match(/Ask [^.]+\./)?.[0] ?? 'Ask the owner.'} I can hand this to a human colleague.`
|
|
121
|
+
: best;
|
|
122
|
+
return footer ? `${ans}\n\n${footer}` : ans;
|
|
123
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A tiny Slack Web API client. Calls go only to slack.com, with the org's own bot token
|
|
3
|
+
* from the environment. Nothing goes to Skill Monster.
|
|
4
|
+
*/
|
|
5
|
+
export type SlackCall = (method: string, body?: Record<string, unknown>) => Promise<any>;
|
|
6
|
+
export declare function slackApi(token: string, fetchImpl?: typeof fetch, base?: string): SlackCall;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export function slackApi(token, fetchImpl = fetch, base = 'https://slack.com/api/') {
|
|
2
|
+
return async (method, body = {}) => {
|
|
3
|
+
const r = await fetchImpl(base + method, {
|
|
4
|
+
method: 'POST',
|
|
5
|
+
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json; charset=utf-8' },
|
|
6
|
+
body: JSON.stringify(body),
|
|
7
|
+
});
|
|
8
|
+
if (r.status === 429) {
|
|
9
|
+
const wait = Number(r.headers.get('retry-after') ?? 1);
|
|
10
|
+
await new Promise(res => setTimeout(res, Math.min(30, wait) * 1000));
|
|
11
|
+
return slackApi(token, fetchImpl, base)(method, body);
|
|
12
|
+
}
|
|
13
|
+
const data = await r.json().catch(() => ({ ok: false, error: `HTTP ${r.status}` }));
|
|
14
|
+
if (!data.ok)
|
|
15
|
+
throw new Error(`Slack ${method}: ${data.error ?? 'failed'}${data.response_metadata?.messages ? ` (${data.response_metadata.messages.join('; ')})` : ''}`);
|
|
16
|
+
return data;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { Workspace } from '../core/workspace.js';
|
|
2
|
+
import type { StoreConfig } from '../core/types.js';
|
|
3
|
+
import { buildDigest } from '../core/digest.js';
|
|
4
|
+
import type { SlackCall } from './api.js';
|
|
5
|
+
export declare const FLAG_SHORTCUT = "flag_wrong_answer";
|
|
6
|
+
/** What a handler answers: the ack payload Slack needs within 3 seconds, and slower work to run after it. */
|
|
7
|
+
export interface Handled {
|
|
8
|
+
ack?: unknown;
|
|
9
|
+
after?: () => Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
export interface SlackState {
|
|
12
|
+
/** receipt_token → Slack user id. Kept out of Git: the correction itself stays nameless. */
|
|
13
|
+
receipts: Record<string, string>;
|
|
14
|
+
/** receipt_token → when the receipt (or decline note) was delivered. */
|
|
15
|
+
delivered: Record<string, string>;
|
|
16
|
+
/** Date (YYYY-MM-DD) the last scheduled digest went out. */
|
|
17
|
+
digest_last?: string;
|
|
18
|
+
}
|
|
19
|
+
export declare function statePath(ws: Workspace): string;
|
|
20
|
+
export declare function loadState(ws: Workspace): SlackState;
|
|
21
|
+
export declare function saveState(ws: Workspace, s: SlackState): void;
|
|
22
|
+
export declare function parseDigestAt(s?: string): {
|
|
23
|
+
day: number;
|
|
24
|
+
h: number;
|
|
25
|
+
m: number;
|
|
26
|
+
} | null;
|
|
27
|
+
export declare function digestDue(now: Date, at: string | undefined, last?: string): boolean;
|
|
28
|
+
export declare function storeLabel(s: StoreConfig): string;
|
|
29
|
+
export interface SlackAppOptions {
|
|
30
|
+
call: SlackCall;
|
|
31
|
+
/** Posts to a Slack response_url (hooks.slack.com). */
|
|
32
|
+
respond?: (url: string, body: unknown) => Promise<void>;
|
|
33
|
+
log?: (m: string) => void;
|
|
34
|
+
/** Skip model calls during approve (tests and demos). */
|
|
35
|
+
offline?: boolean;
|
|
36
|
+
}
|
|
37
|
+
export declare class SlackApp {
|
|
38
|
+
ws: Workspace;
|
|
39
|
+
private o;
|
|
40
|
+
private pending;
|
|
41
|
+
private lock;
|
|
42
|
+
private log;
|
|
43
|
+
constructor(ws: Workspace, o: SlackAppOptions);
|
|
44
|
+
private get cfg();
|
|
45
|
+
private curators;
|
|
46
|
+
isCurator(user?: string): boolean;
|
|
47
|
+
private owner;
|
|
48
|
+
/** One release at a time: approvals change the repo and sign with the org's key. */
|
|
49
|
+
private serial;
|
|
50
|
+
private respond;
|
|
51
|
+
private dm;
|
|
52
|
+
private ephemeral;
|
|
53
|
+
/** Entry point for every Socket Mode envelope. */
|
|
54
|
+
handle(type: string, payload: any): Promise<Handled>;
|
|
55
|
+
private slash;
|
|
56
|
+
private interactive;
|
|
57
|
+
private openFlag;
|
|
58
|
+
private submission;
|
|
59
|
+
private sweep;
|
|
60
|
+
private noteFor;
|
|
61
|
+
private postNote;
|
|
62
|
+
/** Sends receipts (and decline notes) for corrections flagged from Slack, whichever surface approved them. */
|
|
63
|
+
deliverReceipts(): Promise<number>;
|
|
64
|
+
/** Posts the digest to the digest channel, or DMs each curator. */
|
|
65
|
+
sendDigest(prebuilt?: Awaited<ReturnType<typeof buildDigest>>): Promise<number>;
|
|
66
|
+
/** Runs every minute: delivers receipts, and sends the digest when it's due. */
|
|
67
|
+
tick(now?: Date): Promise<void>;
|
|
68
|
+
}
|
|
69
|
+
/** Turns Slack message markup back into plain text for the answer field. */
|
|
70
|
+
export declare function slackToPlain(s: string): string;
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* The self-hosted Slack app (rung 2). The org registers it from the manifest and runs it on
|
|
3
|
+
* its own server with its own tokens. It reads and writes the workspace only, talks only to
|
|
4
|
+
* slack.com, and sends nothing to Skill Monster.
|
|
5
|
+
*/
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { nowIso, readJson, writeJson } from '../core/workspace.js';
|
|
10
|
+
import { approve, decline, fileCorrection, getCorrection, listCorrections, previewCorrection } from '../core/corrections.js';
|
|
11
|
+
import { buildDigest } from '../core/digest.js';
|
|
12
|
+
import { bumpVersion, loadSkill } from '../core/skill.js';
|
|
13
|
+
import { BlockedError, listReleases } from '../core/release.js';
|
|
14
|
+
import * as M from './messages.js';
|
|
15
|
+
export const FLAG_SHORTCUT = 'flag_wrong_answer';
|
|
16
|
+
const PENDING_TTL_MS = 15 * 60 * 1000;
|
|
17
|
+
export function statePath(ws) { return ws.records('private', 'slack.json'); }
|
|
18
|
+
export function loadState(ws) {
|
|
19
|
+
const f = statePath(ws);
|
|
20
|
+
const s = fs.existsSync(f) ? readJson(f) : {};
|
|
21
|
+
return { receipts: s.receipts ?? {}, delivered: s.delivered ?? {}, digest_last: s.digest_last };
|
|
22
|
+
}
|
|
23
|
+
export function saveState(ws, s) {
|
|
24
|
+
const dir = path.dirname(statePath(ws));
|
|
25
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
26
|
+
// Never committed: release commits run "git add" on .skill-monster, which honours this file.
|
|
27
|
+
const ignore = path.join(dir, '.gitignore');
|
|
28
|
+
if (!fs.existsSync(ignore))
|
|
29
|
+
fs.writeFileSync(ignore, '# Private to this server: Slack user ids for receipts. Never commit.\n*\n');
|
|
30
|
+
writeJson(statePath(ws), s);
|
|
31
|
+
try {
|
|
32
|
+
fs.chmodSync(statePath(ws), 0o600);
|
|
33
|
+
}
|
|
34
|
+
catch { /* not supported here */ }
|
|
35
|
+
}
|
|
36
|
+
/* ---------- Schedule ---------- */
|
|
37
|
+
const DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
|
|
38
|
+
export function parseDigestAt(s = 'mon 09:00') {
|
|
39
|
+
if (/^off$/i.test(s.trim()))
|
|
40
|
+
return null;
|
|
41
|
+
const m = s.trim().toLowerCase().match(/^([a-z]{3})[a-z]*\s+(\d{1,2}):(\d{2})$/);
|
|
42
|
+
if (!m || !DAYS.includes(m[1]))
|
|
43
|
+
throw new Error(`slack.digest_at should look like "mon 09:00" or "off", not "${s}".`);
|
|
44
|
+
return { day: DAYS.indexOf(m[1]), h: Number(m[2]), m: Number(m[3]) };
|
|
45
|
+
}
|
|
46
|
+
const localDate = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
|
|
47
|
+
export function digestDue(now, at, last) {
|
|
48
|
+
const p = parseDigestAt(at);
|
|
49
|
+
if (!p || now.getDay() !== p.day)
|
|
50
|
+
return false;
|
|
51
|
+
if (now.getHours() * 60 + now.getMinutes() < p.h * 60 + p.m)
|
|
52
|
+
return false;
|
|
53
|
+
return last !== localDate(now);
|
|
54
|
+
}
|
|
55
|
+
export function storeLabel(s) {
|
|
56
|
+
return { git: 'Git repo', folder: 'folder', notion: 'Notion', airtable: 'Airtable', confluence: 'Confluence' }[s.type] ?? s.type;
|
|
57
|
+
}
|
|
58
|
+
export class SlackApp {
|
|
59
|
+
ws;
|
|
60
|
+
o;
|
|
61
|
+
pending = new Map();
|
|
62
|
+
lock = Promise.resolve();
|
|
63
|
+
log;
|
|
64
|
+
constructor(ws, o) {
|
|
65
|
+
this.ws = ws;
|
|
66
|
+
this.o = o;
|
|
67
|
+
this.log = o.log ?? (() => { });
|
|
68
|
+
}
|
|
69
|
+
get cfg() { return this.ws.config; }
|
|
70
|
+
curators() { return this.cfg.slack?.curators ?? {}; }
|
|
71
|
+
isCurator(user) { return !!user && Object.prototype.hasOwnProperty.call(this.curators(), user); }
|
|
72
|
+
owner(skill) { try {
|
|
73
|
+
return loadSkill(this.ws, skill).owner || this.cfg.curator;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return this.cfg.curator;
|
|
77
|
+
} }
|
|
78
|
+
/** One release at a time: approvals change the repo and sign with the org's key. */
|
|
79
|
+
serial(fn) {
|
|
80
|
+
const run = this.lock.then(fn, fn);
|
|
81
|
+
this.lock = run.catch(() => undefined);
|
|
82
|
+
return run;
|
|
83
|
+
}
|
|
84
|
+
async respond(url, body) {
|
|
85
|
+
if (!url || !this.o.respond)
|
|
86
|
+
return;
|
|
87
|
+
await this.o.respond(url, body);
|
|
88
|
+
}
|
|
89
|
+
dm(user, msg) {
|
|
90
|
+
return this.o.call('chat.postMessage', { channel: user, text: msg.text, blocks: msg.blocks, unfurl_links: false, unfurl_media: false });
|
|
91
|
+
}
|
|
92
|
+
ephemeral(text) { return { response_type: 'ephemeral', text }; }
|
|
93
|
+
/** Entry point for every Socket Mode envelope. */
|
|
94
|
+
async handle(type, payload) {
|
|
95
|
+
const team = payload?.team_id ?? payload?.team?.id;
|
|
96
|
+
if (this.cfg.slack?.team_id && team && team !== this.cfg.slack.team_id) {
|
|
97
|
+
this.log(`Ignored a request from another workspace (${team}).`);
|
|
98
|
+
return {};
|
|
99
|
+
}
|
|
100
|
+
if (type === 'slash_commands')
|
|
101
|
+
return this.slash(payload);
|
|
102
|
+
if (type === 'interactive')
|
|
103
|
+
return this.interactive(payload);
|
|
104
|
+
return {};
|
|
105
|
+
}
|
|
106
|
+
/* ----- /skill-monster ----- */
|
|
107
|
+
async slash(p) {
|
|
108
|
+
const [sub = '', ...rest] = String(p.text ?? '').trim().split(/\s+/);
|
|
109
|
+
const user = p.user_id;
|
|
110
|
+
if (sub === '' || sub === 'flag')
|
|
111
|
+
return { after: () => this.openFlag(p.trigger_id) };
|
|
112
|
+
if (sub === 'digest') {
|
|
113
|
+
if (!this.isCurator(user))
|
|
114
|
+
return { ack: this.ephemeral(M.notCuratorText(this.cfg)) };
|
|
115
|
+
return {
|
|
116
|
+
ack: this.ephemeral('Counting what the monster caught…'),
|
|
117
|
+
after: async () => {
|
|
118
|
+
const d = await buildDigest(this.ws, { interactive: true });
|
|
119
|
+
await this.respond(p.response_url, { response_type: 'ephemeral', replace_original: true, text: d.text, blocks: d.blocks });
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
if (sub === 'note') {
|
|
124
|
+
if (!this.isCurator(user))
|
|
125
|
+
return { ack: this.ephemeral(M.notCuratorText(this.cfg)) };
|
|
126
|
+
const skill = rest[0];
|
|
127
|
+
if (!skill)
|
|
128
|
+
return { ack: this.ephemeral('Which skill? `/skill-monster note <skill>`') };
|
|
129
|
+
let note;
|
|
130
|
+
try {
|
|
131
|
+
note = this.noteFor(skill);
|
|
132
|
+
}
|
|
133
|
+
catch (e) {
|
|
134
|
+
return { ack: this.ephemeral(e.message) };
|
|
135
|
+
}
|
|
136
|
+
const ch = this.cfg.slack?.release_channel;
|
|
137
|
+
const blocks = [
|
|
138
|
+
...note.msg.blocks,
|
|
139
|
+
{ type: 'divider' },
|
|
140
|
+
ch
|
|
141
|
+
? { type: 'actions', elements: [{ type: 'button', style: 'primary', text: { type: 'plain_text', text: 'Post to channel' }, action_id: 'sm_post_note', value: `${note.rec.skill}@${note.rec.version}` }] }
|
|
142
|
+
: { type: 'context', elements: [{ type: 'mrkdwn', text: 'This is a draft only you can see. Paste it where your team will see it, or set slack.release_channel to post it from here.' }] },
|
|
143
|
+
];
|
|
144
|
+
return { ack: { response_type: 'ephemeral', text: note.msg.text, blocks } };
|
|
145
|
+
}
|
|
146
|
+
return { ack: this.ephemeral(M.HELP_TEXT) };
|
|
147
|
+
}
|
|
148
|
+
/* ----- Buttons, shortcuts and modals ----- */
|
|
149
|
+
async interactive(p) {
|
|
150
|
+
const user = p.user?.id;
|
|
151
|
+
if ((p.type === 'message_action' || p.type === 'shortcut') && p.callback_id === FLAG_SHORTCUT) {
|
|
152
|
+
return { after: () => this.openFlag(p.trigger_id, { answer: slackToPlain(p.message?.text ?? '') }) };
|
|
153
|
+
}
|
|
154
|
+
if (p.type === 'view_submission')
|
|
155
|
+
return this.submission(p, user);
|
|
156
|
+
if (p.type === 'block_actions') {
|
|
157
|
+
const a = p.actions?.[0] ?? {};
|
|
158
|
+
if (!['sm_approve', 'sm_decline', 'sm_post_note'].includes(a.action_id))
|
|
159
|
+
return {}; // link buttons: Slack opens the URL itself
|
|
160
|
+
if (!this.isCurator(user))
|
|
161
|
+
return { after: () => this.respond(p.response_url, { response_type: 'ephemeral', replace_original: false, text: M.notCuratorText(this.cfg) }) };
|
|
162
|
+
if (a.action_id === 'sm_post_note')
|
|
163
|
+
return { after: () => this.postNote(String(a.value ?? ''), p.response_url) };
|
|
164
|
+
const ids = String(a.value ?? '').split(',').filter(Boolean);
|
|
165
|
+
return {
|
|
166
|
+
after: async () => {
|
|
167
|
+
let cors;
|
|
168
|
+
try {
|
|
169
|
+
cors = ids.map(id => getCorrection(this.ws, id));
|
|
170
|
+
}
|
|
171
|
+
catch (e) {
|
|
172
|
+
return this.respond(p.response_url, { response_type: 'ephemeral', replace_original: false, text: e.message });
|
|
173
|
+
}
|
|
174
|
+
const done = cors.filter(c => c.status !== 'open');
|
|
175
|
+
if (done.length)
|
|
176
|
+
return this.respond(p.response_url, { response_type: 'ephemeral', replace_original: false, text: `${done.map(c => `${c.id} is already ${c.status}`).join('; ')}. Nothing to do.` });
|
|
177
|
+
const view = a.action_id === 'sm_approve'
|
|
178
|
+
? M.approveModal(cors, loadSkill(this.ws, cors[0].skill), bumpVersion(loadSkill(this.ws, cors[0].skill).version))
|
|
179
|
+
: M.declineModal(cors);
|
|
180
|
+
await this.o.call('views.open', { trigger_id: p.trigger_id, view });
|
|
181
|
+
},
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
return {};
|
|
185
|
+
}
|
|
186
|
+
async openFlag(trigger_id, prefill = {}) {
|
|
187
|
+
const skills = this.ws.listSkills().map(n => loadSkill(this.ws, n));
|
|
188
|
+
if (!skills.length) {
|
|
189
|
+
await this.o.call('views.open', { trigger_id, view: M.workingModal('No skills yet', 'There are no skills in this workspace yet, so there is nothing to flag.') });
|
|
190
|
+
return;
|
|
191
|
+
}
|
|
192
|
+
await this.o.call('views.open', { trigger_id, view: M.flagModal(skills, prefill) });
|
|
193
|
+
}
|
|
194
|
+
async submission(p, user) {
|
|
195
|
+
const v = p.view?.state?.values ?? {};
|
|
196
|
+
const val = (b) => String(v[b]?.v?.value ?? v[b]?.v?.selected_option?.value ?? '').trim();
|
|
197
|
+
const cb = p.view?.callback_id;
|
|
198
|
+
if (cb === M.FLAG_CALLBACK) {
|
|
199
|
+
const input = {
|
|
200
|
+
skill: val('skill'), question: val('question'), answer: val('answer') || undefined,
|
|
201
|
+
what_was_wrong: val('wrong'), suggested_rule: val('rule') || undefined, reporter_role: val('role') || undefined,
|
|
202
|
+
};
|
|
203
|
+
if (!this.ws.listSkills().includes(input.skill))
|
|
204
|
+
return { ack: { response_action: 'errors', errors: { skill: 'Pick one of the skills in the list.' } } };
|
|
205
|
+
const preview = previewCorrection(this.ws, input);
|
|
206
|
+
this.sweep();
|
|
207
|
+
const id = crypto.randomBytes(9).toString('hex');
|
|
208
|
+
// The raw text stays in memory only, for 15 minutes, and is scrubbed again when filed.
|
|
209
|
+
this.pending.set(id, { input, user: user ?? '', expires: Date.now() + PENDING_TTL_MS });
|
|
210
|
+
return { ack: { response_action: 'update', view: M.flagPreviewModal(preview, this.owner(input.skill), id) } };
|
|
211
|
+
}
|
|
212
|
+
if (cb === M.FLAG_CONFIRM_CALLBACK) {
|
|
213
|
+
const id = p.view?.private_metadata;
|
|
214
|
+
const item = this.pending.get(id);
|
|
215
|
+
if (!item || item.expires < Date.now() || item.user !== (user ?? '')) {
|
|
216
|
+
this.pending.delete(id);
|
|
217
|
+
return { ack: { response_action: 'update', view: M.workingModal('Preview expired', 'That preview expired, so nothing was sent. Flag the answer again.') } };
|
|
218
|
+
}
|
|
219
|
+
this.pending.delete(id);
|
|
220
|
+
const c = fileCorrection(this.ws, item.input);
|
|
221
|
+
if (user) {
|
|
222
|
+
const st = loadState(this.ws);
|
|
223
|
+
st.receipts[c.receipt_token] = user;
|
|
224
|
+
saveState(this.ws, st);
|
|
225
|
+
}
|
|
226
|
+
const owner = this.owner(c.skill);
|
|
227
|
+
this.log(`${c.id} filed for ${c.skill}.`);
|
|
228
|
+
return { ack: { response_action: 'update', view: M.flagFiledModal(c, owner) }, after: async () => { if (user)
|
|
229
|
+
await this.dm(user, M.flagFiledMessage(c, owner)); } };
|
|
230
|
+
}
|
|
231
|
+
if (cb === M.APPROVE_CALLBACK || cb === M.DECLINE_CALLBACK) {
|
|
232
|
+
const first = cb === M.APPROVE_CALLBACK ? 'section' : 'note';
|
|
233
|
+
if (!this.isCurator(user))
|
|
234
|
+
return { ack: { response_action: 'errors', errors: { [first]: M.notCuratorText(this.cfg).slice(0, 150) } } };
|
|
235
|
+
const ids = String(p.view?.private_metadata ?? '').split(',').filter(Boolean);
|
|
236
|
+
const name = this.curators()[user];
|
|
237
|
+
if (cb === M.DECLINE_CALLBACK) {
|
|
238
|
+
const note = val('note');
|
|
239
|
+
if (!note)
|
|
240
|
+
return { ack: { response_action: 'errors', errors: { note: 'Say why, in a line. The person who flagged it will see this.' } } };
|
|
241
|
+
return {
|
|
242
|
+
ack: { response_action: 'clear' },
|
|
243
|
+
after: async () => {
|
|
244
|
+
for (const id of ids)
|
|
245
|
+
if (getCorrection(this.ws, id).status === 'open')
|
|
246
|
+
decline(this.ws, id, name, note);
|
|
247
|
+
await this.dm(user, { text: `Declined ${ids.join(', ')}.`, blocks: [{ type: 'section', text: { type: 'mrkdwn', text: `Declined ${ids.join(', ')}. They'll see your note.` } }] });
|
|
248
|
+
await this.deliverReceipts();
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
const include = val('expect').split(';').map(g => g.split('|').map(s => s.trim()).filter(Boolean)).filter(g => g.length);
|
|
253
|
+
if (!include.length)
|
|
254
|
+
return { ack: { response_action: 'errors', errors: { expect: 'Add at least one phrase the right answer must include.' } } };
|
|
255
|
+
if (!val('new'))
|
|
256
|
+
return { ack: { response_action: 'errors', errors: { new: 'Write the new rule.' } } };
|
|
257
|
+
const cors = ids.map(id => getCorrection(this.ws, id));
|
|
258
|
+
if (cors.some(c => c.status !== 'open'))
|
|
259
|
+
return { ack: { response_action: 'errors', errors: { section: 'Someone already decided on this. Nothing was changed.' } } };
|
|
260
|
+
const meta = loadSkill(this.ws, cors[0].skill);
|
|
261
|
+
const next = bumpVersion(meta.version);
|
|
262
|
+
const previous = listReleases(this.ws, meta.name)[0]?.version;
|
|
263
|
+
const models = this.cfg.models.map(m => m.name).join(', ');
|
|
264
|
+
return {
|
|
265
|
+
ack: { response_action: 'update', view: M.workingModal('Chewing…', `Testing *${meta.name} ${next}* on ${models}, then signing. The monster is chewing.`) },
|
|
266
|
+
after: () => this.serial(async () => {
|
|
267
|
+
try {
|
|
268
|
+
const out = await approve(this.ws, {
|
|
269
|
+
ids, section: val('section'), old_text: val('old') || undefined, new_text: val('new'),
|
|
270
|
+
test: { question: val('test') || cors[0].question, include, exclude: val('exclude') ? val('exclude').split(';').map(s => s.trim()).filter(Boolean) : undefined },
|
|
271
|
+
curator: name, offline: this.o.offline,
|
|
272
|
+
});
|
|
273
|
+
const sent = await this.deliverReceipts();
|
|
274
|
+
await this.dm(user, M.approveResultMessage(this.cfg, out.record, sent, previous));
|
|
275
|
+
}
|
|
276
|
+
catch (e) {
|
|
277
|
+
if (e instanceof BlockedError)
|
|
278
|
+
await this.dm(user, M.blockedMessage(e.findings));
|
|
279
|
+
else
|
|
280
|
+
await this.dm(user, M.errorMessage(`Approving ${ids.join(', ')}`, e.message));
|
|
281
|
+
}
|
|
282
|
+
}),
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
return {};
|
|
286
|
+
}
|
|
287
|
+
sweep() { const now = Date.now(); for (const [k, v] of this.pending)
|
|
288
|
+
if (v.expires < now)
|
|
289
|
+
this.pending.delete(k); }
|
|
290
|
+
/* ----- Release notes ----- */
|
|
291
|
+
noteFor(skill, version) {
|
|
292
|
+
const meta = loadSkill(this.ws, skill);
|
|
293
|
+
const rels = listReleases(this.ws, skill);
|
|
294
|
+
const rec = version ? rels.find(r => r.version === version) : rels[0];
|
|
295
|
+
if (!rec)
|
|
296
|
+
throw new Error(`${skill} has no release${version ? ` ${version}` : ''} yet. Release it first.`);
|
|
297
|
+
return { rec, msg: M.releaseNote(this.cfg, meta, rec, storeLabel(this.cfg.store)) };
|
|
298
|
+
}
|
|
299
|
+
async postNote(value, response_url) {
|
|
300
|
+
const [skill, version] = value.split('@');
|
|
301
|
+
const ch = this.cfg.slack?.release_channel;
|
|
302
|
+
if (!ch)
|
|
303
|
+
return this.respond(response_url, { response_type: 'ephemeral', replace_original: false, text: 'Set slack.release_channel in skill-monster.yaml to post release notes.' });
|
|
304
|
+
const { msg } = this.noteFor(skill, version);
|
|
305
|
+
await this.o.call('chat.postMessage', { channel: ch, text: msg.text, blocks: msg.blocks, unfurl_links: false });
|
|
306
|
+
await this.respond(response_url, { response_type: 'ephemeral', replace_original: false, text: `Posted the ${skill} ${version} release note to <#${ch}>.` });
|
|
307
|
+
}
|
|
308
|
+
/* ----- Things that go out on their own ----- */
|
|
309
|
+
/** Sends receipts (and decline notes) for corrections flagged from Slack, whichever surface approved them. */
|
|
310
|
+
async deliverReceipts() {
|
|
311
|
+
const st = loadState(this.ws);
|
|
312
|
+
const want = new Set(Object.keys(st.receipts).filter(t => !st.delivered[t]));
|
|
313
|
+
if (!want.size)
|
|
314
|
+
return 0;
|
|
315
|
+
let sent = 0;
|
|
316
|
+
const dir = this.ws.records('receipts');
|
|
317
|
+
const receipts = fs.existsSync(dir) ? fs.readdirSync(dir).filter(f => f.endsWith('.json')).map(f => readJson(path.join(dir, f))) : [];
|
|
318
|
+
for (const r of receipts) {
|
|
319
|
+
if (!want.has(r.receipt_token))
|
|
320
|
+
continue;
|
|
321
|
+
try {
|
|
322
|
+
await this.dm(st.receipts[r.receipt_token], M.receiptMessage(this.cfg, r));
|
|
323
|
+
st.delivered[r.receipt_token] = nowIso();
|
|
324
|
+
want.delete(r.receipt_token);
|
|
325
|
+
sent++;
|
|
326
|
+
}
|
|
327
|
+
catch (e) {
|
|
328
|
+
this.log(`Receipt for ${r.correction} not delivered yet: ${e.message}`);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
for (const c of listCorrections(this.ws, 'declined')) {
|
|
332
|
+
if (!want.has(c.receipt_token))
|
|
333
|
+
continue;
|
|
334
|
+
try {
|
|
335
|
+
await this.dm(st.receipts[c.receipt_token], M.declinedMessage(c));
|
|
336
|
+
st.delivered[c.receipt_token] = nowIso();
|
|
337
|
+
sent++;
|
|
338
|
+
}
|
|
339
|
+
catch (e) {
|
|
340
|
+
this.log(`Decline note for ${c.id} not delivered yet: ${e.message}`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
saveState(this.ws, st);
|
|
344
|
+
return sent;
|
|
345
|
+
}
|
|
346
|
+
/** Posts the digest to the digest channel, or DMs each curator. */
|
|
347
|
+
async sendDigest(prebuilt) {
|
|
348
|
+
const d = prebuilt ?? await buildDigest(this.ws, { interactive: true });
|
|
349
|
+
const ch = this.cfg.slack?.digest_channel;
|
|
350
|
+
const targets = ch ? [ch] : Object.keys(this.curators());
|
|
351
|
+
for (const t of targets)
|
|
352
|
+
await this.o.call('chat.postMessage', { channel: t, text: d.text, blocks: d.blocks, unfurl_links: false });
|
|
353
|
+
return targets.length;
|
|
354
|
+
}
|
|
355
|
+
/** Runs every minute: delivers receipts, and sends the digest when it's due. */
|
|
356
|
+
async tick(now = new Date()) {
|
|
357
|
+
try {
|
|
358
|
+
await this.deliverReceipts();
|
|
359
|
+
}
|
|
360
|
+
catch (e) {
|
|
361
|
+
this.log(`Receipts: ${e.message}`);
|
|
362
|
+
}
|
|
363
|
+
try {
|
|
364
|
+
const st = loadState(this.ws);
|
|
365
|
+
if (digestDue(now, this.cfg.slack?.digest_at, st.digest_last)) {
|
|
366
|
+
const d = await buildDigest(this.ws, { interactive: true });
|
|
367
|
+
if (d.items.length || d.blanks.some(b => b.count)) {
|
|
368
|
+
const n = await this.sendDigest(d);
|
|
369
|
+
this.log(`Monday digest sent to ${n} place${n === 1 ? '' : 's'}.`);
|
|
370
|
+
}
|
|
371
|
+
const st2 = loadState(this.ws);
|
|
372
|
+
st2.digest_last = localDate(now);
|
|
373
|
+
saveState(this.ws, st2);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
catch (e) {
|
|
377
|
+
this.log(`Digest: ${e.message}`);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/** Turns Slack message markup back into plain text for the answer field. */
|
|
382
|
+
export function slackToPlain(s) {
|
|
383
|
+
return s
|
|
384
|
+
.replace(/<([^|>]+)\|([^>]+)>/g, '$2')
|
|
385
|
+
.replace(/<([^>]+)>/g, '$1')
|
|
386
|
+
.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
|
|
387
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Slack app manifest your org registers itself (api.slack.com/apps → Create from manifest).
|
|
3
|
+
* Socket Mode, three bot scopes, no public URL. It is your app, in your workspace, not ours.
|
|
4
|
+
*/
|
|
5
|
+
export declare function slackManifest(org?: string): {
|
|
6
|
+
display_information: {
|
|
7
|
+
name: string;
|
|
8
|
+
description: string;
|
|
9
|
+
background_color: string;
|
|
10
|
+
long_description: string;
|
|
11
|
+
};
|
|
12
|
+
features: {
|
|
13
|
+
app_home: {
|
|
14
|
+
home_tab_enabled: boolean;
|
|
15
|
+
messages_tab_enabled: boolean;
|
|
16
|
+
messages_tab_read_only_enabled: boolean;
|
|
17
|
+
};
|
|
18
|
+
bot_user: {
|
|
19
|
+
display_name: string;
|
|
20
|
+
always_online: boolean;
|
|
21
|
+
};
|
|
22
|
+
shortcuts: {
|
|
23
|
+
name: string;
|
|
24
|
+
type: string;
|
|
25
|
+
callback_id: string;
|
|
26
|
+
description: string;
|
|
27
|
+
}[];
|
|
28
|
+
slash_commands: {
|
|
29
|
+
command: string;
|
|
30
|
+
description: string;
|
|
31
|
+
usage_hint: string;
|
|
32
|
+
should_escape: boolean;
|
|
33
|
+
}[];
|
|
34
|
+
};
|
|
35
|
+
oauth_config: {
|
|
36
|
+
scopes: {
|
|
37
|
+
bot: string[];
|
|
38
|
+
};
|
|
39
|
+
};
|
|
40
|
+
settings: {
|
|
41
|
+
interactivity: {
|
|
42
|
+
is_enabled: boolean;
|
|
43
|
+
};
|
|
44
|
+
org_deploy_enabled: boolean;
|
|
45
|
+
socket_mode_enabled: boolean;
|
|
46
|
+
token_rotation_enabled: boolean;
|
|
47
|
+
};
|
|
48
|
+
};
|
|
49
|
+
/** The pixel monster as a 512×512 PNG, for the app icon. Built here, so there's no image to download. */
|
|
50
|
+
export declare function monsterIcon(size?: number): Buffer;
|