@engenty/wizards-runtime 0.11.5 → 0.11.7

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 (124) hide show
  1. package/apps/runtime/dist/agents/architect.js +40 -55
  2. package/apps/runtime/dist/agents/chat-clients.js +3 -0
  3. package/apps/runtime/dist/agents/company.js +4 -12
  4. package/apps/runtime/dist/agents/studio-assistant.js +82 -74
  5. package/apps/runtime/dist/agents/subscription.js +27 -17
  6. package/apps/runtime/dist/assistant/knows.js +19 -19
  7. package/apps/runtime/dist/auth/account.js +51 -12
  8. package/apps/runtime/dist/auth/index.js +15 -2
  9. package/apps/runtime/dist/authoring/guide.js +20 -447
  10. package/apps/runtime/dist/browser/fast/run.js +18 -12
  11. package/apps/runtime/dist/cli/account.js +127 -10
  12. package/apps/runtime/dist/cli/main.js +4 -2
  13. package/apps/runtime/dist/connectors/mail.js +4 -3
  14. package/apps/runtime/dist/data/chat-models.json +116 -0
  15. package/apps/runtime/dist/docs/user-guide/models.md +15 -5
  16. package/apps/runtime/dist/documents/parse.js +5 -14
  17. package/apps/runtime/dist/engine/decide.js +2 -1
  18. package/apps/runtime/dist/engine/runner.js +4 -3
  19. package/apps/runtime/dist/engine/steps.js +82 -91
  20. package/apps/runtime/dist/engine/template.js +2 -3
  21. package/apps/runtime/dist/env.js +5 -0
  22. package/apps/runtime/dist/harness/antigravity.js +2 -2
  23. package/apps/runtime/dist/harness/apple.js +4 -6
  24. package/apps/runtime/dist/harness/codex.js +5 -6
  25. package/apps/runtime/dist/harness/prompt.js +8 -8
  26. package/apps/runtime/dist/mcp/handler.js +5 -7
  27. package/apps/runtime/dist/mcp/tools.js +33 -54
  28. package/apps/runtime/dist/media/conversation.js +18 -23
  29. package/apps/runtime/dist/media/generate.js +18 -3
  30. package/apps/runtime/dist/media/transcribe.js +5 -4
  31. package/apps/runtime/dist/models.js +8 -9
  32. package/apps/runtime/dist/motion-graphics/project.js +19 -53
  33. package/apps/runtime/dist/motion-graphics/sounds.js +2 -1
  34. package/apps/runtime/dist/motion-graphics/step.js +31 -16
  35. package/apps/runtime/dist/prompts/README.md +48 -0
  36. package/apps/runtime/dist/prompts/architect.md +89 -0
  37. package/apps/runtime/dist/prompts/authoring.md +503 -0
  38. package/apps/runtime/dist/prompts/goose.md +229 -0
  39. package/apps/runtime/dist/prompts/mcp.md +156 -0
  40. package/apps/runtime/dist/prompts/safety.md +23 -0
  41. package/apps/runtime/dist/prompts/services.md +151 -0
  42. package/apps/runtime/dist/prompts/step.md +334 -0
  43. package/apps/runtime/dist/prompts/tools.md +330 -0
  44. package/apps/runtime/dist/prompts/voice.md +53 -0
  45. package/apps/runtime/dist/prompts.js +50 -0
  46. package/apps/runtime/dist/routes/studio.js +58 -7
  47. package/apps/runtime/dist/safety.js +45 -0
  48. package/apps/runtime/dist/sandbox/index.js +8 -3
  49. package/apps/runtime/dist/services/architect.js +5 -4
  50. package/apps/runtime/dist/services/assistant-chats.js +5 -8
  51. package/apps/runtime/dist/services/brand.js +2 -7
  52. package/apps/runtime/dist/services/chat-models.js +58 -0
  53. package/apps/runtime/dist/services/cloud.js +8 -4
  54. package/apps/runtime/dist/services/knowledge-model.js +17 -8
  55. package/apps/runtime/dist/services/knowledge.js +5 -9
  56. package/apps/runtime/dist/services/project-files.js +3 -8
  57. package/apps/runtime/dist/services/relevance.js +4 -3
  58. package/apps/runtime/dist/services/runs.js +6 -7
  59. package/apps/runtime/dist/services/site.js +2 -2
  60. package/apps/runtime/dist/services/translations.js +17 -10
  61. package/apps/runtime/dist/services/wizards.js +8 -0
  62. package/apps/runtime/dist/sync/client.js +116 -1
  63. package/apps/runtime/dist/tools/browser.js +36 -33
  64. package/apps/runtime/dist/tools/code.js +20 -6
  65. package/apps/runtime/dist/tools/connector.js +23 -9
  66. package/apps/runtime/dist/tools/index.js +14 -11
  67. package/apps/runtime/dist/tools/mail.js +5 -5
  68. package/apps/runtime/dist/tools/net-guard.js +4 -4
  69. package/apps/runtime/dist/tools/pages.js +3 -2
  70. package/apps/runtime/dist/tools/project.js +7 -8
  71. package/apps/runtime/dist/tools/store.js +14 -10
  72. package/apps/web/dist/assets/{AboutDialog-B525L37O.js → AboutDialog-J9rRhJTJ.js} +1 -1
  73. package/apps/web/dist/assets/{ChangelogDialog-gInSm1Xe.js → ChangelogDialog-D9bBSuLQ.js} +1 -1
  74. package/apps/web/dist/assets/{CodeEditor-C0TmdCrb.js → CodeEditor-CiRJjYpm.js} +1 -1
  75. package/apps/web/dist/assets/{EditorPage-7t3vhZi6.js → EditorPage-ChLV09jO.js} +1 -1
  76. package/apps/web/dist/assets/{FlowPreview-BBN-APkG.js → FlowPreview-QRnLE4JM.js} +1 -1
  77. package/apps/web/dist/assets/{Harness-fAoC908y.js → Harness-dM1CDgnx.js} +1 -1
  78. package/apps/web/dist/assets/Marketplace-8rU-MhWj.js +2 -0
  79. package/apps/web/dist/assets/{NewWizardChannels-X32lBGMf.js → NewWizardChannels--JqgVT-t.js} +1 -1
  80. package/apps/web/dist/assets/{NewWizardPage-DMoqDhsh.js → NewWizardPage-CNv5UuBn.js} +1 -1
  81. package/apps/web/dist/assets/{OnboardingPage-BjZy-bhI.js → OnboardingPage-CDuhfBEI.js} +1 -1
  82. package/apps/web/dist/assets/{PreviewPane-Bt-ForJG.js → PreviewPane-BsMrHW8b.js} +2 -2
  83. package/apps/web/dist/assets/{ProjectPage-B5a-nod-.js → ProjectPage-CoVMEoB1.js} +1 -1
  84. package/apps/web/dist/assets/{PublicRunner-Cq_XzX54.js → PublicRunner-Ckte5NnM.js} +1 -1
  85. package/apps/web/dist/assets/{ReadOnly-DX3beZJz.js → ReadOnly-Ch-ss9Mh.js} +1 -1
  86. package/apps/web/dist/assets/SettingsPage-CGp6G_fp.js +2 -0
  87. package/apps/web/dist/assets/{SetupPage-BI9bgEkI.js → SetupPage-DgFT_646.js} +1 -1
  88. package/apps/web/dist/assets/{SharePage-Ch-1oLBs.js → SharePage-CEcFKE3b.js} +1 -1
  89. package/apps/web/dist/assets/changelog-DMhLfQmS.js +1 -0
  90. package/apps/web/dist/assets/i18n-AXoEWXfv.js +55 -0
  91. package/apps/web/dist/assets/index-BYZBN0xx.css +1 -0
  92. package/apps/web/dist/assets/index-Dx7qMiM3.js +34 -0
  93. package/apps/web/dist/assets/{oss-credits-CZT1KRIp.js → oss-credits-Da4KrYmP.js} +1 -1
  94. package/apps/web/dist/assets/{phone-DxC6eM6O.js → phone-De-HF0g7.js} +1 -1
  95. package/apps/web/dist/assets/{runners-SQHfvvNQ.js → runners-UIPj9xyX.js} +1 -1
  96. package/apps/web/dist/assets/{session-4CTNIlai.js → session-DUxZmhqy.js} +1 -1
  97. package/apps/web/dist/assets/{settings-menu-B0af5EBE.js → settings-menu-Bo1yXMGF.js} +1 -1
  98. package/apps/web/dist/assets/{theme-mtamawa_.js → theme-CSuPPxre.js} +1 -1
  99. package/apps/web/dist/assets/ui-CBDsXUoA.js +83 -0
  100. package/apps/web/dist/assets/{upload-DXJQU2lL.js → upload-CZgdEF60.js} +1 -1
  101. package/apps/web/dist/assets/{useMutation-DwRYrG3V.js → useMutation-ZHWqRSPd.js} +1 -1
  102. package/apps/web/dist/assets/{volume-2-CYbbBiXP.js → volume-2-c641MxaU.js} +1 -1
  103. package/apps/web/dist/assets/{wrench-D8lG2BH7.js → wrench-DCEAyYuR.js} +1 -1
  104. package/apps/web/dist/index.html +8 -9
  105. package/apps/web/dist/mcp/flow.html +87 -87
  106. package/node_modules/@engenty/wizards-shared/dist/assistant.d.ts +1 -0
  107. package/node_modules/@engenty/wizards-shared/dist/assistant.js +2 -0
  108. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +6 -0
  109. package/node_modules/@engenty/wizards-shared/dist/run.js +12 -0
  110. package/node_modules/@engenty/wizards-shared/dist/surface.d.ts +0 -2
  111. package/node_modules/@engenty/wizards-shared/dist/surface.js +0 -29
  112. package/node_modules/@engenty/wizards-shared/dist/sync.d.ts +5 -0
  113. package/package.json +2 -2
  114. package/plugin/.claude-plugin/plugin.json +1 -1
  115. package/plugin/plugin.json +1 -1
  116. package/apps/runtime/dist/assistant/primer.js +0 -26
  117. package/apps/web/dist/assets/Marketplace-CotMMcJ-.js +0 -2
  118. package/apps/web/dist/assets/SettingsPage-DPuwA3QL.js +0 -2
  119. package/apps/web/dist/assets/changelog-BlJc9UFS.js +0 -1
  120. package/apps/web/dist/assets/coins-D_yN56kT.js +0 -1
  121. package/apps/web/dist/assets/i18n-Dy3fTQM3.js +0 -55
  122. package/apps/web/dist/assets/index-Dt1Ps3ge.js +0 -34
  123. package/apps/web/dist/assets/index-rX7eCvWh.css +0 -1
  124. package/apps/web/dist/assets/ui-CL8v8Goa.js +0 -83
