@engenty/wizards-runtime 0.19.1 → 0.20.1

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 (166) hide show
  1. package/apps/runtime/dist/agents/architect.js +4 -4
  2. package/apps/runtime/dist/agents/studio-assistant.js +2 -31
  3. package/apps/runtime/dist/app.js +4 -4
  4. package/apps/runtime/dist/assistant/knows.js +2 -2
  5. package/apps/runtime/dist/auth/index.js +1 -1
  6. package/apps/runtime/dist/authoring/example.js +1 -1
  7. package/apps/runtime/dist/authoring/guide.js +35 -6
  8. package/apps/runtime/dist/broker/account.js +85 -16
  9. package/apps/runtime/dist/broker/call.js +137 -37
  10. package/apps/runtime/dist/broker/log.js +19 -5
  11. package/apps/runtime/dist/broker/rwx.js +12 -9
  12. package/apps/runtime/dist/cli/main.js +2 -0
  13. package/apps/runtime/dist/connectors/index.js +52 -11
  14. package/apps/runtime/dist/connectors/person-connections.js +279 -0
  15. package/apps/runtime/dist/connectors/person-sign-ins.js +74 -3
  16. package/apps/runtime/dist/connectors/same-service.js +14 -0
  17. package/apps/runtime/dist/connectors/space-choice.js +116 -0
  18. package/apps/runtime/dist/connectors/space-connections.js +40 -2
  19. package/apps/runtime/dist/db/client.js +8 -0
  20. package/apps/runtime/dist/db/kept-accounts.js +88 -0
  21. package/apps/runtime/dist/db/migrations/tenant/0075_person_connection.sql +25 -0
  22. package/apps/runtime/dist/db/migrations/tenant/0076_clients_in_spaces.sql +28 -0
  23. package/apps/runtime/dist/db/migrations/tenant/0077_client_spaces_at_root.sql +21 -0
  24. package/apps/runtime/dist/db/migrations/tenant/meta/0075_snapshot.json +7859 -0
  25. package/apps/runtime/dist/db/migrations/tenant/meta/0076_snapshot.json +7859 -0
  26. package/apps/runtime/dist/db/migrations/tenant/meta/0077_snapshot.json +7859 -0
  27. package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +21 -0
  28. package/apps/runtime/dist/db/schema.js +67 -16
  29. package/apps/runtime/dist/docs/dev/api.md +8 -8
  30. package/apps/runtime/dist/docs/dev/wizard-format/index.md +3 -1
  31. package/apps/runtime/dist/docs/user-guide/command-line.md +2 -1
  32. package/apps/runtime/dist/elements/caller.js +1 -1
  33. package/apps/runtime/dist/elements/knowledge.js +5 -5
  34. package/apps/runtime/dist/elements/wizards.js +7 -11
  35. package/apps/runtime/dist/engine/notices.js +13 -1
  36. package/apps/runtime/dist/engine/requirements.js +116 -3
  37. package/apps/runtime/dist/engine/run-needs.js +58 -0
  38. package/apps/runtime/dist/engine/runner.js +209 -16
  39. package/apps/runtime/dist/engine/starts.js +9 -0
  40. package/apps/runtime/dist/engine/types.js +5 -1
  41. package/apps/runtime/dist/harness/claude.js +3 -1
  42. package/apps/runtime/dist/manage.js +1 -1
  43. package/apps/runtime/dist/mcp/tools.js +3 -3
  44. package/apps/runtime/dist/plugins/runs.js +2 -1
  45. package/apps/runtime/dist/prompts/authoring.md +13 -3
  46. package/apps/runtime/dist/prompts/goose.md +0 -5
  47. package/apps/runtime/dist/routes/api.js +9 -4
  48. package/apps/runtime/dist/routes/client-contract.js +2 -2
  49. package/apps/runtime/dist/routes/client-spaces.js +1 -16
  50. package/apps/runtime/dist/routes/connections.js +6 -1
  51. package/apps/runtime/dist/routes/marketplace.js +27 -7
  52. package/apps/runtime/dist/routes/plugins.js +1 -1
  53. package/apps/runtime/dist/routes/runs.js +157 -11
  54. package/apps/runtime/dist/routes/studio.js +42 -5
  55. package/apps/runtime/dist/services/client-portal.js +58 -49
  56. package/apps/runtime/dist/services/client-spaces.js +57 -125
  57. package/apps/runtime/dist/services/links.js +3 -3
  58. package/apps/runtime/dist/services/marketplace.js +6 -2
  59. package/apps/runtime/dist/services/members-studio.js +1 -1
  60. package/apps/runtime/dist/services/query-vectors.js +1 -1
  61. package/apps/runtime/dist/services/runs.js +19 -20
  62. package/apps/runtime/dist/services/space-parent.js +4 -11
  63. package/apps/runtime/dist/services/spaces.js +56 -47
  64. package/apps/runtime/dist/services/work-ai.js +3 -3
  65. package/apps/runtime/dist/store/index.js +28 -8
  66. package/apps/runtime/dist/store/shared-lists.js +2 -2
  67. package/apps/runtime/dist/sync/hub.js +9 -5
  68. package/apps/runtime/dist/tools/connector.js +4 -2
  69. package/apps/web/dist/assets/{AboutDialog-BUWu36Mb.js → AboutDialog-BFi6vOyJ.js} +1 -1
  70. package/apps/web/dist/assets/{BlockEditor-1-EvUIta.js → BlockEditor-C44bI_ih.js} +1 -1
  71. package/apps/web/dist/assets/{Bundle-RNkjBwAL.js → Bundle-DZyQ1FP7.js} +1 -1
  72. package/apps/web/dist/assets/CapabilitiesPage-DAX03vkY.js +2 -0
  73. package/apps/web/dist/assets/{ChangelogDialog-C_ZZLRZT.js → ChangelogDialog-CdchxTO8.js} +1 -1
  74. package/apps/web/dist/assets/{CodeEditor-BEJKIMd0.js → CodeEditor-BRufUwu0.js} +1 -1
  75. package/apps/web/dist/assets/ConnectorsSection-CNpieoyT.js +1 -0
  76. package/apps/web/dist/assets/EditorPage-CxABBMqo.js +3 -0
  77. package/apps/web/dist/assets/{FlowPreview-ptI86Ogs.js → FlowPreview-aj58c-gH.js} +1 -1
  78. package/apps/web/dist/assets/{LangSwitch-BNa_H8AR.js → LangSwitch-BNkytlus.js} +1 -1
  79. package/apps/web/dist/assets/Marketplace-D3hdvrkz.js +2 -0
  80. package/apps/web/dist/assets/NewWizardChannels-0aZoziks.js +1 -0
  81. package/apps/web/dist/assets/NewWizardPage-Bn2BPaUB.js +7 -0
  82. package/apps/web/dist/assets/OnboardingPage-DwF6KdQy.js +1 -0
  83. package/apps/web/dist/assets/ProtocolSection-Ce5LBBzL.js +1 -0
  84. package/apps/web/dist/assets/PublicRunner-Bp4DxTrD.js +1 -0
  85. package/apps/web/dist/assets/{ReadOnly-YF0RkR7P.js → ReadOnly-BFVaKM3w.js} +1 -1
  86. package/apps/web/dist/assets/{Results-DJRLiVo0.js → Results--mJFsNH2.js} +1 -1
  87. package/apps/web/dist/assets/{RunDrawer-CSpTNJp-.js → RunDrawer-DtbxGBIm.js} +1 -1
  88. package/apps/web/dist/assets/SettingsPage-Cytcl_9w.js +2 -0
  89. package/apps/web/dist/assets/SetupPage-B5zCrIKT.js +1 -0
  90. package/apps/web/dist/assets/{SharePage-OiKEnmL1.js → SharePage-CgQp_PT6.js} +1 -1
  91. package/apps/web/dist/assets/SkillEditor-ARx8QPGp.js +1 -0
  92. package/apps/web/dist/assets/Skills-frfXXEcF.js +9 -0
  93. package/apps/web/dist/assets/SpacePage-Bd5-wBUc.js +2 -0
  94. package/apps/web/dist/assets/StudioHome-DzVpWMrD.js +1 -0
  95. package/apps/web/dist/assets/TableEditor-CRhc6jI6.js +7 -0
  96. package/apps/web/dist/assets/{UpdateCheck-BpdsLIOc.js → UpdateCheck-BEruHgs0.js} +2 -2
  97. package/apps/web/dist/assets/{brand-ByQY-UcL.js → brand-DKuVyYhH.js} +1 -1
  98. package/apps/web/dist/assets/changelog-BgFhbmMa.js +1 -0
  99. package/apps/web/dist/assets/{code-editor-B8zG80PA.js → code-editor-BLwDuQLI.js} +2 -2
  100. package/apps/web/dist/assets/host-B2ZzDrkc.js +69 -0
  101. package/apps/web/dist/assets/i18n-Dyi0kvaA.js +55 -0
  102. package/apps/web/dist/assets/index-C1m_S1ls.js +102 -0
  103. package/apps/web/dist/assets/{index-D18zQ05f.css → index-CduFlFCp.css} +1 -1
  104. package/apps/web/dist/assets/{read-aloud-spC7eEBp.js → read-aloud-DGS8mWgC.js} +1 -1
  105. package/apps/web/dist/assets/session-EIDP3Wzc.js +1 -0
  106. package/apps/web/dist/assets/theme-B46aPLtX.js +14 -0
  107. package/apps/web/dist/assets/ui-DSgksc1H.js +16 -0
  108. package/apps/web/dist/assets/{useMutation-CoEdB_9_.js → useMutation-fT44ij_b.js} +1 -1
  109. package/apps/web/dist/assets/{viewers-BmcrgvXX.js → viewers-DvA5VsXw.js} +2 -2
  110. package/apps/web/dist/index.html +18 -13
  111. package/apps/web/dist/mcp/flow.html +62 -62
  112. package/bin/bot.mjs +1120 -0
  113. package/bin/wizards.mjs +6 -0
  114. package/node_modules/@engenty/wizards-shared/dist/catalog-prompt.js +2 -2
  115. package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +67 -0
  116. package/node_modules/@engenty/wizards-shared/dist/definition.d.ts +10324 -7
  117. package/node_modules/@engenty/wizards-shared/dist/definition.js +32 -6
  118. package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +17 -23
  119. package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +17 -23
  120. package/node_modules/@engenty/wizards-shared/dist/json-schema.js +3 -3
  121. package/node_modules/@engenty/wizards-shared/dist/marketplace-search.js +7 -1
  122. package/node_modules/@engenty/wizards-shared/dist/marketplace.d.ts +9 -2
  123. package/node_modules/@engenty/wizards-shared/dist/page-data.d.ts +72 -0
  124. package/node_modules/@engenty/wizards-shared/dist/page-data.js +5 -0
  125. package/node_modules/@engenty/wizards-shared/dist/page-look.d.ts +17 -0
  126. package/node_modules/@engenty/wizards-shared/dist/page-look.js +118 -0
  127. package/node_modules/@engenty/wizards-shared/dist/page-styles.d.ts +6 -0
  128. package/node_modules/@engenty/wizards-shared/dist/page-styles.js +98 -0
  129. package/node_modules/@engenty/wizards-shared/dist/page-texts.d.ts +36 -0
  130. package/node_modules/@engenty/wizards-shared/dist/page-texts.js +119 -0
  131. package/node_modules/@engenty/wizards-shared/dist/requires.js +2 -0
  132. package/node_modules/@engenty/wizards-shared/dist/run.d.ts +54 -1
  133. package/node_modules/@engenty/wizards-shared/dist/run.js +23 -0
  134. package/node_modules/@engenty/wizards-shared/dist/runner-texts.d.ts +27 -1
  135. package/node_modules/@engenty/wizards-shared/dist/runner-texts.js +26 -0
  136. package/node_modules/@engenty/wizards-shared/dist/store.d.ts +24 -1
  137. package/node_modules/@engenty/wizards-shared/dist/transition.d.ts +2 -1
  138. package/node_modules/@engenty/wizards-shared/dist/transition.js +5 -1
  139. package/node_modules/@engenty/wizards-shared/dist/wizard-text.js +1 -1
  140. package/package.json +1 -1
  141. package/plugin/.claude-plugin/plugin.json +1 -1
  142. package/plugin/plugin.json +1 -1
  143. package/apps/web/dist/assets/CapabilitiesPage-fgTP28Mn.js +0 -2
  144. package/apps/web/dist/assets/ConnectorsSection-iLrduYak.js +0 -1
  145. package/apps/web/dist/assets/EditorPage-CRZte0O1.js +0 -3
  146. package/apps/web/dist/assets/Marketplace-9aGWG2pJ.js +0 -2
  147. package/apps/web/dist/assets/NewWizardChannels-BFDm9vCT.js +0 -1
  148. package/apps/web/dist/assets/NewWizardPage-ueGFlLDo.js +0 -7
  149. package/apps/web/dist/assets/OnboardingPage-DtDd7k_O.js +0 -1
  150. package/apps/web/dist/assets/PreviewPane-CEltrf_-.js +0 -7
  151. package/apps/web/dist/assets/ProtocolSection-Bb3c44Te.js +0 -1
  152. package/apps/web/dist/assets/PublicRunner-BaTg24s3.js +0 -1
  153. package/apps/web/dist/assets/SettingsPage--_ap3omw.js +0 -2
  154. package/apps/web/dist/assets/SetupPage-ELKHbmnE.js +0 -1
  155. package/apps/web/dist/assets/SkillEditor-C1_zwNOQ.js +0 -1
  156. package/apps/web/dist/assets/Skills-_pLGtOjH.js +0 -9
  157. package/apps/web/dist/assets/SpacePage-r4EbxEJe.js +0 -2
  158. package/apps/web/dist/assets/StudioHome-CwvxI29m.js +0 -1
  159. package/apps/web/dist/assets/changelog-Dt-V-BKp.js +0 -1
  160. package/apps/web/dist/assets/host-Ckjz94Ea.js +0 -69
  161. package/apps/web/dist/assets/i18n-ClCOlfx2.js +0 -55
  162. package/apps/web/dist/assets/index-BHKh0A9F.js +0 -10
  163. package/apps/web/dist/assets/runners-DNqzwMQ0.js +0 -1
  164. package/apps/web/dist/assets/session-Dd9duhPc.js +0 -1
  165. package/apps/web/dist/assets/theme-DumM6FI_.js +0 -14
  166. package/apps/web/dist/assets/ui-BjhZhw8x.js +0 -16
