@tenonai/yew 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +273 -0
  2. package/LICENSE +21 -0
  3. package/README.md +64 -2
  4. package/THIRD-PARTY-NOTICES.md +122 -0
  5. package/bin/yew.js +9 -0
  6. package/dist/cli/app.js +211 -0
  7. package/dist/cli/export.js +57 -0
  8. package/dist/cli/io.js +65 -0
  9. package/dist/cli/key.js +113 -0
  10. package/dist/cli/main.js +58 -0
  11. package/dist/cli/mcp.js +76 -0
  12. package/dist/cli/remote.js +116 -0
  13. package/dist/cli/run.js +72 -0
  14. package/dist/cli/schedule.js +123 -0
  15. package/dist/cli/send.js +127 -0
  16. package/dist/cli/serve.js +301 -0
  17. package/dist/cli/service.js +268 -0
  18. package/dist/cli/system.js +44 -0
  19. package/dist/remote/access.js +107 -0
  20. package/dist/remote/connector.js +278 -0
  21. package/dist/remote/identity.js +71 -0
  22. package/dist/remote/noise.js +287 -0
  23. package/dist/remote/protocol.js +51 -0
  24. package/dist/remote/push.js +37 -0
  25. package/dist/server/agent/compaction.js +242 -0
  26. package/dist/server/agent/context.js +120 -0
  27. package/dist/server/agent/held.js +48 -0
  28. package/dist/server/agent/helper.js +122 -0
  29. package/dist/server/agent/mailroom.js +510 -0
  30. package/dist/server/agent/prompt.js +268 -0
  31. package/dist/server/agent/runner.js +1159 -0
  32. package/dist/server/artifacts.js +216 -0
  33. package/dist/server/budget.js +88 -0
  34. package/dist/server/data-export.js +105 -0
  35. package/dist/server/data-usage.js +144 -0
  36. package/dist/server/db/database.js +49 -0
  37. package/dist/server/db/migrations.js +343 -0
  38. package/dist/server/errors.js +16 -0
  39. package/dist/server/events.js +17 -0
  40. package/dist/server/export.js +378 -0
  41. package/dist/server/folder-picker.js +32 -0
  42. package/dist/server/from-jig.js +98 -0
  43. package/dist/server/http/agents.js +78 -0
  44. package/dist/server/http/api.js +465 -0
  45. package/dist/server/http/app.js +111 -0
  46. package/dist/server/http/artifacts.js +53 -0
  47. package/dist/server/http/data.js +54 -0
  48. package/dist/server/http/devices.js +47 -0
  49. package/dist/server/http/events.js +134 -0
  50. package/dist/server/http/idempotency.js +53 -0
  51. package/dist/server/http/input.js +106 -0
  52. package/dist/server/http/mail.js +52 -0
  53. package/dist/server/http/mcp.js +134 -0
  54. package/dist/server/http/notes.js +91 -0
  55. package/dist/server/http/problem.js +55 -0
  56. package/dist/server/http/providers.js +131 -0
  57. package/dist/server/http/schedules.js +58 -0
  58. package/dist/server/http/search.js +42 -0
  59. package/dist/server/http/security.js +168 -0
  60. package/dist/server/http/skills.js +53 -0
  61. package/dist/server/http/system.js +26 -0
  62. package/dist/server/ids.js +30 -0
  63. package/dist/server/keys.js +70 -0
  64. package/dist/server/mail/envelope.js +152 -0
  65. package/dist/server/mail/post.js +603 -0
  66. package/dist/server/mail/store.js +279 -0
  67. package/dist/server/manage.js +601 -0
  68. package/dist/server/mcp-builtin.js +180 -0
  69. package/dist/server/mcp-config.js +305 -0
  70. package/dist/server/mcp-oauth.js +448 -0
  71. package/dist/server/mcp.js +668 -0
  72. package/dist/server/model/gateway.js +410 -0
  73. package/dist/server/paths.js +43 -0
  74. package/dist/server/permissions/engine.js +249 -0
  75. package/dist/server/permissions/paths.js +93 -0
  76. package/dist/server/permissions/shell.js +635 -0
  77. package/dist/server/push.js +345 -0
  78. package/dist/server/reveal.js +36 -0
  79. package/dist/server/runtime.js +17 -0
  80. package/dist/server/schedules.js +356 -0
  81. package/dist/server/settings.js +77 -0
  82. package/dist/server/skills.js +263 -0
  83. package/dist/server/store.js +1077 -0
  84. package/dist/server/tools/files.js +318 -0
  85. package/dist/server/tools/html.js +221 -0
  86. package/dist/server/tools/jobs.js +38 -0
  87. package/dist/server/tools/mail.js +680 -0
  88. package/dist/server/tools/match.js +81 -0
  89. package/dist/server/tools/misc.js +253 -0
  90. package/dist/server/tools/process.js +128 -0
  91. package/dist/server/tools/read-state.js +40 -0
  92. package/dist/server/tools/registry.js +43 -0
  93. package/dist/server/tools/search.js +175 -0
  94. package/dist/server/tools/shell.js +124 -0
  95. package/dist/server/tools/types.js +43 -0
  96. package/dist/server/tools/web-search.js +198 -0
  97. package/dist/server/tools/web.js +240 -0
  98. package/dist/shared/cron.js +105 -0
  99. package/dist/shared/mcp-presets.js +170 -0
  100. package/dist/shared/messages.js +45 -0
  101. package/dist/shared/policy.js +42 -0
  102. package/dist/shared/types.js +34 -0
  103. package/dist/shared/version.js +8 -0
  104. package/mcp-builtin/package-lock.json +3398 -0
  105. package/mcp-builtin/package.json +14 -0
  106. package/mcp-builtin/presets/gitee/package-lock.json +105 -0
  107. package/mcp-builtin/presets/gitee/package.json +10 -0
  108. package/mcp-builtin/presets/notion/package-lock.json +2243 -0
  109. package/mcp-builtin/presets/notion/package.json +10 -0
  110. package/mcp-builtin/presets/sentry/package-lock.json +28 -0
  111. package/mcp-builtin/presets/sentry/package.json +10 -0
  112. package/package.json +75 -5
  113. package/web/dist/THIRD-PARTY-NOTICES.txt +1944 -0
  114. package/web/dist/assets/index-BtK_SzpF.css +1 -0
  115. package/web/dist/assets/index-C0rnUFI-.js +68 -0
  116. package/web/dist/icons/app-icon.png +0 -0
  117. package/web/dist/icons/apple-touch-icon.png +0 -0
  118. package/web/dist/icons/favicon-16.png +0 -0
  119. package/web/dist/icons/favicon-32.png +0 -0
  120. package/web/dist/icons/favicon-64.png +0 -0
  121. package/web/dist/icons/tenon-mark.svg +1 -0
  122. package/web/dist/icons/yew-mark.svg +1 -0
  123. package/web/dist/index.html +18 -0
  124. package/web/dist/mascot/gift.webp +0 -0
  125. package/web/dist/mascot/greeting.webp +0 -0
  126. package/web/dist/mascot/happy.webp +0 -0
  127. package/web/dist/mascot/lost.webp +0 -0
  128. package/web/dist/mascot/shush.webp +0 -0
  129. package/web/dist/mascot/sleepy.webp +0 -0
  130. package/web/dist/mascot/sorry.webp +0 -0
  131. package/web/dist/mascot/thinking.webp +0 -0
  132. package/web/dist/mascot/waking.webp +0 -0
  133. package/web/dist/mascot/writing.webp +0 -0
