wizards 0.2.44 → 0.2.46

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 (89) hide show
  1. package/apps/runtime/dist/app.js +31 -1
  2. package/apps/runtime/dist/cli/main.js +8 -1
  3. package/apps/runtime/dist/cli/report.js +81 -0
  4. package/apps/runtime/dist/debug.js +196 -0
  5. package/apps/runtime/dist/harness/model.js +2 -0
  6. package/apps/runtime/dist/index.js +3 -0
  7. package/apps/runtime/dist/log.js +106 -0
  8. package/apps/runtime/dist/routes/debug.js +42 -0
  9. package/apps/runtime/dist/routes/internal.js +18 -5
  10. package/apps/runtime/dist/routes/runs.js +1 -1
  11. package/apps/runtime/dist/routes/studio.js +5 -2
  12. package/apps/runtime/dist/tenants/control.js +7 -0
  13. package/apps/runtime/dist/update.js +9 -5
  14. package/apps/web/dist/assets/AboutDialog-DkY1j7k6.js +1 -0
  15. package/apps/web/dist/assets/ChangelogDialog-820LI5Jt.js +1 -0
  16. package/apps/web/dist/assets/ChatView-DBl0iRMg.js +10 -0
  17. package/apps/web/dist/assets/EditorPage-BwJ-hqPg.js +3 -0
  18. package/apps/web/dist/assets/{FlowPreview-DgZiepFR.js → FlowPreview-ChXfiMn_.js} +1 -1
  19. package/apps/web/dist/assets/{Harness-ffZUxkbb.js → Harness-CfUfchNw.js} +2 -2
  20. package/apps/web/dist/assets/HomePage-BG5OZJkv.js +1 -0
  21. package/apps/web/dist/assets/Marketplace-BWhUJ4UX.js +2 -0
  22. package/apps/web/dist/assets/NewWizardPage-C3NqEGmg.js +1 -0
  23. package/apps/web/dist/assets/ProjectPage-Btf0TeP_.js +2 -0
  24. package/apps/web/dist/assets/PublicRunner-BxYinn04.js +1 -0
  25. package/apps/web/dist/assets/ReadOnly-C9P9aiU6.js +1 -0
  26. package/apps/web/dist/assets/RunDrawer-DfnEMPTq.js +4 -0
  27. package/apps/web/dist/assets/RunnerView-CLrGb-oq.js +2 -0
  28. package/apps/web/dist/assets/SettingsPage-FWH84btd.js +1 -0
  29. package/apps/web/dist/assets/SetupPage-BI0kUNVW.js +1 -0
  30. package/apps/web/dist/assets/SharePage-D5AvnhlY.js +1 -0
  31. package/apps/web/dist/assets/ThemeSwitch-C1qYFoYP.js +1 -0
  32. package/apps/web/dist/assets/arrow-right-Dpp_mpHe.js +1 -0
  33. package/apps/web/dist/assets/changelog-B6QMrVxX.js +1 -0
  34. package/apps/web/dist/assets/{circle-alert-D_6s0Xgw.js → circle-alert-CPo3Naay.js} +1 -1
  35. package/apps/web/dist/assets/definition-CQGiBQ4X.js +56 -0
  36. package/apps/web/dist/assets/{external-link-DitV3n6l.js → external-link-CpU8aJY2.js} +1 -1
  37. package/apps/web/dist/assets/index-CIO9W4pe.js +78 -0
  38. package/apps/web/dist/assets/index-DKHClEy3.css +1 -0
  39. package/apps/web/dist/assets/{lock-DSPinlFN.js → lock-C_WlXIQ0.js} +1 -1
  40. package/apps/web/dist/assets/logo-C80CWCDM.js +1 -0
  41. package/apps/web/dist/assets/{refresh-cw-CWRkEENy.js → refresh-cw-Cli5WGnW.js} +1 -1
  42. package/apps/web/dist/assets/session-miDEdw2c.js +1 -0
  43. package/apps/web/dist/assets/settings-menu-ROT8Lbbj.js +1 -0
  44. package/apps/web/dist/assets/sparkles-CP5H-O1E.js +1 -0
  45. package/apps/web/dist/assets/{trash-t3O7FdUR.js → trash-DU-hZpV0.js} +1 -1
  46. package/apps/web/dist/assets/ui-D92EkdEB.js +9 -0
  47. package/apps/web/dist/assets/upload-DMq5N6Fw.js +1 -0
  48. package/apps/web/dist/assets/useMutation-DKcIz55V.js +1 -0
  49. package/apps/web/dist/assets/volume-2-0SfkvOho.js +1 -0
  50. package/apps/web/dist/index.html +14 -13
  51. package/apps/web/dist/mcp/flow.html +43 -43
  52. package/modules/calls/dist/client.css +1 -1
  53. package/modules/sms/dist/client.css +1 -1
  54. package/modules/whatsapp/dist/client.css +1 -1
  55. package/package.json +1 -1
  56. package/apps/web/dist/assets/ChangelogDialog-C1_ZvuwE.js +0 -1
  57. package/apps/web/dist/assets/ChatView-DLG771z6.js +0 -10
  58. package/apps/web/dist/assets/CreditsDialog-Ce7Czhxq.js +0 -1
  59. package/apps/web/dist/assets/EditorPage-CXx32-a7.js +0 -3
  60. package/apps/web/dist/assets/HomePage-B3RVPuUu.js +0 -1
  61. package/apps/web/dist/assets/ImportWizard-CHlCjPEo.js +0 -1
  62. package/apps/web/dist/assets/NewWizardPage-BQW7PoZq.js +0 -2
  63. package/apps/web/dist/assets/ProjectPage-D-_A4iZz.js +0 -2
  64. package/apps/web/dist/assets/PublicRunner-sbya6PXg.js +0 -1
  65. package/apps/web/dist/assets/RunDrawer-BgLxai9C.js +0 -4
  66. package/apps/web/dist/assets/RunnerView-BVm9fL62.js +0 -2
  67. package/apps/web/dist/assets/SettingsPage-Ce6k9xDs.js +0 -1
  68. package/apps/web/dist/assets/SetupPage-CLymFxat.js +0 -1
  69. package/apps/web/dist/assets/SharePage-1Ni5ejt6.js +0 -1
  70. package/apps/web/dist/assets/ThemeSwitch-DN42WOTx.js +0 -1
  71. package/apps/web/dist/assets/arrow-right-BgKM1Npq.js +0 -1
  72. package/apps/web/dist/assets/changelog-CH4sN8Dm.js +0 -1
  73. package/apps/web/dist/assets/copy-BAtcCufT.js +0 -1
  74. package/apps/web/dist/assets/definition-CfFlylCM.js +0 -56
  75. package/apps/web/dist/assets/globe-CoQ1BSyl.js +0 -1
  76. package/apps/web/dist/assets/image-B1a1ax-P.js +0 -1
  77. package/apps/web/dist/assets/index-B8VsYgck.js +0 -78
  78. package/apps/web/dist/assets/index-mB3Du8ho.css +0 -1
  79. package/apps/web/dist/assets/meta-Bpe6vzmM.js +0 -1
  80. package/apps/web/dist/assets/mouse-pointer-click-SHJL7g1i.js +0 -1
  81. package/apps/web/dist/assets/pen-line-DgSzJ60H.js +0 -1
  82. package/apps/web/dist/assets/session-C24kIPr-.js +0 -1
  83. package/apps/web/dist/assets/settings-menu-e8OMChHm.js +0 -1
  84. package/apps/web/dist/assets/star-ClV5w6K4.js +0 -1
  85. package/apps/web/dist/assets/type-BbMmv2qL.js +0 -1
  86. package/apps/web/dist/assets/ui-C4b__6Oo.js +0 -9
  87. package/apps/web/dist/assets/video-D04-GeyG.js +0 -1
  88. package/apps/web/dist/assets/volume-2-FUU7z0rq.js +0 -1
  89. package/apps/web/dist/assets/wand-sparkles-BsD2e8V6.js +0 -1
