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.
Files changed (88) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +155 -2
  3. package/desk-ui/app.css +73 -0
  4. package/desk-ui/app.js +182 -0
  5. package/desk-ui/fonts/bricolage-grotesque-800.woff2 +0 -0
  6. package/desk-ui/fonts/ibm-plex-mono-400.woff2 +0 -0
  7. package/desk-ui/fonts/ibm-plex-mono-600.woff2 +0 -0
  8. package/desk-ui/fonts/ibm-plex-sans-400.woff2 +0 -0
  9. package/desk-ui/fonts/silkscreen-400.woff2 +0 -0
  10. package/desk-ui/fonts.css +70 -0
  11. package/desk-ui/index.html +29 -0
  12. package/desk-ui/mascot.svg +1 -0
  13. package/dist/build.json +1 -0
  14. package/dist/cli/index.d.ts +2 -0
  15. package/dist/cli/index.js +640 -0
  16. package/dist/cli/ui.d.ts +18 -0
  17. package/dist/cli/ui.js +120 -0
  18. package/dist/core/checkup.d.ts +14 -0
  19. package/dist/core/checkup.js +69 -0
  20. package/dist/core/corrections.d.ts +54 -0
  21. package/dist/core/corrections.js +138 -0
  22. package/dist/core/digest.d.ts +36 -0
  23. package/dist/core/digest.js +91 -0
  24. package/dist/core/export.d.ts +8 -0
  25. package/dist/core/export.js +28 -0
  26. package/dist/core/external.d.ts +48 -0
  27. package/dist/core/external.js +127 -0
  28. package/dist/core/guard.d.ts +10 -0
  29. package/dist/core/guard.js +48 -0
  30. package/dist/core/mirror.d.ts +37 -0
  31. package/dist/core/mirror.js +148 -0
  32. package/dist/core/release.d.ts +69 -0
  33. package/dist/core/release.js +173 -0
  34. package/dist/core/report.d.ts +10 -0
  35. package/dist/core/report.js +65 -0
  36. package/dist/core/scrub.d.ts +20 -0
  37. package/dist/core/scrub.js +67 -0
  38. package/dist/core/sign.d.ts +25 -0
  39. package/dist/core/sign.js +86 -0
  40. package/dist/core/skill.d.ts +26 -0
  41. package/dist/core/skill.js +68 -0
  42. package/dist/core/starters.d.ts +54 -0
  43. package/dist/core/starters.js +184 -0
  44. package/dist/core/types.d.ts +187 -0
  45. package/dist/core/types.js +1 -0
  46. package/dist/core/version.d.ts +4 -0
  47. package/dist/core/version.js +17 -0
  48. package/dist/core/workspace.d.ts +23 -0
  49. package/dist/core/workspace.js +79 -0
  50. package/dist/desk/server.d.ts +10 -0
  51. package/dist/desk/server.js +140 -0
  52. package/dist/index.d.ts +11 -0
  53. package/dist/index.js +10 -0
  54. package/dist/mcp/server.d.ts +8 -0
  55. package/dist/mcp/server.js +112 -0
  56. package/dist/providers/index.d.ts +15 -0
  57. package/dist/providers/index.js +123 -0
  58. package/dist/slack/api.d.ts +6 -0
  59. package/dist/slack/api.js +18 -0
  60. package/dist/slack/app.d.ts +70 -0
  61. package/dist/slack/app.js +387 -0
  62. package/dist/slack/manifest.d.ts +50 -0
  63. package/dist/slack/manifest.js +71 -0
  64. package/dist/slack/messages.d.ts +414 -0
  65. package/dist/slack/messages.js +226 -0
  66. package/dist/slack/socket.d.ts +24 -0
  67. package/dist/slack/socket.js +84 -0
  68. package/dist/stores/airtable.d.ts +26 -0
  69. package/dist/stores/airtable.js +52 -0
  70. package/dist/stores/confluence-format.d.ts +34 -0
  71. package/dist/stores/confluence-format.js +458 -0
  72. package/dist/stores/confluence.d.ts +55 -0
  73. package/dist/stores/confluence.js +204 -0
  74. package/dist/stores/index.d.ts +30 -0
  75. package/dist/stores/index.js +53 -0
  76. package/dist/stores/notion.d.ts +43 -0
  77. package/dist/stores/notion.js +313 -0
  78. package/docs/SECURITY.md +45 -0
  79. package/docs/slack.md +78 -0
  80. package/package.json +48 -4
  81. package/starters/_core/SKILL.md +30 -0
  82. package/starters/customer-support-answers/starter.yaml +98 -0
  83. package/starters/data-warehouse-kb/starter.yaml +119 -0
  84. package/starters/engineering-house-rules/starter.yaml +106 -0
  85. package/starters/people-policies/starter.yaml +89 -0
  86. package/starters/pricing-and-packaging/starter.yaml +90 -0
  87. package/starters/product-analytics-kb/starter.yaml +109 -0
  88. package/starters/security-questionnaire-answers/starter.yaml +94 -0