@@ -0,0 +1,279 @@
1
+ import { featureOn } from "@engenty/wizards-shared/features";
2
+ import { and, eq, getTableColumns, inArray, notExists } from "drizzle-orm";
3
+ import { nanoid } from "nanoid";
4
+ import { inAudience, whoOf } from "../broker/index.js";
5
+ import { db, schema } from "../db/client.js";
6
+ import { currentFeatures } from "../features.js";
7
+ import { seal } from "../secrets/crypto.js";
8
+ import { roleOf } from "../services/access.js";
9
+ import { candidates } from "./index.js";
10
+ import { sameService } from "./same-service.js";
11
+ import { listSpaceConnections, spaceConnectionOf, } from "./space-connections.js";
12
+ const { secret: _secret, ...PUBLIC } = getTableColumns(schema.personConnection);
13
+ const NONE = { candidates: [], chosen: null, by: null };
14
+ /** Whether the switch for the new reach is on for the tenant at hand. */
15
+ export async function runConnectionsOn() {
16
+ return featureOn(await currentFeatures().catch(() => null), "runConnections");
17
+ }
18
+ /** For whom the space remembers a choice: the runs nobody watches. */
19
+ export const spaceHolder = (spaceId) => `s:${spaceId}`;
20
+ /** A run nobody of the team watches (a start's, a channel's), as the checks and the studio read it. */
21
+ export const unwatchedScope = (wizardId) => ({
22
+ wizardId,
23
+ holder: "r:",
24
+ unwatched: true,
25
+ });
26
+ /**
27
+ * A connection of the space an admin may choose for the runs nobody watches: one that signs in
28
+ * as the space, is signed in, and is not the admins' alone. Nobody there signs in for themselves.
29
+ * The admin's choice is what lets such a run use it; its audience would count the run as a guest.
30
+ */
31
+ const unwatchedUsable = (row) => row.signIn === "space" && row.secret !== null && row.audience !== "admins";
32
+ /** The need's connectors by id, with the ones of the same service read as the need's. */
33
+ async function needConnectors(need, spaceId) {
34
+ const connectors = await candidates(need, spaceId);
35
+ const asNeed = new Map(connectors.map((c) => [c.id, c]));
36
+ for (const c of connectors) {
37
+ for (const id of sameService(c.id)) {
38
+ if (!asNeed.has(id)) {
39
+ asNeed.set(id, c);
40
+ }
41
+ }
42
+ }
43
+ return asNeed;
44
+ }
45
+ /**
46
+ * The connections of the space an admin may choose for a need, for the runs nobody watches
47
+ * (`unwatchedUsable`). Only the admin sees these; such a run sees the one chosen.
48
+ */
49
+ export async function unwatchedOptions(scope, spaceId, need) {
50
+ const asNeed = await needConnectors(need, spaceId);
51
+ const out = [];
52
+ for (const row of await listSpaceConnections(homeOf(scope, spaceId))) {
53
+ const connector = asNeed.get(row.connectorId);
54
+ if (connector && unwatchedUsable(row)) {
55
+ out.push({ kind: "space", row, connector });
56
+ }
57
+ }
58
+ return out;
59
+ }
60
+ /** The space a run is in: the one it carries, else the wizard's. */
61
+ const homeOf = (scope, spaceId) => scope.clientSpaceId ?? spaceId;
62
+ async function whoOfHolder(holder) {
63
+ return holder.startsWith("u:") ? whoOf(holder, await roleOf(holder.slice(2))) : whoOf(holder);
64
+ }
65
+ /** A connection of the space someone may use: in their audience and signed in. */
66
+ async function spaceUsable(row, who) {
67
+ if (!inAudience(row.audience, who)) {
68
+ return false;
69
+ }
70
+ if (row.signIn === "space") {
71
+ return row.secret !== null;
72
+ }
73
+ if (!who.id || who.kind === "guest") {
74
+ return false;
75
+ }
76
+ const own = await db.query.spaceConnectionSignIn.findFirst({
77
+ where: and(eq(schema.spaceConnectionSignIn.connectionId, row.id), eq(schema.spaceConnectionSignIn.userId, who.id)),
78
+ columns: { userId: true },
79
+ });
80
+ return own !== undefined;
81
+ }
82
+ /**
83
+ * The connections a run may use for one of its wizard's needs, and the one to use: the
84
+ * remembered choice while it is still a candidate, else the only candidate, else none.
85
+ */
86
+ export async function connectionsFor(scope, spaceId, need) {
87
+ const asNeed = await needConnectors(need, spaceId);
88
+ if (!asNeed.size) {
89
+ return NONE;
90
+ }
91
+ const home = homeOf(scope, spaceId);
92
+ const holders = [
93
+ scope.holder,
94
+ // A run nobody watches uses what an admin chose for the space.
95
+ ...(scope.unwatched ? [spaceHolder(home)] : []),
96
+ ];
97
+ const choices = await db.query.connectionChoice.findMany({
98
+ where: and(eq(schema.connectionChoice.wizardId, scope.wizardId), eq(schema.connectionChoice.need, need.id), inArray(schema.connectionChoice.holder, holders)),
99
+ });
100
+ const reach = await runConnectionsOn();
101
+ if (scope.unwatched) {
102
+ return unwatchedFor(scope, home, asNeed, choices, reach);
103
+ }
104
+ const choice = choices.find((c) => c.holder === scope.holder);
105
+ const found = [];
106
+ const own = await db
107
+ .select(PUBLIC)
108
+ .from(schema.personConnection)
109
+ .where(and(eq(schema.personConnection.holder, scope.holder), inArray(schema.personConnection.connectorId, [...asNeed.keys()])));
110
+ for (const row of own) {
111
+ const connector = asNeed.get(row.connectorId);
112
+ if (connector && (reach || row.id === choice?.personConnectionId)) {
113
+ found.push({ kind: "person", row, connector });
114
+ }
115
+ }
116
+ if (reach) {
117
+ const who = await whoOfHolder(scope.holder);
118
+ for (const row of await listSpaceConnections(home)) {
119
+ const connector = asNeed.get(row.connectorId);
120
+ if (connector && (await spaceUsable(row, who))) {
121
+ found.push({ kind: "space", row, connector });
122
+ }
123
+ }
124
+ }
125
+ const remembered = choice
126
+ ? found.find((u) => u.kind === "person"
127
+ ? u.row.id === choice.personConnectionId
128
+ : u.row.id === choice.spaceConnectionId)
129
+ : undefined;
130
+ if (remembered) {
131
+ return { candidates: found, chosen: remembered, by: "choice" };
132
+ }
133
+ return found.length === 1
134
+ ? { candidates: found, chosen: found[0], by: "only" }
135
+ : { candidates: found, chosen: null, by: null };
136
+ }
137
+ /**
138
+ * A run nobody of the team watches: its own accounts where it has any (a channel's person may
139
+ * have connected one), and of the space's connections only the one an admin chose for such runs,
140
+ * which it sees and uses but cannot choose itself. No only candidate is taken: nobody chose it.
141
+ */
142
+ async function unwatchedFor(scope, home, asNeed, choices, reach) {
143
+ const own = choices.find((c) => c.holder === scope.holder && c.personConnectionId);
144
+ const forSpace = choices.find((c) => c.holder === spaceHolder(home) && c.spaceConnectionId);
145
+ const found = [];
146
+ const rows = await db
147
+ .select(PUBLIC)
148
+ .from(schema.personConnection)
149
+ .where(and(eq(schema.personConnection.holder, scope.holder), inArray(schema.personConnection.connectorId, [...asNeed.keys()])));
150
+ for (const row of rows) {
151
+ const connector = asNeed.get(row.connectorId);
152
+ if (connector && (reach || row.id === own?.personConnectionId)) {
153
+ found.push({ kind: "person", row, connector });
154
+ }
155
+ }
156
+ const space = reach && forSpace ? await spaceConnectionOf(home, forSpace.spaceConnectionId ?? "") : null;
157
+ const spaceConnector = space ? asNeed.get(space.connectorId) : undefined;
158
+ if (space && spaceConnector && unwatchedUsable(space)) {
159
+ found.push({ kind: "space", row: space, connector: spaceConnector });
160
+ }
161
+ const chosen = found.find((u) => u.kind === "person" && u.row.id === own?.personConnectionId) ??
162
+ found.find((u) => u.kind === "space");
163
+ return chosen
164
+ ? { candidates: found, chosen, by: "choice" }
165
+ : { candidates: found, chosen: null, by: null };
166
+ }
167
+ // --- writing ---------------------------------------------------------------------
168
+ /**
169
+ * Keeps an account a person (or a visitor) signed in to: one row per address and service, so a
170
+ * second sign-in to the same address replaces the tokens of the first.
171
+ */
172
+ export async function saveConnection(holder, connectorId, label, data) {
173
+ const secret = seal(data);
174
+ const existing = await db.query.personConnection.findFirst({
175
+ where: and(eq(schema.personConnection.holder, holder), inArray(schema.personConnection.connectorId, sameService(connectorId)), eq(schema.personConnection.label, label)),
176
+ columns: { id: true },
177
+ });
178
+ if (existing) {
179
+ const [row] = await db
180
+ .update(schema.personConnection)
181
+ .set({ connectorId, secret, updatedAt: new Date() })
182
+ .where(eq(schema.personConnection.id, existing.id))
183
+ .returning(PUBLIC);
184
+ return row;
185
+ }
186
+ const [row] = await db
187
+ .insert(schema.personConnection)
188
+ .values({ id: nanoid(14), holder, connectorId, label, secret })
189
+ .returning(PUBLIC);
190
+ return row;
191
+ }
192
+ /** Remembers which connection a wizard uses for a need, for one holder. */
193
+ export async function remember(wizardId, need, holder, to) {
194
+ const target = to.kind === "person"
195
+ ? { personConnectionId: to.row.id, spaceConnectionId: null }
196
+ : { personConnectionId: null, spaceConnectionId: to.row.id };
197
+ await db
198
+ .insert(schema.connectionChoice)
199
+ .values({ wizardId, need, holder, ...target })
200
+ .onConflictDoUpdate({
201
+ target: [
202
+ schema.connectionChoice.wizardId,
203
+ schema.connectionChoice.need,
204
+ schema.connectionChoice.holder,
205
+ ],
206
+ set: { ...target, chosenAt: new Date() },
207
+ });
208
+ }
209
+ /**
210
+ * Forgets choices of a wizard for one holder: one need's, or all of them. A person's connection
211
+ * no choice points at any more goes with it; one another wizard uses stays.
212
+ */
213
+ export async function forget(wizardId, holder, need) {
214
+ const gone = await db
215
+ .delete(schema.connectionChoice)
216
+ .where(and(eq(schema.connectionChoice.wizardId, wizardId), eq(schema.connectionChoice.holder, holder), need === undefined ? undefined : eq(schema.connectionChoice.need, need)))
217
+ .returning({ id: schema.connectionChoice.personConnectionId });
218
+ await dropUnchosen(gone.flatMap((g) => (g.id ? [g.id] : [])));
219
+ }
220
+ /** Deletes those of the person's connections that no wizard chose. */
221
+ async function dropUnchosen(ids) {
222
+ if (!ids.length) {
223
+ return;
224
+ }
225
+ await db
226
+ .delete(schema.personConnection)
227
+ .where(and(inArray(schema.personConnection.id, ids), notExists(db
228
+ .select({ id: schema.connectionChoice.wizardId })
229
+ .from(schema.connectionChoice)
230
+ .where(eq(schema.connectionChoice.personConnectionId, schema.personConnection.id)))));
231
+ }
232
+ /**
233
+ * What a wizard remembers for a holder, as „Was dieser Wizard sich merkt“ lists it: one entry
234
+ * per chosen connection, under the slot the wizard's account had in its store before.
235
+ */
236
+ export async function chosenAccounts(wizardId, holder) {
237
+ const rows = await db
238
+ .select({
239
+ need: schema.connectionChoice.need,
240
+ person: {
241
+ connectorId: schema.personConnection.connectorId,
242
+ label: schema.personConnection.label,
243
+ createdAt: schema.personConnection.createdAt,
244
+ },
245
+ space: {
246
+ connectorId: schema.spaceConnection.connectorId,
247
+ label: schema.spaceConnection.label,
248
+ name: schema.spaceConnection.name,
249
+ setUpAt: schema.spaceConnection.setUpAt,
250
+ },
251
+ })
252
+ .from(schema.connectionChoice)
253
+ .leftJoin(schema.personConnection, eq(schema.personConnection.id, schema.connectionChoice.personConnectionId))
254
+ .leftJoin(schema.spaceConnection, eq(schema.spaceConnection.id, schema.connectionChoice.spaceConnectionId))
255
+ .where(and(eq(schema.connectionChoice.wizardId, wizardId), eq(schema.connectionChoice.holder, holder)));
256
+ return rows.flatMap((r) => {
257
+ if (r.person) {
258
+ return [
259
+ {
260
+ slot: `connection:${r.need}`,
261
+ provider: r.person.connectorId,
262
+ label: r.person.label,
263
+ createdAt: r.person.createdAt.toISOString(),
264
+ },
265
+ ];
266
+ }
267
+ if (r.space) {
268
+ return [
269
+ {
270
+ slot: `connection:${r.need}`,
271
+ provider: r.space.connectorId,
272
+ label: r.space.label ?? r.space.name,
273
+ createdAt: r.space.setUpAt.toISOString(),
274
+ },
275
+ ];
276
+ }
277
+ return [];
278
+ });
279
+ }
@@ -1,8 +1,9 @@
1
- import { eq } from "drizzle-orm";
1
+ import { and, desc, eq } from "drizzle-orm";
2
2
  import { inAudience } from "../broker/index.js";