@@ -12,6 +12,7 @@ import { ZodError } from "zod";
12
12
  import { authRoutes, principalOf } from "./auth/index.js";
13
13
  import { db, schema, withTenant } from "./db/client.js";
14
14
  import { basePath, env } from "./env.js";
15
+ import { allowed, hashIp } from "./limits.js";
15
16
  import { linkPreview } from "./link-preview.js";
16
17
  import { discovery, managed } from "./manage.js";
17
18
  import { bridgeRequest } from "./mcp/bridge.js";
@@ -19,11 +20,12 @@ import { mcpHandler } from "./mcp/handler.js";
19
20
  import { MCP_RESOURCE, SCOPES } from "./mcp/scopes.js";
20
21
  import { PLUGIN_NAME, pluginArchive, pluginMarketplace } from "./plugin.js";
21
22
  import { apiRoutes } from "./routes/api.js";
23
+ import { browserReport, localDebugRoutes } from "./routes/debug.js";
22
24
  import { internalRoutes } from "./routes/internal.js";
23
25
  import { marketplaceStudio } from "./routes/marketplace.js";
24
26
  import { publicPluginRoutes } from "./routes/plugin-public.js";
25
27
  import { pluginRoutes } from "./routes/plugins.js";
26
- import { connectCallback, publicRoutes, runRoutes, shareRoutes } from "./routes/runs.js";
28
+ import { clientIp, connectCallback, publicRoutes, runRoutes, shareRoutes } from "./routes/runs.js";
27
29
  import { studio } from "./routes/studio.js";
28
30
  import { wizardStream } from "./routes/wizard-stream.js";
29
31
  import { runTicketValid } from "./secrets/signing.js";