@@ -4,11 +4,16 @@ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node
4
4
  import { homedir } from "node:os";
5
5
  import { dirname, join } from "node:path";
6
6
  import { createInterface } from "node:readline";
7
+ import { note } from "@engenty/wizards-shared/run";
7
8
  import { internalKey } from "../auth/keys.js";
8
9
  import { env } from "../env.js";
9
10
  import { resolveEnv } from "../harness/env.js";
10
11
  import { detectHarness, harness, signedOut } from "../harness/index.js";
11
- import { CHAT_WAYS, chatWayReady, localModelSettings } from "../models.js";
12
+ import { ModelUnavailableError } from "../model-errors.js";
13
+ import { CHAT_WAYS, chatWayReady, localModelSettings, } from "../models.js";
14
+ import { prompt } from "../prompts.js";
15
+ import { contentPolicy } from "../safety.js";
16
+ import { chatModelId } from "../services/chat-models.js";
12
17
  import { ServiceError } from "../services/errors.js";
13
18
  import { deleteSetting, readSetting, writeSetting } from "../settings.js";
14
19
  import { serverText } from "../texts.js";
@@ -51,12 +56,7 @@ function ownCursorServers() {
51
56
  return [];
52
57
  }
53
58
  }
54
- const SYSTEM = (wizardId) => [
55
- "You are the architect in the engenty wizards studio. The admin talks to you in the studio's chat panel, next to a diagram of the wizard.",
56
- `You work on exactly one wizard: id "${wizardId}". Read it with get_wizard before you change it; change it with edit_wizard and the file tools; never create another wizard and never publish unless the admin asks.`,
57
- "Call get_authoring_guide once before your first change. Fix every issue a write reports before you answer.",
58
- "Answer in the admin's language, in two or three plain sentences: what you changed and what to try next. No JSON, no tool names.",
59
- ].join("\n");
59
+ const SYSTEM = (wizardId) => `${prompt("architect", "persona")}\n\n${prompt("architect", "subscription.system", { wizard_id: wizardId })}\n\n${contentPolicy()}`;
60
60
  const BUILDING = /edit_wizard|write_wizard|write_file|delete_file|create_wizard/;