3
3
  import { db, schema } from "../db/client.js";
4
4
  import { managed, tenantMembers } from "../manage.js";
5
5
  import { isAdminRole } from "../services/access.js";
6
+ import { notFound } from "../services/errors.js";
6
7
  import { userProfile } from "../services/profile.js";
7
8
  import { listSpaces } from "../services/spaces.js";
8
9
  import { currentTenant } from "../tenants/tenant.js";
@@ -15,6 +16,11 @@ import { listSpaceConnections } from "./space-connections.js";
15
16
  *
16
17
  * Every sign-in belongs to a connection of a space: Goose uses the person's sign-ins to those
17
18
  * (`agents/goose-connections.ts`), so there are none „only for Goose“ to list yet.
19
+ *
20
+ * Above them the person's own connections (`person_connection` of `u:<id>`,
21
+ * docs/plans/run-connections.md): the accounts they connected in a run, which count in every space
22
+ * of theirs, with the wizards that chose each. Disconnecting one deletes it and every choice that
23
+ * names it. Listed with `runConnections` on or off.
18
24
  */
19
25
  /** Names of the organization's people by id; alone, the one person. */
20
26
  export async function namesOf(user) {
@@ -24,6 +30,67 @@ export async function namesOf(user) {
24
30
  const people = await tenantMembers(currentTenant()).catch(() => null);
25
31
  return new Map((people?.members ?? []).map((m) => [m.userId, m.name]));
26
32
  }
33
+ /** The person's own connections, newest first, with the wizards that chose each. */
34
+ async function ownConnections(user, spaceIds) {
35
+ const rows = await db
36
+ .select({
37
+ id: schema.personConnection.id,
38
+ connectorId: schema.personConnection.connectorId,
39
+ label: schema.personConnection.label,
40
+ createdAt: schema.personConnection.createdAt,
41
+ })
42
+ .from(schema.personConnection)
43
+ .where(eq(schema.personConnection.holder, `u:${user.id}`))
44
+ .orderBy(desc(schema.personConnection.createdAt));
45
+ if (!rows.length) {
46
+ return [];
47
+ }
48
+ const chosen = await db
49
+ .selectDistinct({
50
+ connection: schema.connectionChoice.personConnectionId,
51
+ id: schema.wizard.id,
52
+ title: schema.wizard.title,
53
+ })
54
+ .from(schema.connectionChoice)
55
+ .innerJoin(schema.wizard, eq(schema.wizard.id, schema.connectionChoice.wizardId))
56
+ .where(eq(schema.connectionChoice.holder, `u:${user.id}`));
57
+ const names = new Map();
58
+ for (const row of rows) {
59
+ if (!names.has(row.connectorId)) {
60
+ let name = null;
61
+ for (const spaceId of spaceIds) {
62
+ name = (await resolveConnector(spaceId, row.connectorId))?.connector.name ?? null;
63
+ if (name) {
64
+ break;
65
+ }
66
+ }
67
+ names.set(row.connectorId, name);
68
+ }
69
+ }
70
+ return rows.map((row) => ({
71
+ id: row.id,
72
+ connectorId: row.connectorId,
73
+ connectorName: names.get(row.connectorId) ?? null,
74
+ label: row.label,
75
+ createdAt: row.createdAt.toISOString(),
76
+ wizards: chosen
77
+ .filter((c) => c.connection === row.id)
78
+ .map((c) => ({ id: c.id, title: c.title }))
79
+ .sort((a, b) => a.title.localeCompare(b.title)),
80
+ }));
81
+ }
82
+ /** Disconnects one of the person's own connections: the account goes, and every choice naming it. */
83
+ export async function disconnectOwn(user, id) {
84
+ const mine = and(eq(schema.personConnection.id, id), eq(schema.personConnection.holder, `u:${user.id}`));
85
+ const row = await db.query.personConnection.findFirst({ where: mine, columns: { id: true } });
86
+ if (!row) {
87
+ throw notFound();
88
+ }
89
+ await db
90
+ .delete(schema.connectionChoice)
91
+ .where(eq(schema.connectionChoice.personConnectionId, row.id));
92
+ await db.delete(schema.personConnection).where(mine);
93
+ }
27
94
  export async function personSignIns(user) {
28
95
  const who = { kind: isAdminRole(user.role) ? "admin" : "person", id: user.id };
29
96
  const own = await db.query.spaceConnectionSignIn.findMany({
@@ -31,7 +98,8 @@ export async function personSignIns(user) {
31
98
  });
32
99
  let names = null;
33
100
  const spaces = [];
34
- for (const space of await listSpaces(user.id)) {
101
+ const theirs = await listSpaces(user.id);
102
+ for (const space of theirs) {
35
103
  const rows = (await listSpaceConnections(space.id)).filter((row) => inAudience(row.audience, who));
36
104
  if (rows.length && rows.some((row) => row.setUpBy) && !names) {
37
105
  names = await namesOf(user);
@@ -70,5 +138,8 @@ export async function personSignIns(user) {
70
138
  }
71
139
  spaces.push({ id: space.id, name: space.name, connections });
72
140
  }
73
- return { spaces };
141
+ return {
142
+ own: await ownConnections(user, theirs.map((s) => s.id)),
143
+ spaces,
144
+ };
74
145
  }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Connectors of one service: one sign-in serves kind `mail` and the service's own connector,
3
+ * one account per address (docs/plans/run-connections.md, decided 2026-11-14). No imports: the
4
+ * database's own conversion reads it while a tenant opens (`db/kept-accounts.ts`).
5
+ */
6
+ const SAME_SERVICE = [
7
+ ["mail-gmail", "google-gmail"],
8
+ ["mail-outlook", "microsoft-outlook"],
9
+ ];
10
+ /** The connector ids that share one account with `connectorId`, itself first. */
11
+ export function sameService(connectorId) {
12
+ const ids = SAME_SERVICE.find((s) => s.includes(connectorId)) ?? [];
13
+ return [connectorId, ...ids.filter((id) => id !== connectorId)];
14
+ }
@@ -0,0 +1,116 @@
1
+ import { unavoidableSteps } from "@engenty/wizards-shared/fit";
2
+ import { note, saidText } from "@engenty/wizards-shared/run";
3
+ import { missingConnectionsSaid, stepsUsing } from "../engine/requirements.js";
4
+ import { requireAdmin } from "../services/access.js";
5
+ import { notFound } from "../services/errors.js";
6
+ import { usable } from "./builtin.js";
7
+ import { candidates } from "./index.js";
8
+ import { connectionsFor, forget, remember, runConnectionsOn, spaceHolder, unwatchedOptions, unwatchedScope, } from "./person-connections.js";
9
+ import { listSpaceConnections } from "./space-connections.js";
10
+ function accountView(u) {
11
+ return {
12
+ id: u.row.id,
13
+ owner: u.kind,
14
+ connectorName: u.connector.name,
15
+ label: u.kind === "person" ? u.row.label : (u.row.label ?? u.row.name),
16
+ };
17
+ }
18
+ /** The needs of a wizard's draft as `viewer` sees them; an admin also sees the space's choice. */
19
+ export async function wizardNeeds(w, viewer, lang) {
20
+ const def = w.draft;
21
+ const needs = def.connections ?? [];
22
+ if (!needs.length) {
23
+ return [];
24
+ }
25
+ const unavoidable = unavoidableSteps(def);
26
+ const missing = new Map((await missingConnectionsSaid(def, w.spaceId, viewer.admin)).map((m) => [m.id, m]));
27
+ const forSpace = viewer.admin && (await runConnectionsOn());
28
+ const person = { wizardId: w.id, holder: `u:${viewer.userId}` };
29
+ const views = [];
30
+ for (const need of needs) {
31
+ const connectors = await candidates(need, w.spaceId);
32
+ const steps = stepsUsing(def, need.id);
33
+ const view = {
34
+ id: need.id,
35
+ name: need.title ?? (need.connector ? (connectors[0]?.name ?? need.connector) : null),
36
+ kind: need.kind ?? null,
37
+ steps: steps.map((s) => ({ id: s.id, title: s.title })),
38
+ unavoidable: steps.some((s) => unavoidable.has(s.id)),
39
+ };
40
+ views.push({
41
+ ...view,
42
+ here: await resolvesHere(need, connectors, missing.get(need.id)?.problem, person, w, lang),
43
+ ...(forSpace && !need.spaceConnection ? { space: await spaceChoice(w, need) } : {}),
44
+ });
45
+ }
46
+ return views;
47
+ }
48
+ async function resolvesHere(need, connectors, problem, person, w, lang) {
49
+ if (need.spaceConnection) {
50
+ const row = (await listSpaceConnections(w.spaceId)).find((r) => r.id === need.spaceConnection);
51
+ if (row) {
52
+ const connector = connectors.find((c) => c.id === row.connectorId);
53
+ return {
54
+ state: "named",
55
+ account: {
56
+ id: row.id,
57
+ owner: "space",
58
+ connectorName: connector?.name ?? row.connectorId,
59
+ label: row.label ?? row.name,
60
+ },
61
+ };
62
+ }
63
+ return { state: "cannot", problem: saidText(note("notFound"), lang) };
64
+ }
65
+ let can = false;
66
+ for (const c of connectors) {
67
+ can ||= await usable(c);
68
+ }
69
+ if (!can) {
70
+ return {
71
+ state: "cannot",
72
+ problem: saidText(problem ?? note("connectorNotInSpace", { connector: need.connector ?? need.id }), lang),
73
+ };
74
+ }
75
+ const found = await connectionsFor(person, w.spaceId, need);
76
+ if (found.chosen && found.by) {
77
+ return { state: found.by === "choice" ? "chosen" : "only", account: accountView(found.chosen) };
78
+ }
79
+ return found.candidates.length
80
+ ? { state: "choose", count: found.candidates.length }
81
+ : { state: "connect" };
82
+ }
83
+ /** The space's connections that fit a need for a run nobody watches, and the one chosen. */
84
+ async function spaceChoice(w, need) {
85
+ const found = await connectionsFor(unwatchedScope(w.id), w.spaceId, need);
86
+ return {
87
+ chosen: found.chosen?.kind === "space" ? found.chosen.row.id : null,
88
+ options: (await unwatchedOptions(unwatchedScope(w.id), w.spaceId, need)).map(accountView),
89
+ };
90
+ }
91
+ function needOf(w, needId) {
92
+ const need = (w.draft.connections ?? []).find((c) => c.id === needId && !c.spaceConnection);
93
+ if (!need) {
94
+ throw notFound();
95
+ }
96
+ return need;
97
+ }
98
+ /** Chooses the connection of the space a wizard's runs nobody watches use for a need. Admins only. */
99
+ export async function chooseForSpace(w, needId, connectionId) {
100
+ await requireAdmin();
101
+ if (!(await runConnectionsOn())) {
102
+ throw notFound();
103
+ }
104
+ const need = needOf(w, needId);
105
+ const options = await unwatchedOptions(unwatchedScope(w.id), w.spaceId, need);
106
+ const target = options.find((u) => u.row.id === connectionId);
107
+ if (!target) {
108
+ throw notFound();
109
+ }
110
+ await remember(w.id, need.id, spaceHolder(w.spaceId), target);
111
+ }
112
+ /** Clears the space's choice for a need: runs nobody watches no longer start. Admins only. */
113
+ export async function clearForSpace(w, needId) {
114
+ await requireAdmin();
115
+ await forget(w.id, spaceHolder(w.spaceId), needOf(w, needId).id);
116
+ }
@@ -18,6 +18,8 @@ import { currentTenant } from "../tenants/tenant.js";
18
18
  import { connectorFetch, resolveEnv, signInFetch, viaAccount } from "./builtin.js";
19
19
  import { resolveConnector } from "./external.js";
20
20
  import { connectRedirectUri as redirectUri } from "./index.js";
21
+ import { remember, spaceHolder } from "./person-connections.js";
22
+ import { sameService } from "./same-service.js";
21
23
  import { standInUrl } from "./stand-ins.js";
22
24
  import { AccountConnectError, redeemTicket, startThroughAccount } from "./via-account.js";
23
25
  export const rulesSchema = z.object(Object.fromEntries(CONNECTION_ACTION_KINDS.map((k) => [k, z.enum(CONNECTION_OUTCOMES)])));
@@ -258,6 +260,39 @@ plugin = null) {
258
260
  .returning();
259
261
  return row;
260
262
  }
263
+ /**
264
+ * The connector a connection of the space uses for an account a run connects with `connectorId`:
265
+ * itself, or the service's own (kind `mail` signs in to Gmail as `mail-gmail`, the space keeps
266
+ * `google-gmail`). Null: the space can't keep it as a connection (a mailbox over IMAP).
267
+ */
268
+ export async function spaceConnectorFor(spaceId, connectorId) {
269
+ for (const id of sameService(connectorId)) {
270
+ const found = await resolveConnector(spaceId, id);
271
+ if (found && found.connector.auth.kind !== "browser") {
272
+ return found.connector.id;
273
+ }
274
+ }
275
+ return null;
276
+ }
277
+ /**
278
+ * An admin connects an account for the space from inside a run (docs/plans/run-connections.md,
279
+ * decision 2): a connection of the space that signs in as the space, under the space's default
280
+ * rules, and the space's choice for the wizard's need, and the admin's own. One the admin began
281
+ * here and never signed in is taken again, not set up twice. The sign-in follows, as the space:
282
+ * `startSpaceConnectionOAuth` or `signInWithCredentials`.
283
+ */
284
+ export async function spaceConnectionForNeed(userId, spaceId, need, connectorId) {
285
+ const begun = (await listSpaceConnections(spaceId)).find((r) => r.connectorId === connectorId &&
286
+ r.signIn === "space" &&
287
+ r.secret === null &&
288
+ r.setUpBy === userId);
289
+ const row = begun ??
290
+ (await createSpaceConnection(userId, spaceId, newConnectionSchema.parse({ connectorId, name: need.name, signIn: "space" })));
291
+ for (const holder of [spaceHolder(spaceId), need.holder]) {
292
+ await remember(need.wizardId, need.id, holder, { kind: "space", row });
293
+ }
294
+ return row;
295
+ }
261
296
  export async function updateSpaceConnection(userId, id, patch) {
262
297
  const row = await spaceConnectionById(id);
263
298
  await ownedSpace(userId, row.spaceId);
@@ -498,7 +533,9 @@ function scopesOf(connector, actions) {
498
533
  return [...scopes];
499
534
  }
500
535
  /** The provider's sign-in page for a connection; the callback (`/api/connect/callback`) finishes it. */
501
- export async function startSpaceConnectionOAuth(id, as, lang) {
536
+ export async function startSpaceConnectionOAuth(id, as, lang,
537
+ /** The run whose connect card started it. */
538
+ runId) {
502
539
  const row = await spaceConnectionById(id);
503
540
  await allowSignIn(row, as);
504
541
  const connector = await connectorOfRow(row);
@@ -512,6 +549,7 @@ export async function startSpaceConnectionOAuth(id, as, lang) {
512
549
  userId: as.as === "person" ? as.userId : null,
513
550
  exp: Date.now() + 15 * 60_000,
514
551
  lang,
552
+ ...(runId ? { runId } : {}),
515
553
  };
516
554
  if (await viaAccount(connector)) {
517
555
  // The Manage-App keeps the PKCE verifier; ours stays empty.
@@ -586,7 +624,7 @@ export async function finishSpaceConnectionOAuth(answer, rawState) {
586
624
  throw new Error("The connection no longer signs in per person.");
587
625
  }
588
626
  await keepSignIn(row, as, account.label, stored);
589
- return { connectionId: row.id };
627
+ return { connectionId: row.id, runId: state.runId ?? null };
590
628
  }
591
629
  /** Forgets a sign-in: the space's (admins) or the person's own. */
592
630
  export async function removeSignIn(id, as) {
@@ -9,6 +9,7 @@ import { migrate } from "drizzle-orm/libsql/migrator";
9
9
  import { env } from "../env.js";
10
10
  import { currentTenant, inTenant } from "../tenants/tenant.js";
11
11
  import * as control from "./control-schema.js";
12
+ import { moveKeptAccounts } from "./kept-accounts.js";
12
13
  import * as schema from "./schema.js";
13
14
  mkdirSync(join(env.dataDir, "tenants"), { recursive: true });
14
15
  const here = dirname(fileURLToPath(import.meta.url));
@@ -284,6 +285,13 @@ async function openTenantNow(id) {
284
285
  client.close();
285
286
  throw err;
286
287
  }
288
+ // The accounts wizards kept become their holders' connections; a failure keeps them where
289
+ // they are until the next start, and the tenant opens anyway.
290
+ await whileBusy(() => moveKeptAccounts(db)).then((moved) => {
291
+ if (moved.choices) {
292
+ console.log(`[accounts ${id}] ${moved.choices} kept accounts moved: ${moved.accounts} new connections, ${moved.reused} already there`);
293
+ }
294
+ }, (err) => console.error(`[accounts ${id}] kept accounts stay in the store until the next start:`, err));
287
295
  for (const hook of openHooks) {
288
296
  await hook(id, client);
289
297
  }