@@ -99,6 +101,33 @@ app.use("*", async (c, next) => {
99
101
  return next();
100
102
  });
101
103
  app.get("/api/health", (c) => c.json({ ok: true }));
104
+ /**
105
+ * A page in a browser (the studio, a wizard's own page) tells of an error it met: the line
106
+ * goes into this process's log like the server's own, so a look from afar sees both sides
107
+ * (docs/plans/remote-debug.md). Anyone may send; the size and the count per address are capped.
108
+ */
109
+ app.post("/api/log", bodyLimit({ maxSize: 8 * 1024 }), async (c) => {
110
+ const ip = hashIp(clientIp(c));
111
+ if (!allowed(`log:${ip ?? "?"}`, 60, 60 * 60 * 1000)) {
112
+ return c.json({ ok: false }, 429);
113
+ }
114
+ const parsed = browserReport.safeParse(await c.req.json().catch(() => null));
115
+ if (!parsed.success) {
116
+ return c.json({ ok: false }, 400);
117
+ }
118
+ const report = parsed.data;
119
+ const who = await principalOf(c).catch(() => null);
120
+ const tag = who ? `${who.tenantId}/${who.id}` : "visitor";
121
+ const where = report.url ? ` at ${report.url}` : "";
122
+ const line = `[browser ${tag}]${where}: ${report.message}${report.stack ? `\n${report.stack}` : ""}${report.agent ? `\n${report.agent}` : ""}`;
123
+ if (report.level === "warn") {
124
+ console.warn(line);
125
+ }
126
+ else {
127
+ console.error(line);
128
+ }
129
+ return c.json({ ok: true });
130
+ });
102
131
  app.route("/api", authRoutes);
