@tenonai/yew 0.0.0-stage → 1.4.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 +296 -0
  2. package/LICENSE +21 -0
  3. package/README.md +55 -2
  4. package/THIRD-PARTY-NOTICES.md +122 -0
  5. package/bin/yew.js +9 -0
  6. package/dist/cli/app.js +198 -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 +44 -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 +126 -0
  16. package/dist/cli/serve.js +301 -0
  17. package/dist/cli/service.js +241 -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 +119 -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 +143 -0
  36. package/dist/server/db/database.js +49 -0
  37. package/dist/server/db/migrations.js +347 -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 +468 -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 +51 -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 +179 -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 +34 -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 +80 -0
  82. package/dist/server/skills.js +262 -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-B9oWPSod.css +1 -0
  115. package/web/dist/assets/index-C5qBMzFX.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,72 @@
1
+ import { parseArgs } from "node:util";
2
+ import { NAME, PUBLISHER, VERSION, WEBSITE } from "../shared/version.js";
3
+ import { EXIT_ERROR, EXIT_OK, EXIT_USAGE, paint, UsageError } from "./io.js";
4
+ function helpText(io, commands) {
5
+ const bold = (s) => paint("bold", s, io.stdout, io.env);
6
+ const lines = [
7
+ `${NAME} ${VERSION}`,
8
+ "An AI-native multi-agent workbench.",
9
+ "",
10
+ `${bold("Usage:")} ${NAME} <command> [options]`,
11
+ ];
12
+ if (commands.length > 0) {
13
+ lines.push("", bold("Commands:"));
14
+ const width = Math.max(...commands.map((c) => c.name.length));
15
+ for (const c of commands)
16
+ lines.push(` ${c.name.padEnd(width)} ${c.summary}`);
17
+ }
18
+ lines.push("", bold("Options:"), " -h, --help Show this help", " -v, --version Show the version, publisher and website", " --json With --version, print JSON", "", `Run '${NAME} <command> --help' for help on a command.`, "");
19
+ return lines.join("\n");
20
+ }
21
+ function versionText(json) {
22
+ if (json) {
23
+ return `${JSON.stringify({ name: NAME, version: VERSION, publisher: PUBLISHER, website: WEBSITE })}\n`;
24
+ }
25
+ return `${NAME} ${VERSION}\n${PUBLISHER} · ${WEBSITE}\n`;
26
+ }
27
+ export async function run(argv, io, commands = []) {
28
+ const first = argv[0];
29
+ const command = first && !first.startsWith("-") ? commands.find((c) => c.name === first) : undefined;
30
+ try {
31
+ if (command)
32
+ return await command.run(argv.slice(1), io);
33
+ if (first && !first.startsWith("-")) {
34
+ throw new UsageError(`unknown command '${first}'`);
35
+ }
36
+ const { values } = parseArgs({
37
+ args: argv,
38
+ options: {
39
+ help: { type: "boolean", short: "h" },
40
+ version: { type: "boolean", short: "v" },
41
+ json: { type: "boolean" },
42
+ },
43
+ strict: true,
44
+ allowPositionals: false,
45
+ });
46
+ if (values.version) {
47
+ io.stdout.write(versionText(values.json === true));
48
+ return EXIT_OK;
49
+ }
50
+ if (values.json)
51
+ throw new UsageError("--json needs --version or a command");
52
+ io.stdout.write(helpText(io, commands));
53
+ return EXIT_OK;
54
+ }
55
+ catch (error) {
56
+ return report(error, io);
57
+ }
58
+ }
59
+ function report(error, io) {
60
+ const prefix = paint("red", `${NAME}:`, io.stderr, io.env);
61
+ if (error instanceof UsageError || isParseArgsError(error)) {
62
+ io.stderr.write(`${prefix} ${error.message}\nRun '${NAME} --help' for usage.\n`);
63
+ return EXIT_USAGE;
64
+ }
65
+ const message = error instanceof Error ? error.message : String(error);
66
+ io.stderr.write(`${prefix} ${message}\n`);
67
+ return EXIT_ERROR;
68
+ }
69
+ function isParseArgsError(error) {
70
+ const code = error?.code;
71
+ return typeof code === "string" && code.startsWith("ERR_PARSE_ARGS_");
72
+ }
@@ -0,0 +1,123 @@
1
+ import { parseArgs } from "node:util";
2
+ import { EXIT_ERROR, EXIT_OK, UsageError } from "./io.js";
3
+ import { serviceRunning } from "./serve.js";
4
+ const HELP = `Usage: yew schedule <list|run> [options] [<task>]
5
+
6
+ Scheduled tasks send a standing session a letter at set times; the session's
7
+ last reply goes to the main conversation as the report. Set them up in Yew's
8
+ web interface, or ask the main conversation.
9
+
10
+ Commands:
11
+ list List the scheduled tasks with their next and last runs
12
+ run <task> Run a task now, by name or id; its next run stays as it was
13
+
14
+ Options:
15
+ --json Print as JSON
16
+ -h, --help Show this help
17
+ `;
18
+ const pad = (n) => String(n).padStart(2, "0");
19
+ function time(at) {
20
+ if (at === null)
21
+ return "-";
22
+ const date = new Date(at);
23
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
24
+ }
25
+ function lastRun(schedule) {
26
+ if (!schedule.lastStatus)
27
+ return "never run";
28
+ const detail = schedule.lastStatus === "skipped"
29
+ ? ` (${{ busy: "the last run was not finished", archived: "the session is archived", missed: "missed" }[schedule.lastDetail] ?? schedule.lastDetail})`
30
+ : "";
31
+ return `${schedule.lastStatus}${detail} ${time(schedule.lastRunAt)}`;
32
+ }
33
+ export function scheduleCommand() {
34
+ return {
35
+ name: "schedule",
36
+ summary: "List scheduled tasks, or run one now",
37
+ async run(args, io) {
38
+ const { values, positionals } = parseArgs({
39
+ args,
40
+ options: { json: { type: "boolean" }, help: { type: "boolean", short: "h" } },
41
+ allowPositionals: true,
42
+ strict: true,
43
+ });
44
+ if (values.help) {
45
+ io.stdout.write(HELP);
46
+ return EXIT_OK;
47
+ }
48
+ const [action, ref] = positionals;
49
+ if (action === "list" ? positionals.length !== 1 : action !== "run" || !ref) {
50
+ throw new UsageError(action === "run" && !ref
51
+ ? "yew schedule run needs a task's name or id"
52
+ : "yew schedule needs list or run");
53
+ }
54
+ if (positionals.length > 2)
55
+ throw new UsageError("too many arguments");
56
+ const { yewHome, dbPath } = await import("../server/paths.js");
57
+ const { openDatabase } = await import("../server/db/database.js");
58
+ const { EventBus } = await import("../server/events.js");
59
+ const { Store } = await import("../server/store.js");
60
+ const { PostOffice } = await import("../server/mail/post.js");
61
+ const { ScheduleBook, Scheduler } = await import("../server/schedules.js");
62
+ const home = yewHome(io.env);
63
+ const db = openDatabase(dbPath(home));
64
+ try {
65
+ const store = new Store(db, new EventBus());
66
+ const book = new ScheduleBook(store);
67
+ const sessionName = (id) => {
68
+ try {
69
+ return store.getSession(id).name;
70
+ }
71
+ catch {
72
+ return id;
73
+ }
74
+ };
75
+ if (action === "list") {
76
+ const schedules = book.list();
77
+ if (values.json) {
78
+ const items = schedules.map((schedule) => ({
79
+ ...schedule,
80
+ session: { id: schedule.sessionId, name: sessionName(schedule.sessionId) },
81
+ }));
82
+ io.stdout.write(`${JSON.stringify(items)}\n`);
83
+ return EXIT_OK;
84
+ }
85
+ if (schedules.length === 0) {
86
+ io.stdout.write("No scheduled tasks yet.\n");
87
+ return EXIT_OK;
88
+ }
89
+ for (const schedule of schedules) {
90
+ io.stdout.write(`${schedule.name} ${schedule.cron} to ${sessionName(schedule.sessionId)}${schedule.enabled ? "" : " (off)"}\n next: ${time(schedule.nextRunAt)} last: ${lastRun(schedule)}\n`);
91
+ }
92
+ return EXIT_OK;
93
+ }
94
+ const schedule = book.find(ref);
95
+ if (!schedule) {
96
+ io.stderr.write(`yew: there is no scheduled task with the name or id ${ref}\n`);
97
+ return EXIT_ERROR;
98
+ }
99
+ const scheduler = new Scheduler(store, new PostOffice(store), book, () => { });
100
+ const result = scheduler.run(schedule.id);
101
+ if ("skipped" in result) {
102
+ io.stderr.write(result.skipped === "busy"
103
+ ? `yew: the last run of ${schedule.name} is not finished yet\n`
104
+ : `yew: ${sessionName(schedule.sessionId)} is archived\n`);
105
+ return EXIT_ERROR;
106
+ }
107
+ if (values.json) {
108
+ io.stdout.write(`${JSON.stringify({ schedule: book.get(schedule.id), letter: result.letter })}\n`);
109
+ }
110
+ else {
111
+ io.stdout.write(`Sent ${schedule.name} to ${sessionName(schedule.sessionId)} (letter ${result.letter.id}).\n`);
112
+ }
113
+ if (!serviceRunning(home)) {
114
+ io.stderr.write("Yew is not running; the letter is delivered when it starts.\n");
115
+ }
116
+ return EXIT_OK;
117
+ }
118
+ finally {
119
+ db.close();
120
+ }
121
+ },
122
+ };
123
+ }
@@ -0,0 +1,126 @@
1
+ import { parseArgs } from "node:util";
2
+ import { EXIT_ERROR, EXIT_OK, UsageError } from "./io.js";
3
+ import { serviceRunning } from "./serve.js";
4
+ const HELP = `Usage: yew send [options] <session> <message>
5
+
6
+ Send a letter to a session, from a script, CI or a git hook. <session> is the
7
+ session's id or name. Use - as the message to read it from standard input; the
8
+ first line is the summary. The letter is marked as coming from the command
9
+ line, not from you; run inside a session's shell, it comes from that session
10
+ and counts against its letters. A running Yew delivers it within a few
11
+ seconds; otherwise it waits until Yew starts.
12
+
13
+ Options:
14
+ -k, --kind <kind> notice, request or report (default: notice)
15
+ --json Print the letter as JSON
16
+ -h, --help Show this help
17
+ `;
18
+ const KINDS = ["notice", "request", "report"];
19
+ export function sendCommand() {
20
+ return {
21
+ name: "send",
22
+ summary: "Send a letter to a session",
23
+ async run(args, io) {
24
+ const { values, positionals } = parseArgs({
25
+ args,
26
+ options: {
27
+ kind: { type: "string", short: "k" },
28
+ json: { type: "boolean" },
29
+ help: { type: "boolean", short: "h" },
30
+ },
31
+ allowPositionals: true,
32
+ strict: true,
33
+ });
34
+ if (values.help) {
35
+ io.stdout.write(HELP);
36
+ return EXIT_OK;
37
+ }
38
+ if (positionals.length !== 2) {
39
+ throw new UsageError("yew send needs a session and a message");
40
+ }
41
+ const kind = (values.kind ?? "notice");
42
+ if (!KINDS.includes(kind)) {
43
+ throw new UsageError("--kind must be notice, request or report");
44
+ }
45
+ const [target, raw] = positionals;
46
+ let message = raw;
47
+ if (raw === "-") {
48
+ message = "";
49
+ for await (const chunk of io.stdin)
50
+ message += chunk.toString();
51
+ }
52
+ message = message.trim();
53
+ if (!message)
54
+ throw new UsageError("the message is empty");
55
+ const { yewHome, dbPath } = await import("../server/paths.js");
56
+ const { openDatabase } = await import("../server/db/database.js");
57
+ const { EventBus } = await import("../server/events.js");
58
+ const { Store } = await import("../server/store.js");
59
+ const { PostOffice, SUMMARY_MAX, reasonText } = await import("../server/mail/post.js");
60
+ const { YewError } = await import("../server/errors.js");
61
+ const home = yewHome(io.env);
62
+ const db = openDatabase(dbPath(home));
63
+ try {
64
+ const store = new Store(db, new EventBus());
65
+ let session = store.findSessionByName(target);
66
+ if (!session) {
67
+ try {
68
+ session = store.getSession(target);
69
+ }
70
+ catch {
71
+ io.stderr.write(`yew: there is no session with the name or id ${target}\n`);
72
+ return EXIT_ERROR;
73
+ }
74
+ }
75
+ // Inside a session's shell the letter is that session's, with its quota, limits and hold.
76
+ const fromId = io.env.YEW_SESSION?.trim();
77
+ let sender = { kind: "cli" };
78
+ if (fromId) {
79
+ try {
80
+ sender = { kind: "session", session: store.getSession(fromId) };
81
+ }
82
+ catch {
83
+ io.stderr.write(`yew: YEW_SESSION names no session (${fromId})\n`);
84
+ return EXIT_ERROR;
85
+ }
86
+ }
87
+ const [first = "", ...rest] = message.split("\n");
88
+ const line = first.trim();
89
+ const summary = [...line].length > SUMMARY_MAX
90
+ ? `${[...line].slice(0, SUMMARY_MAX - 1).join("")}…`
91
+ : line;
92
+ const body = summary === line ? rest.join("\n").trim() : message;
93
+ let letter;
94
+ try {
95
+ letter = new PostOffice(store).send(sender, { to: session.id, kind, summary, body });
96
+ }
97
+ catch (error) {
98
+ if (!(error instanceof YewError))
99
+ throw error;
100
+ io.stderr.write(`yew: ${error.message}\n`);
101
+ return EXIT_ERROR;
102
+ }
103
+ if (letter.status === "refused" || letter.status === "dropped") {
104
+ io.stderr.write(`yew: ${session.name} did not take the letter: ${reasonText(letter.statusReason)}\n`);
105
+ return EXIT_ERROR;
106
+ }
107
+ if (values.json) {
108
+ io.stdout.write(`${JSON.stringify({ id: letter.id, to: { id: session.id, name: session.name }, kind, status: letter.status })}\n`);
109
+ }
110
+ else {
111
+ io.stdout.write(`Sent letter ${letter.id} to ${session.name}.\n`);
112
+ }
113
+ if (letter.status === "held") {
114
+ io.stderr.write("It is held until you release it in Yew's approval center.\n");
115
+ }
116
+ else if (!serviceRunning(home)) {
117
+ io.stderr.write("Yew is not running; the letter is delivered when it starts.\n");
118
+ }
119
+ return EXIT_OK;
120
+ }
121
+ finally {
122
+ db.close();
123
+ }
124
+ },
125
+ };
126
+ }
@@ -0,0 +1,301 @@
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { parseArgs } from "node:util";
6
+ import { VERSION } from "../shared/version.js";
7
+ import { EXIT_ERROR, EXIT_OK, UsageError } from "./io.js";
8
+ export const DEFAULT_PORT = 4777;
9
+ const EVENT_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
10
+ /** How often the service looks for letters from `yew send`, which writes to the database directly. */
11
+ const LETTER_SWEEP_MS = 2000;
12
+ /** How often the service checks whether phone access was turned on or off. */
13
+ const REMOTE_SYNC_MS = 5000;
14
+ const SERVE_HELP = `Usage: yew serve [options]
15
+
16
+ Start Yew's local service. It listens on 127.0.0.1 only, keeps running while
17
+ the browser is closed, and prints a one-time link to open the web interface.
18
+
19
+ Options:
20
+ -p, --port <n> Port to listen on (default ${DEFAULT_PORT})
21
+ --open Open the link in the default browser
22
+ -h, --help Show this help
23
+ `;
24
+ const OPEN_HELP = `Usage: yew open [options]
25
+
26
+ Open the web interface of the running Yew service with a new one-time link.
27
+
28
+ Options:
29
+ --print Print the link instead of opening a browser
30
+ -h, --help Show this help
31
+ `;
32
+ const serveFile = (home) => join(home, "serve.json");
33
+ /** The short commit of a source checkout; null when Yew does not run from a git checkout. */
34
+ function shortCommit() {
35
+ try {
36
+ return execFileSync("git", ["rev-parse", "--short", "HEAD"], {
37
+ cwd: fileURLToPath(new URL("../..", import.meta.url)),
38
+ encoding: "utf8",
39
+ stdio: ["ignore", "pipe", "ignore"],
40
+ }).trim();
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ }
46
+ export function openBrowser(url) {
47
+ const [command, args] = process.platform === "darwin"
48
+ ? ["open", [url]]
49
+ : process.platform === "win32"
50
+ ? ["cmd", ["/c", "start", "", url]]
51
+ : ["xdg-open", [url]];
52
+ spawn(command, args, { detached: true, stdio: "ignore" }).unref();
53
+ }
54
+ export function serveCommand() {
55
+ return {
56
+ name: "serve",
57
+ summary: "Start Yew's local service",
58
+ async run(args, io) {
59
+ const { values } = parseArgs({
60
+ args,
61
+ options: {
62
+ port: { type: "string", short: "p" },
63
+ open: { type: "boolean" },
64
+ help: { type: "boolean", short: "h" },
65
+ },
66
+ strict: true,
67
+ });
68
+ if (values.help) {
69
+ io.stdout.write(SERVE_HELP);
70
+ return EXIT_OK;
71
+ }
72
+ const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
73
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
74
+ throw new UsageError("--port must be a whole number from 1 to 65535");
75
+ }
76
+ const { openRuntime } = await import("../server/runtime.js");
77
+ const { serve } = await import("@hono/node-server");
78
+ const { Agents } = await import("../server/agent/runner.js");
79
+ const { PermissionEngine } = await import("../server/permissions/engine.js");
80
+ const { createApp } = await import("../server/http/app.js");
81
+ const { issueLoginToken } = await import("../server/http/security.js");
82
+ const { MailStore } = await import("../server/mail/store.js");
83
+ const { Scheduler } = await import("../server/schedules.js");
84
+ const runtime = openRuntime({ env: io.env });
85
+ const { store, bus, gateway, home } = runtime;
86
+ const stuck = store.recoverAfterRestart();
87
+ if (stuck.length > 0) {
88
+ io.stderr.write(`${stuck.length} session(s) were working when Yew last stopped. They are marked for review; nothing was redone.\n`);
89
+ }
90
+ store.pruneEvents(Date.now() - EVENT_RETENTION_MS);
91
+ // Answers handed to a waiting call whose result was never stored come back as letters.
92
+ new MailStore(store).requeueHandedOff();
93
+ const log = (line) => io.stderr.write(`${line}\n`);
94
+ // Tools beyond the built-in ones: web search when a search service has a key (M4 plan).
95
+ const { ALL_TOOLS } = await import("../server/tools/registry.js");
96
+ const { SearchAccess, webSearchTool } = await import("../server/tools/web-search.js");
97
+ const search = new SearchAccess(runtime.keys);
98
+ // MCP servers from mcp.json in the data folder; their tools ask before the first use.
99
+ const { McpHub } = await import("../server/mcp.js");
100
+ const { McpAuth } = await import("../server/mcp-oauth.js");
101
+ const { systemKeys } = await import("../server/keys.js");
102
+ const { builtinMcp, mcpInstaller } = await import("../server/mcp-builtin.js");
103
+ const mcp = new McpHub({
104
+ yewHome: home,
105
+ version: VERSION,
106
+ log,
107
+ builtin: builtinMcp(home, io.env),
108
+ prepare: mcpInstaller({ yewHome: home, env: io.env, log }),
109
+ // Sign-ins to MCP servers: tokens in the keychain; the browser comes back to this port.
110
+ auth: new McpAuth({
111
+ keys: systemKeys("mcp", io.env),
112
+ redirectUri: `http://127.0.0.1:${port}/oauth/callback`,
113
+ version: VERSION,
114
+ }),
115
+ });
116
+ const { skillTool } = await import("../server/skills.js");
117
+ const { homedir } = await import("node:os");
118
+ const { ArtifactStore, saveArtifactTool } = await import("../server/artifacts.js");
119
+ const artifacts = new ArtifactStore(store, home);
120
+ const extraTools = [
121
+ webSearchTool(search, { version: VERSION }),
122
+ skillTool(home, homedir(), () => store.getSetting("disabledSkills", [])),
123
+ saveArtifactTool(artifacts),
124
+ ];
125
+ const agents = new Agents({
126
+ store,
127
+ gateway,
128
+ permissions: new PermissionEngine(home),
129
+ home,
130
+ version: VERSION,
131
+ log,
132
+ tools: () => [...ALL_TOOLS, ...extraTools, ...mcp.tools()],
133
+ userHome: homedir(),
134
+ });
135
+ const { RemoteAccess } = await import("../remote/access.js");
136
+ // A paired phone's requests run in-process against the same app, as that device.
137
+ let handle = null;
138
+ const remote = new RemoteAccess(store, systemKeys("remote"), {
139
+ version: VERSION,
140
+ log,
141
+ handle: async (request, device) => {
142
+ if (!handle)
143
+ throw new Error("Yew is still starting.");
144
+ return handle(request, device.id);
145
+ },
146
+ });
147
+ // Notifications to paired phones, sealed for each; the relay passes them to Apple's service.
148
+ const { Notifier } = await import("../server/push.js");
149
+ const { NoteStreams } = await import("../server/http/notes.js");
150
+ const notes = new NoteStreams(store);
151
+ const notifier = new Notifier({
152
+ store,
153
+ mail: agents.post.mail,
154
+ bus,
155
+ schedules: () => agents.schedules.list(),
156
+ // iPhones through Apple's service; phones that keep their own connection directly.
157
+ send: (note, mode, id) => remote.push(note, mode, id) + notes.send(note),
158
+ });
159
+ const { systemControl } = await import("./system.js");
160
+ // Scheduled tasks run from the service, whether or not a page is open (blueprint 6.5).
161
+ const scheduler = new Scheduler(store, agents.post, agents.schedules, log);
162
+ const app = createApp({
163
+ store,
164
+ gateway,
165
+ agents,
166
+ bus,
167
+ log,
168
+ security: { port },
169
+ webRoot: fileURLToPath(new URL("../../web/dist", import.meta.url)),
170
+ build: shortCommit(),
171
+ remote,
172
+ scheduler,
173
+ onPresence: () => notifier.seen(),
174
+ notes,
175
+ artifacts,
176
+ mcp: { home, hub: mcp },
177
+ skills: { home, userHome: homedir() },
178
+ data: { home },
179
+ search,
180
+ system: systemControl({ home, env: io.env }),
181
+ });
182
+ handle = async (request, device) => app.fetch(request, { device });
183
+ const server = serve({ fetch: app.fetch, hostname: "127.0.0.1", port });
184
+ const started = await new Promise((resolve) => {
185
+ server.once("listening", () => resolve(true));
186
+ server.once("error", (error) => {
187
+ io.stderr.write(error.code === "EADDRINUSE"
188
+ ? `yew: port ${port} is in use. Is Yew already running? Try 'yew open', or pick another port with --port.\n`
189
+ : `yew: could not start: ${error.message}\n`);
190
+ resolve(false);
191
+ });
192
+ });
193
+ if (!started) {
194
+ runtime.close();
195
+ return EXIT_ERROR;
196
+ }
197
+ // Letters that were waiting when Yew stopped, and letters from `yew send`, start their sessions.
198
+ agents.wakeQueued();
199
+ const sweep = setInterval(() => agents.wakeQueued(), LETTER_SWEEP_MS);
200
+ // Runs missed while Yew was not running are run or skipped now, as each task says.
201
+ scheduler.start();
202
+ notifier.start();
203
+ // Phone access follows the settings, which `yew remote` may change while Yew runs.
204
+ const syncRemote = () => {
205
+ void remote.sync().catch((error) => log(`remote access: ${error.message}`));
206
+ // A search key saved with `yew key set` while Yew runs is picked up here.
207
+ void search.refresh().catch(() => { });
208
+ // A changed mcp.json is read again: new servers start, removed ones stop.
209
+ void mcp.refresh().catch((error) => log(`mcp: ${error.message}`));
210
+ };
211
+ syncRemote();
212
+ const remoteSweep = setInterval(syncRemote, REMOTE_SYNC_MS);
213
+ const info = { port, pid: process.pid, startedAt: Date.now() };
214
+ writeFileSync(serveFile(home), JSON.stringify(info), { mode: 0o600 });
215
+ const url = `http://127.0.0.1:${port}/#t=${issueLoginToken(store)}`;
216
+ io.stdout.write(`Yew ${VERSION} is running at http://127.0.0.1:${port}/\nSign in with this link (works once, within 10 minutes):\n${url}\nStop with Ctrl-C. For a new link later, run: yew open\n`);
217
+ if (values.open)
218
+ openBrowser(url);
219
+ return await new Promise((resolve) => {
220
+ const stop = () => {
221
+ io.stderr.write("Stopping Yew…\n");
222
+ clearInterval(sweep);
223
+ clearInterval(remoteSweep);
224
+ scheduler.stop();
225
+ notifier.stop();
226
+ mcp.stop();
227
+ remote.stop();
228
+ agents.shutdown();
229
+ server.close();
230
+ // Open event streams would keep the process alive; end them too.
231
+ if ("closeAllConnections" in server)
232
+ server.closeAllConnections();
233
+ rmSync(serveFile(home), { force: true });
234
+ runtime.close();
235
+ resolve(EXIT_OK);
236
+ };
237
+ process.once("SIGINT", stop);
238
+ process.once("SIGTERM", stop);
239
+ });
240
+ },
241
+ };
242
+ }
243
+ /** True when a Yew service is running for this data directory. */
244
+ export function serviceRunning(home) {
245
+ try {
246
+ const info = JSON.parse(readFileSync(serveFile(home), "utf8"));
247
+ process.kill(info.pid, 0);
248
+ return true;
249
+ }
250
+ catch {
251
+ return false;
252
+ }
253
+ }
254
+ export function openCommand() {
255
+ return {
256
+ name: "open",
257
+ summary: "Open the web interface with a new sign-in link",
258
+ async run(args, io) {
259
+ const { values } = parseArgs({
260
+ args,
261
+ options: { print: { type: "boolean" }, help: { type: "boolean", short: "h" } },
262
+ strict: true,
263
+ });
264
+ if (values.help) {
265
+ io.stdout.write(OPEN_HELP);
266
+ return EXIT_OK;
267
+ }
268
+ const { yewHome } = await import("../server/paths.js");
269
+ const home = yewHome(io.env);
270
+ let info;
271
+ try {
272
+ info = JSON.parse(readFileSync(serveFile(home), "utf8"));
273
+ process.kill(info.pid, 0);
274
+ }
275
+ catch {
276
+ io.stderr.write("yew: Yew is not running. Start it with: yew serve\n");
277
+ return EXIT_ERROR;
278
+ }
279
+ const { openDatabase } = await import("../server/db/database.js");
280
+ const { EventBus } = await import("../server/events.js");
281
+ const { Store } = await import("../server/store.js");
282
+ const { dbPath } = await import("../server/paths.js");
283
+ const { issueLoginToken } = await import("../server/http/security.js");
284
+ const db = openDatabase(dbPath(home));
285
+ try {
286
+ const url = `http://127.0.0.1:${info.port}/#t=${issueLoginToken(new Store(db, new EventBus()))}`;
287
+ if (values.print) {
288
+ io.stdout.write(`${url}\n`);
289
+ }
290
+ else {
291
+ openBrowser(url);
292
+ io.stdout.write(`Opened Yew in the browser (http://127.0.0.1:${info.port}/).\n`);
293
+ }
294
+ return EXIT_OK;
295
+ }
296
+ finally {
297
+ db.close();
298
+ }
299
+ },
300
+ };
301
+ }