Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Add a wiki: linked pages the agents read and a curator keeps (#94)

Eduardo Machado75609ee643eb
diff --git a/package-lock.json b/package-lock.json
index 0548b4a..19f4f9c 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -16,6 +16,7 @@
"smol-toml": "^1.9.1"
},
"devDependencies": {
+ "@mozilla/readability": "^0.6.0",
"@types/node": "^26.6.5",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
@@ -23,6 +24,10 @@
"electron": "^44.8.0",
"electron-builder": "^26.15.3",
"electron-vite": "^6.0.0",
+ "exceljs": "^4.4.0",
+ "jszip": "^3.10.2",
+ "linkedom": "^0.18.15",
+ "mammoth": "^1.13.0",
"open-bot-avatar": "0.1.1",
"playwright": "^1.64.1",
"react": "^19.3.1",
@@ -30,6 +35,7 @@
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"typescript": "^7.0.2",
+ "unpdf": "^2.1.0",
"vite": "^8.3.4",
"vitest": "^4.1.12"
}
@@ -624,6 +630,51 @@
"node": ">=14.14"
}
},
+ "node_modules/@fast-csv/format": {
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/@fast-csv/format/-/format-4.3.5.tgz",
+ "integrity": "sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "^14.0.1",
+ "lodash.escaperegexp": "^4.1.2",
+ "lodash.isboolean": "^3.0.3",
+ "lodash.isequal": "^4.5.0",
+ "lodash.isfunction": "^3.0.9",
+ "lodash.isnil": "^4.0.0"
+ }
+ },
+ "node_modules/@fast-csv/format/node_modules/@types/node": {
+ "version": "14.18.63",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz",
+ "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@fast-csv/parse": {
+ "version": "4.3.6",
+ "resolved": "https://registry.npmjs.org/@fast-csv/parse/-/parse-4.3.6.tgz",
+ "integrity": "sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "^14.0.1",
+ "lodash.escaperegexp": "^4.1.2",
+ "lodash.groupby": "^4.6.0",
+ "lodash.isfunction": "^3.0.9",
+ "lodash.isnil": "^4.0.0",
+ "lodash.isundefined": "^3.0.1",
+ "lodash.uniq": "^4.5.0"
+ }
+ },
+ "node_modules/@fast-csv/parse/node_modules/@types/node": {
+ "version": "14.18.63",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-14.18.63.tgz",
+ "integrity": "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@fontsource-variable/inter": {
"version": "5.3.0",
"resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
@@ -803,6 +854,16 @@
}
}
},
+ "node_modules/@mozilla/readability": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/@mozilla/readability/-/readability-0.6.0.tgz",
+ "integrity": "sha512-juG5VWh4qAivzTAeMzvY9xs9HY5rAcr2E4I7tiSSCokRFi7XIZCAu92ZkSTsIj1OPceCifL3cpfteP3pDT9/QQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
"node_modules/@noble/hashes": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz",
@@ -2136,12 +2197,107 @@
"node": "^18.17.0 || >=20.5.0"
}
},
+ "node_modules/archiver": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/archiver/-/archiver-5.3.2.tgz",
+ "integrity": "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "archiver-utils": "^2.1.0",
+ "async": "^3.2.4",
+ "buffer-crc32": "^0.2.1",
+ "readable-stream": "^3.6.0",
+ "readdir-glob": "^1.1.2",
+ "tar-stream": "^2.2.0",
+ "zip-stream": "^4.1.0"
+ },
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/archiver-utils": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-2.1.0.tgz",
+ "integrity": "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "glob": "^7.1.4",
+ "graceful-fs": "^4.2.0",
+ "lazystream": "^1.0.0",
+ "lodash.defaults": "^4.2.0",
+ "lodash.difference": "^4.5.0",
+ "lodash.flatten": "^4.4.0",
+ "lodash.isplainobject": "^4.0.6",
+ "lodash.union": "^4.6.0",
+ "normalize-path": "^3.0.0",
+ "readable-stream": "^2.0.0"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/archiver/node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/argparse": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
"license": "Python-2.0"
},
+ "node_modules/array-buffer-byte-length": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz",
+ "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "is-array-buffer": "^3.0.5"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/arraybuffer.prototype.slice": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz",
+ "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "array-buffer-byte-length": "^1.0.1",
+ "call-bind": "^1.0.8",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.5",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
+ "is-array-buffer": "^3.0.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/asn1js": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.1.0.tgz",
@@ -2184,6 +2340,16 @@
"node": ">=0.12.0"
}
},
+ "node_modules/async-function": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz",
+ "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
@@ -2201,6 +2367,22 @@
"node": ">= 4.0.0"
}
},
+ "node_modules/available-typed-arrays": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",
+ "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "possible-typed-array-names": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/aws4": {
"version": "1.13.2",
"resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz",
@@ -2263,6 +2445,57 @@
"node": ">=6.0.0"
}
},
+ "node_modules/big-integer": {
+ "version": "1.6.52",
+ "resolved": "https://registry.npmjs.org/big-integer/-/big-integer-1.6.52.tgz",
+ "integrity": "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==",
+ "dev": true,
+ "license": "Unlicense",
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
+ "node_modules/binary": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/binary/-/binary-0.3.0.tgz",
+ "integrity": "sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "buffers": "~0.1.1",
+ "chainsaw": "~0.1.0"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/bl": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
+ "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "buffer": "^5.5.0",
+ "inherits": "^2.0.4",
+ "readable-stream": "^3.4.0"
+ }
+ },
+ "node_modules/bl/node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/bluebird": {
"version": "3.7.2",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
@@ -2307,6 +2540,20 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/boolbase": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-2.0.0.tgz",
+ "integrity": "sha512-DkVaaQHymRhpYEYo9x1oo7Q7B0Y6KJUsjm3c9eTyFDby4MHLBTwZ6ZDWBel5zrYxj1WsZgC5oLpiz+93MluXeA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
"node_modules/boolean": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz",
@@ -2363,6 +2610,41 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
+ "node_modules/buffer": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.1.13"
+ }
+ },
+ "node_modules/buffer-crc32": {
+ "version": "0.2.13",
+ "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
+ "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
@@ -2370,6 +2652,25 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/buffer-indexof-polyfill": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.2.tgz",
+ "integrity": "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10"
+ }
+ },
+ "node_modules/buffers": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/buffers/-/buffers-0.1.1.tgz",
+ "integrity": "sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ==",
+ "dev": true,
+ "engines": {
+ "node": ">=0.2.0"
+ }
+ },
"node_modules/builder-util": {
"version": "26.15.3",
"resolved": "https://registry.npmjs.org/builder-util/-/builder-util-26.15.3.tgz",
@@ -2467,6 +2768,25 @@
"node": ">=8"
}
},
+ "node_modules/call-bind": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.9.tgz",
+ "integrity": "sha512-a/hy+pNsFUTR+Iz8TCJvXudKVLAnz/DyeSUo10I5yvFDQJBFU2s9uqQpoSrJlroHUKoKqzg+epxyP9lqFdzfBQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "get-intrinsic": "^1.3.0",
+ "set-function-length": "^1.2.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
@@ -2538,6 +2858,19 @@
"node": ">=18"
}
},
+ "node_modules/chainsaw": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/chainsaw/-/chainsaw-0.1.0.tgz",
+ "integrity": "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ==",
+ "dev": true,
+ "license": "MIT/X11",
+ "dependencies": {
+ "traverse": ">=0.3.0 <0.4"
+ },
+ "engines": {
+ "node": "*"
+ }
+ },
"node_modules/chalk": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz",
@@ -2724,6 +3057,37 @@
"node": ">=0.10.0"
}
},
+ "node_modules/compress-commons": {
+ "version": "4.1.2",
+ "resolved": "https://registry.npmjs.org/compress-commons/-/compress-commons-4.1.2.tgz",
+ "integrity": "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "buffer-crc32": "^0.2.13",
+ "crc32-stream": "^4.0.2",
+ "normalize-path": "^3.0.0",
+ "readable-stream": "^3.6.0"
+ },
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/compress-commons/node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/concat-map": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
@@ -2802,6 +3166,48 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/crc-32": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/crc-32/-/crc-32-1.2.2.tgz",
+ "integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "crc32": "bin/crc32.njs"
+ },
+ "engines": {
+ "node": ">=0.8"
+ }
+ },
+ "node_modules/crc32-stream": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/crc32-stream/-/crc32-stream-4.0.3.tgz",
+ "integrity": "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "crc-32": "^1.2.0",
+ "readable-stream": "^3.4.0"
+ },
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/crc32-stream/node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/cross-dirname": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/cross-dirname/-/cross-dirname-0.1.0.tgz",
@@ -2825,34 +3231,140 @@
"node": ">= 8"
}
},
- "node_modules/csstype": {
- "version": "3.2.3",
- "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
- "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "node_modules/css-select": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/css-select/-/css-select-7.0.0.tgz",
+ "integrity": "sha512-snmjEVXy+1LnwXdxhYvTMj1d9tOh4HxkA1YmoayVBeeyR2C14Pum7fcxJIm4SswYspVy866eYNwlH6xC3/VH5g==",
"dev": true,
- "license": "MIT"
- },
- "node_modules/debug": {
- "version": "4.4.3",
- "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
- "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
- "license": "MIT",
+ "license": "BSD-2-Clause",
"dependencies": {
- "ms": "^2.1.3"
+ "boolbase": "^2.0.0",
+ "css-what": "^8.0.0",
+ "domhandler": "^6.0.1",
+ "domutils": "^4.0.2",
+ "nth-check": "^3.0.1"
},
"engines": {
- "node": ">=6.0"
+ "node": ">=20.19.0"
},
- "peerDependenciesMeta": {
- "supports-color": {
- "optional": true
- }
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
}
},
- "node_modules/decode-named-character-reference": {
- "version": "1.3.0",
- "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",
- "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==",
+ "node_modules/css-what": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/css-what/-/css-what-8.0.0.tgz",
+ "integrity": "sha512-DH0Bqq3DNp5tdOReuNyAA+Ev4Y2GS5FMbZpeTLP6C4CDi0h5nL0BmUPChXw3o/qbHLDWHl49sbNqQVY7bMSDdw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ },
+ "node_modules/cssomnom": {
+ "version": "0.1.11",
+ "resolved": "https://registry.npmjs.org/cssomnom/-/cssomnom-0.1.11.tgz",
+ "integrity": "sha512-P4RkO1Sq2Ual77xypEmAc4MkM5k2Ha4UwtBPCOpJmXculGCYPgzsU/xnOCy084esZaPePgGkkJg4Il/HE7GS5A==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/data-view-buffer": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",
+ "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "es-errors": "^1.3.0",
+ "is-data-view": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/data-view-byte-length": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz",
+ "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "es-errors": "^1.3.0",
+ "is-data-view": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/inspect-js"
+ }
+ },
+ "node_modules/data-view-byte-offset": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz",
+ "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "is-data-view": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/dayjs": {
+ "version": "1.11.23",
+ "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
+ "integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/decode-named-character-reference": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz",
+ "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2908,7 +3420,6 @@
"integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==",
"dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"es-define-property": "^1.0.0",
"es-errors": "^1.3.0",
@@ -2927,7 +3438,6 @@
"integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==",
"dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"define-data-property": "^1.0.1",
"has-property-descriptors": "^1.0.0",
@@ -3001,6 +3511,13 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/dingbat-to-unicode": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/dingbat-to-unicode/-/dingbat-to-unicode-1.0.2.tgz",
+ "integrity": "sha512-R0bRerYzy/EZP6QzD3Hkl6JjUDA1Mnn+pd928w0nWjPzihnbAR6dcjGJGiRyznj5E4S1duEKzWrTqw02DPcdzg==",
+ "dev": true,
+ "license": "BSD-2-Clause"
+ },
"node_modules/dir-compare": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/dir-compare/-/dir-compare-4.2.0.tgz",
@@ -3056,6 +3573,77 @@
"js-yaml": "^4.1.0"
}
},
+ "node_modules/dom-serializer": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-3.1.1.tgz",
+ "integrity": "sha512-4MEa38/QexBob6gFNwu+EGdWvhJ1OKuNwdYY3Y3NyeWDQfnGeDYQUDfIRzWu5B5gsv03so2Uxd28YC6zrsx3Lw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^3.0.0",
+ "domhandler": "^6.0.0",
+ "entities": "^8.0.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/domelementtype": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-3.0.0.tgz",
+ "integrity": "sha512-umCQid3jKbDmVjx8jGaW7uUykm4DEUeyV21hPxNMo2nV955DhUThwqyOIDtreepP31hl84X7G5U9ZfsWvIB3Pg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
+ "node_modules/domhandler": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-6.0.1.tgz",
+ "integrity": "sha512-gYzvtM72ZtxQO0T048kd6HWSbbGCNOUwcnfQ01cqIJ4X2IYKFFHZ5mKvrQETcFXxsRObZulDaKmy//R7TPtsBg==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "domelementtype": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/domutils": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-4.0.2.tgz",
+ "integrity": "sha512-qI4JLRKnSzqFqr7hAlS5xQDusBCjKSEG4t4+7aNrIQMHBcsC2TGEhuyABJdYkgSewL57PNLYEiibY2iPKhKpaA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "dom-serializer": "^3.0.0",
+ "domelementtype": "^3.0.0",
+ "domhandler": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
"node_modules/dotenv": {
"version": "16.6.1",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz",
@@ -3085,6 +3673,16 @@
"url": "https://dotenvx.com"
}
},
+ "node_modules/duck": {
+ "version": "0.1.12",
+ "resolved": "https://registry.npmjs.org/duck/-/duck-0.1.12.tgz",
+ "integrity": "sha512-wkctla1O6VfP89gQ+J/yDesM0S7B7XLXjKGzXxMDVFg7uEn706niAtyYovKbyq1oT9YwDcly721/iUWoc8MVRg==",
+ "dev": true,
+ "license": "BSD",
+ "dependencies": {
+ "underscore": "^1.13.1"
+ }
+ },
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
@@ -3375,6 +3973,19 @@
"once": "^1.4.0"
}
},
+ "node_modules/entities": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",
+ "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/env-paths": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
@@ -3395,6 +4006,94 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/es-abstract": {
+ "version": "1.24.2",
+ "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.2.tgz",
+ "integrity": "sha512-2FpH9Q5i2RRwyEP1AylXe6nYLR5OhaJTZwmlcP0dL/+JCbgg7yyEo/sEK6HeGZRf3dFpWwThaRHVApXSkW3xeg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "array-buffer-byte-length": "^1.0.2",
+ "arraybuffer.prototype.slice": "^1.0.4",
+ "available-typed-arrays": "^1.0.7",
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.4",
+ "data-view-buffer": "^1.0.2",
+ "data-view-byte-length": "^1.0.2",
+ "data-view-byte-offset": "^1.0.1",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "es-set-tostringtag": "^2.1.0",
+ "es-to-primitive": "^1.3.0",
+ "function.prototype.name": "^1.1.8",
+ "get-intrinsic": "^1.3.0",
+ "get-proto": "^1.0.1",
+ "get-symbol-description": "^1.1.0",
+ "globalthis": "^1.0.4",
+ "gopd": "^1.2.0",
+ "has-property-descriptors": "^1.0.2",
+ "has-proto": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "internal-slot": "^1.1.0",
+ "is-array-buffer": "^3.0.5",
+ "is-callable": "^1.2.7",
+ "is-data-view": "^1.0.2",
+ "is-negative-zero": "^2.0.3",
+ "is-regex": "^1.2.1",
+ "is-set": "^2.0.3",
+ "is-shared-array-buffer": "^1.0.4",
+ "is-string": "^1.1.1",
+ "is-typed-array": "^1.1.15",
+ "is-weakref": "^1.1.1",
+ "math-intrinsics": "^1.1.0",
+ "object-inspect": "^1.13.4",
+ "object-keys": "^1.1.1",
+ "object.assign": "^4.1.7",
+ "own-keys": "^1.0.1",
+ "regexp.prototype.flags": "^1.5.4",
+ "safe-array-concat": "^1.1.3",
+ "safe-push-apply": "^1.0.0",
+ "safe-regex-test": "^1.1.0",
+ "set-proto": "^1.0.0",
+ "stop-iteration-iterator": "^1.1.0",
+ "string.prototype.trim": "^1.2.10",
+ "string.prototype.trimend": "^1.0.9",
+ "string.prototype.trimstart": "^1.0.8",
+ "typed-array-buffer": "^1.0.3",
+ "typed-array-byte-length": "^1.0.3",
+ "typed-array-byte-offset": "^1.0.4",
+ "typed-array-length": "^1.0.7",
+ "unbox-primitive": "^1.1.0",
+ "which-typed-array": "^1.1.19"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/es-abstract-get": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/es-abstract-get/-/es-abstract-get-1.0.0.tgz",
+ "integrity": "sha512-6PMWXpdhshVvFp+FoWYs1EvG1Nj0tvk0dZM+XcK0xMEM1czRVcP6ohqPWHy6qPagSpC8j4+p89WXlT+xXJs/fg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.2",
+ "is-callable": "^1.2.7",
+ "object-inspect": "^1.13.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
@@ -3448,6 +4147,27 @@
"node": ">= 0.4"
}
},
+ "node_modules/es-to-primitive": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.4.tgz",
+ "integrity": "sha512-yPDz7wqpg1/mmHLmS3tcfTfbw5f1eryXvyghYBffGdERwe+mV7ZcWzTR8LR17Kvqt3qfPurjlonmnq3MKXIOXw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-abstract-get": "^1.0.0",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "is-callable": "^1.2.7",
+ "is-date-object": "^1.1.0",
+ "is-symbol": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/es6-error": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz",
@@ -3536,6 +4256,84 @@
"node": ">=18.0.0"
}
},
+ "node_modules/exceljs": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/exceljs/-/exceljs-4.4.0.tgz",
+ "integrity": "sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "archiver": "^5.0.0",
+ "dayjs": "^1.8.34",
+ "fast-csv": "^4.3.1",
+ "jszip": "^3.10.1",
+ "readable-stream": "^3.6.0",
+ "saxes": "^5.0.1",
+ "tmp": "^0.2.0",
+ "unzipper": "^0.10.11",
+ "uuid": "^8.3.0"
+ },
+ "engines": {
+ "node": ">=8.3.0"
+ }
+ },
+ "node_modules/exceljs/node_modules/bluebird": {
+ "version": "3.4.7",
+ "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz",
+ "integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/exceljs/node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/exceljs/node_modules/unzipper": {
+ "version": "0.10.14",
+ "resolved": "https://registry.npmjs.org/unzipper/-/unzipper-0.10.14.tgz",
+ "integrity": "sha512-ti4wZj+0bQTiX2KmKWuwj7lhV+2n//uXEotUmGuQqrbVZSEGFMbI68+c6JCQ8aAmUWYvtHEz2A8K6wXvueR/6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "big-integer": "^1.6.17",
+ "binary": "~0.3.0",
+ "bluebird": "~3.4.1",
+ "buffer-indexof-polyfill": "~1.0.0",
+ "duplexer2": "~0.1.4",
+ "fstream": "^1.0.12",
+ "graceful-fs": "^4.2.2",
+ "listenercount": "~1.0.1",
+ "readable-stream": "~2.3.6",
+ "setimmediate": "~1.0.4"
+ }
+ },
+ "node_modules/exceljs/node_modules/unzipper/node_modules/readable-stream": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "core-util-is": "~1.0.0",
+ "inherits": "~2.0.3",
+ "isarray": "~1.0.0",
+ "process-nextick-args": "~2.0.0",
+ "safe-buffer": "~5.1.1",
+ "string_decoder": "~1.1.1",
+ "util-deprecate": "~1.0.1"
+ }
+ },
"node_modules/expect-type": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
@@ -3635,6 +4433,20 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/fast-csv": {
+ "version": "4.3.6",
+ "resolved": "https://registry.npmjs.org/fast-csv/-/fast-csv-4.3.6.tgz",
+ "integrity": "sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@fast-csv/format": "4.3.5",
+ "@fast-csv/parse": "4.3.6"
+ },
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -3736,16 +4548,32 @@
"url": "https://opencollective.com/express"
}
},
- "node_modules/form-data": {
- "version": "4.0.6",
- "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
- "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",
+ "node_modules/for-each": {
+ "version": "0.3.5",
+ "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz",
+ "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==",
"dev": true,
"license": "MIT",
"dependencies": {
- "asynckit": "^0.4.0",
- "combined-stream": "^1.0.8",
- "es-set-tostringtag": "^2.1.0",
+ "is-callable": "^1.2.7"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/form-data": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz",
+ "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.4",
"mime-types": "^2.1.35"
},
@@ -3794,6 +4622,13 @@
"node": ">= 0.8"
}
},
+ "node_modules/fs-constants": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz",
+ "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/fs-extra": {
"version": "10.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz",
@@ -3830,6 +4665,23 @@
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
+ "node_modules/fstream": {
+ "version": "1.0.12",
+ "resolved": "https://registry.npmjs.org/fstream/-/fstream-1.0.12.tgz",
+ "integrity": "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg==",
+ "deprecated": "This package is no longer supported.",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "graceful-fs": "^4.1.2",
+ "inherits": "~2.0.0",
+ "mkdirp": ">=0.5 0",
+ "rimraf": "2"
+ },
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
@@ -3839,6 +4691,50 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/function.prototype.name": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.2.0.tgz",
+ "integrity": "sha512-jObKIik1P2QjPHP5nz5BaOtUlfgS0fWo8IUByNXkM+o+02sJOi94em77GwJKQSJ3gfPHdgzLNrHc1uokV4P/ew==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.9",
+ "call-bound": "^1.0.4",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "functions-have-names": "^1.2.3",
+ "has-property-descriptors": "^1.0.2",
+ "hasown": "^2.0.4",
+ "is-callable": "^1.2.7",
+ "is-document.all": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/functions-have-names": {
+ "version": "1.2.3",
+ "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz",
+ "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/generator-function": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz",
+ "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/gensync": {
"version": "1.0.0-beta.2",
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
@@ -3912,6 +4808,24 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/get-symbol-description": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz",
+ "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
@@ -3990,7 +4904,6 @@
"integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==",
"dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"define-properties": "^1.2.1",
"gopd": "^1.0.1"
@@ -4052,6 +4965,19 @@
"integrity": "sha512-P8/mMxVLU7o4+55+1TCnQrPmgjPKnwkzkXOK1asnR9Jg2lna4tEY5qBJjMmAaOBDDZWtlRjBXjLa0w53G/uBLA==",
"license": "Standard 'no charge' license: https://gsap.com/standard-license."
},
+ "node_modules/has-bigints": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz",
+ "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
@@ -4068,7 +4994,6 @@
"integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==",
"dev": true,
"license": "MIT",
- "optional": true,
"dependencies": {
"es-define-property": "^1.0.0"
},
@@ -4076,6 +5001,22 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/has-proto": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz",
+ "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
@@ -4200,6 +5141,13 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/html-escaper": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-3.0.3.tgz",
+ "integrity": "sha512-RuMffC89BOWQoY0WKGpIhn5gX3iI54O6nRA0yC124NYVtzjmFWBIiFd8M0x+ZdX0P9R4lADg1mgP8C7PxGOWuQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/html-url-attributes": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/html-url-attributes/-/html-url-attributes-3.0.1.tgz",
@@ -4211,6 +5159,111 @@
"url": "https://opencollective.com/unified"
}
},
+ "node_modules/htmlparser2": {
+ "version": "10.1.0",
+ "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.1.0.tgz",
+ "integrity": "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ==",
+ "dev": true,
+ "funding": [
+ "https://github.com/fb55/htmlparser2?sponsor=1",
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3",
+ "domutils": "^3.2.2",
+ "entities": "^7.0.1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/dom-serializer": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz",
+ "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.2",
+ "entities": "^4.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/dom-serializer/node_modules/entities": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
+ "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/domelementtype": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz",
+ "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fb55"
+ }
+ ],
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/htmlparser2/node_modules/domhandler": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz",
+ "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "domelementtype": "^2.3.0"
+ },
+ "engines": {
+ "node": ">= 4"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domhandler?sponsor=1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/domutils": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
+ "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "dom-serializer": "^2.0.0",
+ "domelementtype": "^2.3.0",
+ "domhandler": "^5.0.3"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/domutils?sponsor=1"
+ }
+ },
+ "node_modules/htmlparser2/node_modules/entities": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
+ "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.12"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
"node_modules/http-cache-semantics": {
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz",
@@ -4296,6 +5349,34 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/immediate": {
+ "version": "3.0.6",
+ "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
+ "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/inflight": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
@@ -4321,6 +5402,21 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/internal-slot": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz",
+ "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "hasown": "^2.0.2",
+ "side-channel": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/ip-address": {
"version": "10.7.4",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz",
@@ -4365,64 +5461,423 @@
"url": "https://github.com/sponsors/wooorm"
}
},
- "node_modules/is-decimal": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",
- "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
+ "node_modules/is-array-buffer": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
+ "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==",
"dev": true,
"license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.3",
+ "get-intrinsic": "^1.2.6"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
"funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
+ "url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/is-fullwidth-code-point": {
- "version": "3.0.0",
- "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
- "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "node_modules/is-async-function": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz",
+ "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==",
"dev": true,
"license": "MIT",
+ "dependencies": {
+ "async-function": "^1.0.0",
+ "call-bound": "^1.0.3",
+ "get-proto": "^1.0.1",
+ "has-tostringtag": "^1.0.2",
+ "safe-regex-test": "^1.1.0"
+ },
"engines": {
- "node": ">=8"
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/is-hexadecimal": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
- "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",
+ "node_modules/is-bigint": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz",
+ "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==",
"dev": true,
"license": "MIT",
+ "dependencies": {
+ "has-bigints": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
"funding": {
- "type": "github",
- "url": "https://github.com/sponsors/wooorm"
+ "url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/is-plain-obj": {
- "version": "4.1.0",
- "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
- "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",
+ "node_modules/is-boolean-object": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz",
+ "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==",
"dev": true,
"license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "has-tostringtag": "^1.0.2"
+ },
"engines": {
- "node": ">=12"
+ "node": ">= 0.4"
},
"funding": {
- "url": "https://github.com/sponsors/sindresorhus"
+ "url": "https://github.com/sponsors/ljharb"
}
},
- "node_modules/is-promise": {
- "version": "4.0.0",
- "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
- "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
- "license": "MIT"
- },
- "node_modules/isarray": {
- "version": "1.0.0",
- "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
- "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
+ "node_modules/is-callable": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz",
+ "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==",
"dev": true,
- "license": "MIT"
- },
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-data-view": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz",
+ "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "get-intrinsic": "^1.2.6",
+ "is-typed-array": "^1.1.13"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-date-object": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz",
+ "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "has-tostringtag": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-decimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",
+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-document.all": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/is-document.all/-/is-document.all-1.0.0.tgz",
+ "integrity": "sha512-+XSoyS05OdBbhFuELhgTCpFNHkpBOJqtsZfUFFpe5QTw+9Sjbh8zitxhQkYAo6wV7e1Vb8cAPvpCk9jGam/82g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-finalizationregistry": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz",
+ "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/is-generator-function": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz",
+ "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.4",
+ "generator-function": "^2.0.0",
+ "get-proto": "^1.0.1",
+ "has-tostringtag": "^1.0.2",
+ "safe-regex-test": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-hexadecimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-map": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz",
+ "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-negative-zero": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz",
+ "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-number-object": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz",
+ "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "has-tostringtag": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-plain-obj": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz",
+ "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/is-promise": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
+ "license": "MIT"
+ },
+ "node_modules/is-regex": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",
+ "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "gopd": "^1.2.0",
+ "has-tostringtag": "^1.0.2",
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-set": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz",
+ "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-shared-array-buffer": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz",
+ "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-string": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz",
+ "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "has-tostringtag": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-symbol": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz",
+ "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "has-symbols": "^1.1.0",
+ "safe-regex-test": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-typed-array": {
+ "version": "1.1.15",
+ "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz",
+ "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "which-typed-array": "^1.1.16"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-weakmap": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz",
+ "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-weakref": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz",
+ "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-weakset": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz",
+ "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "get-intrinsic": "^1.2.6"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/isarray": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/isbinaryfile": {
"version": "5.0.7",
"resolved": "https://registry.npmjs.org/isbinaryfile/-/isbinaryfile-5.0.7.tgz",
@@ -4573,6 +6028,19 @@
"graceful-fs": "^4.1.6"
}
},
+ "node_modules/jszip": {
+ "version": "3.10.2",
+ "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.2.tgz",
+ "integrity": "sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ==",
+ "dev": true,
+ "license": "(MIT OR GPL-3.0-or-later)",
+ "dependencies": {
+ "lie": "~3.3.0",
+ "pako": "~1.0.2",
+ "readable-stream": "~2.3.6",
+ "setimmediate": "^1.0.5"
+ }
+ },
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",
@@ -4589,6 +6057,29 @@
"integrity": "sha512-0/BnGCCfyUMkBpeDgWihanIAF9JmZhHBgUhEqzvf+adhNGLoP6TaiI5oF8oyb3I45P+PcnrqihSf01M0l0G5+Q==",
"license": "MIT"
},
+ "node_modules/lazystream": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/lazystream/-/lazystream-1.0.1.tgz",
+ "integrity": "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "readable-stream": "^2.0.5"
+ },
+ "engines": {
+ "node": ">= 0.6.3"
+ }
+ },
+ "node_modules/lie": {
+ "version": "3.3.0",
+ "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
+ "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "immediate": "~3.0.5"
+ }
+ },
"node_modules/lightningcss": {
"version": "1.33.0",
"resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
@@ -4850,6 +6341,38 @@
"url": "https://opencollective.com/parcel"
}
},
+ "node_modules/linkedom": {
+ "version": "0.18.15",
+ "resolved": "https://registry.npmjs.org/linkedom/-/linkedom-0.18.15.tgz",
+ "integrity": "sha512-o0w7eD/SvoCao+pUi6dzocCLuMR11g4Tv/et0W2OUzwWmUcewntSzyl+Ua/K+0yKym0Y/Mav3nFAaI5Av5jvZg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "css-select": "^7.0.0",
+ "cssomnom": "^0.1.11",
+ "html-escaper": "^3.0.3",
+ "htmlparser2": "^10.1.0",
+ "uhyphen": "^0.2.0"
+ },
+ "engines": {
+ "node": ">=16"
+ },
+ "peerDependencies": {
+ "canvas": ">= 2"
+ },
+ "peerDependenciesMeta": {
+ "canvas": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/listenercount": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/listenercount/-/listenercount-1.0.1.tgz",
+ "integrity": "sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ==",
+ "dev": true,
+ "license": "ISC"
+ },
"node_modules/lodash": {
"version": "4.18.1",
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
@@ -4857,17 +6380,94 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/lodash.defaults": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz",
+ "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lodash.difference": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.difference/-/lodash.difference-4.5.0.tgz",
+ "integrity": "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/lodash.escaperegexp": {
"version": "4.1.2",
"resolved": "https://registry.npmjs.org/lodash.escaperegexp/-/lodash.escaperegexp-4.1.2.tgz",
"integrity": "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw==",
"license": "MIT"
},
- "node_modules/lodash.isequal": {
+ "node_modules/lodash.flatten": {
+ "version": "4.4.0",
+ "resolved": "https://registry.npmjs.org/lodash.flatten/-/lodash.flatten-4.4.0.tgz",
+ "integrity": "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lodash.groupby": {
+ "version": "4.6.0",
+ "resolved": "https://registry.npmjs.org/lodash.groupby/-/lodash.groupby-4.6.0.tgz",
+ "integrity": "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lodash.isboolean": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz",
+ "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lodash.isequal": {
+ "version": "4.5.0",
+ "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
+ "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==",
+ "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.",
+ "license": "MIT"
+ },
+ "node_modules/lodash.isfunction": {
+ "version": "3.0.9",
+ "resolved": "https://registry.npmjs.org/lodash.isfunction/-/lodash.isfunction-3.0.9.tgz",
+ "integrity": "sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lodash.isnil": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/lodash.isnil/-/lodash.isnil-4.0.0.tgz",
+ "integrity": "sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lodash.isplainobject": {
+ "version": "4.0.6",
+ "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz",
+ "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lodash.isundefined": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/lodash.isundefined/-/lodash.isundefined-3.0.1.tgz",
+ "integrity": "sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lodash.union": {
+ "version": "4.6.0",
+ "resolved": "https://registry.npmjs.org/lodash.union/-/lodash.union-4.6.0.tgz",
+ "integrity": "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lodash.uniq": {
"version": "4.5.0",
- "resolved": "https://registry.npmjs.org/lodash.isequal/-/lodash.isequal-4.5.0.tgz",
- "integrity": "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ==",
- "deprecated": "This package is deprecated. Use require('node:util').isDeepStrictEqual instead.",
+ "resolved": "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz",
+ "integrity": "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ==",
+ "dev": true,
"license": "MIT"
},
"node_modules/longest-streak": {
@@ -4881,6 +6481,18 @@
"url": "https://github.com/sponsors/wooorm"
}
},
+ "node_modules/lop": {
+ "version": "0.4.2",
+ "resolved": "https://registry.npmjs.org/lop/-/lop-0.4.2.tgz",
+ "integrity": "sha512-RefILVDQ4DKoRZsJ4Pj22TxE3omDO47yFpkIBoDKzkqPRISs5U1cnAdg/5583YPkWPaLIYHOKRMQSvjFsO26cw==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "duck": "^0.1.12",
+ "option": "~0.2.1",
+ "underscore": "^1.13.1"
+ }
+ },
"node_modules/lowercase-keys": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",
@@ -4911,6 +6523,56 @@
"@jridgewell/sourcemap-codec": "^1.6.0"
}
},
+ "node_modules/mammoth": {
+ "version": "1.13.0",
+ "resolved": "https://registry.npmjs.org/mammoth/-/mammoth-1.13.0.tgz",
+ "integrity": "sha512-2cawcYFcP7ISfXbBcL9lmVgTNWo88v/52ND1gnywHtVT/pX0//puPnf0iMPV9ZgmuvNOE+zkIhDgZ9M2c2dDDg==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "@xmldom/xmldom": "^0.8.6",
+ "argparse": "~1.0.3",
+ "base64-js": "^1.5.1",
+ "dingbat-to-unicode": "^1.0.1",
+ "jszip": "^3.7.1",
+ "lop": "^0.4.2",
+ "underscore": "^1.13.1",
+ "xmlbuilder": "^10.0.0"
+ },
+ "bin": {
+ "mammoth": "bin/mammoth"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/mammoth/node_modules/argparse": {
+ "version": "1.0.10",
+ "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz",
+ "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "sprintf-js": "~1.0.2"
+ }
+ },
+ "node_modules/mammoth/node_modules/sprintf-js": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz",
+ "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/mammoth/node_modules/xmlbuilder": {
+ "version": "10.1.1",
+ "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-10.1.1.tgz",
+ "integrity": "sha512-OyzrcFLL/nb6fMGHbiRDuPup9ljBycsdCypwuyg5AAHvyWzGfChJpCXMG88AGTIMFhGZ9RccFN1e6lhg3hkwKg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
"node_modules/markdown-table": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/markdown-table/-/markdown-table-3.0.4.tgz",
@@ -5987,7 +7649,6 @@
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"minimist": "^1.2.6"
},
@@ -6176,6 +7837,16 @@
"node": "^20.17.0 || >=22.9.0"
}
},
+ "node_modules/normalize-path": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
+ "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
"node_modules/normalize-url": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",
@@ -6189,6 +7860,23 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/nth-check": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-3.0.1.tgz",
+ "integrity": "sha512-GX0gsdbGVCgnRgbeGaubfjpBXyYRWOOCVeYh08bSQvDZqxz5ndXs1OTfAt/h36G1xvI94YIspsI0sVFqAV9+RQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "boolbase": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/fb55/nth-check?sponsor=1"
+ }
+ },
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@@ -6216,11 +7904,31 @@
"integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==",
"dev": true,
"license": "MIT",
- "optional": true,
"engines": {
"node": ">= 0.4"
}
},
+ "node_modules/object.assign": {
+ "version": "4.1.7",
+ "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz",
+ "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "call-bound": "^1.0.3",
+ "define-properties": "^1.2.1",
+ "es-object-atoms": "^1.0.0",
+ "has-symbols": "^1.1.0",
+ "object-keys": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/obug": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
@@ -6263,6 +7971,32 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/option": {
+ "version": "0.2.4",
+ "resolved": "https://registry.npmjs.org/option/-/option-0.2.4.tgz",
+ "integrity": "sha512-pkEqbDyl8ou5cpq+VsnQbe/WlEy5qS7xPzMS1U55OCG9KPvwFD46zDbxQIj3egJSFc3D+XhYOPUzz49zQAVy7A==",
+ "dev": true,
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/own-keys": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.2.tgz",
+ "integrity": "sha512-19YVAg7T+WTrxggPukVq7DjTv6+PJ867TmhCvBsYwmbFCsZd344rq2Ld1p0wo8f8Qrrhgp82c6FJRqdXWtSEhg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.4",
+ "get-intrinsic": "^1.3.0",
+ "object-keys": "^1.1.1",
+ "safe-push-apply": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/p-cancelable": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",
@@ -6289,6 +8023,13 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/pako": {
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
+ "dev": true,
+ "license": "(MIT AND Zlib)"
+ },
"node_modules/parse-entities": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",
@@ -6483,6 +8224,16 @@
"node": ">=10.4.0"
}
},
+ "node_modules/possible-typed-array-names": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz",
+ "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/postcss": {
"version": "8.5.30",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.30.tgz",
@@ -6791,6 +8542,90 @@
"util-deprecate": "~1.0.1"
}
},
+ "node_modules/readdir-glob": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/readdir-glob/-/readdir-glob-1.1.3.tgz",
+ "integrity": "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "minimatch": "^5.1.0"
+ }
+ },
+ "node_modules/readdir-glob/node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/readdir-glob/node_modules/brace-expansion": {
+ "version": "2.1.7",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
+ "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^1.0.0"
+ }
+ },
+ "node_modules/readdir-glob/node_modules/minimatch": {
+ "version": "5.1.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz",
+ "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/reflect.getprototypeof": {
+ "version": "1.0.10",
+ "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz",
+ "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.23.9",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.0.0",
+ "get-intrinsic": "^1.2.7",
+ "get-proto": "^1.0.1",
+ "which-builtin-type": "^1.2.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/regexp.prototype.flags": {
+ "version": "1.5.4",
+ "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz",
+ "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "define-properties": "^1.2.1",
+ "es-errors": "^1.3.0",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "set-function-name": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/remark-gfm": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",
@@ -6935,7 +8770,6 @@
"deprecated": "Rimraf versions prior to v4 are no longer supported",
"dev": true,
"license": "ISC",
- "peer": true,
"dependencies": {
"glob": "^7.1.3"
},
@@ -7012,6 +8846,33 @@
"node": ">= 18"
}
},
+ "node_modules/safe-array-concat": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.4.tgz",
+ "integrity": "sha512-wtZlHyOje6OZTGqAoaDKxFkgRtkF9CnHAVnCHKfuj200wAgL+bSJhdsCD2l0Qx/2ekEXjPWcyKkfGb5CPboslg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.9",
+ "call-bound": "^1.0.4",
+ "get-intrinsic": "^1.3.0",
+ "has-symbols": "^1.1.0",
+ "isarray": "^2.0.5"
+ },
+ "engines": {
+ "node": ">=0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/safe-array-concat/node_modules/isarray": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",
+ "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/safe-buffer": {
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
@@ -7019,6 +8880,48 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/safe-push-apply": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz",
+ "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "isarray": "^2.0.5"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/safe-push-apply/node_modules/isarray": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",
+ "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/safe-regex-test": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz",
+ "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "is-regex": "^1.2.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
@@ -7044,6 +8947,19 @@
"node": ">=11.0.0"
}
},
+ "node_modules/saxes": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-5.0.1.tgz",
+ "integrity": "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "xmlchars": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
"node_modules/scheduler": {
"version": "0.28.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
@@ -7134,6 +9050,62 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/set-function-length": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz",
+ "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "define-data-property": "^1.1.4",
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2",
+ "get-intrinsic": "^1.2.4",
+ "gopd": "^1.0.1",
+ "has-property-descriptors": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/set-function-name": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz",
+ "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "define-data-property": "^1.1.4",
+ "es-errors": "^1.3.0",
+ "functions-have-names": "^1.2.3",
+ "has-property-descriptors": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/set-proto": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz",
+ "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/setimmediate": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
+ "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
@@ -7355,6 +9327,20 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/stop-iteration-iterator": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz",
+ "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "internal-slot": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/string_decoder": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
@@ -7380,6 +9366,66 @@
"node": ">=8"
}
},
+ "node_modules/string.prototype.trim": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.11.tgz",
+ "integrity": "sha512-PwvK7BU+CMTJGYQCTZb5RWXIML92lftJLhQz1tBzgKiqGxJaMlBAa48POXaNAC2s4y8jr3EFqrkF9+44neS46w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.9",
+ "call-bound": "^1.0.4",
+ "define-data-property": "^1.1.4",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.24.2",
+ "es-object-atoms": "^1.1.2",
+ "has-property-descriptors": "^1.0.2",
+ "safe-regex-test": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/string.prototype.trimend": {
+ "version": "1.0.10",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.10.tgz",
+ "integrity": "sha512-2+3aDAOmPTmuFwjDnmJG2ctEkQKVki7vOSqaxkv42Mowj1V6PnvuwFCRrR5lChUux1TBskPjfkeTOhqczDMxTw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.9",
+ "call-bound": "^1.0.4",
+ "define-properties": "^1.2.1",
+ "es-object-atoms": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/string.prototype.trimstart": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz",
+ "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.7",
+ "define-properties": "^1.2.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/stringify-entities": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",
@@ -7471,6 +9517,38 @@
"node": ">=18"
}
},
+ "node_modules/tar-stream": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz",
+ "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "bl": "^4.0.3",
+ "end-of-stream": "^1.4.1",
+ "fs-constants": "^1.0.0",
+ "inherits": "^2.0.3",
+ "readable-stream": "^3.1.1"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/tar-stream/node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/tar/node_modules/yallist": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz",
@@ -7606,6 +9684,26 @@
"node": ">=0.6"
}
},
+ "node_modules/traverse": {
+ "version": "0.3.10",
+ "resolved": "https://registry.npmjs.org/traverse/-/traverse-0.3.10.tgz",
+ "integrity": "sha512-pd6fq5qmiFuPA3TpdqBCqJXlOrSdCSt0l9IZDg83Vbf4x3m/X18prEwMMVM5LXp9vGL9NxjeiDGBrTasqyngXQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "define-data-property": "^1.1.4",
+ "es-to-primitive": "^1.3.4",
+ "gopd": "^1.2.0",
+ "typedarray.prototype.slice": "^1.0.6",
+ "which-typed-array": "^1.1.24"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/trim-lines": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/trim-lines/-/trim-lines-3.0.1.tgz",
@@ -7690,6 +9788,106 @@
"url": "https://opencollective.com/express"
}
},
+ "node_modules/typed-array-buffer": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz",
+ "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "es-errors": "^1.3.0",
+ "is-typed-array": "^1.1.14"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/typed-array-byte-length": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz",
+ "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.8",
+ "for-each": "^0.3.3",
+ "gopd": "^1.2.0",
+ "has-proto": "^1.2.0",
+ "is-typed-array": "^1.1.14"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/typed-array-byte-offset": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.5.tgz",
+ "integrity": "sha512-0FHJvLPqZ7KJzp17O13jfsAjsqazgrxBu2zEK95PmUz8lv2+GjRuxUInCr2Rk9Dms3ihN21zJ929ZO43yJ95QQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "available-typed-arrays": "^1.0.7",
+ "call-bind": "^1.0.9",
+ "for-each": "^0.3.5",
+ "gopd": "^1.2.0",
+ "is-typed-array": "^1.1.15",
+ "reflect.getprototypeof": "^1.0.10"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/typed-array-length": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.8.tgz",
+ "integrity": "sha512-phPGCwqr2+Qo0fwniCE8e4pKnGu/yFb5nD5Y8bf0EEeiI5GklnACYA9GFy/DrAeRrKHXvHn+1SUsOWgJp6RO+g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.9",
+ "for-each": "^0.3.5",
+ "gopd": "^1.2.0",
+ "is-typed-array": "^1.1.15",
+ "possible-typed-array-names": "^1.1.0",
+ "reflect.getprototypeof": "^1.0.10"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/typedarray.prototype.slice": {
+ "version": "1.0.6",
+ "resolved": "https://registry.npmjs.org/typedarray.prototype.slice/-/typedarray.prototype.slice-1.0.6.tgz",
+ "integrity": "sha512-r+7YvGfM5TkTiDQ5EqWi/Z4L4KP3jUI+YCmTtWg1tmTHUw6xladLJqzR2heMaHBIM0TTFLZmn/EkIaEHYs/bIA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bind": "^1.0.9",
+ "define-properties": "^1.2.1",
+ "es-abstract": "^1.24.2",
+ "es-errors": "^1.3.0",
+ "get-proto": "^1.0.1",
+ "math-intrinsics": "^1.1.0",
+ "typed-array-buffer": "^1.0.3",
+ "typed-array-byte-offset": "^1.0.5"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/typescript": {
"version": "7.0.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
@@ -7725,6 +9923,39 @@
"@typescript/typescript-win32-x64": "7.0.2"
}
},
+ "node_modules/uhyphen": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/uhyphen/-/uhyphen-0.2.0.tgz",
+ "integrity": "sha512-qz3o9CHXmJJPGBdqzab7qAYuW8kQGKNEuoHFYrBwV6hWIMcpAmxDLXojcHfFr9US1Pe6zUswEIJIbLI610fuqA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/unbox-primitive": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz",
+ "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.3",
+ "has-bigints": "^1.0.2",
+ "has-symbols": "^1.1.0",
+ "which-boxed-primitive": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/underscore": {
+ "version": "1.13.8",
+ "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.8.tgz",
+ "integrity": "sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/undici": {
"version": "7.30.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz",
@@ -7845,6 +10076,24 @@
"node": ">= 10.0.0"
}
},
+ "node_modules/unpdf": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/unpdf/-/unpdf-2.1.0.tgz",
+ "integrity": "sha512-G/Hsrm++g0EoubUhV8TDFItq6oQ+FUu9EMvIRtHUwseKXB0iJoCvaLvBGOpYUBqyvggv/XfxhYYtohL2QpE3xQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=24"
+ },
+ "peerDependencies": {
+ "@napi-rs/canvas": "^0.1.69 || ^1.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@napi-rs/canvas": {
+ "optional": true
+ }
+ }
+ },
"node_modules/unpipe": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
@@ -7928,6 +10177,17 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/uuid": {
+ "version": "8.3.2",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
+ "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
+ "deprecated": "uuid@10 and below is no longer supported. For ESM codebases, update to uuid@latest. For CommonJS codebases, use uuid@11 (but be aware this version will likely be deprecated in 2028).",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "uuid": "dist/bin/uuid"
+ }
+ },
"node_modules/vary": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
@@ -8174,6 +10434,102 @@
"node": ">= 8"
}
},
+ "node_modules/which-boxed-primitive": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz",
+ "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-bigint": "^1.1.0",
+ "is-boolean-object": "^1.2.1",
+ "is-number-object": "^1.1.1",
+ "is-string": "^1.1.1",
+ "is-symbol": "^1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/which-builtin-type": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz",
+ "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "function.prototype.name": "^1.1.6",
+ "has-tostringtag": "^1.0.2",
+ "is-async-function": "^2.0.0",
+ "is-date-object": "^1.1.0",
+ "is-finalizationregistry": "^1.1.0",
+ "is-generator-function": "^1.0.10",
+ "is-regex": "^1.2.1",
+ "is-weakref": "^1.0.2",
+ "isarray": "^2.0.5",
+ "which-boxed-primitive": "^1.1.0",
+ "which-collection": "^1.0.2",
+ "which-typed-array": "^1.1.16"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/which-builtin-type/node_modules/isarray": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz",
+ "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/which-collection": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz",
+ "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-map": "^2.0.3",
+ "is-set": "^2.0.3",
+ "is-weakmap": "^2.0.2",
+ "is-weakset": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/which-typed-array": {
+ "version": "1.1.24",
+ "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.24.tgz",
+ "integrity": "sha512-wk4Mf4pR5mRP7eYuuTBCIQ9d0ud2Fv2jRLQpfgnRjbOxAFHmjKFValgTpitVKzJJS8ajnYQV2Du1SZ8j6b/EUQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "available-typed-arrays": "^1.0.7",
+ "call-bind": "^1.0.9",
+ "call-bound": "^1.0.4",
+ "for-each": "^0.3.5",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-tostringtag": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
@@ -8225,6 +10581,13 @@
"node": ">=8.0"
}
},
+ "node_modules/xmlchars": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/y18n": {
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
@@ -8284,6 +10647,58 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/zip-stream": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/zip-stream/-/zip-stream-4.1.1.tgz",
+ "integrity": "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "archiver-utils": "^3.0.4",
+ "compress-commons": "^4.1.2",
+ "readable-stream": "^3.6.0"
+ },
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/zip-stream/node_modules/archiver-utils": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/archiver-utils/-/archiver-utils-3.0.4.tgz",
+ "integrity": "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "glob": "^7.2.3",
+ "graceful-fs": "^4.2.0",
+ "lazystream": "^1.0.0",
+ "lodash.defaults": "^4.2.0",
+ "lodash.difference": "^4.5.0",
+ "lodash.flatten": "^4.4.0",
+ "lodash.isplainobject": "^4.0.6",
+ "lodash.union": "^4.6.0",
+ "normalize-path": "^3.0.0",
+ "readable-stream": "^3.6.0"
+ },
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/zip-stream/node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
"node_modules/zod": {
"version": "4.6.7",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
diff --git a/package.json b/package.json
index 3aaab9b..fa0b15e 100644
--- a/package.json
+++ b/package.json
@@ -20,6 +20,7 @@
"release": "sh scripts/release.sh"
},
"devDependencies": {
+ "@mozilla/readability": "^0.6.0",
"@types/node": "^26.6.5",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
@@ -27,6 +28,10 @@
"electron": "^44.8.0",
"electron-builder": "^26.15.3",
"electron-vite": "^6.0.0",
+ "exceljs": "^4.4.0",
+ "jszip": "^3.10.2",
+ "linkedom": "^0.18.15",
+ "mammoth": "^1.13.0",
"open-bot-avatar": "0.1.1",
"playwright": "^1.64.1",
"react": "^19.3.1",
@@ -34,6 +39,7 @@
"react-markdown": "^10.1.0",
"remark-gfm": "^4.0.1",
"typescript": "^7.0.2",
+ "unpdf": "^2.1.0",
"vite": "^8.3.4",
"vitest": "^4.1.12"
},
diff --git a/src/core/context.ts b/src/core/context.ts
index 74bb800..0815fb8 100644
--- a/src/core/context.ts
+++ b/src/core/context.ts
@@ -24,8 +24,9 @@ export function systemPrompt(opts: {
skills?: Skill[] // the active ones it follows, when it has skill tools
publish?: string[] // the GitHub repositories it can push agent/* branches to
builder?: string // the Tuca's view of the workspace: models, connectors, the team
+ wiki?: { pages: number; kinds: string[] } // the wiki it may read
}): string {
- const { agent, settings, conversation, peers, memories, canRemember, hasComputer, macFolder, offline, web, browser, apps, routines, skills, publish, builder } = opts
+ const { agent, settings, conversation, peers, memories, canRemember, hasComputer, macFolder, offline, web, browser, apps, routines, skills, publish, builder, wiki } = opts
const me = settings.workspaceName || L('o usuário', 'the user')
const where =
conversation.kind === 'dm'
@@ -75,6 +76,11 @@ export function systemPrompt(opts: {
apps?.length && appsSection(me, apps),
builder,
memories && (memories.aboutMe.length > 0 || memories.own.length > 0 || !!memories.searchable) && memorySection(me, memories),
+ wiki &&
+ L(
+ `## A wiki\n${me} tem uma wiki com ${wiki.pages === 1 ? '1 página' : `${wiki.pages} páginas`} (${wiki.kinds.join(', ')}): o que ${me} e o time sabem, escrito. Quando a pergunta puder estar lá (uma pessoa, um cliente, um projeto, uma decisão, um assunto), consulte antes de responder ou de perguntar: wiki_indice pra ver o que existe, wiki_buscar pra achar, wiki_ler pra abrir. Ao usar uma página, cite com [[Título]]. Se a wiki não disser, diga que não está lá; não invente. Você só lê a wiki: o curador a atualiza sozinho depois da conversa, com o que ficar decidido; não diga que ela vai ficar desatualizada nem peça pra alguém editar.`,
+ `## The wiki\n${me} has a wiki with ${wiki.pages === 1 ? '1 page' : `${wiki.pages} pages`} (${wiki.kinds.join(', ')}): what ${me} and the team know, written down. When the answer could be there (a person, a client, a project, a decision, a topic), look before replying or asking: wiki_indice to see what exists, wiki_buscar to find, wiki_ler to open. When you use a page, cite it as [[Title]]. If the wiki doesn't say, say it isn't there; don't make it up. You only read the wiki: the curator updates it on its own after the conversation, with what was settled; don't say it will be out of date or ask anyone to edit it.`
+ ),
skills &&
skills.length > 0 &&
`${L(
diff --git a/src/core/db.ts b/src/core/db.ts
index ba9a514..ebed88e 100644
--- a/src/core/db.ts
+++ b/src/core/db.ts
@@ -240,6 +240,12 @@ const MIGRATIONS = [
`,
`
ALTER TABLE agents ADD COLUMN avatar TEXT;
+ `,
+ `
+ ALTER TABLE agents ADD COLUMN wiki TEXT;
+ `,
+ `
+ ALTER TABLE conversations ADD COLUMN wiki_capture INTEGER;
`
]
@@ -340,6 +346,7 @@ export class Db {
...(r['custom_color'] ? { customColor: str(r['custom_color']) } : {}),
...(r['picture'] ? { picture: str(r['picture']) } : {}),
...(r['avatar'] ? { avatar: JSON.parse(str(r['avatar'])) as Agent['avatar'] } : {}),
+ ...(r['wiki'] === 'none' || r['wiki'] === 'read' ? { wiki: r['wiki'] } : {}),
autoApprove: JSON.parse(str(r['auto_approve']) || '[]') as string[],
folders: JSON.parse(str(r['folders']) || '[]') as LentFolder[],
archived: r['archived'] === 1,
@@ -359,14 +366,14 @@ export class Db {
saveAgent(a: Agent): void {
this.db
.prepare(
- `INSERT INTO agents (id, name, handle, role, color, instructions, model, fallback_model, fallback_account, account, effort, limit_tokens, max_routines, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, custom_color, picture, avatar, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `INSERT INTO agents (id, name, handle, role, color, instructions, model, fallback_model, fallback_account, account, effort, limit_tokens, max_routines, grants, memory_mode, computer, computer_kind, web, browser, apps, auto_approve, archived, kind, custom_color, picture, avatar, wiki, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT (id) DO UPDATE SET name = excluded.name, handle = excluded.handle, role = excluded.role,
color = excluded.color, instructions = excluded.instructions, model = excluded.model, fallback_model = excluded.fallback_model, fallback_account = excluded.fallback_account, account = excluded.account, effort = excluded.effort,
limit_tokens = excluded.limit_tokens, max_routines = excluded.max_routines, grants = excluded.grants, memory_mode = excluded.memory_mode,
- computer = excluded.computer, computer_kind = excluded.computer_kind, web = excluded.web, browser = excluded.browser, apps = excluded.apps, auto_approve = excluded.auto_approve, archived = excluded.archived, kind = COALESCE(excluded.kind, agents.kind), custom_color = excluded.custom_color, picture = excluded.picture, avatar = excluded.avatar`
+ computer = excluded.computer, computer_kind = excluded.computer_kind, web = excluded.web, browser = excluded.browser, apps = excluded.apps, auto_approve = excluded.auto_approve, archived = excluded.archived, kind = COALESCE(excluded.kind, agents.kind), custom_color = excluded.custom_color, picture = excluded.picture, avatar = excluded.avatar, wiki = excluded.wiki`
)
- .run(a.id, a.name, a.handle, a.role, a.color, a.instructions, a.modelId, a.fallbackModelId || null, a.fallbackAccountId || null, a.accountId || null, a.effort, a.limit, routineCap(a.maxRoutines), JSON.stringify(a.grants), a.memory ?? 'auto', a.computer ? 1 : 0, a.computerKind === 'mac' ? 'mac' : 'linux', a.web === false ? 0 : 1, a.browser ? 1 : 0, JSON.stringify(a.apps ?? []), JSON.stringify(a.autoApprove ?? []), a.archived ? 1 : 0, a.kind ?? null, a.customColor ?? null, a.picture ?? null, a.avatar ? JSON.stringify(a.avatar) : null, Date.now())
+ .run(a.id, a.name, a.handle, a.role, a.color, a.instructions, a.modelId, a.fallbackModelId || null, a.fallbackAccountId || null, a.accountId || null, a.effort, a.limit, routineCap(a.maxRoutines), JSON.stringify(a.grants), a.memory ?? 'auto', a.computer ? 1 : 0, a.computerKind === 'mac' ? 'mac' : 'linux', a.web === false ? 0 : 1, a.browser ? 1 : 0, JSON.stringify(a.apps ?? []), JSON.stringify(a.autoApprove ?? []), a.archived ? 1 : 0, a.kind ?? null, a.customColor ?? null, a.picture ?? null, a.avatar ? JSON.stringify(a.avatar) : null, a.wiki ?? null, Date.now())
}
// Kept apart from saveAgent: folders change only after the core checks them.
@@ -394,7 +401,8 @@ export class Db {
members: members.filter((m) => m.conversation_id === r['id']).map((m) => m.agent_id),
summary: r['summary'] ? str(r['summary']) : undefined,
summaryUntil: r['summary_until'] ? Number(r['summary_until']) : undefined,
- summaryAt: r['summary_at'] ? Number(r['summary_at']) : undefined
+ summaryAt: r['summary_at'] ? Number(r['summary_at']) : undefined,
+ ...(r['wiki_capture'] === 0 ? { wikiCapture: false } : {})
}))
}
@@ -419,6 +427,11 @@ export class Db {
this.db.prepare('UPDATE conversations SET name = ? WHERE id = ?').run(name, id)
}
+ // Off: the wiki's curator leaves the conversation out. On is the default (stored as null).
+ setWikiCapture(id: string, on: boolean): void {
+ this.db.prepare('UPDATE conversations SET wiki_capture = ? WHERE id = ?').run(on ? null : 0, id)
+ }
+
setTopic(id: string, topic: string | undefined): void {
this.db.prepare('UPDATE conversations SET topic = ? WHERE id = ?').run(topic ?? null, id)
}
diff --git a/src/core/engines/fake.ts b/src/core/engines/fake.ts
index aedc07e..8b577cd 100644
--- a/src/core/engines/fake.ts
+++ b/src/core/engines/fake.ts
@@ -2,6 +2,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'
import { L } from '../../shared/lang'
import { memorySystem } from '../memory'
+import { curatorSystem } from '../wiki-curator'
import { routerSystem } from '../router'
import type { Engine, EngineEvent, Turn } from './types'
@@ -26,6 +27,8 @@ export function fakeEngine(id: Engine['id'], opts: { delayMs?: number; reply?: (
reply = JSON.stringify(fakeRoute(turn.prompt))
} else if (turn.system === memorySystem()) {
reply = JSON.stringify(fakeConsolidation(turn.prompt))
+ } else if (turn.system === curatorSystem()) {
+ reply = JSON.stringify(fakeCuration(turn.prompt))
} else if (opts.reply) {
reply = opts.reply(turn)
} else if (turn.mcpUrl && (turn.system.includes('## Pra montar agentes') || turn.system.includes('## For building agents'))) {
@@ -174,3 +177,18 @@ export async function callTool(url: string, name: string, args: Record<string, u
await client.close()
}
}
+
+// The wiki's curator, for trying it without an engine: a page the stretch names gets a line
+// under History; a stretch with numbers or a decision becomes a page of its own.
+function fakeCuration(prompt: string): { guardar: boolean; motivo: string; titulo_fonte: string; mudancas: Record<string, string>[] } {
+ const stretch = prompt.split(/\n## [^\n]*(?:Trecho|Stretch)[^\n]*\n/)[1]?.split('\n\nResponda')[0]?.split('\n\nReply')[0] ?? ''
+ const titles = [...prompt.matchAll(/^- \[\[([^\]]+)\]\]/gm)].map((m) => m[1]!)
+ const named = titles.find((t) => t.toLowerCase().split(/\s+/).filter((w) => w.length >= 5).some((w) => stretch.toLowerCase().includes(w)))
+ const plain = stretch.replace(/\*\*[^*]+\*\* \([^)]*\): /g, '').replace(/\s+/g, ' ').trim()
+ const line = plain.length > 160 ? `${plain.slice(0, 157)}…` : plain
+ const day = new Date().toLocaleDateString('pt-BR', { day: '2-digit', month: '2-digit' })
+ const mudancas: Record<string, string>[] = []
+ if (named) mudancas.push({ op: 'append', pagina: named, secao: L('Histórico', 'History'), texto: `- **${day}:** ${line}` })
+ if (/\d|decid|fech|guarda/i.test(plain) && !named) mudancas.push({ op: 'create', pagina: plain.split(/[.!?:]/)[0]!.split(' ').slice(0, 5).join(' '), tipo: L('Assunto', 'Topic'), texto: `${line}\n\n## ${L('Detalhes', 'Details')}\n- ${line}` })
+ return { guardar: mudancas.length > 0, motivo: L('Um fato que vale lembrar.', 'A fact worth remembering.'), titulo_fonte: plain.split(/[.!?]/)[0]!.slice(0, 60) || L('Trecho de conversa', 'Conversation excerpt'), mudancas }
+}
diff --git a/src/core/index.ts b/src/core/index.ts
index f614525..cd1724f 100644
--- a/src/core/index.ts
+++ b/src/core/index.ts
@@ -1,15 +1,16 @@
// The core runs in an Electron utility process: database, engines and runs
// live here so the window never waits on agent work. The renderer talks to it
// over a MessagePort handed out by the main process.
+import { createHash } from 'node:crypto'
import { execFile, spawn } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { userInfo } from 'node:os'
-import { join } from 'node:path'
+import { basename, join } from 'node:path'
import { randomUUID } from 'node:crypto'
import type { MessagePortMain } from 'electron'
import { L, langOf, locale, setLang, type Lang } from '../shared/lang'
import type { Api, CoreEvent, Method, Request, Wire } from '../shared/rpc'
-import { channelName, ENGINES, inQuietHours, modelInfo, rememberModels, WEBHOOK_PORT, type Account, type AccountEngine, type Agent, type BrowserReply, type Message, type EngineId, type EngineStatus, type Settings } from '../shared/types'
+import { channelName, ENGINES, inQuietHours, modelInfo, rememberModels, usable, WEBHOOK_PORT, type Account, type AccountEngine, type Agent, type BrowserReply, type Message, type EngineId, type EngineStatus, type Settings } from '../shared/types'
import { listModels, quietClaude, quietCodex, withChoice } from './harness'
import { cleanLook } from './agent-look'
import { Db } from './db'
@@ -33,6 +34,10 @@ import { GitHub } from './github'
import { report } from './report'
import { usage } from './usage'
import { Skills } from './skills'
+import { Wiki } from './wiki'
+import { WikiCurator } from './wiki-curator'
+import { WikiReviewer } from './wiki-review'
+import { extractFile, extractLink } from './wiki-extract'
import { backup, backupIfDue, exportTeam, importTeam } from './team'
import { applyForeignTeam, readForeignZip } from './agent-import'
import { zipFromBuffer, zipFromFile } from './zip'
@@ -246,6 +251,7 @@ const notifyAll = (title: string, body: string, conversationId?: string): void =
type ToMain =
| { type: 'open'; url: string }
| { type: 'open_path'; path: string }
+ | { type: 'wiki_dir'; path: string } // the wiki's folder, which the app may open
| { type: 'notify'; title: string; body: string; conversationId?: string; kind?: 'approval' | 'question' | 'done'; sound?: boolean }
| { type: 'login_item'; open: boolean }
| { type: 'busy'; busy: boolean }
@@ -433,6 +439,39 @@ const routines = new Routines({
})
const skills = new Skills({ db, emit, notify: (title, body) => notifyAll(title, body) })
+// The wiki's folder is the truth (Markdown, as Obsidian opens it); TUCANO_WIKI points it elsewhere.
+// The default folder keeps wiki.db; another folder gets an index of its own, so going back finds the old one.
+const wikiHome = join(dataDir, 'wiki')
+const wikiIndex = (dir: string): string => (dir === wikiHome ? join(dataDir, 'wiki.db') : join(dataDir, `wiki-${createHash('sha256').update(dir).digest('hex').slice(0, 12)}.db`))
+const wikiDir = (): string => process.env['TUCANO_WIKI'] || settings().wikiDir || wikiHome
+const wiki = new Wiki({ dir: wikiDir(), indexPath: wikiIndex(wikiDir()), onChange: () => emit({ type: 'wiki' }) })
+wiki.init()
+toMain({ type: 'wiki_dir', path: wiki.dir })
+// The curator reads the conversations with the memory's cheap model, and keeps what lasts.
+const wikiLlm = async (system: string, prompt: string): Promise<string> => {
+ const s = settings()
+ const model = usable(modelInfo(s.memoryModel)) ?? modelInfo('haiku')!
+ const st = s.engines[model.engine]
+ if (!st.installed || !st.loggedIn) throw new Error(L(`O ${ENGINES[model.engine].label} não está pronto pra organizar a wiki.`, `${ENGINES[model.engine].label} isn't ready to organize the wiki.`))
+ const cwd = join(dataDir, 'agents', '_wiki')
+ mkdirSync(cwd, { recursive: true })
+ const started = Date.now()
+ let text = ''
+ for await (const ev of engineImpls[model.engine].run({ model: model.id, effort: 'low', system, prompt, cwd, signal: AbortSignal.timeout(180_000) })) {
+ if (ev.type === 'text') text += ev.delta
+ else if (ev.type === 'done') {
+ text = ev.text || text
+ db.addReceipt({ ...ev.usage, model: model.id, ms: Date.now() - started, messageId: 'wiki', agentId: 'wiki', engine: model.engine, at: Date.now() })
+ } else if (ev.type === 'error') throw new Error(ev.message)
+ }
+ return text
+}
+const curator = new WikiCurator({ wiki, db, settings, emitMessage: (message) => emit({ type: 'message', message }), llm: wikiLlm })
+// The review: by hand, or once a week when asked (checked every hour).
+const reviewer = new WikiReviewer({ wiki, settings, llm: wikiLlm })
+setInterval(() => {
+ if (reviewer.due()) void reviewer.review().then(() => emit({ type: 'wiki' }))
+}, 3600_000).unref()
const runner = new Runner({
db,
@@ -449,6 +488,8 @@ const runner = new Runner({
...(serverMode ? {} : { apps: desktopApps }),
routines,
skills,
+ wiki,
+ wikiCurator: curator,
models: () => availableModels(settings(), listed),
// Approvals and questions reach the phone with their buttons, through toPhone; a finished reply stays on the Mac.
notify: (title, body, conversationId, kind) => (kind ? toMain({ type: 'notify', title, body, conversationId, kind, sound: settings().sounds !== false }) : notifyAll(title, body, conversationId)),
@@ -928,6 +969,73 @@ const api: Api = {
saveRoutine: ({ routine }) => routines.save(routine),
removeRoutine: ({ id }) => routines.remove(id),
+ wiki: () => ({ dir: wiki.dir, pages: wiki.list(), kinds: wiki.kinds(), log: wiki.log(), pending: [...wiki.changes('pending'), ...wiki.changes('conflict')].filter((c) => c.by !== 'review').length, findings: wiki.findings().length, server: serverMode, graph: wiki.graph(), recent: wiki.recent(), sources: wiki.sourceCount() }),
+ wikiPage: ({ title }) => wiki.page(title) ?? null,
+ wikiSearch: ({ q }) => wiki.search(q, 20),
+ wikiSave: ({ title, body, kind, expectedHash, rename }) => wiki.save({ title, body, by: 'me', byName: settings().workspaceName || L('Você', 'You'), ...(kind !== undefined ? { kind } : {}), ...(expectedHash !== undefined ? { expectedHash } : {}), ...(rename ? { rename } : {}) }),
+ wikiRemove: ({ title }) => wiki.remove(title, 'me', settings().workspaceName || L('Você', 'You')),
+ wikiHistory: ({ title }) => wiki.history(title),
+ wikiRestore: ({ id }) => wiki.restore(id, 'me', settings().workspaceName || L('Você', 'You')),
+ wikiSchema: () => wiki.schema(),
+ wikiSaveSchema: ({ text }) => wiki.saveSchema(text),
+ wikiChanges: ({ state }) => wiki.changes(state),
+ wikiChange: ({ id }) => wiki.change(id) ?? null,
+ wikiApplyChange: ({ id }) => wiki.applyChange(id, settings().workspaceName || L('Você', 'You')),
+ wikiRefuseChange: ({ id }) => wiki.refuseChange(id),
+ wikiUndoChange: ({ id }) => wiki.undoChange(id, settings().workspaceName || L('Você', 'You')),
+ wikiSources: () => wiki.sources(),
+ wikiSource: ({ id }) => wiki.source(id) ?? null,
+ wikiKeepMessage: async ({ messageId }) => (await curator.keepMessage(messageId)).length,
+ wikiRedoChange: async ({ id }) => (await curator.redo(id)).length,
+ wikiAddFile: async ({ name, data }) => {
+ const buf = Buffer.from(data, 'base64')
+ const text = await extractFile(name, buf)
+ const src = wiki.addSource({ title: name, text, kind: 'file', file: { name, data: buf }, by: 'me', status: 'reading' })
+ void curator.ingest(src.id)
+ return src
+ },
+ wikiAddLink: async ({ url }) => {
+ const page = await extractLink(url.trim())
+ const src = wiki.addSource({ title: page.title, text: `${url.trim()}\n\n${page.text}`, kind: 'link', origin: { url: url.trim() }, by: 'me', status: 'reading' })
+ void curator.ingest(src.id)
+ return src
+ },
+ wikiAddNote: ({ text, title }) => {
+ const first = text.trim().split('\n')[0]!.replace(/^#+\s*/, '').slice(0, 60)
+ const src = wiki.addSource({ title: title?.trim() || first || L('Anotação', 'Note'), text, kind: 'note', by: 'me', status: 'reading' })
+ void curator.ingest(src.id)
+ return src
+ },
+ wikiOpenOriginal: ({ id }) => {
+ const p = wiki.originalPath(id)
+ if (!p || !existsSync(p)) return null
+ if (serverMode) return { name: basename(p), data: readFileSync(p).toString('base64') }
+ toMain({ type: 'open_path', path: p })
+ return null
+ },
+ wikiIngestAgain: ({ id }) => void curator.ingest(id),
+ wikiReview: () => reviewer.status(),
+ wikiRunReview: () => {
+ void reviewer.review().then(() => emit({ type: 'wiki' }))
+ emit({ type: 'wiki' })
+ },
+ wikiDismissFinding: ({ id }) => wiki.dismissFinding(id),
+ wikiImport: ({ dir }) => wiki.importVault(dir, settings().workspaceName || L('Você', 'You')),
+ setWikiCapture: ({ conversationId, on }) => {
+ db.setWikiCapture(conversationId, on)
+ const c = db.conversation(conversationId)
+ if (c) emit({ type: 'conversation', conversation: c })
+ },
+ setWikiDir: async ({ dir }) => {
+ const next = dir?.trim() || wikiHome
+ if (!existsSync(next)) throw new Error(L('Essa pasta não existe.', "That folder doesn't exist."))
+ db.setSettings({ wikiDir: next === wikiHome ? undefined : next })
+ wiki.relocate(next, wikiIndex(next))
+ toMain({ type: 'wiki_dir', path: next })
+ emit({ type: 'settings', settings: settings() })
+ return next
+ },
+ openWikiFolder: () => (serverMode ? undefined : toMain({ type: 'open_path', path: wiki.dir })),
runRoutine: ({ id }) => routines.runNow(id),
refreshEngines: () => {
diff --git a/src/core/runs.ts b/src/core/runs.ts
index 9e1c688..f898887 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -4,9 +4,10 @@ import { randomUUID } from 'node:crypto'
import { L, locale } from '../shared/lang'
import type { CoreEvent } from '../shared/rpc'
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
-import { ACCESS_REQUEST, CACHE_READ_WEIGHT, describeSchedule, workIn, ENGINES, ERRORS_STOP, usable, modelInfo, REPEAT_STOP, REPEAT_WARN, RUN_BUDGET_PCT, RUN_STALL_MINUTES, IMAGE_MIMES, MAX_IMAGE_BYTES, MAX_IMAGES_PER_MESSAGE, type Account, type Agent, type Approval, type Artifact, type ImageUpload, type Connector, type ConnectorTool, type Conversation, type EngineId, type Message, type Quota, type Receipt, type Routine, type Run, type RunStatus, type Settings, type Step } from '../shared/types'
+import { ACCESS_REQUEST, CACHE_READ_WEIGHT, describeSchedule, workIn, ENGINES, ERRORS_STOP, usable, modelInfo, REPEAT_STOP, REPEAT_WARN, RUN_BUDGET_PCT, RUN_STALL_MINUTES, IMAGE_MIMES, MAX_IMAGE_BYTES, MAX_IMAGES_PER_MESSAGE, type Account, type Agent, type Approval, type Artifact, type ImageUpload, type Connector, type ConnectorTool, type Conversation, type EngineId, type Message, type Quota, type Receipt, type Routine, type Run, type RunStatus, type Settings, type Step, wikiAccess } from '../shared/types'
import { HISTORY_LIMIT, mentioned, systemPrompt, transcriptBlocks } from './context'
import { BUSCAR_MEMORIAS, LEMBRAR, type Memories } from './memory'
+import { WIKI_TOOL_NAMES, WIKI_TOOLS, wikiCall, type Wiki } from './wiki'
import { BROWSER_TOOL_NAMES, browserStep, browserTools, NAVEGADOR, type Browser } from './browser'
import { APP_TOOL_NAMES, APPS, appStep, appTools, type DesktopApps } from './apps'
import { COMPUTER_TOOL_NAMES, computerTools, stepFor, type Computers } from './computer'
@@ -76,6 +77,8 @@ export interface RunnerDeps {
github?: Pick<GitHub, 'pushable' | 'openPr'> // without it, agents can't open PRs
skills?: Pick<Skills, 'forAgent' | 'read' | 'propose'> // without it, agents have no skills
models?: () => { id: string; label: string }[] // what the Tuca may propose; without it, the plans' listed models
+ wiki?: Pick<Wiki, 'indexText' | 'search' | 'page' | 'count' | 'kinds'> // without it, agents have no wiki
+ wikiCurator?: { afterReply(conversationId: string): void } // reads the conversation after a reply, to keep what lasts
}
// What the runner needs from the connector manager.
@@ -549,6 +552,8 @@ export class Runner {
const routines = this.deps.gateway ? this.deps.routines : undefined
const skills = this.deps.gateway ? this.deps.skills : undefined
const mySkills = skills?.forAgent(agent.id) ?? []
+ // The wiki: for agents that may read it, once it has a page.
+ const wiki = this.deps.gateway && this.deps.wiki && wikiAccess(agent) !== 'none' && this.deps.wiki.count() > 0 ? this.deps.wiki : undefined
const control: Control = { ctl: new AbortController() }
this.controllers.set(msg.id, control)
@@ -668,6 +673,7 @@ export class Runner {
...(apps ? appTools(agent) : []),
...(routines ? [AGENDAR, CANCELAR] : []),
...(skills ? [...(mySkills.length ? [LER_SKILL] : []), PROPOR_SKILL] : []),
+ ...(wiki ? WIKI_TOOLS : []),
...[...exposed].map(([name, { connector, tool }]): ToolDef => {
const schema = tool.inputSchema as ToolDef['inputSchema']
if (tool.cls !== 'sensitive') return { name, description: `[${connector.name}] ${tool.description}`, inputSchema: schema }
@@ -747,6 +753,12 @@ export class Runner {
return textResult(r.reply)
}
+ if (wiki && WIKI_TOOL_NAMES.has(name)) {
+ const r = wikiCall(wiki, name, args)
+ addSteps({ id: randomUUID(), label: r.step.label, detail: r.step.detail, status: 'done' })
+ return textResult(r.text, r.error)
+ }
+
if (skills && SKILL_TOOL_NAMES.has(name)) {
const r = name === LER_SKILL.name ? skills.read(agent, args) : skills.propose(db.agent(agent.id) ?? agent, args)
if (r.skill) addSteps({ id: randomUUID(), label: name === LER_SKILL.name ? L('Leu a skill', 'Read the skill') : L('Propôs uma skill', 'Proposed a skill'), detail: r.skill.name, status: 'done' })
@@ -1109,6 +1121,7 @@ export class Runner {
web: agent.web !== false,
routines: routines?.forAgent(agent.id),
skills: skills && mySkills,
+ wiki: wiki ? { pages: wiki.count(), kinds: wiki.kinds() } : undefined,
publish: repos,
builder: builds ? builderSection(settings, { models: this.deps.models?.() ?? availableModels(settings), connectors: this.deps.connectors?.list() ?? [], team: db.agents().filter((a) => !a.archived && a.kind !== 'tuca'), own: agent.modelId }) : undefined
}),
@@ -1244,6 +1257,7 @@ export class Runner {
const updated = db.agent(agent.id)
if (updated) emit({ type: 'agent', agent: updated })
void memory?.consolidate(conv.id)
+ if (!opts.routine && msg.run?.status === 'done') this.deps.wikiCurator?.afterReply(conv.id)
return msg
}
diff --git a/src/core/wiki-curator.ts b/src/core/wiki-curator.ts
new file mode 100644
index 0000000..bcaa9e9
--- /dev/null
+++ b/src/core/wiki-curator.ts
@@ -0,0 +1,280 @@
+// The wiki's curator: after a conversation moves on, it reads what was said and decides if
+// something lasting came up (a decision, a fact about a person or a project, a result worth
+// keeping). If so, the exchange is kept as a source, as it was, and the pages are brought up
+// to date in a change package: a new page goes in right away; changing a page that exists
+// goes in or waits for you, as the wiki's settings say. The conversation shows what was kept,
+// with Undo. A message can also be kept on purpose ("Keep in the wiki"), and "guarda isso"
+// said in the conversation makes the curator keep it.
+import { L } from '../shared/lang'
+import type { Agent, Message, Settings, WikiChange, WikiOp } from '../shared/types'
+import { ftsQuery } from './wiki'
+import type { Wiki } from './wiki'
+
+const QUIET_MS = 20_000 // a conversation that went quiet this long gets read
+const MAX_MESSAGES = 14
+const MIN_CHARS = 160 // less than this said since the last read: nothing to keep
+const MAX_PAGE_CHARS = 3_000
+const DOC_PART = 30_000 // a long document is read in parts this size, one after the other
+
+export interface CuratorDeps {
+ wiki: Wiki
+ db: { conversation(id: string): { id: string; kind: string; name: string; wikiCapture?: boolean } | undefined; messagesAfter(conversationId: string, at: number): Message[]; message(id: string): Message | undefined; saveMessage(m: Message): void; agents(): Agent[] }
+ settings: () => Settings
+ llm: (system: string, prompt: string) => Promise<string> // a cheap model, chosen inside; throws when none is ready
+ emitMessage: (m: Message) => void
+}
+
+export const curatorSystem = (): string =>
+ L(
+ `Você é o curador da wiki de um time. A wiki guarda o que vale lembrar por muito tempo, em páginas ligadas por [[Título]]: pessoas, clientes, projetos, assuntos e decisões.
+
+Você recebe as regras da wiki (o esquema), o índice das páginas, algumas páginas que podem ter a ver, e um trecho novo (uma conversa ou uma mensagem). Decida se o trecho traz algo durável:
+- uma decisão ("vamos fechar com a Construtora Alpha");
+- um fato que continua valendo sobre uma pessoa, um cliente ou um projeto (contato, preferência, prazo, valor, situação);
+- o resultado de um trabalho ou de uma pesquisa (um roteiro, uma comparação, um orçamento);
+- algo que a pessoa pediu pra guardar ("guarda isso", "anota na wiki").
+Não guarde: conversa fiada, perguntas sem resposta, o que só importa nesta conversa, tarefas em andamento sem conclusão.
+
+Se valer, escreva as mudanças:
+- "create": uma página nova, inteira, no formato do esquema (uma frase de resumo no começo; seções com ##; [[links]] pras outras páginas). Só crie se não houver página sobre isso no índice.
+- "append": acrescente um trecho curto numa seção de uma página que existe (a seção é criada se faltar). Prefira isso a reescrever.
+- "replace": troque um trecho exato que ficou errado ou velho. "old" tem que estar na página, letra por letra.
+Escreva só o que é novo: o que já está numa página (inclusive em outra) não se repete; ligue com [[link]]. Não invente nem complete. Datas no formato dd/mm. Pouco e certo é melhor que muito.
+
+Responda só com JSON:
+{"guardar": true|false, "motivo": "uma frase", "titulo_fonte": "título curto do trecho", "mudancas": [{"op": "create"|"append"|"replace", "pagina": "Título", "tipo": "Pessoa|Projeto|Assunto|Decisão", "secao": "Histórico", "texto": "markdown", "old": "trecho exato", "new": "trecho novo"}]}`,
+ `You curate a team's wiki. The wiki keeps what's worth remembering for a long time, as pages linked with [[Title]]: people, clients, projects, topics and decisions.
+
+You get the wiki's rules (the schema), the page index, a few pages that may be related, and a new stretch (a conversation or a message). Decide if the stretch brings something lasting:
+- a decision ("we're going with Alpha Builders");
+- a fact that keeps holding about a person, a client or a project (contact, preference, deadline, price, status);
+- the result of a piece of work or research (a plan, a comparison, a quote);
+- something the person asked to keep ("save this", "put it in the wiki").
+Don't keep: small talk, unanswered questions, what matters only in this conversation, tasks in progress with no outcome.
+
+If it's worth it, write the changes:
+- "create": a new page, whole, in the schema's format (a summary sentence first; ## sections; [[links]] to other pages). Only create it if no page in the index is about it.
+- "append": add a short passage under a section of an existing page (the section is made if missing). Prefer this to rewriting.
+- "replace": swap an exact passage that became wrong or old. "old" must be on the page, letter by letter.
+Write only what is new: what a page already says (even another page) isn't repeated; link to it with [[link]]. Don't make things up or fill gaps. Dates written out, like Jan 12 or Nov 3 (never 12/01). Little and right beats a lot.
+
+Reply with JSON only:
+{"guardar": true|false, "motivo": "one sentence", "titulo_fonte": "short title of the stretch", "mudancas": [{"op": "create"|"append"|"replace", "pagina": "Title", "tipo": "Person|Project|Topic|Decision", "secao": "History", "texto": "markdown", "old": "exact passage", "new": "new passage"}]}`
+ )
+
+// Lenient: models sometimes wrap the JSON in a fence or add a word around it.
+export function parseCuration(text: string): { worth: boolean; reason: string; title: string; ops: WikiOp[] } | null {
+ const json = text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)
+ if (!json) return null
+ let v: Record<string, unknown>
+ try {
+ v = JSON.parse(json) as Record<string, unknown>
+ } catch {
+ return null
+ }
+ const str = (x: unknown): string => (typeof x === 'string' ? x.trim() : '')
+ const ops = parseOps(v['mudancas'] ?? v['changes'])
+ const worth = v['guardar'] === true || v['worth'] === true
+ return { worth: worth && ops.length > 0, reason: str(v['motivo'] ?? v['reason']), title: str(v['titulo_fonte'] ?? v['source_title']) || L('Trecho de conversa', 'Conversation excerpt'), ops }
+}
+
+// The changes a model wrote, in the JSON both the curator and the review use.
+export function parseOps(list: unknown): WikiOp[] {
+ const str = (x: unknown): string => (typeof x === 'string' ? x.trim() : '')
+ const ops: WikiOp[] = []
+ for (const c of Array.isArray(list) ? list : []) {
+ const o = c as Record<string, unknown>
+ const op = str(o['op'])
+ const page = str(o['pagina'] ?? o['page']).replace(/^\[\[|\]\]$/g, '')
+ if (!page || !['create', 'append', 'replace'].includes(op)) continue
+ if (op === 'replace' && !str(o['old'])) continue
+ if (op !== 'replace' && !str(o['texto'] ?? o['text'])) continue
+ ops.push({
+ op: op as WikiOp['op'],
+ page,
+ ...(str(o['tipo'] ?? o['kind']) ? { kind: str(o['tipo'] ?? o['kind']) } : {}),
+ ...(str(o['secao'] ?? o['section']) ? { section: str(o['secao'] ?? o['section']) } : {}),
+ ...(op !== 'replace' ? { text: str(o['texto'] ?? o['text']) } : { old: String(o['old']), new: String(o['new'] ?? '') })
+ })
+ }
+ return ops
+}
+
+export class WikiCurator {
+ private timers = new Map<string, ReturnType<typeof setTimeout>>()
+ private running = new Map<string, Promise<void>>()
+
+ constructor(private deps: CuratorDeps) {}
+
+ // After a reply: read the conversation once it goes quiet, if capture is on.
+ afterReply(conversationId: string, quietMs = QUIET_MS): void {
+ if (this.deps.settings().wikiCapture === false) return
+ const t = this.timers.get(conversationId)
+ if (t) clearTimeout(t)
+ this.timers.set(
+ conversationId,
+ setTimeout(() => {
+ this.timers.delete(conversationId)
+ void this.read(conversationId)
+ }, quietMs)
+ )
+ }
+
+ // Reads what came since the last time; one at a time per conversation.
+ read(conversationId: string): Promise<void> {
+ const cur = this.running.get(conversationId)
+ if (cur) return cur
+ const p = this.doRead(conversationId)
+ .catch((e: unknown) => console.error('[wiki]', e))
+ .finally(() => this.running.delete(conversationId))
+ this.running.set(conversationId, p)
+ return p
+ }
+
+ async idle(): Promise<void> {
+ while (this.running.size) await Promise.all(this.running.values())
+ }
+
+ private name(m: Message): string {
+ const me = this.deps.settings().workspaceName || L('Você', 'You')
+ if (m.author.kind === 'me') return me
+ if (m.author.kind === 'routine') return L('Rotina', 'Routine')
+ const id = m.author.kind === 'agent' ? m.author.id : ''
+ return this.deps.db.agents().find((a) => a.id === id)?.name ?? L('Agente', 'Agent')
+ }
+ private excerpt(messages: Message[]): string {
+ return messages.map((m) => `**${this.name(m)}** (${new Date(m.at).toLocaleString('pt-BR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}): ${m.text.trim()}`).join('\n\n')
+ }
+
+ private async doRead(conversationId: string): Promise<void> {
+ const { db, wiki } = this.deps
+ const conv = db.conversation(conversationId)
+ if (!conv || conv.wikiCapture === false) return // a conversation kept out of the wiki
+ const since = wiki.mark(conversationId)
+ // what was already kept on purpose ("Keep in the wiki") isn't read a second time
+ const kept = wiki.readMessages(conversationId)
+ const all = db.messagesAfter(conversationId, since).filter((m) => (m.author.kind === 'me' || m.author.kind === 'agent') && m.text.trim() && m.run?.status !== 'working')
+ const fresh = all.filter((m) => !kept.has(m.id))
+ if (!fresh.length) return all.length ? wiki.setMark(conversationId, all.at(-1)!.at) : undefined
+ const stretch = fresh.slice(-MAX_MESSAGES)
+ const last = stretch.at(-1)!
+ if (stretch.reduce((n, m) => n + m.text.length, 0) < MIN_CHARS) return wiki.setMark(conversationId, last.at)
+ await this.curate({ messages: stretch, kind: 'conversation', conversationId, force: false })
+ wiki.setMark(conversationId, last.at)
+ }
+
+ // A message kept on purpose: with the one it answers, if it's a reply.
+ async keepMessage(messageId: string): Promise<WikiChange[]> {
+ const m = this.deps.db.message(messageId)
+ if (!m) throw new Error(L('Essa mensagem não existe mais.', 'That message no longer exists.'))
+ const before = this.deps.db.messagesAfter(m.conversationId, 0).filter((x) => x.at < m.at && x.author.kind === 'me').at(-1)
+ return this.curate({ messages: before && m.author.kind !== 'me' ? [before, m] : [m], kind: 'message', conversationId: m.conversationId, force: true })
+ }
+
+ // A package that ran into a newer page: made again on the page as it is now; when a passage
+ // it swaps is gone, written again from its source.
+ async redo(changeId: string): Promise<WikiChange[]> {
+ const { wiki } = this.deps
+ const c = wiki.change(changeId)
+ if (!c || c.state !== 'conflict') return []
+ const again = wiki.rebaseChange(changeId)
+ if (again) return [again]
+ const src = c.source && wiki.source(c.source.id)
+ if (!src) throw new Error(L('A fonte dessa mudança não existe mais.', "This change's source no longer exists."))
+ wiki.refuseChange(changeId)
+ return this.curate({ text: src.text.replace(/^# .*\n+/, ''), plain: src.text, kind: 'message', conversationId: src.origin.conversationId ?? '', force: true, source: src, messages: [] })
+ }
+
+ // A file, a link or a note brought to the wiki: read (in parts, if long) and turned into pages.
+ ingest(sourceId: string): Promise<void> {
+ const cur = this.running.get(`source:${sourceId}`)
+ if (cur) return cur
+ const p = this.doIngest(sourceId).finally(() => this.running.delete(`source:${sourceId}`))
+ this.running.set(`source:${sourceId}`, p)
+ return p
+ }
+
+ private async doIngest(sourceId: string): Promise<void> {
+ const { wiki } = this.deps
+ const src = wiki.source(sourceId)
+ if (!src) return
+ wiki.setSourceStatus(sourceId, 'reading')
+ try {
+ const body = src.text.trimStart().replace(/^# .*\n+/, '')
+ const parts: string[] = []
+ for (let at = 0; at < body.length; at += DOC_PART) {
+ // cut at a paragraph near the edge, so a part doesn't end mid-sentence
+ let end = Math.min(body.length, at + DOC_PART)
+ if (end < body.length) {
+ const brk = body.lastIndexOf('\n\n', end)
+ if (brk > at + DOC_PART / 2) end = brk
+ }
+ parts.push(body.slice(at, end))
+ at = end - DOC_PART
+ }
+ let made = 0
+ for (const [k, part] of parts.entries()) {
+ const head = parts.length > 1 ? L(`(parte ${k + 1} de ${parts.length} de "${src.title}")\n\n`, `(part ${k + 1} of ${parts.length} of "${src.title}")\n\n`) : ''
+ made += (await this.curate({ messages: [], kind: src.kind === 'note' ? 'message' : 'document', conversationId: '', force: src.kind === 'note', text: head + part, plain: part, source: src })).length
+ }
+ wiki.setSourceStatus(sourceId, 'done', { changes: made })
+ } catch (e) {
+ wiki.setSourceStatus(sourceId, 'failed', { error: e instanceof Error ? e.message : String(e) })
+ }
+ }
+
+ private async curate(p: { messages: Message[]; kind: 'conversation' | 'message' | 'document'; conversationId: string; force: boolean; text?: string; plain?: string; source?: { id: string; file: string; title: string } }): Promise<WikiChange[]> {
+ const { wiki } = this.deps
+ const text = p.text ?? this.excerpt(p.messages)
+ const plain = p.plain ?? p.messages.map((m) => m.text).join(' ')
+ // The pages it may touch: the ones the words of the stretch find.
+ const words = ftsQuery(plain, true)
+ const related = words ? wiki.search(plain.slice(0, 600), 4) : []
+ const pages = related.map((h) => wiki.page(h.title)).filter((x): x is NonNullable<typeof x> => !!x)
+ // What already waits for approval on those pages, so it isn't proposed twice or fought over.
+ const titles = new Set(pages.map((pg) => pg.title))
+ const waiting = wiki.changes('pending').flatMap((c) => c.ops.filter((o) => titles.has(o.page)).map((o) => `- [[${o.page}]] ${o.op}${o.section ? ` (${o.section})` : ''}: ${o.op === 'replace' ? `"${o.old}" → "${o.new}"` : (o.text ?? '').slice(0, 300)}`))
+ const owner = this.deps.settings().workspaceName
+ const prompt = [
+ ...(owner ? [L(`A wiki é de ${owner} ("eu", "você" nas conversas; a empresa ou o nome dela nos documentos). Não crie página sobre ${owner}.`, `The wiki belongs to ${owner} ("I", "you" in conversations; their company or name in documents). Don't make a page about ${owner}.`)] : []),
+ L('## Esquema da wiki', "## The wiki's schema"),
+ wiki.schema().trim(),
+ L('## Índice', '## Index'),
+ wiki.indexText().trim() || L('(a wiki está vazia)', '(the wiki is empty)'),
+ ...(pages.length ? [L('## Páginas que podem ter a ver', '## Pages that may be related'), ...pages.map((pg) => `### [[${pg.title}]] (${pg.kind})\n${pg.body.slice(0, MAX_PAGE_CHARS)}`)] : []),
+ ...(waiting.length ? [L('## Mudanças já propostas, esperando aprovação (não repita; se o trecho mudar algo delas, escreva sobre o texto atual da página)', '## Changes already proposed, waiting for approval (don\'t repeat them; if the stretch changes one, write against the page as it is now)'), waiting.join('\n')] : []),
+ p.kind === 'message'
+ ? L('## Trecho que a pessoa pediu pra guardar (guarde)', '## Stretch the person asked to keep (keep it)')
+ : p.kind === 'document'
+ ? L('## Trecho de um documento que a pessoa trouxe pra wiki (guarde o que for durável: pessoas, valores, prazos, decisões, regras)', '## Stretch of a document the person brought to the wiki (keep what lasts: people, amounts, deadlines, decisions, rules)')
+ : L('## Trecho novo da conversa', '## New stretch of the conversation'),
+ text,
+ L('Responda só com o JSON.', 'Reply with the JSON only.')
+ ].join('\n\n')
+ const out = parseCuration(await this.deps.llm(curatorSystem(), prompt))
+ if (!out || (!out.worth && !p.force) || !out.ops.length) return []
+ const source = p.source ?? wiki.addSource({ title: out.title, text, kind: p.kind === 'document' ? 'file' : p.kind, origin: { conversationId: p.conversationId, messageIds: p.messages.map((m) => m.id) }, by: 'auto' })
+ const cite = ` ([[${source.file}|${L('fonte', 'source')}]])`
+ const ops = out.ops.map((o): WikiOp => (o.op === 'append' ? { ...o, text: `${o.text}${cite}` } : o.op === 'create' ? { ...o, text: `${o.text}\n\n${L('Fontes', 'Sources')}: [[${source.file}|${source.title}]]` } : o.op === 'replace' && o.new ? { ...o, new: `${o.new}${cite}` } : o))
+ // New pages go in now; changes to existing ones go in or wait, as the settings say.
+ const exists = (t: string): boolean => !!wiki.page(t)
+ const creates = ops.filter((o) => o.op === 'create' && !exists(o.page))
+ const edits = ops.filter((o) => !creates.includes(o))
+ const me = this.deps.settings().workspaceName || L('Você', 'You')
+ const made: WikiChange[] = []
+ if (creates.length) made.push(wiki.applyChange(wiki.addChange({ ops: creates, sourceId: source.id, by: 'auto', reason: out.reason }).id, L('Curador da wiki', 'Wiki curator')))
+ if (edits.length) {
+ const c = wiki.addChange({ ops: edits, sourceId: source.id, by: 'auto', reason: out.reason })
+ made.push(this.deps.settings().wikiEdits === 'auto' ? wiki.applyChange(c.id, L('Curador da wiki', 'Wiki curator')) : c)
+ }
+ // The reply it came from says so, with what was kept and Undo.
+ const anchor = [...p.messages].reverse().find((m) => m.author.kind === 'agent') ?? p.messages.at(-1)
+ const msg = anchor && this.deps.db.message(anchor.id)
+ if (msg?.run && made.length) {
+ const next: Message = { ...msg, run: { ...msg.run, wikiChanges: [...(msg.run.wikiChanges ?? []), ...made.map((c) => c.id)] } }
+ this.deps.db.saveMessage(next)
+ this.deps.emitMessage(next)
+ }
+ return made
+ }
+}
diff --git a/src/core/wiki-extract.ts b/src/core/wiki-extract.ts
new file mode 100644
index 0000000..665d3ea
--- /dev/null
+++ b/src/core/wiki-extract.ts
@@ -0,0 +1,119 @@
+// What a file or a link says, as text the wiki's curator can read: PDF (unpdf, no worker),
+// Word (mammoth), spreadsheets (exceljs, each sheet a table), CSV, plain text and Markdown;
+// a web page through Readability, so only its main content comes along. All in the core,
+// nothing leaves the computer except the fetch of the link itself.
+import { extname } from 'node:path'
+import { L } from '../shared/lang'
+
+export const MAX_FILE = 20 * 1024 * 1024
+export const MAX_TEXT = 400_000 // characters kept from one source
+const TEXT = new Set(['.txt', '.md', '.markdown', '.json', '.log', '.yml', '.yaml'])
+export const ACCEPTS = ['.pdf', '.docx', '.xlsx', '.csv', ...TEXT]
+
+const clip = (s: string): string => {
+ const t = s.replace(/\r\n/g, '\n').replace(/[ \t]+\n/g, '\n').replace(/\n{3,}/g, '\n\n').trim()
+ return t.length > MAX_TEXT ? `${t.slice(0, MAX_TEXT)}\n\n${L('[o resto do texto foi cortado]', '[the rest of the text was cut]')}` : t
+}
+
+// A grid as a Markdown table; a long one keeps its first rows.
+function table(rows: string[][], max = 400): string {
+ const width = Math.max(0, ...rows.map((r) => r.length))
+ if (!width) return ''
+ const cell = (v: string): string => v.replace(/\|/g, '\\|').replace(/\n/g, ' ').trim()
+ const pad = (r: string[]): string[] => Array.from({ length: width }, (_, k) => cell(r[k] ?? ''))
+ const [head, ...body] = rows
+ const lines = [`| ${pad(head!).join(' | ')} |`, `| ${Array(width).fill('---').join(' | ')} |`, ...body.slice(0, max).map((r) => `| ${pad(r).join(' | ')} |`)]
+ if (body.length > max) lines.push(L(`\n(${body.length - max} linhas a mais não entraram)`, `\n(${body.length - max} more rows left out)`))
+ return lines.join('\n')
+}
+
+export function parseCsv(text: string): string[][] {
+ const rows: string[][] = []
+ const sep = (text.split('\n')[0]!.match(/;/g)?.length ?? 0) > (text.split('\n')[0]!.match(/,/g)?.length ?? 0) ? ';' : ','
+ let row: string[] = []
+ let cur = ''
+ let quoted = false
+ for (let i = 0; i < text.length; i++) {
+ const ch = text[i]!
+ if (quoted) {
+ if (ch === '"' && text[i + 1] === '"') (cur += '"'), i++
+ else if (ch === '"') quoted = false
+ else cur += ch
+ } else if (ch === '"') quoted = true
+ else if (ch === sep) row.push(cur), (cur = '')
+ else if (ch === '\n' || ch === '\r') {
+ if (ch === '\r' && text[i + 1] === '\n') i++
+ row.push(cur), rows.push(row), (row = []), (cur = '')
+ } else cur += ch
+ }
+ if (cur || row.length) row.push(cur), rows.push(row)
+ return rows.filter((r) => r.some((c) => c.trim()))
+}
+
+export async function extractFile(name: string, data: Buffer): Promise<string> {
+ if (data.length > MAX_FILE) throw new Error(L('O arquivo passa de 20 MB.', 'The file is over 20 MB.'))
+ const ext = extname(name).toLowerCase()
+ if (ext === '.pdf') {
+ const { extractText, getDocumentProxy } = await import('unpdf')
+ const pdf = await getDocumentProxy(new Uint8Array(data))
+ const { text } = await extractText(pdf, { mergePages: false })
+ const pages = (Array.isArray(text) ? text : [text]).map((t, k) => `${L('Página', 'Page')} ${k + 1}\n\n${t}`)
+ const out = clip(pages.join('\n\n'))
+ if (out.replace(/(Página|Page) \d+/g, '').trim().length < 20) throw new Error(L('Esse PDF não tem texto (deve ser uma imagem escaneada).', 'This PDF has no text (it must be a scanned image).'))
+ return out
+ }
+ if (ext === '.docx') {
+ const mammoth = await import('mammoth')
+ const { value } = await mammoth.extractRawText({ buffer: data })
+ return clip(value)
+ }
+ if (ext === '.xlsx') {
+ const { default: ExcelJS } = await import('exceljs')
+ const book = new ExcelJS.Workbook()
+ await book.xlsx.load(data as unknown as ArrayBuffer)
+ const parts: string[] = []
+ book.eachSheet((sheet) => {
+ const rows: string[][] = []
+ sheet.eachRow({ includeEmpty: false }, (row) => {
+ const values = (row.values as unknown[]).slice(1)
+ rows.push(values.map((v) => (v == null ? '' : typeof v === 'object' && v && 'text' in v ? String((v as { text: unknown }).text) : typeof v === 'object' && v && 'result' in v ? String((v as { result: unknown }).result) : v instanceof Date ? v.toLocaleDateString('pt-BR') : String(v))))
+ })
+ if (rows.length) parts.push(`## ${sheet.name}\n\n${table(rows)}`)
+ })
+ return clip(parts.join('\n\n'))
+ }
+ if (ext === '.csv') return clip(table(parseCsv(data.toString('utf8'))))
+ if (TEXT.has(ext) || !ext) return clip(data.toString('utf8'))
+ throw new Error(L(`Ainda não leio arquivos ${ext}. Dá pra usar PDF, Word, planilha (.xlsx, .csv) ou texto.`, `I can't read ${ext} files yet. PDF, Word, spreadsheets (.xlsx, .csv) or text work.`))
+}
+
+// A web page's main content, and its title.
+export async function extractLink(url: string, fetcher: typeof fetch = fetch): Promise<{ title: string; text: string }> {
+ if (!/^https?:\/\//i.test(url)) throw new Error(L('O link precisa começar com http:// ou https://.', 'The link must start with http:// or https://.'))
+ const res = await fetcher(url, { headers: { 'user-agent': 'Mozilla/5.0 (Tucano wiki)', accept: 'text/html,application/xhtml+xml,application/pdf;q=0.9,*/*;q=0.8' }, signal: AbortSignal.timeout(30_000), redirect: 'follow' })
+ if (!res.ok) throw new Error(L(`A página respondeu ${res.status}.`, `The page answered ${res.status}.`))
+ const type = res.headers.get('content-type') ?? ''
+ const buf = Buffer.from(await res.arrayBuffer())
+ if (buf.length > MAX_FILE) throw new Error(L('A página passa de 20 MB.', 'The page is over 20 MB.'))
+ const last = new URL(res.url || url).pathname.split('/').pop() || 'arquivo'
+ if (type.includes('pdf')) return { title: decodeURIComponent(last), text: await extractFile(`${last}.pdf`, buf) }
+ if (!type.includes('html')) return { title: decodeURIComponent(last), text: clip(buf.toString('utf8')) }
+ const { parseHTML } = await import('linkedom')
+ const { Readability } = await import('@mozilla/readability')
+ const { document } = parseHTML(buf.toString('utf8'))
+ const article = new Readability(document as unknown as Document).parse()
+ const title = (article?.title || document.querySelector('title')?.textContent || new URL(url).hostname).trim()
+ // Paragraph by paragraph, so the curator sees the shape of the text.
+ const html = article?.content ?? document.body?.innerHTML ?? ''
+ const { document: doc } = parseHTML(`<!doctype html><html><body>${html}</body></html>`)
+ const blocks = [...doc.querySelectorAll('h1,h2,h3,h4,p,li,pre,blockquote,td')].map((e) => {
+ const t = (e.textContent ?? '').replace(/\s+/g, ' ').trim()
+ if (!t) return ''
+ if (/^H\d$/.test(e.tagName)) return `${'#'.repeat(Math.min(4, Number(e.tagName[1]) + 1))} ${t}`
+ if (e.tagName === 'LI') return `- ${t}`
+ return t
+ })
+ const text = clip(blocks.filter(Boolean).join('\n\n') || (article?.textContent ?? ''))
+ if (text.length < 40) throw new Error(L('Não achei texto nessa página (pode precisar de login).', "I found no text on that page (it may need a login)."))
+ return { title, text }
+}
diff --git a/src/core/wiki-review.ts b/src/core/wiki-review.ts
new file mode 100644
index 0000000..9037a28
--- /dev/null
+++ b/src/core/wiki-review.ts
@@ -0,0 +1,219 @@
+// Looking after the wiki: what's broken or missing (found by reading the pages, no model), and
+// what no longer adds up (a cheap model reads what changed since the last review, next to the
+// pages around it). Everything it finds waits for the person; nothing goes in on its own.
+import { L } from '../shared/lang'
+import type { Settings, WikiFinding, WikiOp, WikiPage, WikiReview } from '../shared/types'
+import { parseOps } from './wiki-curator'
+import { linksIn, type Wiki } from './wiki'
+
+export interface ReviewDeps {
+ wiki: Wiki
+ settings: () => Settings
+ llm: (system: string, prompt: string) => Promise<string>
+}
+
+type Found = Omit<WikiFinding, 'id' | 'at' | 'change'> & { key: string; ops?: WikiOp[]; reason?: string }
+
+const WEEK = 7 * 24 * 3600_000
+const MAX_CHARS = 60_000 // of pages shown to the model in one review
+const PAGE_CHARS = 4_000
+const link = (t: string): string => `[[${t}]]`
+const list = (ts: string[]): string => (ts.length <= 3 ? ts.map(link).join(', ') : `${ts.slice(0, 3).map(link).join(', ')} ${L(`e mais ${ts.length - 3}`, `and ${ts.length - 3} more`)}`)
+
+// Names written with capitals ("Construtora Alpha", "Dona Rita"), in the text outside links and code.
+const NAME = /(?<![\p{L}\p{N}])(\p{Lu}[\p{L}\p{N}]+(?:\s+(?:d[aeo]s?\s+|e\s+)?\p{Lu}[\p{L}\p{N}]+){1,3})(?![\p{L}\p{N}])/gu
+function namesIn(body: string): Set<string> {
+ const text = body
+ .replace(/```[\s\S]*?```/g, ' ')
+ .replace(/`[^`\n]*`/g, ' ')
+ .replace(/\[\[[^\]]*\]\]/g, ' · ')
+ .replace(/^#+ .*$/gm, ' · ')
+ .replace(/\*\*[^*\n]*:\*\*/g, ' · ')
+ const out = new Set<string>()
+ for (const line of text.split(/\n|[.!?:;]\s/)) {
+ for (const m of line.matchAll(NAME)) out.add(m[1]!.replace(/\s+/g, ' '))
+ }
+ return out
+}
+
+// What can be found without a model.
+export function lint(wiki: Wiki, owner?: string): Found[] {
+ const pages = wiki
+ .list()
+ .map((p) => wiki.page(p.title))
+ .filter((p): p is WikiPage => !!p)
+ const titles = new Set(pages.map((p) => p.title.toLowerCase()))
+ const out: Found[] = []
+ // links to pages that don't exist
+ const broken = new Map<string, string[]>()
+ for (const p of pages) for (const m of p.missing) broken.set(m, [...(broken.get(m) ?? []), p.title])
+ for (const [name, from] of broken)
+ out.push({ key: `broken:${name.toLowerCase()}`, kind: 'broken', name, pages: from, text: L(`${list(from)} ${from.length === 1 ? 'liga' : 'ligam'} pra ${link(name)}, que ainda não existe.`, `${list(from)} ${from.length === 1 ? 'links' : 'link'} to ${link(name)}, which doesn't exist yet.`) })
+ // pages nothing links to (in a wiki big enough for that to matter), as one finding
+ const alone = pages.length >= 4 ? pages.filter((p) => !p.backlinks.length).map((p) => p.title) : []
+ if (alone.length)
+ out.push({
+ key: `orphan:${[...alone].sort().join('|').toLowerCase()}`,
+ kind: 'orphan',
+ pages: alone,
+ text: alone.length === 1 ? L(`Nenhuma página liga pra ${link(alone[0]!)}.`, `No page links to ${link(alone[0]!)}.`) : L(`Nenhuma página liga pra ${alone.map(link).join(', ')}. Quem chega nelas só chega buscando.`, `No page links to ${alone.map(link).join(', ')}. They're only found by searching.`)
+ })
+ // a name several pages mention, with no page of its own
+ const seen = new Map<string, { name: string; pages: string[] }>()
+ for (const p of pages)
+ for (const n of namesIn(p.body)) {
+ const k = n.toLowerCase()
+ if (titles.has(k) || broken.has(n) || (owner && k.includes(owner.toLowerCase()))) continue
+ const s = seen.get(k) ?? { name: n, pages: [] }
+ if (!s.pages.includes(p.title)) s.pages.push(p.title)
+ seen.set(k, s)
+ }
+ for (const [k, s] of seen) if (s.pages.length >= 3) out.push({ key: `missing:${k}`, kind: 'missing', name: s.name, pages: s.pages, text: L(`**${s.name}** aparece em ${list(s.pages)}, e não tem página.`, `**${s.name}** shows up in ${list(s.pages)}, and has no page.`) })
+ return out
+}
+
+export const reviewSystem = (): string =>
+ L(
+ `Você revisa a wiki de um time: páginas em Markdown ligadas por [[Título]]. Leia as páginas e procure só problemas reais:
+- "contradicao": duas páginas (ou uma página consigo mesma) dizem coisas diferentes sobre o mesmo fato (um valor, uma data, um contato, uma situação);
+- "desatualizada": uma página diz algo que outra, mais nova, mostra que já mudou (ex.: "aguardando resposta" numa página, "contrato assinado" em outra);
+- "duplicada": duas páginas sobre a mesma coisa (mesma pessoa, mesmo projeto) com títulos diferentes;
+- "ligacao": uma página sem ninguém ligando pra ela, que deveria ser citada em outra (diga onde).
+Para cada problema, proponha a correção como mudanças:
+- "replace": troque um trecho exato ("old" tem que estar na página, letra por letra) pelo certo ("new");
+- "append": acrescente um trecho numa seção de uma página.
+Corrija pelo que é mais novo ou tem fonte; na dúvida, não troque: só aponte, sem mudanças. Pra duplicadas, fique com a página que mais páginas ligam (ou a mais completa), leve pra ela todo fato que só a outra tem, sem perder nenhum, e na outra deixe só "Ver [[Título]]". Não invente nada que não esteja nas páginas. Pouco e certo: se nada estiver errado, a lista vem vazia.
+
+Responda só com JSON:
+{"achados": [{"tipo": "contradicao"|"desatualizada"|"duplicada"|"ligacao", "paginas": ["Título"], "explicacao": "uma frase, com [[links]]", "mudancas": [{"op": "replace"|"append", "pagina": "Título", "secao": "Seção", "texto": "markdown", "old": "trecho exato", "new": "trecho novo"}]}]}`,
+ `You review a team's wiki: Markdown pages linked with [[Title]]. Read the pages and look only for real problems:
+- "contradicao": two pages (or a page and itself) say different things about the same fact (an amount, a date, a contact, a status);
+- "desatualizada": a page says something another, newer one shows has changed (e.g. "waiting for an answer" on one page, "contract signed" on another);
+- "duplicada": two pages about the same thing (same person, same project) under different titles;
+- "ligacao": a page nothing links to, that another one should mention (say where).
+For each problem, write the fix as changes:
+- "replace": swap an exact passage ("old" must be on the page, letter by letter) for the right one ("new");
+- "append": add a passage under a section of a page.
+Fix toward what's newer or has a source; when unsure, don't swap: just point it out, with no changes. For duplicates, keep the page more pages link to (or the fuller one), bring into it every fact only the other has, losing none, and leave just "See [[Title]]" in the other. Don't make up anything the pages don't say. Little and right: if nothing is wrong, the list is empty.
+
+Reply with JSON only:
+{"achados": [{"tipo": "contradicao"|"desatualizada"|"duplicada"|"ligacao", "paginas": ["Title"], "explicacao": "one sentence, with [[links]]", "mudancas": [{"op": "replace"|"append", "pagina": "Title", "secao": "Section", "texto": "markdown", "old": "exact passage", "new": "new passage"}]}]}`
+ )
+
+const KINDS: Record<string, WikiFinding['kind']> = { contradicao: 'contradiction', contradiction: 'contradiction', desatualizada: 'stale', stale: 'stale', duplicada: 'duplicate', duplicate: 'duplicate', ligacao: 'link', link: 'link' }
+
+export function parseReview(text: string, wiki: Wiki): Found[] {
+ const json = text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1)
+ let v: Record<string, unknown>
+ try {
+ v = JSON.parse(json) as Record<string, unknown>
+ } catch {
+ return []
+ }
+ const out: Found[] = []
+ for (const a of Array.isArray(v['achados']) ? v['achados'] : Array.isArray(v['findings']) ? v['findings'] : []) {
+ const o = a as Record<string, unknown>
+ const kind = KINDS[String(o['tipo'] ?? o['kind'] ?? '').toLowerCase().normalize('NFD').replace(/\p{M}/gu, '')]
+ const text = String(o['explicacao'] ?? o['explanation'] ?? '').trim()
+ if (!kind || !text) continue
+ const pages = (Array.isArray(o['paginas']) ? o['paginas'] : Array.isArray(o['pages']) ? o['pages'] : []).map((t) => String(t).replace(/^\[\[|\]\]$/g, '').trim()).filter((t) => !!wiki.page(t))
+ // A swap whose passage isn't on the page, or a change to a page that doesn't exist, is dropped.
+ const ops = parseOps(o['mudancas'] ?? o['changes'])
+ .filter((op) => {
+ const pg = op.op !== 'create' ? wiki.page(op.page) : undefined
+ return !!pg && (op.op !== 'replace' || pg.body.includes(op.old!))
+ })
+ // a swap names no section of its own; one the page doesn't have ("raiz") says nothing
+ .map(({ section, ...op }) => (section && op.op === 'append' ? { ...op, section } : op))
+ out.push({ key: `${kind}:${[...pages].sort().join('|').toLowerCase()}:${text.slice(0, 80).toLowerCase()}`, kind, pages, text, ...(ops.length ? { ops, reason: text.replace(/\[\[([^\]|]+)(\|[^\]]*)?\]\]/g, '$1') } : {}) })
+ }
+ return out
+}
+
+export class WikiReviewer {
+ private running: Promise<void> | null = null
+ private error: string | undefined
+
+ constructor(private deps: ReviewDeps) {}
+
+ status(): WikiReview {
+ const at = Number(this.deps.wiki.getMeta('reviewed_at') ?? 0)
+ return { ...(at ? { at } : {}), running: !!this.running, ...(this.error ? { error: this.error } : {}), findings: this.deps.wiki.findings() }
+ }
+
+ // Once a week, when the person asked for that.
+ due(now = Date.now()): boolean {
+ const at = Number(this.deps.wiki.getMeta('reviewed_at') ?? 0)
+ return this.deps.settings().wikiReview === 'weekly' && !this.running && this.deps.wiki.count() >= 3 && now - at >= WEEK
+ }
+
+ review(): Promise<void> {
+ this.running ??= this.run().finally(() => {
+ this.running = null
+ // a failed model read leaves the mark where it was, so the next review reads those pages again
+ if (!this.error) this.deps.wiki.setMeta('reviewed_at', String(Date.now()))
+ this.deps.wiki.setFindings(this.found)
+ })
+ return this.running
+ }
+
+ private found: Found[] = []
+
+ private async run(): Promise<void> {
+ const { wiki } = this.deps
+ const owner = this.deps.settings().workspaceName
+ this.error = undefined
+ this.found = lint(wiki, owner)
+ if (wiki.count() < 2) return
+ try {
+ const asked = await this.ask()
+ // a page the model already said where to link isn't also listed as nobody's
+ const linked = new Set(asked.filter((f) => f.kind === 'link').flatMap((f) => [...f.pages, ...linksIn(f.text), ...(f.ops ?? []).flatMap((o) => linksIn(o.text ?? o.new ?? ''))].map((t) => t.toLowerCase())))
+ const orphan = this.found.find((f) => f.kind === 'orphan')
+ if (orphan) {
+ orphan.pages = orphan.pages.filter((t) => !linked.has(t.toLowerCase()))
+ if (!orphan.pages.length) this.found = this.found.filter((f) => f !== orphan)
+ else if (linked.size) Object.assign(orphan, { key: `orphan:${[...orphan.pages].sort().join('|').toLowerCase()}`, text: L(`Nenhuma página liga pra ${orphan.pages.map(link).join(', ')}.`, `No page links to ${orphan.pages.map(link).join(', ')}.`) })
+ }
+ this.found.push(...asked)
+ } catch (e) {
+ this.error = e instanceof Error ? e.message : String(e)
+ }
+ }
+
+ // What changed since the last review, and the pages around it; the first review reads it all.
+ private async ask(): Promise<Found[]> {
+ const { wiki } = this.deps
+ const since = Number(wiki.getMeta('reviewed_at') ?? 0)
+ const all = wiki.list()
+ const changed = all.filter((p) => p.updatedAt > since).sort((a, b) => b.updatedAt - a.updatedAt)
+ if (!changed.length) return []
+ const picked = new Map<string, WikiPage>()
+ const add = (t: string): void => {
+ if (picked.has(t.toLowerCase())) return
+ const pg = wiki.page(t)
+ if (pg) picked.set(t.toLowerCase(), pg)
+ }
+ for (const p of changed) {
+ add(p.title)
+ const pg = wiki.page(p.title)
+ for (const t of [...(pg?.links ?? []), ...(pg?.backlinks ?? []), ...wiki.search(p.title, 3).map((h) => h.title)]) add(t)
+ }
+ let size = 0
+ const shown: WikiPage[] = []
+ for (const pg of picked.values()) {
+ if (size > MAX_CHARS) break
+ shown.push(pg)
+ size += Math.min(pg.body.length, PAGE_CHARS)
+ }
+ const orphans = shown.filter((p) => !p.backlinks.length).map((p) => link(p.title))
+ const date = (ms: number): string => new Date(ms).toLocaleDateString('pt-BR')
+ const prompt = [
+ L('## Páginas', '## Pages'),
+ ...shown.map((p) => `### [[${p.title}]] (${p.kind}, ${L('atualizada em', 'updated')} ${date(p.updatedAt)})\n${p.body.slice(0, PAGE_CHARS)}`),
+ ...(orphans.length ? [L('## Páginas sem ninguém ligando pra elas', '## Pages nothing links to'), orphans.join(', ')] : []),
+ L('Responda só com o JSON.', 'Reply with the JSON only.')
+ ].join('\n\n')
+ return parseReview(await this.deps.llm(reviewSystem(), prompt), wiki)
+ }
+}
diff --git a/src/core/wiki.ts b/src/core/wiki.ts
new file mode 100644
index 0000000..bfd4ac7
--- /dev/null
+++ b/src/core/wiki.ts
@@ -0,0 +1,954 @@
+// The wiki (an LLM wiki, after Karpathy's idea): what the team knows, as linked pages.
+// The pages are plain Markdown files in a folder Obsidian opens as is (pages/, plus esquema.md,
+// índice.md and registro.md); that folder is the truth. A SQLite file next to the data keeps
+// only what comes from it or watches over it: the search, the links, and each page's history.
+// A page changed outside Tucano (Obsidian, git, any editor) is picked up and indexed again;
+// a save made from an older copy of a page is refused instead of overwriting the newer one.
+import { createHash } from 'node:crypto'
+import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, watch, writeFileSync, type FSWatcher } from 'node:fs'
+import { basename, join, relative, resolve, sep } from 'node:path'
+import { DatabaseSync } from 'node:sqlite'
+import { L, locale } from '../shared/lang'
+import type { WikiChange, WikiFinding, WikiHit, WikiImport, WikiOp, WikiPage, WikiPageInfo, WikiSource, WikiVersion } from '../shared/types'
+import type { ToolDef } from './gateway'
+
+const PAGES = 'pages'
+const SOURCES = 'fontes'
+const SCHEMA = 'esquema.md'
+const INDEX = 'índice.md'
+const LOG = 'registro.md'
+const CHUNK = 1500 // characters per search chunk: a long page answers with the right part
+const KIND_OTHER = () => L('Outros', 'Other')
+
+export class WikiConflict extends Error {
+ constructor() {
+ super(L('Essa página mudou desde que foi aberta. Recarregue e faça a mudança de novo.', 'This page changed since it was opened. Reload it and make the change again.'))
+ }
+}
+
+const sha = (s: string): string => createHash('sha256').update(s).digest('hex').slice(0, 16)
+// [[Clientes/Marcos Lima]] and [[Marcos Lima.md]] are the page Marcos Lima, as in Obsidian.
+export const pageName = (target: string): string => target.replace(/\.md$/i, '').split('/').pop()!.trim()
+// A page's file name is its title, minus what file systems refuse.
+export const fileOf = (title: string): string => `${title.replace(/[\\/:*?"<>|\n\r\t]/g, '-').replace(/^\.+/, '').trim().slice(0, 120) || 'sem-titulo'}.md`
+
+// "---\nkey: value\n---\nbody": the frontmatter Obsidian shows as Properties.
+export function parsePage(text: string): { meta: Record<string, string>; body: string } {
+ const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text)
+ if (!m) return { meta: {}, body: text }
+ const meta: Record<string, string> = {}
+ let list: string | null = null // a key whose value is the " - item" lines under it (Obsidian's tags, aliases)
+ for (const line of m[1]!.split(/\r?\n/)) {
+ const item = /^\s+-\s+(.*)$/.exec(line)
+ if (item && list) {
+ meta[list] = [meta[list], item[1]!.replace(/^["']|["']$/g, '').trim()].filter(Boolean).join(', ')
+ continue
+ }
+ const kv = /^([\wÀ-ɏ-]+):\s*(.*)$/.exec(line)
+ if (!kv) continue
+ const key = kv[1]!.toLowerCase()
+ const v = kv[2]!.trim()
+ list = v ? null : key
+ meta[key] = v.startsWith('[') && v.endsWith(']') ? v.slice(1, -1).split(',').map((x) => x.trim().replace(/^["']|["']$/g, '')).filter(Boolean).join(', ') : v.replace(/^["']|["']$/g, '').trim()
+ }
+ return { meta, body: text.slice(m[0].length) }
+}
+
+// Changes some keys of a page's frontmatter and leaves every other line as it was (lists,
+// aliases, whatever Obsidian or its plugins keep there).
+export function withFront(text: string | undefined, set: Record<string, string>, body: string): string {
+ const m = text ? /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text) : null
+ const lines = m ? m[1]!.split(/\r?\n/) : []
+ for (const [k, v] of Object.entries(set)) {
+ const at = lines.findIndex((l) => new RegExp(`^${k}:`, 'i').test(l))
+ const line = `${k}: ${/[:#[\]{}]/.test(v) ? JSON.stringify(v) : v}`
+ if (at >= 0) lines[at] = line
+ else lines.push(line)
+ }
+ const clean = body.replace(/^\n+/, '')
+ return lines.length ? `---\n${lines.join('\n')}\n---\n\n${clean}` : clean
+}
+
+const SKIP = new Set(['.obsidian', '.trash', '.git', 'node_modules'])
+// Every file under a folder, as paths relative to it, leaving out Obsidian's own folder and the like.
+function walk(root: string, keep: (rel: string) => boolean = () => true): string[] {
+ const out: string[] = []
+ const go = (rel: string): void => {
+ for (const e of readdirSync(rel ? join(root, rel) : root, { withFileTypes: true })) {
+ if (e.name.startsWith('.') || SKIP.has(e.name)) continue
+ const r = rel ? `${rel}/${e.name}` : e.name
+ if (e.isDirectory()) {
+ if (keep(`${r}/`)) go(r)
+ } else if (keep(r)) out.push(r)
+ }
+ }
+ if (existsSync(root)) go('')
+ return out
+}
+const pageText = (meta: Record<string, string>, body: string): string => {
+ const keys = Object.entries(meta).filter(([, v]) => v !== '')
+ return (keys.length ? `---\n${keys.map(([k, v]) => `${k}: ${/[:#[\]{}]/.test(v) ? JSON.stringify(v) : v}`).join('\n')}\n---\n\n` : '') + body.replace(/^\n+/, '')
+}
+
+// [[Page]], [[Page|shown]], [[Page#section]]: the titles a body links to, outside code.
+export function linksIn(body: string): string[] {
+ const text = body.replace(/```[\s\S]*?```/g, '').replace(/`[^`\n]*`/g, '')
+ const out = new Set<string>()
+ for (const m of text.matchAll(/(!?)\[\[([^\]|#\n]+)(?:#[^\]|\n]*)?(?:\|[^\]\n]*)?\]\]/g)) {
+ const target = m[2]!.trim()
+ if (target.startsWith(`${SOURCES}/`)) continue
+ if (m[1] && /\.(?!md$)[a-z0-9]{2,5}$/i.test(target)) continue // ![[foto.png]]: an attachment, not a page
+ out.add(pageName(target))
+ }
+ return [...out]
+}
+
+// The first line worth reading: what the index shows next to a title.
+export function summaryOf(body: string): string {
+ const line = body
+ .split(/\r?\n/)
+ .map((l) => l.trim())
+ .find((l) => l && !l.startsWith('#') && !l.startsWith('---') && !l.startsWith('|') && !l.startsWith('```'))
+ if (!line) return ''
+ const plain = line.replace(/^[-*>]\s+/, '').replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, '$2').replace(/\[\[([^\]]+)\]\]/g, '$1').replace(/[*_`]/g, '')
+ return plain.length > 140 ? `${plain.slice(0, 137).trimEnd()}…` : plain
+}
+
+function chunks(body: string): string[] {
+ const out: string[] = []
+ let cur = ''
+ for (const para of body.split(/\n{2,}/)) {
+ if (cur && cur.length + para.length > CHUNK) (out.push(cur), (cur = ''))
+ cur = cur ? `${cur}\n\n${para}` : para
+ while (cur.length > CHUNK * 1.5) (out.push(cur.slice(0, CHUNK)), (cur = cur.slice(CHUNK)))
+ }
+ if (cur.trim()) out.push(cur)
+ return out.length ? out : ['']
+}
+
+// A search hit's text as one plain line: its **marks** stay, the Markdown around them goes.
+export const plainSnippet = (s: string): string =>
+ s
+ .replace(/\[\[([^\]|]+)\|([^\]]+)\]\]/g, '$2')
+ .replace(/\[\[([^\]]+)\]\]/g, '$1')
+ .split(/\r?\n/)
+ .map((l) => l.replace(/^\s*(#+|[-*>]|\d+\.)\s+/, '').trim())
+ .filter(Boolean)
+ .join(' · ')
+
+// Words of a search, as FTS5 terms: each word a prefix, all of them needed.
+export function ftsQuery(q: string, any = false): string {
+ const words = q
+ .normalize('NFC')
+ .toLowerCase()
+ .split(/[^\p{L}\p{N}]+/u)
+ .filter((w) => w.length > 1)
+ .slice(0, 12)
+ return words.map((w) => `"${w}"*`).join(any ? ' OR ' : ' ')
+}
+
+const defaultSchema = (): string =>
+ L(
+ `# Esquema da wiki
+
+As regras desta wiki, pra quem escreve nela (você e os agentes). Mude à vontade: os agentes leem esta página.
+
+## Tipos de página
+- **Pessoa**: alguém com quem você fala (cliente, colega, família). Seções: Quem é, Contato, Histórico.
+- **Projeto**: um trabalho com começo e fim. Seções: Objetivo, Situação, Decisões, Próximos passos.
+- **Assunto**: um tema que vale entender (uma ferramenta, um processo, uma área). Seções: Resumo, Detalhes, Links.
+- **Decisão**: o que se decidiu, quando, por quê e quem decidiu.
+
+## Como escrever
+- Uma página por pessoa, projeto ou assunto. O nome do arquivo é o título.
+- Ligue páginas com [[Título]]: é assim que a wiki vira uma rede.
+- No começo da página, uma frase que resume. O índice mostra essa frase.
+- Escreva o que é durável. O que só importa numa conversa fica na conversa.
+- Quando uma informação vier de algum lugar (um e-mail, um documento, uma conversa), diga de onde.
+`,
+ `# Wiki schema
+
+This wiki's rules, for whoever writes in it (you and the agents). Change them freely: the agents read this page.
+
+## Kinds of page
+- **Person**: someone you deal with (a client, a colleague, family). Sections: Who, Contact, History.
+- **Project**: a piece of work with a start and an end. Sections: Goal, Status, Decisions, Next steps.
+- **Topic**: something worth understanding (a tool, a process, an area). Sections: Summary, Details, Links.
+- **Decision**: what was decided, when, why and by whom.
+
+## How to write
+- One page per person, project or topic. The file name is the title.
+- Link pages with [[Title]]: that's how the wiki becomes a web.
+- At the top of the page, one sentence that sums it up. The index shows that sentence.
+- Write what lasts. What matters only in one conversation stays in the conversation.
+- When a piece of information comes from somewhere (an email, a document, a conversation), say where.
+`
+ )
+
+export interface WikiDeps {
+ dir: string // the folder of Markdown files: the truth
+ indexPath: string // the SQLite file with the search, the links and the history
+ onChange?: () => void
+}
+
+export class Wiki {
+ dir: string
+ private db!: DatabaseSync
+ private watcher?: FSWatcher
+ private timer?: ReturnType<typeof setTimeout>
+ private onChange: () => void
+
+ constructor(private deps: WikiDeps) {
+ this.dir = deps.dir
+ this.onChange = deps.onChange ?? (() => {})
+ }
+
+ // Where the pages are: pages/ in a wiki Tucano made; the folder itself when it's an Obsidian
+ // vault the person pointed it to (notes at its root, in folders of its own).
+ private root = ''
+ private importing = false
+ private get pagesDir(): string {
+ return this.root
+ }
+ private pickRoot(): string {
+ const pages = join(this.dir, PAGES)
+ if (existsSync(pages) || !existsSync(this.dir)) return pages
+ const vault = existsSync(join(this.dir, '.obsidian')) || readdirSync(this.dir).some((f) => f.endsWith('.md') && ![SCHEMA, INDEX, LOG].includes(f))
+ return vault ? this.dir : pages
+ }
+ // A file under the root that's a page: Markdown, and not one of Tucano's own files.
+ private isPage = (rel: string): boolean => (rel.endsWith('/') ? !(this.root === this.dir && rel === `${SOURCES}/`) : rel.endsWith('.md') && !(this.root === this.dir && [SCHEMA, INDEX, LOG].includes(rel)))
+
+ init(watchFolder = true): void {
+ this.root = this.pickRoot()
+ mkdirSync(this.pagesDir, { recursive: true })
+ mkdirSync(join(this.dir, SOURCES), { recursive: true })
+ if (!existsSync(join(this.dir, SCHEMA))) writeFileSync(join(this.dir, SCHEMA), defaultSchema())
+ if (!existsSync(join(this.dir, LOG))) writeFileSync(join(this.dir, LOG), L('# Registro\n\nO que mudou na wiki, do mais antigo pro mais novo.\n\n', '# Log\n\nWhat changed in the wiki, oldest first.\n\n'))
+ this.db = new DatabaseSync(this.deps.indexPath)
+ this.db.exec(`
+ CREATE TABLE IF NOT EXISTS pages (file TEXT PRIMARY KEY, title TEXT NOT NULL, kind TEXT NOT NULL, summary TEXT NOT NULL, body TEXT NOT NULL, hash TEXT NOT NULL, mtime INTEGER NOT NULL, updated_at INTEGER NOT NULL, updated_by TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS links (src TEXT NOT NULL, target TEXT NOT NULL);
+ CREATE INDEX IF NOT EXISTS links_by_target ON links (target);
+ CREATE TABLE IF NOT EXISTS versions (id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT NOT NULL, at INTEGER NOT NULL, by TEXT NOT NULL, action TEXT NOT NULL, before TEXT, after TEXT, reason TEXT);
+ CREATE INDEX IF NOT EXISTS versions_by_title ON versions (title, at);
+ CREATE VIRTUAL TABLE IF NOT EXISTS fts USING fts5(title, body, file UNINDEXED, tokenize = 'unicode61 remove_diacritics 2');
+ CREATE TABLE IF NOT EXISTS sources (id TEXT PRIMARY KEY, file TEXT NOT NULL, title TEXT NOT NULL, kind TEXT NOT NULL, origin TEXT NOT NULL, added_by TEXT NOT NULL, added_at INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS changes (id TEXT PRIMARY KEY, source_id TEXT, at INTEGER NOT NULL, by TEXT NOT NULL, state TEXT NOT NULL, ops TEXT NOT NULL, base TEXT NOT NULL, before TEXT, reason TEXT, decided_at INTEGER);
+ CREATE TABLE IF NOT EXISTS marks (conversation_id TEXT PRIMARY KEY, until INTEGER NOT NULL);
+ CREATE TABLE IF NOT EXISTS findings (id TEXT PRIMARY KEY, key TEXT NOT NULL, at INTEGER NOT NULL, kind TEXT NOT NULL, pages TEXT NOT NULL, text TEXT NOT NULL, name TEXT, change_id TEXT, state TEXT NOT NULL);
+ CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
+ `)
+ for (const col of ['status TEXT', 'error TEXT', 'changes INTEGER']) {
+ try {
+ this.db.exec(`ALTER TABLE sources ADD COLUMN ${col}`)
+ } catch {
+ // already there
+ }
+ }
+ this.scan()
+ this.writeIndex()
+ if (watchFolder) this.watchFolder()
+ }
+
+ // Another folder: the index is that folder's own; what was in the old one stays there.
+ relocate(dir: string, indexPath: string): void {
+ this.close()
+ this.dir = dir
+ this.deps = { ...this.deps, dir, indexPath }
+ this.init()
+ this.onChange()
+ }
+
+ close(): void {
+ this.watcher?.close()
+ if (this.timer) clearTimeout(this.timer)
+ this.db?.close()
+ }
+
+ // Changes made outside Tucano: indexed again, and kept in the history as such.
+ private watchFolder(): void {
+ try {
+ this.watcher = watch(this.pagesDir, { recursive: true }, () => {
+ if (this.importing) return
+ if (this.timer) clearTimeout(this.timer)
+ this.timer = setTimeout(() => {
+ if (this.scan()) (this.writeIndex(), this.onChange())
+ }, 250)
+ })
+ } catch {
+ // Some file systems can't be watched: pages written by the app still index right away.
+ }
+ }
+
+ // Brings the index in line with the folder. True when something changed.
+ scan(): boolean {
+ const files = walk(this.pagesDir, this.isPage)
+ const known = new Map((this.db.prepare('SELECT file, hash, mtime FROM pages').all() as { file: string; hash: string; mtime: number }[]).map((r) => [r.file, r]))
+ let changed = false
+ for (const file of files) {
+ const path = join(this.pagesDir, file)
+ const mtime = Math.round(statSync(path).mtimeMs)
+ const k = known.get(file)
+ known.delete(file)
+ if (k && k.mtime === mtime) continue
+ const text = readFileSync(path, 'utf8')
+ if (k && k.hash === sha(text)) {
+ this.db.prepare('UPDATE pages SET mtime = ? WHERE file = ?').run(mtime, file)
+ continue
+ }
+ const before = k ? this.bodyOf(file) : null
+ this.indexFile(file, text, mtime, 'outside')
+ this.version(this.titleOf(file, text), 'outside', k ? 'edit' : 'create', before, parsePage(text).body)
+ this.appendLog(k ? L(`[[${this.titleOf(file, text)}]] mudou fora do Tucano`, `[[${this.titleOf(file, text)}]] changed outside Tucano`) : L(`[[${this.titleOf(file, text)}]] apareceu na pasta`, `[[${this.titleOf(file, text)}]] showed up in the folder`))
+ changed = true
+ }
+ for (const file of known.keys()) {
+ const title = (this.db.prepare('SELECT title FROM pages WHERE file = ?').get(file) as { title: string } | undefined)?.title ?? file
+ this.version(title, 'outside', 'delete', this.bodyOf(file), null)
+ this.appendLog(L(`${title} saiu da pasta`, `${title} left the folder`))
+ this.unindex(file)
+ changed = true
+ }
+ return changed
+ }
+
+ // A page is called by its file's name, as in Obsidian (that's what [[links]] point to).
+ private titleOf(file: string, _text?: string): string {
+ return file.split('/').pop()!.replace(/\.md$/, '')
+ }
+ // Its kind: the tipo it says; else the folder it's in (an Obsidian vault's "Clientes/"); else its first tag.
+ private kindOf(file: string, meta: Record<string, string>, own = true): string {
+ const said = own ? meta['tipo'] || meta['type'] || meta['kind'] : ''
+ if (said) return said
+ const folder = file.includes('/') ? file.split('/')[0]! : ''
+ if (folder) return folder
+ const tag = (meta['tags'] || meta['tag'] || '').split(',')[0]?.trim().replace(/^#/, '').split('/').pop()
+ return tag ? tag.charAt(0).toUpperCase() + tag.slice(1) : KIND_OTHER()
+ }
+ private bodyOf(file: string): string | null {
+ return (this.db.prepare('SELECT body FROM pages WHERE file = ?').get(file) as { body: string } | undefined)?.body ?? null
+ }
+
+ private indexFile(file: string, text: string, mtime: number, by: string): void {
+ const { meta, body } = parsePage(text)
+ const title = this.titleOf(file, text)
+ this.unindex(file)
+ this.db.prepare('INSERT INTO pages (file, title, kind, summary, body, hash, mtime, updated_at, updated_by) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)').run(file, title, this.kindOf(file, meta), summaryOf(body), body, sha(text), mtime, Date.now(), by)
+ // links in the properties count too, as in Obsidian (cliente: "[[Marcos Lima]]")
+ for (const target of new Set([...linksIn(body), ...linksIn(Object.values(meta).join('\n'))].map((t) => t.toLowerCase()))) this.db.prepare('INSERT INTO links (src, target) VALUES (?, ?)').run(file, target)
+ for (const c of chunks(body)) this.db.prepare('INSERT INTO fts (title, body, file) VALUES (?, ?, ?)').run(title, c, file)
+ }
+ private unindex(file: string): void {
+ this.db.prepare('DELETE FROM pages WHERE file = ?').run(file)
+ this.db.prepare('DELETE FROM links WHERE src = ?').run(file)
+ this.db.prepare('DELETE FROM fts WHERE file = ?').run(file)
+ }
+ private version(title: string, by: string, action: WikiVersion['action'], before: string | null, after: string | null, reason?: string): void {
+ this.db.prepare('INSERT INTO versions (title, at, by, action, before, after, reason) VALUES (?, ?, ?, ?, ?, ?, ?)').run(title, Date.now(), by, action, before, after, reason ?? null)
+ }
+
+ // ---------- reading ----------
+
+ count(): number {
+ return (this.db.prepare('SELECT COUNT(*) AS n FROM pages').get() as { n: number }).n
+ }
+
+ list(): WikiPageInfo[] {
+ return (this.db.prepare('SELECT title, kind, summary, updated_at, updated_by FROM pages ORDER BY title COLLATE NOCASE').all() as Record<string, unknown>[]).map((r) => ({
+ title: String(r['title']),
+ kind: String(r['kind']),
+ summary: String(r['summary']),
+ updatedAt: Number(r['updated_at']),
+ updatedBy: String(r['updated_by'])
+ }))
+ }
+
+ kinds(): string[] {
+ return [...new Set(this.list().map((p) => p.kind))].sort((a, b) => (a === KIND_OTHER() ? 1 : b === KIND_OTHER() ? -1 : a.localeCompare(b, locale())))
+ }
+
+ private fileFor(title: string): string | undefined {
+ const r = this.db.prepare('SELECT file FROM pages WHERE lower(title) = lower(?)').get(title.trim()) as { file: string } | undefined
+ return r?.file
+ }
+
+ page(title: string): WikiPage | undefined {
+ const file = this.fileFor(title)
+ if (!file) return undefined
+ const path = join(this.pagesDir, file)
+ if (!existsSync(path)) return undefined
+ const text = readFileSync(path, 'utf8')
+ const { meta, body } = parsePage(text)
+ const r = this.db.prepare('SELECT title, kind, updated_at, updated_by FROM pages WHERE file = ?').get(file) as Record<string, unknown>
+ const backlinks = (this.db.prepare('SELECT DISTINCT p.title FROM links l JOIN pages p ON p.file = l.src WHERE l.target = lower(?) AND l.src != ? ORDER BY p.title').all(String(r['title']), file) as { title: string }[]).map((x) => x.title)
+ const known = new Set(this.list().map((p) => p.title.toLowerCase()))
+ return {
+ title: String(r['title']),
+ kind: String(r['kind']),
+ summary: summaryOf(body),
+ body,
+ meta,
+ hash: sha(text),
+ updatedAt: Number(r['updated_at']),
+ updatedBy: String(r['updated_by']),
+ links: linksIn(body),
+ missing: linksIn(body).filter((t) => !known.has(t.toLowerCase())),
+ backlinks,
+ file: relative(this.dir, join(this.pagesDir, file)).split(sep).join('/')
+ }
+ }
+
+ search(q: string, limit = 8): WikiHit[] {
+ const run = (match: string): WikiHit[] =>
+ match
+ ? (this.db
+ .prepare(`SELECT p.title, p.kind, snippet(fts, 1, '**', '**', '…', 18) AS snip, bm25(fts, 6.0, 1.0) AS rank FROM fts JOIN pages p ON p.file = fts.file WHERE fts MATCH ? ORDER BY rank LIMIT ?`)
+ .all(match, limit * 3) as Record<string, unknown>[])
+ .map((r) => ({ title: String(r['title']), kind: String(r['kind']), snippet: plainSnippet(String(r['snip'])) }))
+ : []
+ let hits: WikiHit[] = []
+ try {
+ hits = run(ftsQuery(q))
+ if (!hits.length) hits = run(ftsQuery(q, true))
+ } catch {
+ hits = []
+ }
+ const seen = new Set<string>()
+ return hits.filter((h) => !seen.has(h.title) && seen.add(h.title)).slice(0, limit)
+ }
+
+ history(title: string): WikiVersion[] {
+ return (this.db.prepare('SELECT * FROM versions WHERE lower(title) = lower(?) ORDER BY at DESC, id DESC LIMIT 100').all(title) as Record<string, unknown>[]).map((r) => ({
+ id: Number(r['id']),
+ title: String(r['title']),
+ at: Number(r['at']),
+ by: String(r['by']),
+ action: String(r['action']) as WikiVersion['action'],
+ before: r['before'] == null ? null : String(r['before']),
+ after: r['after'] == null ? null : String(r['after']),
+ ...(r['reason'] ? { reason: String(r['reason']) } : {})
+ }))
+ }
+
+ schema(): string {
+ const p = join(this.dir, SCHEMA)
+ return existsSync(p) ? readFileSync(p, 'utf8') : ''
+ }
+ saveSchema(text: string): void {
+ writeFileSync(join(this.dir, SCHEMA), text)
+ this.onChange()
+ }
+
+ indexText(): string {
+ const p = join(this.dir, INDEX)
+ return existsSync(p) ? readFileSync(p, 'utf8') : ''
+ }
+
+ // The latest lines of the log, newest first.
+ log(limit = 30): string[] {
+ const p = join(this.dir, LOG)
+ if (!existsSync(p)) return []
+ return readFileSync(p, 'utf8')
+ .split(/\r?\n/)
+ .filter((l) => l.startsWith('- '))
+ .slice(-limit)
+ .reverse()
+ .map((l) => l.slice(2))
+ }
+
+ // ---------- writing ----------
+
+ // Creates or changes a page. expectedHash: the copy the change was made on; a page that moved on since is refused.
+ save(p: { title: string; body: string; kind?: string; by: string; byName: string; expectedHash?: string; rename?: string; reason?: string }): WikiPage {
+ const title = p.title.trim().replace(/\s+/g, ' ')
+ if (!title) throw new Error(L('A página precisa de um título.', 'The page needs a title.'))
+ const oldFile = this.fileFor(p.rename ?? title)
+ // a page in a folder stays in it, renamed or not
+ const folder = oldFile?.includes('/') ? oldFile.slice(0, oldFile.lastIndexOf('/') + 1) : ''
+ const file = folder + fileOf(title)
+ const existing = oldFile ? readFileSync(join(this.pagesDir, oldFile), 'utf8') : undefined
+ if (existing !== undefined && p.expectedHash !== undefined && sha(existing) !== p.expectedHash) throw new WikiConflict()
+ if (existing === undefined && p.expectedHash) throw new WikiConflict()
+ const other = this.fileFor(title)
+ if (other && other !== oldFile) throw new Error(L(`Já existe uma página chamada "${title}".`, `There's already a page called "${title}".`))
+ const day = new Date().toISOString().slice(0, 10)
+ const prev = existing ? parsePage(existing).meta : {}
+ const body = p.body.replace(/\r\n/g, '\n').trimEnd() + '\n'
+ // A page Tucano writes says its kind and dates; one that came from elsewhere keeps its
+ // frontmatter as it was, and only gets a kind when it's changed to one it didn't have.
+ const set: Record<string, string> = {}
+ if (existing === undefined) Object.assign(set, { tipo: p.kind || KIND_OTHER(), criada: day, atualizada: day })
+ else {
+ if (p.kind && p.kind !== this.kindOf(file, prev, !!prev['tipo'])) set['tipo'] = p.kind
+ if ('atualizada' in prev) set['atualizada'] = day
+ }
+ const text = withFront(existing, set, body)
+ if (oldFile && oldFile !== file) {
+ renameSync(join(this.pagesDir, oldFile), join(this.pagesDir, file)) // Obsidian's links by name follow it
+ this.unindex(oldFile)
+ }
+ writeFileSync(join(this.pagesDir, file), text)
+ this.indexFile(file, text, Math.round(statSync(join(this.pagesDir, file)).mtimeMs), p.by)
+ const before = existing !== undefined ? parsePage(existing).body : null
+ this.version(title, p.by, existing === undefined ? 'create' : 'edit', before, parsePage(text).body, p.reason)
+ this.appendLog(existing === undefined ? L(`**${p.byName}** criou [[${title}]]`, `**${p.byName}** created [[${title}]]`) : p.rename && p.rename !== title ? L(`**${p.byName}** renomeou [[${p.rename}]] pra [[${title}]]`, `**${p.byName}** renamed [[${p.rename}]] to [[${title}]]`) : L(`**${p.byName}** editou [[${title}]]`, `**${p.byName}** edited [[${title}]]`))
+ this.writeIndex()
+ this.onChange()
+ return this.page(title)!
+ }
+
+ remove(title: string, by: string, byName: string): void {
+ const file = this.fileFor(title)
+ if (!file) return
+ const path = join(this.pagesDir, file)
+ const before = existsSync(path) ? parsePage(readFileSync(path, 'utf8')).body : this.bodyOf(file)
+ if (existsSync(path)) rmSync(path)
+ this.unindex(file)
+ this.version(title, by, 'delete', before, null)
+ this.appendLog(L(`**${byName}** apagou ${title}`, `**${byName}** deleted ${title}`))
+ this.writeIndex()
+ this.onChange()
+ }
+
+ // An Obsidian vault (or any folder of Markdown) brought in as it is: notes, folders and
+ // attachments copied under the pages, untouched; the vault itself stays where it was. A file
+ // already here isn't overwritten. The agents read it all from then on.
+ importVault(src: string, byName: string): WikiImport {
+ const from = resolve(src)
+ if (!existsSync(from) || !statSync(from).isDirectory()) throw new Error(L('Essa pasta não existe.', "That folder doesn't exist."))
+ if (from === resolve(this.dir) || resolve(this.pagesDir).startsWith(from + sep) || from.startsWith(resolve(this.dir) + sep)) throw new Error(L('Essa pasta é a própria wiki, ou está dentro dela.', "That folder is the wiki itself, or inside it."))
+ const files = walk(from)
+ const notes = files.filter((f) => f.endsWith('.md'))
+ if (!notes.length) throw new Error(L('Não achei nenhuma nota (.md) nessa pasta.', 'I found no notes (.md) in that folder.'))
+ const skipped: string[] = []
+ const copied: string[] = []
+ this.importing = true
+ try {
+ for (const f of files) {
+ const to = join(this.pagesDir, f)
+ if (existsSync(to)) {
+ skipped.push(f)
+ continue
+ }
+ mkdirSync(join(to, '..'), { recursive: true })
+ copyFileSync(join(from, f), to)
+ copied.push(f)
+ }
+ for (const f of copied.filter((x) => x.endsWith('.md'))) {
+ const text = readFileSync(join(this.pagesDir, f), 'utf8')
+ this.indexFile(f, text, Math.round(statSync(join(this.pagesDir, f)).mtimeMs), 'import')
+ this.version(this.titleOf(f), 'import', 'create', null, parsePage(text).body, L('importada do Obsidian', 'imported from Obsidian'))
+ }
+ } finally {
+ this.importing = false
+ }
+ const pages = copied.filter((f) => f.endsWith('.md'))
+ const graph = this.graph()
+ const kinds = new Map<string, number>()
+ for (const f of pages) {
+ const k = (this.db.prepare('SELECT kind FROM pages WHERE file = ?').get(f) as { kind: string } | undefined)?.kind
+ if (k) kinds.set(k, (kinds.get(k) ?? 0) + 1)
+ }
+ const name = basename(from)
+ this.appendLog(L(`**${byName}** importou ${pages.length} ${pages.length === 1 ? 'nota' : 'notas'} de ${name}`, `**${byName}** imported ${pages.length} ${pages.length === 1 ? 'note' : 'notes'} from ${name}`))
+ this.writeIndex()
+ this.onChange()
+ return {
+ from: name ?? from,
+ pages: pages.length,
+ attachments: copied.length - pages.length,
+ skipped,
+ links: graph.edges.length,
+ missing: graph.nodes.filter((n) => n.missing).length,
+ kinds: [...kinds.entries()].sort((a, b) => b[1] - a[1])
+ }
+ }
+
+ // Puts a page back as it was after a version (or before it, for a deletion).
+ restore(versionId: number, by: string, byName: string): WikiPage {
+ const v = this.db.prepare('SELECT * FROM versions WHERE id = ?').get(versionId) as Record<string, unknown> | undefined
+ if (!v) throw new Error(L('Essa versão não existe mais.', 'That version no longer exists.'))
+ const body = v['action'] === 'delete' ? v['before'] : v['after']
+ if (body == null) throw new Error(L('Não há texto pra restaurar nessa versão.', 'There is no text to restore in that version.'))
+ const current = this.page(String(v['title']))
+ return this.save({ title: String(v['title']), body: String(body), by, byName, ...(current ? { expectedHash: current.hash } : {}), reason: L('restaurou uma versão anterior', 'restored an earlier version') })
+ }
+
+ private appendLog(line: string): void {
+ const when = new Date().toLocaleString(locale(), { dateStyle: 'short', timeStyle: 'short' })
+ writeFileSync(join(this.dir, LOG), `${existsSync(join(this.dir, LOG)) ? readFileSync(join(this.dir, LOG), 'utf8').replace(/\n*$/, '\n') : ''}- ${when} · ${line}\n`)
+ }
+
+ // índice.md: every page by kind, with its first line. Kept by Tucano, read by the agents.
+ private writeIndex(): void {
+ const pages = this.list()
+ const byKind = new Map<string, WikiPageInfo[]>()
+ for (const p of pages) byKind.set(p.kind, [...(byKind.get(p.kind) ?? []), p])
+ const head = L(`# Índice\n\n${pages.length === 1 ? '1 página' : `${pages.length} páginas`}. Mantido pelo Tucano: não precisa editar.\n`, `# Index\n\n${pages.length === 1 ? '1 page' : `${pages.length} pages`}. Kept by Tucano: no need to edit it.\n`)
+ const body = this.kinds()
+ .map((k) => `\n## ${k}\n${byKind.get(k)!.map((p) => `- [[${p.title}]]${p.summary ? `: ${p.summary}` : ''}`).join('\n')}\n`)
+ .join('')
+ const text = head + body
+ const path = join(this.dir, INDEX)
+ if (!existsSync(path) || readFileSync(path, 'utf8') !== text) writeFileSync(path, text)
+ }
+
+ // ---------- sources: what the wiki is made from, kept as it came ----------
+
+ addSource(p: { title: string; text: string; kind: WikiSource['kind']; origin?: WikiSource['origin']; by: string; file?: { name: string; data: Buffer }; status?: WikiSource['status'] }): WikiSource {
+ const at = Date.now()
+ const d = new Date(at)
+ const stamp = `${d.toISOString().slice(0, 10)} ${String(d.getHours()).padStart(2, '0')}${String(d.getMinutes()).padStart(2, '0')}`
+ let file = fileOf(`${stamp} ${p.title}`)
+ for (let k = 2; existsSync(join(this.dir, SOURCES, file)); k++) file = fileOf(`${stamp} ${p.title} ${k}`)
+ const origin: WikiSource['origin'] = { ...(p.origin ?? {}) }
+ // The file as it came, next to its text: fontes/arquivos/<date> <name>.
+ if (p.file) {
+ mkdirSync(join(this.dir, SOURCES, 'arquivos'), { recursive: true })
+ const safe = p.file.name.replace(/[\\/:*?"<>|\n\r\t]/g, '-').slice(0, 120)
+ let name = `${stamp} ${safe}`
+ for (let k = 2; existsSync(join(this.dir, SOURCES, 'arquivos', name)); k++) name = `${stamp} ${k} ${safe}`
+ writeFileSync(join(this.dir, SOURCES, 'arquivos', name), p.file.data)
+ origin.original = `${SOURCES}/arquivos/${name}`
+ }
+ const meta: Record<string, string> = { tipo: L('fonte', 'source'), origem: p.kind, adicionada: d.toISOString().slice(0, 16).replace('T', ' '), ...(origin.url ? { link: origin.url } : {}), ...(origin.original ? { arquivo: `[[${origin.original}]]` } : {}) }
+ writeFileSync(join(this.dir, SOURCES, file), pageText(meta, `# ${p.title}\n\n${p.text.trim()}\n`))
+ const src: WikiSource = { id: sha(file + at), file: `${SOURCES}/${file.replace(/\.md$/, '')}`, title: p.title, kind: p.kind, origin, addedBy: p.by, addedAt: at, ...(p.status ? { status: p.status } : {}) }
+ this.db.prepare('INSERT INTO sources (id, file, title, kind, origin, added_by, added_at, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(src.id, src.file, src.title, src.kind, JSON.stringify(src.origin), src.addedBy, src.addedAt, p.status ?? null)
+ this.onChange()
+ return src
+ }
+
+ private toSource(r: Record<string, unknown>): WikiSource {
+ return {
+ id: String(r['id']),
+ file: String(r['file']),
+ title: String(r['title']),
+ kind: String(r['kind']) as WikiSource['kind'],
+ origin: JSON.parse(String(r['origin'])) as WikiSource['origin'],
+ addedBy: String(r['added_by']),
+ addedAt: Number(r['added_at']),
+ ...(r['status'] ? { status: String(r['status']) as WikiSource['status'] } : {}),
+ ...(r['error'] ? { error: String(r['error']) } : {}),
+ ...(r['changes'] != null ? { changes: Number(r['changes']) } : {})
+ }
+ }
+ setSourceStatus(id: string, status: NonNullable<WikiSource['status']>, p: { error?: string; changes?: number } = {}): void {
+ this.db.prepare('UPDATE sources SET status = ?, error = ?, changes = ? WHERE id = ?').run(status, p.error ?? null, p.changes ?? null, id)
+ this.onChange()
+ }
+ // Where a source's original file is, on disk (to open it).
+ originalPath(id: string): string | undefined {
+ const s = this.source(id)
+ return s?.origin.original ? join(this.dir, s.origin.original) : undefined
+ }
+
+ sources(limit = 100): WikiSource[] {
+ return (this.db.prepare('SELECT * FROM sources ORDER BY added_at DESC LIMIT ?').all(limit) as Record<string, unknown>[]).map((r) => this.toSource(r))
+ }
+ source(idOrFile: string): (WikiSource & { text: string }) | undefined {
+ const r = this.db.prepare('SELECT * FROM sources WHERE id = ? OR file = ?').get(idOrFile, idOrFile) as Record<string, unknown> | undefined
+ if (!r) return undefined
+ const src = this.toSource(r)
+ const path = join(this.dir, `${src.file}.md`)
+ return { ...src, text: existsSync(path) ? parsePage(readFileSync(path, 'utf8')).body : '' }
+ }
+
+ // ---------- conversations: how far the curator has read each one ----------
+
+ // The messages of a conversation some source already holds.
+ readMessages(conversationId: string): Set<string> {
+ const rows = this.db.prepare('SELECT origin FROM sources WHERE origin LIKE ?').all(`%"conversationId":"${conversationId.replace(/[%_"]/g, '')}"%`) as { origin: string }[]
+ return new Set(rows.flatMap((r) => (JSON.parse(r.origin) as WikiSource['origin']).messageIds ?? []))
+ }
+
+ // The pages and their links, for the map; a link to a page not written yet is a node too.
+ graph(): { nodes: { title: string; kind: string; links: number; missing?: boolean }[]; edges: [string, string][] } {
+ const pages = this.db.prepare('SELECT file, title, kind FROM pages').all() as { file: string; title: string; kind: string }[]
+ const byFile = new Map(pages.map((p) => [p.file, p.title]))
+ const byName = new Map(pages.map((p) => [p.title.toLowerCase(), p.title]))
+ const ghosts = new Map<string, string>()
+ const edges: [string, string][] = []
+ const seen = new Set<string>()
+ for (const l of this.db.prepare('SELECT src, target FROM links').all() as { src: string; target: string }[]) {
+ const a = byFile.get(l.src)
+ if (!a) continue
+ let b = byName.get(l.target)
+ if (!b) {
+ // a page nobody wrote yet, named as the link that points to it writes it
+ b = ghosts.get(l.target) ?? this.linkAsWritten(l.src, l.target) ?? l.target
+ ghosts.set(l.target, b)
+ }
+ const k = [a, b].sort().join('\n')
+ if (a === b || seen.has(k)) continue
+ seen.add(k)
+ edges.push([a, b])
+ }
+ const degree = new Map<string, number>()
+ for (const [a, b] of edges) degree.set(a, (degree.get(a) ?? 0) + 1), degree.set(b, (degree.get(b) ?? 0) + 1)
+ return {
+ nodes: [...pages.map((p) => ({ title: p.title, kind: p.kind, links: degree.get(p.title) ?? 0 })), ...[...ghosts.values()].map((t) => ({ title: t, kind: '', links: degree.get(t) ?? 0, missing: true }))],
+ edges
+ }
+ }
+
+ private linkAsWritten(file: string, target: string): string | undefined {
+ const text = existsSync(join(this.pagesDir, file)) ? readFileSync(join(this.pagesDir, file), 'utf8') : ''
+ return linksIn(text).find((t) => t.toLowerCase() === target)
+ }
+
+ // The latest changes to any page, newest first.
+ recent(limit = 12): Omit<WikiVersion, 'before' | 'after'>[] {
+ return (this.db.prepare('SELECT id, title, at, by, action, reason FROM versions ORDER BY at DESC, id DESC LIMIT ?').all(limit) as Record<string, unknown>[]).map((r) => ({ id: Number(r['id']), title: String(r['title']), at: Number(r['at']), by: String(r['by']), action: String(r['action']) as WikiVersion['action'], ...(r['reason'] ? { reason: String(r['reason']) } : {}) }))
+ }
+
+ sourceCount(): number {
+ return (this.db.prepare('SELECT COUNT(*) AS n FROM sources').get() as { n: number }).n
+ }
+
+ mark(conversationId: string): number {
+ return (this.db.prepare('SELECT until FROM marks WHERE conversation_id = ?').get(conversationId) as { until: number } | undefined)?.until ?? 0
+ }
+ setMark(conversationId: string, until: number): void {
+ this.db.prepare('INSERT INTO marks (conversation_id, until) VALUES (?, ?) ON CONFLICT (conversation_id) DO UPDATE SET until = excluded.until').run(conversationId, until)
+ }
+
+ // ---------- change packages: what the curator wants to write, applied or waiting for you ----------
+
+ // Records a package on the pages as they are now. The caller decides: apply it or leave it pending.
+ getMeta(key: string): string | undefined {
+ const r = this.db.prepare('SELECT value FROM meta WHERE key = ?').get(key) as { value: string } | undefined
+ return r?.value
+ }
+ setMeta(key: string, value: string): void {
+ this.db.prepare('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value').run(key, value)
+ }
+
+ // ---------- what a review found ----------
+
+ // Open: not dismissed, and its fix (if any) still waiting. A fix that went in or was refused closes it.
+ findings(): WikiFinding[] {
+ const rows = this.db.prepare("SELECT * FROM findings WHERE state = 'open' ORDER BY at, rowid").all() as Record<string, unknown>[]
+ const out: WikiFinding[] = []
+ for (const r of rows) {
+ const change = r['change_id'] ? this.change(String(r['change_id'])) : undefined
+ if (r['change_id'] && (!change || (change.state !== 'pending' && change.state !== 'conflict'))) continue
+ out.push({ id: String(r['id']), at: Number(r['at']), kind: String(r['kind']) as WikiFinding['kind'], pages: JSON.parse(String(r['pages'])) as string[], text: String(r['text']), ...(r['name'] ? { name: String(r['name']) } : {}), ...(change ? { change } : {}) })
+ }
+ return out
+ }
+
+ // A new review's findings take the place of the old ones; what was dismissed, or still waits, isn't said again.
+ setFindings(list: (Omit<WikiFinding, 'id' | 'at' | 'change'> & { key: string; ops?: WikiOp[]; reason?: string })[]): void {
+ // a fix refused counts as "leave it"
+ const keep = new Set((this.db.prepare("SELECT key FROM findings WHERE state = 'dismissed' OR change_id IN (SELECT id FROM changes WHERE state = 'refused')").all() as { key: string }[]).map((r) => r.key))
+ for (const f of this.findings()) if (f.change) keep.add((this.db.prepare('SELECT key FROM findings WHERE id = ?').get(f.id) as { key: string }).key)
+ this.db.prepare("DELETE FROM findings WHERE state = 'open' AND (change_id IS NULL OR change_id NOT IN (SELECT id FROM changes WHERE state IN ('pending', 'conflict')))").run()
+ const at = Date.now()
+ for (const f of list) {
+ if (keep.has(f.key)) continue
+ keep.add(f.key)
+ const change = f.ops?.length ? this.addChange({ ops: f.ops, by: 'review', ...(f.reason ? { reason: f.reason } : {}) }) : undefined
+ this.db.prepare("INSERT INTO findings (id, key, at, kind, pages, text, name, change_id, state) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open')").run(sha(f.key + at + Math.random()), f.key, at, f.kind, JSON.stringify(f.pages), f.text, f.name ?? null, change?.id ?? null)
+ }
+ this.onChange()
+ }
+
+ dismissFinding(id: string): void {
+ const r = this.db.prepare('SELECT change_id FROM findings WHERE id = ?').get(id) as { change_id: string | null } | undefined
+ if (!r) return
+ this.db.prepare("UPDATE findings SET state = 'dismissed' WHERE id = ?").run(id)
+ if (r.change_id) this.refuseChange(r.change_id)
+ this.onChange()
+ }
+
+ addChange(p: { ops: WikiOp[]; sourceId?: string; by: string; reason?: string }): WikiChange {
+ const base: Record<string, string | null> = {}
+ for (const op of p.ops) base[op.page] = this.page(op.page)?.hash ?? null
+ const id = sha(JSON.stringify(p.ops) + Date.now() + Math.random())
+ this.db.prepare('INSERT INTO changes (id, source_id, at, by, state, ops, base, reason) VALUES (?, ?, ?, ?, ?, ?, ?, ?)').run(id, p.sourceId ?? null, Date.now(), p.by, 'pending', JSON.stringify(p.ops), JSON.stringify(base), p.reason ?? null)
+ this.onChange()
+ return this.change(id)!
+ }
+
+ private toChange(r: Record<string, unknown>): WikiChange {
+ const sourceId = r['source_id'] ? String(r['source_id']) : undefined
+ const src = sourceId ? this.source(sourceId) : undefined
+ return {
+ id: String(r['id']),
+ at: Number(r['at']),
+ by: String(r['by']),
+ state: String(r['state']) as WikiChange['state'],
+ ops: JSON.parse(String(r['ops'])) as WikiOp[],
+ ...(r['reason'] ? { reason: String(r['reason']) } : {}),
+ ...(src ? { source: { id: src.id, title: src.title, file: src.file } } : {}),
+ ...(r['decided_at'] ? { decidedAt: Number(r['decided_at']) } : {})
+ }
+ }
+ change(id: string): WikiChange | undefined {
+ const r = this.db.prepare('SELECT * FROM changes WHERE id = ?').get(id) as Record<string, unknown> | undefined
+ return r && this.toChange(r)
+ }
+ changes(state?: WikiChange['state']): WikiChange[] {
+ const rows = (state ? this.db.prepare('SELECT * FROM changes WHERE state = ? ORDER BY at DESC LIMIT 200').all(state) : this.db.prepare('SELECT * FROM changes ORDER BY at DESC LIMIT 200').all()) as Record<string, unknown>[]
+ return rows.map((r) => this.toChange(r))
+ }
+
+ // Writes a package. A page that moved on since it was proposed stops it (nothing is written): it's a conflict.
+ applyChange(id: string, byName: string): WikiChange {
+ const r = this.db.prepare('SELECT * FROM changes WHERE id = ?').get(id) as Record<string, unknown> | undefined
+ if (!r) throw new Error(L('Essa mudança não existe mais.', 'That change no longer exists.'))
+ if (r['state'] !== 'pending' && r['state'] !== 'conflict') return this.toChange(r)
+ const ops = JSON.parse(String(r['ops'])) as WikiOp[]
+ const base = JSON.parse(String(r['base'])) as Record<string, string | null>
+ const by = String(r['by'])
+ for (const [title, hash] of Object.entries(base)) {
+ const now = this.page(title)?.hash ?? null
+ if (now !== hash && !(hash === null && ops.every((o) => o.page !== title || o.op === 'create'))) {
+ this.db.prepare("UPDATE changes SET state = 'conflict' WHERE id = ?").run(id)
+ this.onChange()
+ return this.change(id)!
+ }
+ }
+ // Every page as it will be, worked out before anything is written.
+ const next = new Map<string, { body: string; kind?: string; existed: boolean; hash?: string }>()
+ for (const op of ops) {
+ const cur = next.get(op.page) ?? (() => {
+ const p = this.page(op.page)
+ return p ? { body: p.body, kind: p.kind, existed: true, hash: p.hash } : { body: '', existed: false }
+ })()
+ next.set(op.page, { ...cur, body: applyOp(cur.body, op), ...(op.op === 'create' && op.kind && !cur.existed ? { kind: op.kind } : {}) })
+ }
+ const before: Record<string, string | null> = {}
+ for (const [title, n] of next) {
+ const p = this.page(title)
+ before[title] = p ? p.body : null
+ this.save({ title, body: n.body, ...(n.kind ? { kind: n.kind } : {}), by, byName, ...(p ? { expectedHash: p.hash } : {}), ...(r['reason'] ? { reason: String(r['reason']) } : {}) })
+ }
+ this.db.prepare("UPDATE changes SET state = 'applied', before = ?, decided_at = ? WHERE id = ?").run(JSON.stringify(before), Date.now(), id)
+ this.onChange()
+ return this.change(id)!
+ }
+
+ // A package that ran into a newer page, made again on the page as it is now. Null when a
+ // passage it swaps is gone: then it has to be written again (the curator does it).
+ rebaseChange(id: string): WikiChange | null {
+ const c = this.change(id)
+ if (!c || c.state !== 'conflict') return null
+ const ops = c.ops.map((o): WikiOp => (o.op === 'create' && this.page(o.page) ? { op: 'append', page: o.page, ...(o.text ? { text: o.text } : {}) } : o))
+ const bodies = new Map<string, string>()
+ try {
+ for (const o of ops) bodies.set(o.page, applyOp(bodies.get(o.page) ?? this.page(o.page)?.body ?? '', o))
+ } catch {
+ return null
+ }
+ this.db.prepare("UPDATE changes SET state = 'refused', decided_at = ? WHERE id = ?").run(Date.now(), id)
+ return this.addChange({ ops, by: c.by, ...(c.source ? { sourceId: c.source.id } : {}), ...(c.reason ? { reason: c.reason } : {}) })
+ }
+
+ refuseChange(id: string): void {
+ this.db.prepare("UPDATE changes SET state = 'refused', decided_at = ? WHERE id = ? AND state IN ('pending', 'conflict')").run(Date.now(), id)
+ this.onChange()
+ }
+
+ // Puts the pages back as they were before a package, unless they changed again since.
+ undoChange(id: string, byName: string): void {
+ const r = this.db.prepare('SELECT * FROM changes WHERE id = ?').get(id) as Record<string, unknown> | undefined
+ if (!r || r['state'] !== 'applied' || !r['before']) return
+ const before = JSON.parse(String(r['before'])) as Record<string, string | null>
+ for (const [title, body] of Object.entries(before)) {
+ if (body === null) this.remove(title, 'me', byName)
+ else {
+ const p = this.page(title)
+ this.save({ title, body, by: 'me', byName, ...(p ? { expectedHash: p.hash } : {}), reason: L('desfez uma mudança da wiki', 'undid a wiki change') })
+ }
+ }
+ this.db.prepare("UPDATE changes SET state = 'undone', decided_at = ? WHERE id = ?").run(Date.now(), id)
+ this.onChange()
+ }
+}
+
+// One change on a page's body: write it whole, add under a section (made if missing), or swap an exact passage.
+export function applyOp(body: string, op: WikiOp): string {
+ const text = (op.text ?? '').trim()
+ if (op.op === 'create') return body.trim() ? `${body.trimEnd()}\n\n${text}\n` : `${text}\n`
+ if (op.op === 'replace') {
+ if (!op.old || !body.includes(op.old)) throw new Error(L(`O trecho a trocar não está mais em "${op.page}".`, `The passage to swap is no longer in "${op.page}".`))
+ return body.replace(op.old, op.new ?? '')
+ }
+ if (!op.section) return `${body.trimEnd()}\n\n${text}\n`
+ const lines = body.replace(/\s+$/, '').split('\n')
+ const head = lines.findIndex((l) => /^#{1,6}\s/.test(l) && l.replace(/^#+\s*/, '').trim().toLowerCase() === op.section!.trim().toLowerCase())
+ if (head < 0) return `${body.trimEnd()}\n\n## ${op.section.trim()}\n${text}\n`
+ let end = lines.length
+ const level = /^#+/.exec(lines[head]!)![0].length
+ for (let k = head + 1; k < lines.length; k++) if (/^#{1,6}\s/.test(lines[k]!) && /^#+/.exec(lines[k]!)![0].length <= level) (end = k), (k = lines.length)
+ let at = end
+ while (at > head + 1 && !lines[at - 1]!.trim()) at--
+ lines.splice(at, 0, text)
+ return `${lines.join('\n')}\n`
+}
+
+// ---------- the agents' tools: read the index, search, open a page ----------
+
+export const WIKI_INDICE: ToolDef = {
+ name: 'wiki_indice',
+ get description() {
+ return L(
+ 'Mostra o índice da wiki: todas as páginas, por tipo, com a primeira linha de cada uma. Comece por aqui pra saber o que já está escrito.',
+ "Shows the wiki's index: every page, by kind, with its first line. Start here to see what's already written."
+ )
+ },
+ inputSchema: { type: 'object', properties: {} }
+}
+export const WIKI_BUSCAR: ToolDef = {
+ name: 'wiki_buscar',
+ get description() {
+ return L(
+ 'Busca nas páginas da wiki por palavras (acento não importa) e traz os trechos que batem, com o título de cada página. Depois abra a página com wiki_ler.',
+ "Searches the wiki's pages by words (accents don't matter) and brings the matching parts, with each page's title. Then open the page with wiki_ler."
+ )
+ },
+ get inputSchema() {
+ return {
+ type: 'object' as const,
+ properties: { busca: { type: 'string', description: L('Palavras que estariam na página, ex.: "orçamento reforma marcos".', 'Words that would be on the page, e.g. "quote renovation marcos".') } },
+ required: ['busca']
+ }
+ }
+}
+export const WIKI_LER: ToolDef = {
+ name: 'wiki_ler',
+ get description() {
+ return L('Abre uma página da wiki inteira, com as páginas que ela liga e as que citam ela.', 'Opens a whole wiki page, with the pages it links to and the ones that cite it.')
+ },
+ get inputSchema() {
+ return { type: 'object' as const, properties: { pagina: { type: 'string', description: L('O título da página, como no índice.', 'The page title, as in the index.') } }, required: ['pagina'] }
+ }
+}
+export const WIKI_TOOLS = [WIKI_INDICE, WIKI_BUSCAR, WIKI_LER]
+export const WIKI_TOOL_NAMES = new Set(WIKI_TOOLS.map((t) => t.name))
+const MAX_READ = 24_000
+
+// One call: the text for the agent, and the step the reply shows.
+export function wikiCall(wiki: Pick<Wiki, 'indexText' | 'search' | 'page' | 'count'>, name: string, args: Record<string, unknown>): { text: string; error?: boolean; step: { label: string; detail: string } } {
+ if (name === WIKI_INDICE.name) {
+ const text = wiki.indexText()
+ return { text: text.length > MAX_READ ? `${text.slice(0, MAX_READ)}\n…` : text, step: { label: L('Leu o índice da wiki', "Read the wiki's index"), detail: L(`${wiki.count()} páginas`, `${wiki.count()} pages`) } }
+ }
+ if (name === WIKI_BUSCAR.name) {
+ const busca = typeof args['busca'] === 'string' ? args['busca'].trim() : ''
+ if (!busca) return { text: L('Faltou o que buscar.', 'Missing what to search for.'), error: true, step: { label: L('Buscou na wiki', 'Searched the wiki'), detail: '' } }
+ const hits = wiki.search(busca, 8)
+ const step = { label: L('Buscou na wiki', 'Searched the wiki'), detail: `${busca} · ${hits.length === 1 ? L('1 página', '1 page') : L(`${hits.length} páginas`, `${hits.length} pages`)}` }
+ if (!hits.length) return { text: L(`Nenhuma página com "${busca}". Tente outras palavras ou veja o índice; se não estiver lá, a wiki não diz: não invente.`, `No page with "${busca}". Try other words or look at the index; if it isn't there, the wiki doesn't say: don't make it up.`), step }
+ return { text: hits.map((h) => `- [[${h.title}]] (${h.kind}): ${h.snippet.replace(/\s+/g, ' ')}`).join('\n'), step }
+ }
+ const pagina = typeof args['pagina'] === 'string' ? args['pagina'].replace(/^\[\[|\]\]$/g, '').trim() : ''
+ const p = pagina ? wiki.page(pagina) : undefined
+ if (!p) return { text: L(`Não há página "${pagina}". Veja os títulos com wiki_indice.`, `There's no page "${pagina}". See the titles with wiki_indice.`), error: true, step: { label: L('Abriu na wiki', 'Opened in the wiki'), detail: pagina } }
+ const body = p.body.length > MAX_READ ? `${p.body.slice(0, MAX_READ)}\n…` : p.body
+ const extra = [p.backlinks.length && L(`Citada por: ${p.backlinks.map((t) => `[[${t}]]`).join(', ')}`, `Cited by: ${p.backlinks.map((t) => `[[${t}]]`).join(', ')}`)].filter(Boolean)
+ return { text: `# ${p.title}\n(${p.kind}, ${new Date(p.updatedAt).toLocaleDateString(locale())})\n\n${body}${extra.length ? `\n\n${extra.join('\n')}` : ''}`, step: { label: L('Leu na wiki', 'Read in the wiki'), detail: p.title } }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index de6c879..67379aa 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -37,6 +37,8 @@ const moved: Moved =
if (moved === 'old-app-open' || moved === 'keychain-denied') app.setPath('userData', join(app.getPath('temp'), 'tucano-esperando'))
const dataDir = (): string => process.env['TUCANO_DATA'] ?? app.getPath('userData')
+// The wiki's folder, as the core says (an Obsidian vault, say): the one folder outside the app's own it may open.
+let wikiFolder = ''
// tucano://artifact/<id>/<name> serves what agents showed in the chat.
protocol.registerSchemesAsPrivileged([{ scheme: 'tucano', privileges: { standard: true, secure: true, supportFetchAPI: true, stream: true } }])
@@ -65,6 +67,7 @@ type CoreRequest =
| { type: 'secret'; id: string; op: 'encrypt' | 'decrypt'; data: string }
| { type: 'open'; url: string }
| { type: 'open_path'; path: string }
+ | { type: 'wiki_dir'; path: string }
| { type: 'notify'; title: string; body: string; conversationId?: string; kind?: 'approval' | 'question' | 'done'; sound?: boolean }
| { type: 'login_item'; open: boolean }
| { type: 'busy'; busy: boolean }
@@ -175,10 +178,12 @@ function handleCore(child: UtilityProcess, msg: CoreRequest): void {
}
} else if (msg.type === 'open') {
if (/^https?:\/\//.test(msg.url)) void shell.openExternal(msg.url)
+ } else if (msg.type === 'wiki_dir') {
+ wikiFolder = normalize(msg.path)
} else if (msg.type === 'open_path') {
// Only folders the app keeps (an agent's computer, the backups), never an arbitrary path.
const path = normalize(msg.path)
- if (path.startsWith(join(dataDir(), 'computers') + sep) || path === join(dataDir(), 'backups')) void shell.openPath(path)
+ if (path.startsWith(join(dataDir(), 'computers') + sep) || path === join(dataDir(), 'backups') || (!!wikiFolder && (path === wikiFolder || path.startsWith(join(wikiFolder, 'fontes', 'arquivos') + sep)))) void shell.openPath(path)
} else if (msg.type === 'notify') {
// Already looking at that conversation: nothing to tell.
if (msg.conversationId && msg.conversationId === viewing && mainWindow?.isFocused()) return
diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx
index b8f1253..4aac7bb 100644
--- a/src/renderer/src/App.tsx
+++ b/src/renderer/src/App.tsx
@@ -7,6 +7,7 @@ import { Lightbox } from './components/Lightbox'
import { AgentPage, ApprovalsPage, ConnectorsPage, SettingsPage } from './components/Pages'
import { UsagePage } from './components/Usage'
import { MemoryPage } from './components/Memory'
+import { WikiView } from './components/Wiki'
import { RoutinesPage } from './components/Routines'
import { SkillsPage } from './components/Skills'
import { ReportPage } from './components/Report'
@@ -86,6 +87,7 @@ export function App(): ReactNode {
{view.kind === 'usage' && <UsagePage />}
{view.kind === 'connectors' && <ConnectorsPage />}
{view.kind === 'memory' && <MemoryPage />}
+ {view.kind === 'wiki' && <WikiView />}
{view.kind === 'routines' && <RoutinesPage />}
{view.kind === 'skills' && <SkillsPage />}
{view.kind === 'report' && <ReportPage />}
diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsx
index 5df35f3..8eff306 100644
--- a/src/renderer/src/components/Conversation.tsx
+++ b/src/renderer/src/components/Conversation.tsx
@@ -3,6 +3,7 @@ import { CODE_SPANS } from '../../../shared/types'
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react'
import Markdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
+import { KeepInWiki, WikiChip, WikiLink, wikiLinks } from './Wiki'
import {
agentById,
conversationTitle,
@@ -234,7 +235,7 @@ function MessageRow({ message, grouped }: { message: Message; grouped: boolean }
{message.run && <RunSteps message={message} />}
{message.text ? (
<div className="md">
- <Markdown remarkPlugins={[remarkGfm]} components={{ pre: CodeBlock }}>{highlightMentions(message.text)}</Markdown>
+ <Markdown remarkPlugins={[remarkGfm]} components={{ pre: CodeBlock, a: (p) => <WikiLink href={p.href}>{p.children}</WikiLink> }}>{highlightMentions(message.text)}</Markdown>
</div>
) : null}
{attached.length > 0 && (
@@ -249,6 +250,7 @@ function MessageRow({ message, grouped }: { message: Message; grouped: boolean }
{message.run?.agentDraft && <AgentProposal message={message} />}
{message.run?.memoryIds?.map((mid) => <MemoryChip key={mid} id={mid} />)}
{message.run?.routineIds?.map((rid) => <RoutineChip key={rid} id={rid} />)}
+ {message.run?.wikiChanges?.map((cid) => <WikiChip key={cid} id={cid} />)}
{message.run?.artifactIds && (
<div className="artifacts">
{message.run.artifactIds.map((aid) => (
@@ -274,6 +276,7 @@ function MessageRow({ message, grouped }: { message: Message; grouped: boolean }
{L('Tentar de novo', 'Try again')}
</button>
)}
+ {message.run?.status === 'done' && message.text.trim() && !message.run.wikiChanges?.length && <KeepInWiki messageId={message.id} />}
{message.run?.receipt && <ReceiptLine receipt={message.run.receipt} />}
</div>
</article>
@@ -310,7 +313,7 @@ function RoutineMessage({ message }: { message: Message }): ReactNode {
</div>
)}
<div className="md">
- <Markdown remarkPlugins={[remarkGfm]} components={{ pre: CodeBlock }}>{highlightMentions(message.text)}</Markdown>
+ <Markdown remarkPlugins={[remarkGfm]} components={{ pre: CodeBlock, a: (p) => <WikiLink href={p.href}>{p.children}</WikiLink> }}>{highlightMentions(message.text)}</Markdown>
</div>
</div>
</article>
@@ -459,6 +462,7 @@ function QuestionCard({ question, answered }: { question: string; answered: bool
// A @handle in code is not bolded (CODE_SPANS, the core's rule too): the box shows and copies the real text.
const boldMentions = (t: string): string => t.replace(/(^|\s)@([a-z0-9_-]{2,32})/gi, '$1**@$2**')
const highlightMentions = (text: string): string => {
+ text = wikiLinks(text)
let out = ''
let last = 0
for (const m of text.matchAll(CODE_SPANS)) {
diff --git a/src/renderer/src/components/Dialogs.tsx b/src/renderer/src/components/Dialogs.tsx
index 60cee68..6ff07c4 100644
--- a/src/renderer/src/components/Dialogs.tsx
+++ b/src/renderer/src/components/Dialogs.tsx
@@ -234,6 +234,7 @@ const fold = (s: string): string =>
const PAGES = (): { label: string; view: View; icon: IconName }[] => [
{ label: L('Aprovações', 'Approvals'), view: { kind: 'approvals' }, icon: 'shield' },
{ label: L('Memória', 'Memory'), view: { kind: 'memory' }, icon: 'book' },
+ { label: 'Wiki', view: { kind: 'wiki' }, icon: 'layers' },
{ label: L('Rotinas', 'Routines'), view: { kind: 'routines' }, icon: 'clock' },
{ label: 'Skills', view: { kind: 'skills' }, icon: 'layers' },
{ label: L('Boletim', 'Report'), view: { kind: 'report' }, icon: 'report' },
diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsx
index fe47f5f..7034fc4 100644
--- a/src/renderer/src/components/Pages.tsx
+++ b/src/renderer/src/components/Pages.tsx
@@ -590,6 +590,36 @@ export function AgentPage({ id, draft: proposed, fromMessage }: { id?: string; d
</Card>
)}
+ {pane('memoria') && (
+ <Card
+ title="Wiki"
+ lead={L('A wiki é o que você e o time sabem, em páginas. Com acesso, o agente consulta antes de responder e cita as páginas.', 'The wiki is what you and the team know, as pages. With access, the agent looks there before replying and cites the pages.')}
+ >
+ <div className="segmented segmented--wide" role="radiogroup" aria-label="Wiki">
+ {([['read', L('Lê a wiki', 'Reads the wiki')], ['none', L('Sem acesso', 'No access')]] as const).map(([value, label]) => (
+ <button
+ key={value}
+ role="radio"
+ aria-checked={(draft.wiki ?? 'read') === value}
+ className={(draft.wiki ?? 'read') === value ? 'is-active' : ''}
+ onClick={() => {
+ if (isNew) return patch({ wiki: value })
+ setDraft((d) => ({ ...d, wiki: value }))
+ patchAgent(draft.id, { wiki: value })
+ }}
+ >
+ {label}
+ </button>
+ ))}
+ </div>
+ <p className="muted small">
+ <button className="link" onClick={() => navigate({ kind: 'wiki' })}>
+ {L('Abrir a wiki', 'Open the wiki')}
+ </button>
+ </p>
+ </Card>
+ )}
+
{pane('perfil') && (
<Card title={L('Harness e modelo', 'Harness and model')} lead={L('O agente roda num dos harnesses que você usa, como você o configurou: no seu plano, no gateway da empresa ou no seu provedor.', 'The agent runs on one of the harnesses you use, the way you set it up: on your plan, your company’s gateway or your provider.')}>
<ModelPicker value={draft.modelId} onChange={(modelId) => patch({ modelId })} />
diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsx
index 3941b0b..6f25ff7 100644
--- a/src/renderer/src/components/Sidebar.tsx
+++ b/src/renderer/src/components/Sidebar.tsx
@@ -18,13 +18,15 @@ import {
type Agent,
type View
} from '../store'
+import { call } from '../rpc'
import { ContextMenu, type MenuItem, type MenuState } from './Dialogs'
import { FoldToggle, useFold } from './Fold'
import { GettingStarted } from './Onboarding'
import { UpdateNote } from './Update'
import { AgentAvatar, Icon, TucaMark, type IconName } from './ui'
-const same = (a: View | null, b: View): boolean => JSON.stringify(a) === JSON.stringify(b)
+// The wiki stays lit on any of its pages.
+const same = (a: View | null, b: View): boolean => (b.kind === 'wiki' ? a?.kind === 'wiki' : JSON.stringify(a) === JSON.stringify(b))
function NavItem({ view, icon, label, badge }: { view: View; icon: IconName; label: string; badge?: number }): ReactNode {
const active = useStore((s) => same(s.view, view))
@@ -80,11 +82,18 @@ export function Sidebar(): ReactNode {
e.preventDefault()
setMenu({ x: e.clientX, y: e.clientY, items })
}
+ // The wiki's curator reads every conversation; one can be kept out (a personal DM, say).
+ const wikiItem = (id: string, on: boolean): MenuItem => ({
+ label: on ? L('Não guardar na wiki', "Don't keep in the wiki") : L('Voltar a guardar na wiki', 'Keep in the wiki again'),
+ icon: 'layers',
+ onClick: () => void call('setWikiCapture', { conversationId: id, on: !on })
+ })
const channelMenu = (c: (typeof channels)[number]): MenuItem[] => [
{ label: L('Adicionar ou remover agentes…', 'Add or remove agents…'), icon: 'users', onClick: () => openDialog({ kind: 'members', id: c.id }) },
{ label: L('Renomear…', 'Rename…'), icon: 'edit', onClick: () => openDialog({ kind: 'rename', id: c.id }) },
{ label: L('Mudar o tema…', 'Change the topic…'), icon: 'hash', onClick: () => openDialog({ kind: 'topic', id: c.id }) },
...(c.unread ? [{ label: L('Marcar como lido', 'Mark as read'), icon: 'check' as const, onClick: () => markRead(c.id) }] : []),
+ wikiItem(c.id, c.wikiCapture !== false),
'separator',
{
label: L('Excluir canal…', 'Delete channel…'),
@@ -98,6 +107,7 @@ export function Sidebar(): ReactNode {
const dmMenu = (id: string, agentId: string, agentName: string): MenuItem[] => [
{ label: L(`Ver ${agentName}`, `See ${agentName}`), icon: 'eye', onClick: () => navigate({ kind: 'agent', id: agentId }) },
{ label: L('Marcar como lido', 'Mark as read'), icon: 'check', onClick: () => markRead(id) },
+ wikiItem(id, s.conversations.find((x) => x.id === id)?.wikiCapture !== false),
'separator',
{
label: L('Apagar a conversa…', 'Delete the conversation…'),
@@ -156,6 +166,7 @@ export function Sidebar(): ReactNode {
<TucaItem />
<NavItem view={{ kind: 'approvals' }} icon="shield" label={L('Aprovações', 'Approvals')} badge={pending} />
<NavItem view={{ kind: 'memory' }} icon="book" label={L('Memória', 'Memory')} badge={suggestions} />
+ <NavItem view={{ kind: 'wiki' }} icon="layers" label="Wiki" />
<NavItem view={{ kind: 'routines' }} icon="clock" label={L('Rotinas', 'Routines')} />
<NavItem view={{ kind: 'skills' }} icon="layers" label="Skills" badge={proposals} />
<NavItem view={{ kind: 'report' }} icon="report" label={L('Boletim', 'Report')} />
diff --git a/src/renderer/src/components/Wiki.tsx b/src/renderer/src/components/Wiki.tsx
new file mode 100644
index 0000000..1a752e4
--- /dev/null
+++ b/src/renderer/src/components/Wiki.tsx
@@ -0,0 +1,1781 @@
+// The wiki: what you and the team know, as linked pages (an LLM wiki, after Karpathy). The
+// pages are Markdown files in a folder Obsidian opens as is; the agents read them, search
+// them and cite them as [[Title]]. Here: one place with a rail (the home, what waits for you,
+// the sources, what needs care, and the pages by kind) and, beside it, the map of the pages,
+// a page with what links to it, the sources, the review; the editor takes the whole screen.
+import { L, locale } from '../../../shared/lang'
+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react'
+import { createPortal } from 'react-dom'
+import Markdown from 'react-markdown'
+import remarkGfm from 'remark-gfm'
+import { call } from '../rpc'
+import { agentById, navigate, updateSettings, useStore, type View, type WikiChange, type WikiFinding, type WikiHit, type WikiImport, type WikiPage, type WikiPageInfo, type WikiReview, type WikiSource, type WikiVersion } from '../store'
+import { Sheet, Toggle } from './Pages'
+import { AgentAvatar, Icon, type IconName } from './ui'
+
+const DEFAULT_KINDS = (): string[] => [L('Pessoa', 'Person'), L('Projeto', 'Project'), L('Assunto', 'Topic'), L('Decisão', 'Decision')]
+const CODE = /```[\s\S]*?```|`[^`\n]*`/g
+
+type Graph = { nodes: { title: string; kind: string; links: number; missing?: boolean }[]; edges: [string, string][] }
+type WikiData = { dir: string; pages: WikiPageInfo[]; kinds: string[]; log: string[]; pending: number; findings: number; server: boolean; graph: Graph; recent: Omit<WikiVersion, 'before' | 'after'>[]; sources: number }
+type WikiViewState = Extract<View, { kind: 'wiki' }>
+
+// ---------- small things used everywhere ----------
+
+// Each kind of page has a color: the usual four always the same one, any other one by its name.
+const KNOWN: Record<string, string> = { pessoa: 'rose', pessoas: 'rose', person: 'rose', people: 'rose', projeto: 'indigo', projetos: 'indigo', project: 'indigo', projects: 'indigo', assunto: 'teal', assuntos: 'teal', topic: 'teal', topics: 'teal', decisao: 'amber', decisoes: 'amber', decision: 'amber', decisions: 'amber', cliente: 'violet', clientes: 'violet', client: 'violet', clients: 'violet' }
+const PALETTE = ['indigo', 'rose', 'teal', 'amber', 'violet', 'sky', 'green', 'graphite']
+const fold = (s: string): string => s.toLowerCase().normalize('NFD').replace(/\p{M}/gu, '').trim()
+// The wiki's other kinds (an Obsidian vault's folders, say) take the colors the usual ones
+// leave free, the most used first, so no two kinds look alike while there are colors left.
+let given = new Map<string, string>()
+export function setKinds(kinds: [string, number][]): void {
+ const next = new Map<string, string>()
+ const taken = new Set<string>()
+ for (const [k] of kinds) if (KNOWN[fold(k)] && !taken.has(KNOWN[fold(k)]!)) (next.set(fold(k), KNOWN[fold(k)]!), taken.add(KNOWN[fold(k)]!))
+ for (const [k] of kinds) {
+ if (next.has(fold(k))) continue
+ const free = PALETTE.find((c) => !taken.has(c)) ?? PALETTE[next.size % PALETTE.length]!
+ next.set(fold(k), free)
+ taken.add(free)
+ }
+ given = next
+}
+export function kindColor(kind: string): string {
+ if (!kind) return 'var(--text-3)'
+ const k = fold(kind)
+ const c = given.get(k) ?? KNOWN[k]
+ if (c) return `var(--c-${c})`
+ let h = 0
+ for (const ch of k) h = (h * 31 + ch.charCodeAt(0)) >>> 0
+ return `var(--c-${PALETTE[h % PALETTE.length]})`
+}
+
+function KindPill({ kind, small }: { kind: string; small?: boolean }): ReactNode {
+ if (!kind) return null
+ return (
+ <span className={`wk-pill ${small ? 'wk-pill--sm' : ''}`} style={{ ['--k' as string]: kindColor(kind) }}>
+ <i />
+ {kind}
+ </span>
+ )
+}
+
+function rel(t: number): string {
+ const s = (Date.now() - t) / 1000
+ const f = new Intl.RelativeTimeFormat(locale(), { numeric: 'auto' })
+ if (s < 50) return L('agora', 'just now')
+ if (s < 3600) return f.format(-Math.round(s / 60), 'minute')
+ if (s < 86400) return f.format(-Math.round(s / 3600), 'hour')
+ if (s < 86400 * 7) return f.format(-Math.round(s / 86400), 'day')
+ return new Date(t).toLocaleDateString(locale(), { day: 'numeric', month: 'short' })
+}
+const when = (t: number): string => new Date(t).toLocaleString(locale(), { dateStyle: 'short', timeStyle: 'short' })
+
+// Who changed something: you, an agent, the curator, the review, or another app (Obsidian).
+function useWho(): (by: string) => string {
+ const me = useStore((s) => s.me.name)
+ const state = useStore((s) => s)
+ return (by) => (by === 'me' ? me : by === 'outside' ? L('fora do Tucano', 'outside Tucano') : by === 'auto' ? L('o curador', 'the curator') : by === 'review' ? L('a revisão', 'the review') : by === 'import' ? L('veio do Obsidian', 'came from Obsidian') : (agentById(state, by)?.name ?? by))
+}
+function Who({ by, size = 22 }: { by: string; size?: number }): ReactNode {
+ const me = useStore((s) => s.me)
+ const agent = useStore((s) => (by.length > 20 ? agentById(s, by) : undefined))
+ if (agent) return <AgentAvatar agent={agent} size={size} />
+ const icon: IconName | null = by === 'auto' ? 'layers' : by === 'review' ? 'shield' : by === 'outside' || by === 'import' ? 'folder' : null
+ return (
+ <span className={`wk-who ${by === 'auto' || by === 'review' ? 'wk-who--curator' : ''}`} style={{ width: size, height: size, fontSize: size * 0.42 }}>
+ {icon ? <Icon name={icon} size={Math.round(size * 0.55)} /> : me.initials}
+ </span>
+ )
+}
+
+function useWikiData(): WikiData | null {
+ const rev = useStore((s) => s.wikiRev)
+ const [data, setData] = useState<WikiData | null>(null)
+ useEffect(() => void call('wiki').then((d) => setData(d as WikiData)), [rev])
+ return data
+}
+
+// ---------- links ----------
+
+// [[Title]] and [[Title|shown]] as links the Markdown renderer can hand to WikiLink, outside code.
+export function wikiLinks(text: string): string {
+ const swap = (t: string): string =>
+ t
+ .replace(/^(>\s*)\[!(\w+)\][+-]?[ \t]*(.*)$/gm, (_, q: string, type: string, title: string) => `${q}**${title.trim() || type.charAt(0).toUpperCase() + type.slice(1)}** `) // an Obsidian callout: its title in bold
+ .replace(/\s?\((\[\[fontes\/[^\]\n]+\]\])\)/g, ' $1') // "(source)" after a passage: the badge says it
+ // ![[foto.png]]: an attachment in the vault, shown by name
+ .replace(/!\[\[([^\]|#\n]+\.(?!md\])[a-z0-9]{2,5})(?:\|[^\]\n]*)?\]\]/gi, (_, file: string) => `[${file.split('/').pop()}](#att/${encodeURIComponent(file)})`)
+ // [[Clientes/Marcos Lima]] is the page Marcos Lima, as in Obsidian
+ .replace(/!?\[\[([^\]|#\n]+)(?:#[^\]|\n]*)?(?:\|([^\]\n]+))?\]\]/g, (_, target: string, shown?: string) => {
+ const t = target.trim()
+ const title = t.startsWith('fontes/') ? t : t.replace(/\.md$/i, '').split('/').pop()!.trim()
+ return `[${(shown ?? title).trim()}](#wiki/${encodeURIComponent(title)})`
+ })
+ let out = ''
+ let last = 0
+ for (const m of text.matchAll(CODE)) {
+ out += swap(text.slice(last, m.index)) + m[0]
+ last = m.index! + m[0].length
+ }
+ return out + swap(text.slice(last))
+}
+
+// What a link points to, shown when the pointer rests on it.
+const peeks = new Map<string, Promise<WikiPage | null>>()
+let peekRev = -1
+function peek(title: string, rev: number): Promise<WikiPage | null> {
+ if (rev !== peekRev) (peeks.clear(), (peekRev = rev))
+ let p = peeks.get(title)
+ if (!p) peeks.set(title, (p = call('wikiPage', { title })))
+ return p
+}
+
+function Peek({ title, rect }: { title: string; rect: DOMRect }): ReactNode {
+ const rev = useStore((s) => s.wikiRev)
+ const [page, setPage] = useState<WikiPage | null | undefined>(undefined)
+ useEffect(() => void peek(title, rev).then(setPage), [title, rev])
+ if (page === undefined) return null
+ const below = rect.top < 220
+ const style = { left: Math.min(Math.max(12, rect.left + rect.width / 2 - 160), window.innerWidth - 332), ...(below ? { top: rect.bottom + 8 } : { bottom: window.innerHeight - rect.top + 8 }) }
+ return createPortal(
+ <div className="wk-peek" style={style}>
+ {page ? (
+ <>
+ <KindPill kind={page.kind} small />
+ <b>{page.title}</b>
+ {page.summary && <p>{page.summary}</p>}
+ <small>
+ {L('atualizada', 'updated')} {rel(page.updatedAt)}
+ {page.backlinks.length > 0 && ` · ${page.backlinks.length === 1 ? L('1 página liga pra ela', '1 page links here') : L(`${page.backlinks.length} páginas ligam pra ela`, `${page.backlinks.length} pages link here`)}`}
+ </small>
+ </>
+ ) : (
+ <>
+ <b>{title}</b>
+ <p>{L('Ainda não existe. Clique pra escrever.', "Doesn't exist yet. Click to write it.")}</p>
+ </>
+ )}
+ </div>,
+ document.body
+ )
+}
+
+// A link inside rendered Markdown: a wiki page opens here; anything else stays a link.
+export function WikiLink({ href, children, missing }: { href?: string; children?: ReactNode; missing?: Set<string> }): ReactNode {
+ const [hover, setHover] = useState<DOMRect | null>(null)
+ const timer = useRef<ReturnType<typeof setTimeout>>(undefined)
+ if (href?.startsWith('#att/'))
+ return (
+ <span className="wiki-link wiki-link--source wiki-link--file" title={decodeURIComponent(href.slice(5))}>
+ <Icon name="image" size={11} />
+ {children}
+ </span>
+ )
+ if (!href?.startsWith('#wiki/')) return <a href={href}>{children}</a>
+ const title = decodeURIComponent(href.slice(6))
+ if (title.startsWith('fontes/'))
+ return (
+ <button type="button" className="wiki-link wiki-link--source" title={L('Abrir a fonte', 'Open the source')} onClick={() => navigate({ kind: 'wiki', source: title })}>
+ <Icon name="book" size={11} />
+ {children}
+ </button>
+ )
+ const isMissing = missing?.has(title.toLowerCase())
+ return (
+ <>
+ <button
+ type="button"
+ className={`wiki-link ${isMissing ? 'is-missing' : ''}`}
+ onMouseEnter={(e) => {
+ const r = e.currentTarget.getBoundingClientRect()
+ timer.current = setTimeout(() => setHover(r), 380)
+ }}
+ onMouseLeave={() => (clearTimeout(timer.current), setHover(null))}
+ onClick={() => (clearTimeout(timer.current), setHover(null), navigate({ kind: 'wiki', title, ...(isMissing ? { edit: true } : {}) }))}
+ >
+ {children}
+ </button>
+ {hover && <Peek title={title} rect={hover} />}
+ </>
+ )
+}
+
+const mdLinks = (missing?: Set<string>) => ({ a: (p: { href?: string; children?: ReactNode }) => <WikiLink href={p.href} missing={missing}>{p.children}</WikiLink> })
+
+// ---------- the map ----------
+
+type Pos = { x: number; y: number }
+type Cam = { x: number; y: number; k: number }
+type Body = { x: number; y: number; vx: number; vy: number; held?: boolean }
+const SPREAD = 1.6 // from the simulation's units to the map's
+
+// One step of the forces: pages push each other away, links pull, the middle holds them.
+// A page being dragged stays under the pointer and pulls its neighbors along.
+function tick(bodies: Body[], links: (readonly [number, number])[], deg: Uint16Array, heat: number): void {
+ const n = bodies.length
+ for (let i = 0; i < n; i++)
+ for (let j = i + 1; j < n; j++) {
+ const a = bodies[i]!
+ const b = bodies[j]!
+ const dx = a.x - b.x
+ const dy = a.y - b.y
+ const d2 = Math.max(dx * dx + dy * dy, 30)
+ const f = 70 / d2
+ a.vx += dx * f
+ a.vy += dy * f
+ b.vx -= dx * f
+ b.vy -= dy * f
+ }
+ for (const [i, j] of links) {
+ const a = bodies[i]!
+ const b = bodies[j]!
+ const dx = b.x - a.x
+ const dy = b.y - a.y
+ const d = Math.sqrt(dx * dx + dy * dy) || 1
+ const f = ((d - 70) / d) * 0.06
+ a.vx += dx * f
+ a.vy += dy * f
+ b.vx -= dx * f
+ b.vy -= dy * f
+ }
+ for (let i = 0; i < n; i++) {
+ const b = bodies[i]!
+ // a page with no links would drift off; it's held closer
+ const g = deg[i]! ? 0.009 : 0.03
+ b.vx -= b.x * g
+ b.vy -= b.y * g * 1.6
+ if (b.held) {
+ b.vx = 0
+ b.vy = 0
+ continue
+ }
+ b.x += b.vx * heat
+ b.y += b.vy * heat
+ b.vx *= 0.55
+ b.vy *= 0.55
+ }
+}
+
+// The pages as bodies of a small physics, kept across renders: a new page lands next to one it
+// links to and the rest makes room; the first time, it settles before it's shown.
+function useBodies(graph: Graph): { bodies: Map<string, Body>; kick: (heat: number) => void; frame: number } {
+ const bodies = useRef(new Map<string, Body>()).current
+ const heat = useRef(0)
+ const loop = useRef(0)
+ const [frame, setFrame] = useState(0)
+ const parts = useRef<{ list: Body[]; links: (readonly [number, number])[]; deg: Uint16Array }>({ list: [], links: [], deg: new Uint16Array() })
+
+ useMemo(() => {
+ const first = bodies.size === 0
+ const titles = new Set(graph.nodes.map((n) => n.title))
+ for (const t of [...bodies.keys()]) if (!titles.has(t)) bodies.delete(t)
+ graph.nodes.forEach((nd, i) => {
+ if (bodies.has(nd.title)) return
+ const friend = graph.edges.find(([a, b]) => (a === nd.title && bodies.has(b)) || (b === nd.title && bodies.has(a)))
+ const near = friend ? bodies.get(friend[0] === nd.title ? friend[1] : friend[0])! : null
+ // a golden spiral to start from, so the same wiki always lands the same way
+ const r = 16 * Math.sqrt(i + 1)
+ const a = i * 2.399963
+ bodies.set(nd.title, near ? { x: near.x + Math.cos(a) * 30, y: near.y + Math.sin(a) * 30, vx: 0, vy: 0 } : { x: Math.cos(a) * r, y: Math.sin(a) * r, vx: 0, vy: 0 })
+ })
+ const idx = new Map(graph.nodes.map((n, i) => [n.title, i]))
+ const list = graph.nodes.map((n) => bodies.get(n.title)!)
+ const links = graph.edges.map(([a, b]) => [idx.get(a), idx.get(b)] as const).filter((l): l is readonly [number, number] => l[0] !== undefined && l[1] !== undefined)
+ const deg = new Uint16Array(list.length)
+ for (const [a, b] of links) deg[a]!++, deg[b]!++
+ parts.current = { list, links, deg }
+ if (first) for (let it = 0, iters = list.length > 250 ? 140 : 300; it < iters; it++) tick(list, links, deg, 0.3 + (1 - it / iters))
+ else heat.current = Math.max(heat.current, 0.6)
+ }, [graph])
+
+ const run = (): void => {
+ const { list, links, deg } = parts.current
+ tick(list, links, deg, heat.current)
+ heat.current *= 0.965
+ setFrame((f) => f + 1)
+ const busy = list.some((b) => b.held)
+ if (heat.current > 0.02 || busy) loop.current = requestAnimationFrame(run)
+ else loop.current = 0
+ }
+ const kick = (h: number): void => {
+ heat.current = Math.max(heat.current, h)
+ if (!loop.current) loop.current = requestAnimationFrame(run)
+ }
+ useEffect(() => {
+ if (heat.current > 0.02) kick(heat.current)
+ }, [graph])
+ useEffect(() => () => cancelAnimationFrame(loop.current), [])
+ return { bodies, kick, frame }
+}
+
+function useSize(): [React.RefObject<HTMLDivElement | null>, { w: number; h: number }] {
+ const ref = useRef<HTMLDivElement>(null)
+ const [size, setSize] = useState({ w: 0, h: 0 })
+ useLayoutEffect(() => {
+ if (!ref.current) return
+ const ro = new ResizeObserver(([e]) => setSize({ w: Math.round(e!.contentRect.width), h: Math.round(e!.contentRect.height) }))
+ ro.observe(ref.current)
+ return () => ro.disconnect()
+ }, [])
+ return [ref, size]
+}
+
+const PANEL = 560 // the panel's width; the map keeps what's left of it in view
+const ease = (p: number): number => (p < 0.5 ? 4 * p * p * p : 1 - (-2 * p + 2) ** 3 / 2)
+
+// The whole wiki as a map you can move around: drag the empty map to move it, drag a page to
+// pull it (and what it links to) around, pinch or the mouse wheel (or ⌘/Ctrl + scroll) to zoom. A page picked flies to
+// the middle of what the panel leaves free, with its links lit.
+function WikiCanvas({ graph, selected, pending, only, panel }: { graph: Graph; selected?: string; pending: Set<string>; only: string | null; panel: boolean }): ReactNode {
+ const [ref, size] = useSize()
+ const { bodies, kick } = useBodies(graph)
+ const world = (t: string): Pos | undefined => {
+ const b = bodies.get(t)
+ return b && { x: b.x * SPREAD, y: b.y * SPREAD }
+ }
+ const [cam, setCam] = useState<Cam | null>(null)
+ const camRef = useRef(cam)
+ camRef.current = cam
+ const anim = useRef(0)
+ const [hover, setHover] = useState<string | null>(null)
+ const [panning, setPanning] = useState(false)
+ const [holding, setHolding] = useState<string | null>(null)
+ const drag = useRef<{ x: number; y: number; cx: number; cy: number; moved: boolean; page?: string | null; missing?: boolean } | null>(null)
+ const free = (): { w: number; h: number } => ({ w: size.w - (panel && size.w > 980 ? PANEL + 24 : 0), h: size.h })
+
+ const fit = (): Cam => {
+ let x0 = Infinity
+ let x1 = -Infinity
+ let y0 = Infinity
+ let y1 = -Infinity
+ for (const b of bodies.values()) (x0 = Math.min(x0, b.x * SPREAD)), (x1 = Math.max(x1, b.x * SPREAD)), (y0 = Math.min(y0, b.y * SPREAD)), (y1 = Math.max(y1, b.y * SPREAD))
+ if (!isFinite(x0)) return { x: 0, y: 0, k: 1 }
+ const a = free()
+ const k = Math.max(0.3, Math.min((a.w - 260) / Math.max(1, x1 - x0), (a.h - 180) / Math.max(1, y1 - y0), 1.5))
+ return { k, x: a.w / 2 - ((x0 + x1) / 2) * k, y: a.h / 2 - ((y0 + y1) / 2) * k }
+ }
+ const fly = (to: Cam, ms = 700): void => {
+ cancelAnimationFrame(anim.current)
+ const from = camRef.current
+ if (!from) return setCam(to)
+ const t0 = performance.now()
+ const step = (t: number): void => {
+ const e = ease(Math.min(1, (t - t0) / ms))
+ setCam({ x: from.x + (to.x - from.x) * e, y: from.y + (to.y - from.y) * e, k: from.k + (to.k - from.k) * e })
+ if (e < 1) anim.current = requestAnimationFrame(step)
+ }
+ anim.current = requestAnimationFrame(step)
+ }
+ const zoom = (f: number, at?: Pos): void => {
+ const c = camRef.current
+ if (!c) return
+ const k = Math.max(0.3, Math.min(3, c.k * f))
+ const p = at ?? { x: free().w / 2, y: size.h / 2 }
+ setCam({ k, x: p.x - (p.x - c.x) * (k / c.k), y: p.y - (p.y - c.y) * (k / c.k) })
+ }
+
+ // the first look fits it all; then it follows the page that's open, and fits again when it closes
+ const had = useRef<string | undefined>(undefined)
+ useEffect(() => {
+ if (!size.w) return
+ const p = selected ? world(selected) : undefined
+ const was = had.current
+ had.current = selected
+ if (!camRef.current) {
+ const f = fit()
+ const k = Math.max(f.k, 1.15)
+ setCam(p ? { k, x: free().w / 2 - p.x * k, y: size.h / 2 - p.y * k } : f)
+ return
+ }
+ if (p) {
+ const k = Math.max(camRef.current.k, 1.15)
+ fly({ k, x: free().w / 2 - p.x * k, y: size.h / 2 - p.y * k })
+ } else if (was && !panel) fly(fit())
+ }, [selected, panel, size.w > 0])
+ useEffect(() => () => cancelAnimationFrame(anim.current), [])
+
+ // scrolling moves it; pinching (or ⌘/Ctrl + scroll) zooms where the pointer is
+ useEffect(() => {
+ const el = ref.current
+ if (!el) return
+ const onWheel = (e: WheelEvent): void => {
+ e.preventDefault()
+ cancelAnimationFrame(anim.current)
+ const r = el.getBoundingClientRect()
+ // a mouse wheel (notches of 100 or 120, or lines) zooms too; a trackpad's two fingers move
+ const wheel = e.deltaMode !== 0 || (e.deltaX === 0 && e.deltaY !== 0 && (Math.abs(e.deltaY) % 100 === 0 || Math.abs(e.deltaY) % 120 === 0))
+ if (e.ctrlKey || e.metaKey || wheel) zoom(Math.exp(-(wheel ? Math.sign(e.deltaY) * 0.18 : e.deltaY * 0.012)), { x: e.clientX - r.left, y: e.clientY - r.top })
+ else {
+ const c = camRef.current
+ if (c) setCam({ ...c, x: c.x - e.deltaX, y: c.y - e.deltaY })
+ }
+ }
+ el.addEventListener('wheel', onWheel, { passive: false })
+ return () => el.removeEventListener('wheel', onWheel)
+ })
+
+ const near = useMemo(() => {
+ const m = new Map<string, Set<string>>()
+ for (const [a, b] of graph.edges) (m.get(a) ?? m.set(a, new Set()).get(a)!).add(b), (m.get(b) ?? m.set(b, new Set()).get(b)!).add(a)
+ return m
+ }, [graph])
+ const lit = holding ?? hover ?? selected ?? null
+ const around = lit ? near.get(lit) : undefined
+ const isNear = (t: string): boolean => !lit || t === lit || !!around?.has(t)
+ const kindOf = new Map(graph.nodes.map((n) => [n.title, n.kind]))
+ const shown = (t: string): boolean => !only || kindOf.get(t) === only
+
+ const k = cam?.k ?? 1
+ const at = (t: string): Pos | null => {
+ const p = world(t)
+ return p && cam ? { x: p.x * k + cam.x, y: p.y * k + cam.y } : null
+ }
+ const scale = 0.8 + 0.2 * Math.min(k, 1.8)
+ const many = graph.nodes.length > 40
+ return (
+ <div
+ ref={ref}
+ className={`wk-canvas ${panning ? 'is-panning' : ''} ${holding ? 'is-holding' : ''}`}
+ style={cam ? { backgroundPosition: `${cam.x}px ${cam.y}px`, backgroundSize: `${26 * k}px ${26 * k}px` } : undefined}
+ onPointerDown={(e) => {
+ if (!cam || e.button !== 0) return
+ cancelAnimationFrame(anim.current)
+ const hit = (e.target as Element).closest('[data-page]')
+ drag.current = { x: e.clientX, y: e.clientY, cx: cam.x, cy: cam.y, moved: false, page: hit?.getAttribute('data-page'), missing: !!hit?.getAttribute('data-missing') }
+ e.currentTarget.setPointerCapture(e.pointerId)
+ }}
+ onPointerMove={(e) => {
+ const d = drag.current
+ if (!d || !cam) return
+ const dx = e.clientX - d.x
+ const dy = e.clientY - d.y
+ if (!d.moved && Math.hypot(dx, dy) > 4) {
+ d.moved = true
+ if (d.page) setHolding(d.page)
+ else setPanning(true)
+ }
+ if (!d.moved) return
+ if (d.page) {
+ // the page follows the pointer; its links pull the others after it
+ const b = bodies.get(d.page)
+ const r = ref.current!.getBoundingClientRect()
+ if (b) {
+ b.held = true
+ b.x = (e.clientX - r.left - cam.x) / cam.k / SPREAD
+ b.y = (e.clientY - r.top - cam.y) / cam.k / SPREAD
+ kick(0.5)
+ }
+ } else setCam({ ...cam, x: d.cx + dx, y: d.cy + dy })
+ }}
+ onPointerUp={() => {
+ const d = drag.current
+ drag.current = null
+ setPanning(false)
+ setHolding(null)
+ if (!d) return
+ if (d.moved && d.page) {
+ const b = bodies.get(d.page)
+ if (b) b.held = false
+ kick(0.5)
+ } else if (!d.moved) {
+ // a click: on a page opens it; on the empty map closes what's open
+ if (d.page) navigate({ kind: 'wiki', title: d.page, ...(d.missing ? { edit: true } : {}) })
+ else if (panel) navigate({ kind: 'wiki' })
+ }
+ }}
+ >
+ {cam && (
+ <svg width={size.w} height={size.h}>
+ <g className="wk-canvas__edges">
+ {graph.edges.map(([a, b]) => {
+ const p = at(a)
+ const q = at(b)
+ if (!p || !q) return null
+ const hot = !!lit && (a === lit || b === lit)
+ const off = !shown(a) && !shown(b)
+ return <line key={`${a}\n${b}`} x1={p.x} y1={p.y} x2={q.x} y2={q.y} className={hot ? 'is-hot' : lit || off ? 'is-dim' : ''} />
+ })}
+ </g>
+ {graph.nodes.map((nd, i) => {
+ const p = at(nd.title)
+ if (!p) return null
+ const r = (nd.title === selected || nd.title === holding ? 9 : 5 + Math.sqrt(nd.links) * 2.4) * scale
+ const label = !many || k > 1.05 || nd.links >= 3 || (!!lit && isNear(nd.title))
+ const dim = !isNear(nd.title) || !shown(nd.title)
+ return (
+ <g
+ key={nd.title}
+ data-page={nd.title}
+ data-missing={nd.missing ? '1' : undefined}
+ className={`wk-node ${nd.missing ? 'is-missing' : ''} ${dim ? 'is-dim' : ''} ${nd.title === lit ? 'is-lit' : ''} ${nd.title === selected ? 'is-sel' : ''} ${nd.title === holding ? 'is-held' : ''}`}
+ style={{ ['--k' as string]: kindColor(nd.kind), ['--i' as string]: i }}
+ transform={`translate(${p.x} ${p.y})`}
+ onPointerEnter={() => !drag.current && setHover(nd.title)}
+ onPointerLeave={() => setHover((h) => (h === nd.title ? null : h))}
+ >
+ <circle className="wk-node__hit" r={r + 12} />
+ {pending.has(nd.title) && <circle className="wk-node__ping" r={r + 4} />}
+ <circle className="wk-node__halo" r={r + 8} />
+ <circle className="wk-node__dot" r={r} />
+ {label && (
+ <text y={r + 15} textAnchor="middle">
+ {nd.title.length > 28 ? `${nd.title.slice(0, 26)}…` : nd.title}
+ </text>
+ )}
+ </g>
+ )
+ })}
+ </svg>
+ )}
+ <div className="wk-zoom" onPointerDown={(e) => e.stopPropagation()} style={{ right: panel && size.w > 980 ? PANEL + 40 : 16 }}>
+ <button title={L('Afastar', 'Zoom out')} onClick={() => zoom(1 / 1.3)}>
+ −
+ </button>
+ <button title={L('Ver tudo', 'Fit all')} onClick={() => fly(fit(), 500)}>
+ <svg width="13" height="13" viewBox="0 0 13 13" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round">
+ <path d="M1.5 4.5v-3h3M8.5 1.5h3v3M11.5 8.5v3h-3M4.5 11.5h-3v-3" />
+ </svg>
+ </button>
+ <button title={L('Aproximar', 'Zoom in')} onClick={() => zoom(1.3)}>
+ +
+ </button>
+ </div>
+ </div>
+ )
+}
+
+// ---------- the place: the map, and a panel over it ----------
+
+export function WikiView(): ReactNode {
+ const view = useStore((s) => s.view)
+ if (view?.kind !== 'wiki') return null
+ if (view.edit) return <WikiEditor key={`edit:${view.title ?? ''}`} title={view.title} />
+ return <WikiShell view={view} />
+}
+
+// The search shortcut as the keyboard in front of the person says it (a browser on a server included).
+const SEARCH_KEY = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.userAgent) ? '⌘K' : 'Ctrl K'
+
+function WikiShell({ view }: { view: WikiViewState }): ReactNode {
+ const data = useWikiData()
+ const rev = useStore((s) => s.wikiRev)
+ const [searching, setSearching] = useState(false)
+ const [settings, setSettings] = useState(false)
+ const [dropping, setDropping] = useState(0)
+ const [dropError, setDropError] = useState<string[]>([])
+ const [only, setOnly] = useState<string | null>(null)
+ const [pending, setPending] = useState<WikiChange[]>([])
+ const [reading, setReading] = useState<WikiSource[]>([])
+ useEffect(() => void Promise.all([call('wikiChanges', { state: 'pending' }), call('wikiChanges', { state: 'conflict' })]).then(([a, b]) => setPending([...a, ...b].filter((c) => c.by !== 'review'))), [rev])
+ useEffect(() => void call('wikiSources').then((l) => setReading(l.filter((s) => s.status === 'reading'))), [rev])
+ const panel = !!(view.title || view.source || view.tab)
+ const close = (): void => navigate({ kind: 'wiki' })
+ const [imported, setImported] = useState<WikiImport | { error: string } | 'busy' | null>(null)
+ const startImport = (): void => {
+ const pick = (window.tucano as unknown as { pickFolder?: () => Promise<string | null> }).pickFolder
+ void pick?.().then((dir) => {
+ if (!dir) return
+ setSettings(false)
+ setImported('busy')
+ void call('wikiImport', { dir }).then(setImported, (e: Error) => setImported({ error: e.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') }))
+ })
+ }
+
+ // ⌘K or / searches, N writes a new page, E edits the open one, Esc closes the panel.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent): void => {
+ const typing = (e.target as HTMLElement | null)?.closest('input, textarea, select, [contenteditable]')
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') return void (e.preventDefault(), setSearching(true))
+ if (typing || e.metaKey || e.ctrlKey || e.altKey || searching || settings) return
+ if (e.key === '/') setSearching(true)
+ else if (e.key.toLowerCase() === 'n') navigate({ kind: 'wiki', edit: true, title: '' })
+ else if (e.key.toLowerCase() === 'e' && view.title) navigate({ kind: 'wiki', title: view.title, edit: true })
+ else if (e.key === 'Escape' && panel) close()
+ else return
+ e.preventDefault()
+ }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ })
+
+ const drop = {
+ onDragEnter: (e: React.DragEvent) => e.dataTransfer.types.includes('Files') && setDropping((n) => n + 1),
+ onDragLeave: () => setDropping((n) => Math.max(0, n - 1)),
+ onDragOver: (e: React.DragEvent) => e.dataTransfer.types.includes('Files') && e.preventDefault(),
+ onDrop: (e: React.DragEvent) => {
+ e.preventDefault()
+ setDropping(0)
+ const fs = [...e.dataTransfer.files]
+ if (fs.length) void addWikiFiles(fs).then((errs) => (setDropError(errs), navigate({ kind: 'wiki', tab: 'sources' })))
+ }
+ }
+
+ const count = data?.pages.length ?? 0
+ const links = data?.graph.edges.length ?? 0
+ const touched = useMemo(() => new Set(pending.flatMap((c) => c.ops.map((o) => o.page))), [pending])
+ const kinds = useMemo(() => {
+ const m = new Map<string, number>()
+ for (const p of data?.pages ?? []) m.set(p.kind, (m.get(p.kind) ?? 0) + 1)
+ const list = [...m.entries()].sort((a, b) => b[1] - a[1])
+ setKinds(list)
+ return list
+ }, [data])
+ const content = view.source ? <WikiSourceView key={view.source} id={view.source} /> : view.title ? <WikiPageView key={view.title} title={view.title} data={data} /> : view.tab === 'pending' ? <WikiPending /> : view.tab === 'sources' ? <WikiSources errors={dropError} /> : view.tab === 'review' ? <WikiReviewPane /> : null
+
+ return (
+ <Sheet
+ fill
+ title={L('Wiki', 'Wiki')}
+ lede={
+ count > 0
+ ? [count === 1 ? L('1 página', '1 page') : L(`${count} páginas`, `${count} pages`), links === 1 ? L('1 ligação', '1 link') : L(`${links} ligações`, `${links} links`)].join(' · ')
+ : L('O que você e o seu time sabem, em páginas ligadas.', 'What you and your team know, as linked pages.')
+ }
+ actions={
+ <>
+ {kinds.length > 1 && (
+ <div className="wk-kinds" role="group" aria-label={L('Mostrar só um tipo', 'Show only one kind')}>
+ {kinds.slice(0, 6).map(([k, n]) => (
+ <button key={k} className={only === k ? 'is-on' : only ? 'is-dim' : ''} style={{ ['--k' as string]: kindColor(k) }} title={only === k ? L('Mostrar todas', 'Show all') : `${k} · ${n}`} onClick={() => setOnly(only === k ? null : k)}>
+ <i />
+ {k}
+ </button>
+ ))}
+ </div>
+ )}
+ <button className="wk-search-btn" title={L(`Buscar (${SEARCH_KEY})`, `Search (${SEARCH_KEY})`)} onClick={() => setSearching(true)}>
+ <Icon name="search" size={14} />
+ <kbd>{SEARCH_KEY}</kbd>
+ </button>
+ <button className="btn btn--ghost btn--sm wk-icon-btn" title={L('Ajustes da wiki', 'Wiki settings')} onClick={() => setSettings(true)}>
+ <Icon name="gear" size={15} />
+ </button>
+ <button className="btn btn--primary btn--sm" title={L('Nova página (N)', 'New page (N)')} onClick={() => navigate({ kind: 'wiki', edit: true, title: '' })}>
+ <Icon name="plus" size={14} /> {L('Nova página', 'New page')}
+ </button>
+ </>
+ }
+ >
+ {(pending.length > 0 || reading.length > 0 || (data?.findings ?? 0) > 0) && (
+ <div className="cal-watch wk-watch">
+ {pending.length > 0 && <span className="cal-watch__label">{L('Esperando você', 'Waiting for you')}</span>}
+ {pending.slice(0, 3).map((c) => (
+ <button key={c.id} className="cal-watch__chip wk-watch__chip wk-watch__chip--pending" onClick={() => navigate({ kind: 'wiki', tab: 'pending' })}>
+ <i />
+ <span>{c.reason || [...new Set(c.ops.map((o) => o.page))].join(', ')}</span>
+ </button>
+ ))}
+ {pending.length > 3 && (
+ <button className="cal-watch__chip" onClick={() => navigate({ kind: 'wiki', tab: 'pending' })}>
+ {L(`+${pending.length - 3}`, `+${pending.length - 3}`)}
+ </button>
+ )}
+ {reading.map((s) => (
+ <button key={s.id} className="cal-watch__chip wk-watch__chip" onClick={() => navigate({ kind: 'wiki', source: s.file })}>
+ <span className="wk-spin" />
+ <span>{L(`Lendo ${s.title}`, `Reading ${s.title}`)}</span>
+ </button>
+ ))}
+ {(data?.findings ?? 0) > 0 && (
+ <button className="cal-watch__chip wk-watch__chip wk-watch__chip--care" onClick={() => navigate({ kind: 'wiki', tab: 'review' })}>
+ <i />
+ {data!.findings === 1 ? L('1 coisa pra cuidar', '1 thing to look after') : L(`${data!.findings} coisas pra cuidar`, `${data!.findings} things to look after`)}
+ </button>
+ )}
+ </div>
+ )}
+
+ <div className="wk-stage" {...drop}>
+ {data && count === 0 && !panel ? <WikiEmpty onImport={startImport} /> : data && <WikiCanvas graph={data.graph} selected={view.title} pending={touched} only={only} panel={panel} />}
+ {panel && content && (
+ <aside className="wk-panel" key={JSON.stringify([view.title, view.tab, view.source])}>
+ <button className="wk-panel__close" title={L('Fechar (Esc)', 'Close (Esc)')} onClick={close}>
+ <Icon name="x" size={15} />
+ </button>
+ {content}
+ </aside>
+ )}
+ {dropping > 0 && (
+ <div className="wk-drop">
+ <div>
+ <Icon name="down" size={22} />
+ <b>{L('Solte pra trazer pra wiki', 'Drop to bring it into the wiki')}</b>
+ <small>{L('PDF, Word, planilha ou texto. O curador lê e escreve nas páginas.', 'PDF, Word, spreadsheet or text. The curator reads it and writes in the pages.')}</small>
+ </div>
+ </div>
+ )}
+ </div>
+
+ <footer className="cal-foot wk-foot">
+ <button className="text-btn" onClick={() => navigate({ kind: 'wiki', tab: 'sources' })}>
+ <Icon name="book" size={13} /> {data?.sources === 1 ? L('1 fonte', '1 source') : L(`${data?.sources ?? 0} fontes`, `${data?.sources ?? 0} sources`)}
+ </button>
+ <button className="text-btn" onClick={() => navigate({ kind: 'wiki', tab: 'pending' })}>
+ <Icon name="hand" size={13} /> {L('Decisões do curador', "The curator's changes")}
+ </button>
+ <button className="text-btn" onClick={() => navigate({ kind: 'wiki', tab: 'review' })}>
+ <Icon name="shield" size={13} /> {L('Revisar a wiki', 'Review the wiki')}
+ </button>
+ <span className="grow" />
+ <span>{L('Arraste um arquivo pra cá pra trazer pra wiki', 'Drag a file here to bring it in')}</span>
+ </footer>
+ {searching && <WikiSearch pages={data?.pages ?? []} onClose={() => setSearching(false)} />}
+ {settings && <WikiSettingsDialog data={data} onClose={() => setSettings(false)} onImport={startImport} />}
+ {imported && <ImportResult result={imported} onClose={() => setImported(null)} />}
+ </Sheet>
+ )
+}
+
+function WikiEmpty({ onImport }: { onImport: () => void }): ReactNode {
+ // a little constellation, to show what it becomes
+ const dots = [
+ [120, 70, 'rose'],
+ [210, 40, 'indigo'],
+ [290, 95, 'teal'],
+ [190, 135, 'amber'],
+ [70, 140, 'violet'],
+ [330, 30, 'indigo']
+ ] as const
+ const lines = [
+ [0, 1],
+ [1, 2],
+ [1, 3],
+ [0, 3],
+ [0, 4],
+ [2, 5],
+ [1, 5]
+ ]
+ return (
+ <div className="wk-empty">
+ <svg viewBox="0 0 400 170" className="wk-empty__art">
+ {lines.map(([a, b]) => (
+ <line key={`${a}${b}`} x1={dots[a!]![0]} y1={dots[a!]![1]} x2={dots[b!]![0]} y2={dots[b!]![1]} />
+ ))}
+ {dots.map(([x, y, c], i) => (
+ <circle key={i} cx={x} cy={y} r={i === 1 ? 11 : 7} style={{ fill: `var(--c-${c})`, ['--i' as string]: i }} />
+ ))}
+ </svg>
+ <h2>{L('Tudo o que você sabe, num lugar só', 'Everything you know, in one place')}</h2>
+ <p>
+ {L(
+ 'Pessoas, clientes, projetos, decisões. Cada página liga com as outras, e os agentes leem tudo antes de responder. Você escreve, ou deixa o curador escrever pelas conversas e pelos documentos que você traz.',
+ 'People, clients, projects, decisions. Each page links to the others, and the agents read it all before replying. You write it, or let the curator write it from the conversations and the documents you bring.'
+ )}
+ </p>
+ <div className="wk-empty__actions">
+ <button className="btn btn--primary" onClick={() => navigate({ kind: 'wiki', edit: true, title: '' })}>
+ <Icon name="edit" size={14} /> {L('Escrever a primeira página', 'Write the first page')}
+ </button>
+ <button className="btn" onClick={onImport}>
+ <Icon name="folder" size={14} /> {L('Importar do Obsidian', 'Import from Obsidian')}
+ </button>
+ </div>
+ <small className="muted">{L('Já tem um cofre no Obsidian? Ele entra como está, com pastas, links e anexos. O original fica onde está.', 'Already have an Obsidian vault? It comes in as it is, with folders, links and attachments. The original stays where it is.')}</small>
+ </div>
+ )
+}
+
+// What came in from a vault: how much, of what kinds, and what to look at next.
+function ImportResult({ result, onClose }: { result: WikiImport | { error: string } | 'busy'; onClose: () => void }): ReactNode {
+ return (
+ <div className="modal" onMouseDown={(e) => e.target === e.currentTarget && result !== 'busy' && onClose()}>
+ <div className="form-modal wk-settings wk-import">
+ {result === 'busy' ? (
+ <div className="wk-import__busy">
+ <span className="wk-spin" />
+ <b>{L('Trazendo as notas…', 'Bringing the notes in…')}</b>
+ <small className="muted">{L('Copiando as pastas e lendo os links.', 'Copying the folders and reading the links.')}</small>
+ </div>
+ ) : 'error' in result ? (
+ <>
+ <header>
+ <h2>{L('Não deu pra importar', "Couldn't import")}</h2>
+ </header>
+ <p className="field__error">{result.error}</p>
+ <div className="wk-row">
+ <button className="btn btn--sm" onClick={onClose}>
+ {L('Fechar', 'Close')}
+ </button>
+ </div>
+ </>
+ ) : (
+ <>
+ <header>
+ <h2>{L(`${result.from} chegou`, `${result.from} is in`)}</h2>
+ </header>
+ <div className="wk-import__stats">
+ <span>
+ <b>{result.pages}</b>
+ {result.pages === 1 ? L('nota', 'note') : L('notas', 'notes')}
+ </span>
+ <span>
+ <b>{result.links}</b>
+ {result.links === 1 ? L('ligação', 'link') : L('ligações', 'links')}
+ </span>
+ <span>
+ <b>{result.attachments}</b>
+ {result.attachments === 1 ? L('anexo', 'attachment') : L('anexos', 'attachments')}
+ </span>
+ </div>
+ {result.kinds.length > 0 && (
+ <div className="wk-page__chips">
+ {result.kinds.slice(0, 10).map(([k, n]) => (
+ <span key={k} className="wk-pill" style={{ ['--k' as string]: kindColor(k) }}>
+ <i />
+ {k} · {n}
+ </span>
+ ))}
+ </div>
+ )}
+ <small className="muted">
+ {L('Os agentes já leem essas páginas e citam elas nas respostas. O cofre original não mudou.', 'The agents already read these pages and cite them in their replies. The original vault is unchanged.')}
+ {result.missing > 0 && ' ' + L(`${result.missing} ${result.missing === 1 ? 'link aponta' : 'links apontam'} pra notas que ainda não existem: aparecem tracejados no mapa.`, `${result.missing} ${result.missing === 1 ? 'link points' : 'links point'} to notes that don't exist yet: they're dashed on the map.`)}
+ {result.skipped.length > 0 && ' ' + L(`${result.skipped.length} ${result.skipped.length === 1 ? 'arquivo já existia e ficou' : 'arquivos já existiam e ficaram'} como estava.`, `${result.skipped.length} ${result.skipped.length === 1 ? 'file was already here and was left' : 'files were already here and were left'} as they were.`)}
+ </small>
+ <div className="wk-row">
+ <button className="btn btn--primary btn--sm" onClick={onClose}>
+ {L('Ver o mapa', 'See the map')}
+ </button>
+ <button className="btn btn--ghost btn--sm" onClick={() => (onClose(), navigate({ kind: 'wiki', tab: 'review' }))}>
+ {L('Revisar o que chegou', 'Review what came in')}
+ </button>
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ )
+}
+
+// ---------- search ----------
+
+function WikiSearch({ pages, onClose }: { pages: WikiPageInfo[]; onClose: () => void }): ReactNode {
+ const [q, setQ] = useState('')
+ const [hits, setHits] = useState<WikiHit[] | null>(null)
+ const [at, setAt] = useState(0)
+ useEffect(() => {
+ if (!q.trim()) return setHits(null)
+ const t = setTimeout(() => void call('wikiSearch', { q }).then((h) => (setHits(h), setAt(0))), 120)
+ return () => clearTimeout(t)
+ }, [q])
+ const titleHits = q.trim() ? pages.filter((p) => fold(p.title).includes(fold(q))) : []
+ const rows: { title: string; kind: string; snippet?: string }[] = q.trim()
+ ? [...titleHits.map((p) => ({ title: p.title, kind: p.kind, snippet: p.summary })), ...(hits ?? []).filter((h) => !titleHits.some((p) => p.title === h.title))]
+ : [...pages].sort((a, b) => b.updatedAt - a.updatedAt).slice(0, 7).map((p) => ({ title: p.title, kind: p.kind, snippet: p.summary }))
+ const open = (t?: string): void => {
+ onClose()
+ if (t) navigate({ kind: 'wiki', title: t })
+ else if (q.trim()) navigate({ kind: 'wiki', title: q.trim(), edit: true })
+ }
+ return (
+ <div className="modal wk-palette-back" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
+ <div className="wk-palette">
+ <div className="wk-palette__input">
+ <Icon name="search" size={16} />
+ <input
+ autoFocus
+ placeholder={L('Buscar uma pessoa, um projeto, uma decisão…', 'Search a person, a project, a decision…')}
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape') onClose()
+ else if (e.key === 'ArrowDown') (e.preventDefault(), setAt((a) => Math.min(a + 1, rows.length)))
+ else if (e.key === 'ArrowUp') (e.preventDefault(), setAt((a) => Math.max(a - 1, 0)))
+ else if (e.key === 'Enter') open(rows[at]?.title)
+ }}
+ />
+ <kbd>esc</kbd>
+ </div>
+ <div className="wk-palette__list">
+ {!q.trim() && rows.length > 0 && <div className="wk-palette__label">{L('Mexidas há pouco', 'Recently touched')}</div>}
+ {rows.map((r, i) => (
+ <button key={r.title} className={`wk-palette__row ${i === at ? 'is-on' : ''}`} style={{ ['--k' as string]: kindColor(r.kind) }} onMouseEnter={() => setAt(i)} onClick={() => open(r.title)}>
+ <i />
+ <span>
+ <b>{r.title}</b>
+ {r.snippet && (
+ <small>
+ <Markdown allowedElements={['p', 'strong', 'em']} unwrapDisallowed>
+ {r.snippet}
+ </Markdown>
+ </small>
+ )}
+ </span>
+ <em>{r.kind}</em>
+ </button>
+ ))}
+ {q.trim() && (
+ <button className={`wk-palette__row wk-palette__new ${at === rows.length ? 'is-on' : ''}`} onMouseEnter={() => setAt(rows.length)} onClick={() => open()}>
+ <Icon name="plus" size={14} />
+ <span>
+ <b>{L(`Escrever “${q.trim()}”`, `Write “${q.trim()}”`)}</b>
+ <small>{rows.length ? L('Uma página nova com esse título', 'A new page with that title') : L('Nada com esse nome ainda', 'Nothing by that name yet')}</small>
+ </span>
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ )
+}
+
+// ---------- settings ----------
+
+function WikiSettingsDialog({ data, onClose, onImport }: { data: WikiData | null; onClose: () => void; onImport: () => void }): ReactNode {
+ const s = useStore((st) => st.settings)
+ const capture = s.wikiCapture !== false
+ const edits = s.wikiEdits ?? 'approve'
+ const [dir, setDir] = useState(data?.dir ?? '')
+ const [error, setError] = useState('')
+ const pick = (window.tucano as unknown as { pickFolder?: () => Promise<string | null> }).pickFolder
+ const move = (to: string | null): void => void call('setWikiDir', { dir: to }).then((d) => (setDir(d), setError('')), (e: Error) => setError(e.message))
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent): void => void (e.key === 'Escape' && onClose())
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ })
+ return (
+ <div className="modal" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>
+ <div className="form-modal wk-settings">
+ <header>
+ <h2>{L('Ajustes da wiki', 'Wiki settings')}</h2>
+ <button className="btn btn--ghost btn--sm wk-icon-btn" onClick={onClose}>
+ <Icon name="x" size={15} />
+ </button>
+ </header>
+
+ <section>
+ <h4>{L('O curador', 'The curator')}</h4>
+ <div className="wk-setting">
+ <span>
+ <b>{L('Guardar das conversas', 'Keep from conversations')}</b>
+ <small>{L('Depois que uma conversa assenta, ele guarda as decisões, os fatos e os resultados nas páginas. Dá pra desligar por canal ou DM, no menu da conversa.', 'Once a conversation settles, it keeps the decisions, facts and results in the pages. It can be turned off per channel or DM, from the conversation menu.')}</small>
+ </span>
+ <Toggle on={capture} onChange={(v) => updateSettings({ wikiCapture: v })} />
+ </div>
+ <div className="wk-setting">
+ <span>
+ <b>{L('Mudar uma página que já existe', 'Changing a page that exists')}</b>
+ <small>{L('Páginas novas sempre entram direto. Tudo fica no histórico, com Desfazer.', 'New pages always go in right away. It all stays in the history, with Undo.')}</small>
+ </span>
+ <div className="segmented">
+ <button className={edits === 'approve' ? 'is-active' : ''} onClick={() => updateSettings({ wikiEdits: 'approve' })}>
+ {L('Pede aprovação', 'Asks first')}
+ </button>
+ <button className={edits === 'auto' ? 'is-active' : ''} onClick={() => updateSettings({ wikiEdits: 'auto' })}>
+ {L('Automático', 'Automatic')}
+ </button>
+ </div>
+ </div>
+ <div className="wk-setting">
+ <span>
+ <b>{L('Revisar sozinha toda semana', 'Review on its own every week')}</b>
+ <small>{L('Procura o que não bate, o que ficou velho e o que está repetido. O que achar espera você em Cuidados.', 'Looks for what disagrees, what got old and what repeats. What it finds waits for you in Care.')}</small>
+ </span>
+ <Toggle on={s.wikiReview === 'weekly'} onChange={(v) => updateSettings({ wikiReview: v ? 'weekly' : 'off' })} />
+ </div>
+ </section>
+
+ <section>
+ <h4>{L('A pasta', 'The folder')}</h4>
+ <code className="wk-folder" title={dir}>
+ <Icon name="folder" size={14} />
+ {dir.replace(/^\/Users\/[^/]+/, '~')}
+ </code>
+ <small className="muted">{L('Markdown puro: abre no Obsidian, vai pro iCloud ou pro git. Pode ser o seu cofre do Obsidian.', 'Plain Markdown: it opens in Obsidian, goes to iCloud or git. It can be your Obsidian vault.')}</small>
+ <div className="wk-row">
+ {data && !data.server && (
+ <button className="btn btn--sm" onClick={() => void call('openWikiFolder')}>
+ {L('Abrir pasta', 'Open folder')}
+ </button>
+ )}
+ {pick && (
+ <button
+ className="btn btn--sm"
+ onClick={() =>
+ void pick().then((p) => {
+ if (p && confirm(L(`Usar ${p} como a pasta da wiki?\n\nAs páginas da pasta atual continuam lá; a wiki passa a mostrar o que está na nova.`, `Use ${p} as the wiki's folder?\n\nThe pages in the current folder stay there; the wiki shows what's in the new one.`))) move(p)
+ })
+ }
+ >
+ {L('Trocar pasta…', 'Change folder…')}
+ </button>
+ )}
+ {s.wikiDir && (
+ <button className="btn btn--ghost btn--sm" onClick={() => move(null)}>
+ {L('Voltar pra pasta do Tucano', "Back to Tucano's folder")}
+ </button>
+ )}
+ </div>
+ {error && <small className="field__error">{error}</small>}
+ </section>
+
+ <section>
+ <h4>{L('Trazer o que você já tem', 'Bring what you already have')}</h4>
+ <div className="wk-setting">
+ <span>
+ <b>{L('Importar um cofre do Obsidian', 'Import an Obsidian vault')}</b>
+ <small>{L('As notas entram como estão, com as pastas, os links e os anexos. O cofre original não muda.', 'The notes come in as they are, with their folders, links and attachments. The original vault stays as it was.')}</small>
+ </span>
+ <button className="btn btn--sm" onClick={onImport}>
+ {L('Importar…', 'Import…')}
+ </button>
+ </div>
+ </section>
+
+ <section>
+ <h4>{L('As regras', 'The rules')}</h4>
+ <div className="wk-setting">
+ <span>
+ <b>{L('Esquema da wiki', 'Wiki schema')}</b>
+ <small>{L('Os tipos de página e como escrever. Os agentes e o curador seguem esta página.', 'The kinds of page and how to write. The agents and the curator follow this page.')}</small>
+ </span>
+ <button className="btn btn--sm" onClick={() => (onClose(), navigate({ kind: 'wiki', edit: true }))}>
+ {L('Editar', 'Edit')}
+ </button>
+ </div>
+ </section>
+ </div>
+ </div>
+ )
+}
+
+// ---------- changes ----------
+
+// One change, as the curator wrote it: what goes where.
+function OpView({ op }: { op: WikiChange['ops'][number] }): ReactNode {
+ const md = (t?: string): ReactNode => (
+ <Markdown remarkPlugins={[remarkGfm]} components={mdLinks()}>
+ {wikiLinks(t ?? '')}
+ </Markdown>
+ )
+ return (
+ <div className={`wiki-op wiki-op--${op.op}`}>
+ <div className="wiki-op__head">
+ <span className="wiki-op__verb">{op.op === 'create' ? L('Página nova', 'New page') : op.op === 'append' ? L('Acrescenta em', 'Adds to') : L('Troca em', 'Swaps in')}</span>
+ <button className="wiki-link" onClick={() => navigate({ kind: 'wiki', title: op.page })}>
+ {op.page}
+ </button>
+ {op.section && <span className="muted">› {op.section}</span>}
+ </div>
+ {op.op === 'replace' ? (
+ <div className="wiki-diff">
+ <div className="wiki-diff__old md">{md(op.old)}</div>
+ <div className="wiki-diff__new md">{md(op.new)}</div>
+ </div>
+ ) : (
+ <div className="wiki-diff__new md">{md(op.text)}</div>
+ )}
+ </div>
+ )
+}
+
+const STATE_LABEL = (s: WikiChange['state']): string =>
+ s === 'pending' ? L('Esperando você', 'Waiting for you') : s === 'conflict' ? L('A página mudou depois', 'The page changed since') : s === 'applied' ? L('Entrou', 'Went in') : s === 'undone' ? L('Desfeita', 'Undone') : L('Recusada', 'Refused')
+
+export function ChangeCard({ change, compact, bare }: { change: WikiChange; compact?: boolean; bare?: boolean }): ReactNode {
+ const [error, setError] = useState('')
+ const who = useWho()
+ const act = (p: Promise<unknown>): void => void p.then(() => setError(''), (e: Error) => setError(e.message))
+ return (
+ <section className={`wiki-change wiki-change--${change.state}`}>
+ {!bare && (
+ <header>
+ {change.state !== 'pending' && <span className={`wiki-change__state wiki-change__state--${change.state}`}>{STATE_LABEL(change.state)}</span>}
+ {change.reason && <b className="wiki-change__why">{change.reason}</b>}
+ <small className="muted">
+ {who(change.by)} · {rel(change.at)}
+ {change.source && (
+ <>
+ {' · '}
+ <button className="text-btn" onClick={() => navigate({ kind: 'wiki', source: change.source!.file })}>
+ {L('de onde veio', 'where it came from')}
+ </button>
+ </>
+ )}
+ </small>
+ </header>
+ )}
+ {!compact && <div className="wiki-change__ops">{change.ops.map((op, k) => <OpView key={k} op={op} />)}</div>}
+ {error && <p className="field__error">{error}</p>}
+ {(change.state === 'pending' || change.state === 'conflict') && (
+ <div className="wiki-change__actions">
+ {change.state === 'conflict' && (
+ <>
+ <small className="muted">{L('A página mudou depois dessa sugestão. O curador refaz a mudança sobre a versão nova, sem perder o que mudou.', 'The page changed after this suggestion. The curator makes the change again on the newer version, keeping what changed.')}</small>
+ <button className="btn btn--primary btn--sm" onClick={() => act(call('wikiRedoChange', { id: change.id }))}>
+ {L('Refazer sobre a versão nova', 'Redo on the newer version')}
+ </button>
+ </>
+ )}
+ {change.state === 'pending' && (
+ <button className="btn btn--primary btn--sm" onClick={() => act(call('wikiApplyChange', { id: change.id }))}>
+ <Icon name="check" size={13} /> {L('Aprovar', 'Approve')}
+ </button>
+ )}
+ <button className="btn btn--ghost btn--sm" onClick={() => act(call('wikiRefuseChange', { id: change.id }))}>
+ {L('Recusar', 'Refuse')}
+ </button>
+ </div>
+ )}
+ {change.state === 'applied' && !compact && (
+ <div className="wiki-change__actions">
+ <button className="btn btn--ghost btn--sm" onClick={() => act(call('wikiUndoChange', { id: change.id }))}>
+ {L('Desfazer', 'Undo')}
+ </button>
+ </div>
+ )}
+ </section>
+ )
+}
+
+function PaneHead({ icon, title, lede, children }: { icon: IconName; title: string; lede: ReactNode; children?: ReactNode }): ReactNode {
+ return (
+ <header className="wk-pane-head">
+ <span className="wk-pane-head__icon">
+ <Icon name={icon} size={18} />
+ </span>
+ <div>
+ <h2>{title}</h2>
+ <p>{lede}</p>
+ </div>
+ {children && <div className="wk-pane-head__actions">{children}</div>}
+ </header>
+ )
+}
+
+function WikiPending(): ReactNode {
+ const rev = useStore((s) => s.wikiRev)
+ const [list, setList] = useState<WikiChange[] | null>(null)
+ const [recent, setRecent] = useState<WikiChange[]>([])
+ const [showRecent, setShowRecent] = useState(false)
+ useEffect(() => void Promise.all([call('wikiChanges', { state: 'pending' }), call('wikiChanges', { state: 'conflict' })]).then(([a, b]) => setList([...a, ...b].filter((c) => c.by !== 'review'))), [rev])
+ useEffect(() => void call('wikiChanges', {}).then((all) => setRecent(all.filter((c) => c.state !== 'pending' && c.state !== 'conflict' && c.by !== 'review').slice(0, 12))), [rev])
+ if (!list) return null
+ return (
+ <div className="wk-pane">
+ <PaneHead icon="hand" title={L('Esperando você', 'Waiting for you')} lede={L('O que o curador quer mudar em páginas que já existem. Aprove, recuse, ou mude o jeito nos ajustes.', 'What the curator wants to change in pages that already exist. Approve, refuse, or change how it works in the settings.')} />
+ {list.length === 0 ? (
+ <div className="wk-calm">
+ <Icon name="check" size={18} />
+ <span>{L('Nada esperando você.', 'Nothing waiting for you.')}</span>
+ </div>
+ ) : (
+ list.map((c) => <ChangeCard key={c.id} change={c} />)
+ )}
+ {recent.length > 0 && (
+ <>
+ <button className="text-btn wk-more" onClick={() => setShowRecent(!showRecent)}>
+ {L('Decididas há pouco', 'Recently decided')} ({recent.length}) {showRecent ? '▾' : '▸'}
+ </button>
+ {showRecent && recent.map((c) => <ChangeCard key={c.id} change={c} />)}
+ </>
+ )}
+ </div>
+ )
+}
+
+// ---------- looking after the wiki ----------
+
+const FINDING_LABEL: Record<WikiFinding['kind'], () => string> = {
+ contradiction: () => L('Não batem', "Don't agree"),
+ stale: () => L('Desatualizada', 'Out of date'),
+ duplicate: () => L('Repetida', 'Duplicate'),
+ link: () => L('Falta ligar', 'Missing link'),
+ broken: () => L('Página por escrever', 'Page to write'),
+ missing: () => L('Sem página', 'No page'),
+ orphan: () => L('Ninguém liga pra elas', 'Nothing links to them')
+}
+const FINDING_TONE: Record<WikiFinding['kind'], 'danger' | 'warn' | 'calm'> = { contradiction: 'danger', stale: 'warn', duplicate: 'warn', link: 'calm', broken: 'calm', missing: 'calm', orphan: 'calm' }
+const FINDING_ORDER: WikiFinding['kind'][] = ['contradiction', 'stale', 'duplicate', 'link', 'broken', 'missing', 'orphan']
+
+function WikiReviewPane(): ReactNode {
+ const rev = useStore((s) => s.wikiRev)
+ const [r, setR] = useState<WikiReview | null>(null)
+ useEffect(() => void call('wikiReview').then(setR), [rev])
+ if (!r) return null
+ const sorted = [...r.findings].sort((a, b) => FINDING_ORDER.indexOf(a.kind) - FINDING_ORDER.indexOf(b.kind))
+ const md = (t: string): ReactNode => (
+ <Markdown components={{ ...mdLinks(), p: (p) => <span>{p.children}</span> }}>{wikiLinks(t)}</Markdown>
+ )
+ return (
+ <div className="wk-pane">
+ <PaneHead
+ icon="shield"
+ title={L('Cuidados', 'Care')}
+ lede={
+ r.running
+ ? L('Lendo as páginas… Leva um ou dois minutos.', 'Reading the pages… It takes a minute or two.')
+ : r.at
+ ? L(`Revisada ${rel(r.at)}. A próxima lê só o que mudou desde então.`, `Reviewed ${rel(r.at)}. The next one reads only what changed since.`)
+ : L('Uma leitura da wiki inteira: o que não bate, o que ficou velho, o que está repetido, links quebrados. Nada muda sem você.', 'A read of the whole wiki: what disagrees, what got old, what repeats, broken links. Nothing changes without you.')
+ }
+ >
+ <button className={`btn btn--primary btn--sm ${r.running ? 'is-busy' : ''}`} disabled={r.running} onClick={() => (setR({ ...r, running: true }), void call('wikiRunReview'))}>
+ {r.running ? <span className="wk-spin" /> : <Icon name="spark" size={13} />} {r.running ? L('Revisando…', 'Reviewing…') : L('Revisar agora', 'Review now')}
+ </button>
+ </PaneHead>
+ {r.error && <p className="field__error">{L(`A última revisão não conseguiu ler as páginas com o modelo: ${r.error}`, `The last review couldn't read the pages with the model: ${r.error}`)}</p>}
+ {!r.at && !r.running && (
+ <div className="wk-checks">
+ {(
+ [
+ ['danger', L('Não batem', "Don't agree"), L('Duas páginas dizendo coisas diferentes sobre o mesmo valor, data ou prazo.', 'Two pages saying different things about the same amount, date or deadline.')],
+ ['warn', L('Desatualizada', 'Out of date'), L('"Aguardando resposta" numa página, "contrato assinado" em outra.', '"Waiting for an answer" on one page, "contract signed" on another.')],
+ ['warn', L('Repetida', 'Duplicate'), L('Duas páginas sobre a mesma pessoa ou o mesmo projeto. Ela junta, sem perder nada.', 'Two pages about the same person or project. It merges them, losing nothing.')],
+ ['calm', L('Solta', 'Loose'), L('Links pra páginas que não existem, nomes sem página, páginas que ninguém cita.', 'Links to missing pages, names with no page, pages nothing cites.')]
+ ] as const
+ ).map(([tone, t, d]) => (
+ <div key={t} className="wk-check" style={{ ['--tone' as string]: tone === 'danger' ? 'var(--danger)' : tone === 'warn' ? 'var(--warn)' : 'var(--text-3)' }}>
+ <i />
+ <span>
+ <b>{t}</b>
+ <small>{d}</small>
+ </span>
+ </div>
+ ))}
+ </div>
+ )}
+ {r.at && !r.running && sorted.length === 0 && (
+ <div className="wk-calm">
+ <Icon name="check" size={18} />
+ <span>{L('Tudo em ordem. Nada pra cuidar agora.', 'All in order. Nothing to look after now.')}</span>
+ </div>
+ )}
+ {sorted.map((f) => (
+ <section key={f.id} className={`wk-finding wk-finding--${FINDING_TONE[f.kind]}`}>
+ <div className="wk-finding__head">
+ <span className="wk-finding__kind">{FINDING_LABEL[f.kind]()}</span>
+ <div className="wk-finding__text md">{md(f.text)}</div>
+ </div>
+ {f.change ? (
+ <ChangeCard change={f.change} bare />
+ ) : (
+ <div className="wk-finding__actions">
+ {f.name && (f.kind === 'broken' || f.kind === 'missing') && (
+ <button className="btn btn--sm" onClick={() => navigate({ kind: 'wiki', title: f.name!, edit: true })}>
+ <Icon name="edit" size={13} /> {L('Escrever a página', 'Write the page')}
+ </button>
+ )}
+ <button className="btn btn--ghost btn--sm" onClick={() => void call('wikiDismissFinding', { id: f.id })}>
+ {L('Deixar assim', 'Leave it')}
+ </button>
+ </div>
+ )}
+ </section>
+ ))}
+ </div>
+ )
+}
+
+// ---------- sources ----------
+
+const ACCEPT = '.pdf,.docx,.xlsx,.csv,.txt,.md,.markdown,.json'
+
+// Files as base64, one after the other; what fails says why.
+export async function addWikiFiles(files: File[]): Promise<string[]> {
+ const errors: string[] = []
+ for (const f of files) {
+ try {
+ const data = await new Promise<string>((res, rej) => {
+ const r = new FileReader()
+ r.onload = () => res(String(r.result).split(',')[1] ?? '')
+ r.onerror = () => rej(r.error ?? new Error('read'))
+ r.readAsDataURL(f)
+ })
+ await call('wikiAddFile', { name: f.name, data })
+ } catch (e) {
+ errors.push(`${f.name}: ${e instanceof Error ? e.message.replace(/^Error invoking remote method '[^']+': (Error: )?/, '') : String(e)}`)
+ }
+ }
+ return errors
+}
+
+// What a source is, as a small badge: the file's type, or an icon.
+function SourceBadge({ s }: { s: Pick<WikiSource, 'kind' | 'title' | 'origin'> }): ReactNode {
+ if (s.kind === 'file') {
+ const ext = ((s.origin.original ?? s.title).split('.').pop() ?? '').toLowerCase()
+ const [label, color] = ext === 'pdf' ? ['PDF', 'rose'] : ext === 'docx' ? ['DOC', 'indigo'] : ext === 'xlsx' || ext === 'csv' ? ['XLS', 'green'] : ['TXT', 'graphite']
+ return (
+ <span className="wk-badge-file" style={{ ['--k' as string]: `var(--c-${color})` }}>
+ {label}
+ </span>
+ )
+ }
+ const icon: IconName = s.kind === 'link' ? 'globe' : s.kind === 'note' ? 'edit' : 'hash'
+ return (
+ <span className="wk-badge-file wk-badge-file--icon">
+ <Icon name={icon} size={14} />
+ </span>
+ )
+}
+const KIND_LABEL = (k: WikiSource['kind']): string => ({ conversation: L('conversa', 'conversation'), message: L('mensagem guardada', 'kept message'), note: L('anotação', 'note'), file: L('arquivo', 'file'), link: 'link' })[k]
+
+function SourceStatus({ s }: { s: WikiSource }): ReactNode {
+ if (s.status === 'reading')
+ return (
+ <span className="wk-status wk-status--reading">
+ <span className="wk-spin" /> {L('o curador está lendo', 'the curator is reading')}
+ </span>
+ )
+ if (s.status === 'failed')
+ return (
+ <span className="wk-status wk-status--failed" title={s.error}>
+ {L('não deu pra ler', "couldn't read it")}
+ </span>
+ )
+ if (s.status === 'done') return <span className="wk-status wk-status--done">{s.changes ? (s.changes === 1 ? L('virou 1 mudança', 'became 1 change') : L(`virou ${s.changes} mudanças`, `became ${s.changes} changes`)) : L('nada novo', 'nothing new')}</span>
+ return null
+}
+
+function AddSources({ errors: dropped }: { errors: string[] }): ReactNode {
+ const [link, setLink] = useState('')
+ const [note, setNote] = useState('')
+ const [busy, setBusy] = useState('')
+ const [errors, setErrors] = useState<string[]>(dropped)
+ useEffect(() => setErrors(dropped), [dropped])
+ const files = (list: FileList | null): void => {
+ if (!list?.length) return
+ setBusy(L('Lendo os arquivos…', 'Reading the files…'))
+ void addWikiFiles([...list]).then((errs) => (setErrors(errs), setBusy('')))
+ }
+ const addLink = (): void => {
+ if (!link.trim()) return
+ setBusy(L('Baixando a página…', 'Fetching the page…'))
+ void call('wikiAddLink', { url: link }).then(
+ () => (setLink(''), setBusy(''), setErrors([])),
+ (e: Error) => (setBusy(''), setErrors([e.message]))
+ )
+ }
+ const addNote = (): void => {
+ if (!note.trim()) return
+ void call('wikiAddNote', { text: note }).then(() => setNote(''))
+ }
+ return (
+ <div className="wk-add">
+ <label className="wk-add__tile wk-add__tile--file">
+ <span className="wk-add__icons">
+ <span className="wk-badge-file" style={{ ['--k' as string]: 'var(--c-rose)' }}>PDF</span>
+ <span className="wk-badge-file" style={{ ['--k' as string]: 'var(--c-indigo)' }}>DOC</span>
+ <span className="wk-badge-file" style={{ ['--k' as string]: 'var(--c-green)' }}>XLS</span>
+ </span>
+ <b>{L('Um arquivo', 'A file')}</b>
+ <small>{L('Escolha, ou arraste pra qualquer lugar da wiki', 'Choose one, or drag it anywhere in the wiki')}</small>
+ <input type="file" multiple accept={ACCEPT} hidden onChange={(e) => (files(e.target.files), (e.target.value = ''))} />
+ </label>
+ <div className="wk-add__tile">
+ <span className="wk-add__icons">
+ <span className="wk-badge-file wk-badge-file--icon">
+ <Icon name="globe" size={14} />
+ </span>
+ </span>
+ <b>{L('Um link', 'A link')}</b>
+ <div className="wk-add__line">
+ <input placeholder="https://…" value={link} onChange={(e) => setLink(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && addLink()} />
+ <button className="btn btn--sm" disabled={!link.trim()} onClick={addLink}>
+ {L('Trazer', 'Bring')}
+ </button>
+ </div>
+ </div>
+ <div className="wk-add__tile">
+ <span className="wk-add__icons">
+ <span className="wk-badge-file wk-badge-file--icon">
+ <Icon name="edit" size={14} />
+ </span>
+ </span>
+ <b>{L('Uma anotação', 'A note')}</b>
+ <div className="wk-add__line">
+ <input placeholder={L('A Helena prefere WhatsApp…', 'Helen prefers texting…')} value={note} onChange={(e) => setNote(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && addNote()} />
+ <button className="btn btn--sm" disabled={!note.trim()} onClick={addNote}>
+ {L('Guardar', 'Keep')}
+ </button>
+ </div>
+ </div>
+ {(busy || errors.length > 0) && (
+ <div className="wk-add__msg">
+ {busy && <small className="muted">{busy}</small>}
+ {errors.map((e) => (
+ <small key={e} className="field__error">
+ {e}
+ </small>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
+
+function WikiSources({ errors }: { errors: string[] }): ReactNode {
+ const rev = useStore((s) => s.wikiRev)
+ const [list, setList] = useState<WikiSource[] | null>(null)
+ useEffect(() => void call('wikiSources').then(setList), [rev])
+ return (
+ <div className="wk-pane">
+ <PaneHead icon="book" title={L('Fontes', 'Sources')} lede={L('O material de onde a wiki sai. O curador lê cada fonte e escreve nas páginas, citando de onde veio.', 'What the wiki is made from. The curator reads each source and writes in the pages, citing where it came from.')} />
+ <AddSources errors={errors} />
+ {list && list.length > 0 && (
+ <div className="wk-sources">
+ {list.map((s) => (
+ <button key={s.id} className="wk-source" onClick={() => navigate({ kind: 'wiki', source: s.file })}>
+ <SourceBadge s={s} />
+ <span className="wk-source__main">
+ <b>{s.title}</b>
+ <small>
+ {KIND_LABEL(s.kind)} · {rel(s.addedAt)}
+ </small>
+ </span>
+ <SourceStatus s={s} />
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
+
+// On a server the original comes to the browser, as a download.
+function download(file: { name: string; data: string } | null): void {
+ if (!file) return
+ const a = document.createElement('a')
+ a.href = URL.createObjectURL(new Blob([Uint8Array.from(atob(file.data), (c) => c.charCodeAt(0))]))
+ a.download = file.name
+ a.click()
+ setTimeout(() => URL.revokeObjectURL(a.href), 10_000)
+}
+
+function WikiSourceView({ id }: { id: string }): ReactNode {
+ const rev = useStore((s) => s.wikiRev)
+ const [src, setSrc] = useState<(WikiSource & { text: string }) | null | undefined>(undefined)
+ useEffect(() => void call('wikiSource', { id }).then(setSrc), [id, rev])
+ if (src === undefined) return null
+ if (!src)
+ return (
+ <div className="wk-read">
+ <p className="muted">{L('Essa fonte não existe mais.', 'This source no longer exists.')}</p>
+ </div>
+ )
+ return (
+ <div className="wk-read">
+ <button className="text-btn wk-back" onClick={() => navigate({ kind: 'wiki', tab: 'sources' })}>
+ ← {L('Fontes', 'Sources')}
+ </button>
+ <div className="wk-read__kicker">
+ <SourceBadge s={src} />
+ <span>
+ {KIND_LABEL(src.kind)} · {when(src.addedAt)}
+ </span>
+ <SourceStatus s={src} />
+ </div>
+ <h1 className="wk-read__title">{src.title}</h1>
+ <div className="wk-row">
+ {src.origin.conversationId && (
+ <button className="btn btn--sm" onClick={() => navigate({ kind: 'conversation', id: src.origin.conversationId! })}>
+ {L('Abrir a conversa', 'Open the conversation')}
+ </button>
+ )}
+ {src.origin.original && (
+ <button className="btn btn--sm" onClick={() => void call('wikiOpenOriginal', { id: src.id }).then(download)}>
+ {L('Abrir o arquivo original', 'Open the original file')}
+ </button>
+ )}
+ {src.origin.url && (
+ <button className="btn btn--sm" onClick={() => void call('openExternal', { url: src.origin.url! })}>
+ {L('Abrir o link', 'Open the link')}
+ </button>
+ )}
+ {src.status === 'failed' && (
+ <button className="btn btn--sm" onClick={() => void call('wikiIngestAgain', { id: src.id })}>
+ {L('Tentar de novo', 'Try again')}
+ </button>
+ )}
+ </div>
+ {src.error && <p className="field__error">{src.error}</p>}
+ <article className="wk-doc md wk-doc--source">
+ <Markdown remarkPlugins={[remarkGfm]}>{src.text.trimStart().replace(/^# .*\n+/, '')}</Markdown>
+ </article>
+ </div>
+ )
+}
+
+// ---------- in the conversation ----------
+
+// Under a reply: what the curator kept from this exchange, with Undo (or Approve, if it waits).
+export function WikiChip({ id }: { id: string }): ReactNode {
+ const rev = useStore((s) => s.wikiRev)
+ const [c, setC] = useState<WikiChange | null>(null)
+ useEffect(() => void call('wikiChange', { id }).then(setC), [id, rev])
+ if (!c || c.state === 'refused') return null
+ const pages = [...new Set(c.ops.map((o) => o.page))]
+ const label = c.state === 'applied' ? L('Guardou na wiki', 'Kept in the wiki') : c.state === 'undone' ? L('Desfeito na wiki', 'Undone in the wiki') : c.state === 'conflict' ? L('Mudança na wiki com conflito', 'Wiki change with a conflict') : L('Quer guardar na wiki', 'Wants to keep in the wiki')
+ return (
+ <div className={`memory-chip wiki-chip wiki-chip--${c.state}`}>
+ <Icon name="layers" size={13} />
+ <span className="memory-chip__label">{label}:</span>
+ <span className="memory-chip__text">
+ {pages.map((t) => (
+ <button key={t} className="wiki-link" onClick={() => navigate({ kind: 'wiki', title: t })}>
+ {t}
+ </button>
+ ))}
+ </span>
+ {c.state === 'applied' && (
+ <button className="link" onClick={() => void call('wikiUndoChange', { id })}>
+ {L('Desfazer', 'Undo')}
+ </button>
+ )}
+ {c.state === 'pending' && (
+ <>
+ <button className="btn btn--xs btn--primary" onClick={() => void call('wikiApplyChange', { id })}>
+ {L('Guardar', 'Keep')}
+ </button>
+ <button className="btn btn--xs btn--ghost" onClick={() => navigate({ kind: 'wiki', tab: 'pending' })}>
+ {L('Ver', 'See')}
+ </button>
+ </>
+ )}
+ </div>
+ )
+}
+
+// "Keep in the wiki", on a message: the curator reads it now and keeps it.
+export function KeepInWiki({ messageId }: { messageId: string }): ReactNode {
+ const [state, setState] = useState<'idle' | 'busy' | 'done' | 'none'>('idle')
+ const [error, setError] = useState('')
+ if (state === 'done') return null // the chip above says what was kept
+ return (
+ <span className="wiki-keep">
+ <button
+ className="link"
+ disabled={state === 'busy'}
+ onClick={() => {
+ setState('busy')
+ void call('wikiKeepMessage', { messageId }).then(
+ (n) => setState(n ? 'done' : 'none'),
+ (e: Error) => (setState('idle'), setError(e.message))
+ )
+ }}
+ >
+ {state === 'busy' ? L('Guardando…', 'Keeping…') : state === 'none' ? L('Nada pra guardar', 'Nothing to keep') : L('Guardar na wiki', 'Keep in the wiki')}
+ </button>
+ {error && <small className="field__error"> {error}</small>}
+ </span>
+ )
+}
+
+// ---------- a page ----------
+
+// The sources a page cites, once each, in the order they appear.
+function sourcesIn(body: string): { file: string; label: string }[] {
+ const out = new Map<string, string>()
+ for (const m of body.matchAll(/\[\[(fontes\/[^\]|\n]+)(?:\|([^\]\n]+))?\]\]/g)) {
+ const file = m[1]!.trim()
+ const name = file.replace(/^fontes\/\d{4}-\d\d-\d\d \d{4} /, '')
+ if (!out.has(file)) out.set(file, m[2] && !/^(fonte|source)$/i.test(m[2].trim()) ? m[2].trim() : name)
+ }
+ return [...out].map(([file, label]) => ({ file, label }))
+}
+
+function WikiPageView({ title, data }: { title: string; data: WikiData | null }): ReactNode {
+ const rev = useStore((s) => s.wikiRev)
+ const who = useWho()
+ const [page, setPage] = useState<WikiPage | null | undefined>(undefined)
+ const [history, setHistory] = useState<WikiVersion[] | null>(null)
+ const [sources, setSources] = useState<WikiSource[]>([])
+ const [error, setError] = useState('')
+ useEffect(() => void call('wikiPage', { title }).then(setPage), [title, rev])
+ useEffect(() => void call('wikiSources').then(setSources), [rev])
+ useEffect(() => {
+ if (history) void call('wikiHistory', { title }).then(setHistory)
+ }, [rev])
+ if (page === undefined) return null
+ if (page === null)
+ return (
+ <div className="wk-read">
+ <h1 className="wk-read__title">{title}</h1>
+ <p className="muted">{L('Essa página não existe (ainda).', "This page doesn't exist (yet).")}</p>
+ <button className="btn btn--primary" onClick={() => navigate({ kind: 'wiki', title, edit: true })}>
+ {L('Escrever essa página', 'Write this page')}
+ </button>
+ </div>
+ )
+ const missing = new Set(page.missing.map((t) => t.toLowerCase()))
+ const cited = sourcesIn(page.body)
+ const remove = (): void => {
+ if (!confirm(L(`Apagar "${page.title}"? Dá pra restaurar pelo histórico.`, `Delete "${page.title}"? It can be restored from the history.`))) return
+ void call('wikiRemove', { title: page.title }).then(() => navigate({ kind: 'wiki' }))
+ }
+ const kindOf = (t: string): string => data?.pages.find((p) => p.title === t)?.kind ?? ''
+ return (
+ <article className="wk-page" style={{ ['--k' as string]: kindColor(page.kind) }}>
+ <div className="wk-page__kicker">
+ <KindPill kind={page.kind} />
+ <span className="wk-page__meta">
+ <Who by={page.updatedBy} size={18} />
+ {L(`${who(page.updatedBy)} · ${rel(page.updatedAt)}`, `${who(page.updatedBy)} · ${rel(page.updatedAt)}`)}
+ </span>
+ </div>
+ <h1 className="wk-page__title">{page.title}</h1>
+ <div className="wk-doc md">
+ <Markdown remarkPlugins={[remarkGfm]} components={mdLinks(missing)}>
+ {wikiLinks(page.body)}
+ </Markdown>
+ </div>
+
+ {page.backlinks.length > 0 && (
+ <section className="wk-page__more">
+ <h5>{L('Quem cita esta página', 'Pages that cite this one')}</h5>
+ <div className="wk-page__chips">
+ {page.backlinks.map((t) => (
+ <button key={t} className="wk-pill" style={{ ['--k' as string]: kindColor(kindOf(t)) }} onClick={() => navigate({ kind: 'wiki', title: t })}>
+ <i />
+ {t}
+ </button>
+ ))}
+ </div>
+ </section>
+ )}
+ {cited.length > 0 && (
+ <section className="wk-page__more">
+ <h5>{L('De onde veio', 'Where it came from')}</h5>
+ {cited.map((c) => {
+ const s = sources.find((x) => x.file === c.file)
+ return (
+ <button key={c.file} className="wk-page__source" onClick={() => navigate({ kind: 'wiki', source: c.file })}>
+ {s ? <SourceBadge s={s} /> : <Icon name="book" size={13} />}
+ <span>
+ <b>{s?.title ?? c.label}</b>
+ {s && <small>{rel(s.addedAt)}</small>}
+ </span>
+ </button>
+ )
+ })}
+ </section>
+ )}
+ {history && (
+ <section className="wk-page__more">
+ <h5>{L('Histórico', 'History')}</h5>
+ {error && <p className="field__error">{error}</p>}
+ <ol className="wk-history">
+ {history.map((v) => (
+ <li key={v.id}>
+ <Who by={v.by} size={18} />
+ <span>
+ <b>{who(v.by)}</b> {v.action === 'create' ? L('escreveu', 'wrote') : v.action === 'delete' ? L('apagou', 'deleted') : L('mudou', 'changed')}
+ <small>
+ {when(v.at)}
+ {v.reason ? ` · ${v.reason}` : ''}
+ </small>
+ </span>
+ {v.after !== null && v.after !== page.body && (
+ <button className="text-btn" onClick={() => void call('wikiRestore', { id: v.id }).then(() => setError(''), (e: Error) => setError(e.message))}>
+ {L('voltar a esta', 'restore')}
+ </button>
+ )}
+ </li>
+ ))}
+ </ol>
+ </section>
+ )}
+
+ <footer className="wk-page__tools">
+ <button className="btn btn--primary btn--sm" title={L('Editar (E)', 'Edit (E)')} onClick={() => navigate({ kind: 'wiki', title: page.title, edit: true })}>
+ <Icon name="edit" size={13} /> {L('Editar', 'Edit')}
+ </button>
+ <button className="btn btn--ghost btn--sm" onClick={() => (history ? setHistory(null) : void call('wikiHistory', { title: page.title }).then(setHistory))}>
+ <Icon name="clock" size={13} /> {history ? L('Esconder histórico', 'Hide history') : L('Histórico', 'History')}
+ </button>
+ <span className="grow" />
+ <button className="btn btn--ghost btn--sm wk-icon-btn" title={L('Apagar', 'Delete')} onClick={remove}>
+ <Icon name="trash" size={14} />
+ </button>
+ </footer>
+ </article>
+ )
+}
+
+// ---------- the editor (a page, or the schema when there's no title at all) ----------
+
+function WikiEditor({ title }: { title?: string }): ReactNode {
+ const schemaMode = title === undefined
+ const [page, setPage] = useState<WikiPage | null>(null)
+ const [loaded, setLoaded] = useState(false)
+ const [name, setName] = useState(title ?? '')
+ const [kind, setKind] = useState('')
+ const [body, setBody] = useState('')
+ const [kinds, setKinds] = useState<string[]>(DEFAULT_KINDS())
+ const [error, setError] = useState('')
+ useEffect(() => {
+ if (schemaMode) {
+ void call('wikiSchema').then((t) => (setBody(t), setLoaded(true)))
+ return
+ }
+ void call('wiki').then((w) => setKinds([...new Set([...DEFAULT_KINDS(), ...w.kinds])]))
+ if (!title) return setLoaded(true)
+ void call('wikiPage', { title }).then((p) => {
+ setPage(p)
+ if (p) (setName(p.title), setKind(p.kind), setBody(p.body.replace(/^\s*\n/, '')))
+ else setBody('')
+ setLoaded(true)
+ })
+ }, [])
+ if (!loaded) return null
+ const save = (): void => {
+ setError('')
+ if (schemaMode) return void call('wikiSaveSchema', { text: body }).then(() => navigate({ kind: 'wiki' }))
+ void call('wikiSave', { title: name, body, kind: kind || DEFAULT_KINDS()[2]!, ...(page ? { expectedHash: page.hash, rename: page.title } : {}) }).then(
+ (p) => navigate({ kind: 'wiki', title: p.title }),
+ (e: Error) => setError(e.message)
+ )
+ }
+ const back = (): void => navigate(schemaMode || !page ? { kind: 'wiki' } : { kind: 'wiki', title: page.title })
+ return (
+ <Sheet
+ fill
+ title={schemaMode ? L('Esquema da wiki', 'Wiki schema') : page ? L('Editando', 'Editing') : L('Nova página', 'New page')}
+ lede={schemaMode ? L('As regras da wiki: os tipos de página e como escrever. Os agentes e o curador seguem esta página.', 'The wiki rules: the kinds of page and how to write. The agents and the curator follow this page.') : L('Markdown. Ligue páginas com [[Título]]; uma que ainda não existe vira um convite pra escrever.', "Markdown. Link pages with [[Title]]; one that doesn't exist yet becomes an invitation to write it.")}
+ back={{ label: L('Voltar', 'Back'), onClick: back }}
+ actions={
+ <>
+ <button className="btn btn--ghost btn--sm" onClick={back}>
+ {L('Cancelar', 'Cancel')}
+ </button>
+ <button className="btn btn--primary btn--sm" disabled={!schemaMode && !name.trim()} onClick={save}>
+ {L('Salvar', 'Save')}
+ </button>
+ </>
+ }
+ >
+ <div className="wiki-editor">
+ {!schemaMode && (
+ <div className="wiki-editor__head" style={{ ['--k' as string]: kindColor(kind) }}>
+ <input className="wiki-editor__title" placeholder={L('Título, ex.: Marcos Lima', 'Title, e.g. Mark Lee')} value={name} onChange={(e) => setName(e.target.value)} autoFocus={!title} />
+ <div className="wiki-editor__kinds">
+ {kinds.map((k) => (
+ <button key={k} type="button" className={`wk-pill ${fold(k) === fold(kind) ? 'is-on' : ''}`} style={{ ['--k' as string]: kindColor(k) }} onClick={() => setKind(k)}>
+ <i />
+ {k}
+ </button>
+ ))}
+ <input className="wiki-editor__kind" placeholder={L('outro tipo…', 'another kind…')} value={kinds.some((k) => fold(k) === fold(kind)) ? '' : kind} onChange={(e) => setKind(e.target.value)} />
+ </div>
+ </div>
+ )}
+ {error && <p className="field__error">{error}</p>}
+ <div className="wiki-editor__panes">
+ <textarea className="wiki-editor__text" value={body} onChange={(e) => setBody(e.target.value)} spellCheck placeholder={L('Comece com uma frase que diga o que é. Depois, seções com ##.', 'Start with one sentence that says what it is. Then sections with ##.')} />
+ <div className="wiki-editor__preview wk-doc md">
+ {body.trim() ? (
+ <Markdown remarkPlugins={[remarkGfm]} components={mdLinks()}>
+ {wikiLinks(body)}
+ </Markdown>
+ ) : (
+ <p className="muted">{L('A prévia aparece aqui.', 'The preview shows up here.')}</p>
+ )}
+ </div>
+ </div>
+ </div>
+ </Sheet>
+ )
+}
diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.ts
index 41ebc4a..4543076 100644
--- a/src/renderer/src/store.ts
+++ b/src/renderer/src/store.ts
@@ -52,6 +52,7 @@ export type View =
| { kind: 'usage' }
| { kind: 'connectors' }
| { kind: 'memory' }
+ | { kind: 'wiki'; title?: string; edit?: boolean; tab?: 'pages' | 'pending' | 'sources' | 'review'; source?: string } // the wiki's home (a tab), a page (being edited), or a source
| { kind: 'routines' }
| { kind: 'skills' }
| { kind: 'report' }
@@ -76,6 +77,7 @@ export interface State {
browsers: BrowserView[]
routines: Routine[]
skills: Skill[]
+ wikiRev: number // goes up when a wiki page changes: the wiki screens read again
platform: Os
packaged: boolean
panel: Panel | null // the side panel next to a conversation
@@ -98,6 +100,7 @@ const initials = (name: string): string =>
let state: State = {
ready: false,
+ wikiRev: 0,
navOpen: false,
view: null,
me: { name: 'Eu', initials: 'EU' },
@@ -257,6 +260,8 @@ function apply(e: CoreEvent): void {
return { ...s, skills: upsert(s.skills, e.skill).sort((a, b) => a.name.localeCompare(b.name)) }
case 'skill_removed':
return { ...s, skills: s.skills.filter((k) => k.id !== e.id) }
+ case 'wiki':
+ return { ...s, wikiRev: s.wikiRev + 1 }
}
})
}
diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.css
index c5d6719..b367bff 100644
--- a/src/renderer/src/styles.css
+++ b/src/renderer/src/styles.css
@@ -6652,3 +6652,288 @@ kbd {
.swatch--custom.is-active {
overflow: visible;
}
+
+
+/* The wiki: what you and the team know, as linked pages */
+
+/* the place: the map takes it all, a panel comes over it */
+.wk-stage { flex: 1; min-height: 0; position: relative; overflow: hidden; border-top: 1px solid var(--border); }
+.wk-watch { margin: -4px 32px 12px; }
+.wk-watch__chip span:not(.wk-spin) { max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.wk-watch__chip--pending > i { background: var(--accent); animation-name: wk-watch-accent; }
+.wk-watch__chip--care > i { background: var(--warn); animation-name: wk-watch-warn; }
+@keyframes wk-watch-accent { 50% { box-shadow: 0 0 0 4px var(--accent-soft); } }
+@keyframes wk-watch-warn { 50% { box-shadow: 0 0 0 4px var(--warn-soft); } }
+.wk-watch .wk-spin { width: 9px; height: 9px; color: var(--text-3); }
+.wk-foot { gap: 20px; }
+.wk-foot .text-btn { display: inline-flex; align-items: center; gap: 6px; }
+.wk-foot .grow { flex: 1; }
+
+.wk-search-btn { display: inline-flex; align-items: center; gap: 8px; height: 30px; padding: 0 7px 0 10px; border-radius: 8px; border: 1px solid var(--border); background: var(--panel); color: var(--text-3); font: inherit; cursor: pointer; transition: border-color 0.15s, color 0.15s; }
+.wk-search-btn:hover { border-color: var(--border-strong); color: var(--text); }
+.wk-search-btn kbd, .wk-palette kbd { font: 600 10.5px var(--font); color: var(--text-3); border: 1px solid var(--border); border-radius: 5px; padding: 1px 5px; background: var(--bg); }
+.wk-icon-btn { width: 30px; padding: 0; justify-content: center; }
+.wk-kinds { display: flex; gap: 2px; padding-right: 12px; margin-right: 4px; border-right: 1px solid var(--border); }
+.wk-kinds button { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 9px; border: 0; border-radius: 7px; background: none; font: 500 12.5px var(--font); color: var(--text-2); cursor: pointer; transition: opacity 0.15s, background 0.15s; }
+.wk-kinds button:hover { background: var(--hover); }
+.wk-kinds button i { width: 8px; height: 8px; border-radius: 50%; background: var(--k); }
+.wk-kinds button.is-on { background: color-mix(in srgb, var(--k) 14%, transparent); color: var(--text); font-weight: 600; }
+.wk-kinds button.is-dim { opacity: 0.45; }
+
+.wk-panel { position: absolute; z-index: 3; top: 12px; right: 12px; bottom: 12px; width: 560px; max-width: calc(100% - 24px); overflow-y: auto; background: var(--panel); border-radius: 18px; box-shadow: 0 0 0 1px var(--border), 0 24px 60px -20px rgba(40, 25, 10, 0.28), 0 8px 20px -12px rgba(40, 25, 10, 0.18); animation: wk-slide 0.34s var(--ease) both; }
+@keyframes wk-slide { from { opacity: 0; transform: translateX(24px); } }
+.wk-panel__close { position: sticky; top: 14px; float: right; margin: 14px 14px -44px 0; z-index: 2; width: 30px; height: 30px; display: grid; place-items: center; border-radius: 9px; border: 0; background: color-mix(in srgb, var(--panel) 80%, transparent); backdrop-filter: blur(6px); color: var(--text-3); cursor: pointer; }
+.wk-panel__close:hover { background: var(--hover); color: var(--text); }
+
+.wk-drop { position: absolute; inset: 12px; z-index: 5; display: grid; place-items: center; border-radius: 18px; border: 2px dashed var(--accent); background: color-mix(in srgb, var(--panel) 82%, transparent); backdrop-filter: blur(4px); pointer-events: none; animation: wk-fade 0.15s both; }
+.wk-drop div { display: grid; justify-items: center; gap: 8px; color: var(--accent); }
+.wk-drop b { font-size: 18px; color: var(--text); }
+.wk-drop small { color: var(--text-2); }
+@keyframes wk-fade { from { opacity: 0; transform: translateY(4px); } }
+
+/* pills, people, little badges */
+.wk-pill { display: inline-flex; align-items: center; gap: 6px; height: 24px; padding: 0 10px 0 8px; border-radius: 12px; border: 0; background: color-mix(in srgb, var(--k) 12%, transparent); color: color-mix(in srgb, var(--k) 78%, var(--text)); font: 600 12px var(--font); white-space: nowrap; }
+.wk-pill i { width: 7px; height: 7px; border-radius: 50%; background: var(--k); }
+.wk-pill--sm { height: 21px; font-size: 11.5px; padding: 0 8px 0 7px; }
+.wk-pill--ghost { --k: var(--text-3); background: transparent; border: 1px dashed var(--border-strong); color: var(--text-3); }
+button.wk-pill { cursor: pointer; transition: background 0.15s, box-shadow 0.15s; }
+button.wk-pill:hover { background: color-mix(in srgb, var(--k) 20%, transparent); }
+button.wk-pill.is-on { box-shadow: 0 0 0 1.5px var(--k); background: color-mix(in srgb, var(--k) 20%, transparent); }
+.wk-who { display: inline-grid; place-items: center; flex: none; border-radius: 50%; background: var(--primary); color: var(--primary-text); font-weight: 700; }
+.wk-who--curator { background: linear-gradient(135deg, var(--accent), #f2a65a); color: #fff; }
+.wk-badge-file { flex: none; display: inline-grid; place-items: center; width: 32px; height: 32px; border-radius: 8px; background: color-mix(in srgb, var(--k) 13%, transparent); color: color-mix(in srgb, var(--k) 85%, var(--text)); font: 800 9.5px var(--font); letter-spacing: 0.03em; }
+.wk-badge-file--icon { --k: var(--text-3); color: var(--text-2); background: var(--hover); }
+.wk-spin { width: 11px; height: 11px; border-radius: 50%; border: 2px solid currentColor; border-right-color: transparent; display: inline-block; animation: wk-spin 0.8s linear infinite; vertical-align: -1px; }
+@keyframes wk-spin { to { transform: rotate(360deg); } }
+.wk-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
+
+/* links in the text, and what they point to */
+.wiki-link { display: inline; padding: 0 2px; margin: 0; border-radius: 4px; background: transparent; color: var(--accent); font: inherit; font-weight: 600; cursor: pointer; border: 0; text-decoration: underline; text-decoration-color: color-mix(in srgb, var(--accent) 35%, transparent); text-underline-offset: 3px; text-decoration-thickness: 1.5px; transition: background 0.12s, text-decoration-color 0.12s; }
+.wiki-link:hover { background: var(--accent-soft); text-decoration-color: var(--accent); }
+.wiki-link.is-missing { color: var(--text-2); text-decoration-style: dashed; text-decoration-color: var(--text-3); }
+.wiki-link--source { display: inline-flex; align-items: center; gap: 3px; padding: 0 5px; text-decoration: none; color: var(--text-3); font-weight: 500; font-size: 0.78em; vertical-align: 1px; border-radius: 6px; background: var(--hover); }
+.wiki-link--source:hover { color: var(--text); background: var(--active); }
+.wk-peek { position: fixed; z-index: 60; width: 320px; padding: 14px 16px; border-radius: 12px; background: var(--panel); box-shadow: var(--shadow-lg), 0 0 0 1px var(--border); display: grid; gap: 6px; justify-items: start; animation: wk-fade 0.16s var(--ease) both; pointer-events: none; }
+.wk-peek b { font-size: 15px; }
+.wk-peek p { margin: 0; font-size: 13px; line-height: 1.5; color: var(--text-2); display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; }
+.wk-peek small { color: var(--text-3); font-size: 11.5px; }
+
+/* the map */
+.wk-canvas { position: absolute; inset: 0; cursor: grab; touch-action: none; user-select: none; background-image: radial-gradient(circle, color-mix(in srgb, var(--text-3) 32%, transparent) 1px, transparent 1.3px); }
+.wk-canvas.is-panning { cursor: grabbing; }
+.wk-canvas > svg { display: block; position: absolute; inset: 0; }
+.wk-canvas__edges line { stroke: color-mix(in srgb, var(--text-3) 45%, transparent); stroke-width: 1.3; transition: opacity 0.25s, stroke 0.25s; }
+.wk-canvas__edges line.is-hot { stroke: var(--accent); stroke-width: 2; }
+.wk-canvas__edges line.is-dim { opacity: 0.18; }
+.wk-node { cursor: pointer; transition: opacity 0.25s; animation: wk-pop 0.6s var(--ease) both; animation-delay: calc(var(--i) * 22ms); }
+@keyframes wk-pop { from { opacity: 0; } }
+.wk-node__hit { fill: transparent; }
+.wk-node__dot { fill: var(--k); stroke: var(--bg); stroke-width: 2.5; }
+.wk-node__halo { fill: var(--k); opacity: 0; transition: opacity 0.2s; }
+.wk-node:hover .wk-node__halo, .wk-node.is-lit .wk-node__halo { opacity: 0.16; }
+.wk-node.is-sel .wk-node__halo { opacity: 0.22; animation: wk-breathe 2.6s ease-in-out infinite; }
+@keyframes wk-breathe { 50% { opacity: 0.08; } }
+.wk-node__ping { fill: none; stroke: var(--accent); stroke-width: 1.5; animation: wk-ping 2s ease-out infinite; transform-box: fill-box; transform-origin: center; }
+@keyframes wk-ping { from { opacity: 0.9; transform: scale(1); } to { opacity: 0; transform: scale(1.9); } }
+.wk-node text { font: 500 12px var(--font); fill: var(--text-2); paint-order: stroke; stroke: var(--bg); stroke-width: 5px; stroke-linejoin: round; pointer-events: none; transition: fill 0.2s; }
+.wk-node.is-lit text, .wk-node.is-sel text { fill: var(--text); font-weight: 650; }
+.wk-node.is-dim { opacity: 0.2; }
+.wk-node.is-missing .wk-node__dot { fill: var(--bg); stroke: var(--text-3); stroke-dasharray: 2.5 2.5; stroke-width: 1.4; }
+.wk-node.is-missing text { fill: var(--text-3); font-style: italic; }
+.wk-zoom { position: absolute; bottom: 16px; z-index: 2; display: flex; border-radius: 10px; background: var(--panel); box-shadow: 0 0 0 1px var(--border), var(--shadow); overflow: hidden; transition: right 0.34s var(--ease); }
+.wk-zoom button { width: 32px; height: 30px; border: 0; background: none; color: var(--text-2); font: 500 16px var(--font); cursor: pointer; display: grid; place-items: center; }
+.wk-zoom button + button { border-left: 1px solid var(--border); }
+.wk-zoom button:hover { background: var(--hover); color: var(--text); }
+
+.wk-empty { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; gap: 14px; padding: 0 28px; text-align: center; }
+.wk-empty > * { max-width: 540px; }
+.wk-empty__art { width: 360px; max-width: 100%; overflow: visible; margin-bottom: 6px; }
+.wk-empty__art line { stroke: var(--border-strong); stroke-width: 1.4; stroke-dasharray: 3 4; }
+.wk-empty__art circle { animation: wk-float 5s ease-in-out infinite; animation-delay: calc(var(--i) * -0.8s); }
+@keyframes wk-float { 50% { transform: translateY(-5px); } }
+.wk-empty h2 { margin: 0; font-size: 26px; letter-spacing: -0.02em; }
+.wk-empty p { margin: 0; color: var(--text-2); font-size: 15px; line-height: 1.6; }
+.wk-empty__actions { display: flex; gap: 10px; margin: 6px 0 4px; }
+
+/* search */
+.wk-palette-back { align-items: flex-start; padding-top: 12vh; }
+.wk-palette { width: min(640px, 92vw); border-radius: 16px; background: var(--panel); box-shadow: var(--shadow-lg), 0 0 0 1px var(--border); overflow: hidden; animation: wk-fade 0.16s var(--ease) both; }
+.wk-palette__input { display: flex; align-items: center; gap: 12px; padding: 16px 18px; border-bottom: 1px solid var(--border); color: var(--text-3); }
+.wk-palette__input input, .wk-palette__input input:focus { flex: 1; border: 0; outline: 0; box-shadow: none; padding: 0; background: transparent; font: inherit; font-size: 17px; color: var(--text); }
+.wk-palette__list { max-height: 56vh; overflow-y: auto; padding: 8px; }
+.wk-palette__label { padding: 6px 10px 4px; font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--text-3); }
+.wk-palette__row { width: 100%; display: flex; align-items: center; gap: 12px; padding: 9px 10px; border-radius: 10px; border: 0; background: none; font: inherit; color: inherit; text-align: left; cursor: pointer; }
+.wk-palette__row.is-on { background: var(--active); }
+.wk-palette__row > i { flex: none; width: 9px; height: 9px; border-radius: 50%; background: var(--k); }
+.wk-palette__row > span { flex: 1; min-width: 0; display: grid; gap: 2px; }
+.wk-palette__row b { font-size: 14px; }
+.wk-palette__row small { color: var(--text-2); font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.wk-palette__row small p { margin: 0; display: inline; }
+.wk-palette__row small strong { color: var(--text); background: var(--accent-soft); border-radius: 3px; padding: 0 2px; }
+.wk-palette__row em { font-style: normal; font-size: 11.5px; color: var(--text-3); }
+.wk-palette__new { color: var(--accent); }
+.wk-palette__new b { color: var(--text); }
+
+/* settings */
+.wk-settings { width: min(560px, 94vw); display: grid; gap: 4px; padding: 22px 24px 24px; background: var(--panel); border-radius: 18px; box-shadow: var(--shadow-lg), 0 0 0 1px var(--border); animation: wk-fade 0.18s var(--ease) both; max-height: 88vh; overflow-y: auto; }
+.wk-settings header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; }
+.wk-settings h2 { margin: 0; font-size: 19px; }
+.wk-settings section { display: grid; gap: 10px; padding: 14px 0; border-top: 1px solid var(--border); }
+.wk-settings h4 { margin: 0; font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--text-3); }
+.wk-setting { display: flex; gap: 16px; align-items: center; justify-content: space-between; }
+.wk-setting > span { display: grid; gap: 2px; }
+.wk-setting b { font-size: 13.5px; font-weight: 600; }
+.wk-setting small { color: var(--text-2); font-size: 12.5px; line-height: 1.45; }
+.wk-setting .segmented { flex: none; }
+.wk-folder { display: flex; gap: 8px; align-items: center; padding: 10px 12px; border-radius: 9px; background: var(--code-bg); font: 12.5px var(--mono); color: var(--text-2); word-break: break-all; }
+
+/* panes: waiting, sources, care */
+.wk-pane { padding: 30px 32px 40px; display: grid; gap: 14px; align-content: start; }
+.wk-pane-head { padding-right: 36px; }
+.wk-pane-head { display: flex; gap: 14px; align-items: flex-start; margin-bottom: 6px; }
+.wk-pane-head__icon { flex: none; width: 40px; height: 40px; border-radius: 12px; display: grid; place-items: center; background: var(--accent-soft); color: var(--accent); }
+.wk-pane-head > div:not(.wk-pane-head__actions) { flex: 1; }
+.wk-pane-head h2 { margin: 0 0 3px; font-size: 20px; letter-spacing: -0.015em; }
+.wk-pane-head p { margin: 0; color: var(--text-2); font-size: 13.5px; line-height: 1.5; max-width: 560px; }
+.wk-calm { display: flex; gap: 10px; align-items: center; padding: 18px; border-radius: 14px; background: var(--ok-soft); color: var(--ok); font-weight: 600; font-size: 14px; }
+.wk-more { justify-self: start; margin-top: 8px; color: var(--text-2); }
+
+.wiki-change { padding: 16px 18px; border-radius: 14px; background: var(--panel); border: 1px solid var(--border); display: grid; gap: 12px; }
+.wiki-change--pending { border-color: color-mix(in srgb, var(--accent) 45%, var(--border)); box-shadow: 0 1px 0 var(--accent-soft), 0 8px 24px -14px color-mix(in srgb, var(--accent) 60%, transparent); }
+.wiki-change--conflict { border-color: color-mix(in srgb, var(--danger) 50%, var(--border)); }
+.wiki-change--undone, .wiki-change--refused { opacity: 0.6; }
+.wiki-change header { display: grid; gap: 5px; justify-items: start; }
+.wiki-change__state { font-size: 11px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; color: var(--text-3); }
+.wiki-change__state--pending { color: var(--accent); }
+.wiki-change__state--conflict { color: var(--danger); }
+.wiki-change__state--applied { color: var(--ok); }
+.wiki-change__why { font-size: 14.5px; font-weight: 600; line-height: 1.4; }
+.wiki-change__ops { display: grid; gap: 12px; }
+.wiki-change__actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
+.wiki-change__actions small { flex-basis: 100%; }
+.wiki-op { display: grid; gap: 6px; }
+.wiki-op__head { display: flex; gap: 6px; align-items: center; font-size: 12.5px; flex-wrap: wrap; }
+.wiki-op__verb { color: var(--text-3); font-weight: 600; }
+.wiki-diff { display: grid; gap: 3px; }
+.wiki-diff__old, .wiki-diff__new { padding: 9px 13px; border-radius: 9px; font-size: 13.5px; line-height: 1.55; border-left: 3px solid; }
+.wiki-diff__old { background: var(--danger-soft); border-color: color-mix(in srgb, var(--danger) 50%, transparent); text-decoration: line-through; text-decoration-color: color-mix(in srgb, var(--danger) 50%, transparent); color: var(--text-2); }
+.wiki-diff__new { background: var(--ok-soft); border-color: color-mix(in srgb, var(--ok) 55%, transparent); }
+.wiki-diff__old > :first-child, .wiki-diff__new > :first-child { margin-top: 0; }
+.wiki-diff__old > :last-child, .wiki-diff__new > :last-child { margin-bottom: 0; }
+.wiki-diff__new ul, .wiki-diff__old ul { padding-left: 18px; }
+
+.wk-finding { display: grid; gap: 12px; padding: 16px 18px; border-radius: 14px; border: 1px solid var(--border); background: var(--panel); position: relative; overflow: hidden; }
+.wk-finding::before { content: ''; position: absolute; inset: 0 auto 0 0; width: 3px; background: var(--tone); }
+.wk-finding--danger { --tone: var(--danger); }
+.wk-finding--warn { --tone: var(--warn); }
+.wk-finding--calm { --tone: var(--border-strong); }
+.wk-finding__head { display: grid; gap: 6px; }
+.wk-finding__kind { font-size: 11px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase; color: color-mix(in srgb, var(--tone) 85%, var(--text)); }
+.wk-finding--calm .wk-finding__kind { color: var(--text-3); }
+.wk-finding__text { font-size: 14px; line-height: 1.55; }
+.wk-finding__actions { display: flex; gap: 8px; }
+.wk-finding .wiki-change { padding: 0; border: 0; box-shadow: none; background: transparent; }
+
+.wk-add { display: grid; gap: 10px; }
+.wk-add__tile { display: grid; gap: 6px; align-content: start; padding: 16px; border-radius: 14px; border: 1px solid var(--border); background: var(--panel); }
+.wk-add__tile--file { cursor: pointer; border-style: dashed; border-width: 1.5px; transition: border-color 0.15s, background 0.15s; }
+.wk-add__tile--file:hover { border-color: var(--accent); background: color-mix(in srgb, var(--accent) 4%, var(--panel)); }
+.wk-add__tile b { font-size: 14px; margin-top: 4px; }
+.wk-add__tile small { color: var(--text-2); font-size: 12.5px; line-height: 1.45; }
+.wk-add__icons { display: flex; gap: 5px; }
+.wk-add__icons .wk-badge-file { width: 30px; height: 30px; }
+.wk-add__line { display: flex; gap: 6px; }
+.wk-add__line input { flex: 1; min-width: 0; padding: 6px 10px; border-radius: 8px; border: 1px solid var(--border); background: var(--bg); font: inherit; font-size: 13px; color: var(--text); }
+.wk-add__msg { grid-column: 1 / -1; display: grid; gap: 4px; }
+.wk-sources { display: grid; margin-top: 8px; border-radius: 14px; border: 1px solid var(--border); background: var(--panel); overflow: hidden; }
+.wk-source { display: flex; gap: 12px; align-items: center; padding: 11px 14px; border: 0; border-top: 1px solid var(--border); background: none; font: inherit; color: inherit; text-align: left; cursor: pointer; }
+.wk-source:first-child { border-top: 0; }
+.wk-source:hover { background: var(--hover); }
+.wk-source__main { flex: 1; min-width: 0; display: grid; gap: 1px; }
+.wk-source__main b { font-size: 13.5px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.wk-source__main small { color: var(--text-3); font-size: 12px; }
+.wk-status { flex: none; font-size: 12px; font-weight: 600; padding: 3px 9px; border-radius: 10px; display: inline-flex; align-items: center; gap: 6px; }
+.wk-status--reading { color: var(--warn); background: var(--warn-soft); }
+.wk-status--failed { color: var(--danger); background: var(--danger-soft); }
+.wk-status--done { color: var(--ok); background: var(--ok-soft); }
+
+/* reading: a page, a source */
+.wk-doc { font-size: 15.5px; line-height: 1.72; color: var(--text); }
+.wk-doc h1 { font-size: 22px; margin: 1.4em 0 0.4em; }
+.wk-doc h2 { font-size: 18px; font-weight: 680; letter-spacing: -0.01em; margin: 1.8em 0 0.5em; padding-top: 0.9em; border-top: 1px solid var(--border); }
+.wk-doc h2:first-child, .wk-doc h1:first-child { margin-top: 0; border-top: 0; padding-top: 0; }
+.wk-doc h3 { font-size: 15.5px; margin: 1.4em 0 0.4em; }
+.wk-doc p { margin: 0 0 0.85em; }
+.wk-doc > p:first-child { font-size: 17.5px; line-height: 1.6; color: var(--text); letter-spacing: -0.005em; }
+.wk-doc ul, .wk-doc ol { padding-left: 22px; margin: 0 0 0.9em; }
+.wk-doc li { margin: 0.25em 0; }
+.wk-doc li::marker { color: color-mix(in srgb, var(--k, var(--accent)) 70%, var(--text-3)); }
+.wk-doc table { border-collapse: collapse; width: 100%; font-size: 13.5px; margin: 0.6em 0 1em; }
+.wk-doc th, .wk-doc td { border-bottom: 1px solid var(--border); padding: 7px 10px; text-align: left; }
+.wk-doc th { font-weight: 650; color: var(--text-2); }
+.wk-doc blockquote { margin: 0 0 1em; padding: 4px 16px; border-left: 3px solid var(--k, var(--accent)); color: var(--text-2); }
+.wk-doc strong { font-weight: 650; }
+.wk-doc--source { padding: 22px 26px; margin-top: 18px; border-radius: 14px; background: var(--panel); border: 1px solid var(--border); font-size: 14.5px; }
+
+.wk-page { padding: 34px 36px 0; }
+.wk-page__kicker { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding-right: 40px; }
+.wk-page__meta { display: inline-flex; align-items: center; gap: 7px; color: var(--text-3); font-size: 12.5px; }
+.wk-page__title { margin: 16px 0 18px; font-size: 34px; line-height: 1.1; letter-spacing: -0.03em; font-weight: 700; }
+.wk-page__more { margin-top: 26px; padding-top: 18px; border-top: 1px solid var(--border); display: grid; gap: 8px; }
+.wk-page__more h5 { margin: 0 0 2px; font-size: 11px; font-weight: 650; letter-spacing: 0.06em; text-transform: uppercase; color: var(--text-3); }
+.wk-page__chips { display: flex; gap: 6px; flex-wrap: wrap; }
+.wk-page__source { display: flex; align-items: center; gap: 11px; padding: 7px 8px; margin: 0 -8px; border-radius: 10px; border: 0; background: none; font: inherit; color: inherit; text-align: left; cursor: pointer; }
+.wk-page__source:hover { background: var(--hover); }
+.wk-page__source span { display: grid; min-width: 0; }
+.wk-page__source b { font-size: 13px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.wk-page__source small { font-size: 11.5px; color: var(--text-3); }
+.wk-page__tools { position: sticky; bottom: 0; display: flex; gap: 6px; align-items: center; margin: 28px -36px 0; padding: 12px 36px 14px; background: var(--panel); border-top: 1px solid var(--border); }
+.wk-page__tools .grow { flex: 1; }
+.wk-history { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; }
+.wk-history li { display: grid; grid-template-columns: 18px 1fr auto; gap: 10px; font-size: 13px; line-height: 1.4; align-items: start; }
+.wk-history small { display: block; color: var(--text-3); font-size: 12px; }
+
+.wk-read { padding: 34px 36px 48px; }
+.wk-back { color: var(--text-3); margin-bottom: 14px; }
+.wk-read__kicker { display: flex; align-items: center; gap: 10px; color: var(--text-3); font-size: 12.5px; }
+.wk-read__title { margin: 12px 0 14px; font-size: 30px; letter-spacing: -0.025em; line-height: 1.15; }
+
+/* the editor */
+.wiki-editor { display: flex; flex-direction: column; gap: 14px; flex: 1; min-height: 0; padding: 0 32px 24px; }
+.wiki-editor__head { display: grid; gap: 12px; }
+.wiki-editor__title { font-size: 30px; font-weight: 700; letter-spacing: -0.025em; padding: 4px 0; border: 0; border-bottom: 2px solid var(--border); background: transparent; color: var(--text); outline: 0; transition: border-color 0.2s; }
+.wiki-editor__title:focus { border-color: var(--k, var(--accent)); }
+.wiki-editor__kinds { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; }
+.wiki-editor__kind { width: 140px; height: 24px; padding: 0 10px; border-radius: 12px; border: 1px dashed var(--border-strong); background: transparent; font: inherit; font-size: 12px; color: var(--text); }
+.wiki-editor__panes { flex: 1; min-height: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
+.wiki-editor__text { resize: none; padding: 18px 20px; border-radius: 14px; border: 1px solid var(--border); background: var(--panel); font: 13.5px/1.65 var(--mono); color: var(--text); outline: 0; transition: border-color 0.15s, box-shadow 0.15s; }
+.wiki-editor__text:focus { border-color: var(--border-strong); box-shadow: var(--shadow); }
+.wiki-editor__preview { overflow: auto; padding: 18px 24px; border-radius: 14px; border: 1px dashed var(--border); }
+
+/* in the conversation */
+.wiki-chip .wiki-link { margin-right: 4px; }
+.wiki-keep { display: inline-block; margin: 2px 0 0; font-size: 12px; opacity: 0; transition: opacity 0.15s; }
+.msg:hover .wiki-keep, .wiki-keep:has(.field__error) { opacity: 1; }
+
+@media (max-width: 900px) {
+ .wk-panel { left: 12px; width: auto; }
+ .wk-kinds { display: none; }
+ .wiki-editor__panes { grid-template-columns: 1fr; }
+ .wk-foot > span:last-child { display: none; }
+}
+.wk-setting .toggle, .wk-pane-head__actions { flex: none; }
+.wk-checks { display: grid; gap: 8px; }
+.wk-check { display: flex; gap: 12px; padding: 14px 16px; border-radius: 14px; border: 1px solid var(--border); background: var(--panel); }
+.wk-check i { flex: none; width: 10px; height: 10px; margin-top: 5px; border-radius: 50%; background: var(--tone); box-shadow: 0 0 0 4px color-mix(in srgb, var(--tone) 18%, transparent); }
+.wk-check b { display: block; font-size: 13.5px; margin-bottom: 2px; }
+.wk-check small { color: var(--text-2); font-size: 12.5px; line-height: 1.45; }
+.wk-canvas.is-holding { cursor: grabbing; }
+.wk-node.is-held .wk-node__halo { opacity: 0.25; }
+.wk-node.is-held text { fill: var(--text); font-weight: 650; }
+.wk-import { gap: 16px; }
+.wk-import__busy { display: grid; justify-items: center; gap: 8px; padding: 30px 0; }
+.wk-import__busy .wk-spin { width: 20px; height: 20px; color: var(--accent); }
+.wk-import__stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
+.wk-import__stats span { display: grid; gap: 2px; padding: 14px 16px; border-radius: 14px; background: var(--hover); color: var(--text-2); font-size: 12.5px; }
+.wk-import__stats b { font-size: 26px; letter-spacing: -0.02em; color: var(--text); }
+.wiki-link--file { cursor: default; }
diff --git a/src/shared/rpc.ts b/src/shared/rpc.ts
index 8c85629..b9a7f57 100644
--- a/src/shared/rpc.ts
+++ b/src/shared/rpc.ts
@@ -1,4 +1,5 @@
// The contract between the renderer and the core, carried over a MessagePort.
+import type { WikiChange, WikiHit, WikiPage, WikiImport, WikiPageInfo, WikiReview, WikiSource, WikiVersion } from './types'
import type { Os, Account, AccountEngine, Agent, BrowserInput, Approval, Artifact, ImageUpload, BrowserView, ComputerInfo, Connector, ConnectorInput, ConnectorTool, HarnessMcp, Conversation, EngineId, Memory, MemoryScope, Message, Routine, RoutineInput, Report, Settings, LocalSkill, Skill, SkillInput, SkillVersion, Trigger, UsageReport } from './types'
export interface Snapshot {
@@ -98,6 +99,38 @@ export interface Api {
setGithubToken(p: { token: string | null }): Promise<void> // checked with GitHub; throws why it's refused
removeRoutine(p: { id: string }): void
runRoutine(p: { id: string }): void
+ // The wiki: pages in a folder of Markdown, linked, searched and kept with their history.
+ wiki(): { dir: string; pages: WikiPageInfo[]; kinds: string[]; log: string[]; pending: number; findings: number; server: boolean; graph: { nodes: { title: string; kind: string; links: number; missing?: boolean }[]; edges: [string, string][] }; recent: Omit<WikiVersion, 'before' | 'after'>[]; sources: number } // pending: the curator's changes; the review's are in findings
+ wikiPage(p: { title: string }): WikiPage | null
+ wikiSearch(p: { q: string }): WikiHit[]
+ wikiSave(p: { title: string; body: string; kind?: string; expectedHash?: string; rename?: string }): WikiPage // throws on a conflict or a taken title
+ wikiRemove(p: { title: string }): void
+ wikiHistory(p: { title: string }): WikiVersion[]
+ wikiRestore(p: { id: number }): WikiPage
+ wikiSchema(): string
+ wikiSaveSchema(p: { text: string }): void
+ openWikiFolder(): void
+ wikiChanges(p: { state?: WikiChange['state'] }): WikiChange[]
+ wikiChange(p: { id: string }): WikiChange | null
+ wikiApplyChange(p: { id: string }): WikiChange // a pending one; a conflict comes back as such
+ wikiRefuseChange(p: { id: string }): void
+ wikiUndoChange(p: { id: string }): void
+ wikiSources(): WikiSource[]
+ wikiSource(p: { id: string }): (WikiSource & { text: string }) | null
+ wikiKeepMessage(p: { messageId: string }): Promise<number> // how many changes it made; throws when no model is ready
+ wikiRedoChange(p: { id: string }): Promise<number> // a conflict, made again on the newer page
+ // Sources brought on purpose: the text is taken now, the curator reads it next (status on the source).
+ wikiAddFile(p: { name: string; data: string }): Promise<WikiSource> // data: base64
+ wikiAddLink(p: { url: string }): Promise<WikiSource>
+ wikiAddNote(p: { text: string; title?: string }): WikiSource
+ wikiOpenOriginal(p: { id: string }): { name: string; data: string } | null // on a server: the file itself (base64), to download
+ wikiIngestAgain(p: { id: string }): void
+ wikiReview(): WikiReview // the last review and what it found that's still open
+ wikiRunReview(): void // reviews now, in the background; a 'wiki' event when done
+ wikiDismissFinding(p: { id: string }): void // and refuses its fix
+ wikiImport(p: { dir: string }): WikiImport // an Obsidian vault copied in, as it is
+ setWikiCapture(p: { conversationId: string; on: boolean }): void
+ setWikiDir(p: { dir: string | null }): Promise<string> // null: back to the app's own folder; returns where it is now
}
export type Method = keyof Api
@@ -123,6 +156,7 @@ export type CoreEvent =
| { type: 'conversation_removed'; id: string }
| { type: 'skill'; skill: Skill }
| { type: 'skill_removed'; id: string }
+ | { type: 'wiki' } // a page changed: here, by an agent or in another app
export type Request = { id: number; method: Method; params: unknown }
export type Response = { id: number; result?: unknown; error?: string }
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 0cf5da3..3834290 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -59,6 +59,7 @@ export interface Agent {
customColor?: string // a color of the person's own (#rrggbb), over `color`
picture?: string // a small picture (data URL), over the face
avatar?: AvatarDefinition // a drawn character (open-bot-avatar), over the face; a picture wins over it
+ wiki?: WikiAccess // what it can do with the wiki; 'read' when unset
instructions: string
modelId: string
// Where a reply goes when modelId's subscription is out (its 5-hour or weekly limit, a 429): tried
@@ -114,6 +115,7 @@ export interface Conversation {
summaryUntil?: number // `at` of the last message the summary covers
summaryAt?: number
unread?: number
+ wikiCapture?: boolean // false: the wiki's curator leaves this conversation out
}
// "Lançamento do App" → "lancamento-do-app": lowercase, no accents, hyphens.
@@ -157,6 +159,7 @@ export interface Run {
depth?: number // 1 when a human message triggered it, +1 for each agent-to-agent hop
question?: string // asked with ask_user; answered by the next human message here
memoryIds?: string[] // memories saved or proposed with `lembrar` in this reply
+ wikiChanges?: string[] // what the wiki's curator kept from this exchange (change packages)
artifactIds?: string[] // files and screenshots shown in this reply
services?: string[] // services started in this reply, by name, on the author's computer
routineIds?: string[] // routines scheduled or changed with `agendar_rotina` in this reply
@@ -205,6 +208,10 @@ export interface Settings {
browserJev?: boolean // Jev finds what agents click in their browsers (each click sends the page to TypeSafe)
memoryModel: string // summarizes conversations and extracts memories
memoryLearning: 'approve' | 'auto' | 'off' // what extracted memories about me become
+ wikiCapture?: boolean // the curator reads the conversations and keeps what lasts; on when unset
+ wikiEdits?: 'approve' | 'auto' // changing a page that exists: waits for me (the default) or goes in
+ wikiReview?: 'weekly' | 'off' // reviews the wiki on its own once a week; by hand only otherwise (the default)
+ wikiDir?: string // where the wiki's folder is (an Obsidian vault, say); inside the app's data when unset
defaultLimit: number
approvalTtlHours: number
theme: 'system' | 'light' | 'dark'
@@ -775,3 +782,96 @@ export interface Report {
skills: SkillReport[]
work: { work: string; tokens: number; replies: number; agents: string[]; last: number }[]
}
+
+// ---------- the wiki ----------
+export type WikiAccess = 'none' | 'read'
+export const wikiAccess = (a: Pick<Agent, 'wiki' | 'kind'>): WikiAccess => (a.kind === 'tuca' ? 'none' : (a.wiki ?? 'read'))
+export interface WikiPageInfo {
+ title: string
+ kind: string // the page's tipo, from its frontmatter
+ summary: string // its first line worth reading
+ updatedAt: number
+ updatedBy: string // 'me', an agent's id, or 'outside' (changed in another app)
+}
+export interface WikiPage extends WikiPageInfo {
+ body: string // the Markdown, without the frontmatter
+ meta: Record<string, string>
+ hash: string // of the file as read: a save made on an older copy is refused
+ links: string[] // the titles it links to
+ missing: string[] // of those, the ones with no page yet
+ backlinks: string[] // the pages that link to it
+ file: string // where it is, inside the wiki's folder
+}
+export interface WikiHit {
+ title: string
+ kind: string
+ snippet: string // the matching part, with **marks**
+}
+export interface WikiVersion {
+ id: number
+ title: string
+ at: number
+ by: string
+ action: 'create' | 'edit' | 'delete'
+ before: string | null
+ after: string | null
+ reason?: string
+}
+export interface WikiSource {
+ id: string
+ file: string // "fontes/<date> <title>", inside the wiki's folder (a [[link]] target)
+ title: string
+ kind: 'conversation' | 'message' | 'note' | 'file' | 'link'
+ origin: { conversationId?: string; messageIds?: string[]; url?: string; original?: string } // original: the file as it came, inside the wiki's folder
+ status?: 'reading' | 'done' | 'failed' // a file, a link or a note while the curator reads it
+ error?: string
+ changes?: number // how many change packages it became
+ addedBy: string // 'me', 'auto' (the curator) or an agent's id
+ addedAt: number
+}
+// One change in a package: write a new page, add under a section of one, or swap an exact passage.
+export interface WikiOp {
+ op: 'create' | 'append' | 'replace'
+ page: string
+ kind?: string // for a new page
+ section?: string // for append: the ## heading it goes under (made if missing)
+ text?: string // create, append
+ old?: string // replace
+ new?: string // replace
+}
+export interface WikiChange {
+ id: string
+ at: number
+ by: string // 'auto' (the curator) or 'me'
+ state: 'pending' | 'applied' | 'refused' | 'conflict' | 'undone'
+ ops: WikiOp[]
+ reason?: string // why the curator thought it worth keeping
+ source?: { id: string; title: string; file: string }
+ decidedAt?: number
+}
+// What a review of the wiki found: something broken, missing or that no longer adds up.
+export interface WikiFinding {
+ id: string
+ at: number
+ kind: 'broken' | 'missing' | 'orphan' | 'contradiction' | 'stale' | 'duplicate' | 'link'
+ pages: string[] // the pages it is about
+ text: string // what's wrong, in a sentence (Markdown, with [[links]])
+ name?: string // broken, missing: the page it would take
+ change?: WikiChange // the fix it suggests, waiting for approval
+}
+// What came in from an Obsidian vault.
+export interface WikiImport {
+ from: string // the vault's name
+ pages: number
+ attachments: number // images, PDFs and the like, copied along
+ skipped: string[] // files already in the wiki, left as they were
+ links: number // links between pages, in the whole wiki now
+ missing: number // links to pages nobody wrote yet
+ kinds: [string, number][] // the kinds the new pages got (their tipo, folder or first tag)
+}
+export interface WikiReview {
+ at?: number // the last review
+ running: boolean
+ error?: string // the last review failed
+ findings: WikiFinding[] // still open
+}
diff --git a/test/wiki-curator.test.ts b/test/wiki-curator.test.ts
new file mode 100644
index 0000000..3b3f7a3
--- /dev/null
+++ b/test/wiki-curator.test.ts
@@ -0,0 +1,214 @@
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, it } from 'vitest'
+import type { Agent, Message, Settings } from '../src/shared/types'
+import { applyOp, Wiki } from '../src/core/wiki'
+import { parseCuration, WikiCurator } from '../src/core/wiki-curator'
+
+const fresh = (): Wiki => {
+ const root = mkdtempSync(join(tmpdir(), 'tucano-wiki-'))
+ const w = new Wiki({ dir: join(root, 'wiki'), indexPath: join(root, 'wiki.db') })
+ w.init(false)
+ return w
+}
+const by = { by: 'me', byName: 'Ana' }
+
+describe('a change on a page', () => {
+ it('adds under a section, makes the section when missing, swaps an exact passage', () => {
+ const body = '# Marcos\n\nCliente.\n\n## Histórico\n- 28/10: pediu orçamento.\n\n## Contato\n- (41) 9999'
+ expect(applyOp(body, { op: 'append', page: 'M', section: 'Histórico', text: '- 03/11: recebeu.' })).toContain('- 28/10: pediu orçamento.\n- 03/11: recebeu.\n\n## Contato')
+ expect(applyOp(body, { op: 'append', page: 'M', section: 'Decisões', text: '- Piso vinílico.' })).toMatch(/## Decisões\n- Piso vinílico\.\n$/)
+ expect(applyOp(body, { op: 'replace', page: 'M', old: '(41) 9999', new: '(41) 8888' })).toContain('(41) 8888')
+ expect(() => applyOp(body, { op: 'replace', page: 'M', old: 'não existe', new: 'x' })).toThrow()
+ })
+})
+
+describe('change packages', () => {
+ it('applies, refuses on a conflict, and undoes', () => {
+ const w = fresh()
+ w.save({ title: 'Marcos Lima', body: 'Cliente.\n\n## Histórico\n- 28/10: pediu orçamento.', ...by })
+ const c = w.addChange({ ops: [{ op: 'append', page: 'Marcos Lima', section: 'Histórico', text: '- 03/11: recebeu o orçamento.' }, { op: 'create', page: 'Reforma', kind: 'Projeto', text: 'Do [[Marcos Lima]].' }], by: 'auto' })
+ expect(c.state).toBe('pending')
+ expect(w.applyChange(c.id, 'Curador').state).toBe('applied')
+ expect(w.page('Marcos Lima')!.body).toContain('03/11: recebeu')
+ expect(w.page('Reforma')!.kind).toBe('Projeto')
+ w.undoChange(c.id, 'Ana')
+ expect(w.page('Reforma')).toBeUndefined()
+ expect(w.page('Marcos Lima')!.body).not.toContain('03/11')
+ expect(w.change(c.id)!.state).toBe('undone')
+
+ // a page changed after the package was made: nothing is written
+ const c2 = w.addChange({ ops: [{ op: 'append', page: 'Marcos Lima', text: 'x' }], by: 'auto' })
+ const p = w.page('Marcos Lima')!
+ w.save({ title: 'Marcos Lima', body: p.body + '\nEditada por mim.', expectedHash: p.hash, ...by })
+ expect(w.applyChange(c2.id, 'Ana').state).toBe('conflict')
+ expect(w.page('Marcos Lima')!.body).not.toMatch(/\nx\n/)
+ w.refuseChange(c2.id)
+ expect(w.change(c2.id)!.state).toBe('refused')
+ })
+
+ it('keeps a source as it came, in the fontes folder', () => {
+ const w = fresh()
+ const s = w.addSource({ title: 'E-mail do Marcos', text: 'Quero começar em janeiro.', kind: 'message', by: 'auto' })
+ expect(s.file).toMatch(/^fontes\/\d{4}-\d\d-\d\d \d{4} E-mail do Marcos$/)
+ expect(w.source(s.id)!.text).toContain('Quero começar em janeiro.')
+ expect(w.sources()[0]!.title).toBe('E-mail do Marcos')
+ })
+})
+
+describe('the curator', () => {
+ const agents = [{ id: 'lia', name: 'Lia' } as Agent]
+ const off = new Set<string>()
+ const setup = (reply: (prompt: string) => string, settings: Partial<Settings> = {}) => {
+ const w = fresh()
+ const messages: Message[] = []
+ const emitted: Message[] = []
+ const calls: string[] = []
+ const curator = new WikiCurator({
+ wiki: w,
+ db: {
+ conversation: (id) => ({ id, kind: 'dm', name: 'lia', ...(off.has(id) ? { wikiCapture: false } : {}) }),
+ messagesAfter: (_c, at) => messages.filter((m) => m.at > at),
+ message: (id) => messages.find((m) => m.id === id),
+ saveMessage: (m) => messages.splice(messages.findIndex((x) => x.id === m.id), 1, m),
+ agents: () => agents
+ },
+ settings: () => ({ workspaceName: 'Ana', ...settings }) as Settings,
+ llm: async (_s, prompt) => (calls.push(prompt), reply(prompt)),
+ emitMessage: (m) => emitted.push(m)
+ })
+ const say = (id: string, who: 'me' | 'lia', text: string, at: number): void => {
+ messages.push({ id, conversationId: 'c', author: who === 'me' ? { kind: 'me' } : { kind: 'agent', id: 'lia' }, text, at, ...(who === 'lia' ? { run: { status: 'done', steps: [] } } : {}) } as Message)
+ }
+ return { w, curator, say, calls, emitted, messages }
+ }
+ const decision = JSON.stringify({
+ guardar: true,
+ motivo: 'Uma decisão sobre a reforma.',
+ titulo_fonte: 'Orçamento aceito',
+ mudancas: [
+ { op: 'create', pagina: 'Reforma do apto 302', tipo: 'Projeto', texto: 'Reforma do [[Marcos Lima]].\n\n## Decisões\n- Fechou em R$ 12.960.' },
+ { op: 'append', pagina: 'Marcos Lima', secao: 'Histórico', texto: '- 03/11: aceitou o orçamento.' }
+ ]
+ })
+
+ it('keeps a decision: the new page goes in, the edit waits for you, the reply says so', async () => {
+ const { w, curator, say, emitted } = setup(() => '```json\n' + decision + '\n```')
+ w.save({ title: 'Marcos Lima', kind: 'Pessoa', body: 'Cliente.\n\n## Histórico\n- 28/10: pediu orçamento.', ...by })
+ say('m1', 'me', 'O Marcos aceitou o orçamento de R$ 12.960 da reforma, fechado em 3 vezes. Começa em janeiro.', 1)
+ say('m2', 'lia', 'Ótimo! Anotei: reforma do apto 302 fechada em R$ 12.960, em 3 vezes, começo em janeiro.', 2)
+ await curator.read('c')
+ expect(w.page('Reforma do apto 302')!.body).toContain('Fechou em R$ 12.960.')
+ expect(w.page('Reforma do apto 302')!.body).toMatch(/Fontes: \[\[fontes\/.+\|Orçamento aceito\]\]/)
+ expect(w.page('Marcos Lima')!.body).not.toContain('aceitou') // waits
+ const [pending] = w.changes('pending')
+ expect(pending!.ops[0]!.text).toMatch(/aceitou o orçamento\. \(\[\[fontes\/.+\|fonte\]\]\)$/)
+ expect(emitted.at(-1)!.run!.wikiChanges).toHaveLength(2)
+ expect(w.mark('c')).toBe(2)
+ })
+
+ it('with edits on auto, the edit goes in too', async () => {
+ const { w, curator, say } = setup(() => decision, { wikiEdits: 'auto' })
+ w.save({ title: 'Marcos Lima', body: 'Cliente.\n\n## Histórico\n- 28/10.', ...by })
+ say('m1', 'me', 'O Marcos aceitou o orçamento de R$ 12.960 da reforma, fechado em 3 vezes, e quer começar em janeiro.', 1)
+ say('m2', 'lia', 'Ótimo, fica registrado: R$ 12.960 em 3 vezes, começo em janeiro.', 2)
+ await curator.read('c')
+ expect(w.page('Marcos Lima')!.body).toContain('aceitou o orçamento')
+ expect(w.changes('pending')).toHaveLength(0)
+ })
+
+ it('reads nothing twice, skips small talk without asking the model, and keeps nothing when it says so', async () => {
+ const { w, curator, say, calls } = setup(() => JSON.stringify({ guardar: false, mudancas: [] }))
+ say('m1', 'me', 'oi', 1)
+ say('m2', 'lia', 'Oi, Ana!', 2)
+ await curator.read('c')
+ expect(calls).toHaveLength(0)
+ say('m3', 'me', 'Que horas são em Tóquio agora? Estou curiosa pra saber a diferença de fuso de lá pra cá.', 3)
+ say('m4', 'lia', 'Em Tóquio são 22h agora: 12 horas a mais que Curitiba, já que lá não tem horário de verão.', 4)
+ await curator.read('c')
+ await curator.read('c')
+ expect(calls).toHaveLength(1)
+ expect(w.sources()).toHaveLength(0)
+ })
+
+ it('keeps a message on purpose, with the question it answered', async () => {
+ const { w, curator, say, calls } = setup(() => JSON.stringify({ guardar: false, titulo_fonte: 'Roteiro', mudancas: [{ op: 'create', pagina: 'Viagem a Morretes', tipo: 'Projeto', texto: 'Trem às 8h15.' }] }))
+ say('m1', 'me', 'Planeja o feriado', 1)
+ say('m2', 'lia', 'Morretes de trem, saindo às 8h15.', 2)
+ expect(await curator.keepMessage('m2')).toHaveLength(1)
+ expect(calls[0]).toContain('pediu pra guardar')
+ expect(calls[0]).toContain('Planeja o feriado')
+ expect(w.page('Viagem a Morretes')).toBeDefined()
+ })
+
+ it("doesn't read again what was kept on purpose", async () => {
+ const { curator, say, calls } = setup(() => JSON.stringify({ guardar: true, titulo_fonte: 'Fechamento', mudancas: [{ op: 'create', pagina: 'Reforma', tipo: 'Projeto', texto: 'Fechada.' }] }))
+ say('m1', 'me', 'O Marcos fechou a reforma! Começa dia 12 de janeiro, em 3 vezes de R$ 4.320.', 1)
+ say('m2', 'lia', 'Que ótimo! Reforma fechada: começa em 12/01, 3 parcelas de R$ 4.320.', 2)
+ await curator.keepMessage('m2')
+ await curator.read('c') // the conversation settles: those two are already kept
+ expect(calls).toHaveLength(1)
+ say('m3', 'me', 'Na verdade começa dia 15 de janeiro, o Marcos pediu pra adiar uns dias por causa da mudança.', 3)
+ say('m4', 'lia', 'Anotado: o início da reforma passa pra 15/01, a pedido do Marcos. As parcelas continuam as mesmas, 3 de R$ 4.320.', 4)
+ await curator.read('c')
+ expect(calls).toHaveLength(2)
+ expect(calls[1]).toContain('15 de janeiro')
+ expect(calls[1]).not.toContain('Começa dia 12')
+ })
+
+ it('reads the model leniently', () => {
+ expect(parseCuration('nada')).toBeNull()
+ expect(parseCuration('{"guardar": true, "mudancas": [{"op": "append", "pagina": "[[X]]", "texto": "y"}, {"op": "replace", "pagina": "X"}, {"op": "voar", "pagina": "X"}]}')).toMatchObject({ worth: true, ops: [{ op: 'append', page: 'X', text: 'y' }] })
+ })
+
+ it('leaves out a conversation kept out of the wiki, but keeps a message kept on purpose', async () => {
+ const { w, curator, say, calls } = setup(() => decision)
+ off.add('c')
+ say('m1', 'me', 'O Marcos aceitou o orçamento de R$ 12.960 da reforma, fechado em 3 vezes, e quer começar em janeiro.', 1)
+ say('m2', 'lia', 'Ótimo, fica registrado: R$ 12.960 em 3 vezes, começo em janeiro.', 2)
+ await curator.read('c')
+ expect(calls).toHaveLength(0)
+ expect(await curator.keepMessage('m2')).not.toHaveLength(0)
+ expect(w.page('Reforma do apto 302')).toBeDefined()
+ off.clear()
+ })
+
+ it('redoes a conflict on the newer page; when the passage is gone, writes it again from the source', async () => {
+ const { w, curator } = setup(() => JSON.stringify({ guardar: true, mudancas: [{ op: 'append', pagina: 'Marcos Lima', secao: 'Histórico', texto: '- 03/11: refeito.' }] }))
+ w.save({ title: 'Marcos Lima', body: 'Cliente.\n\n## Histórico\n- 28/10.', ...by })
+ const src = w.addSource({ title: 'Conversa', text: 'O Marcos aceitou.', kind: 'conversation', by: 'auto' })
+ const append = w.addChange({ ops: [{ op: 'append', page: 'Marcos Lima', section: 'Histórico', text: '- 03/11: aceitou.' }], sourceId: src.id, by: 'auto' })
+ const swap = w.addChange({ ops: [{ op: 'replace', page: 'Marcos Lima', old: 'Cliente.', new: 'Cliente desde março.' }], sourceId: src.id, by: 'auto' })
+ const p = w.page('Marcos Lima')!
+ w.save({ title: 'Marcos Lima', body: p.body.replace('Cliente.', 'Cliente antigo.'), expectedHash: p.hash, ...by })
+ expect(w.applyChange(append.id, 'Ana').state).toBe('conflict')
+ expect(w.applyChange(swap.id, 'Ana').state).toBe('conflict')
+ // the add still fits: made again on the page as it is now
+ const [again] = await curator.redo(append.id)
+ expect(again!.state).toBe('pending')
+ expect(w.change(append.id)!.state).toBe('refused')
+ expect(w.applyChange(again!.id, 'Ana').state).toBe('applied')
+ expect(w.page('Marcos Lima')!.body).toContain('Cliente antigo.')
+ expect(w.page('Marcos Lima')!.body).toContain('03/11: aceitou.')
+ // the swapped passage is gone: the curator writes it again from the source
+ const redone = await curator.redo(swap.id)
+ expect(redone).toHaveLength(1)
+ expect(redone[0]!.ops[0]!.text).toContain('refeito.')
+ })
+})
+
+describe('the wiki in another folder', () => {
+ it('moves to another folder with an index of its own, and comes back', () => {
+ const root = mkdtempSync(join(tmpdir(), 'tucano-wiki-'))
+ const w = new Wiki({ dir: join(root, 'a'), indexPath: join(root, 'a.db') })
+ w.init(false)
+ w.save({ title: 'Na pasta A', body: 'a', ...by })
+ w.relocate(join(root, 'b'), join(root, 'b.db'))
+ expect(w.list()).toEqual([])
+ w.save({ title: 'Na pasta B', body: 'b', ...by })
+ w.relocate(join(root, 'a'), join(root, 'a.db'))
+ expect(w.list().map((p) => p.title)).toEqual(['Na pasta A'])
+ w.close()
+ })
+})
diff --git a/test/wiki-extract.test.ts b/test/wiki-extract.test.ts
new file mode 100644
index 0000000..57fe190
--- /dev/null
+++ b/test/wiki-extract.test.ts
@@ -0,0 +1,91 @@
+import { existsSync, mkdtempSync, readFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import ExcelJS from 'exceljs'
+import JSZip from 'jszip'
+import { describe, expect, it } from 'vitest'
+import type { Settings } from '../src/shared/types'
+import { Wiki } from '../src/core/wiki'
+import { WikiCurator } from '../src/core/wiki-curator'
+import { extractFile, extractLink, parseCsv } from '../src/core/wiki-extract'
+
+// The smallest PDF with one line of text (pdf.js rebuilds the missing cross-reference table).
+const pdf = (line: string): Buffer => {
+ const stream = `BT /F1 18 Tf 20 100 Td (${line}) Tj ET`
+ return Buffer.from(
+ `%PDF-1.4\n1 0 obj<</Type/Catalog/Pages 2 0 R>>endobj\n2 0 obj<</Type/Pages/Kids[3 0 R]/Count 1>>endobj\n3 0 obj<</Type/Page/Parent 2 0 R/MediaBox[0 0 400 144]/Contents 4 0 R/Resources<</Font<</F1 5 0 R>>>>>>endobj\n4 0 obj<</Length ${stream.length}>>stream\n${stream}\nendstream endobj\n5 0 obj<</Type/Font/Subtype/Type1/BaseFont/Helvetica>>endobj\ntrailer<</Root 1 0 R>>\n%%EOF\n`,
+ 'latin1'
+ )
+}
+// A Word file with two paragraphs.
+const docx = async (paras: string[]): Promise<Buffer> => {
+ const zip = new JSZip()
+ zip.file('[Content_Types].xml', '<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>')
+ zip.file('_rels/.rels', '<?xml version="1.0"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="r1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>')
+ zip.file('word/document.xml', `<?xml version="1.0"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>${paras.map((p) => `<w:p><w:r><w:t>${p}</w:t></w:r></w:p>`).join('')}</w:body></w:document>`)
+ return zip.generateAsync({ type: 'nodebuffer' })
+}
+
+describe('reading files and links', () => {
+ it('reads a PDF, a Word file, a spreadsheet, a CSV and text', async () => {
+ expect(await extractFile('contrato.pdf', pdf('Contrato Silva e Souza'))).toContain('Contrato Silva e Souza')
+ expect(await extractFile('contrato.docx', await docx(['Cliente: Silva & Souza', 'Valor: R$ 4.800']))).toBe('Cliente: Silva &amp; Souza\n\nValor: R$ 4.800'.replace('&amp;', '&'))
+ const book = new ExcelJS.Workbook()
+ const sheet = book.addWorksheet('Gastos')
+ sheet.addRow(['Mês', 'Mercado'])
+ sheet.addRow(['Outubro', 1390])
+ expect(await extractFile('gastos.xlsx', Buffer.from(await book.xlsx.writeBuffer()))).toBe('## Gastos\n\n| Mês | Mercado |\n| --- | --- |\n| Outubro | 1390 |')
+ expect(await extractFile('g.csv', Buffer.from('nome;valor\n"Silva; Souza";4800\n'))).toContain('| Silva; Souza | 4800 |')
+ expect(await extractFile('n.md', Buffer.from('# Nota\n\nTexto.'))).toBe('# Nota\n\nTexto.')
+ await expect(extractFile('foto.heic', Buffer.from('x'))).rejects.toThrow('.heic')
+ })
+
+ it('splits CSV with quotes, commas and line breaks inside', () => {
+ expect(parseCsv('a,b\n"x, y","linha\nquebrada"\n')).toEqual([['a', 'b'], ['x, y', 'linha\nquebrada']])
+ })
+
+ it("takes a page's main content, not its menu", async () => {
+ const html = '<html><head><title>Guia</title></head><body><nav>Menu Início Contato</nav><article><h1>Piso vinílico</h1><p>É mais barato e rápido de instalar que o porcelanato, e aguenta bem a umidade da cozinha.</p><ul><li>Prazo médio: 45 dias</li></ul></article><footer>Rodapé</footer></body></html>'
+ const page = await extractLink('https://exemplo.com/guia', (async () => new Response(html, { headers: { 'content-type': 'text/html' } })) as unknown as typeof fetch)
+ expect(page.title).toBe('Guia')
+ expect(page.text).toContain('aguenta bem a umidade')
+ expect(page.text).toContain('- Prazo médio: 45 dias')
+ expect(page.text).not.toContain('Rodapé')
+ await expect(extractLink('ftp://x')).rejects.toThrow('http')
+ })
+})
+
+describe('a document brought to the wiki', () => {
+ it('keeps the original, reads it in parts and turns it into pages', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'tucano-wiki-'))
+ const w = new Wiki({ dir: join(root, 'wiki'), indexPath: join(root, 'wiki.db') })
+ w.init(false)
+ const prompts: string[] = []
+ const curator = new WikiCurator({
+ wiki: w,
+ db: { conversation: () => undefined, messagesAfter: () => [], message: () => undefined, saveMessage: () => {}, agents: () => [] },
+ settings: () => ({ workspaceName: 'Ana' }) as Settings,
+ llm: async (_s, prompt) => {
+ prompts.push(prompt)
+ const part = /parte (\d) de/.exec(prompt)?.[1] ?? '1'
+ return JSON.stringify({ guardar: true, titulo_fonte: 'Contrato', mudancas: [{ op: 'create', pagina: `Cláusulas ${part}`, tipo: 'Assunto', texto: `Parte ${part} do contrato.` }] })
+ },
+ emitMessage: () => {}
+ })
+ const long = Array.from({ length: 30 }, (_, k) => `Cláusula ${k + 1}. ${'Texto do contrato. '.repeat(120)}`).join('\n\n')
+ const src = w.addSource({ title: 'Contrato Silva', text: long, kind: 'file', file: { name: 'contrato.pdf', data: Buffer.from('%PDF') }, by: 'me', status: 'reading' })
+ expect(existsSync(w.originalPath(src.id)!)).toBe(true)
+ expect(readFileSync(w.originalPath(src.id)!, 'utf8')).toBe('%PDF')
+ await curator.ingest(src.id)
+ expect(prompts.length).toBeGreaterThan(1)
+ expect(prompts[0]).toContain('documento que a pessoa trouxe')
+ expect(w.source(src.id)).toMatchObject({ status: 'done', changes: prompts.length })
+ expect(w.page('Cláusulas 1')!.body).toMatch(/Fontes: \[\[fontes\/.+\|Contrato Silva\]\]/)
+
+ // a note: kept on purpose; a curator that fails marks the source as failed
+ const broken = new WikiCurator({ wiki: w, db: { conversation: () => undefined, messagesAfter: () => [], message: () => undefined, saveMessage: () => {}, agents: () => [] }, settings: () => ({}) as Settings, llm: async () => { throw new Error('sem modelo') }, emitMessage: () => {} })
+ const note = w.addSource({ title: 'Lembrete', text: 'O Marcos prefere WhatsApp depois das 18h.', kind: 'note', by: 'me', status: 'reading' })
+ await broken.ingest(note.id)
+ expect(w.source(note.id)).toMatchObject({ status: 'failed', error: 'sem modelo' })
+ })
+})
diff --git a/test/wiki-import.test.ts b/test/wiki-import.test.ts
new file mode 100644
index 0000000..5be659c
--- /dev/null
+++ b/test/wiki-import.test.ts
@@ -0,0 +1,77 @@
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { linksIn, Wiki } from '../src/core/wiki'
+
+const vault = (): string => {
+ const v = mkdtempSync(join(tmpdir(), 'cofre-'))
+ const w = (rel: string, text: string): void => (mkdirSync(join(v, rel, '..'), { recursive: true }), writeFileSync(join(v, rel), text))
+ w('.obsidian/app.json', '{}')
+ w('Anexos/planta.png', 'png')
+ w('Clientes/Marcos Lima.md', '---\ntags:\n - cliente\n - reforma\naliases:\n - Marcos\n---\nCliente da [[Projetos/Reforma do 302|reforma]], indicado pela [[Construtora Alpha]].\n\n![[planta.png]]\n')
+ w('Projetos/Reforma do 302.md', '---\ncliente: "[[Marcos Lima]]"\n---\nA obra. Ver [[Prazos#Apartamentos]].\n')
+ w('Construtora Alpha.md', '---\ntags: [fornecedor]\n---\nParceira.\n')
+ w('Prazos.md', 'Sem cabeçalho. [[Orçamento da Beta]].\n')
+ return v
+}
+const fresh = (): Wiki => {
+ const root = mkdtempSync(join(tmpdir(), 'tucano-wiki-'))
+ const w = new Wiki({ dir: join(root, 'wiki'), indexPath: join(root, 'wiki.db') })
+ w.init(false)
+ return w
+}
+
+describe('an Obsidian vault', () => {
+ it('reads links the way Obsidian does', () => {
+ expect(linksIn('[[Clientes/Marcos Lima|Marcos]] [[Prazos#Casas]] [[Nota.md]] ![[foto.png]] ![[Outra nota]]')).toEqual(['Marcos Lima', 'Prazos', 'Nota', 'Outra nota'])
+ })
+
+ it('comes in as it is: folders, links, attachments, kinds; the vault stays untouched', () => {
+ const v = vault()
+ const before = readFileSync(join(v, 'Clientes/Marcos Lima.md'), 'utf8')
+ const w = fresh()
+ const r = w.importVault(v, 'Ana')
+ expect(r).toMatchObject({ pages: 4, attachments: 1, skipped: [], missing: 1 })
+ expect(Object.fromEntries(r.kinds)).toEqual({ Clientes: 1, Projetos: 1, Fornecedor: 1, Outros: 1 })
+ const marcos = w.page('Marcos Lima')!
+ expect(marcos.file).toBe('pages/Clientes/Marcos Lima.md')
+ expect(marcos.links).toEqual(['Reforma do 302', 'Construtora Alpha'])
+ // the link in the project's properties counts as a link back
+ expect(marcos.backlinks).toEqual(['Reforma do 302'])
+ expect(w.page('Prazos')!.backlinks).toEqual(['Reforma do 302'])
+ expect(w.search('parceira')[0]!.title).toBe('Construtora Alpha')
+ expect(w.history('Marcos Lima')[0]).toMatchObject({ by: 'import', action: 'create' })
+ expect(readFileSync(join(v, 'Clientes/Marcos Lima.md'), 'utf8')).toBe(before)
+ // again: what's already here is left alone
+ expect(w.importVault(v, 'Ana')).toMatchObject({ pages: 0, skipped: expect.arrayContaining(['Clientes/Marcos Lima.md']) })
+ })
+
+ it('an edit keeps the frontmatter it had and the folder the note is in', () => {
+ const w = fresh()
+ w.importVault(vault(), 'Ana')
+ const p = w.page('Marcos Lima')!
+ w.save({ title: 'Marcos Lima', body: p.body + '\n## Contato\n- (41) 99999-0000', kind: p.kind, expectedHash: p.hash, by: 'me', byName: 'Ana' })
+ const text = readFileSync(join(w.dir, 'pages/Clientes/Marcos Lima.md'), 'utf8')
+ expect(text).toMatch(/^---\ntags:\n {2}- cliente\n {2}- reforma\naliases:\n {2}- Marcos\n---\n/)
+ expect(text).not.toContain('tipo:')
+ expect(text).toContain('## Contato')
+ // renamed: still in its folder
+ w.save({ title: 'Marcos A. Lima', rename: 'Marcos Lima', body: w.page('Marcos Lima')!.body, by: 'me', byName: 'Ana' })
+ expect(w.page('Marcos A. Lima')!.file).toBe('pages/Clientes/Marcos A. Lima.md')
+ })
+
+ it('a vault can also be the wiki itself, in place', () => {
+ const v = vault()
+ const w = new Wiki({ dir: v, indexPath: join(mkdtempSync(join(tmpdir(), 'idx-')), 'wiki.db') })
+ w.init(false)
+ expect(w.count()).toBe(4)
+ expect(w.page('Reforma do 302')!.file).toBe('Projetos/Reforma do 302.md')
+ })
+
+ it('refuses a folder with no notes, or the wiki itself', () => {
+ const w = fresh()
+ expect(() => w.importVault(mkdtempSync(join(tmpdir(), 'vazio-')), 'Ana')).toThrow('.md')
+ expect(() => w.importVault(w.dir, 'Ana')).toThrow()
+ })
+})
diff --git a/test/wiki-review.test.ts b/test/wiki-review.test.ts
new file mode 100644
index 0000000..970b37c
--- /dev/null
+++ b/test/wiki-review.test.ts
@@ -0,0 +1,102 @@
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, it } from 'vitest'
+import type { Settings } from '../src/shared/types'
+import { Wiki } from '../src/core/wiki'
+import { lint, parseReview, WikiReviewer } from '../src/core/wiki-review'
+
+function wiki(): Wiki {
+ const root = mkdtempSync(join(tmpdir(), 'tucano-wiki-'))
+ const w = new Wiki({ dir: join(root, 'wiki'), indexPath: join(root, 'wiki.db') })
+ w.init(false)
+ const save = (title: string, body: string, kind = 'Projeto'): void => void w.save({ title, body, kind, by: 'me', byName: 'Ana' })
+ save('Marcos Lima', 'Cliente da [[Reforma do apto 302]]. Indicado pela Construtora Alpha.', 'Pessoa')
+ save('Reforma do apto 302', 'Do [[Marcos Lima]], com a Construtora Alpha.\n\n## Situação\nAguardando resposta.\n\nVer [[Orçamento antigo]].')
+ save('Valor do m² de projeto', 'R$ 180 por m². Vale pra obras da Construtora Alpha.', 'Decisão')
+ save('Viagem a Morretes', 'Ana Ribeiro e a família, em dezembro.', 'Assunto')
+ return w
+}
+
+describe('a review of the wiki', () => {
+ it('finds broken links, names with no page and pages nothing links to', () => {
+ const found = lint(wiki(), 'Ana Ribeiro')
+ expect(found.find((f) => f.kind === 'broken')).toMatchObject({ name: 'Orçamento antigo', pages: ['Reforma do apto 302'] })
+ expect(found.find((f) => f.kind === 'missing')).toMatchObject({ name: 'Construtora Alpha' })
+ expect(found.find((f) => f.kind === 'missing')!.pages).toHaveLength(3)
+ expect(found.filter((f) => f.kind === 'orphan').map((f) => [...f.pages].sort())).toEqual([['Valor do m² de projeto', 'Viagem a Morretes']])
+ // the owner's own name isn't a missing page
+ expect(found.some((f) => f.name?.includes('Ana'))).toBe(false)
+ })
+
+ it("keeps the model's findings whose fix fits the pages", () => {
+ const w = wiki()
+ const out = parseReview(
+ JSON.stringify({
+ achados: [
+ { tipo: 'desatualizada', paginas: ['Reforma do apto 302'], explicacao: 'A [[Reforma do apto 302]] diz que espera resposta.', mudancas: [{ op: 'replace', pagina: 'Reforma do apto 302', secao: 'raiz', old: 'Aguardando resposta.', new: 'Fechada.' }] },
+ { tipo: 'contradição', paginas: ['Marcos Lima'], explicacao: 'Trecho que não está na página.', mudancas: [{ op: 'replace', pagina: 'Marcos Lima', old: 'não existe', new: 'x' }] },
+ { tipo: 'outra coisa', paginas: [], explicacao: 'ignorado' }
+ ]
+ }),
+ w
+ )
+ expect(out).toHaveLength(2)
+ expect(out[0]).toMatchObject({ kind: 'stale', ops: [{ op: 'replace', old: 'Aguardando resposta.' }], reason: 'A Reforma do apto 302 diz que espera resposta.' })
+ expect(out[0]!.ops![0]!.section).toBeUndefined()
+ // the swap with a passage that isn't there is dropped; the finding stays, to be read
+ expect(out[1]).toMatchObject({ kind: 'contradiction' })
+ expect(out[1]!.ops).toBeUndefined()
+ })
+
+ it('leaves everything waiting, and what was left alone or refused is not said again', async () => {
+ const w = wiki()
+ const answer = { achados: [{ tipo: 'desatualizada', paginas: ['Reforma do apto 302'], explicacao: 'Espera resposta, mas fechou.', mudancas: [{ op: 'replace', pagina: 'Reforma do apto 302', old: 'Aguardando resposta.', new: 'Fechada.' }] }] }
+ const prompts: string[] = []
+ const r = new WikiReviewer({ wiki: w, settings: () => ({ workspaceName: 'Ana Ribeiro' }) as Settings, llm: async (_s, p) => (prompts.push(p), JSON.stringify(answer)) })
+ await r.review()
+ const st = r.status()
+ expect(st.at).toBeGreaterThan(0)
+ const stale = st.findings.find((f) => f.kind === 'stale')!
+ expect(stale.change).toMatchObject({ state: 'pending', by: 'review' })
+ expect(w.page('Reforma do apto 302')!.body).toContain('Aguardando resposta.')
+ expect(prompts[0]).toContain('### [[Reforma do apto 302]]')
+
+ // refuse the fix, leave a broken link alone: the next review doesn't bring them back
+ w.refuseChange(stale.change!.id)
+ w.dismissFinding(st.findings.find((f) => f.kind === 'broken')!.id)
+ w.save({ title: 'Reforma do apto 302', body: w.page('Reforma do apto 302')!.body + '\n\nObra em janeiro.', by: 'me', byName: 'Ana' })
+ await r.review()
+ const again = r.status().findings
+ expect(again.some((f) => f.kind === 'stale' || f.kind === 'broken')).toBe(false)
+ expect(again.some((f) => f.kind === 'missing')).toBe(true)
+ // only what changed since the last review (and the pages around it) goes to the model
+ expect(prompts[1]).toContain('Obra em janeiro')
+ expect(prompts[1]).not.toContain('Viagem a Morretes')
+ })
+
+ it('an approved fix closes the finding; nothing changed means no model call', async () => {
+ const w = wiki()
+ let calls = 0
+ const r = new WikiReviewer({ wiki: w, settings: () => ({ wikiReview: 'weekly' }) as Settings, llm: async () => (calls++, JSON.stringify({ achados: [{ tipo: 'desatualizada', paginas: ['Reforma do apto 302'], explicacao: 'Velha.', mudancas: [{ op: 'replace', pagina: 'Reforma do apto 302', old: 'Aguardando resposta.', new: 'Fechada.' }] }] })) })
+ expect(r.due()).toBe(true)
+ await r.review()
+ expect(r.due()).toBe(false)
+ const f = r.status().findings.find((x) => x.change)!
+ w.applyChange(f.change!.id, 'Ana')
+ expect(w.page('Reforma do apto 302')!.body).toContain('Fechada.')
+ expect(r.status().findings.some((x) => x.id === f.id)).toBe(false)
+ await r.review() // only the fix changed a page
+ await r.review() // nothing changed
+ expect(calls).toBe(2)
+ })
+
+ it('a model that fails keeps the mark, so the next review reads those pages again', async () => {
+ const w = wiki()
+ const r = new WikiReviewer({ wiki: w, settings: () => ({}) as Settings, llm: async () => { throw new Error('sem modelo') } })
+ await r.review()
+ expect(r.status()).toMatchObject({ error: 'sem modelo' })
+ expect(r.status().at).toBeUndefined()
+ expect(r.status().findings.some((f) => f.kind === 'broken')).toBe(true)
+ })
+})
diff --git a/test/wiki.test.ts b/test/wiki.test.ts
new file mode 100644
index 0000000..4473413
--- /dev/null
+++ b/test/wiki.test.ts
@@ -0,0 +1,106 @@
+import { existsSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { describe, expect, it } from 'vitest'
+import { fileOf, linksIn, parsePage, summaryOf, Wiki, WikiConflict, wikiCall } from '../src/core/wiki'
+import { wikiAccess } from '../src/shared/types'
+
+const fresh = (): Wiki => {
+ const root = mkdtempSync(join(tmpdir(), 'tucano-wiki-'))
+ const w = new Wiki({ dir: join(root, 'wiki'), indexPath: join(root, 'wiki.db') })
+ w.init(false)
+ return w
+}
+const by = { by: 'me', byName: 'Ana' }
+
+describe('the wiki folder', () => {
+ it('starts with the schema, the log and the index, as Obsidian opens them', () => {
+ const w = fresh()
+ for (const f of ['esquema.md', 'registro.md', 'índice.md', 'pages']) expect(existsSync(join(w.dir, f))).toBe(true)
+ expect(w.schema()).toContain('Tipos de página')
+ })
+
+ it('keeps a page as a Markdown file with frontmatter, and lists it in the index and the log', () => {
+ const w = fresh()
+ const p = w.save({ title: 'Marcos Lima', kind: 'Pessoa', body: 'Cliente da reforma do apto 302.\n\nQuer começar em janeiro.', ...by })
+ const text = readFileSync(join(w.dir, 'pages', 'Marcos Lima.md'), 'utf8')
+ expect(parsePage(text).meta).toMatchObject({ tipo: 'Pessoa' })
+ expect(parsePage(text).body).toContain('Quer começar em janeiro.')
+ expect(p).toMatchObject({ title: 'Marcos Lima', kind: 'Pessoa', summary: 'Cliente da reforma do apto 302.', updatedBy: 'me' })
+ expect(w.indexText()).toContain('- [[Marcos Lima]]: Cliente da reforma do apto 302.')
+ expect(w.log()[0]).toContain('**Ana** criou [[Marcos Lima]]')
+ })
+
+ it('finds pages by words, with or without accents', () => {
+ const w = fresh()
+ w.save({ title: 'Reforma do apto 302', kind: 'Projeto', body: 'Orçamento aprovado: R$ 12.960, em 3 vezes.', ...by })
+ w.save({ title: 'Viagem a Morretes', kind: 'Projeto', body: 'Trem pela Serra do Mar.', ...by })
+ expect(w.search('orcamento').map((h) => h.title)).toEqual(['Reforma do apto 302'])
+ expect(w.search('ORÇAMENTO aprovado')[0]!.snippet).toContain('**')
+ expect(w.search('morretes')[0]!.title).toBe('Viagem a Morretes')
+ expect(w.search('nada disso')).toEqual([])
+ })
+
+ it('knows what links to a page, and which links have no page yet', () => {
+ const w = fresh()
+ w.save({ title: 'Marcos Lima', kind: 'Pessoa', body: 'Cliente.', ...by })
+ w.save({ title: 'Reforma do apto 302', kind: 'Projeto', body: 'De [[Marcos Lima]], com a [[Construtora Alpha]]. `[[não é link]]`', ...by })
+ expect(w.page('marcos lima')!.backlinks).toEqual(['Reforma do apto 302'])
+ expect(w.page('Reforma do apto 302')!.missing).toEqual(['Construtora Alpha'])
+ })
+
+ it('refuses a save made on an older copy of the page', () => {
+ const w = fresh()
+ const p = w.save({ title: 'Marcos Lima', body: 'v1', ...by })
+ w.save({ title: 'Marcos Lima', body: 'v2', expectedHash: p.hash, ...by })
+ expect(() => w.save({ title: 'Marcos Lima', body: 'v3', expectedHash: p.hash, ...by })).toThrow(WikiConflict)
+ expect(w.page('Marcos Lima')!.body).toContain('v2')
+ })
+
+ it('picks up a page changed outside Tucano, and keeps it in the history', () => {
+ const w = fresh()
+ w.save({ title: 'Marcos Lima', body: 'Cliente.', ...by })
+ writeFileSync(join(w.dir, 'pages', 'Marcos Lima.md'), '---\ntipo: Pessoa\n---\n\nCliente desde março.\n')
+ writeFileSync(join(w.dir, 'pages', 'Nova.md'), 'Escrita no Obsidian.\n')
+ expect(w.scan()).toBe(true)
+ expect(w.page('Marcos Lima')!.body).toContain('desde março')
+ expect(w.history('Marcos Lima')[0]).toMatchObject({ by: 'outside', action: 'edit' })
+ expect(w.search('obsidian')[0]!.title).toBe('Nova')
+ expect(w.scan()).toBe(false) // nothing new the second time
+ })
+
+ it('renames a page, deletes it, and brings it back from its history', () => {
+ const w = fresh()
+ const p = w.save({ title: 'Marcos', body: 'Cliente.', ...by })
+ w.save({ title: 'Marcos Lima', body: 'Cliente.', rename: 'Marcos', expectedHash: p.hash, ...by })
+ expect(w.list().map((x) => x.title)).toEqual(['Marcos Lima'])
+ w.remove('Marcos Lima', 'me', 'Ana')
+ expect(w.page('Marcos Lima')).toBeUndefined()
+ const del = w.history('Marcos Lima').find((v) => v.action === 'delete')!
+ expect(w.restore(del.id, 'me', 'Ana').body).toContain('Cliente.')
+ })
+})
+
+describe('the agents and the wiki', () => {
+ it('reads the index, searches and opens a page, and says when it is not there', () => {
+ const w = fresh()
+ w.save({ title: 'Marcos Lima', kind: 'Pessoa', body: 'Quer começar a reforma em janeiro.', ...by })
+ expect(wikiCall(w, 'wiki_indice', {}).text).toContain('[[Marcos Lima]]')
+ expect(wikiCall(w, 'wiki_buscar', { busca: 'reforma janeiro' }).text).toContain('- [[Marcos Lima]] (Pessoa)')
+ expect(wikiCall(w, 'wiki_ler', { pagina: '[[Marcos Lima]]' }).text).toContain('Quer começar a reforma em janeiro.')
+ expect(wikiCall(w, 'wiki_ler', { pagina: 'Ninguém' }).error).toBe(true)
+ expect(wikiCall(w, 'wiki_buscar', { busca: 'pizza' }).text).toContain('não invente')
+ })
+
+ it('every agent reads the wiki unless told otherwise; the Tuca does not', () => {
+ expect(wikiAccess({})).toBe('read')
+ expect(wikiAccess({ wiki: 'none' })).toBe('none')
+ expect(wikiAccess({ kind: 'tuca' })).toBe('none')
+ })
+
+ it('parses the bits a page is made of', () => {
+ expect(linksIn('[[A]] e [[B|bê]] e [[C#seção]] ```[[D]]```')).toEqual(['A', 'B', 'C'])
+ expect(summaryOf('# Título\n\n- **Cliente** de [[Marcos Lima|Marcos]].')).toBe('Cliente de Marcos.')
+ expect(fileOf('a/b: c?')).toBe('a-b- c-.md')
+ })
+})