103
132
  app.get("/api/config", (c) => c.json({
104
133
  mode: managed ? "managed" : "local",
@@ -184,6 +213,7 @@ app.route("/api/studio/plugins", pluginRoutes);
184
213
  app.route("/api/studio", studio);
185
214
  app.route("/api/v1", apiRoutes);
186
215
  app.route("/api/internal", internalRoutes);
216
+ app.route("/api/local/debug", localDebugRoutes);
187
217
  app.route("/api/public/plugins", publicPluginRoutes);
188
218
  app.route("/api/public", publicRoutes);
189
219
  app.route("/api/runs", runRoutes);
@@ -3,6 +3,7 @@ import { command, layout, packageVersion, readInstallNote } from "./home.js";
3
3
  import { CLIENTS, nodeIsCurrent } from "./machine.js";
4
4
  import { mcp } from "./mcp.js";
5
5
  import { menu } from "./menu.js";
6
+ import { logsCommand, reportCommand } from "./report.js";
6
7
  import { setup } from "./setup.js";
7
8
  import { open, start, studio } from "./start.js";
8
9
  import { autostart, restart, status, stop } from "./status.js";
@@ -17,6 +18,8 @@ const HELP = `engenty wizards ${packageVersion()}
17
18
  ${command()} open let this browser into the running studio (--print: only show the link)
18
19
  ${command()} status what is installed and what runs
19
20
  ${command()} doctor status, and what is wrong
21
+ ${command()} logs the last lines it printed (\`logs 500\` for more)
22
+ ${command()} report send status, model settings and the last log lines to your account, for support
20
23
  ${command()} stop stop it; the data is kept
21
24
  ${command()} restart stop it and start it again (after an update: the new version)
22
25
  ${command()} update the newest version
@@ -77,7 +80,7 @@ function parse(argv) {
77
80
  else if (arg.startsWith("-")) {
78
81
  return `Unknown option ${arg}.`;
79
82
  }
80
- else if (args.command === "autostart" && !args.value) {
83
+ else if ((args.command === "autostart" || args.command === "logs") && !args.value) {
81
84
  args.value = arg;
82
85
  }
83
86
  else if (args.command === "connect" || args.command === "disconnect") {
@@ -140,6 +143,10 @@ async function main(argv) {
140
143
  return status(paths, false);
141
144
  case "doctor":
142
145
  return status(paths, true);
146
+ case "logs":
147
+ return logsCommand(paths, args.value);
148
+ case "report":
149
+ return reportCommand(paths);
143
150
  case "stop":
144
151
  return stop(paths);
145
152
  case "restart":
@@ -0,0 +1,81 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { LOCAL_MCP_HEADER, mintLocalTicket } from "../auth/local-ticket.js";
4
+ import { command } from "./home.js";
5
+ import { runningRuntime, settings } from "./start.js";
6
+ import { bad, dim, ok } from "./ui.js";
7
+ /**
8
+ * `wizards logs` shows the last lines the running runtime printed; `wizards report` sends its
9
+ * status, model settings and those lines to the linked account, where an operator reads them
10
+ * (docs/plans/remote-debug.md). Both talk to the running process, signed with the data folder's
11
+ * secret as `wizards mcp` does; neither sends anything by itself.
12
+ */
13
+ function readSecret(paths, dataDir) {
14
+ const given = process.env.APP_SECRET?.trim() || settings(paths).fileEnv.APP_SECRET?.trim();
15
+ if (given) {
16
+ return given;
17
+ }
18
+ try {
19
+ return readFileSync(join(dataDir, "secret"), "utf8").trim();
20
+ }
21
+ catch {
22
+ return null;
23
+ }
24
+ }
25
+ async function ask(paths, method, path) {
26
+ const { dataDir } = settings(paths);
27
+ const running = await runningRuntime(dataDir);
28
+ if (!running) {
29
+ return `engenty wizards is not running. Start it with \`${command()} start\` first.`;
30
+ }
31
+ const secret = readSecret(paths, dataDir);
32
+ if (!secret) {
33
+ return "The data folder's secret could not be read.";
34
+ }
35
+ const res = await fetch(`http://127.0.0.1:${running.port}/api/local/debug${path}`, {
36
+ method,
37
+ headers: { [LOCAL_MCP_HEADER]: mintLocalTicket(secret, Date.now(), "local-debug") },
38
+ signal: AbortSignal.timeout(30_000),
39
+ });
40
+ return {
41
+ status: res.status,
42
+ body: (await res.json().catch(() => ({}))),
43
+ };
44
+ }
45
+ /** The last lines of the running runtime; `value` may name how many (default 100). */
46
+ export async function logsCommand(paths, value) {
47
+ const limit = Math.min(Math.max(1, Number(value) || 100), 2000);
48
+ const answer = await ask(paths, "GET", `/logs?limit=${limit}`);
49
+ if (typeof answer === "string") {
50
+ console.error(answer);
51
+ return 1;
52
+ }
53
+ const lines = answer.body.lines ?? [];
54
+ for (const line of lines) {
55
+ const at = new Date(line.at).toISOString().slice(11, 19);
56
+ const level = line.level === "info" ? " " : line.level.padEnd(5);
57
+ console.log(`${dim(at)} ${level} ${line.text}`);
58
+ }
59
+ if (!lines.length) {
60
+ console.log(dim("Nothing printed yet."));
61
+ }
62
+ return 0;
63
+ }
64
+ export async function reportCommand(paths) {
65
+ console.log(dim("Sending status, model settings (no keys) and the last log lines …"));
66
+ const answer = await ask(paths, "POST", "/report");
67
+ if (typeof answer === "string") {
68
+ console.error(answer);
69
+ return 1;
70
+ }
71
+ if (answer.status === 409) {
72
+ console.error(`${bad} This install is linked to no account. Link one in the studio under Settings → Modelle & Konto, then send again.`);
73
+ return 1;
74
+ }
75
+ if (answer.status !== 200) {
76
+ console.error(`${bad} ${answer.body.error ?? `The runtime answered ${answer.status}.`}`);
77
+ return 1;
78
+ }
79
+ console.log(`${ok} Report ${answer.body.id} is at ${answer.body.to}. Name it when you ask for help.`);
80
+ return 0;
81
+ }
@@ -0,0 +1,196 @@
1
+ import { arch, hostname, platform } from "node:os";
2
+ import { desc, eq } from "drizzle-orm";
3
+ import { accountToken, linkedAccount } from "./auth/account.js";
4
+ import { packageVersion } from "./cli/home.js";
5
+ import { db, knownTenants, schema, withTenant } from "./db/client.js";
6
+ import { env } from "./env.js";
7
+ import { logState, startedAt, tail } from "./log.js";
8
+ import { managed } from "./manage.js";
9
+ import { modelSettings } from "./models.js";
10
+ import { loadedPlugins } from "./plugins/registry.js";
11
+ import { runIndexOf, tenantOfRun } from "./tenants/control.js";
12
+ import { LOCAL_TENANT } from "./tenants/tenant.js";
13
+ /**
14
+ * What an installation tells about itself when someone looks at it from afar
15
+ * (docs/plans/remote-debug.md): its status, the lines it printed, one run, a tenant's models.
16
+ * Nothing here holds a key or a person's answers; the log ring took the secrets out already.
17
+ * The Manage-App asks a runtime of its own over `/api/internal/debug/*`; a runtime that runs
18
+ * alone answers the command line over `/api/local/debug/*` and sends a report to its account.
19
+ */
20
+ /** This process, as every installation names itself. */
21
+ export function processStatus() {
22
+ const memory = process.memoryUsage();
23
+ return {
24
+ pid: process.pid,
25
+ node: process.version,
26
+ platform: `${platform()} ${arch()}`,
27
+ hostname: hostname(),
28
+ startedAt: new Date(startedAt).toISOString(),
29
+ uptimeSeconds: Math.round((Date.now() - startedAt) / 1000),
30
+ memoryMb: Math.round(memory.rss / 1_048_576),
31
+ log: logState(),
32
+ };
33
+ }
34
+ export async function status() {
35
+ const tenants = await knownTenants().catch(() => []);
36
+ return {
37
+ app: "engenty-wizards-runtime",
38
+ version: packageVersion(),
39
+ process: processStatus(),
40
+ managed,
41
+ appUrl: env.appUrl,
42
+ manageUrl: env.manage.url || null,
43
+ gatewayUrl: (managed ? env.manage.gatewayUrl : env.local.gatewayUrl) || null,
44
+ sandbox: env.sandbox,
45
+ browser: env.browserCdpUrl ? "cdp" : "local",
46
+ files: env.s3.bucket ? "s3" : "data folder",
47
+ database: env.databaseUrl ? "libsql" : "file",
48
+ tenantDatabases: env.tenantDbUrlTemplate ? "libsql" : "files",
49
+ tenants: tenants.length,
50
+ plugins: loadedPlugins().map((p) => ({
51
+ id: p.source.id,
52
+ version: p.source.manifest.version ?? null,
53
+ })),
54
+ };
55
+ }
56
+ const from = () => hostname();
57
+ /** The lines this process printed. */
58
+ export function logs(query) {
59
+ const own = from();
60
+ return {
61
+ sources: [{ from: own, ok: true }],
62
+ lines: tail(query).map((line) => ({ ...line, from: own })),
63
+ };
64
+ }
65
+ /** One run, whichever tenant it belongs to: its state, its error, what the line knows, its last events. */
66
+ export async function runDetail(runId) {
67
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(runId)) {
68
+ return null;
69
+ }
70
+ const tenantId = await tenantOfRun(runId);
71
+ if (!tenantId) {
72
+ return null;
73
+ }
74
+ return withTenant(tenantId, async () => {
75
+ const run = await db.query.run.findFirst({
76
+ where: eq(schema.run.id, runId),
77
+ columns: {
78
+ id: true,
79
+ wizardId: true,
80
+ version: true,
81
+ mode: true,
82
+ status: true,
83
+ cursor: true,
84
+ error: true,
85
+ ask: true,
86
+ unattended: true,
87
+ costMicros: true,
88
+ userId: true,
89
+ createdAt: true,
90
+ updatedAt: true,
91
+ expiresAt: true,
92
+ },
93
+ });
94
+ if (!run) {
95
+ return null;
96
+ }
97
+ const [wizard, events, line] = await Promise.all([
98
+ db.query.wizard.findFirst({
99
+ where: eq(schema.wizard.id, run.wizardId),
100
+ columns: { title: true, publishedVersion: true },
101
+ }),
102
+ db
103
+ .select({
104
+ id: schema.runEvent.id,
105
+ stepId: schema.runEvent.stepId,
106
+ type: schema.runEvent.type,
107
+ message: schema.runEvent.message,
108
+ createdAt: schema.runEvent.createdAt,
109
+ })
110
+ .from(schema.runEvent)
111
+ .where(eq(schema.runEvent.runId, runId))
112
+ .orderBy(desc(schema.runEvent.id))
113
+ .limit(60),
114
+ runIndexOf(runId),
115
+ ]);
116
+ return {
117
+ tenantId,
118
+ run: {
119
+ ...run,
120
+ ask: run.ask ? { id: run.ask.id, kind: run.ask.kind } : null,
121
+ costCredits: Math.round(run.costMicros / 10_000) / 100,
122
+ },
123
+ wizard: wizard ? { id: run.wizardId, ...wizard } : null,
124
+ line,
125
+ events: events.reverse(),
126
+ };
127
+ });
128
+ }
129
+ /** Where each class of a tenant runs, as its settings page shows it; never a key. */
130
+ export async function tenantModels(tenantId) {
131
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(tenantId)) {
132
+ return null;
133
+ }
134
+ const known = await knownTenants();
135
+ if (!known.includes(tenantId)) {
136
+ return null;
137
+ }
138
+ return withTenant(tenantId, async () => {
139
+ const settings = await modelSettings();
140
+ return {
141
+ tenantId,
142
+ source: settings.source,
143
+ bindings: settings.bindings,
144
+ creditFallback: settings.creditFallback,
145
+ keys: settings.keys,
146
+ ways: settings.ways,
147
+ };
148
+ });
149
+ }
150
+ export class ReportError extends Error {
151
+ code;
152
+ constructor(code, message) {
153
+ super(message);
154
+ this.code = code;
155
+ }
156
+ }
157
+ /**
158
+ * A runtime that runs alone sends its account what a look from afar needs: its status, its
159
+ * model settings (never a key) and the last lines it printed. The person asks for it
160
+ * (`wizards report`); nothing goes by itself.
161
+ */
162
+ export async function sendReport() {
163
+ const account = await linkedAccount();
164
+ const token = account ? await accountToken() : null;
165
+ if (!account || !token) {
166
+ throw new ReportError("no_account", "This install is linked to no account.");
167
+ }
168
+ const [state, models] = await Promise.all([status(), withTenant(LOCAL_TENANT, modelSettings)]);
169
+ const body = {
170
+ kind: "install",
171
+ version: state.version,
172
+ status: state,
173
+ models: {
174
+ source: models.source,
175
+ bindings: models.bindings,
176
+ creditFallback: models.creditFallback,
177
+ keys: models.keys,
178
+ ways: models.ways,
179
+ },
180
+ logs: tail({ limit: 500 }),
181
+ };
182
+ const res = await fetch(`${env.local.accountUrl}/v1/diagnostics`, {
183
+ method: "POST",
184
+ headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
185
+ body: JSON.stringify(body),
186
+ signal: AbortSignal.timeout(20_000),
187
+ }).catch((err) => {
188
+ throw new ReportError("not_sent", `The account did not answer: ${err.message}`);
189
+ });
190
+ if (!res.ok) {
191
+ const text = await res.text().catch(() => "");
192
+ throw new ReportError("not_sent", `The account answered ${res.status}: ${text.slice(0, 200)}`);
193
+ }
194
+ const { id } = (await res.json());
195
+ return { id, to: env.local.accountUrl };
196
+ }
@@ -13,6 +13,8 @@ export const exhausted = (h) => h.exhausted ??
13
13
  `Das Konto, mit dem ${h.name} angemeldet ist, hat kein Guthaben oder Kontingent mehr.`;