61
61
  const ACTIVITY = [
62
62
  [/get_authoring_guide/, "doingGuide"],
@@ -120,6 +120,7 @@ export async function subscriptionTurn(input) {
120
120
  mcpUrl: mcpUrl(),
121
121
  dir,
122
122
  mcpConfigFile: input.client === "claude" ? mcpConfig() : undefined,
123
+ model: (await chatModelId(input.client, input.extra === false ? "normal" : "extra")) ?? undefined,
123
124
  images,
124
125
  };
125
126
  const h = harness(input.client);
@@ -210,26 +211,35 @@ export async function subscriptionTurn(input) {
210
211
  }
211
212
  }
212
213
  /** The ways that can answer the studio's chats now, in the order the settings offer them. */
213
- export async function chatWays(textModelReady) {
214
- const ready = await Promise.all(CHAT_WAYS.map((w) => chatWayReady(w, textModelReady)));
214
+ export async function chatWays() {
215
+ const ready = await Promise.all(CHAT_WAYS.map((w) => chatWayReady(w)));
215
216
  return CHAT_WAYS.filter((_, i) => ready[i]);
216
217
  }
217
218
  /**
218
219
  * What answers the studio's chats, Goose and the editor's chat, on a runtime that runs alone: the
219
- * way chosen while it can answer, else the text classes, or Claude Code where it is the source.
220
+ * way chosen while it can answer, else Claude Code where it is the source of models, else the
221
+ * first way that is ready. Null where none is: the chat then says what to set up.
220
222
  */
221
- export async function chatEngine(textModelReady) {
223
+ export async function chatEngine() {
222
224
  const chosen = await readSetting("chat-engine");
223
- if (chosen && CHAT_WAYS.includes(chosen) && (await chatWayReady(chosen, textModelReady))) {
225
+ if (chosen && CHAT_WAYS.includes(chosen) && (await chatWayReady(chosen))) {
224
226
  return chosen;
225
227
  }
226
- const claude = await chatWayReady("claude", textModelReady);
227
- // Nothing chosen: where Claude Code is the source of models, it answers the chat too.
228
- if (claude && localModelSettings().source === "claude") {
228
+ if (localModelSettings().source === "claude" && (await chatWayReady("claude"))) {
229
229
  return "claude";
230
230
  }
231
- // Else a configured model answers; without one, the Claude subscription does.
232
- return textModelReady || !claude ? "models" : "claude";
231
+ return (await chatWays())[0] ?? null;
232
+ }
233
+ /** The way a turn runs on: a cloud runtime's own classes, else `chatEngine`, or a refusal naming what to set up. */
234
+ export async function chatTurnWay(managed) {
235
+ if (managed) {
236
+ return "models";
237
+ }
238
+ const way = await chatEngine();
239
+ if (!way) {
240
+ throw new ModelUnavailableError(note("chatNoWay"));
241
+ }
242
+ return way;
233
243
  }
234
244
  export function setChatEngine(way) {
235
245
  return writeSetting("chat-engine", way);
@@ -10,6 +10,7 @@ import { detectHarnesses } from "../harness/index.js";
10
10
  import { managed, publicPlans, tenantInfo, tenantUsage } from "../manage.js";
11
11
  import { classWays, waysIn } from "../models.js";
12
12
  import { pluginToolsOf } from "../plugins/registry.js";
13
+ import { prompt } from "../prompts.js";
13
14
  import { earlierChats, readChat, searchChats } from "../services/assistant-chats.js";
14
15
  import { asLang, marketplaceDetail, searchMarketplace } from "../services/marketplace.js";
15
16
  import { listWizards } from "../services/wizards.js";
@@ -35,7 +36,6 @@ async function usageOf(tenantId) {
35
36
  }
36
37
  return (await res.json());
37
38
  }
38
- const NOT_LINKED = "This install is not linked to an account. Settings › Account signs one in; then credits, cloud publishing and plans apply. Docs and the gallery work without one.";
39
39
  export function knowsTools(ctx) {
40
40
  const { user } = ctx;
41
41
  // The entries this turn's searches found, so show_templates needs no second request.
@@ -43,7 +43,7 @@ export function knowsTools(ctx) {
43
43
  return {
44
44
  docs_search: createTool({
45
45
  id: "docs_search",
46
- description: "Search the engenty wizards user guide and plugin guide of this installed version. Gives the best sections with an excerpt and their engenty.ai/docs link. Use it before you explain how something works.",
46
+ description: prompt("goose", "tool.docs_search"),
47
47
  inputSchema: z.object({ query: z.string().min(2).max(200) }),
48
48
  execute: async ({ query }) => {
49
49
  ctx.doing(serverText(ctx.lang, "doingReadGuide"));
@@ -52,7 +52,7 @@ export function knowsTools(ctx) {
52
52
  }),
53
53
  docs_read: createTool({
54
54
  id: "docs_read",
55
- description: "Read one page of the guides by its id from docs_search (user/steps, dev/plugins/tools), from a character on.",
55
+ description: prompt("goose", "tool.docs_read"),
56
56
  inputSchema: z.object({
57
57
  page: z.string().min(1).max(200),
58
58
  from: z.number().int().min(0).optional(),
@@ -64,7 +64,7 @@ export function knowsTools(ctx) {
64
64
  }),
65
65
  authoring_guide: createTool({
66
66
  id: "authoring_guide",
67
- description: "The authoring guide the wizard editor and AI apps build with: how a wizard is written (steps, fields, flows, tools, outputs, model classes). Long: read it in parts with `from`.",
67
+ description: prompt("goose", "tool.authoring_guide"),
68
68
  inputSchema: z.object({ from: z.number().int().min(0).optional() }),
69
69
  execute: ({ from }) => attempt(async () => {
70
70
  ctx.doing(serverText(ctx.lang, "doingAuthoringGuide"));
@@ -78,7 +78,7 @@ export function knowsTools(ctx) {
78
78
  }),
79
79
  gallery_search: createTool({
80
80
  id: "gallery_search",
81
- description: "Search the gallery of wizard templates (engenty.ai/wizards and the plugins' starters): title, pitch, what it needs that this install has no model for, and its price per run in credits.",
81
+ description: prompt("goose", "tool.gallery_search"),
82
82
  inputSchema: z.object({ query: z.string().max(200).optional() }),
83
83
  execute: ({ query }) => attempt(async () => {
84
84
  ctx.doing(serverText(ctx.lang, "doingGallery"));
@@ -109,7 +109,7 @@ export function knowsTools(ctx) {
109
109
  }),
110
110
  gallery_detail: createTool({
111
111
  id: "gallery_detail",
112
- description: "One template of the gallery: what it does, its steps, what it makes and needs.",
112
+ description: prompt("goose", "tool.gallery_detail"),
113
113
  inputSchema: z.object({ id: z.string().min(1).max(120) }),
114
114
  execute: ({ id }) => attempt(async () => {
115
115
  const detail = await marketplaceDetail(id, asLang(ctx.lang));
@@ -122,7 +122,7 @@ export function knowsTools(ctx) {
122
122
  }),
123
123
  show_templates: createTool({
124
124
  id: "show_templates",
125
- description: "Show templates of the gallery as cards under your answer, in the order given. A card shows the title, the pitch, the time, the cost and what it makes; the person opens it to see the steps and make a wizard of it.",
125
+ description: prompt("goose", "tool.show_templates"),
126
126
  inputSchema: z.object({ ids: z.array(z.string().min(1).max(120)).min(1).max(6) }),
127
127
  execute: ({ ids }) => attempt(async () => {
128
128
  const entries = [];
@@ -144,7 +144,7 @@ export function knowsTools(ctx) {
144
144
  }),
145
145
  plans: createTool({
146
146
  id: "plans",
147
- description: "The plans organizations can be on (Free, Pro, Team): price a month, monthly credits, limits, and the credit packages to buy on top. Live from the account service.",
147
+ description: prompt("goose", "tool.plans"),
148
148
  inputSchema: z.object({}),
149
149
  execute: () => attempt(async () => {
150
150
  ctx.doing(serverText(ctx.lang, "doingPlans"));
@@ -154,7 +154,7 @@ export function knowsTools(ctx) {
154
154
  }),
155
155
  account: createTool({
156
156
  id: "account",
157
- description: "The person, their organization, their role, the organization's plan, the credit balance and credits that end on a date.",
157
+ description: prompt("goose", "tool.account"),
158
158
  inputSchema: z.object({}),
159
159
  execute: () => attempt(async () => {
160
160
  ctx.doing(serverText(ctx.lang, "doingAccount"));
@@ -169,14 +169,14 @@ export function knowsTools(ctx) {
169
169
  };
170
170
  }
171
171
  if (!(await linkedAccount())) {
172
- return { linked: false, note: NOT_LINKED };
172
+ return { linked: false, note: prompt("goose", "note.not_linked") };
173
173
  }
174
174
  const overview = await accountOverview();
175
175
  if (!overview) {
176
176
  return {
177
177
  linked: true,
178
178
  signedIn: false,
179
- note: "The sign-in ran out: Settings › Account signs in again.",
179
+ note: prompt("goose", "note.signed_out"),
180
180
  };
181
181
  }
182
182
  return {
@@ -192,16 +192,16 @@ export function knowsTools(ctx) {
192
192
  }),
193
193
  usage: createTool({
194
194
  id: "usage",
195
- description: "Credits the organization used per month (the last three), and the runs and wizards that cost the most.",
195
+ description: prompt("goose", "tool.usage"),
196
196
  inputSchema: z.object({}),
197
197
  execute: () => attempt(async () => {
198
198
  ctx.doing(serverText(ctx.lang, "doingUsage"));
199
199
  if (!(managed || (await linkedAccount()))) {
200
- return { linked: false, note: NOT_LINKED };
200
+ return { linked: false, note: prompt("goose", "note.not_linked") };
201
201
  }
202
202
  const usage = await usageOf(user.tenantId);
203
203
  if (!usage) {
204
- return { note: "The sign-in ran out: Settings › Account signs in again." };
204
+ return { note: prompt("goose", "note.signed_out") };
205
205
  }
206
206
  const runIds = [...new Set(usage.months.flatMap((m) => m.runs.map((r) => r.runId)))];
207
207
  const runs = runIds.length
@@ -236,7 +236,7 @@ export function knowsTools(ctx) {
236
236
  }),
237
237
  wizards: createTool({
238
238
  id: "wizards",
239
- description: "The space's wizards: title, description, published or draft, whether its link is on, steps, last change.",
239
+ description: prompt("goose", "tool.wizards"),
240
240
  inputSchema: z.object({}),
241
241
  execute: () => attempt(async () => {
242
242
  if (!ctx.project) {
@@ -258,7 +258,7 @@ export function knowsTools(ctx) {
258
258
  }),
259
259
  runs: createTool({
260
260
  id: "runs",
261
- description: "The space's latest runs, newest first: wizard, test or live, status, the error of a failed one.",
261
+ description: prompt("goose", "tool.runs"),
262
262
  inputSchema: z.object({
263
263
  status: z.enum(["failed", "done", "running", "waiting_input", "cancelled"]).optional(),
264
264
  limit: z.number().int().min(1).max(40).optional(),
@@ -294,7 +294,7 @@ export function knowsTools(ctx) {
294
294
  }),
295
295
  models: createTool({
296
296
  id: "models",
297
- description: "What thinks and makes for this install, per model class: an installed AI client, an own key, a local model, credits, or nothing (with the problem). Also which AI clients are installed and signed in.",
297
+ description: prompt("goose", "tool.models"),
298
298
  inputSchema: z.object({}),
299
299
  execute: () => attempt(async () => {
300
300
  ctx.doing(serverText(ctx.lang, "doingModels"));
@@ -313,7 +313,7 @@ export function knowsTools(ctx) {
313
313
  }),
314
314
  chats_search: createTool({
315
315
  id: "chats_search",
316
- description: "Search the person's earlier chats with you (their messages and summaries) for words: what was asked, changed or decided before.",
316
+ description: prompt("goose", "tool.chats_search"),
317
317
  inputSchema: z.object({ query: z.string().min(3).max(200) }),
318
318
  execute: ({ query }) => attempt(async () => {
319
319
  ctx.doing(serverText(ctx.lang, "doingEarlierChats"));
@@ -332,7 +332,7 @@ export function knowsTools(ctx) {
332
332
  }),
333
333
  chat_read: createTool({
334
334
  id: "chat_read",
335
- description: "Read one earlier chat by its id (from chats_search): its summary and messages.",
335
+ description: prompt("goose", "tool.chat_read"),
336
336
  inputSchema: z.object({ id: z.string().min(1).max(40) }),
337
337
  execute: ({ id }) => attempt(async () => {
338
338
  const chat = await readChat(user, id);
@@ -21,6 +21,8 @@ function redirectUri() {
21
21
  /**
22
22
  * The address that links an account. `signup`: the person has none yet — the account's sign-up
23
23
  * page takes the invitation code (`code` fills it in) and goes on to the same sign-in.
24
+ * `organization` (its id or address) names the organization to sign in to: a member gets it
25
+ * without the picker, a switch.
24
26
  */
25
27
  export async function startLink(options = {}) {
26
28
  const d = await discovery(env.local.accountUrl);
@@ -36,6 +38,7 @@ export async function startLink(options = {}) {
36
38
  code_challenge: createHash("sha256").update(verifier).digest("base64url"),
37
39
  code_challenge_method: "S256",
38
40
  state: seal(state),
41
+ ...(options.organization ? { organization: options.organization } : {}),
39
42
  }).toString();
40
43
  if (!options.signup) {
41
44
  return url.toString();
@@ -50,21 +53,47 @@ export async function startLink(options = {}) {
50
53
  return signUp.toString();
51
54
  }
52
55
  let cached = null;
56
+ /** The organization last written to the settings, so an unchanged one is not written again. */
57
+ let rememberedOrganization = null;
53
58
  /**
54
59
  * Keeps what the token endpoint handed out: the refresh token in the vault, the account in the
55
- * settings. The browser flow (finishLink) and the device flow (device.ts) end here alike.
60
+ * settings. The browser flow (finishLink) and the device flow (device.ts) end here alike. A
61
+ * token for another organization than before is a switch: the sync of the one before is
62
+ * forgotten first, so nothing of it goes up to the new one (sync/client.ts).
56
63
  */
57
64
  export async function keep(tokens) {
58
65
  const claims = unverifiedClaims(tokens.access_token);
59
66
  if (!claims) {
60
67
  throw new Error("The account's token names no tenant.");
61
68
  }
69
+ const before = await linkedAccount();
70
+ const switched = Boolean(before && before.tenantId !== claims.tenantId);
71
+ const oldRefresh = switched ? await vaultGet(REFRESH) : null;
72
+ if (switched) {
73
+ cached = null;
74
+ // Loaded here: the sync reads the account this module keeps.
75
+ const [{ forgetCloud }, sync, { withTenant }, { LOCAL_TENANT }] = await Promise.all([
76
+ import("../services/cloud.js"),
77
+ import("../sync/client.js"),
78
+ import("../db/client.js"),
79
+ import("../tenants/tenant.js"),
80
+ ]);
81
+ // The browser's callback and a terminal come here without the install's tenant.
82
+ await withTenant(LOCAL_TENANT, async () => {
83
+ await sync.noteSyncedSpaces();
84
+ await forgetCloud();
85
+ await sync.keepUnsyncedHere();
86
+ });
87
+ rememberedOrganization = null;
88
+ await deleteSetting(ORGANIZATION);
89
+ }
62
90
  if (tokens.refresh_token) {
63
91
  await vaultSet(REFRESH, tokens.refresh_token);
64
92
  }
65
93
  cached = {
66
94
  token: tokens.access_token,
67
95
  expiresAt: Date.now() + (tokens.expires_in ?? 600) * 1000,
96
+ tenantId: claims.tenantId,
68
97
  };
69
98
  const account = {
70
99
  userId: claims.userId,
@@ -73,8 +102,23 @@ export async function keep(tokens) {
73
102
  email: claims.email,
74
103
  };
75
104
  await writeSetting("account", account);
105
+ if (oldRefresh && oldRefresh !== tokens.refresh_token) {
106
+ await revoke(oldRefresh);
107
+ }
76
108
  return account;
77
109
  }
110
+ /** Ends a refresh token at the Manage-App; a Manage-App out of reach lets it run out by itself. */
111
+ async function revoke(refresh) {
112
+ const d = await discovery(env.local.accountUrl).catch(() => null);
113
+ if (d?.revocation_endpoint) {
114
+ await fetch(d.revocation_endpoint, {
115
+ method: "POST",
116
+ headers: { "content-type": "application/x-www-form-urlencoded" },
117
+ body: new URLSearchParams({ token: refresh, client_id: CLIENT.id }),
118
+ signal: AbortSignal.timeout(10_000),
119
+ }).catch(() => undefined);
120
+ }
121
+ }
78
122
  export async function finishLink(code, rawState) {
79
123
  const state = unseal(rawState);
80
124
  if (!state || state.exp < Date.now()) {
@@ -95,7 +139,11 @@ export function linkedAccount() {
95
139
  /** A fresh access token of the linked account, or null when none is linked (or it was revoked). */
96
140
  export async function accountToken() {
97
141
  if (cached && cached.expiresAt - Date.now() > 60_000) {
98
- return cached.token;
142
+ // `wizards account switch` in a terminal changes the account under a runtime that runs.
143
+ if ((await linkedAccount())?.tenantId === cached.tenantId) {
144
+ return cached.token;
145
+ }
146
+ cached = null;
99
147
  }
100
148
  // One refresh at a time: a refresh token is used once, a second caller would be refused.
101
149
  refreshing ??= refreshAccount().finally(() => {
@@ -121,15 +169,7 @@ async function refreshAccount() {
121
169
  export async function unlink() {
122
170
  const refresh = await vaultGet(REFRESH);
123
171
  if (refresh) {
124
- const d = await discovery(env.local.accountUrl).catch(() => null);
125
- if (d?.revocation_endpoint) {
126
- await fetch(d.revocation_endpoint, {
127
- method: "POST",
128
- headers: { "content-type": "application/x-www-form-urlencoded" },
129
- body: new URLSearchParams({ token: refresh, client_id: CLIENT.id }),
130
- signal: AbortSignal.timeout(10_000),
131
- }).catch(() => undefined);
132
- }
172
+ await revoke(refresh);
133
173
  }
134
174
  cached = null;
135
175
  await vaultDelete(REFRESH);
@@ -140,7 +180,6 @@ export async function unlink() {
140
180
  export function knownOrganization() {
141
181
  return readSetting(ORGANIZATION);
142
182
  }
143
- let rememberedOrganization = null;
144
183
  async function rememberOrganization(tenant) {
145
184
  const same = `${tenant.id}\n${tenant.name}\n${tenant.balanceCredits}`;
146
185
  if (same === rememberedOrganization) {
@@ -74,6 +74,8 @@ const WISH_MAX = 600;
74
74
  const STATE_COOKIE = "wz_oauth";
75
75
  const SESSION_DAYS = 30;
76
76
  const SCOPE = "openid profile email offline_access wizards:read wizards:write wizards:publish runs:test";
77
+ /** Marks the state of a sign-in started again (nanoid never makes a dot). */
78
+ const AGAIN = "again.";
77
79
  // The desktop app shows a server in its window but signs in through the system browser
78
80
  // (Google refuses embedded views). The finished session travels back as a one-time code in an
79
81
  // `engenty-wizards://` link; it only counts in the window that asked for it, which holds the
@@ -272,7 +274,8 @@ export const authRoutes = new Hono()
272
274
  const ticket = unseal(c.req.query("desktop") ?? "");
273
275
  const state = {
274
276
  verifier,
275
- nonce: nanoid(16),
277
+ // A second try after a sign-in whose state stayed in another browser: marked, so it runs once.
278
+ nonce: c.req.query("again") === "1" ? `${AGAIN}${nanoid(16)}` : nanoid(16),
276
279
  returnTo: safeReturn(c.req.query("return")),
277
280
  exp: Date.now() + 15 * 60_000,
278
281
  ...(ticket && ticket.exp > Date.now() ? { desktop: ticket.desktop } : {}),
@@ -331,9 +334,19 @@ export const authRoutes = new Hono()
331
334
  }
332
335
  const state = unseal(getCookie(c, STATE_COOKIE) ?? "");
333
336
  deleteCookie(c, STATE_COOKIE, { path: `${basePath}/api/auth` });
334
- if (!code || !state || state.exp < Date.now() || state.nonce !== rawState) {
337
+ if (!code) {
335
338
  return c.redirect(`${home}?signin=failed`);
336
339
  }
340
+ if (!state || state.exp < Date.now() || state.nonce !== rawState) {
341
+ // The sign-in began in another browser (the e-mail link opened on the phone): its state is
342
+ // there. The account is signed in here now, so a sign-in started here goes through without
343
+ // a page. Once: a second miss is a failure.
344
+ if (rawState.startsWith(AGAIN)) {
345
+ return c.redirect(`${home}?signin=failed`);
346
+ }
347
+ const again = new URLSearchParams({ again: "1", return: home });
348
+ return c.redirect(`${basePath}/api/auth/login?${again}`);
349
+ }
337
350
  try {
338
351
  const tokens = await tokenRequest({
339
352
  grant_type: "authorization_code",