@@ -0,0 +1,204 @@
1
+ import { blocks, esc, inlineToStorage, markdownToStorage, parseStorage, storageToMarkdown, unreadable } from './confluence-format.js';
2
+ /**
3
+ * Reads a Confluence Cloud site, and optionally a space and parent page, from what people paste:
4
+ * "acme.atlassian.net", "https://acme.atlassian.net/wiki", or a page or space link such as
5
+ * https://acme.atlassian.net/wiki/spaces/KB/pages/123456/Analytics+KB.
6
+ */
7
+ export function parseConfluenceLink(input) {
8
+ let s = String(input ?? '').trim();
9
+ if (!s)
10
+ throw new Error('Give the Confluence site, e.g. acme.atlassian.net, or a link to the parent page.');
11
+ if (!/^https?:\/\//i.test(s))
12
+ s = 'https://' + s;
13
+ let u;
14
+ try {
15
+ u = new URL(s);
16
+ }
17
+ catch {
18
+ throw new Error(`"${input}" is not a Confluence site or page link.`);
19
+ }
20
+ const local = u.hostname === 'localhost' || u.hostname === '127.0.0.1';
21
+ if (u.protocol !== 'https:' && !local)
22
+ throw new Error('Confluence must be reached over https, so the token is never sent in the clear.');
23
+ const space = u.pathname.match(/\/spaces\/([^/]+)/)?.[1];
24
+ const page = u.pathname.match(/\/pages\/(\d+)/)?.[1] ?? u.searchParams.get('pageId') ?? undefined;
25
+ return { site: u.origin, space: space ? decodeURIComponent(space) : undefined, page };
26
+ }
27
+ const sleep = (ms) => new Promise(res => setTimeout(res, ms));
28
+ /**
29
+ * Confluence Cloud store (REST API v2). Layout: a parent page (the one you name, or the space's
30
+ * home page) → one page per skill, titled with the skill name → one page per section, titled
31
+ * "<skill>: <section>", because Confluence page titles must be unique in a space.
32
+ * Content is kept in Confluence's storage format and converted to and from Markdown.
33
+ * Uses an Atlassian account's own API token; Skill Monster has no Atlassian app of its own.
34
+ */
35
+ export class ConfluenceStore {
36
+ ws;
37
+ cfg;
38
+ kind = 'confluence';
39
+ site;
40
+ spaceKey;
41
+ parent;
42
+ space;
43
+ constructor(ws, cfg) {
44
+ this.ws = ws;
45
+ this.cfg = cfg;
46
+ const p = parseConfluenceLink(cfg.site);
47
+ this.site = p.site;
48
+ const key = cfg.space || p.space;
49
+ if (!key)
50
+ throw new Error('Set store.space to the Confluence space key (the KB part of /wiki/spaces/KB/…).');
51
+ this.spaceKey = key;
52
+ this.parent = cfg.parent_page ? (cfg.parent_page.match(/(\d{3,})/)?.[1] ?? cfg.parent_page) : p.page;
53
+ }
54
+ describe() { return `Confluence (${new URL(this.site).host}, space ${this.spaceKey}${this.parent ? `, under page ${this.parent}` : ''})`; }
55
+ static sectionTitle(skill, id) { return `${skill}: ${id}`; }
56
+ auth() {
57
+ const tEnv = this.cfg.token_env ?? 'CONFLUENCE_TOKEN', eEnv = this.cfg.email_env ?? 'CONFLUENCE_EMAIL';
58
+ const t = process.env[tEnv];
59
+ if (!t)
60
+ throw new Error(`Set ${tEnv} to an Atlassian API token (id.atlassian.com → Security → API tokens) and ${eEnv} to that account's email. No token where Skill Monster runs? Use a folder store and mirror it with your Confluence connector: skill-monster read <skill> --dir <folder> --wiki confluence.`);
61
+ const e = process.env[eEnv];
62
+ return e ? `Basic ${Buffer.from(`${e}:${t}`).toString('base64')}` : `Bearer ${t}`;
63
+ }
64
+ async call(method, url, body) {
65
+ for (let attempt = 0;; attempt++) {
66
+ const r = await fetch(`${this.site}/wiki/api/v2${url}`, {
67
+ method,
68
+ headers: { Authorization: this.auth(), Accept: 'application/json', 'Content-Type': 'application/json' },
69
+ body: body ? JSON.stringify(body) : undefined,
70
+ });
71
+ if (r.ok)
72
+ return r.status === 204 ? {} : r.json();
73
+ if ((r.status === 429 || r.status >= 500) && attempt < 5) {
74
+ const after = Number(r.headers.get('retry-after'));
75
+ await sleep(after >= 0 && r.headers.get('retry-after') ? after * 1000 : 500 * 2 ** attempt);
76
+ continue;
77
+ }
78
+ const text = await r.text();
79
+ const err = new Error(this.explain(r.status, method, url, text));
80
+ err.status = r.status;
81
+ throw err;
82
+ }
83
+ }
84
+ explain(status, method, url, text) {
85
+ const eEnv = this.cfg.email_env ?? 'CONFLUENCE_EMAIL';
86
+ if (status === 401)
87
+ return `Confluence rejected the sign-in (401). Check the API token, and set ${eEnv} to the email of the Atlassian account that made it.`;
88
+ if (status === 403)
89
+ return `That Atlassian account can't ${method === 'GET' ? 'see' : 'edit'} this in space ${this.spaceKey} (403). Ask a space admin for view and add-page permission.`;
90
+ if (status === 404)
91
+ return `Confluence can't find that (404) in space ${this.spaceKey}. Check the space key and parent page, and that the account can see them.`;
92
+ return `Confluence ${method} ${url.split('?')[0]} failed: ${status} ${text.slice(0, 300)}`;
93
+ }
94
+ async getSpace() {
95
+ if (this.space)
96
+ return this.space;
97
+ const res = await this.call('GET', `/spaces?keys=${encodeURIComponent(this.spaceKey)}&limit=1`);
98
+ const s = res.results?.[0];
99
+ if (!s)
100
+ throw new Error(`Confluence has no space "${this.spaceKey}" that this account can see. Use the space key from the link (/wiki/spaces/<KEY>/…).`);
101
+ this.space = { id: String(s.id), homepageId: s.homepageId ? String(s.homepageId) : undefined };
102
+ if (this.parent)
103
+ await this.call('GET', `/pages/${this.parent}`);
104
+ return this.space;
105
+ }
106
+ async byTitle(title) {
107
+ const sp = await this.getSpace();
108
+ const res = await this.call('GET', `/pages?space-id=${sp.id}&title=${encodeURIComponent(title)}&status=current&body-format=storage&limit=5`);
109
+ return (res.results ?? []).find((p) => p.title === title);
110
+ }
111
+ async create(title, parentId, storage) {
112
+ const sp = await this.getSpace();
113
+ return this.call('POST', '/pages', { spaceId: sp.id, status: 'current', title, ...(parentId ? { parentId } : {}), body: { representation: 'storage', value: storage } });
114
+ }
115
+ async skillPage(skill, create) {
116
+ const found = await this.byTitle(skill.name);
117
+ if (found || !create)
118
+ return found;
119
+ const sp = await this.getSpace();
120
+ return this.create(skill.name, this.parent ?? sp.homepageId, `<p>${esc(skill.title ?? skill.name)}. Kept by Skill Monster: one child page per section.</p>`);
121
+ }
122
+ async sectionPage(skill, id, create) {
123
+ const title = ConfluenceStore.sectionTitle(skill.name, id);
124
+ const found = await this.byTitle(title);
125
+ if (found || !create)
126
+ return found;
127
+ const parent = await this.skillPage(skill, true);
128
+ return this.create(title, parent.id, '');
129
+ }
130
+ /** Replaces a page's body, bumping its version. If someone saved in between, re-reads once and retries. */
131
+ async update(page, change, message) {
132
+ for (let attempt = 0;; attempt++) {
133
+ const cur = attempt === 0 && page.body?.storage ? page : await this.call('GET', `/pages/${page.id}?body-format=storage`);
134
+ const value = change(cur.body?.storage?.value ?? '');
135
+ try {
136
+ await this.call('PUT', `/pages/${page.id}`, { id: page.id, status: 'current', title: cur.title, body: { representation: 'storage', value }, version: { number: cur.version.number + 1, message } });
137
+ return;
138
+ }
139
+ catch (e) {
140
+ if (e.status === 409 && attempt < 2)
141
+ continue;
142
+ throw e;
143
+ }
144
+ }
145
+ }
146
+ async readSections(skill) {
147
+ const out = {};
148
+ for (const id of skill.sections) {
149
+ const pg = await this.byTitle(ConfluenceStore.sectionTitle(skill.name, id));
150
+ out[id] = pg ? storageToMarkdown(pg.body?.storage?.value ?? '') : '';
151
+ }
152
+ return out;
153
+ }
154
+ async writeSection(skill, id, md) {
155
+ const pg = await this.sectionPage(skill, id, true);
156
+ await this.update(pg, () => markdownToStorage(md), 'Skill Monster: section replaced');
157
+ }
158
+ async applyChange(skill, id, oldText, newText) {
159
+ const pg = await this.sectionPage(skill, id, true);
160
+ await this.update(pg, storage => replaceInStorage(storage, oldText, newText), oldText ? 'Skill Monster: approved fix' : 'Skill Monster: rule added');
161
+ }
162
+ }
163
+ /**
164
+ * Applies one approved fix to a page's storage format, touching as little as it can: the text
165
+ * itself when it sits inside one run of text, otherwise only the one block (paragraph, list,
166
+ * table) that holds it. Panels, macros and layouts around it are kept. Appends when oldText is empty.
167
+ */
168
+ export function replaceInStorage(storage, oldText, newText) {
169
+ if (!oldText)
170
+ return storage + markdownToStorage(newText);
171
+ if (!newText.includes('\n')) {
172
+ for (const enc of [esc(oldText), esc(oldText).replace(/&quot;/g, '"')]) {
173
+ const at = storage.indexOf(enc);
174
+ const inTag = /<[^>]*$/.test(storage.slice(0, at)), inCdata = storage.lastIndexOf('<![CDATA[', at) > storage.lastIndexOf(']]>', at);
175
+ if (at >= 0 && !inTag && !inCdata && !/[`*_[\]]/.test(oldText))
176
+ return storage.slice(0, at) + inlineToStorage(newText) + storage.slice(at + enc.length);
177
+ }
178
+ }
179
+ const CONTAINERS = new Set(['div', 'section', 'ac:layout', 'ac:layout-section', 'ac:layout-cell', 'ac:rich-text-body', 'blockquote']);
180
+ const pick = (nodes) => {
181
+ for (const n of nodes) {
182
+ if (n.tag === '#text')
183
+ continue;
184
+ if (!blocks([n]).includes(oldText))
185
+ continue;
186
+ const el = n;
187
+ const isContainer = CONTAINERS.has(el.tag) || (el.tag === 'ac:structured-macro' && el.children.some(c => c.tag === 'ac:rich-text-body'));
188
+ if (isContainer) {
189
+ const inner = el.tag === 'ac:structured-macro' ? el.children.filter(c => c.tag === 'ac:rich-text-body') : el.children;
190
+ return pick(inner.flatMap(c => (c.tag === 'ac:rich-text-body' ? c.children : [c]))) ?? el;
191
+ }
192
+ return el;
193
+ }
194
+ return undefined;
195
+ };
196
+ const target = pick(parseStorage(storage));
197
+ if (!target)
198
+ throw new Error('Could not find the old rule text in the Confluence section. Nothing was changed.');
199
+ const blockers = unreadable([target]);
200
+ if (blockers.length)
201
+ throw new Error(`The old rule text sits in a part of the Confluence page Skill Monster can't rewrite safely (${blockers.join(', ')}). Make this fix in Confluence by hand. Nothing was changed.`);
202
+ const md = blocks([target]);
203
+ return storage.slice(0, target.start) + markdownToStorage(md.replace(oldText, () => newText)) + storage.slice(target.end);
204
+ }
@@ -0,0 +1,30 @@
1
+ import type { SkillMeta, StoreConfig } from '../core/types.js';
2
+ import type { Workspace } from '../core/workspace.js';
3
+ /**
4
+ * A knowledge store is where people read and edit the skill's content.
5
+ * Skill Monster's own records (versions, corrections, tests, signatures) always
6
+ * live as files in the workspace, whatever the store is.
7
+ */
8
+ export interface KnowledgeStore {
9
+ kind: string;
10
+ /** Read every section's markdown, keyed by section id. */
11
+ readSections(skill: SkillMeta): Promise<Record<string, string>>;
12
+ /** Write a section (used by starters and approved fixes). */
13
+ writeSection(skill: SkillMeta, id: string, markdown: string): Promise<void>;
14
+ /** Replace oldText with newText inside a section, or append newText when oldText is empty. */
15
+ applyChange(skill: SkillMeta, id: string, oldText: string, newText: string): Promise<void>;
16
+ describe(): string;
17
+ }
18
+ export declare class FileStore implements KnowledgeStore {
19
+ private ws;
20
+ private base?;
21
+ kind: string;
22
+ constructor(ws: Workspace, base?: string | undefined);
23
+ private dir;
24
+ readSections(skill: SkillMeta): Promise<Record<string, string>>;
25
+ writeSection(skill: SkillMeta, id: string, md: string): Promise<void>;
26
+ applyChange(skill: SkillMeta, id: string, oldText: string, newText: string): Promise<void>;
27
+ describe(): string;
28
+ }
29
+ export declare function replaceOrAppend(cur: string, oldText: string, newText: string): string;
30
+ export declare function openStore(ws: Workspace, cfg?: StoreConfig): KnowledgeStore;
@@ -0,0 +1,53 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { NotionStore } from './notion.js';
4
+ import { AirtableStore } from './airtable.js';
5
+ import { ConfluenceStore } from './confluence.js';
6
+ export class FileStore {
7
+ ws;
8
+ base;
9
+ kind = 'git';
10
+ constructor(ws, base) {
11
+ this.ws = ws;
12
+ this.base = base;
13
+ if (base)
14
+ this.kind = 'folder';
15
+ }
16
+ dir(skill) {
17
+ return this.base ? path.resolve(this.ws.root, this.base, skill.name) : path.join(this.ws.skillDir(skill.name), 'sections');
18
+ }
19
+ async readSections(skill) {
20
+ const out = {};
21
+ for (const id of skill.sections) {
22
+ const f = path.join(this.dir(skill), `${id}.md`);
23
+ out[id] = fs.existsSync(f) ? fs.readFileSync(f, 'utf8') : '';
24
+ }
25
+ return out;
26
+ }
27
+ async writeSection(skill, id, md) {
28
+ fs.mkdirSync(this.dir(skill), { recursive: true });
29
+ fs.writeFileSync(path.join(this.dir(skill), `${id}.md`), md);
30
+ }
31
+ async applyChange(skill, id, oldText, newText) {
32
+ const cur = (await this.readSections(skill))[id] ?? '';
33
+ await this.writeSection(skill, id, replaceOrAppend(cur, oldText, newText));
34
+ }
35
+ describe() { return this.base ? `folder ${this.base}` : 'Git repo (files in skills/<name>/sections)'; }
36
+ }
37
+ export function replaceOrAppend(cur, oldText, newText) {
38
+ if (oldText && cur.includes(oldText))
39
+ return cur.replace(oldText, () => newText);
40
+ if (oldText)
41
+ throw new Error(`Could not find the old rule text in the section. Nothing was changed.`);
42
+ return cur.replace(/\s*$/, '') + `\n\n${newText}\n`;
43
+ }
44
+ export function openStore(ws, cfg = ws.config.store) {
45
+ switch (cfg.type) {
46
+ case 'git': return new FileStore(ws);
47
+ case 'folder': return new FileStore(ws, cfg.path);
48
+ case 'notion': return new NotionStore(ws, cfg);
49
+ case 'airtable': return new AirtableStore(ws, cfg);
50
+ case 'confluence': return new ConfluenceStore(ws, cfg);
51
+ default: throw new Error(`Unknown store type: ${cfg.type}`);
52
+ }
53
+ }
@@ -0,0 +1,43 @@
1
+ import type { SkillMeta, StoreConfig } from '../core/types.js';
2
+ import type { Workspace } from '../core/workspace.js';
3
+ import type { KnowledgeStore } from './index.js';
4
+ type NotionCfg = Extract<StoreConfig, {
5
+ type: 'notion';
6
+ }>;
7
+ /**
8
+ * Accepts a page id with or without dashes, or a full Notion page link
9
+ * (https://www.notion.so/Team/Metrics-KB-1a2b3c…?pvs=4), and returns the page id.
10
+ */
11
+ export declare function parseNotionPageId(input: string): string;
12
+ /**
13
+ * Notion store. Layout: root page → one child page per skill (titled with the skill name)
14
+ * → one child page per section (titled with the section id). Uses the team's own
15
+ * Notion integration token; Skill Monster has no Notion app of its own.
16
+ */
17
+ export declare class NotionStore implements KnowledgeStore {
18
+ private ws;
19
+ private cfg;
20
+ kind: string;
21
+ private root;
22
+ private rootChecked;
23
+ constructor(ws: Workspace, cfg: NotionCfg);
24
+ describe(): string;
25
+ private token;
26
+ private call;
27
+ private checkRoot;
28
+ private children;
29
+ /** Children with their own nested children loaded (toggles, nested lists, tables, columns). */
30
+ private tree;
31
+ private childPages;
32
+ private skillPage;
33
+ private sectionPage;
34
+ readSections(skill: SkillMeta): Promise<Record<string, string>>;
35
+ private append;
36
+ writeSection(skill: SkillMeta, id: string, md: string): Promise<void>;
37
+ applyChange(skill: SkillMeta, id: string, oldText: string, newText: string): Promise<void>;
38
+ }
39
+ /** Splits text into Notion rich text items of at most 1,900 characters each. */
40
+ export declare function richText(s: string): any[];
41
+ export declare function blocksToMarkdown(blocks: any[], indent?: string): string;
42
+ export declare function markdownToBlocks(md: string): any[];
43
+ export {};
@@ -0,0 +1,313 @@
1
+ const apiBase = () => (process.env.SKILL_MONSTER_NOTION_API ?? 'https://api.notion.com/v1').replace(/\/$/, '');
2
+ /** Notion caps one rich text item at 2,000 characters and one block at 100 items. */
3
+ const TEXT_CHUNK = 1900;
4
+ const MAX_ITEMS = 100;
5
+ /**
6
+ * Accepts a page id with or without dashes, or a full Notion page link
7
+ * (https://www.notion.so/Team/Metrics-KB-1a2b3c…?pvs=4), and returns the page id.
8
+ */
9
+ export function parseNotionPageId(input) {
10
+ const s = String(input ?? '').trim();
11
+ const clean = s.split(/[?#]/)[0];
12
+ const m = clean.replace(/-/g, '').match(/([0-9a-f]{32})$/i) ?? s.replace(/-/g, '').match(/([0-9a-f]{32})/i);
13
+ if (!m)
14
+ throw new Error(`"${s}" is not a Notion page id or page link. Copy the link of the root page from Notion (Share → Copy link).`);
15
+ const h = m[1].toLowerCase();
16
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
17
+ }
18
+ /**
19
+ * Notion store. Layout: root page → one child page per skill (titled with the skill name)
20
+ * → one child page per section (titled with the section id). Uses the team's own
21
+ * Notion integration token; Skill Monster has no Notion app of its own.
22
+ */
23
+ export class NotionStore {
24
+ ws;
25
+ cfg;
26
+ kind = 'notion';
27
+ root;
28
+ rootChecked = false;
29
+ constructor(ws, cfg) {
30
+ this.ws = ws;
31
+ this.cfg = cfg;
32
+ this.root = parseNotionPageId(cfg.root_page);
33
+ }
34
+ describe() { return `Notion (root page ${this.root})`; }
35
+ token() {
36
+ const env = this.cfg.token_env ?? 'NOTION_TOKEN';
37
+ const t = process.env[env];
38
+ if (!t)
39
+ throw new Error(`Set ${env} to your company's Notion integration token to read the knowledge store.`);
40
+ return t;
41
+ }
42
+ async call(method, url, body) {
43
+ for (let attempt = 0;; attempt++) {
44
+ const r = await fetch(apiBase() + url, {
45
+ method,
46
+ headers: { Authorization: `Bearer ${this.token()}`, 'Notion-Version': '2022-06-28', 'Content-Type': 'application/json' },
47
+ body: body ? JSON.stringify(body) : undefined,
48
+ });
49
+ if (r.ok)
50
+ return r.json();
51
+ if ((r.status === 429 || r.status >= 500) && attempt < 5) {
52
+ const after = Number(r.headers.get('retry-after'));
53
+ await sleep(after > 0 ? after * 1000 : 500 * 2 ** attempt);
54
+ continue;
55
+ }
56
+ const text = await r.text();
57
+ if (r.status === 401)
58
+ throw new Error('Notion rejected the token (401). Check NOTION_TOKEN is the internal integration secret.');
59
+ if (r.status === 404 || (r.status === 400 && /object_not_found|Could not find/.test(text))) {
60
+ throw new Error(`Notion can't see that page (${r.status}). Share the root page with your integration: open it in Notion, ••• → Connections → add the integration. Root page: ${this.root}`);
61
+ }
62
+ throw new Error(`Notion ${method} ${url} failed: ${r.status} ${text.slice(0, 300)}`);
63
+ }
64
+ }
65
+ async checkRoot() {
66
+ if (this.rootChecked)
67
+ return;
68
+ await this.call('GET', `/pages/${this.root}`);
69
+ this.rootChecked = true;
70
+ }
71
+ async children(blockId) {
72
+ const out = [];
73
+ let cursor;
74
+ do {
75
+ const q = cursor ? `?start_cursor=${encodeURIComponent(cursor)}&page_size=100` : '?page_size=100';
76
+ const res = await this.call('GET', `/blocks/${blockId}/children${q}`);
77
+ out.push(...res.results);
78
+ cursor = res.has_more ? res.next_cursor : undefined;
79
+ } while (cursor);
80
+ return out;
81
+ }
82
+ /** Children with their own nested children loaded (toggles, nested lists, tables, columns). */
83
+ async tree(blockId, depth = 0) {
84
+ const blocks = await this.children(blockId);
85
+ for (const b of blocks) {
86
+ if (b.has_children && b.type !== 'child_page' && b.type !== 'child_database' && depth < 6)
87
+ b._children = await this.tree(b.id, depth + 1);
88
+ }
89
+ return blocks;
90
+ }
91
+ async childPages(id) {
92
+ return (await this.children(id)).filter(b => b.type === 'child_page').map(b => ({ id: b.id, title: b.child_page.title }));
93
+ }
94
+ async skillPage(skill, create = false) {
95
+ await this.checkRoot();
96
+ const found = (await this.childPages(this.root)).find(p => p.title === skill.name);
97
+ if (found || !create)
98
+ return found;
99
+ const res = await this.call('POST', '/pages', { parent: { page_id: this.root }, properties: { title: { title: [{ text: { content: skill.name } }] } } });
100
+ return { id: res.id, title: skill.name };
101
+ }
102
+ async sectionPage(skill, id, create = false) {
103
+ const sp = await this.skillPage(skill, create);
104
+ if (!sp)
105
+ return undefined;
106
+ const found = (await this.childPages(sp.id)).find(p => p.title === id);
107
+ if (found || !create)
108
+ return found;
109
+ const res = await this.call('POST', '/pages', { parent: { page_id: sp.id }, properties: { title: { title: [{ text: { content: id } }] } } });
110
+ return { id: res.id, title: id };
111
+ }
112
+ async readSections(skill) {
113
+ const out = {};
114
+ const sp = await this.skillPage(skill);
115
+ const pages = sp ? await this.childPages(sp.id) : [];
116
+ for (const id of skill.sections) {
117
+ const pg = pages.find(p => p.title === id);
118
+ out[id] = pg ? blocksToMarkdown(await this.tree(pg.id)) : '';
119
+ }
120
+ return out;
121
+ }
122
+ async append(pageId, blocks) {
123
+ for (let i = 0; i < blocks.length; i += 90)
124
+ await this.call('PATCH', `/blocks/${pageId}/children`, { children: blocks.slice(i, i + 90) });
125
+ }
126
+ async writeSection(skill, id, md) {
127
+ const pg = await this.sectionPage(skill, id, true);
128
+ for (const b of await this.children(pg.id))
129
+ await this.call('DELETE', `/blocks/${b.id}`);
130
+ await this.append(pg.id, markdownToBlocks(md));
131
+ }
132
+ async applyChange(skill, id, oldText, newText) {
133
+ const pg = await this.sectionPage(skill, id, true);
134
+ if (oldText) {
135
+ const walk = async (blocks) => {
136
+ for (const b of blocks) {
137
+ const rt = b[b.type]?.rich_text;
138
+ if (Array.isArray(rt)) {
139
+ const plain = rt.map((t) => t.plain_text).join('');
140
+ if (plain.includes(oldText)) {
141
+ await this.call('PATCH', `/blocks/${b.id}`, { [b.type]: { rich_text: richText(plain.replace(oldText, newText)) } });
142
+ return true;
143
+ }
144
+ }
145
+ if (b._children && (await walk(b._children)))
146
+ return true;
147
+ }
148
+ return false;
149
+ };
150
+ if (await walk(await this.tree(pg.id)))
151
+ return;
152
+ throw new Error('Could not find the old rule text in the Notion section (it must sit inside one block). Nothing was changed.');
153
+ }
154
+ await this.append(pg.id, markdownToBlocks(newText));
155
+ }
156
+ }
157
+ const sleep = (ms) => new Promise(res => setTimeout(res, ms));
158
+ /** Splits text into Notion rich text items of at most 1,900 characters each. */
159
+ export function richText(s) {
160
+ const out = [];
161
+ for (let i = 0; i < s.length && out.length < MAX_ITEMS; i += TEXT_CHUNK)
162
+ out.push({ type: 'text', text: { content: s.slice(i, i + TEXT_CHUNK) } });
163
+ return out.length ? out : [{ type: 'text', text: { content: '' } }];
164
+ }
165
+ const txt = (rt = []) => rt.map(t => {
166
+ let s = (t.plain_text ?? t.text?.content ?? '');
167
+ if (!s.trim())
168
+ return s;
169
+ if (t.annotations?.code)
170
+ s = '`' + s + '`';
171
+ if (t.annotations?.bold)
172
+ s = `**${s}**`;
173
+ if (t.annotations?.italic)
174
+ s = `_${s}_`;
175
+ const href = t.href ?? t.text?.link?.url;
176
+ if (href)
177
+ s = `[${s}](${href})`;
178
+ return s;
179
+ }).join('');
180
+ const cell = (rt) => txt(rt).replace(/\|/g, '\\|').replace(/\n/g, ' ');
181
+ export function blocksToMarkdown(blocks, indent = '') {
182
+ const lines = [];
183
+ const kids = (b, extra = ' ') => { if (b._children?.length)
184
+ lines.push(blocksToMarkdown(b._children, indent + extra).replace(/\n$/, '')); };
185
+ for (const b of blocks) {
186
+ const v = b[b.type] ?? {};
187
+ switch (b.type) {
188
+ case 'heading_1':
189
+ case 'heading_2':
190
+ case 'heading_3': {
191
+ const n = Number(b.type.slice(-1));
192
+ lines.push(`${indent}${'#'.repeat(n)} ${txt(v.rich_text)}`);
193
+ kids(b, '');
194
+ break;
195
+ }
196
+ case 'bulleted_list_item':
197
+ lines.push(`${indent}- ${txt(v.rich_text)}`);
198
+ kids(b);
199
+ break;
200
+ case 'numbered_list_item':
201
+ lines.push(`${indent}1. ${txt(v.rich_text)}`);
202
+ kids(b, ' ');
203
+ break;
204
+ case 'to_do':
205
+ lines.push(`${indent}- [${v.checked ? 'x' : ' '}] ${txt(v.rich_text)}`);
206
+ kids(b);
207
+ break;
208
+ case 'toggle':
209
+ lines.push(`${indent}- ${txt(v.rich_text)}`);
210
+ kids(b);
211
+ break;
212
+ case 'quote':
213
+ case 'callout':
214
+ lines.push(`${indent}> ${txt(v.rich_text)}`);
215
+ kids(b, '');
216
+ break;
217
+ case 'code':
218
+ lines.push(`${indent}\`\`\`${v.language && v.language !== 'plain text' ? v.language : ''}`, ...(v.rich_text ?? []).map((t) => t.plain_text ?? t.text?.content ?? '').join('').split('\n').map((l) => indent + l), `${indent}\`\`\``);
219
+ break;
220
+ case 'divider':
221
+ lines.push(`${indent}---`);
222
+ break;
223
+ case 'paragraph':
224
+ lines.push(`${indent}${txt(v.rich_text)}`);
225
+ kids(b);
226
+ break;
227
+ case 'table': {
228
+ const rows = (b._children ?? []).filter((r) => r.type === 'table_row').map((r) => (r.table_row.cells ?? []).map(cell));
229
+ if (!rows.length)
230
+ break;
231
+ const w = Math.max(...rows.map((r) => r.length));
232
+ const fmt = (r) => `${indent}| ${Array.from({ length: w }, (_, i) => r[i] ?? '').join(' | ')} |`;
233
+ lines.push('', fmt(rows[0]), `${indent}|${' --- |'.repeat(w)}`, ...rows.slice(1).map(fmt), '');
234
+ break;
235
+ }
236
+ case 'column_list':
237
+ case 'column':
238
+ case 'synced_block':
239
+ kids(b, '');
240
+ break;
241
+ case 'child_database':
242
+ lines.push(`${indent}> (Notion database "${v.title ?? ''}" is not read. Paste its rows as a table instead.)`);
243
+ break;
244
+ case 'bookmark':
245
+ case 'embed':
246
+ case 'link_preview':
247
+ if (v.url)
248
+ lines.push(`${indent}${v.url}`);
249
+ break;
250
+ default:
251
+ kids(b, '');
252
+ break;
253
+ }
254
+ }
255
+ return lines.join('\n').replace(/\n{3,}/g, '\n\n').replace(/^\n+/, '').replace(/\s+$/, '') + '\n';
256
+ }
257
+ export function markdownToBlocks(md) {
258
+ const out = [];
259
+ const lines = md.split('\n');
260
+ for (let i = 0; i < lines.length; i++) {
261
+ const l = lines[i];
262
+ if (!l.trim())
263
+ continue;
264
+ if (l.trim().startsWith('```')) {
265
+ const lang = l.trim().slice(3).trim();
266
+ const code = [];
267
+ i++;
268
+ while (i < lines.length && !lines[i].trim().startsWith('```'))
269
+ code.push(lines[i++]);
270
+ out.push({ type: 'code', code: { rich_text: richText(code.join('\n')), language: NOTION_LANGS.has(lang.toLowerCase()) ? lang.toLowerCase() : 'plain text' } });
271
+ continue;
272
+ }
273
+ if (/^\s*\|.*\|\s*$/.test(l)) {
274
+ const rows = [];
275
+ while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) {
276
+ const r = lines[i].trim().replace(/^\||\|$/g, '').split(/(?<!\\)\|/).map(c => c.trim().replace(/\\\|/g, '|'));
277
+ if (!r.every(c => /^:?-{2,}:?$/.test(c)))
278
+ rows.push(r);
279
+ i++;
280
+ }
281
+ i--;
282
+ const w = Math.max(...rows.map(r => r.length));
283
+ out.push({
284
+ type: 'table',
285
+ table: {
286
+ table_width: w, has_column_header: true, has_row_header: false,
287
+ children: rows.slice(0, 100).map(r => ({ type: 'table_row', table_row: { cells: Array.from({ length: w }, (_, k) => richText(r[k] ?? '')) } })),
288
+ },
289
+ });
290
+ continue;
291
+ }
292
+ let m;
293
+ const t = l.replace(/^\s+/, '');
294
+ if ((m = t.match(/^(#{1,3}) (.*)/))) {
295
+ const h = `heading_${m[1].length}`;
296
+ out.push({ type: h, [h]: { rich_text: richText(m[2]) } });
297
+ }
298
+ else if ((m = t.match(/^[-*] \[( |x)\] (.*)/i)))
299
+ out.push({ type: 'to_do', to_do: { rich_text: richText(m[2]), checked: m[1].toLowerCase() === 'x' } });
300
+ else if ((m = t.match(/^[-*] (.*)/)))
301
+ out.push({ type: 'bulleted_list_item', bulleted_list_item: { rich_text: richText(m[1]) } });
302
+ else if ((m = t.match(/^\d+\. (.*)/)))
303
+ out.push({ type: 'numbered_list_item', numbered_list_item: { rich_text: richText(m[1]) } });
304
+ else if ((m = t.match(/^> ?(.*)/)))
305
+ out.push({ type: 'quote', quote: { rich_text: richText(m[1]) } });
306
+ else if (t.trim() === '---')
307
+ out.push({ type: 'divider', divider: {} });
308
+ else
309
+ out.push({ type: 'paragraph', paragraph: { rich_text: richText(l.trim()) } });
310
+ }
311
+ return out;
312
+ }
313
+ const NOTION_LANGS = new Set(['sql', 'python', 'javascript', 'typescript', 'json', 'yaml', 'bash', 'shell', 'markdown', 'r', 'scala', 'java', 'go', 'ruby', 'html', 'css']);