14
14
  /** The failure a client reports, as the person should read it. */
15
15
  export function failureOf(h, detail) {
16
+ // The client's own words stay in the log: the sentence below sums them up for the person.
17
+ console.warn(`[${h.id}] ${detail.replace(/\s+/g, " ").trim().slice(0, 1500)}`);
16
18
  if (/credit balance|billing|too low|usage limit|quota|insufficient|rate.?limit|\b429\b/i.test(detail)) {
17
19
  return new ModelUnavailableError(exhausted(h));
18
20
  }
@@ -4,6 +4,7 @@ import { adoptLegacyData } from "./db/adopt.js";
4
4
  import { knownTenants, migrateAllTenants, migrateControlDb, openTenantDb, withTenant, } from "./db/client.js";
5
5
  import { resumeInterruptedRuns } from "./engine/runner.js";
6
6
  import { basePath, env } from "./env.js";
7
+ import { hookConsole } from "./log.js";
7
8
  import { managed } from "./manage.js";
8
9
  import { checkModelsAtStart, loadCatalog, loadLocalModels } from "./models.js";
9
10
  import { startJobs } from "./plugins/jobs.js";
@@ -16,6 +17,8 @@ import { purgeExpiredRuns } from "./services/shares.js";
16
17
  import { purgeUnusedStores } from "./store/index.js";
17
18
  import { LOCAL_TENANT } from "./tenants/tenant.js";
18
19
  import { onRestart, RESTART_EXIT } from "./update.js";
20
+ // Before anything prints: the last lines stay in memory for a look from afar (debug.ts).
21
+ hookConsole();
19
22
  await migrateControlDb();
20
23
  // What the linked account's plan confirmed last: the Pro modules it includes load with the rest.
21
24
  await loadEntitlement();
@@ -0,0 +1,106 @@
1
+ import { format } from "node:util";
2
+ const RANK = { debug: 0, info: 1, warn: 2, error: 3 };
3
+ const KEEP = Number(process.env.LOG_KEEP) || 3000;
4
+ const LINE_MAX = 4000;
5
+ /** When this process started. */
6
+ export const startedAt = Date.now();
7
+ const lines = [];
8
+ let next = 1;
9
+ /** What never leaves a process in a log line: keys, tokens, one-time links, passwords. */
10
+ const SECRETS = [
11
+ [/(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi, "$1[redacted]"],
12
+ [/\bwz_[A-Za-z0-9_-]{6,}/g, "wz_[redacted]"],
13
+ [/\b(sk|rk|pk)-[A-Za-z0-9_-]{8,}/g, "$1-[redacted]"],
14
+ [/\bAIza[0-9A-Za-z_-]{20,}/g, "AIza[redacted]"],
15
+ [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, "[jwt]"],
16
+ [/([?&](?:k|t|rt|token|key|secret|code|password|api_?key)=)[^&\s"'<>]+/gi, "$1[redacted]"],
17
+ [
18
+ /((?:secret|password|passwd|token|api[_-]?key|authorization|refresh_token|access_token)["']?\s*[:=]\s*["']?)[^\s,"'}]{6,}/gi,
19
+ "$1[redacted]",
20
+ ],
21
+ ];
22
+ export function redact(text) {
23
+ let out = text;
24
+ for (const [pattern, replacement] of SECRETS) {
25
+ out = out.replace(pattern, replacement);
26
+ }
27
+ return out;
28
+ }
29
+ function push(level, args) {
30
+ const text = redact(format(...args)).slice(0, LINE_MAX);
31
+ lines.push({ id: next++, at: Date.now(), level, text });
32
+ if (lines.length > KEEP) {
33
+ lines.splice(0, lines.length - KEEP);
34
+ }
35
+ }
36
+ /** Keeps a line without printing it. */
37
+ export function note(level, text) {
38
+ push(level, [text]);
39
+ }
40
+ export function tail(query = {}) {
41
+ const limit = Math.min(Math.max(1, query.limit ?? 200), 2000);
42
+ const rank = RANK[query.level ?? "debug"] ?? 0;
43
+ const needle = query.q?.trim().toLowerCase();
44
+ const out = [];
45
+ for (let i = lines.length - 1; i >= 0 && out.length < limit; i--) {
46
+ const line = lines[i];
47
+ if (query.since !== undefined && line.id <= query.since) {
48
+ break;
49
+ }
50
+ if (query.after !== undefined && line.at < query.after) {
51
+ break;
52
+ }
53
+ if (RANK[line.level] < rank) {
54
+ continue;
55
+ }
56
+ if (needle && !line.text.toLowerCase().includes(needle)) {
57
+ continue;
58
+ }
59
+ out.push(line);
60
+ }
61
+ return out.reverse();
62
+ }
63
+ /** How many lines the ring holds and the id of the newest. */
64
+ export function logState() {
65
+ return { lines: lines.length, newest: next - 1, keeps: KEEP };
66
+ }
67
+ /** Reads a query string's values as a tail query. */
68
+ export function tailQuery(get) {
69
+ const int = (key) => {
70
+ const v = Number(get(key));
71
+ return Number.isSafeInteger(v) && v >= 0 ? v : undefined;
72
+ };
73
+ const level = get("level");
74
+ return {
75
+ since: int("since"),
76
+ after: int("after"),
77
+ limit: int("limit"),
78
+ level: level && level in RANK ? level : undefined,
79
+ q: get("q")?.slice(0, 200) || undefined,
80
+ };
81
+ }
82
+ let hooked = false;
83
+ /** Hooks the console once: each method still prints, and keeps a copy here. */
84
+ export function hookConsole() {
85
+ if (hooked) {
86
+ return;
87
+ }
88
+ hooked = true;
89
+ const methods = [
90
+ ["debug", "debug"],
91
+ ["log", "info"],
92
+ ["info", "info"],
93
+ ["warn", "warn"],
94
+ ["error", "error"],
95
+ ];
96
+ for (const [method, level] of methods) {
97
+ const original = console[method].bind(console);
98
+ console[method] = (...args) => {
99
+ push(level, args);
100
+ original(...args);
101
+ };
102
+ }
103
+ process.on("warning", (warning) => {
104
+ push("warn", [`${warning.name}: ${warning.message}`]);
105
+ });
106
+ }
@@ -0,0 +1,42 @@
1
+ import { Hono } from "hono";
2
+ import { z } from "zod";
3
+ import { LOCAL_MCP_HEADER, localTicketExpiry } from "../auth/local-ticket.js";
4
+ import { logs, ReportError, sendReport, status } from "../debug.js";
5
+ import { env } from "../env.js";
6
+ import { tailQuery } from "../log.js";
7
+ import { managed } from "../manage.js";
8
+ /**
9
+ * A runtime that runs alone answers its own command line here (`wizards logs`, `wizards
10
+ * report`): each request signed with the data folder's secret, as `wizards mcp` signs its own.
11
+ * Nothing of this is reached from another machine; the account hears from an install only when
12
+ * the person sends a report.
13
+ */
14
+ export const localDebugRoutes = new Hono()
15
+ .use(async (c, next) => {
16
+ const ticket = c.req.header(LOCAL_MCP_HEADER) ?? "";
17
+ if (managed || !localTicketExpiry(env.authSecret, ticket, Date.now(), "local-debug")) {
18
+ return c.json({ error: "unauthorized" }, 401);
19
+ }
20
+ await next();
21
+ })
22
+ .get("/status", async (c) => c.json(await status()))
23
+ .get("/logs", (c) => c.json(logs(tailQuery((key) => c.req.query(key)))))
24
+ .post("/report", async (c) => {
25
+ try {
26
+ return c.json(await sendReport());
27
+ }
28
+ catch (err) {
29
+ if (err instanceof ReportError) {
30
+ return c.json({ error: err.message, code: err.code }, err.code === "no_account" ? 409 : 502);
31
+ }
32
+ throw err;
33
+ }
34
+ });
35
+ /** What a page reports about itself: an error it met, with where it stood. */
36
+ export const browserReport = z.object({
37
+ level: z.enum(["error", "warn"]).default("error"),
38
+ message: z.string().min(1).max(2000),
39
+ stack: z.string().max(4000).optional(),
40
+ url: z.string().max(500).optional(),
41
+ agent: z.string().max(300).optional(),
42
+ });
@@ -4,8 +4,10 @@ import { join } from "node:path";
4
4
  import { Hono } from "hono";
5
5
  import { z } from "zod";
6
6
  import { closeTenantDb, tenantDb } from "../db/client.js";
7
+ import { logs, runDetail, status, tenantModels } from "../debug.js";
7
8
  import { env } from "../env.js";
8
9
  import { removeTenantObjects } from "../files/objects.js";
10
+ import { tailQuery } from "../log.js";
9
11
  import { forgetTenant, managed } from "../manage.js";
10
12
  import { loadedPlugins } from "../plugins/registry.js";
11
13
  import { forgetTenantRows, setTenantStatus } from "../tenants/control.js";
@@ -23,11 +25,25 @@ function fromManage(header) {
23
25
  * itself is deleted by whoever created it (the Manage-App, or here when it is a file).
24
26
  */
25
27
  export const internalRoutes = new Hono()
26
- // The plugins this runtime carries: the Manage-App offers them when a plan's modules are picked.
27
- .get("/plugins", (c) => {
28
+ .use(async (c, next) => {
28
29
  if (!fromManage(c.req.header("authorization"))) {
29
30
  return c.json({ error: "unauthorized" }, 401);
30
31
  }
32
+ await next();
33
+ })
34
+ // --- a look from afar (docs/plans/remote-debug.md): read-only, never a key -------------
35
+ .get("/debug/status", async (c) => c.json(await status()))
36
+ .get("/debug/logs", (c) => c.json(logs(tailQuery((key) => c.req.query(key)))))
37
+ .get("/debug/runs/:id", async (c) => {
38
+ const found = await runDetail(c.req.param("id"));
39
+ return found ? c.json(found) : c.json({ error: "not found" }, 404);
40
+ })
41
+ .get("/debug/tenants/:id/models", async (c) => {
42
+ const found = await tenantModels(c.req.param("id"));
43
+ return found ? c.json(found) : c.json({ error: "not found" }, 404);
44
+ })
45
+ // The plugins this runtime carries: the Manage-App offers them when a plan's modules are picked.
46
+ .get("/plugins", (c) => {
31
47
  return c.json({
32
48
  plugins: loadedPlugins().map((p) => ({
33
49
  id: p.source.id,
@@ -38,9 +54,6 @@ export const internalRoutes = new Hono()
38
54
  });
39
55
  })
40
56
  .post("/tenants/:id", async (c) => {
41
- if (!fromManage(c.req.header("authorization"))) {
42
- return c.json({ error: "unauthorized" }, 401);
43
- }
44
57
  const id = c.req.param("id");
45
58
  if (!/^[A-Za-z0-9_-]{1,64}$/.test(id)) {
46
59
  return c.json({ error: "bad tenant id" }, 400);
@@ -38,7 +38,7 @@ import { byteRange, uploadLimit, wizardManifest } from "./delivery.js";
38
38
  const VISITOR_COOKIE = "wz_vid";
39
39
  /** Kept files a review shows inline. */
40
40
  const INLINE_TYPES = new Set(["application/pdf", "image/png", "image/jpeg", "image/webp"]);
41
- function clientIp(c) {
41
+ export function clientIp(c) {
42
42
  const fwd = c.req.header("x-forwarded-for")?.split(",")[0]?.trim();
43
43
  if (fwd) {
44
44
  return fwd;
@@ -264,8 +264,11 @@ export const studio = new Hono()
264
264
  canManage: isAdminRole(user.role),
265
265
  });
266
266
  })
267
- // A runtime that runs alone says when a newer release is out and can run the update itself.
268
- .get("/update", async (c) => managed ? c.json({ error: "not_local" }, 404) : c.json(await updateStatus()))
267
+ // A runtime that runs alone says when a newer release is out and can run the update itself;
268
+ // `?fresh=1` asks GitHub now instead of within the hour.
269
+ .get("/update", async (c) => managed
270
+ ? c.json({ error: "not_local" }, 404)
271
+ : c.json(await updateStatus(c.req.query("fresh") === "1")))
269
272
  .post("/update", async (c) => {
270
273
  if (managed) {
271
274
  return c.json({ error: "not_local" }, 404);
@@ -151,3 +151,10 @@ export async function forgetTenantRows(id) {
151
151
  }
152
152
  }
153
153
  }
154
+ /** The line's view of one run: which tenant it belongs to, whether it is awake. */
155
+ export async function runIndexOf(runId) {
156
+ const row = await controlDb.query.runIndex.findFirst({
157
+ where: eq(control.runIndex.runId, runId),
158
+ });
159
+ return row ? { tenantId: row.tenantId, active: row.active } : null;
160
+ }