@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.
- package/CHANGELOG.md +273 -0
- package/LICENSE +21 -0
- package/README.md +64 -2
- package/THIRD-PARTY-NOTICES.md +122 -0
- package/bin/yew.js +9 -0
- package/dist/cli/app.js +211 -0
- package/dist/cli/export.js +57 -0
- package/dist/cli/io.js +65 -0
- package/dist/cli/key.js +113 -0
- package/dist/cli/main.js +58 -0
- package/dist/cli/mcp.js +76 -0
- package/dist/cli/remote.js +116 -0
- package/dist/cli/run.js +72 -0
- package/dist/cli/schedule.js +123 -0
- package/dist/cli/send.js +127 -0
- package/dist/cli/serve.js +301 -0
- package/dist/cli/service.js +268 -0
- package/dist/cli/system.js +44 -0
- package/dist/remote/access.js +107 -0
- package/dist/remote/connector.js +278 -0
- package/dist/remote/identity.js +71 -0
- package/dist/remote/noise.js +287 -0
- package/dist/remote/protocol.js +51 -0
- package/dist/remote/push.js +37 -0
- package/dist/server/agent/compaction.js +242 -0
- package/dist/server/agent/context.js +120 -0
- package/dist/server/agent/held.js +48 -0
- package/dist/server/agent/helper.js +122 -0
- package/dist/server/agent/mailroom.js +510 -0
- package/dist/server/agent/prompt.js +268 -0
- package/dist/server/agent/runner.js +1159 -0
- package/dist/server/artifacts.js +216 -0
- package/dist/server/budget.js +88 -0
- package/dist/server/data-export.js +105 -0
- package/dist/server/data-usage.js +144 -0
- package/dist/server/db/database.js +49 -0
- package/dist/server/db/migrations.js +343 -0
- package/dist/server/errors.js +16 -0
- package/dist/server/events.js +17 -0
- package/dist/server/export.js +378 -0
- package/dist/server/folder-picker.js +32 -0
- package/dist/server/from-jig.js +98 -0
- package/dist/server/http/agents.js +78 -0
- package/dist/server/http/api.js +465 -0
- package/dist/server/http/app.js +111 -0
- package/dist/server/http/artifacts.js +53 -0
- package/dist/server/http/data.js +54 -0
- package/dist/server/http/devices.js +47 -0
- package/dist/server/http/events.js +134 -0
- package/dist/server/http/idempotency.js +53 -0
- package/dist/server/http/input.js +106 -0
- package/dist/server/http/mail.js +52 -0
- package/dist/server/http/mcp.js +134 -0
- package/dist/server/http/notes.js +91 -0
- package/dist/server/http/problem.js +55 -0
- package/dist/server/http/providers.js +131 -0
- package/dist/server/http/schedules.js +58 -0
- package/dist/server/http/search.js +42 -0
- package/dist/server/http/security.js +168 -0
- package/dist/server/http/skills.js +53 -0
- package/dist/server/http/system.js +26 -0
- package/dist/server/ids.js +30 -0
- package/dist/server/keys.js +70 -0
- package/dist/server/mail/envelope.js +152 -0
- package/dist/server/mail/post.js +603 -0
- package/dist/server/mail/store.js +279 -0
- package/dist/server/manage.js +601 -0
- package/dist/server/mcp-builtin.js +180 -0
- package/dist/server/mcp-config.js +305 -0
- package/dist/server/mcp-oauth.js +448 -0
- package/dist/server/mcp.js +668 -0
- package/dist/server/model/gateway.js +410 -0
- package/dist/server/paths.js +43 -0
- package/dist/server/permissions/engine.js +249 -0
- package/dist/server/permissions/paths.js +93 -0
- package/dist/server/permissions/shell.js +635 -0
- package/dist/server/push.js +345 -0
- package/dist/server/reveal.js +36 -0
- package/dist/server/runtime.js +17 -0
- package/dist/server/schedules.js +356 -0
- package/dist/server/settings.js +77 -0
- package/dist/server/skills.js +263 -0
- package/dist/server/store.js +1077 -0
- package/dist/server/tools/files.js +318 -0
- package/dist/server/tools/html.js +221 -0
- package/dist/server/tools/jobs.js +38 -0
- package/dist/server/tools/mail.js +680 -0
- package/dist/server/tools/match.js +81 -0
- package/dist/server/tools/misc.js +253 -0
- package/dist/server/tools/process.js +128 -0
- package/dist/server/tools/read-state.js +40 -0
- package/dist/server/tools/registry.js +43 -0
- package/dist/server/tools/search.js +175 -0
- package/dist/server/tools/shell.js +124 -0
- package/dist/server/tools/types.js +43 -0
- package/dist/server/tools/web-search.js +198 -0
- package/dist/server/tools/web.js +240 -0
- package/dist/shared/cron.js +105 -0
- package/dist/shared/mcp-presets.js +170 -0
- package/dist/shared/messages.js +45 -0
- package/dist/shared/policy.js +42 -0
- package/dist/shared/types.js +34 -0
- package/dist/shared/version.js +8 -0
- package/mcp-builtin/package-lock.json +3398 -0
- package/mcp-builtin/package.json +14 -0
- package/mcp-builtin/presets/gitee/package-lock.json +105 -0
- package/mcp-builtin/presets/gitee/package.json +10 -0
- package/mcp-builtin/presets/notion/package-lock.json +2243 -0
- package/mcp-builtin/presets/notion/package.json +10 -0
- package/mcp-builtin/presets/sentry/package-lock.json +28 -0
- package/mcp-builtin/presets/sentry/package.json +10 -0
- package/package.json +75 -5
- package/web/dist/THIRD-PARTY-NOTICES.txt +1944 -0
- package/web/dist/assets/index-BtK_SzpF.css +1 -0
- package/web/dist/assets/index-C0rnUFI-.js +68 -0
- package/web/dist/icons/app-icon.png +0 -0
- package/web/dist/icons/apple-touch-icon.png +0 -0
- package/web/dist/icons/favicon-16.png +0 -0
- package/web/dist/icons/favicon-32.png +0 -0
- package/web/dist/icons/favicon-64.png +0 -0
- package/web/dist/icons/tenon-mark.svg +1 -0
- package/web/dist/icons/yew-mark.svg +1 -0
- package/web/dist/index.html +18 -0
- package/web/dist/mascot/gift.webp +0 -0
- package/web/dist/mascot/greeting.webp +0 -0
- package/web/dist/mascot/happy.webp +0 -0
- package/web/dist/mascot/lost.webp +0 -0
- package/web/dist/mascot/shush.webp +0 -0
- package/web/dist/mascot/sleepy.webp +0 -0
- package/web/dist/mascot/sorry.webp +0 -0
- package/web/dist/mascot/thinking.webp +0 -0
- package/web/dist/mascot/waking.webp +0 -0
- package/web/dist/mascot/writing.webp +0 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { homedir, userInfo } from "node:os";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { parseArgs } from "node:util";
|
|
7
|
+
import { fromJigEnv, JIG_SERVICE_LABEL, JIG_SERVICE_UNIT } from "../server/from-jig.js";
|
|
8
|
+
import { EXIT_ERROR, EXIT_OK, UsageError } from "./io.js";
|
|
9
|
+
import { serviceRunning } from "./serve.js";
|
|
10
|
+
const HELP = `Usage: yew service <install|uninstall|status> [options]
|
|
11
|
+
|
|
12
|
+
Start Yew when you log in, so your phone and scheduled tasks can reach it
|
|
13
|
+
without a terminal open. On macOS this is a LaunchAgent for your user, on
|
|
14
|
+
Linux a systemd user unit. Yew is restarted if it exits with an error, and
|
|
15
|
+
its log goes to the logs folder in Yew's data directory. Nothing is changed
|
|
16
|
+
on your system until you run install.
|
|
17
|
+
|
|
18
|
+
Commands:
|
|
19
|
+
install Start Yew at login, and start it now
|
|
20
|
+
uninstall Stop starting Yew at login, and stop it now
|
|
21
|
+
status Show whether it is installed and running
|
|
22
|
+
|
|
23
|
+
Options:
|
|
24
|
+
--json Print as JSON
|
|
25
|
+
-h, --help Show this help
|
|
26
|
+
`;
|
|
27
|
+
export const SERVICE_LABEL = "cn.tenonai.apps.yew";
|
|
28
|
+
/** Jig's, Yew's earlier name (from-jig.ts): installing or removing Yew's takes it away. */
|
|
29
|
+
const JIG_LABEL = JIG_SERVICE_LABEL;
|
|
30
|
+
const JIG_UNIT = JIG_SERVICE_UNIT;
|
|
31
|
+
const UNIT = "yew.service";
|
|
32
|
+
export function realServiceHost() {
|
|
33
|
+
return {
|
|
34
|
+
platform: process.platform,
|
|
35
|
+
homeDir: homedir(),
|
|
36
|
+
uid: userInfo().uid,
|
|
37
|
+
node: process.execPath,
|
|
38
|
+
// The sources in a checkout, the compiled file in the published package.
|
|
39
|
+
entry: fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./main.ts" : "./main.js", import.meta.url)),
|
|
40
|
+
run: (command, args) => spawnSync(command, args, { stdio: "ignore" }).status,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
const xml = (text) => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
44
|
+
/** The LaunchAgent: starts `yew serve` at login and again after an exit with an error. */
|
|
45
|
+
export function launchAgent(host, env, log) {
|
|
46
|
+
const strings = (values) => values.map((value) => `\t\t<string>${xml(value)}</string>`).join("\n");
|
|
47
|
+
const vars = Object.entries(env)
|
|
48
|
+
.map(([key, value]) => `\t\t<key>${xml(key)}</key>\n\t\t<string>${xml(value)}</string>`)
|
|
49
|
+
.join("\n");
|
|
50
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
51
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
52
|
+
<plist version="1.0">
|
|
53
|
+
<dict>
|
|
54
|
+
<key>Label</key>
|
|
55
|
+
<string>${SERVICE_LABEL}</string>
|
|
56
|
+
<key>ProgramArguments</key>
|
|
57
|
+
<array>
|
|
58
|
+
${strings([host.node, host.entry, "serve"])}
|
|
59
|
+
</array>
|
|
60
|
+
<key>EnvironmentVariables</key>
|
|
61
|
+
<dict>
|
|
62
|
+
${vars}
|
|
63
|
+
</dict>
|
|
64
|
+
<key>RunAtLoad</key>
|
|
65
|
+
<true/>
|
|
66
|
+
<key>KeepAlive</key>
|
|
67
|
+
<dict>
|
|
68
|
+
<key>SuccessfulExit</key>
|
|
69
|
+
<false/>
|
|
70
|
+
</dict>
|
|
71
|
+
<key>ThrottleInterval</key>
|
|
72
|
+
<integer>10</integer>
|
|
73
|
+
<key>ProcessType</key>
|
|
74
|
+
<string>Background</string>
|
|
75
|
+
<key>StandardOutPath</key>
|
|
76
|
+
<string>${xml(log)}</string>
|
|
77
|
+
<key>StandardErrorPath</key>
|
|
78
|
+
<string>${xml(log)}</string>
|
|
79
|
+
</dict>
|
|
80
|
+
</plist>
|
|
81
|
+
`;
|
|
82
|
+
}
|
|
83
|
+
const quoted = (value) => `"${value.replace(/(["\\$`])/g, "\\$1").replace(/%/g, "%%")}"`;
|
|
84
|
+
/** The systemd user unit, with the same behavior as the LaunchAgent. */
|
|
85
|
+
export function systemdUnit(host, env, log) {
|
|
86
|
+
const vars = Object.entries(env)
|
|
87
|
+
.map(([key, value]) => `Environment=${quoted(`${key}=${value}`)}`)
|
|
88
|
+
.join("\n");
|
|
89
|
+
return `[Unit]
|
|
90
|
+
Description=Yew, an AI-native multi-agent workbench
|
|
91
|
+
|
|
92
|
+
[Service]
|
|
93
|
+
ExecStart=${quoted(host.node)} ${quoted(host.entry)} serve
|
|
94
|
+
${vars}
|
|
95
|
+
Restart=on-failure
|
|
96
|
+
RestartSec=10
|
|
97
|
+
StandardOutput=append:${log}
|
|
98
|
+
StandardError=append:${log}
|
|
99
|
+
|
|
100
|
+
[Install]
|
|
101
|
+
WantedBy=default.target
|
|
102
|
+
`;
|
|
103
|
+
}
|
|
104
|
+
/** Starting at login is done with launchd on macOS and systemd on Linux. */
|
|
105
|
+
export const serviceSupported = (host) => host.platform === "darwin" || host.platform === "linux";
|
|
106
|
+
export function serviceFile(host) {
|
|
107
|
+
if (host.platform === "darwin") {
|
|
108
|
+
return join(host.homeDir, "Library", "LaunchAgents", `${SERVICE_LABEL}.plist`);
|
|
109
|
+
}
|
|
110
|
+
if (host.platform === "linux")
|
|
111
|
+
return join(host.homeDir, ".config", "systemd", "user", UNIT);
|
|
112
|
+
throw new Error("yew service works on macOS and Linux.");
|
|
113
|
+
}
|
|
114
|
+
const target = (host) => `gui/${host.uid}/${SERVICE_LABEL}`;
|
|
115
|
+
/**
|
|
116
|
+
* Jig's login service, from before Jig was renamed Yew: stopped and removed when Yew's is installed
|
|
117
|
+
* or removed, so the two never both start.
|
|
118
|
+
*/
|
|
119
|
+
function removeJigService(host) {
|
|
120
|
+
if (host.platform === "darwin") {
|
|
121
|
+
const file = join(host.homeDir, "Library", "LaunchAgents", `${JIG_LABEL}.plist`);
|
|
122
|
+
if (!existsSync(file))
|
|
123
|
+
return;
|
|
124
|
+
host.run("launchctl", ["bootout", `gui/${host.uid}/${JIG_LABEL}`]);
|
|
125
|
+
rmSync(file, { force: true });
|
|
126
|
+
}
|
|
127
|
+
else if (host.platform === "linux") {
|
|
128
|
+
const file = join(host.homeDir, ".config", "systemd", "user", JIG_UNIT);
|
|
129
|
+
if (!existsSync(file))
|
|
130
|
+
return;
|
|
131
|
+
host.run("systemctl", ["--user", "disable", "--now", JIG_UNIT]);
|
|
132
|
+
rmSync(file, { force: true });
|
|
133
|
+
host.run("systemctl", ["--user", "daemon-reload"]);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
/** The service file is there and the system has it loaded (macOS) or enabled (Linux). */
|
|
137
|
+
export function serviceLoaded(host) {
|
|
138
|
+
return (existsSync(serviceFile(host)) &&
|
|
139
|
+
(host.platform === "darwin"
|
|
140
|
+
? host.run("launchctl", ["print", target(host)]) === 0
|
|
141
|
+
: host.run("systemctl", ["--user", "is-enabled", "--quiet", UNIT]) === 0));
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Whether Yew will be started at the next login. On macOS the file is enough: launchd loads what is
|
|
145
|
+
* in LaunchAgents when the person logs in. On Linux the unit has to be enabled.
|
|
146
|
+
*/
|
|
147
|
+
export function serviceAtLogin(host) {
|
|
148
|
+
if (!existsSync(serviceFile(host)))
|
|
149
|
+
return false;
|
|
150
|
+
return (host.platform === "darwin" ||
|
|
151
|
+
host.run("systemctl", ["--user", "is-enabled", "--quiet", UNIT]) === 0);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Writes the service file and registers it. With `start` (what `yew service install` does) the
|
|
155
|
+
* service is also started now; without it Yew starts at the next login and what runs now is left
|
|
156
|
+
* alone, which is what the settings need: they are served by the Yew that is running.
|
|
157
|
+
*/
|
|
158
|
+
export function installService(host, home, env, options) {
|
|
159
|
+
const file = serviceFile(host);
|
|
160
|
+
const mac = host.platform === "darwin";
|
|
161
|
+
const log = join(home, "logs", "serve.log");
|
|
162
|
+
removeJigService(host);
|
|
163
|
+
mkdirSync(join(home, "logs"), { recursive: true, mode: 0o700 });
|
|
164
|
+
// Shell commands the sessions run need your PATH; launchd and systemd start with a bare one.
|
|
165
|
+
const vars = { PATH: env.PATH ?? "/usr/bin:/bin" };
|
|
166
|
+
if (fromJigEnv(env, "HOME"))
|
|
167
|
+
vars.YEW_HOME = home;
|
|
168
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
169
|
+
writeFileSync(file, mac ? launchAgent(host, vars, log) : systemdUnit(host, vars, log), {
|
|
170
|
+
mode: 0o644,
|
|
171
|
+
});
|
|
172
|
+
let code = 0;
|
|
173
|
+
if (mac) {
|
|
174
|
+
if (options.start) {
|
|
175
|
+
// Loading it again picks up a new Node.js or Yew path after an update.
|
|
176
|
+
host.run("launchctl", ["bootout", target(host)]);
|
|
177
|
+
code = host.run("launchctl", ["bootstrap", `gui/${host.uid}`, file]);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
else {
|
|
181
|
+
host.run("systemctl", ["--user", "daemon-reload"]);
|
|
182
|
+
code = host.run("systemctl", ["--user", "enable", ...(options.start ? ["--now"] : []), UNIT]);
|
|
183
|
+
}
|
|
184
|
+
return { code, file, log };
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Removes the service file and its registration; returns whether the file was there. With `stop`
|
|
188
|
+
* (what `yew service uninstall` does) the running service is stopped too; without it the Yew that
|
|
189
|
+
* is running keeps running and is only not started at the next login.
|
|
190
|
+
*/
|
|
191
|
+
export function uninstallService(host, options) {
|
|
192
|
+
const file = serviceFile(host);
|
|
193
|
+
const mac = host.platform === "darwin";
|
|
194
|
+
const had = existsSync(file);
|
|
195
|
+
removeJigService(host);
|
|
196
|
+
if (mac) {
|
|
197
|
+
if (options.stop)
|
|
198
|
+
host.run("launchctl", ["bootout", target(host)]);
|
|
199
|
+
}
|
|
200
|
+
else if (had) {
|
|
201
|
+
host.run("systemctl", ["--user", "disable", ...(options.stop ? ["--now"] : []), UNIT]);
|
|
202
|
+
}
|
|
203
|
+
rmSync(file, { force: true });
|
|
204
|
+
if (!mac && had)
|
|
205
|
+
host.run("systemctl", ["--user", "daemon-reload"]);
|
|
206
|
+
return had;
|
|
207
|
+
}
|
|
208
|
+
export function serviceCommand(host = realServiceHost()) {
|
|
209
|
+
return {
|
|
210
|
+
name: "service",
|
|
211
|
+
summary: "Start Yew when you log in",
|
|
212
|
+
async run(args, io) {
|
|
213
|
+
const { values, positionals } = parseArgs({
|
|
214
|
+
args,
|
|
215
|
+
options: { json: { type: "boolean" }, help: { type: "boolean", short: "h" } },
|
|
216
|
+
allowPositionals: true,
|
|
217
|
+
strict: true,
|
|
218
|
+
});
|
|
219
|
+
if (values.help) {
|
|
220
|
+
io.stdout.write(HELP);
|
|
221
|
+
return EXIT_OK;
|
|
222
|
+
}
|
|
223
|
+
const action = positionals[0];
|
|
224
|
+
if (positionals.length !== 1 || !["install", "uninstall", "status"].includes(action ?? "")) {
|
|
225
|
+
throw new UsageError("yew service needs one of install, uninstall or status");
|
|
226
|
+
}
|
|
227
|
+
const { yewHome } = await import("../server/paths.js");
|
|
228
|
+
const home = yewHome(io.env);
|
|
229
|
+
const file = serviceFile(host);
|
|
230
|
+
const mac = host.platform === "darwin";
|
|
231
|
+
if (action === "status") {
|
|
232
|
+
const state = { installed: serviceLoaded(host), running: serviceRunning(home), file };
|
|
233
|
+
if (values.json)
|
|
234
|
+
io.stdout.write(`${JSON.stringify(state)}\n`);
|
|
235
|
+
else {
|
|
236
|
+
io.stdout.write(`Start at login: ${state.installed ? `on (${file})` : "off"}\nYew service: ${state.running ? "running" : "not running"}\n`);
|
|
237
|
+
}
|
|
238
|
+
return EXIT_OK;
|
|
239
|
+
}
|
|
240
|
+
if (action === "uninstall") {
|
|
241
|
+
const had = uninstallService(host, { stop: true });
|
|
242
|
+
if (values.json)
|
|
243
|
+
io.stdout.write(`${JSON.stringify({ installed: false, file })}\n`);
|
|
244
|
+
else {
|
|
245
|
+
io.stdout.write(had
|
|
246
|
+
? "Yew no longer starts at login, and was stopped.\n"
|
|
247
|
+
: "Yew was not set to start at login.\n");
|
|
248
|
+
}
|
|
249
|
+
return EXIT_OK;
|
|
250
|
+
}
|
|
251
|
+
if (!serviceLoaded(host) && serviceRunning(home)) {
|
|
252
|
+
io.stderr.write("yew: Yew is already running, started by hand. Stop that 'yew serve' first, then run this again.\n");
|
|
253
|
+
return EXIT_ERROR;
|
|
254
|
+
}
|
|
255
|
+
const { code, log } = installService(host, home, io.env, { start: true });
|
|
256
|
+
if (code !== 0) {
|
|
257
|
+
io.stderr.write(`yew: ${mac ? "launchctl" : "systemctl"} could not start the service (exit ${code ?? "none"}). The file is at ${file}.\n`);
|
|
258
|
+
return EXIT_ERROR;
|
|
259
|
+
}
|
|
260
|
+
if (values.json)
|
|
261
|
+
io.stdout.write(`${JSON.stringify({ installed: true, file, log })}\n`);
|
|
262
|
+
else {
|
|
263
|
+
io.stdout.write(`Yew now starts when you log in, and was started.\nLog: ${log}\nOpen the web interface with 'yew open'.\n`);
|
|
264
|
+
}
|
|
265
|
+
return EXIT_OK;
|
|
266
|
+
},
|
|
267
|
+
};
|
|
268
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { conflict } from "../server/errors.js";
|
|
2
|
+
import { appInstalled, appPath, installApp, realAppHost, uninstallApp, } from "./app.js";
|
|
3
|
+
import { installService, realServiceHost, serviceAtLogin, serviceFile, serviceSupported, uninstallService, } from "./service.js";
|
|
4
|
+
/**
|
|
5
|
+
* The settings' two switches, on the functions behind `yew service` and `yew app`. Unlike the
|
|
6
|
+
* commands, the start-at-login switch does not start or stop Yew now: the Yew that serves the
|
|
7
|
+
* settings keeps running as it was started, and only the next login changes.
|
|
8
|
+
*/
|
|
9
|
+
export function systemControl(options) {
|
|
10
|
+
const service = options.service ?? realServiceHost();
|
|
11
|
+
const app = options.app ?? realAppHost();
|
|
12
|
+
const canStart = serviceSupported(service);
|
|
13
|
+
const canLaunch = app.platform === "darwin";
|
|
14
|
+
return {
|
|
15
|
+
status: () => ({
|
|
16
|
+
startAtLogin: {
|
|
17
|
+
supported: canStart,
|
|
18
|
+
on: canStart && serviceAtLogin(service),
|
|
19
|
+
file: canStart ? serviceFile(service) : null,
|
|
20
|
+
},
|
|
21
|
+
launcher: {
|
|
22
|
+
supported: canLaunch,
|
|
23
|
+
on: canLaunch && appInstalled(app),
|
|
24
|
+
path: canLaunch ? appPath(app) : null,
|
|
25
|
+
},
|
|
26
|
+
}),
|
|
27
|
+
setStartAtLogin(on) {
|
|
28
|
+
if (!on) {
|
|
29
|
+
uninstallService(service, { stop: false });
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
const { code, file } = installService(service, options.home, options.env, { start: false });
|
|
33
|
+
if (code !== 0) {
|
|
34
|
+
throw conflict(`The system did not accept the service (exit ${code ?? "none"}). The file is at ${file}.`, undefined, "service-failed");
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
setLauncher(on) {
|
|
38
|
+
if (on)
|
|
39
|
+
installApp(app, options.home, options.env);
|
|
40
|
+
else
|
|
41
|
+
uninstallApp(app);
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|