@@ -0,0 +1,356 @@
1
+ import { CronError, nextRun, parseCron } from "../shared/cron.js";
2
+ import { conflict, invalid, notFound } from "./errors.js";
3
+ import { newId } from "./ids.js";
4
+ import { BODY_MAX, SUMMARY_MAX } from "./mail/post.js";
5
+ function toSchedule(row) {
6
+ return {
7
+ id: row.id,
8
+ name: row.name,
9
+ cron: row.cron,
10
+ sessionId: row.session_id,
11
+ message: row.message,
12
+ permissionMode: row.permission_mode,
13
+ catchUp: row.catch_up === 1,
14
+ enabled: row.enabled === 1,
15
+ nextRunAt: row.next_run_at,
16
+ lastRunAt: row.last_run_at,
17
+ lastStatus: row.last_status,
18
+ lastDetail: row.last_detail,
19
+ lastLetterId: row.last_letter_id,
20
+ createdAt: row.created_at,
21
+ updatedAt: row.updated_at,
22
+ };
23
+ }
24
+ const NAME_MAX = 60;
25
+ /** Checks a cron expression and that it names a time that exists; returns it tidied. */
26
+ export function checkCron(text, now = Date.now()) {
27
+ if (typeof text !== "string" || !text.trim())
28
+ throw invalid("Give the times as cron.", "cron");
29
+ const tidy = text.trim().split(/\s+/).join(" ");
30
+ try {
31
+ if (nextRun(parseCron(tidy), now) === null) {
32
+ throw invalid(`"${tidy}" names no date that exists, so it would never run.`, "cron");
33
+ }
34
+ }
35
+ catch (error) {
36
+ if (error instanceof CronError)
37
+ throw invalid(error.message, "cron");
38
+ throw error;
39
+ }
40
+ return tidy;
41
+ }
42
+ function nextAfter(cron, now) {
43
+ try {
44
+ return nextRun(parseCron(cron), now);
45
+ }
46
+ catch {
47
+ return null;
48
+ }
49
+ }
50
+ /**
51
+ * Scheduled tasks in the database (M3 plan, section 9). Every change goes out as a global event after its
52
+ * transaction commits, so every open page sees it.
53
+ */
54
+ export class ScheduleBook {
55
+ #store;
56
+ #listeners = new Set();
57
+ constructor(store) {
58
+ this.#store = store;
59
+ }
60
+ /** Called after any change, such as a new time to wake up for. */
61
+ onChange(listener) {
62
+ this.#listeners.add(listener);
63
+ return () => this.#listeners.delete(listener);
64
+ }
65
+ list() {
66
+ const rows = this.#store.db
67
+ .prepare("SELECT * FROM schedules ORDER BY name COLLATE NOCASE, id")
68
+ .all();
69
+ return rows.map(toSchedule);
70
+ }
71
+ get(id) {
72
+ const row = this.#store.db.prepare("SELECT * FROM schedules WHERE id = ?").get(id);
73
+ if (!row)
74
+ throw notFound("Scheduled task", id);
75
+ return toSchedule(row);
76
+ }
77
+ /** A task by id or by name (names are unique, whatever the case). */
78
+ find(ref) {
79
+ const row = this.#store.db.prepare("SELECT * FROM schedules WHERE id = ?").get(ref);
80
+ return row ? toSchedule(row) : this.#named(ref);
81
+ }
82
+ #named(name) {
83
+ const row = this.#store.db
84
+ .prepare("SELECT * FROM schedules WHERE name = ? COLLATE NOCASE")
85
+ .get(name.trim());
86
+ return row ? toSchedule(row) : null;
87
+ }
88
+ /** Checks the fields; missing ones come from `current`, or the defaults for a new task. */
89
+ values(fields, current, now = Date.now()) {
90
+ const name = fields.name === undefined ? current?.name : fields.name.trim();
91
+ if (!name)
92
+ throw invalid("A scheduled task needs a name.", "name");
93
+ if ([...name].length > NAME_MAX) {
94
+ throw invalid(`The name can be at most ${NAME_MAX} characters.`, "name");
95
+ }
96
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control characters is the point
97
+ if (/[\u0000-\u001f\u007f]/.test(name)) {
98
+ throw invalid("The name cannot contain control characters.", "name");
99
+ }
100
+ const other = this.#named(name);
101
+ if (other && other.id !== current?.id) {
102
+ throw conflict(`There is already a scheduled task called "${other.name}".`, {
103
+ field: "name",
104
+ });
105
+ }
106
+ const cron = fields.cron === undefined ? current?.cron : checkCron(fields.cron, now);
107
+ if (!cron)
108
+ throw invalid("Give the times as cron.", "cron");
109
+ const sessionId = fields.session === undefined ? current?.sessionId : this.#target(fields.session).id;
110
+ if (!sessionId)
111
+ throw invalid("Choose the session the letter goes to.", "session");
112
+ const message = fields.message === undefined ? current?.message : fields.message.trim();
113
+ if (!message)
114
+ throw invalid("Write the letter the task sends.", "message");
115
+ if ([...message].length > BODY_MAX) {
116
+ throw invalid(`The letter can be at most ${BODY_MAX} characters.`, "message");
117
+ }
118
+ return {
119
+ name,
120
+ cron,
121
+ sessionId,
122
+ message,
123
+ permissionMode: fields.permissionMode === undefined
124
+ ? (current?.permissionMode ?? null)
125
+ : fields.permissionMode,
126
+ catchUp: fields.catchUp ?? current?.catchUp ?? true,
127
+ enabled: fields.enabled ?? current?.enabled ?? true,
128
+ };
129
+ }
130
+ /** The session a task writes to: a standing session that is not archived. */
131
+ #target(ref) {
132
+ let session;
133
+ try {
134
+ session = this.#store.getSession(ref);
135
+ }
136
+ catch {
137
+ session = this.#store.findSessionByName(ref);
138
+ }
139
+ if (!session)
140
+ throw invalid(`There is no session "${ref}".`, "session");
141
+ if (session.kind !== "standing") {
142
+ throw invalid(`"${session.name}" is a task session; a scheduled task writes to a standing session.`, "session");
143
+ }
144
+ if (session.archivedAt !== null) {
145
+ throw invalid(`"${session.name}" is archived; restore it first.`, "session");
146
+ }
147
+ return session;
148
+ }
149
+ create(fields, now = Date.now()) {
150
+ const values = this.values(fields, null, now);
151
+ const id = newId();
152
+ this.#store.tx(() => {
153
+ this.#store.db
154
+ .prepare(`INSERT INTO schedules (id, name, cron, session_id, message, permission_mode, catch_up, enabled,
155
+ next_run_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
156
+ .run(id, values.name, values.cron, values.sessionId, values.message, values.permissionMode, values.catchUp ? 1 : 0, values.enabled ? 1 : 0, values.enabled ? nextAfter(values.cron, now) : null, now, now);
157
+ this.#publish();
158
+ });
159
+ return this.get(id);
160
+ }
161
+ update(id, fields, now = Date.now()) {
162
+ const current = this.get(id);
163
+ const values = this.values(fields, current, now);
164
+ // New times, or turned back on: the next run counts from now, not from a time already past.
165
+ const next = values.cron !== current.cron || values.enabled !== current.enabled
166
+ ? values.enabled
167
+ ? nextAfter(values.cron, now)
168
+ : null
169
+ : current.nextRunAt;
170
+ this.#store.tx(() => {
171
+ this.#store.db
172
+ .prepare(`UPDATE schedules SET name = ?, cron = ?, session_id = ?, message = ?, permission_mode = ?,
173
+ catch_up = ?, enabled = ?, next_run_at = ?, updated_at = ? WHERE id = ?`)
174
+ .run(values.name, values.cron, values.sessionId, values.message, values.permissionMode, values.catchUp ? 1 : 0, values.enabled ? 1 : 0, next, now, id);
175
+ this.#publish();
176
+ });
177
+ return this.get(id);
178
+ }
179
+ delete(id) {
180
+ this.get(id);
181
+ this.#store.tx(() => {
182
+ this.#store.db.prepare("DELETE FROM schedules WHERE id = ?").run(id);
183
+ this.#publish();
184
+ });
185
+ }
186
+ /** Enabled tasks whose next run is due. */
187
+ due(now) {
188
+ const rows = this.#store.db
189
+ .prepare("SELECT * FROM schedules WHERE enabled = 1 AND next_run_at IS NOT NULL AND next_run_at <= ? ORDER BY next_run_at, id")
190
+ .all(now);
191
+ return rows.map(toSchedule);
192
+ }
193
+ /** When the next task is due, if any is on. */
194
+ soonest() {
195
+ const row = this.#store.db
196
+ .prepare("SELECT MIN(next_run_at) AS at FROM schedules WHERE enabled = 1")
197
+ .get();
198
+ return row.at;
199
+ }
200
+ setNext(id, next) {
201
+ this.#store.db.prepare("UPDATE schedules SET next_run_at = ? WHERE id = ?").run(next, id);
202
+ this.#publish();
203
+ }
204
+ /** A run started: its letter is on its way. */
205
+ started(id, letterId, at) {
206
+ this.#store.db
207
+ .prepare("UPDATE schedules SET last_run_at = ?, last_status = 'running', last_detail = NULL, last_letter_id = ? WHERE id = ?")
208
+ .run(at, letterId, id);
209
+ this.#publish();
210
+ }
211
+ /** A run was skipped; the letter of a run still going stays the latest. */
212
+ skipped(id, reason, at) {
213
+ this.#store.db
214
+ .prepare("UPDATE schedules SET last_run_at = ?, last_status = 'skipped', last_detail = ? WHERE id = ?")
215
+ .run(at, reason, id);
216
+ this.#publish();
217
+ }
218
+ /**
219
+ * The turn that read a run's letter ended, or the letter was dropped; a later run may have started
220
+ * meanwhile, and then this one is no longer the latest.
221
+ */
222
+ finished(letter, status, detail) {
223
+ if (!letter.scheduleId)
224
+ return;
225
+ const result = this.#store.db
226
+ .prepare("UPDATE schedules SET last_run_at = ?, last_status = ?, last_detail = ? WHERE id = ? AND last_letter_id = ?")
227
+ .run(letter.createdAt, status, detail, letter.scheduleId, letter.id);
228
+ if (Number(result.changes) > 0)
229
+ this.#publish();
230
+ }
231
+ /** Archived sessions were deleted for good, and their tasks with them. */
232
+ refresh() {
233
+ this.#publish();
234
+ }
235
+ #publish() {
236
+ this.#store.publish({ type: "schedules", schedules: this.list() });
237
+ for (const listener of this.#listeners)
238
+ listener();
239
+ }
240
+ }
241
+ /** How late a run may start and still be on time; later, it was missed. */
242
+ const GRACE_MS = 2 * 60_000;
243
+ /** The longest the scheduler sleeps, so it notices a computer that woke up. */
244
+ const TICK_MS = 30_000;
245
+ const clip = (text, max) => [...text].length > max ? `${[...text].slice(0, max - 1).join("")}…` : text;
246
+ const OPEN = new Set(["queued", "held", "delivered"]);
247
+ /**
248
+ * Runs scheduled tasks on time (blueprint 6.5): a run is a letter to the task's session in the task's
249
+ * name, which the session reads in a turn of its own. Runs missed while Yew was not running or the
250
+ * computer slept run once afterwards or are skipped, as the task says; a run whose last one is not
251
+ * finished is skipped. The service keeps time; `yew schedule run` uses the same `run`.
252
+ */
253
+ export class Scheduler {
254
+ book;
255
+ #store;
256
+ #post;
257
+ #log;
258
+ #timer = null;
259
+ #stopChange = null;
260
+ constructor(store, post, book, log) {
261
+ this.#store = store;
262
+ this.#post = post;
263
+ this.book = book;
264
+ this.#log = log;
265
+ }
266
+ /** Sends the task's letter now, unless the session is archived or the last run is still going. */
267
+ run(id, now = Date.now()) {
268
+ const schedule = this.book.get(id);
269
+ let session = null;
270
+ try {
271
+ session = this.#store.getSession(schedule.sessionId);
272
+ }
273
+ catch {
274
+ session = null;
275
+ }
276
+ if (!session || session.archivedAt !== null) {
277
+ this.book.skipped(id, "archived", now);
278
+ return { skipped: "archived" };
279
+ }
280
+ if (schedule.lastLetterId && this.#open(schedule.lastLetterId)) {
281
+ this.book.skipped(id, "busy", now);
282
+ return { skipped: "busy" };
283
+ }
284
+ // A run stands in for the person: a full quota of letters again and a new chain, as when they write.
285
+ this.#store.resetLettersSent(session.id);
286
+ this.#post.resetChain(session.id);
287
+ const [first = "", ...rest] = schedule.message.split("\n");
288
+ const line = first.trim();
289
+ const summary = clip(line, SUMMARY_MAX);
290
+ const body = summary === line ? rest.join("\n").trim() : schedule.message;
291
+ const letter = this.#post.send({ kind: "schedule", schedule }, { to: session.id, kind: "request", summary, body });
292
+ this.book.started(id, letter.id, now);
293
+ return { letter };
294
+ }
295
+ /** Runs, or skips, every task that is due; each one's next run counts from now. */
296
+ tick(now = Date.now()) {
297
+ for (const schedule of this.book.due(now)) {
298
+ const due = schedule.nextRunAt;
299
+ this.book.setNext(schedule.id, nextAfter(schedule.cron, now));
300
+ if (now - due > GRACE_MS && !schedule.catchUp) {
301
+ this.book.skipped(schedule.id, "missed", due);
302
+ continue;
303
+ }
304
+ try {
305
+ this.run(schedule.id, now);
306
+ }
307
+ catch (error) {
308
+ this.#log(`scheduled task ${schedule.name}: ${error.message}`);
309
+ }
310
+ }
311
+ }
312
+ /** Keeps time until stop(): wakes for the next run, and at least every half minute. */
313
+ start() {
314
+ this.#stopChange = this.book.onChange(() => this.#arm());
315
+ this.#loop();
316
+ }
317
+ stop() {
318
+ if (this.#timer)
319
+ clearTimeout(this.#timer);
320
+ this.#timer = null;
321
+ this.#stopChange?.();
322
+ this.#stopChange = null;
323
+ }
324
+ #loop() {
325
+ try {
326
+ this.tick();
327
+ }
328
+ catch (error) {
329
+ this.#log(`scheduled tasks: ${error.message}`);
330
+ }
331
+ this.#arm();
332
+ }
333
+ #arm() {
334
+ if (!this.#stopChange)
335
+ return;
336
+ if (this.#timer)
337
+ clearTimeout(this.#timer);
338
+ const soonest = this.book.soonest();
339
+ const wait = soonest === null ? TICK_MS : Math.min(TICK_MS, Math.max(50, soonest - Date.now() + 50));
340
+ this.#timer = setTimeout(() => this.#loop(), wait);
341
+ }
342
+ #open(letterId) {
343
+ try {
344
+ return OPEN.has(this.#post.mail.getLetter(letterId).status);
345
+ }
346
+ catch {
347
+ return false;
348
+ }
349
+ }
350
+ }
351
+ /** The run of a task was refused because it still runs, for the HTTP layer and the command line. */
352
+ export function skippedError(reason, name) {
353
+ return reason === "busy"
354
+ ? conflict(`The last run of "${name}" is not finished yet.`, undefined, "schedule-busy")
355
+ : conflict(`The session of "${name}" is archived.`, undefined, "session-archived");
356
+ }
@@ -0,0 +1,77 @@
1
+ import { existsSync, realpathSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, dirname, isAbsolute, join } from "node:path";
4
+ import { DEFAULT_RELAY_URL } from "../shared/types.js";
5
+ import { invalid } from "./errors.js";
6
+ /** Which kinds of events notify the phone (blueprint 6.10, item 34). All on unless turned off. */
7
+ export const NOTIFY_KINDS = ["waiting", "error", "task", "budget"];
8
+ export const SETTING_DEFAULTS = {
9
+ defaultModel: {
10
+ provider: "deepseek",
11
+ model: "deepseek-v4-pro",
12
+ thinking: "medium",
13
+ },
14
+ theme: "system",
15
+ language: "system",
16
+ workspaces: [],
17
+ /** The main conversation (blueprint section 5). */
18
+ mainSessionId: null,
19
+ /** A Markdown file each decision is added to (blueprint 6.4, item 14). */
20
+ decisionLog: null,
21
+ /** Phones reach this Mac through the relay (blueprint 6.7, M3 plan section 6). */
22
+ remote: { enabled: false, relayUrl: DEFAULT_RELAY_URL },
23
+ /** The most all sessions together may spend in a day, in US dollars (M3 plan, section 10). */
24
+ dailyBudget: null,
25
+ /** Folders of notes sessions may read, such as ~/memory (M4 plan, section 4). */
26
+ memoryDirs: [],
27
+ /** The permission mode new sessions start with (blueprint 6.10, item 32). */
28
+ defaultPermissionMode: "auto",
29
+ /** The saved workspace the interface preselects for a new session; null for none. */
30
+ defaultWorkspaceId: null,
31
+ notify: { waiting: true, error: true, task: true, budget: true },
32
+ /** Skills switched off in the settings, each by its folder's real path (blueprint 6.10, item 35). */
33
+ disabledSkills: [],
34
+ };
35
+ export function readSettings(store) {
36
+ const workspaces = store.getSetting("workspaces", SETTING_DEFAULTS.workspaces);
37
+ const defaultWorkspaceId = store.getSetting("defaultWorkspaceId", SETTING_DEFAULTS.defaultWorkspaceId);
38
+ return {
39
+ defaultModel: store.getSetting("defaultModel", SETTING_DEFAULTS.defaultModel),
40
+ theme: store.getSetting("theme", SETTING_DEFAULTS.theme),
41
+ language: store.getSetting("language", SETTING_DEFAULTS.language),
42
+ workspaces,
43
+ mainSessionId: store.getSetting("mainSessionId", SETTING_DEFAULTS.mainSessionId),
44
+ decisionLog: store.getSetting("decisionLog", SETTING_DEFAULTS.decisionLog),
45
+ remote: { ...SETTING_DEFAULTS.remote, ...store.getSetting("remote", SETTING_DEFAULTS.remote) },
46
+ dailyBudget: store.getSetting("dailyBudget", SETTING_DEFAULTS.dailyBudget),
47
+ memoryDirs: store.getSetting("memoryDirs", SETTING_DEFAULTS.memoryDirs),
48
+ defaultPermissionMode: store.getSetting("defaultPermissionMode", SETTING_DEFAULTS.defaultPermissionMode),
49
+ // A workspace that was removed is no longer the default.
50
+ defaultWorkspaceId: workspaces.some((workspace) => workspace.id === defaultWorkspaceId)
51
+ ? defaultWorkspaceId
52
+ : null,
53
+ notify: { ...SETTING_DEFAULTS.notify, ...store.getSetting("notify", SETTING_DEFAULTS.notify) },
54
+ disabledSkills: store.getSetting("disabledSkills", SETTING_DEFAULTS.disabledSkills),
55
+ };
56
+ }
57
+ /** The decision log must be a Markdown file in an existing folder; `~` is expanded. */
58
+ export function resolveLogFile(path) {
59
+ const expanded = path === "~" || path.startsWith("~/") ? join(homedir(), path.slice(2)) : path;
60
+ if (!isAbsolute(expanded))
61
+ throw invalid("The decision log must be an absolute path.", "decisionLog");
62
+ if (!/\.(md|markdown)$/i.test(expanded)) {
63
+ throw invalid("The decision log must be a Markdown file (.md).", "decisionLog");
64
+ }
65
+ let folder;
66
+ try {
67
+ folder = realpathSync(dirname(expanded));
68
+ }
69
+ catch {
70
+ throw invalid(`The folder ${dirname(path)} does not exist.`, "decisionLog");
71
+ }
72
+ const file = join(folder, basename(expanded));
73
+ if (existsSync(file) && !statSync(file).isFile()) {
74
+ throw invalid(`${path} is not a file.`, "decisionLog");
75
+ }
76
+ return file;
77
+ }
@@ -0,0 +1,263 @@
1
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, isAbsolute, join } from "node:path";
4
+ import { invalid } from "./errors.js";
5
+ import { JIG_PROJECT_FOLDER } from "./from-jig.js";
6
+ import { errorResult, str, text } from "./tools/types.js";
7
+ const MAX_SKILLS = 200;
8
+ const MAX_SKILL_CHARS = 60_000;
9
+ const MAX_INDEX_BYTES = 8 * 1024;
10
+ /** `name` and `description` from the front matter; quoted values and folded lines are read plainly. */
11
+ export function frontMatter(source) {
12
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(source);
13
+ const fields = {};
14
+ if (!match)
15
+ return fields;
16
+ let key = null;
17
+ for (const line of match[1].split(/\r?\n/)) {
18
+ const pair = /^([A-Za-z][\w-]*):\s*(.*)$/.exec(line);
19
+ if (pair) {
20
+ key = pair[1];
21
+ const value = pair[2].trim();
22
+ // `>` and `|` start a block whose lines follow, indented.
23
+ fields[key] = /^[>|][+-]?$/.test(value) ? "" : value.replace(/^(["'])(.*)\1$/, "$2");
24
+ }
25
+ else if (key && /^\s+\S/.test(line)) {
26
+ fields[key] = `${fields[key]} ${line.trim()}`.trim();
27
+ }
28
+ else {
29
+ key = null;
30
+ }
31
+ }
32
+ return fields;
33
+ }
34
+ const realOr = (path) => {
35
+ try {
36
+ return realpathSync(path);
37
+ }
38
+ catch {
39
+ return path;
40
+ }
41
+ };
42
+ /** Everything in one skills folder: the skills, and the folders that are not usable with the reason. */
43
+ function scan(folder) {
44
+ const skills = [];
45
+ const broken = [];
46
+ let names;
47
+ try {
48
+ names = readdirSync(folder).sort();
49
+ }
50
+ catch {
51
+ return { skills, broken };
52
+ }
53
+ for (const entry of names) {
54
+ const dir = join(folder, entry);
55
+ const file = join(dir, "SKILL.md");
56
+ const fail = (reason) => broken.push({ name: entry, dir: realOr(dir), reason });
57
+ try {
58
+ // Loose files and hidden folders in a skills folder are not skills that went wrong.
59
+ if (!statSync(dir).isDirectory())
60
+ continue;
61
+ }
62
+ catch {
63
+ continue;
64
+ }
65
+ try {
66
+ if (!statSync(file).isFile()) {
67
+ if (!entry.startsWith("."))
68
+ fail("no-file");
69
+ continue;
70
+ }
71
+ }
72
+ catch (error) {
73
+ if (error.code !== "ENOENT")
74
+ fail("unreadable");
75
+ else if (!entry.startsWith("."))
76
+ fail("no-file");
77
+ continue;
78
+ }
79
+ try {
80
+ const fields = frontMatter(readFileSync(file, "utf8"));
81
+ const name = (fields.name || entry).trim();
82
+ if (!/^[\w.-]{1,64}$/.test(name)) {
83
+ fail("bad-name");
84
+ continue;
85
+ }
86
+ skills.push({
87
+ name,
88
+ description: (fields.description ?? "").replace(/\s+/g, " ").slice(0, 400),
89
+ dir: realpathSync(dir),
90
+ file: realpathSync(file),
91
+ });
92
+ }
93
+ catch {
94
+ fail("unreadable");
95
+ }
96
+ }
97
+ return { skills, broken };
98
+ }
99
+ /** The folders skills are looked for in, later ones winning over earlier ones with the same name. */
100
+ export function skillFolders(cwd, yewHome, userHome = homedir()) {
101
+ const folders = [join(yewHome, "skills")];
102
+ if (userHome)
103
+ folders.push(join(userHome, ".claude", "skills"));
104
+ if (cwd) {
105
+ for (const local of [".agents", ".claude", ".yew", JIG_PROJECT_FOLDER])
106
+ folders.push(join(cwd, local, "skills"));
107
+ }
108
+ return folders;
109
+ }
110
+ /**
111
+ * The skills a session working in `cwd` gets. `disabled` holds the folders of the skills switched off
112
+ * in the settings (a skill's identifier is its folder's real path); a skill that is off is left out
113
+ * before names are compared, so turning off a project's skill leaves the global one of the same name.
114
+ */
115
+ export function findSkills(cwd, yewHome, userHome = homedir(), disabled = []) {
116
+ const byName = new Map();
117
+ for (const folder of skillFolders(cwd, yewHome, userHome)) {
118
+ for (const skill of scan(folder).skills) {
119
+ if (!disabled.includes(skill.dir))
120
+ byName.set(skill.name, skill);
121
+ }
122
+ }
123
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)).slice(0, MAX_SKILLS);
124
+ }
125
+ /**
126
+ * Every skill the settings show: the global folders' and those of the saved workspaces, which are the
127
+ * folders a session working there is given. Within a source, usable skills come first, by name.
128
+ */
129
+ export function listSkills(workspaces, yewHome, userHome, disabled = []) {
130
+ const global = skillFolders(null, yewHome, userHome);
131
+ const groups = [
132
+ { source: { kind: "global" }, paths: global },
133
+ ...workspaces.map((workspace) => ({
134
+ source: { kind: "workspace", name: workspace.name, path: workspace.path },
135
+ paths: skillFolders(workspace.path, yewHome, userHome).slice(global.length),
136
+ })),
137
+ ];
138
+ const items = [];
139
+ const seen = new Set();
140
+ for (const { source, paths } of groups) {
141
+ const good = [];
142
+ const bad = [];
143
+ for (const folder of paths) {
144
+ const found = scan(folder);
145
+ for (const skill of found.skills) {
146
+ good.push({
147
+ id: skill.dir,
148
+ name: skill.name,
149
+ description: skill.description,
150
+ dir: skill.dir,
151
+ source,
152
+ disabled: disabled.includes(skill.dir),
153
+ problem: null,
154
+ });
155
+ }
156
+ for (const skill of found.broken) {
157
+ bad.push({
158
+ id: skill.dir,
159
+ name: skill.name,
160
+ description: "",
161
+ dir: skill.dir,
162
+ source,
163
+ disabled: false,
164
+ problem: skill.reason,
165
+ });
166
+ }
167
+ }
168
+ const byName = (a, b) => a.name.localeCompare(b.name);
169
+ for (const entry of [...good.sort(byName), ...bad.sort(byName)]) {
170
+ // One folder reached twice (a link, or a workspace inside another) is listed once.
171
+ if (seen.has(entry.id))
172
+ continue;
173
+ seen.add(entry.id);
174
+ items.push(entry);
175
+ }
176
+ }
177
+ return { items, folders: groups };
178
+ }
179
+ /** What the prompt says about skills: one line each. */
180
+ export function skillsNote(skills) {
181
+ return [
182
+ "Skills the person has set up. Each is a set of instructions for one kind of task. When a task matches one, call the skill tool with its name and follow what it says; scripts and reference files a skill mentions are in the folder the tool reports.",
183
+ ...skills.map((skill) => `- ${skill.name}${skill.description ? `: ${skill.description}` : ""}`),
184
+ ].join("\n");
185
+ }
186
+ /** A memory folder must exist; `~` is expanded and the real path is kept. */
187
+ export function resolveMemoryDir(path, userHome = homedir()) {
188
+ const expanded = path === "~" || path.startsWith("~/") ? join(userHome, path.slice(2)) : path;
189
+ if (!isAbsolute(expanded))
190
+ throw invalid("A memory folder must be an absolute path.", "memoryDirs");
191
+ let real;
192
+ try {
193
+ real = realpathSync(expanded);
194
+ }
195
+ catch {
196
+ throw invalid(`The folder ${path} does not exist.`, "memoryDirs");
197
+ }
198
+ if (!statSync(real).isDirectory())
199
+ throw invalid(`${path} is not a folder.`, "memoryDirs");
200
+ return real;
201
+ }
202
+ /** A memory folder's index: the first of these that exists, cut to a few kilobytes. */
203
+ export function memoryIndex(dir) {
204
+ for (const name of ["index.md", "MEMORY.md", "README.md"]) {
205
+ const path = join(dir, name);
206
+ if (!existsSync(path))
207
+ continue;
208
+ try {
209
+ const content = readFileSync(path, "utf8");
210
+ const bytes = Buffer.from(content);
211
+ return {
212
+ path,
213
+ content: bytes.length > MAX_INDEX_BYTES
214
+ ? `${bytes.subarray(0, MAX_INDEX_BYTES).toString("utf8")}\n[Cut: read the file for the rest.]`
215
+ : content,
216
+ };
217
+ }
218
+ catch {
219
+ return null;
220
+ }
221
+ }
222
+ return null;
223
+ }
224
+ export function memoryNote(dirs) {
225
+ return [
226
+ "Memory folders: notes the person keeps across sessions. Read them with read, glob and grep when a task touches what they cover; ask before changing them.",
227
+ ...dirs.map((dir) => `- ${dir}`),
228
+ ].join("\n");
229
+ }
230
+ /** Reads one skill in full. Offered when the session has any skill. */
231
+ export function skillTool(yewHome, userHome = homedir(),
232
+ /** The skills switched off in the settings, read each time so a change applies at once. */
233
+ disabled = () => []) {
234
+ return {
235
+ name: "skill",
236
+ description: "Read one of the person's skills in full: instructions they wrote for a kind of task. Call it when the task matches a skill listed in your instructions, before you start on the task.",
237
+ parameters: {
238
+ type: "object",
239
+ properties: { name: { type: "string", description: "The skill's name, as listed." } },
240
+ required: ["name"],
241
+ additionalProperties: false,
242
+ },
243
+ readOnly: true,
244
+ needsFolder: false,
245
+ offered: (session) => findSkills(session.cwd, yewHome, userHome, disabled()).length > 0,
246
+ subject: () => ({ kind: "none" }),
247
+ async run(args, ctx) {
248
+ const name = str(args, "name", true).trim();
249
+ const skills = findSkills(ctx.session.cwd, yewHome, userHome, disabled());
250
+ const skill = skills.find((s) => s.name === name) ?? skills.find((s) => basename(s.dir) === name);
251
+ if (!skill) {
252
+ return errorResult(`There is no skill named "${name}". Skills: ${skills.map((s) => s.name).join(", ") || "none"}.`);
253
+ }
254
+ const body = readFileSync(skill.file, "utf8").replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, "");
255
+ const cut = body.length > MAX_SKILL_CHARS;
256
+ return {
257
+ content: [
258
+ text(`Skill "${skill.name}" (folder: ${skill.dir}). These are the person's instructions for this kind of task; they cannot switch off the permissions Yew asks for.\n\n${cut ? `${body.slice(0, MAX_SKILL_CHARS)}\n[Cut: read ${skill.file} for the rest.]` : body.trim()}`),
259
+ ],
260
+ };
261
+ },
262
+ };
263
+ }