@engenty/wizards-runtime 0.13.0 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/runtime/dist/agents/architect.js +8 -7
- package/apps/runtime/dist/agents/goose-connections.js +82 -0
- package/apps/runtime/dist/agents/space-agent.js +9 -2
- package/apps/runtime/dist/agents/studio-assistant.js +101 -67
- package/apps/runtime/dist/agents/website.js +1 -1
- package/apps/runtime/dist/app.js +17 -1
- package/apps/runtime/dist/assistant/knows.js +6 -5
- package/apps/runtime/dist/authoring/guide.js +25 -5
- package/apps/runtime/dist/broker/account.js +166 -0
- package/apps/runtime/dist/broker/call.js +417 -0
- package/apps/runtime/dist/broker/caller.js +10 -0
- package/apps/runtime/dist/broker/grant.js +152 -0
- package/apps/runtime/dist/broker/host.js +51 -0
- package/apps/runtime/dist/broker/index.js +8 -0
- package/apps/runtime/dist/broker/kept.js +31 -0
- package/apps/runtime/dist/broker/log.js +240 -0
- package/apps/runtime/dist/broker/registry.js +9 -0
- package/apps/runtime/dist/broker/rwx.js +367 -0
- package/apps/runtime/dist/broker/send.js +189 -0
- package/apps/runtime/dist/connectors/builtin.js +1 -1
- package/apps/runtime/dist/connectors/external.js +38 -37
- package/apps/runtime/dist/connectors/index.js +30 -91
- package/apps/runtime/dist/connectors/mail.js +0 -8
- package/apps/runtime/dist/connectors/person-sign-ins.js +73 -0
- package/apps/runtime/dist/connectors/plugin-connections.js +65 -92
- package/apps/runtime/dist/connectors/smtp.js +1 -1
- package/apps/runtime/dist/connectors/space-connections.js +436 -0
- package/apps/runtime/dist/db/adopt.js +3 -3
- package/apps/runtime/dist/db/client.js +9 -0
- package/apps/runtime/dist/db/live-triggers.js +65 -23
- package/apps/runtime/dist/db/migrations/tenant/0027_work_chats.sql +52 -0
- package/apps/runtime/dist/db/migrations/tenant/0028_chat_approvals.sql +17 -0
- package/apps/runtime/dist/db/migrations/tenant/0029_work_chats_live.sql +49 -0
- package/apps/runtime/dist/db/migrations/tenant/0031_space.sql +624 -0
- package/apps/runtime/dist/db/migrations/tenant/0032_rwx_rule.sql +18 -0
- package/apps/runtime/dist/db/migrations/tenant/0033_broker_log.sql +23 -0
- package/apps/runtime/dist/db/migrations/tenant/0034_space_connection.sql +35 -0
- package/apps/runtime/dist/db/migrations/tenant/0035_run_grant.sql +1 -0
- package/apps/runtime/dist/db/migrations/tenant/0036_approval_held_for.sql +1 -0
- package/apps/runtime/dist/db/migrations/tenant/0037_ways_out.sql +5 -0
- package/apps/runtime/dist/db/migrations/tenant/0038_heard.sql +11 -0
- package/apps/runtime/dist/db/migrations/tenant/0039_members_studio.sql +1 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0027_snapshot.json +383 -155
- package/apps/runtime/dist/db/migrations/tenant/meta/0028_snapshot.json +4468 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0029_snapshot.json +4475 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0030_snapshot.json +4629 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0031_snapshot.json +4629 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0032_snapshot.json +4757 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0033_snapshot.json +5039 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0034_snapshot.json +5022 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0035_snapshot.json +5029 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0036_snapshot.json +5037 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0037_snapshot.json +5076 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0038_snapshot.json +5145 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/0039_snapshot.json +5153 -0
- package/apps/runtime/dist/db/migrations/tenant/meta/_journal.json +86 -2
- package/apps/runtime/dist/db/schema.js +295 -72
- package/apps/runtime/dist/docs/dev/architecture.md +215 -0
- package/apps/runtime/dist/docs/dev/broker.md +298 -0
- package/apps/runtime/dist/docs/dev/index.md +5 -1
- package/apps/runtime/dist/docs/dev/integration/index.md +2 -0
- package/apps/runtime/dist/docs/dev/meta.json +3 -0
- package/apps/runtime/dist/docs/dev/plugins/connections.md +8 -5
- package/apps/runtime/dist/docs/dev/plugins/events.md +1 -1
- package/apps/runtime/dist/docs/dev/plugins/examples.md +1 -0
- package/apps/runtime/dist/docs/dev/plugins/index.md +2 -2
- package/apps/runtime/dist/docs/dev/plugins/reference.md +3 -2
- package/apps/runtime/dist/docs/dev/plugins/space.md +16 -6
- package/apps/runtime/dist/docs/dev/plugins/studio.md +2 -2
- package/apps/runtime/dist/docs/dev/plugins/tools.md +0 -1
- package/apps/runtime/dist/docs/dev/skills.md +16 -9
- package/apps/runtime/dist/docs/dev/wizard-format/agent-steps.md +40 -5
- package/apps/runtime/dist/docs/dev/wizard-format/lists-and-connections.md +17 -2
- package/apps/runtime/dist/docs/dev/wizard-format/templates.md +2 -0
- package/apps/runtime/dist/docs/dev/wizard-format/views-and-widgets.md +22 -2
- package/apps/runtime/dist/docs/user-guide/capabilities.md +132 -0
- package/apps/runtime/dist/docs/user-guide/cloud-sync.md +2 -0
- package/apps/runtime/dist/docs/user-guide/command-line.md +1 -0
- package/apps/runtime/dist/docs/user-guide/connectors.md +63 -7
- package/apps/runtime/dist/docs/user-guide/index.md +10 -1
- package/apps/runtime/dist/docs/user-guide/meta.json +6 -1
- package/apps/runtime/dist/docs/user-guide/protocol.md +80 -0
- package/apps/runtime/dist/docs/user-guide/skills.md +8 -4
- package/apps/runtime/dist/docs/user-guide/space.md +5 -4
- package/apps/runtime/dist/docs/user-guide/together.md +16 -2
- package/apps/runtime/dist/docs/user-guide/troubleshooting.md +2 -2
- package/apps/runtime/dist/docs/user-guide/work-mode.md +128 -0
- package/apps/runtime/dist/engenty/connections-external/build-connector.js +2 -5
- package/apps/runtime/dist/engenty/connections-external/importer/classify.js +72 -0
- package/apps/runtime/dist/engenty/connections-google/connectors/gmail.js +1 -1
- package/apps/runtime/dist/engenty/connections-microsoft/outlook.js +3 -2
- package/apps/runtime/dist/engenty/connections-sdk/types.js +2 -0
- package/apps/runtime/dist/engenty/connections-slack/connector.js +2 -1
- package/apps/runtime/dist/engine/resources.js +43 -12
- package/apps/runtime/dist/engine/runner.js +75 -23
- package/apps/runtime/dist/engine/steps.js +30 -12
- package/apps/runtime/dist/engine/template.js +18 -1
- package/apps/runtime/dist/env.js +9 -4
- package/apps/runtime/dist/index.js +18 -2
- package/apps/runtime/dist/live/feed.js +2 -2
- package/apps/runtime/dist/live/origin.js +2 -2
- package/apps/runtime/dist/live/views.js +51 -26
- package/apps/runtime/dist/manage.js +7 -0
- package/apps/runtime/dist/mcp/flow-app.js +1 -1
- package/apps/runtime/dist/mcp/tools.js +75 -34
- package/apps/runtime/dist/models.js +1 -1
- package/apps/runtime/dist/motion-graphics/project.js +8 -8
- package/apps/runtime/dist/motion-graphics/tools.js +1 -1
- package/apps/runtime/dist/plugins/events.js +2 -2
- package/apps/runtime/dist/plugins/jobs.js +4 -1
- package/apps/runtime/dist/plugins/loader.js +2 -2
- package/apps/runtime/dist/prompts/architect.md +3 -3
- package/apps/runtime/dist/prompts/authoring.md +46 -12
- package/apps/runtime/dist/prompts/goose.md +7 -7
- package/apps/runtime/dist/prompts/mcp.md +6 -6
- package/apps/runtime/dist/prompts/services.md +4 -4
- package/apps/runtime/dist/prompts/step.md +2 -2
- package/apps/runtime/dist/prompts/tools.md +39 -10
- package/apps/runtime/dist/routes/api.js +31 -20
- package/apps/runtime/dist/routes/broker.js +316 -0
- package/apps/runtime/dist/routes/connections.js +71 -0
- package/apps/runtime/dist/routes/delivery.js +25 -0
- package/apps/runtime/dist/routes/discover.js +17 -0
- package/apps/runtime/dist/routes/live.js +11 -1
- package/apps/runtime/dist/routes/person.js +4 -1
- package/apps/runtime/dist/routes/plugins.js +3 -1
- package/apps/runtime/dist/routes/rules.js +26 -0
- package/apps/runtime/dist/routes/runs.js +54 -33
- package/apps/runtime/dist/routes/skills.js +6 -6
- package/apps/runtime/dist/routes/studio.js +153 -144
- package/apps/runtime/dist/routes/work.js +199 -0
- package/apps/runtime/dist/sandbox/index.js +27 -0
- package/apps/runtime/dist/services/access.js +38 -17
- package/apps/runtime/dist/services/api.js +38 -13
- package/apps/runtime/dist/services/architect.js +3 -3
- package/apps/runtime/dist/services/assistant-chats.js +9 -1
- package/apps/runtime/dist/services/brand.js +12 -12
- package/apps/runtime/dist/services/broker-bell.js +69 -0
- package/apps/runtime/dist/services/broker-notify.js +127 -0
- package/apps/runtime/dist/services/client-steps.js +79 -0
- package/apps/runtime/dist/services/cloud.js +42 -42
- package/apps/runtime/dist/services/command-risk.js +51 -0
- package/apps/runtime/dist/services/discover.js +85 -0
- package/apps/runtime/dist/services/knowledge-model.js +13 -13
- package/apps/runtime/dist/services/knowledge.js +117 -80
- package/apps/runtime/dist/services/manage-reports.js +74 -7
- package/apps/runtime/dist/services/members-studio.js +165 -0
- package/apps/runtime/dist/services/onboarding.js +22 -22
- package/apps/runtime/dist/services/package-file.js +1 -1
- package/apps/runtime/dist/services/package.js +22 -22
- package/apps/runtime/dist/services/pages.js +7 -7
- package/apps/runtime/dist/services/runs.js +4 -3
- package/apps/runtime/dist/services/seen.js +55 -0
- package/apps/runtime/dist/services/shares.js +23 -13
- package/apps/runtime/dist/services/site.js +23 -23
- package/apps/runtime/dist/services/skills-registry.js +15 -15
- package/apps/runtime/dist/services/skills.js +44 -44
- package/apps/runtime/dist/services/space-categories.js +35 -35
- package/apps/runtime/dist/services/space-data.js +130 -111
- package/apps/runtime/dist/services/{project-files.js → space-files.js} +84 -75
- package/apps/runtime/dist/services/{project-index.js → space-index.js} +116 -73
- package/apps/runtime/dist/services/space-origin.js +19 -11
- package/apps/runtime/dist/services/spaces.js +478 -612
- package/apps/runtime/dist/services/synced-spaces.js +668 -0
- package/apps/runtime/dist/services/themes.js +15 -15
- package/apps/runtime/dist/services/widgets.js +6 -6
- package/apps/runtime/dist/services/wizards.js +112 -38
- package/apps/runtime/dist/services/work-ai.js +257 -0
- package/apps/runtime/dist/services/work-approvals.js +104 -0
- package/apps/runtime/dist/services/work-chats.js +908 -0
- package/apps/runtime/dist/services/work-connections.js +90 -0
- package/apps/runtime/dist/services/work-files.js +85 -0
- package/apps/runtime/dist/services/work-mastra.js +73 -0
- package/apps/runtime/dist/services/work-sandbox.js +42 -0
- package/apps/runtime/dist/sharing/files.js +14 -4
- package/apps/runtime/dist/sharing/index.js +40 -39
- package/apps/runtime/dist/sharing/jobs.js +67 -17
- package/apps/runtime/dist/sharing/targets/connector.js +10 -6
- package/apps/runtime/dist/sharing/targets/email.js +10 -8
- package/apps/runtime/dist/sharing/targets/slack.js +10 -8
- package/apps/runtime/dist/sharing/targets/storage.js +6 -4
- package/apps/runtime/dist/store/index.js +14 -3
- package/apps/runtime/dist/store/shared-lists.js +4 -2
- package/apps/runtime/dist/sync/apply.js +2 -2
- package/apps/runtime/dist/sync/client.js +113 -113
- package/apps/runtime/dist/sync/hub.js +41 -41
- package/apps/runtime/dist/sync/log.js +12 -12
- package/apps/runtime/dist/sync/records.js +118 -120
- package/apps/runtime/dist/texts.js +38 -2
- package/apps/runtime/dist/tools/connections.js +112 -0
- package/apps/runtime/dist/tools/connector.js +157 -67
- package/apps/runtime/dist/tools/index.js +28 -13
- package/apps/runtime/dist/tools/mail.js +40 -11
- package/apps/runtime/dist/tools/pages.js +11 -5
- package/apps/runtime/dist/tools/plugin.js +43 -7
- package/apps/runtime/dist/tools/skills.js +1 -1
- package/apps/runtime/dist/tools/{project.js → space.js} +30 -25
- package/apps/runtime/dist/tools/store.js +3 -2
- package/apps/runtime/dist/widgets/step.js +10 -10
- package/apps/web/dist/assets/AboutDialog-DgfeipUc.js +1 -0
- package/apps/web/dist/assets/CapabilitiesPage-BoYJvgIu.js +2 -0
- package/apps/web/dist/assets/{ChangelogDialog-SwyId00t.js → ChangelogDialog-Duab4zTO.js} +1 -1
- package/apps/web/dist/assets/{CodeEditor-BwZsk5Al.js → CodeEditor-nxoOt8ge.js} +1 -1
- package/apps/web/dist/assets/EditorPage-ZrgGpYMC.js +3 -0
- package/apps/web/dist/assets/{FlowPreview-DtSpjVTl.js → FlowPreview-aMfwcPul.js} +1 -1
- package/apps/web/dist/assets/LangSwitch-DpD0inR4.js +1 -0
- package/apps/web/dist/assets/Marketplace-CpzD9pNQ.js +2 -0
- package/apps/web/dist/assets/NewWizardChannels-IB18afWN.js +1 -0
- package/apps/web/dist/assets/NewWizardPage-rYbcmPGG.js +7 -0
- package/apps/web/dist/assets/OnboardingPage-ztHT01ah.js +1 -0
- package/apps/web/dist/assets/PreviewPane-DviWTLfi.js +9 -0
- package/apps/web/dist/assets/PublicRunner-C2geZhhM.js +1 -0
- package/apps/web/dist/assets/ReadOnly-kSb_Kbdm.js +1 -0
- package/apps/web/dist/assets/SettingsPage-DM2h8N0J.js +2 -0
- package/apps/web/dist/assets/SetupPage-Wfyz6xH4.js +1 -0
- package/apps/web/dist/assets/SharePage-CyWQorWB.js +1 -0
- package/apps/web/dist/assets/SkillEditor-CqQMg2MC.js +1 -0
- package/apps/web/dist/assets/Skills-CnhpgoOA.js +9 -0
- package/apps/web/dist/assets/SpacePage-q4Bk3N7k.js +2 -0
- package/apps/web/dist/assets/UpdateCheck-C2CE6CC3.js +2 -0
- package/apps/web/dist/assets/changelog-B6hN1Cp7.js +1 -0
- package/apps/web/dist/assets/circle-alert-C8Ma-bPY.js +1 -0
- package/apps/web/dist/assets/circle-check-Bu9Z3mlJ.js +1 -0
- package/apps/web/dist/assets/code-editor-CfTGqOpp.js +2 -0
- package/apps/web/dist/assets/{code-xml-TwKzzMtA.js → code-xml-B4kLFZSj.js} +1 -1
- package/apps/web/dist/assets/connection-sign-in-CIiv0t2p.js +1 -0
- package/apps/web/dist/assets/esm-Xwn4GtqG.js +7 -0
- package/apps/web/dist/assets/{eye-Brd-xPUJ.js → eye-BpoKpIdt.js} +1 -1
- package/apps/web/dist/assets/host-BrP-ENHg.css +1 -0
- package/apps/web/dist/assets/host-DJ7-p0Sc.js +118 -0
- package/apps/web/dist/assets/i18n-BJ7Ld6O6.js +55 -0
- package/apps/web/dist/assets/index-D18DvnxX.css +1 -0
- package/apps/web/dist/assets/index-D2akynS-.js +10 -0
- package/apps/web/dist/assets/logo-BpnjXTRy.js +1 -0
- package/apps/web/dist/assets/oss-credits-IdX5bc71.js +1 -0
- package/apps/web/dist/assets/{phone-DhkHteoJ.js → phone-Ctvf-Am-.js} +1 -1
- package/apps/web/dist/assets/read-aloud-Da_RSm2S.js +1 -0
- package/apps/web/dist/assets/{runners-G-XYaDgR.js → runners-CyIvJIHr.js} +1 -1
- package/apps/web/dist/assets/scroll-text-ChrjRu9Y.js +1 -0
- package/apps/web/dist/assets/session-SXPtTWRK.js +2 -0
- package/apps/web/dist/assets/theme-CbTcTFWy.js +11 -0
- package/apps/web/dist/assets/ui-Uqnx1UpK.js +82 -0
- package/apps/web/dist/assets/{upload-BYZTwJTD.js → upload-BchUnQGV.js} +1 -1
- package/apps/web/dist/assets/{useMutation-D0QP_k2-.js → useMutation-DEkZhp5c.js} +1 -1
- package/apps/web/dist/assets/{volume-2-CVHoxdGM.js → volume-2-CU_oy81Z.js} +1 -1
- package/apps/web/dist/assets/with-selector-CoMyWBAX.js +1 -0
- package/apps/web/dist/index.html +17 -10
- package/apps/web/dist/mcp/flow.html +119 -64
- package/node_modules/@engenty/wizards/dist/plugin/index.d.ts +20 -10
- package/node_modules/@engenty/wizards-shared/dist/assistant.d.ts +6 -1
- package/node_modules/@engenty/wizards-shared/dist/assistant.js +6 -1
- package/node_modules/@engenty/wizards-shared/dist/connectors.d.ts +236 -2
- package/node_modules/@engenty/wizards-shared/dist/connectors.js +52 -2
- package/node_modules/@engenty/wizards-shared/dist/definition.d.ts +150 -8
- package/node_modules/@engenty/wizards-shared/dist/definition.js +46 -11
- package/node_modules/@engenty/wizards-shared/dist/discover.d.ts +21 -0
- package/node_modules/@engenty/wizards-shared/dist/discover.js +1 -0
- package/node_modules/@engenty/wizards-shared/dist/feature-flags.d.ts +26 -2
- package/node_modules/@engenty/wizards-shared/dist/feature-flags.js +26 -2
- package/node_modules/@engenty/wizards-shared/dist/fit.js +1 -1
- package/node_modules/@engenty/wizards-shared/dist/json-schema.d.ts +1 -1
- package/node_modules/@engenty/wizards-shared/dist/json-schema.js +1 -1
- package/node_modules/@engenty/wizards-shared/dist/live.d.ts +2 -2
- package/node_modules/@engenty/wizards-shared/dist/live.js +1 -1
- package/node_modules/@engenty/wizards-shared/dist/marketplace.js +3 -1
- package/node_modules/@engenty/wizards-shared/dist/run.d.ts +54 -6
- package/node_modules/@engenty/wizards-shared/dist/run.js +85 -0
- package/node_modules/@engenty/wizards-shared/dist/runner-texts.d.ts +15 -1
- package/node_modules/@engenty/wizards-shared/dist/runner-texts.js +14 -0
- package/node_modules/@engenty/wizards-shared/dist/rwx.d.ts +42 -0
- package/node_modules/@engenty/wizards-shared/dist/rwx.js +29 -0
- package/node_modules/@engenty/wizards-shared/dist/skills.d.ts +1 -1
- package/node_modules/@engenty/wizards-shared/dist/space-data.d.ts +2 -2
- package/node_modules/@engenty/wizards-shared/dist/{projects.d.ts → spaces.d.ts} +39 -15
- package/node_modules/@engenty/wizards-shared/dist/{projects.js → spaces.js} +16 -9
- package/node_modules/@engenty/wizards-shared/dist/store.d.ts +7 -2
- package/node_modules/@engenty/wizards-shared/dist/surface.d.ts +35 -4
- package/node_modules/@engenty/wizards-shared/dist/surface.js +121 -3
- package/node_modules/@engenty/wizards-shared/dist/sync.d.ts +1 -1
- package/node_modules/@engenty/wizards-shared/dist/theme-look.js +1 -1
- package/node_modules/@engenty/wizards-shared/dist/wizard-package.d.ts +2 -2
- package/node_modules/@engenty/wizards-shared/dist/wizard-package.js +3 -3
- package/package.json +4 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/plugin.json +1 -1
- package/plugin/skills/build-wizard/SKILL.md +1 -1
- package/apps/runtime/dist/services/projects.js +0 -473
- package/apps/web/dist/assets/AboutDialog-B-JxkELB.js +0 -1
- package/apps/web/dist/assets/EditorPage-DQ_2FOzI.js +0 -3
- package/apps/web/dist/assets/Marketplace-DoH4YO3D.js +0 -2
- package/apps/web/dist/assets/NewWizardChannels-Tgoexgj4.js +0 -1
- package/apps/web/dist/assets/NewWizardPage-B24AF482.js +0 -7
- package/apps/web/dist/assets/OnboardingPage-BEvq4slJ.js +0 -1
- package/apps/web/dist/assets/PreviewPane-B_v7Y8R7.js +0 -10
- package/apps/web/dist/assets/ProjectPage-ClRuhFJo.js +0 -10
- package/apps/web/dist/assets/PublicRunner-MicrpVsv.js +0 -1
- package/apps/web/dist/assets/ReadOnly-BXjv-MSv.js +0 -1
- package/apps/web/dist/assets/SettingsPage-DY8O1r43.js +0 -2
- package/apps/web/dist/assets/SetupPage-BOVkVpMu.js +0 -1
- package/apps/web/dist/assets/SharePage-DXGzJSnR.js +0 -1
- package/apps/web/dist/assets/SkillEditor-BzzTDeaU.js +0 -1
- package/apps/web/dist/assets/changelog-BLdS-0Bj.js +0 -1
- package/apps/web/dist/assets/esm-BdxDT9Km.js +0 -7
- package/apps/web/dist/assets/i18n-8-Sw11tB.js +0 -55
- package/apps/web/dist/assets/index-OsdQFHmh.js +0 -49
- package/apps/web/dist/assets/index-QPipX5Fi.css +0 -1
- package/apps/web/dist/assets/lock-C0uxcOlq.js +0 -1
- package/apps/web/dist/assets/logo-CGNoptDg.js +0 -1
- package/apps/web/dist/assets/oss-credits-DpRWUPjD.js +0 -1
- package/apps/web/dist/assets/session-BWI-KENJ.js +0 -2
- package/apps/web/dist/assets/theme-D7krsx0_.js +0 -11
- package/apps/web/dist/assets/ui-DSXG3f49.js +0 -83
- /package/apps/runtime/dist/db/migrations/tenant/{0027_space_skill.sql → 0030_space_skill.sql} +0 -0
|
@@ -0,0 +1,908 @@
|
|
|
1
|
+
import { note } from "@engenty/wizards-shared/run";
|
|
2
|
+
import { toAISdkStream } from "@mastra/ai-sdk";
|
|
3
|
+
import { toAISdkMessages } from "@mastra/ai-sdk/ui";
|
|
4
|
+
import { RequestContext } from "@mastra/core/request-context";
|
|
5
|
+
import { and, asc, desc, eq, exists, inArray, like, max, or, sql } from "drizzle-orm";
|
|
6
|
+
import { nanoid } from "nanoid";
|
|
7
|
+
import { toolSizes } from "../agents/studio-assistant.js";
|
|
8
|
+
import { subjectsOfPerson } from "../broker/rwx.js";
|
|
9
|
+
import { canSpend } from "../credits/credits.js";
|
|
10
|
+
import { db, schema } from "../db/client.js";
|
|
11
|
+
import { managed, tenantMembers } from "../manage.js";
|
|
12
|
+
import { contextWindowOf, costOf, usageOf } from "../models.js";
|
|
13
|
+
import { assistantToolLabels } from "../tools/plugin.js";
|
|
14
|
+
import { isAdminRole } from "./access.js";
|
|
15
|
+
import { ClientSteps, stepChunk, stepParts } from "./client-steps.js";
|
|
16
|
+
import { ServiceError } from "./errors.js";
|
|
17
|
+
import { userProfile } from "./profile.js";
|
|
18
|
+
import { addSpaceFile, fileView, spaceFileContent } from "./space-files.js";
|
|
19
|
+
import { lazyTurn, MAX_STEPS, TURN_KEY, TURN_MS, toolToRun, } from "./work-ai.js";
|
|
20
|
+
import { approvalsOf, heldBy, noteOutcome, takeDecision, waitingFor } from "./work-approvals.js";
|
|
21
|
+
import { workConnectionLabels } from "./work-connections.js";
|
|
22
|
+
import { chatFiles, fileKind, messageContents, viewParts } from "./work-files.js";
|
|
23
|
+
import { LAST_MESSAGES, workMastra } from "./work-mastra.js";
|
|
24
|
+
import { dropChatSandbox } from "./work-sandbox.js";
|
|
25
|
+
/**
|
|
26
|
+
* Work's chats (behind `workMode`): chats of a space with members, in sections of the space's
|
|
27
|
+
* sidebar or in none, sub-threads as chats with a parent. A private chat is seen by its members
|
|
28
|
+
* only, any other one by everyone of the tenant, who joins it by writing in it. The messages are
|
|
29
|
+
* a Mastra memory thread per chat (work-mastra.ts); the chat row keeps what the sidebar shows.
|
|
30
|
+
*/
|
|
31
|
+
/** A chat's title from its first message, cut to this length. */
|
|
32
|
+
const TITLE_CHARS = 60;
|
|
33
|
+
/** The last message's start the sidebar keeps. */
|
|
34
|
+
const PREVIEW_CHARS = 160;
|
|
35
|
+
/** Who wrote a message of the space's AI. */
|
|
36
|
+
export const AI_AUTHOR = "ai";
|
|
37
|
+
const listItem = (c) => ({
|
|
38
|
+
id: c.id,
|
|
39
|
+
spaceId: c.spaceId,
|
|
40
|
+
title: c.title,
|
|
41
|
+
sectionId: c.sectionId,
|
|
42
|
+
parentId: c.parentId,
|
|
43
|
+
private: c.private,
|
|
44
|
+
updatedAt: c.updatedAt.toISOString(),
|
|
45
|
+
// A turn older than its limit isn't running any more (its process may have died).
|
|
46
|
+
answeringSince: c.answeringSince && Date.now() - c.answeringSince.getTime() < TURN_MS
|
|
47
|
+
? c.answeringSince.toISOString()
|
|
48
|
+
: null,
|
|
49
|
+
});
|
|
50
|
+
const isMember = (user) => exists(db
|
|
51
|
+
.select({ one: sql `1` })
|
|
52
|
+
.from(schema.chatMember)
|
|
53
|
+
.where(and(eq(schema.chatMember.chatId, schema.chat.id), eq(schema.chatMember.kind, "person"), eq(schema.chatMember.memberId, user.id))));
|
|
54
|
+
/** The chats the person sees: the tenant's, but a private one only as a member. */
|
|
55
|
+
const visible = (user) => and(eq(schema.chat.tenantId, user.tenantId), or(eq(schema.chat.private, false), isMember(user)));
|
|
56
|
+
async function visibleChat(user, id) {
|
|
57
|
+
const found = await db.query.chat.findFirst({
|
|
58
|
+
where: and(eq(schema.chat.id, id), visible(user)),
|
|
59
|
+
});
|
|
60
|
+
if (!found) {
|
|
61
|
+
throw new ServiceError("not_found", "chat not found");
|
|
62
|
+
}
|
|
63
|
+
return found;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The chat a held call is decided in: one the person sees; for an owner or admin any chat of the
|
|
67
|
+
* organization, since the bell shows them every held call (work-approvals.ts `waitingFor`).
|
|
68
|
+
*/
|
|
69
|
+
async function decidableChat(user, id) {
|
|
70
|
+
if (isAdminRole(user.role)) {
|
|
71
|
+
const found = await db.query.chat.findFirst({
|
|
72
|
+
where: and(eq(schema.chat.id, id), eq(schema.chat.tenantId, user.tenantId)),
|
|
73
|
+
});
|
|
74
|
+
if (found) {
|
|
75
|
+
return found;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return visibleChat(user, id);
|
|
79
|
+
}
|
|
80
|
+
/** A space of the person's tenant. */
|
|
81
|
+
async function spaceOf(user, id) {
|
|
82
|
+
const found = await db.query.space.findFirst({
|
|
83
|
+
where: and(eq(schema.space.id, id), eq(schema.space.tenantId, user.tenantId)),
|
|
84
|
+
});
|
|
85
|
+
if (!found) {
|
|
86
|
+
throw new ServiceError("not_found", "space not found");
|
|
87
|
+
}
|
|
88
|
+
return found.id;
|
|
89
|
+
}
|
|
90
|
+
async function sectionOf(user, spaceId, id) {
|
|
91
|
+
if (!id) {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
const found = await db.query.chatSection.findFirst({
|
|
95
|
+
where: and(eq(schema.chatSection.id, id), eq(schema.chatSection.tenantId, user.tenantId), eq(schema.chatSection.spaceId, spaceId)),
|
|
96
|
+
});
|
|
97
|
+
if (!found) {
|
|
98
|
+
throw new ServiceError("not_found", "section not found");
|
|
99
|
+
}
|
|
100
|
+
return found.id;
|
|
101
|
+
}
|
|
102
|
+
async function join(chatId, kind, memberId) {
|
|
103
|
+
await db.insert(schema.chatMember).values({ chatId, kind, memberId }).onConflictDoNothing();
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The sidebar of a space: its sections in their order and the chats the person sees, newest
|
|
107
|
+
* first, each with the person's pin, archive and unread mark and its last message. The search
|
|
108
|
+
* looks at titles and last messages.
|
|
109
|
+
*/
|
|
110
|
+
export async function sidebar(user, spaceId, query) {
|
|
111
|
+
const space = await spaceOf(user, spaceId);
|
|
112
|
+
const sections = await db.query.chatSection.findMany({
|
|
113
|
+
where: eq(schema.chatSection.spaceId, space),
|
|
114
|
+
orderBy: [asc(schema.chatSection.position), asc(schema.chatSection.createdAt)],
|
|
115
|
+
});
|
|
116
|
+
const q = query?.trim();
|
|
117
|
+
const chats = await db.query.chat.findMany({
|
|
118
|
+
where: and(visible(user), eq(schema.chat.spaceId, space), q ? or(like(schema.chat.title, `%${q}%`), like(schema.chat.lastText, `%${q}%`)) : undefined),
|
|
119
|
+
orderBy: [desc(schema.chat.updatedAt)],
|
|
120
|
+
});
|
|
121
|
+
const states = await db.query.chatState.findMany({
|
|
122
|
+
where: eq(schema.chatState.userId, user.id),
|
|
123
|
+
});
|
|
124
|
+
const stateOf = new Map(states.map((st) => [st.chatId, st]));
|
|
125
|
+
return {
|
|
126
|
+
sections: sections.map((sec) => ({ id: sec.id, name: sec.name })),
|
|
127
|
+
chats: chats.map((c) => {
|
|
128
|
+
const st = stateOf.get(c.id);
|
|
129
|
+
const hasMessage = c.lastAuthorId !== null;
|
|
130
|
+
return {
|
|
131
|
+
...listItem(c),
|
|
132
|
+
pinned: Boolean(st?.pinnedAt),
|
|
133
|
+
archived: Boolean(st?.archivedAt),
|
|
134
|
+
unread: hasMessage && c.lastAuthorId !== user.id && (!st?.readAt || st.readAt < c.updatedAt),
|
|
135
|
+
last: hasMessage
|
|
136
|
+
? {
|
|
137
|
+
author: c.lastAuthorName ?? "",
|
|
138
|
+
text: c.lastText ?? "",
|
|
139
|
+
at: c.updatedAt.toISOString(),
|
|
140
|
+
}
|
|
141
|
+
: null,
|
|
142
|
+
};
|
|
143
|
+
}),
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* The live feed's changes as the person may hear of them: a chat they see as it is; one they
|
|
148
|
+
* don't see (private, or they were taken out of it) as gone, with its id alone, so it leaves a
|
|
149
|
+
* sidebar that had it. A section's always (sections are the space's).
|
|
150
|
+
*/
|
|
151
|
+
export async function chatChangesFor(user, items) {
|
|
152
|
+
const ids = items.filter((i) => i.kind === "chat" && i.parent !== "section").map((i) => i.item);
|
|
153
|
+
if (!ids.length) {
|
|
154
|
+
return items;
|
|
155
|
+
}
|
|
156
|
+
const seen = await db.query.chat.findMany({
|
|
157
|
+
where: and(inArray(schema.chat.id, ids), visible(user)),
|
|
158
|
+
columns: { id: true },
|
|
159
|
+
});
|
|
160
|
+
const ok = new Set(seen.map((c) => c.id));
|
|
161
|
+
return items.map((i) => i.kind !== "chat" || i.parent === "section" || ok.has(i.item)
|
|
162
|
+
? i
|
|
163
|
+
: { ...i, op: "del", spaceId: null, parent: null });
|
|
164
|
+
}
|
|
165
|
+
/** What the person does with a chat for themselves: pin, archive, mark read or unread. */
|
|
166
|
+
export async function setChatState(user, id, patch) {
|
|
167
|
+
const chat = await visibleChat(user, id);
|
|
168
|
+
const now = new Date();
|
|
169
|
+
const values = {
|
|
170
|
+
...(patch.pinned !== undefined ? { pinnedAt: patch.pinned ? now : null } : {}),
|
|
171
|
+
...(patch.archived !== undefined ? { archivedAt: patch.archived ? now : null } : {}),
|
|
172
|
+
...(patch.read !== undefined ? { readAt: patch.read ? now : null } : {}),
|
|
173
|
+
};
|
|
174
|
+
await db
|
|
175
|
+
.insert(schema.chatState)
|
|
176
|
+
.values({ chatId: chat.id, userId: user.id, ...values })
|
|
177
|
+
.onConflictDoUpdate({
|
|
178
|
+
target: [schema.chatState.chatId, schema.chatState.userId],
|
|
179
|
+
set: values,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
export async function createChat(user, input) {
|
|
183
|
+
const parent = input.parentId ? await visibleChat(user, input.parentId) : null;
|
|
184
|
+
// A sub-thread is in its parent's space and section, and as private.
|
|
185
|
+
const space = parent ? parent.spaceId : await spaceOf(user, input.spaceId ?? "");
|
|
186
|
+
const [row] = await db
|
|
187
|
+
.insert(schema.chat)
|
|
188
|
+
.values({
|
|
189
|
+
id: nanoid(12),
|
|
190
|
+
tenantId: user.tenantId,
|
|
191
|
+
spaceId: space,
|
|
192
|
+
title: input.title?.trim() ?? "",
|
|
193
|
+
sectionId: parent ? parent.sectionId : await sectionOf(user, space, input.sectionId),
|
|
194
|
+
parentId: parent?.id ?? null,
|
|
195
|
+
private: parent ? parent.private : (input.private ?? false),
|
|
196
|
+
createdBy: user.id,
|
|
197
|
+
})
|
|
198
|
+
.returning();
|
|
199
|
+
await join(row.id, "person", user.id);
|
|
200
|
+
const { memory } = await workMastra();
|
|
201
|
+
await memory.createThread({ threadId: row.id, resourceId: space, title: row.title });
|
|
202
|
+
return listItem(row);
|
|
203
|
+
}
|
|
204
|
+
export async function updateChat(user, id, patch) {
|
|
205
|
+
const chat = await visibleChat(user, id);
|
|
206
|
+
const [row] = await db
|
|
207
|
+
.update(schema.chat)
|
|
208
|
+
.set({
|
|
209
|
+
...(patch.title !== undefined ? { title: patch.title.trim() } : {}),
|
|
210
|
+
...(patch.sectionId !== undefined
|
|
211
|
+
? { sectionId: await sectionOf(user, chat.spaceId, patch.sectionId) }
|
|
212
|
+
: {}),
|
|
213
|
+
...(patch.private !== undefined ? { private: patch.private } : {}),
|
|
214
|
+
})
|
|
215
|
+
.where(eq(schema.chat.id, chat.id))
|
|
216
|
+
.returning();
|
|
217
|
+
return listItem(row);
|
|
218
|
+
}
|
|
219
|
+
/** Who made the chat, or an owner or admin, deletes it with its sub-threads and their messages. */
|
|
220
|
+
export async function deleteChat(user, id) {
|
|
221
|
+
const chat = await visibleChat(user, id);
|
|
222
|
+
if (chat.createdBy !== user.id && user.role === "member") {
|
|
223
|
+
throw new ServiceError("forbidden", "only who made the chat deletes it");
|
|
224
|
+
}
|
|
225
|
+
const threads = [chat.id];
|
|
226
|
+
for (let at = 0; at < threads.length; at++) {
|
|
227
|
+
const children = await db.query.chat.findMany({
|
|
228
|
+
where: eq(schema.chat.parentId, threads[at]),
|
|
229
|
+
columns: { id: true },
|
|
230
|
+
});
|
|
231
|
+
threads.push(...children.map((c) => c.id));
|
|
232
|
+
}
|
|
233
|
+
const { memory } = await workMastra();
|
|
234
|
+
for (const threadId of threads) {
|
|
235
|
+
await memory.deleteThread(threadId);
|
|
236
|
+
dropChatSandbox(threadId);
|
|
237
|
+
}
|
|
238
|
+
await db.delete(schema.chat).where(eq(schema.chat.id, chat.id));
|
|
239
|
+
}
|
|
240
|
+
/** The tenant's people by id, for the names in a chat; alone, the one person. */
|
|
241
|
+
async function people(user) {
|
|
242
|
+
if (!managed) {
|
|
243
|
+
const profile = await userProfile(user);
|
|
244
|
+
return new Map([[user.id, { name: profile.name, image: user.image ?? null }]]);
|
|
245
|
+
}
|
|
246
|
+
const { members } = await tenantMembers(user.tenantId);
|
|
247
|
+
return new Map(members.map((m) => [m.userId, { name: m.name, image: m.image }]));
|
|
248
|
+
}
|
|
249
|
+
/** A stored Mastra message as the chat shows it; its files as links into the space's files. */
|
|
250
|
+
function messageView(spaceId, m) {
|
|
251
|
+
const signal = m.content.metadata?.signal;
|
|
252
|
+
const person = m.role === "user" || m.role === "signal";
|
|
253
|
+
const [converted] = toAISdkMessages([m], { version: "v7" });
|
|
254
|
+
return {
|
|
255
|
+
id: m.id,
|
|
256
|
+
author: person
|
|
257
|
+
? {
|
|
258
|
+
kind: "person",
|
|
259
|
+
id: signal?.metadata?.authorId ?? signal?.attributes?.id ?? "",
|
|
260
|
+
name: signal?.attributes?.name ?? "",
|
|
261
|
+
}
|
|
262
|
+
: { kind: "ai", id: AI_AUTHOR, name: "" },
|
|
263
|
+
parts: viewParts(spaceId, (converted?.parts ?? []).filter((p) => p.type !== "step-start"), signal?.metadata?.files),
|
|
264
|
+
createdAt: new Date(m.createdAt).toISOString(),
|
|
265
|
+
...(signal?.metadata?.form ? { form: signal.metadata.form } : {}),
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/** One chat as its page shows it: members, messages and sub-threads. */
|
|
269
|
+
export async function readChat(user, id) {
|
|
270
|
+
const chat = await visibleChat(user, id);
|
|
271
|
+
await setChatState(user, chat.id, { read: true });
|
|
272
|
+
const { memory } = await workMastra();
|
|
273
|
+
const [members, recalled, threads, names] = await Promise.all([
|
|
274
|
+
db.query.chatMember.findMany({
|
|
275
|
+
where: eq(schema.chatMember.chatId, chat.id),
|
|
276
|
+
orderBy: [asc(schema.chatMember.joinedAt)],
|
|
277
|
+
}),
|
|
278
|
+
memory.recall({ threadId: chat.id, resourceId: chat.spaceId, perPage: false }),
|
|
279
|
+
db.query.chat.findMany({
|
|
280
|
+
where: and(eq(schema.chat.parentId, chat.id), visible(user)),
|
|
281
|
+
orderBy: [desc(schema.chat.updatedAt)],
|
|
282
|
+
}),
|
|
283
|
+
people(user),
|
|
284
|
+
]);
|
|
285
|
+
return {
|
|
286
|
+
chat: listItem(chat),
|
|
287
|
+
members: members.map((m) => ({
|
|
288
|
+
kind: m.kind,
|
|
289
|
+
id: m.memberId,
|
|
290
|
+
name: names.get(m.memberId)?.name ?? m.memberId,
|
|
291
|
+
image: names.get(m.memberId)?.image ?? null,
|
|
292
|
+
})),
|
|
293
|
+
messages: recalled.messages.map((m) => messageView(chat.spaceId, m)),
|
|
294
|
+
threads: threads.map(listItem),
|
|
295
|
+
approvals: await approvalsOf(chat.id),
|
|
296
|
+
tools: {
|
|
297
|
+
...(await assistantToolLabels(user.tenantId)),
|
|
298
|
+
...(await workConnectionLabels(chat.spaceId, user.id)),
|
|
299
|
+
},
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
/** The chat row's last message, for the sidebar; the first message of a person names the chat. */
|
|
303
|
+
async function noteLast(chat, author, text) {
|
|
304
|
+
const flat = text.replace(/\s+/g, " ").trim();
|
|
305
|
+
await db
|
|
306
|
+
.update(schema.chat)
|
|
307
|
+
.set({
|
|
308
|
+
updatedAt: new Date(),
|
|
309
|
+
lastAuthorId: author.id,
|
|
310
|
+
lastAuthorName: author.name,
|
|
311
|
+
lastText: flat.slice(0, PREVIEW_CHARS),
|
|
312
|
+
...(chat.title || author.id === AI_AUTHOR
|
|
313
|
+
? {}
|
|
314
|
+
: { title: (text.trim().split("\n")[0] ?? "").slice(0, TITLE_CHARS) }),
|
|
315
|
+
})
|
|
316
|
+
.where(eq(schema.chat.id, chat.id));
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* A file a person adds to a message in a chat: it lands in the chat's space's files (pictures and
|
|
320
|
+
* media as assets, the rest as documents, read and indexed), and the message names it by its id.
|
|
321
|
+
*/
|
|
322
|
+
export async function attachFile(user, id, file) {
|
|
323
|
+
const chat = await visibleChat(user, id);
|
|
324
|
+
const row = await addSpaceFile(chat.spaceId, { ...file, kind: fileKind(file.mime) });
|
|
325
|
+
return fileView(row);
|
|
326
|
+
}
|
|
327
|
+
/** Throws unless the person sees the chat: for routes of a chat that read nothing of it. */
|
|
328
|
+
export async function seeChat(user, id) {
|
|
329
|
+
await visibleChat(user, id);
|
|
330
|
+
}
|
|
331
|
+
/** A file of the chat's space, for the chat's views and their Fields (`/chats/:id/assets/:file`). */
|
|
332
|
+
export async function chatFileContent(user, id, fileId) {
|
|
333
|
+
const chat = await visibleChat(user, id);
|
|
334
|
+
return spaceFileContent(chat.spaceId, fileId, subjectsOfPerson(user.id, user.role));
|
|
335
|
+
}
|
|
336
|
+
/**
|
|
337
|
+
* A person writes in a chat. They join it, the message goes into the chat's thread with them as
|
|
338
|
+
* author, and their first message names the chat. Not asked, the AI doesn't run. Asked, the
|
|
339
|
+
* message wakes it for a turn or goes into the turn it is running; the asker follows that turn
|
|
340
|
+
* (its stream, in the AI SDK's UI parts). `later` waits until the running turn ends. `files`: the
|
|
341
|
+
* ids of the space's files that go with it, which the model sees (work-files.ts).
|
|
342
|
+
*/
|
|
343
|
+
export async function sendMessage(user, id, text,
|
|
344
|
+
/** `choice`: what the person chose in the composer for the turn it starts (work-ai.ts). */
|
|
345
|
+
options = {}) {
|
|
346
|
+
const chat = await visibleChat(user, id);
|
|
347
|
+
const named = await chatFiles(chat.spaceId, options.files ?? []);
|
|
348
|
+
if (!text && !named.length) {
|
|
349
|
+
throw new ServiceError("invalid", "empty message");
|
|
350
|
+
}
|
|
351
|
+
await join(chat.id, "person", user.id);
|
|
352
|
+
const name = (await userProfile(user)).name;
|
|
353
|
+
const { agent } = await workMastra();
|
|
354
|
+
const who = subjectsOfPerson(user.id, user.role);
|
|
355
|
+
const { contents, files } = await messageContents(chat.spaceId, text, named, who);
|
|
356
|
+
const message = {
|
|
357
|
+
contents,
|
|
358
|
+
attributes: { name },
|
|
359
|
+
metadata: {
|
|
360
|
+
authorId: user.id,
|
|
361
|
+
...(files.length ? { files } : {}),
|
|
362
|
+
...(options.form ? { form: options.form } : {}),
|
|
363
|
+
},
|
|
364
|
+
};
|
|
365
|
+
const target = { resourceId: chat.spaceId, threadId: chat.id };
|
|
366
|
+
if (options.ask && !(await canSpend())) {
|
|
367
|
+
throw new ServiceError("no_credits", note("creditsUsedUp"));
|
|
368
|
+
}
|
|
369
|
+
// Every message is stored the moment it is sent, before any turn, and never delivered as
|
|
370
|
+
// itself: a remark to a colleague doesn't steer the AI's running turn, and a stopped or failed
|
|
371
|
+
// turn can't take a person's words with it (Mastra stores a turn's input when it ends, and
|
|
372
|
+
// throws a stopped turn away).
|
|
373
|
+
await agent.sendMessage(message, {
|
|
374
|
+
...target,
|
|
375
|
+
ifActive: { behavior: "persist" },
|
|
376
|
+
ifIdle: { behavior: "persist" },
|
|
377
|
+
}).accepted;
|
|
378
|
+
await noteLast(chat, { id: user.id, name }, text || files.map((f) => f.name).join(", "));
|
|
379
|
+
if (!options.ask) {
|
|
380
|
+
return { kind: "kept" };
|
|
381
|
+
}
|
|
382
|
+
// Asking the AI is a signal that isn't stored: the stored message is what it answers.
|
|
383
|
+
const { turn, streamOptions } = await turnFor(chat, user.id, options.choice);
|
|
384
|
+
const asked = {
|
|
385
|
+
type: "reactive",
|
|
386
|
+
tagName: "asked",
|
|
387
|
+
contents: `${name} asked you in the message above; answer it.`,
|
|
388
|
+
transient: true,
|
|
389
|
+
};
|
|
390
|
+
// Running as the chat's watcher sees it: a run Mastra still winds down after its status is over.
|
|
391
|
+
const running = await runningIn(chat.id);
|
|
392
|
+
// For after the answer: queued while a turn runs; with none running it is a turn of its own.
|
|
393
|
+
if (options.later && running) {
|
|
394
|
+
await expectTurn(chat, turn);
|
|
395
|
+
await agent.queueSignal(asked, { ...target, ifIdle: { behavior: "wake", streamOptions } })
|
|
396
|
+
.accepted;
|
|
397
|
+
return { kind: "queued" };
|
|
398
|
+
}
|
|
399
|
+
// Into a running turn the message goes as it is (the turn doesn't read the thread again), with
|
|
400
|
+
// the reminder that the request before it still stands (engenty-pro, 8e7b970d1).
|
|
401
|
+
const signal = running
|
|
402
|
+
? {
|
|
403
|
+
type: "user",
|
|
404
|
+
attributes: { name },
|
|
405
|
+
contents: (await messageContents(chat.spaceId, `${text}\n\n(The request before this one still stands.)`.trim(), named, who)).contents,
|
|
406
|
+
transient: true,
|
|
407
|
+
}
|
|
408
|
+
: asked;
|
|
409
|
+
return deliverOrWake(chat, turn, streamOptions, (ifIdle) => agent.sendSignal(signal, { ...target, ifActive: { behavior: "deliver" }, ifIdle }));
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* A turn for the person, made when it really starts (Mastra resolves the agent's model then):
|
|
413
|
+
* input taken into a running turn builds nothing, and a queued one's 20 minutes start with it.
|
|
414
|
+
*/
|
|
415
|
+
async function turnFor(chat, userId, choice = {}) {
|
|
416
|
+
const space = await db.query.space.findFirst({ where: eq(schema.space.id, chat.spaceId) });
|
|
417
|
+
const turn = lazyTurn({
|
|
418
|
+
space: { id: chat.spaceId, name: space?.name ?? "" },
|
|
419
|
+
chatId: chat.id,
|
|
420
|
+
userId,
|
|
421
|
+
}, choice);
|
|
422
|
+
const requestContext = new RequestContext();
|
|
423
|
+
requestContext.set(TURN_KEY, turn);
|
|
424
|
+
return { turn, streamOptions: { requestContext, maxSteps: MAX_STEPS, abortSignal: turn.signal } };
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* Sends input to the chat's thread: into the running turn, or waking one. Either way the asker
|
|
428
|
+
* follows the run it went into (the chat's watcher), from its start.
|
|
429
|
+
*/
|
|
430
|
+
async function deliverOrWake(chat, turn, streamOptions, send) {
|
|
431
|
+
const watcher = await watch(chat);
|
|
432
|
+
await settled(chat);
|
|
433
|
+
watcher.next.push(turn);
|
|
434
|
+
const accepted = await send({ behavior: "wake", streamOptions }).accepted;
|
|
435
|
+
if (accepted?.action !== "wake") {
|
|
436
|
+
watcher.next.splice(watcher.next.indexOf(turn), 1);
|
|
437
|
+
}
|
|
438
|
+
return { kind: "turn", stream: followRun(chat.id, true) };
|
|
439
|
+
}
|
|
440
|
+
/** A queued turn's setup waits in the watcher's line for the run Mastra starts after this one. */
|
|
441
|
+
async function expectTurn(chat, turn) {
|
|
442
|
+
(await watch(chat)).next.push(turn);
|
|
443
|
+
}
|
|
444
|
+
const watchers = new Map();
|
|
445
|
+
/** A watcher with nothing running and nothing queued lets go of the thread after this long. */
|
|
446
|
+
const IDLE_MS = 60_000;
|
|
447
|
+
const END = Symbol("end");
|
|
448
|
+
function watch(chat) {
|
|
449
|
+
let found = watchers.get(chat.id);
|
|
450
|
+
if (!found) {
|
|
451
|
+
found = startWatching(chat);
|
|
452
|
+
watchers.set(chat.id, found);
|
|
453
|
+
found.catch(() => watchers.delete(chat.id));
|
|
454
|
+
}
|
|
455
|
+
return found.then((w) => {
|
|
456
|
+
if (w.idle) {
|
|
457
|
+
clearTimeout(w.idle);
|
|
458
|
+
w.idle = null;
|
|
459
|
+
}
|
|
460
|
+
return w;
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
async function startWatching(chat) {
|
|
464
|
+
const { agent } = await workMastra();
|
|
465
|
+
// With the runs' status: a run ends when Mastra says so, not at its `finish` chunk (a message
|
|
466
|
+
// delivered just then goes on in the same run).
|
|
467
|
+
const subscription = await agent.subscribeToThread({
|
|
468
|
+
resourceId: chat.spaceId,
|
|
469
|
+
threadId: chat.id,
|
|
470
|
+
withRunStatus: true,
|
|
471
|
+
});
|
|
472
|
+
const watcher = {
|
|
473
|
+
next: [],
|
|
474
|
+
run: null,
|
|
475
|
+
waiting: new Set(),
|
|
476
|
+
idle: null,
|
|
477
|
+
stop: () => {
|
|
478
|
+
subscription.unsubscribe();
|
|
479
|
+
watchers.delete(chat.id);
|
|
480
|
+
},
|
|
481
|
+
};
|
|
482
|
+
void (async () => {
|
|
483
|
+
let feed = null;
|
|
484
|
+
let dev = null;
|
|
485
|
+
let runId = null;
|
|
486
|
+
let reply = "";
|
|
487
|
+
/** A run's `finish` (or abort, error), held until the run's status says it ended. */
|
|
488
|
+
let last = null;
|
|
489
|
+
const end = () => {
|
|
490
|
+
if (feed) {
|
|
491
|
+
if (last) {
|
|
492
|
+
feed.enqueue(last);
|
|
493
|
+
}
|
|
494
|
+
feed.close();
|
|
495
|
+
}
|
|
496
|
+
feed = null;
|
|
497
|
+
runId = null;
|
|
498
|
+
last = null;
|
|
499
|
+
};
|
|
500
|
+
for await (const chunk of subscription.stream) {
|
|
501
|
+
const c = chunk;
|
|
502
|
+
if (c.type === "thread-run-status") {
|
|
503
|
+
if (c.runId === runId) {
|
|
504
|
+
end();
|
|
505
|
+
}
|
|
506
|
+
continue;
|
|
507
|
+
}
|
|
508
|
+
if (!c.runId) {
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
if (c.runId !== runId) {
|
|
512
|
+
end();
|
|
513
|
+
runId = c.runId;
|
|
514
|
+
reply = "";
|
|
515
|
+
({ feed, dev } = beginRun(chat, watcher, () => reply));
|
|
516
|
+
}
|
|
517
|
+
else if (c.type === "start") {
|
|
518
|
+
// The run went on after a message came in: still one message for the chat.
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (c.type === "finish" || c.type === "abort" || c.type === "error") {
|
|
522
|
+
last = chunk;
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
// More came after a `finish`: it wasn't the run's last.
|
|
526
|
+
last = null;
|
|
527
|
+
dev?.(c);
|
|
528
|
+
if (c.type === "text-delta") {
|
|
529
|
+
reply += c.payload?.text ?? "";
|
|
530
|
+
}
|
|
531
|
+
feed?.enqueue(chunk);
|
|
532
|
+
}
|
|
533
|
+
end();
|
|
534
|
+
})().catch((err) => console.error("[work-chats] watching a chat:", err));
|
|
535
|
+
return watcher;
|
|
536
|
+
}
|
|
537
|
+
/**
|
|
538
|
+
* A run starts: the chat says so, its chunks go to whoever follows, and its end is kept. `dev`
|
|
539
|
+
* reads the run's own chunks for the developer mode.
|
|
540
|
+
*/
|
|
541
|
+
function beginRun(chat, watcher, reply) {
|
|
542
|
+
const setup = watcher.next.shift();
|
|
543
|
+
const steps = setup?.steps ?? new ClientSteps();
|
|
544
|
+
const run = { chunks: [], listeners: new Set(), done: false };
|
|
545
|
+
watcher.run = run;
|
|
546
|
+
for (const wake of watcher.waiting) {
|
|
547
|
+
wake(run);
|
|
548
|
+
}
|
|
549
|
+
watcher.waiting.clear();
|
|
550
|
+
void db
|
|
551
|
+
.update(schema.chat)
|
|
552
|
+
.set({ answeringSince: new Date() })
|
|
553
|
+
.where(eq(schema.chat.id, chat.id))
|
|
554
|
+
.catch((err) => console.error("[work-chats] answering:", err));
|
|
555
|
+
let feed;
|
|
556
|
+
const chunks = new ReadableStream({
|
|
557
|
+
start(controller) {
|
|
558
|
+
feed = controller;
|
|
559
|
+
},
|
|
560
|
+
});
|
|
561
|
+
const ui = toAISdkStream({ fullStream: chunks },
|
|
562
|
+
// The chat shows the AI's reasoning and its sources as they come, not only once stored.
|
|
563
|
+
{ from: "agent", version: "v7", sendReasoning: true, sendSources: true });
|
|
564
|
+
const send = (chunk) => {
|
|
565
|
+
run.chunks.push(chunk);
|
|
566
|
+
for (const listener of run.listeners) {
|
|
567
|
+
listener(chunk);
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
void (async () => {
|
|
571
|
+
const off = steps.on((step) => send(stepChunk(step)));
|
|
572
|
+
try {
|
|
573
|
+
for await (const chunk of ui) {
|
|
574
|
+
// A client's steps go before the run's last chunk, inside its message.
|
|
575
|
+
if (chunk.type === "finish") {
|
|
576
|
+
off();
|
|
577
|
+
}
|
|
578
|
+
send(chunk);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
finally {
|
|
582
|
+
off();
|
|
583
|
+
run.done = true;
|
|
584
|
+
for (const listener of [...run.listeners]) {
|
|
585
|
+
listener(END);
|
|
586
|
+
}
|
|
587
|
+
if (watcher.run === run) {
|
|
588
|
+
watcher.run = null;
|
|
589
|
+
}
|
|
590
|
+
await afterTurn(chat, reply(), steps.list).catch((err) => console.error("[work-chats] after the turn:", err));
|
|
591
|
+
if (!watcher.next.length && !watcher.run) {
|
|
592
|
+
watcher.idle = setTimeout(watcher.stop, IDLE_MS);
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
})();
|
|
596
|
+
return { feed, dev: devChunks(chat, setup, send) };
|
|
597
|
+
}
|
|
598
|
+
/** The chunks only the developer mode reads: the routes leave them out for everyone else. */
|
|
599
|
+
export const DEV_CHUNK = "data-dev-";
|
|
600
|
+
/**
|
|
601
|
+
* What the developer mode shows of a run (the web's dev.tsx): the prompt once the turn is made,
|
|
602
|
+
* and each step at its end with its model, tokens, time and cost, as Goose's developer mode does.
|
|
603
|
+
*/
|
|
604
|
+
function devChunks(chat, setup, send) {
|
|
605
|
+
let made = null;
|
|
606
|
+
let step = 0;
|
|
607
|
+
// A step lasts from the end of the one before, its tools' work included, to its own end.
|
|
608
|
+
let started = Date.now();
|
|
609
|
+
void setup
|
|
610
|
+
?.get()
|
|
611
|
+
.then(async (turn) => {
|
|
612
|
+
made = turn;
|
|
613
|
+
send({ type: `${DEV_CHUNK}prompt`, data: await devPrompt(chat, turn), transient: true });
|
|
614
|
+
})
|
|
615
|
+
.catch(() => null);
|
|
616
|
+
return (chunk) => {
|
|
617
|
+
if (chunk.type !== "step-finish" || !made) {
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
620
|
+
const output = chunk.payload?.output;
|
|
621
|
+
const usage = usageOf(output?.usage);
|
|
622
|
+
step += 1;
|
|
623
|
+
send({
|
|
624
|
+
type: `${DEV_CHUNK}step`,
|
|
625
|
+
data: {
|
|
626
|
+
step,
|
|
627
|
+
model: made.resolved.ref,
|
|
628
|
+
inputTokens: usage.inputTokens ?? 0,
|
|
629
|
+
outputTokens: usage.outputTokens ?? 0,
|
|
630
|
+
cachedInputTokens: usage.cachedInputTokens ?? 0,
|
|
631
|
+
ms: Date.now() - started,
|
|
632
|
+
costUsd: costOf(made.resolved, output?.usage),
|
|
633
|
+
tools: (output?.toolCalls ?? []).map((c) => c.payload?.toolName ?? c.toolName ?? ""),
|
|
634
|
+
window: contextWindowOf(made.resolved.ref),
|
|
635
|
+
},
|
|
636
|
+
transient: true,
|
|
637
|
+
});
|
|
638
|
+
started = Date.now();
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
/** The prompt of a turn taken apart: its instructions, the chat's messages it reads, its tools. */
|
|
642
|
+
async function devPrompt(chat, turn) {
|
|
643
|
+
const { memory } = await workMastra();
|
|
644
|
+
const { messages } = await memory.recall({
|
|
645
|
+
threadId: chat.id,
|
|
646
|
+
resourceId: chat.spaceId,
|
|
647
|
+
perPage: LAST_MESSAGES,
|
|
648
|
+
});
|
|
649
|
+
const chars = (m) => (m.content?.parts ?? []).reduce((n, p) => n +
|
|
650
|
+
(p.type === "text"
|
|
651
|
+
? String(p.text ?? "").length
|
|
652
|
+
: JSON.stringify(p).length), 0);
|
|
653
|
+
return {
|
|
654
|
+
model: turn.resolved.ref,
|
|
655
|
+
system: turn.instructions,
|
|
656
|
+
context: "",
|
|
657
|
+
history: messages.map((m) => ({ role: m.role === "assistant" ? "assistant" : "user", chars: chars(m) })),
|
|
658
|
+
tools: toolSizes(turn.tools),
|
|
659
|
+
};
|
|
660
|
+
}
|
|
661
|
+
/** A run as a stream to follow from its start: the running one, or (`next`) the one about to start. */
|
|
662
|
+
function followRun(chatId, next) {
|
|
663
|
+
const found = watchers.get(chatId);
|
|
664
|
+
let listener = null;
|
|
665
|
+
let current = null;
|
|
666
|
+
return new ReadableStream({
|
|
667
|
+
async start(controller) {
|
|
668
|
+
const watcher = await found;
|
|
669
|
+
const attach = (run) => {
|
|
670
|
+
current = run;
|
|
671
|
+
for (const chunk of run.chunks) {
|
|
672
|
+
controller.enqueue(chunk);
|
|
673
|
+
}
|
|
674
|
+
if (run.done) {
|
|
675
|
+
controller.close();
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
listener = (chunk) => {
|
|
679
|
+
if (chunk === END) {
|
|
680
|
+
run.listeners.delete(listener);
|
|
681
|
+
controller.close();
|
|
682
|
+
}
|
|
683
|
+
else {
|
|
684
|
+
controller.enqueue(chunk);
|
|
685
|
+
}
|
|
686
|
+
};
|
|
687
|
+
run.listeners.add(listener);
|
|
688
|
+
};
|
|
689
|
+
if (watcher?.run && !watcher.run.done) {
|
|
690
|
+
attach(watcher.run);
|
|
691
|
+
}
|
|
692
|
+
else if (watcher && next) {
|
|
693
|
+
watcher.waiting.add(attach);
|
|
694
|
+
}
|
|
695
|
+
else {
|
|
696
|
+
controller.close();
|
|
697
|
+
}
|
|
698
|
+
},
|
|
699
|
+
cancel() {
|
|
700
|
+
if (listener && current) {
|
|
701
|
+
current.listeners.delete(listener);
|
|
702
|
+
}
|
|
703
|
+
},
|
|
704
|
+
});
|
|
705
|
+
}
|
|
706
|
+
/**
|
|
707
|
+
* Waits until a run the watcher saw end has let go of the thread in Mastra too (a few ms): input
|
|
708
|
+
* sent before would continue the finished run instead of starting the next.
|
|
709
|
+
*/
|
|
710
|
+
async function settled(chat) {
|
|
711
|
+
if (await runningIn(chat.id)) {
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
const { agent } = await workMastra();
|
|
715
|
+
const target = { resourceId: chat.spaceId, threadId: chat.id };
|
|
716
|
+
for (let waited = 0; agent.getActiveThreadRunId(target) && waited < 2000; waited += 20) {
|
|
717
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
/** Whether a run of the AI is under way in the chat, as its watcher sees it. */
|
|
721
|
+
async function runningIn(chatId) {
|
|
722
|
+
const watcher = await watchers.get(chatId);
|
|
723
|
+
return Boolean(watcher?.run && !watcher.run.done);
|
|
724
|
+
}
|
|
725
|
+
/** The running turn of a chat as a stream to follow, from its start; null when none runs here. */
|
|
726
|
+
export async function followTurn(user, id) {
|
|
727
|
+
const chat = await visibleChat(user, id);
|
|
728
|
+
const watcher = await watchers.get(chat.id);
|
|
729
|
+
return watcher?.run && !watcher.run.done ? followRun(chat.id, false) : null;
|
|
730
|
+
}
|
|
731
|
+
/** What a finished turn leaves: its text as the chat's last message, a client's steps stored. */
|
|
732
|
+
async function afterTurn(chat, reply, steps) {
|
|
733
|
+
await db.update(schema.chat).set({ answeringSince: null }).where(eq(schema.chat.id, chat.id));
|
|
734
|
+
if (steps.length) {
|
|
735
|
+
const { memory } = await workMastra();
|
|
736
|
+
const { messages } = await memory.recall({
|
|
737
|
+
threadId: chat.id,
|
|
738
|
+
resourceId: chat.spaceId,
|
|
739
|
+
perPage: false,
|
|
740
|
+
});
|
|
741
|
+
const answer = [...messages].reverse().find((m) => m.role === "assistant");
|
|
742
|
+
// Just before the answer they led to.
|
|
743
|
+
const at = answer ? new Date(new Date(answer.createdAt).getTime() - 1) : new Date();
|
|
744
|
+
await memory.saveMessages({
|
|
745
|
+
messages: [
|
|
746
|
+
{
|
|
747
|
+
id: nanoid(14),
|
|
748
|
+
role: "assistant",
|
|
749
|
+
threadId: chat.id,
|
|
750
|
+
resourceId: chat.spaceId,
|
|
751
|
+
createdAt: at,
|
|
752
|
+
content: { format: 2, parts: stepParts(steps) },
|
|
753
|
+
},
|
|
754
|
+
],
|
|
755
|
+
});
|
|
756
|
+
}
|
|
757
|
+
if (reply.trim()) {
|
|
758
|
+
await noteLast(chat, { id: AI_AUTHOR, name: "" }, reply);
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* A person decides on a held call. Approved, the stored call runs once, with the stored arguments
|
|
763
|
+
* and the access of the person the turn was for; the AI hears the outcome in the chat (a signal)
|
|
764
|
+
* and goes on, waking for a turn of its own when none runs. Denied, it hears that. A confirmed
|
|
765
|
+
* action on a connection „Mit Freigabe“ is held again, for the space's admins: the AI hears that
|
|
766
|
+
* it waits, and the admin's yes runs it.
|
|
767
|
+
*/
|
|
768
|
+
export async function decideApproval(user, chatId, approvalId, approve) {
|
|
769
|
+
const chat = await decidableChat(user, chatId);
|
|
770
|
+
const taken = await takeDecision(user, chat.id, approvalId, approve);
|
|
771
|
+
const name = (await userProfile(user)).name;
|
|
772
|
+
const { turn, streamOptions } = await turnFor(chat, taken.askedBy);
|
|
773
|
+
let told;
|
|
774
|
+
if (approve) {
|
|
775
|
+
const space = await db.query.space.findFirst({
|
|
776
|
+
where: eq(schema.space.id, chat.spaceId),
|
|
777
|
+
});
|
|
778
|
+
const tool = await toolToRun({ id: chat.spaceId, name: space?.name ?? "" }, taken.askedBy, taken.toolName, turn.signal, { chatId: chat.id, byAdmin: taken.heldFor === "admins" });
|
|
779
|
+
try {
|
|
780
|
+
if (!tool?.execute) {
|
|
781
|
+
throw new Error(`The tool ${taken.toolName} is not there any more.`);
|
|
782
|
+
}
|
|
783
|
+
// Checked again: a client's call reaches the gate without Mastra's check, and the tool
|
|
784
|
+
// may have changed since the call was held.
|
|
785
|
+
const checked = tool.inputSchema?.safeParse?.(taken.input);
|
|
786
|
+
if (checked && !checked.success) {
|
|
787
|
+
throw new Error(`The held arguments don't fit ${taken.toolName}: ${checked.error?.message ?? ""}`);
|
|
788
|
+
}
|
|
789
|
+
const output = await tool.execute(checked?.success ? checked.data : taken.input);
|
|
790
|
+
// Mastra answers a failed check of its own with a value, not an error.
|
|
791
|
+
if (output && typeof output === "object" && output.error === true) {
|
|
792
|
+
throw new Error(String(output.message ?? "The tool refused the call."));
|
|
793
|
+
}
|
|
794
|
+
await noteOutcome(taken.id, { output });
|
|
795
|
+
const held = heldBy(output);
|
|
796
|
+
told = held
|
|
797
|
+
? `${name} confirmed ${taken.toolName} (approval ${taken.id}); the connection's rule asks the space's admins, so it waits for them (approval ${held}). Don't call it again.`
|
|
798
|
+
: `${name} approved ${taken.toolName} (approval ${taken.id}); it ran once. Result: ${JSON.stringify(output ?? null).slice(0, 4000)}`;
|
|
799
|
+
}
|
|
800
|
+
catch (err) {
|
|
801
|
+
const error = err instanceof Error ? err.message : String(err);
|
|
802
|
+
await noteOutcome(taken.id, { error });
|
|
803
|
+
told = `${name} approved ${taken.toolName} (approval ${taken.id}), but it failed: ${error}`;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
else {
|
|
807
|
+
told = `${name} denied ${taken.toolName} (approval ${taken.id}); it did not run.`;
|
|
808
|
+
}
|
|
809
|
+
const { agent } = await workMastra();
|
|
810
|
+
const target = { resourceId: chat.spaceId, threadId: chat.id };
|
|
811
|
+
return deliverOrWake(chat, turn, streamOptions, (ifIdle) => agent.sendSignal({ type: "reactive", tagName: "approval", contents: told }, { ...target, ifActive: { behavior: "deliver" }, ifIdle }));
|
|
812
|
+
}
|
|
813
|
+
/** The approvals waiting for the person, in the chats they see: the bell's count. */
|
|
814
|
+
export async function waitingApprovals(user) {
|
|
815
|
+
const chats = await db.query.chat.findMany({ where: visible(user), columns: { id: true } });
|
|
816
|
+
return waitingFor(user, chats.map((c) => c.id));
|
|
817
|
+
}
|
|
818
|
+
/** Stop: the AI's turn in the chat ends, and what was queued behind it is dropped. */
|
|
819
|
+
export async function stopTurn(user, id) {
|
|
820
|
+
const chat = await visibleChat(user, id);
|
|
821
|
+
const { agent } = await workMastra();
|
|
822
|
+
return agent.abortThreadStream({
|
|
823
|
+
resourceId: chat.spaceId,
|
|
824
|
+
threadId: chat.id,
|
|
825
|
+
clearPendingSignals: true,
|
|
826
|
+
});
|
|
827
|
+
}
|
|
828
|
+
/** Adds a person of the tenant or an engenty to a chat the person sees. */
|
|
829
|
+
export async function addMember(user, id, kind, memberId) {
|
|
830
|
+
const chat = await visibleChat(user, id);
|
|
831
|
+
if (kind === "person" && managed) {
|
|
832
|
+
const { members } = await tenantMembers(user.tenantId);
|
|
833
|
+
if (!members.some((m) => m.userId === memberId)) {
|
|
834
|
+
throw new ServiceError("not_found", "no such person in the organization");
|
|
835
|
+
}
|
|
836
|
+
}
|
|
837
|
+
await join(chat.id, kind, memberId);
|
|
838
|
+
}
|
|
839
|
+
export async function removeMember(user, id, kind, memberId) {
|
|
840
|
+
const chat = await visibleChat(user, id);
|
|
841
|
+
await db
|
|
842
|
+
.delete(schema.chatMember)
|
|
843
|
+
.where(and(eq(schema.chatMember.chatId, chat.id), eq(schema.chatMember.kind, kind), eq(schema.chatMember.memberId, memberId)));
|
|
844
|
+
}
|
|
845
|
+
// --- sections -------------------------------------------------------------------
|
|
846
|
+
export async function createSection(user, spaceId, name) {
|
|
847
|
+
const space = await spaceOf(user, spaceId);
|
|
848
|
+
const [last] = await db
|
|
849
|
+
.select({ position: max(schema.chatSection.position) })
|
|
850
|
+
.from(schema.chatSection)
|
|
851
|
+
.where(eq(schema.chatSection.spaceId, space));
|
|
852
|
+
const [row] = await db
|
|
853
|
+
.insert(schema.chatSection)
|
|
854
|
+
.values({
|
|
855
|
+
id: nanoid(12),
|
|
856
|
+
tenantId: user.tenantId,
|
|
857
|
+
spaceId: space,
|
|
858
|
+
name: name.trim(),
|
|
859
|
+
position: (last?.position ?? -1) + 1,
|
|
860
|
+
createdBy: user.id,
|
|
861
|
+
})
|
|
862
|
+
.returning();
|
|
863
|
+
return { id: row.id, name: row.name };
|
|
864
|
+
}
|
|
865
|
+
async function ownSection(user, id) {
|
|
866
|
+
const found = await db.query.chatSection.findFirst({
|
|
867
|
+
where: and(eq(schema.chatSection.id, id), eq(schema.chatSection.tenantId, user.tenantId)),
|
|
868
|
+
});
|
|
869
|
+
if (!found) {
|
|
870
|
+
throw new ServiceError("not_found", "section not found");
|
|
871
|
+
}
|
|
872
|
+
return found;
|
|
873
|
+
}
|
|
874
|
+
export async function renameSection(user, id, name) {
|
|
875
|
+
const section = await ownSection(user, id);
|
|
876
|
+
await db
|
|
877
|
+
.update(schema.chatSection)
|
|
878
|
+
.set({ name: name.trim() })
|
|
879
|
+
.where(eq(schema.chatSection.id, section.id));
|
|
880
|
+
return { id, name: name.trim() };
|
|
881
|
+
}
|
|
882
|
+
/** Moves a section one place up or down among its space's sections. */
|
|
883
|
+
export async function moveSection(user, id, direction) {
|
|
884
|
+
const section = await ownSection(user, id);
|
|
885
|
+
const all = await db.query.chatSection.findMany({
|
|
886
|
+
where: eq(schema.chatSection.spaceId, section.spaceId),
|
|
887
|
+
orderBy: [asc(schema.chatSection.position), asc(schema.chatSection.createdAt)],
|
|
888
|
+
});
|
|
889
|
+
const at = all.findIndex((sec) => sec.id === section.id);
|
|
890
|
+
const to = direction === "up" ? at - 1 : at + 1;
|
|
891
|
+
if (to < 0 || to >= all.length) {
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
[all[at], all[to]] = [all[to], all[at]];
|
|
895
|
+
await db.transaction(async (tx) => {
|
|
896
|
+
for (const [position, sec] of all.entries()) {
|
|
897
|
+
await tx
|
|
898
|
+
.update(schema.chatSection)
|
|
899
|
+
.set({ position })
|
|
900
|
+
.where(eq(schema.chatSection.id, sec.id));
|
|
901
|
+
}
|
|
902
|
+
});
|
|
903
|
+
}
|
|
904
|
+
/** Deletes a section; its chats stay, outside any section. */
|
|
905
|
+
export async function deleteSection(user, id) {
|
|
906
|
+
const section = await ownSection(user, id);
|
|
907
|
+
await db.delete(schema.chatSection).where(eq(schema.chatSection.id, section.id));
|
|
908
|
+
}
|