@mastra/factory 0.28.0-alpha.10 → 0.28.0-alpha.12

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 (82) hide show
  1. package/README.md +18 -14
  2. package/dist/capabilities/version-control.d.ts +6 -1
  3. package/dist/capabilities/version-control.d.ts.map +1 -1
  4. package/dist/environment/build-schedule.js +1 -1
  5. package/dist/environment/build-schedule.js.map +1 -1
  6. package/dist/environment/build.d.ts +3 -3
  7. package/dist/environment/build.d.ts.map +1 -1
  8. package/dist/environment/build.js +3 -1
  9. package/dist/environment/build.js.map +1 -1
  10. package/dist/environment/heads.d.ts +1 -1
  11. package/dist/environment/heads.d.ts.map +1 -1
  12. package/dist/environment/heads.js +4 -1
  13. package/dist/environment/heads.js.map +1 -1
  14. package/dist/environment/repository-access.d.ts +13 -0
  15. package/dist/environment/repository-access.d.ts.map +1 -0
  16. package/dist/environment/repository-access.js +55 -0
  17. package/dist/environment/repository-access.js.map +1 -0
  18. package/dist/factory.d.ts.map +1 -1
  19. package/dist/factory.js +3 -1
  20. package/dist/factory.js.map +1 -1
  21. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  22. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  23. package/dist/integrations/platform/github/integration.js +18 -12
  24. package/dist/integrations/platform/github/integration.js.map +1 -1
  25. package/dist/integrations/slack/integration.d.ts.map +1 -1
  26. package/dist/integrations/slack/integration.js +7 -4
  27. package/dist/integrations/slack/integration.js.map +1 -1
  28. package/dist/mcp/routes.d.ts.map +1 -1
  29. package/dist/mcp/routes.js +3 -5
  30. package/dist/mcp/routes.js.map +1 -1
  31. package/dist/routes/board-snapshot.d.ts +12 -1
  32. package/dist/routes/board-snapshot.d.ts.map +1 -1
  33. package/dist/routes/board-snapshot.js +43 -7
  34. package/dist/routes/board-snapshot.js.map +1 -1
  35. package/dist/routes/contracts.d.ts +33 -0
  36. package/dist/routes/contracts.d.ts.map +1 -1
  37. package/dist/routes/contracts.js +50 -5
  38. package/dist/routes/contracts.js.map +1 -1
  39. package/dist/routes/work-item-selection.d.ts +16 -0
  40. package/dist/routes/work-item-selection.d.ts.map +1 -0
  41. package/dist/routes/work-item-selection.js +56 -0
  42. package/dist/routes/work-item-selection.js.map +1 -0
  43. package/dist/routes/work-items.d.ts.map +1 -1
  44. package/dist/routes/work-items.js +102 -15
  45. package/dist/routes/work-items.js.map +1 -1
  46. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  47. package/dist/rules/dispatch-errors.js +4 -0
  48. package/dist/rules/dispatch-errors.js.map +1 -1
  49. package/dist/rules/dispatcher.d.ts +2 -1
  50. package/dist/rules/dispatcher.d.ts.map +1 -1
  51. package/dist/rules/dispatcher.js +35 -2
  52. package/dist/rules/dispatcher.js.map +1 -1
  53. package/dist/rules/processor.d.ts +2 -0
  54. package/dist/rules/processor.d.ts.map +1 -1
  55. package/dist/rules/processor.js +14 -0
  56. package/dist/rules/processor.js.map +1 -1
  57. package/dist/session/live-sessions.d.ts +1 -1
  58. package/dist/session/live-sessions.d.ts.map +1 -1
  59. package/dist/session/live-sessions.js +12 -2
  60. package/dist/session/live-sessions.js.map +1 -1
  61. package/dist/storage/domains/work-items/base.d.ts +21 -2
  62. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  63. package/dist/storage/domains/work-items/base.js +89 -16
  64. package/dist/storage/domains/work-items/base.js.map +1 -1
  65. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  66. package/dist/storage/domains/work-items/cards.js +3 -2
  67. package/dist/storage/domains/work-items/cards.js.map +1 -1
  68. package/dist/work-items/board-check.d.ts +11 -0
  69. package/dist/work-items/board-check.d.ts.map +1 -0
  70. package/dist/work-items/board-check.js +20 -0
  71. package/dist/work-items/board-check.js.map +1 -0
  72. package/dist/work-items/related-cards.d.ts +21 -0
  73. package/dist/work-items/related-cards.d.ts.map +1 -0
  74. package/dist/work-items/related-cards.js +45 -0
  75. package/dist/work-items/related-cards.js.map +1 -0
  76. package/dist/workspace.d.ts.map +1 -1
  77. package/dist/workspace.js +7 -14
  78. package/dist/workspace.js.map +1 -1
  79. package/factory-skills/factory-build/SKILL.md +1 -1
  80. package/factory-skills/factory-self-review/SKILL.md +1 -1
  81. package/factory-skills/factory-triage/SKILL.md +4 -4
  82. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"integration.js","names":[],"sources":["../../../src/integrations/slack/integration.ts"],"sourcesContent":["/**\n * `SlackIntegration` — Slack as a `FactoryIntegration`.\n *\n * Slack contributes two things to a factory: the chat channels that carry\n * inbound messages into agent runs (`channels()`), and the browser-facing\n * account-link routes that bind a Slack sender to a Mastra tenant (`routes()`).\n * Both used to be assembled by hand in the deploy entry, which had to reach\n * into the prepared agent controller by string key, resolve storage domains\n * itself, mint its own state signer, and splice routes onto the factory's\n * assembled server config. Implementing the integration interface instead means\n * the factory does all of that the same way it already does for GitHub and\n * Linear, and the entry's job shrinks to reading Slack's env vars once.\n *\n * Slack ships as a factory built-in alongside GitHub and Linear (it originally\n * lived in `mastracode/web` to keep `@mastra/slack`/`chat` out of this package;\n * the team reversed that so `create-factory` consumers get Slack channels out\n * of the box). The integration interface remains open — third parties still add\n * capabilities by implementing `FactoryIntegration` from outside the package.\n */\n\nimport type { AgentChannels, TypingStatusFn } from '@mastra/core/channels';\nimport type { InputProcessor, OutputProcessor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { SlackAdapterChannelConfig } from '@mastra/slack';\n\n\nimport type { FactoryChannelsConfig, FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { announcePullRequest } from '../channel-thread-announcements.js';\nimport { parseCreatedPullRequest } from '../github/session-subscriptions.js';\nimport { FactoryChannelReplyProcessor } from './channel-reply-processor.js';\nimport { FactoryChannelSessionLinkProcessor } from './channel-session-link-processor.js';\nimport { createSlackChatTools } from './chat-tools.js';\nimport { createSlackConnectRoutes } from './connect-route.js';\nimport { FactoryReplyReminderProcessor } from './reply-reminder-processor.js';\nimport { createReplyTool, FactoryReplyStreamProcessor, REPLY_TOOL_NAME } from './reply-tool.js';\nimport { createShareFileTool, isSlackThread, slackThreadOf } from './share-file-tool.js';\nimport type { ShareFileToolDeps } from './share-file-tool.js';\nimport { createSlackChannelsConfig } from './slack.js';\nimport { DEFAULT_SLACK_TOOL_SETTINGS, slackToolSettingsSchema } from './tool-settings.js';\nimport type { SlackToolSettings } from './tool-settings.js';\n\n/** Slack app credentials, read from env ONCE by the deploy entry. */\nexport interface SlackIntegrationConfig {\n /** Slack event transport. Defaults to webhook mode. */\n mode?: 'webhook' | 'socket';\n /** Verifies inbound Slack request signatures. Required in webhook mode. */\n signingSecret?: string;\n /** App-level token used to connect to Slack. Required in socket mode. */\n appToken?: string;\n /** Bot token used to post replies and ephemeral cards. */\n botToken?: string;\n /**\n * OAuth client credentials. Required for account linking: \"Sign in with\n * Slack\" (OIDC) is the only flow that writes a link, so without these the\n * settings surface reports `canConnect: false` and no sender can link.\n */\n clientId?: string;\n clientSecret?: string;\n /**\n * HTTPS origin Slack redirects back to. Slack requires HTTPS, so locally this\n * is the tunnel origin rather than the app's own public URL.\n */\n oidcRedirectBaseUrl?: string;\n /** SPA origin the post-connect redirect returns to. */\n uiOrigin?: string;\n /**\n * Overrides for the Slack channel adapter entry.\n *\n * @example\n * ```ts\n * new SlackIntegration({\n * signingSecret,\n * adapterOptions: {\n * streaming: true,\n * toolDisplay: 'grouped',\n * },\n * });\n * ```\n */\n adapterOptions?: SlackAdapterChannelConfig;\n /**\n * What sessions started from Slack may do with the Slack tools. By default a\n * session can read and post only in its own channel, and can't send DMs.\n *\n * @example\n * ```ts\n * new SlackIntegration({\n * signingSecret,\n * // Any channel the app is in, and DMs to anyone in the workspace.\n * tools: { channels: 'all', directMessages: 'anyone' },\n * });\n * ```\n */\n tools?: Partial<SlackToolSettings>;\n}\n\n/** Slack renders the status inline next to the app name; keep it to one short line. */\nconst MAX_STATUS_LENGTH = 80;\n\n/**\n * Turns a tool's `description` arg (\"Listing the repo root\") into a status\n * line that reads after the app name (\"<App> is listing the repo root…\").\n * Only the first line counts: issue/PR creators carry whole bodies there.\n */\nfunction describeToolCall(args: unknown): string | undefined {\n if (!args || typeof args !== 'object') return undefined;\n const { description } = args as { description?: unknown };\n if (typeof description !== 'string') return undefined;\n const line = description\n .split('\\n')\n .map(part => part.replace(/\\s+/g, ' ').trim())\n .find(Boolean);\n if (!line) return undefined;\n const text = line.length > MAX_STATUS_LENGTH ? `${line.slice(0, MAX_STATUS_LENGTH - 1)}…` : line;\n // Drop the sentence-case capital (\"Listing\" → \"listing\") but leave acronyms\n // and identifiers (\"PR lookup\", \"CI status\") alone.\n return `is ${/^[A-Z][a-z]/.test(text) ? text.charAt(0).toLowerCase() + text.slice(1) : text}`;\n}\n\n/**\n * With reply text hidden, streamed text never reaches the thread, so it gets\n * no status: an \"is typing...\" set after the reply tool's post would sit on\n * the thread with nothing coming, and race the clear at the end of the run.\n */\nconst factoryTypingStatus =\n (textDisplay: SlackAdapterChannelConfig['textDisplay']): TypingStatusFn =>\n chunk => {\n switch (chunk.type) {\n case 'reasoning-delta':\n return 'is thinking...';\n case 'text-delta':\n return textDisplay === 'hidden' ? undefined : 'is typing...';\n // The reply tool's text streams into the thread as the model writes it.\n case 'tool-call-input-streaming-start':\n return chunk.payload.toolName === REPLY_TOOL_NAME ? 'is typing...' : undefined;\n case 'tool-call':\n // Still finishing the streamed reply; don't flip to \"is working...\".\n if (chunk.payload.toolName === REPLY_TOOL_NAME) return 'is typing...';\n return describeToolCall(chunk.payload.args) ?? 'is working...';\n default:\n return undefined;\n }\n};\n\n/**\n * Drops keys the caller set to `undefined` so spreading the overrides cannot\n * erase the Factory defaults they sit on top of.\n */\nfunction adapterOverrides(options: SlackAdapterChannelConfig | undefined): SlackAdapterChannelConfig {\n return Object.fromEntries(\n Object.entries(options ?? {}).filter(([, value]) => value !== undefined),\n ) as SlackAdapterChannelConfig;\n}\n\n/**\n * Factory defaults under the caller's overrides. Tool calls stay out of the\n * thread: a Factory session runs hundreds of them, and a row per call (or a\n * card per call) buries the reply. Progress shows through the typing status\n * instead, which names the tool's current step; the session link carries the\n * full trace. `grouped` remains available via `adapterOptions` for callers\n * who want Slack's \"Thinking Steps\" widget.\n */\nfunction factoryAdapterOptions(overrides: SlackAdapterChannelConfig): SlackAdapterChannelConfig {\n const textDisplay = overrides.textDisplay ?? 'hidden';\n return { typingStatus: factoryTypingStatus(textDisplay), toolDisplay: 'hidden', textDisplay, ...overrides };\n}\n\nexport class SlackIntegration implements FactoryIntegration {\n readonly id = 'slack';\n /**\n * The OIDC connect flow round-trips a signed `state` through Slack, so the\n * replica handling the callback must be able to verify a state a different\n * replica signed.\n */\n readonly requiresStableStateSigner = true;\n\n readonly #config: SlackIntegrationConfig;\n readonly #toolSettings: SlackToolSettings;\n readonly #adapterOptions: SlackAdapterChannelConfig;\n /** Bound in `initialize()`; the controller mounts after integrations are built. */\n #channels: ShareFileToolDeps['channels'];\n readonly #deps: ShareFileToolDeps = { channels: () => this.#channels?.() };\n /**\n * With reply text hidden (the Factory default) the agent speaks through\n * `reply_in_thread`, so the prompt, reminder and live streaming for that\n * tool come with it. The setting is fixed for the deployment, so it is\n * decided once here rather than on every run.\n */\n readonly processors: { input: InputProcessor[]; output: OutputProcessor[] };\n /**\n * Whether `channels()` found a source-control owner on the context and wired\n * repo-backed sessions. Set at the channels() attach path, which runs once at\n * boot before diagnostics are served.\n */\n #repoBackedSessions = false;\n\n constructor(config: SlackIntegrationConfig) {\n const mode = config.mode ?? 'webhook';\n if (mode === 'webhook' && !config.signingSecret) {\n throw new Error(\n \"SlackIntegration: 'signingSecret' is required in webhook mode — Slack cannot verify inbound requests without it.\",\n );\n }\n if (mode === 'socket' && !config.appToken) {\n throw new Error(\"SlackIntegration: 'appToken' is required in socket mode — Slack cannot open a Socket Mode connection without it.\");\n }\n if (mode === 'socket' && !config.botToken) {\n throw new Error(\"SlackIntegration: 'botToken' is required in socket mode — Factory cannot reply without it.\");\n }\n this.#config = config;\n // An explicit `undefined` means \"use the default\", not \"unset it\".\n const granted = Object.fromEntries(Object.entries(config.tools ?? {}).filter(([, value]) => value !== undefined));\n this.#toolSettings = slackToolSettingsSchema.parse({ ...DEFAULT_SLACK_TOOL_SETTINGS, ...granted });\n this.#adapterOptions = factoryAdapterOptions(adapterOverrides(config.adapterOptions));\n const textHidden = this.#textHidden;\n this.processors = {\n input: [\n new FactoryChannelReplyProcessor(),\n ...(textHidden ? [new FactoryReplyReminderProcessor()] : []),\n ],\n output: [\n new FactoryChannelSessionLinkProcessor(),\n ...(textHidden ? [new FactoryReplyStreamProcessor(this.#deps)] : []),\n ],\n };\n }\n\n get #textHidden(): boolean {\n return this.#adapterOptions.textDisplay === 'hidden';\n }\n\n initialize(args: { channels?: () => AgentChannels | null | undefined }): void {\n this.#channels = args.channels;\n }\n\n /**\n * On runs whose session is linked to a Slack thread: `attach_file`,\n * `reply_in_thread` when reply text is hidden, and the Slack read, post,\n * search, lookup and DM tools. The tools find the thread to post into when\n * they are called.\n */\n async agentTools({ requestContext }: { requestContext: RequestContext }): Promise<IntegrationTools> {\n const slackThread = await slackThreadOf(requestContext, this.#deps);\n if (!slackThread) return {};\n const chat = this.#channels?.()?.sdk;\n const sessionThreadId = slackThread.threadId;\n return {\n ...createShareFileTool(requestContext, this.#deps),\n ...(this.#textHidden ? createReplyTool(requestContext, this.#deps) : {}),\n ...(chat && sessionThreadId ? createSlackChatTools({ chat, sessionThreadId, settings: this.#toolSettings }) : {}),\n };\n }\n\n /**\n * When a run opens a pull request, post its link into the session's Slack\n * thread.\n */\n async postToolObserver({\n toolContext,\n requestContext,\n }: Parameters<NonNullable<FactoryIntegration['postToolObserver']>>[0]): Promise<void> {\n const url = parseCreatedPullRequest(toolContext);\n const threadId = (requestContext?.get('controller') as { threadId?: string } | undefined)?.threadId;\n if (!url || !requestContext || !threadId || !(await isSlackThread(requestContext, this.#deps))) return;\n // Not awaited: the tool call must not wait on Slack.\n void announcePullRequest(this.#channels?.(), threadId, 'opened', url).catch(error =>\n console.warn('[slack] pull request opened announcement failed', error),\n );\n }\n\n channels(ctx: IntegrationContext): FactoryChannelsConfig {\n // Repo-backed sessions select the source-control provider from the linked\n // repository on each Factory project.\n const sourceControls =\n ctx.storage.sourceControls ?? (ctx.storage.sourceControlOwner ? [ctx.storage.sourceControlOwner] : []);\n this.#repoBackedSessions = sourceControls.length > 0;\n const mode = this.#config.mode ?? 'webhook';\n return createSlackChannelsConfig({\n slack: {\n mode: this.#config.mode,\n ...(mode === 'webhook'\n ? { clientId: this.#config.clientId, clientSecret: this.#config.clientSecret }\n : {}),\n signingSecret: this.#config.signingSecret,\n appToken: this.#config.appToken,\n botToken: this.#config.botToken,\n },\n accountLinks: ctx.storage.channelIdentity,\n projects: ctx.storage.projects,\n sourceControls,\n modelDefaults: ctx.storage.modelDefaults,\n modelCredentials: ctx.storage.modelCredentials,\n voiceSettings: ctx.storage.voiceSettings,\n workItems: ctx.runtime?.workItems,\n adapterOptions: this.#adapterOptions,\n });\n }\n\n routes(ctx: IntegrationContext): ApiRoute[] {\n const { clientId, clientSecret, oidcRedirectBaseUrl, uiOrigin } = this.#config;\n return createSlackConnectRoutes({\n auth: ctx.auth,\n accountLinks: ctx.storage.channelIdentity,\n tenantStateSigner: ctx.stateSigner,\n oidc:\n clientId && clientSecret && oidcRedirectBaseUrl\n ? { clientId, clientSecret, redirectBaseUrl: oidcRedirectBaseUrl, uiOrigin }\n : undefined,\n projects: ctx.storage.projects,\n });\n }\n\n diagnostics(): Record<string, unknown> {\n const { clientId, clientSecret, botToken, oidcRedirectBaseUrl } = this.#config;\n return {\n configured: true,\n botTokenConfigured: Boolean(botToken),\n oidcConfigured: Boolean(clientId && clientSecret && oidcRedirectBaseUrl),\n repoBackedSessions: this.#repoBackedSessions,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAkGA,MAAM,oBAAoB;;;;;;AAO1B,SAAS,iBAA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QAAQ;GAC1B,mBAAmB,IAAI;GACvB,MACE,YAAY,gBAAgB,sBACxB;IAAE;IAAU;IAAc,iBAAiB;IAAqB;GAAS,IACzE,KAAA;GACN,UAAU,IAAI,QAAQ;EACxB,CAAC;CACH;CAEA,cAAuC;EACrC,MAAM,EAAE,UAAU,cAAc,UAAU,wBAAwB,KAAK;EACvE,OAAO;GACL,YAAY;GACZ,oBAAoB,QAAQ,QAAQ;GACpC,gBAAgB,QAAQ,YAAY,gBAAgB,mBAAmB;GACvE,oBAAoB,KAAK;EAC3B;CACF;AACF"}
1
+ {"version":3,"file":"integration.js","names":[],"sources":["../../../src/integrations/slack/integration.ts"],"sourcesContent":["/**\n * `SlackIntegration` — Slack as a `FactoryIntegration`.\n *\n * Slack contributes two things to a factory: the chat channels that carry\n * inbound messages into agent runs (`channels()`), and the browser-facing\n * account-link routes that bind a Slack sender to a Mastra tenant (`routes()`).\n * Both used to be assembled by hand in the deploy entry, which had to reach\n * into the prepared agent controller by string key, resolve storage domains\n * itself, mint its own state signer, and splice routes onto the factory's\n * assembled server config. Implementing the integration interface instead means\n * the factory does all of that the same way it already does for GitHub and\n * Linear, and the entry's job shrinks to reading Slack's env vars once.\n *\n * Slack ships as a factory built-in alongside GitHub and Linear (it originally\n * lived in `mastracode/web` to keep `@mastra/slack`/`chat` out of this package;\n * the team reversed that so `create-factory` consumers get Slack channels out\n * of the box). The integration interface remains open — third parties still add\n * capabilities by implementing `FactoryIntegration` from outside the package.\n */\n\nimport type { AgentChannels, TypingStatusFn } from '@mastra/core/channels';\nimport type { InputProcessor, OutputProcessor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { SlackAdapterChannelConfig } from '@mastra/slack';\n\n\nimport type { FactoryChannelsConfig, FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { announcePullRequest } from '../channel-thread-announcements.js';\nimport { parseCreatedPullRequest } from '../github/session-subscriptions.js';\nimport { FactoryChannelReplyProcessor } from './channel-reply-processor.js';\nimport { FactoryChannelSessionLinkProcessor } from './channel-session-link-processor.js';\nimport { createSlackChatTools } from './chat-tools.js';\nimport { createSlackConnectRoutes } from './connect-route.js';\nimport { FactoryReplyReminderProcessor } from './reply-reminder-processor.js';\nimport { createReplyTool, FactoryReplyStreamProcessor, REPLY_TOOL_NAME } from './reply-tool.js';\nimport { createShareFileTool, isSlackThread, slackThreadOf } from './share-file-tool.js';\nimport type { ShareFileToolDeps } from './share-file-tool.js';\nimport { createSlackChannelsConfig } from './slack.js';\nimport { DEFAULT_SLACK_TOOL_SETTINGS, slackToolSettingsSchema } from './tool-settings.js';\nimport type { SlackToolSettings } from './tool-settings.js';\n\n/** Slack app credentials, read from env ONCE by the deploy entry. */\nexport interface SlackIntegrationConfig {\n /** Slack event transport. Defaults to webhook mode. */\n mode?: 'webhook' | 'socket';\n /** Verifies inbound Slack request signatures. Required in webhook mode. */\n signingSecret?: string;\n /** App-level token used to connect to Slack. Required in socket mode. */\n appToken?: string;\n /** Bot token used to post replies and ephemeral cards. */\n botToken?: string;\n /**\n * OAuth client credentials. Required for account linking: \"Sign in with\n * Slack\" (OIDC) is the only flow that writes a link, so without these the\n * settings surface reports `canConnect: false` and no sender can link.\n */\n clientId?: string;\n clientSecret?: string;\n /**\n * HTTPS origin Slack redirects back to. Slack requires HTTPS, so locally this\n * is the tunnel origin rather than the app's own public URL.\n */\n oidcRedirectBaseUrl?: string;\n /** SPA origin the post-connect redirect returns to. */\n uiOrigin?: string;\n /**\n * Overrides for the Slack channel adapter entry.\n *\n * @example\n * ```ts\n * new SlackIntegration({\n * signingSecret,\n * adapterOptions: {\n * streaming: true,\n * toolDisplay: 'grouped',\n * },\n * });\n * ```\n */\n adapterOptions?: SlackAdapterChannelConfig;\n /**\n * What sessions started from Slack may do with the Slack tools. By default a\n * session can read and post only in its own channel, and can't send DMs.\n *\n * @example\n * ```ts\n * new SlackIntegration({\n * signingSecret,\n * // Any channel the app is in, and DMs to anyone in the workspace.\n * tools: { channels: 'all', directMessages: 'anyone' },\n * });\n * ```\n */\n tools?: Partial<SlackToolSettings>;\n}\n\n/**\n * Slack renders the status inline next to the app name, and rejects a status\n * (sent as its loading message) of 51 characters or more.\n */\nconst MAX_STATUS_LENGTH = 50;\n\n/**\n * Turns a tool's `description` arg (\"Listing the repo root\") into a status\n * line that reads after the app name (\"<App> is listing the repo root…\").\n * Only the first line counts: issue/PR creators carry whole bodies there.\n */\nfunction describeToolCall(args: unknown): string | undefined {\n if (!args || typeof args !== 'object') return undefined;\n const { description } = args as { description?: unknown };\n if (typeof description !== 'string') return undefined;\n const line = description\n .split('\\n')\n .map(part => part.replace(/\\s+/g, ' ').trim())\n .find(Boolean);\n if (!line) return undefined;\n // Drop the sentence-case capital (\"Listing\" → \"listing\") but leave acronyms\n // and identifiers (\"PR lookup\", \"CI status\") alone.\n const status = `is ${/^[A-Z][a-z]/.test(line) ? line.charAt(0).toLowerCase() + line.slice(1) : line}`;\n return status.length > MAX_STATUS_LENGTH ? `${status.slice(0, MAX_STATUS_LENGTH - 1)}…` : status;\n}\n\n/**\n * With reply text hidden, streamed text never reaches the thread, so it gets\n * no status: an \"is typing...\" set after the reply tool's post would sit on\n * the thread with nothing coming, and race the clear at the end of the run.\n */\nconst factoryTypingStatus =\n (textDisplay: SlackAdapterChannelConfig['textDisplay']): TypingStatusFn =>\n chunk => {\n switch (chunk.type) {\n case 'reasoning-delta':\n return 'is thinking...';\n case 'text-delta':\n return textDisplay === 'hidden' ? undefined : 'is typing...';\n // The reply tool's text streams into the thread as the model writes it.\n case 'tool-call-input-streaming-start':\n return chunk.payload.toolName === REPLY_TOOL_NAME ? 'is typing...' : undefined;\n case 'tool-call':\n // Still finishing the streamed reply; don't flip to \"is working...\".\n if (chunk.payload.toolName === REPLY_TOOL_NAME) return 'is typing...';\n return describeToolCall(chunk.payload.args) ?? 'is working...';\n default:\n return undefined;\n }\n};\n\n/**\n * Drops keys the caller set to `undefined` so spreading the overrides cannot\n * erase the Factory defaults they sit on top of.\n */\nfunction adapterOverrides(options: SlackAdapterChannelConfig | undefined): SlackAdapterChannelConfig {\n return Object.fromEntries(\n Object.entries(options ?? {}).filter(([, value]) => value !== undefined),\n ) as SlackAdapterChannelConfig;\n}\n\n/**\n * Factory defaults under the caller's overrides. Tool calls stay out of the\n * thread: a Factory session runs hundreds of them, and a row per call (or a\n * card per call) buries the reply. Progress shows through the typing status\n * instead, which names the tool's current step; the session link carries the\n * full trace. `grouped` remains available via `adapterOptions` for callers\n * who want Slack's \"Thinking Steps\" widget.\n */\nfunction factoryAdapterOptions(overrides: SlackAdapterChannelConfig): SlackAdapterChannelConfig {\n const textDisplay = overrides.textDisplay ?? 'hidden';\n return { typingStatus: factoryTypingStatus(textDisplay), toolDisplay: 'hidden', textDisplay, ...overrides };\n}\n\nexport class SlackIntegration implements FactoryIntegration {\n readonly id = 'slack';\n /**\n * The OIDC connect flow round-trips a signed `state` through Slack, so the\n * replica handling the callback must be able to verify a state a different\n * replica signed.\n */\n readonly requiresStableStateSigner = true;\n\n readonly #config: SlackIntegrationConfig;\n readonly #toolSettings: SlackToolSettings;\n readonly #adapterOptions: SlackAdapterChannelConfig;\n /** Bound in `initialize()`; the controller mounts after integrations are built. */\n #channels: ShareFileToolDeps['channels'];\n readonly #deps: ShareFileToolDeps = { channels: () => this.#channels?.() };\n /**\n * With reply text hidden (the Factory default) the agent speaks through\n * `reply_in_thread`, so the prompt, reminder and live streaming for that\n * tool come with it. The setting is fixed for the deployment, so it is\n * decided once here rather than on every run.\n */\n readonly processors: { input: InputProcessor[]; output: OutputProcessor[] };\n /**\n * Whether `channels()` found a source-control owner on the context and wired\n * repo-backed sessions. Set at the channels() attach path, which runs once at\n * boot before diagnostics are served.\n */\n #repoBackedSessions = false;\n\n constructor(config: SlackIntegrationConfig) {\n const mode = config.mode ?? 'webhook';\n if (mode === 'webhook' && !config.signingSecret) {\n throw new Error(\n \"SlackIntegration: 'signingSecret' is required in webhook mode — Slack cannot verify inbound requests without it.\",\n );\n }\n if (mode === 'socket' && !config.appToken) {\n throw new Error(\"SlackIntegration: 'appToken' is required in socket mode — Slack cannot open a Socket Mode connection without it.\");\n }\n if (mode === 'socket' && !config.botToken) {\n throw new Error(\"SlackIntegration: 'botToken' is required in socket mode — Factory cannot reply without it.\");\n }\n this.#config = config;\n // An explicit `undefined` means \"use the default\", not \"unset it\".\n const granted = Object.fromEntries(Object.entries(config.tools ?? {}).filter(([, value]) => value !== undefined));\n this.#toolSettings = slackToolSettingsSchema.parse({ ...DEFAULT_SLACK_TOOL_SETTINGS, ...granted });\n this.#adapterOptions = factoryAdapterOptions(adapterOverrides(config.adapterOptions));\n const textHidden = this.#textHidden;\n this.processors = {\n input: [\n new FactoryChannelReplyProcessor(),\n ...(textHidden ? [new FactoryReplyReminderProcessor()] : []),\n ],\n output: [\n new FactoryChannelSessionLinkProcessor(),\n ...(textHidden ? [new FactoryReplyStreamProcessor(this.#deps)] : []),\n ],\n };\n }\n\n get #textHidden(): boolean {\n return this.#adapterOptions.textDisplay === 'hidden';\n }\n\n initialize(args: { channels?: () => AgentChannels | null | undefined }): void {\n this.#channels = args.channels;\n }\n\n /**\n * On runs whose session is linked to a Slack thread: `attach_file`,\n * `reply_in_thread` when reply text is hidden, and the Slack read, post,\n * search, lookup and DM tools. The tools find the thread to post into when\n * they are called.\n */\n async agentTools({ requestContext }: { requestContext: RequestContext }): Promise<IntegrationTools> {\n const slackThread = await slackThreadOf(requestContext, this.#deps);\n if (!slackThread) return {};\n const chat = this.#channels?.()?.sdk;\n const sessionThreadId = slackThread.threadId;\n return {\n ...createShareFileTool(requestContext, this.#deps),\n ...(this.#textHidden ? createReplyTool(requestContext, this.#deps) : {}),\n ...(chat && sessionThreadId ? createSlackChatTools({ chat, sessionThreadId, settings: this.#toolSettings }) : {}),\n };\n }\n\n /**\n * When a run opens a pull request, post its link into the session's Slack\n * thread.\n */\n async postToolObserver({\n toolContext,\n requestContext,\n }: Parameters<NonNullable<FactoryIntegration['postToolObserver']>>[0]): Promise<void> {\n const url = parseCreatedPullRequest(toolContext);\n const threadId = (requestContext?.get('controller') as { threadId?: string } | undefined)?.threadId;\n if (!url || !requestContext || !threadId || !(await isSlackThread(requestContext, this.#deps))) return;\n // Not awaited: the tool call must not wait on Slack.\n void announcePullRequest(this.#channels?.(), threadId, 'opened', url).catch(error =>\n console.warn('[slack] pull request opened announcement failed', error),\n );\n }\n\n channels(ctx: IntegrationContext): FactoryChannelsConfig {\n // Repo-backed sessions select the source-control provider from the linked\n // repository on each Factory project.\n const sourceControls =\n ctx.storage.sourceControls ?? (ctx.storage.sourceControlOwner ? [ctx.storage.sourceControlOwner] : []);\n this.#repoBackedSessions = sourceControls.length > 0;\n const mode = this.#config.mode ?? 'webhook';\n return createSlackChannelsConfig({\n slack: {\n mode: this.#config.mode,\n ...(mode === 'webhook'\n ? { clientId: this.#config.clientId, clientSecret: this.#config.clientSecret }\n : {}),\n signingSecret: this.#config.signingSecret,\n appToken: this.#config.appToken,\n botToken: this.#config.botToken,\n },\n accountLinks: ctx.storage.channelIdentity,\n projects: ctx.storage.projects,\n sourceControls,\n modelDefaults: ctx.storage.modelDefaults,\n modelCredentials: ctx.storage.modelCredentials,\n voiceSettings: ctx.storage.voiceSettings,\n workItems: ctx.runtime?.workItems,\n adapterOptions: this.#adapterOptions,\n });\n }\n\n routes(ctx: IntegrationContext): ApiRoute[] {\n const { clientId, clientSecret, oidcRedirectBaseUrl, uiOrigin } = this.#config;\n return createSlackConnectRoutes({\n auth: ctx.auth,\n accountLinks: ctx.storage.channelIdentity,\n tenantStateSigner: ctx.stateSigner,\n oidc:\n clientId && clientSecret && oidcRedirectBaseUrl\n ? { clientId, clientSecret, redirectBaseUrl: oidcRedirectBaseUrl, uiOrigin }\n : undefined,\n projects: ctx.storage.projects,\n });\n }\n\n diagnostics(): Record<string, unknown> {\n const { clientId, clientSecret, botToken, oidcRedirectBaseUrl } = this.#config;\n return {\n configured: true,\n botTokenConfigured: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AE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAe1C;AAuFD;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,oBAAoB,GAAG,QAAQ,EAAE,CAoB5E"}
@@ -1,5 +1,6 @@
1
1
  import { getFactoryAuthUser } from "../auth.js";
2
2
  import "../platform-auth-host.js";
3
+ import { hasEveryWord, searchWords } from "../routes/work-item-selection.js";
3
4
  import { FactorySourceSessionResolutionError, ensureFactorySourceSession } from "../session/factory-session.js";
4
5
  import { auditActorProfile } from "../storage/domains/audit/base.js";
5
6
  import { FACTORY_TOOL_ANNOTATIONS } from "../tools/annotations.js";
@@ -98,11 +99,8 @@ function createSearchFetchTools(scope, deps, inspect) {
98
99
  description: "Search this Factory’s work items by title or id. Returns matching items with ids to pass to `fetch`.",
99
100
  inputSchema: z.object({ query: z.string().describe("Words to look for in work item titles.") }),
100
101
  execute: async ({ query }) => {
101
- const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
102
- return { results: (await deps.tools.workItems.listShared(project)).filter((item) => {
103
- const haystack = `${item.id} ${item.title}`.toLowerCase();
104
- return terms.every((term) => haystack.includes(term));
105
- }).slice(0, 20).map((item) => ({
102
+ const words = searchWords(query);
103
+ return { results: (await deps.tools.workItems.listShared(project)).filter((item) => hasEveryWord(`${item.id} ${item.title}`.toLowerCase(), words)).slice(0, 20).map((item) => ({
106
104
  id: item.id,
107
105
  title: item.title,
108
106
  url: workItemUrl(deps.publicOrigin, scope.factoryProjectId, item.id)
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../src/mcp/routes.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport { createTool } from '@mastra/core/tools';\nimport type { Tool } from '@mastra/core/tools';\nimport { MCPServer } from '@mastra/mcp';\nimport { toFetchResponse, toReqRes } from 'fetch-to-node';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\n\nimport { getFactoryAuthUser } from '../auth.js';\nimport { PLATFORM_AUTH_PROVIDER } from '../platform-auth-host.js';\nimport type { RouteAuth } from '../routes/route.js';\nimport { ensureFactorySourceSession, FactorySourceSessionResolutionError } from '../session/factory-session.js';\nimport { auditActorProfile } from '../storage/domains/audit/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { FACTORY_TOOL_ANNOTATIONS } from '../tools/annotations.js';\nimport { createFactoryTools } from '../tools/index.js';\nimport type { FactoryToolDependencies, FactoryToolScope } from '../tools/index.js';\nimport { propagateClientDisconnect } from './disconnect.js';\nimport { factoryActivityEvent } from './events.js';\n\nexport const FACTORY_MCP_PATH = '/web/factory/projects/:projectId/mcp';\nconst PROTECTED_RESOURCE_PREFIX = '/.well-known/oauth-protected-resource';\n\n/**\n * Tools an MCP client never gets. `factory_message_origin` answers the session\n * that started this one; a connector session is started by a person, not a session.\n */\nconst EXCLUDED_TOOLS = new Set(['factory_message_origin']);\n\nexport interface FactoryMcpConfig {\n /** Serve the MCP endpoint. Default `true`; it is never served without an auth provider. */\n enabled?: boolean;\n /**\n * OAuth authorization servers advertised in the protected-resource metadata\n * (RFC 9728) so clients like ChatGPT know where to sign in. Defaults to the\n * `MASTRA_FACTORY_MCP_AUTHORIZATION_SERVER` env var, then to Mastra Platform's\n * AuthKit when the Factory uses Platform auth. The endpoint isn't served\n * without one, since clients would have nowhere to sign in.\n */\n authorizationServers?: string[];\n}\n\n/**\n * MCP requires a server version. The Factory doesn't expose its package\n * version at runtime, so this versions the endpoint's interface instead.\n */\nconst FACTORY_MCP_SERVER_VERSION = '1.0.0';\n\n/** What a connected client is told the server is for and where to start. */\nconst FACTORY_MCP_INSTRUCTIONS = [\n 'A Mastra Factory tracks software work as work items on a board; agent sessions plan and build them.',\n 'Start with `factory_list_attention` for what needs a person, or `search` and `fetch` to find a work item.',\n 'Work item tools file, update, move and follow items; session tools start, message and follow the agent sessions working on them.',\n 'Every call runs as the signed-in user. When the Factory has a repository, session tools act from a private connector session of theirs.',\n].join(' ');\n\n/** Mastra Platform's WorkOS AuthKit, which issues tokens Platform's `/auth/verify` accepts. */\nexport const PLATFORM_MCP_AUTHORIZATION_SERVER = 'https://auth-kit.mastra.ai';\n\nexport function resolveMcpAuthorizationServers(\n providerName: string | undefined,\n config: FactoryMcpConfig | undefined,\n env: Record<string, string | undefined> = process.env,\n): string[] {\n if (config?.authorizationServers?.length) return config.authorizationServers;\n const fromEnv = env.MASTRA_FACTORY_MCP_AUTHORIZATION_SERVER?.trim();\n if (fromEnv) return [fromEnv];\n if (providerName === PLATFORM_AUTH_PROVIDER) return [PLATFORM_MCP_AUTHORIZATION_SERVER];\n return [];\n}\n\nexport interface FactoryMcpRoutesDeps {\n auth: RouteAuth;\n publicOrigin: string;\n authorizationServers: string[];\n projects: Pick<FactoryProjectsStorage, 'get'>;\n /** Source-control handles a connector session can be filed under, tried in order. */\n sourceControls: readonly SourceControlStorageHandle[];\n tools: FactoryToolDependencies;\n}\n\n/** The connector session a user's MCP client acts from: one per user and Factory, stable across requests. */\nexport function connectorSessionId(orgId: string, userId: string, factoryProjectId: string): string {\n const hex = createHash('sha256').update(`mcp\\0${orgId}\\0${userId}\\0${factoryProjectId}`).digest('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;\n}\n\n/**\n * Get or create the private user session behind a person's MCP client, so\n * session-scoped tools (start/signal sessions, follow work items) have a real\n * session to act from. A Factory without a connected repository has nowhere to\n * file one; its tools still run against the stable id.\n */\nasync function ensureConnectorSession(\n deps: FactoryMcpRoutesDeps,\n args: { orgId: string; userId: string; factoryProjectId: string },\n): Promise<{ sessionId: string; persisted: boolean }> {\n const sessionId = connectorSessionId(args.orgId, args.userId, args.factoryProjectId);\n if (await deps.tools.sessions.getBySessionId(sessionId)) return { sessionId, persisted: true };\n for (const sourceControl of deps.sourceControls) {\n try {\n await ensureFactorySourceSession({\n sourceControl,\n orgId: args.orgId,\n factoryProjectId: args.factoryProjectId,\n branch: `factory/mcp-${sessionId.slice(0, 8)}`,\n attributeToUserId: args.userId,\n sessionId,\n visibility: 'private',\n });\n return { sessionId, persisted: true };\n } catch (error) {\n if (!(error instanceof FactorySourceSessionResolutionError)) throw error;\n }\n }\n return { sessionId, persisted: false };\n}\n\nfunction workItemUrl(publicOrigin: string, factoryProjectId: string, workItemId: string): string {\n return `${publicOrigin}/factory/${encodeURIComponent(factoryProjectId)}/work-items/${encodeURIComponent(workItemId)}`;\n}\n\n/**\n * `search` and `fetch`, the two tools ChatGPT's connectors and deep research\n * look for, answered from the Factory's work items.\n */\nfunction createSearchFetchTools(\n scope: FactoryToolScope,\n deps: FactoryMcpRoutesDeps,\n inspect: Tool<any, any, any, any> | undefined,\n): Record<string, Tool<any, any, any, any>> {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n return {\n search: createTool({\n id: 'search',\n description:\n 'Search this Factory’s work items by title or id. Returns matching items with ids to pass to `fetch`.',\n inputSchema: z.object({ query: z.string().describe('Words to look for in work item titles.') }),\n execute: async ({ query }) => {\n const terms = query.toLowerCase().split(/\\s+/).filter(Boolean);\n const items = await deps.tools.workItems.listShared(project);\n const results = items\n .filter(item => {\n const haystack = `${item.id} ${item.title}`.toLowerCase();\n return terms.every(term => haystack.includes(term));\n })\n .slice(0, 20)\n .map(item => ({\n id: item.id,\n title: item.title,\n url: workItemUrl(deps.publicOrigin, scope.factoryProjectId, item.id),\n }));\n return { results };\n },\n }),\n fetch: createTool({\n id: 'fetch',\n description: 'Fetch everything the Factory knows about one work item, by the id `search` returned.',\n inputSchema: z.object({ id: z.string().describe('Work item id.') }),\n execute: async ({ id }, context) => {\n if (!inspect?.execute) throw new Error('Work item details are unavailable.');\n const details = (await inspect.execute({ workItem: id }, context)) as { item?: { title?: string } };\n return {\n id,\n title: details.item?.title ?? id,\n text: JSON.stringify(details, null, 2),\n url: workItemUrl(deps.publicOrigin, scope.factoryProjectId, id),\n metadata: { factoryProjectId: scope.factoryProjectId },\n };\n },\n }),\n };\n}\n\n/** The tools a signed-in person's MCP client sees for one Factory. */\nexport function createFactoryMcpTools(\n scope: FactoryToolScope,\n deps: FactoryMcpRoutesDeps,\n options: { persistedSession?: boolean } = {},\n): Record<string, Tool<any, any, any, any>> {\n const factoryTools = createFactoryTools({ scope, deps: deps.tools }) as Record<string, Tool<any, any, any, any>>;\n const tools: Record<string, Tool<any, any, any, any>> = {};\n for (const [name, tool] of Object.entries(factoryTools)) {\n if (EXCLUDED_TOOLS.has(name)) continue;\n // Starting a sub-session needs a real parent session row to file it under.\n if (name === 'factory_start_session' && options.persistedSession === false) continue;\n tools[name] = tool;\n }\n Object.assign(tools, createSearchFetchTools(scope, deps, factoryTools.factory_inspect_work_item));\n for (const [name, tool] of Object.entries(tools)) {\n const annotations = FACTORY_TOOL_ANNOTATIONS[name];\n if (annotations) tool.mcp = { ...tool.mcp, annotations };\n }\n return tools;\n}\n\nfunction resourceMetadataUrl(deps: FactoryMcpRoutesDeps, mcpPath: string): string {\n return `${deps.publicOrigin}${PROTECTED_RESOURCE_PREFIX}${mcpPath}`;\n}\n\nfunction unauthorized(deps: FactoryMcpRoutesDeps, mcpPath: string, error = 'unauthorized'): Response {\n return new Response(JSON.stringify({ error }), {\n status: 401,\n headers: {\n 'Content-Type': 'application/json',\n 'WWW-Authenticate': `Bearer resource_metadata=\"${resourceMetadataUrl(deps, mcpPath)}\"`,\n },\n });\n}\n\nasync function handleMcp(deps: FactoryMcpRoutesDeps, c: Context): Promise<Response> {\n const factoryProjectId = c.req.param('projectId') ?? '';\n const mcpPath = new URL(c.req.url).pathname;\n\n await deps.auth.ensureUser(c);\n const tenant = deps.auth.tenant(c);\n if (!tenant) return unauthorized(deps, mcpPath);\n if (!tenant.orgId) return c.json({ error: 'organization_required' }, 403);\n\n const project = await deps.projects.get({ orgId: tenant.orgId, id: factoryProjectId });\n if (!project) return c.json({ error: 'not_found' }, 404);\n\n const { sessionId, persisted } = await ensureConnectorSession(deps, {\n orgId: tenant.orgId,\n userId: tenant.userId,\n factoryProjectId,\n });\n const actorProfile = auditActorProfile(getFactoryAuthUser(c));\n const scope: FactoryToolScope = {\n orgId: tenant.orgId,\n factoryProjectId,\n userId: tenant.userId,\n sessionId,\n // A user session's memory lives under its owner.\n resourceId: tenant.userId,\n threadId: sessionId,\n kind: 'user',\n // A signed-in person is driving the client: the same reach as a web UI turn.\n interactive: true,\n ...(actorProfile ? { actorProfile } : {}),\n };\n\n const server = new MCPServer({\n id: `factory-${factoryProjectId}`,\n name: `${project.name ?? 'Mastra'} Factory`,\n version: FACTORY_MCP_SERVER_VERSION,\n description: 'Manage work items, sessions and decisions in a Mastra Factory.',\n instructions: FACTORY_MCP_INSTRUCTIONS,\n // VS Code and Cursor still open with 2025-era `initialize`; serve them statelessly.\n legacy: 'stateless',\n tools: createFactoryMcpTools(scope, deps, { persistedSession: persisted }),\n events: {\n 'factory.activity': factoryActivityEvent({\n orgId: tenant.orgId,\n factoryProjectId,\n audit: deps.tools.audit,\n workItems: deps.tools.workItems,\n sessions: deps.tools.sessions,\n viewer: { orgId: tenant.orgId, userId: tenant.userId },\n }),\n },\n });\n\n const { req, res } = toReqRes(c.req.raw);\n const done = server\n .startHTTP({ url: new URL(c.req.url), httpPath: mcpPath, req, res })\n .catch(error => {\n console.warn('[factory] MCP request failed:', error);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null }),\n );\n }\n })\n .finally(() => void server.close());\n const response = propagateClientDisconnect(await toFetchResponse(res), res);\n if (res.writableEnded) await done;\n return response;\n}\n\n/**\n * The Factory's MCP endpoint: Streamable HTTP at\n * `/web/factory/projects/:projectId/mcp`, plus its RFC 9728 protected-resource\n * metadata. Callers sign in with OAuth through the Factory's auth provider and\n * get the tools a web UI session would, under the same permissions.\n */\nexport function buildFactoryMcpRoutes(deps: FactoryMcpRoutesDeps): ApiRoute[] {\n const handler = (c: unknown) => handleMcp(deps, c as Context);\n return [\n ...(['POST', 'GET', 'DELETE'] as const).map(method =>\n registerApiRoute(FACTORY_MCP_PATH, { method, requiresAuth: false, handler }),\n ),\n registerApiRoute(`${PROTECTED_RESOURCE_PREFIX}${FACTORY_MCP_PATH}`, {\n method: 'GET',\n requiresAuth: false,\n handler: c => {\n const mcpPath = new URL(c.req.url).pathname.slice(PROTECTED_RESOURCE_PREFIX.length);\n return c.json({\n resource: `${deps.publicOrigin}${mcpPath}`,\n authorization_servers: deps.authorizationServers,\n bearer_methods_supported: ['header'],\n resource_name: 'Mastra Factory',\n });\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;AAwBA,MAAa,mBAAmB;AAChC,MAAM,4BAA4B;;;;;AAMlC,MAAM,iCAAiB,IAAI,IAAI,CAAC,wBAAwB,CAAC;;;;;AAmBzD,MAAM,6BAA6B;;AAGnC,MAAM,2BAA2B;CAC/B;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG;;AAGV,MAAa,oCAAoC;AAEjD,SAAgB,+BACd,cACA,QACA,MAA0C,QAAQ,KACxC;CACV,IAAI,QAAQ,sBAAsB,QAAQ,OAAO,OAAO;CACxD,MAAM,UAAU,IAAI,yCAAyC,KAAK;CAClE,IAAI,SAAS,OAAO,CAAC,OAAO;CAC5B,IAAI,iBAAA,iBAAyC,OAAO,CAAC,iCAAiC;CACtF,OAAO,CAAC;AACV;;AAaA,SAAgB,mBAAmB,OAAe,QAAgB,kBAAkC;CAClG,MAAM,MAAM,WAAW,QAAQ,CAAC,CAAC,OAAO,QAAQ,MAAM,IAAI,OAAO,IAAI,kBAAkB,CAAC,CAAC,OAAO,KAAK;CACrG,OAAO,GAAG,IAAI,MAAM,GAAG,CAAC,EAAE,GAAG,IAAI,MAAM,GAAG,EAAE,EA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ClE,QAAQ;EACR,cAAc;EACd,UAAS,MAAK;GACZ,MAAM,UAAU,IAAI,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,SAAS,MAAM,EAAgC;GAClF,OAAO,EAAE,KAAK;IACZ,UAAU,GAAG,KAAK,eAAe;IACjC,uBAAuB,KAAK;IAC5B,0BAA0B,CAAC,QAAQ;IACnC,eAAe;GACjB,CAAC;EACH;CACF,CAAC,CACH;AACF"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../src/mcp/routes.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport { createTool } from '@mastra/core/tools';\nimport type { Tool } from '@mastra/core/tools';\nimport { MCPServer } from '@mastra/mcp';\nimport { toFetchResponse, toReqRes } from 'fetch-to-node';\nimport type { Context } from 'hono';\nimport { z } from 'zod';\n\nimport { getFactoryAuthUser } from '../auth.js';\nimport { PLATFORM_AUTH_PROVIDER } from '../platform-auth-host.js';\nimport type { RouteAuth } from '../routes/route.js';\nimport { hasEveryWord, searchWords } from '../routes/work-item-selection.js';\nimport { ensureFactorySourceSession, FactorySourceSessionResolutionError } from '../session/factory-session.js';\nimport { auditActorProfile } from '../storage/domains/audit/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { FACTORY_TOOL_ANNOTATIONS } from '../tools/annotations.js';\nimport { createFactoryTools } from '../tools/index.js';\nimport type { FactoryToolDependencies, FactoryToolScope } from '../tools/index.js';\nimport { propagateClientDisconnect } from './disconnect.js';\nimport { factoryActivityEvent } from './events.js';\n\nexport const FACTORY_MCP_PATH = '/web/factory/projects/:projectId/mcp';\nconst PROTECTED_RESOURCE_PREFIX = '/.well-known/oauth-protected-resource';\n\n/**\n * Tools an MCP client never gets. `factory_message_origin` answers the session\n * that started this one; a connector session is started by a person, not a session.\n */\nconst EXCLUDED_TOOLS = new Set(['factory_message_origin']);\n\nexport interface FactoryMcpConfig {\n /** Serve the MCP endpoint. Default `true`; it is never served without an auth provider. */\n enabled?: boolean;\n /**\n * OAuth authorization servers advertised in the protected-resource metadata\n * (RFC 9728) so clients like ChatGPT know where to sign in. Defaults to the\n * `MASTRA_FACTORY_MCP_AUTHORIZATION_SERVER` env var, then to Mastra Platform's\n * AuthKit when the Factory uses Platform auth. The endpoint isn't served\n * without one, since clients would have nowhere to sign in.\n */\n authorizationServers?: string[];\n}\n\n/**\n * MCP requires a server version. The Factory doesn't expose its package\n * version at runtime, so this versions the endpoint's interface instead.\n */\nconst FACTORY_MCP_SERVER_VERSION = '1.0.0';\n\n/** What a connected client is told the server is for and where to start. */\nconst FACTORY_MCP_INSTRUCTIONS = [\n 'A Mastra Factory tracks software work as work items on a board; agent sessions plan and build them.',\n 'Start with `factory_list_attention` for what needs a person, or `search` and `fetch` to find a work item.',\n 'Work item tools file, update, move and follow items; session tools start, message and follow the agent sessions working on them.',\n 'Every call runs as the signed-in user. When the Factory has a repository, session tools act from a private connector session of theirs.',\n].join(' ');\n\n/** Mastra Platform's WorkOS AuthKit, which issues tokens Platform's `/auth/verify` accepts. */\nexport const PLATFORM_MCP_AUTHORIZATION_SERVER = 'https://auth-kit.mastra.ai';\n\nexport function resolveMcpAuthorizationServers(\n providerName: string | undefined,\n config: FactoryMcpConfig | undefined,\n env: Record<string, string | undefined> = process.env,\n): string[] {\n if (config?.authorizationServers?.length) return config.authorizationServers;\n const fromEnv = env.MASTRA_FACTORY_MCP_AUTHORIZATION_SERVER?.trim();\n if (fromEnv) return [fromEnv];\n if (providerName === PLATFORM_AUTH_PROVIDER) return [PLATFORM_MCP_AUTHORIZATION_SERVER];\n return [];\n}\n\nexport interface FactoryMcpRoutesDeps {\n auth: RouteAuth;\n publicOrigin: string;\n authorizationServers: string[];\n projects: Pick<FactoryProjectsStorage, 'get'>;\n /** Source-control handles a connector session can be filed under, tried in order. */\n sourceControls: readonly SourceControlStorageHandle[];\n tools: FactoryToolDependencies;\n}\n\n/** The connector session a user's MCP client acts from: one per user and Factory, stable across requests. */\nexport function connectorSessionId(orgId: string, userId: string, factoryProjectId: string): string {\n const hex = createHash('sha256').update(`mcp\\0${orgId}\\0${userId}\\0${factoryProjectId}`).digest('hex');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-8${hex.slice(17, 20)}-${hex.slice(20, 32)}`;\n}\n\n/**\n * Get or create the private user session behind a person's MCP client, so\n * session-scoped tools (start/signal sessions, follow work items) have a real\n * session to act from. A Factory without a connected repository has nowhere to\n * file one; its tools still run against the stable id.\n */\nasync function ensureConnectorSession(\n deps: FactoryMcpRoutesDeps,\n args: { orgId: string; userId: string; factoryProjectId: string },\n): Promise<{ sessionId: string; persisted: boolean }> {\n const sessionId = connectorSessionId(args.orgId, args.userId, args.factoryProjectId);\n if (await deps.tools.sessions.getBySessionId(sessionId)) return { sessionId, persisted: true };\n for (const sourceControl of deps.sourceControls) {\n try {\n await ensureFactorySourceSession({\n sourceControl,\n orgId: args.orgId,\n factoryProjectId: args.factoryProjectId,\n branch: `factory/mcp-${sessionId.slice(0, 8)}`,\n attributeToUserId: args.userId,\n sessionId,\n visibility: 'private',\n });\n return { sessionId, persisted: true };\n } catch (error) {\n if (!(error instanceof FactorySourceSessionResolutionError)) throw error;\n }\n }\n return { sessionId, persisted: false };\n}\n\nfunction workItemUrl(publicOrigin: string, factoryProjectId: string, workItemId: string): string {\n return `${publicOrigin}/factory/${encodeURIComponent(factoryProjectId)}/work-items/${encodeURIComponent(workItemId)}`;\n}\n\n/**\n * `search` and `fetch`, the two tools ChatGPT's connectors and deep research\n * look for, answered from the Factory's work items.\n */\nfunction createSearchFetchTools(\n scope: FactoryToolScope,\n deps: FactoryMcpRoutesDeps,\n inspect: Tool<any, any, any, any> | undefined,\n): Record<string, Tool<any, any, any, any>> {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n return {\n search: createTool({\n id: 'search',\n description:\n 'Search this Factory’s work items by title or id. Returns matching items with ids to pass to `fetch`.',\n inputSchema: z.object({ query: z.string().describe('Words to look for in work item titles.') }),\n execute: async ({ query }) => {\n const words = searchWords(query);\n const items = await deps.tools.workItems.listShared(project);\n const results = items\n .filter(item => hasEveryWord(`${item.id} ${item.title}`.toLowerCase(), words))\n .slice(0, 20)\n .map(item => ({\n id: item.id,\n title: item.title,\n url: workItemUrl(deps.publicOrigin, scope.factoryProjectId, item.id),\n }));\n return { results };\n },\n }),\n fetch: createTool({\n id: 'fetch',\n description: 'Fetch everything the Factory knows about one work item, by the id `search` returned.',\n inputSchema: z.object({ id: z.string().describe('Work item id.') }),\n execute: async ({ id }, context) => {\n if (!inspect?.execute) throw new Error('Work item details are unavailable.');\n const details = (await inspect.execute({ workItem: id }, context)) as { item?: { title?: string } };\n return {\n id,\n title: details.item?.title ?? id,\n text: JSON.stringify(details, null, 2),\n url: workItemUrl(deps.publicOrigin, scope.factoryProjectId, id),\n metadata: { factoryProjectId: scope.factoryProjectId },\n };\n },\n }),\n };\n}\n\n/** The tools a signed-in person's MCP client sees for one Factory. */\nexport function createFactoryMcpTools(\n scope: FactoryToolScope,\n deps: FactoryMcpRoutesDeps,\n options: { persistedSession?: boolean } = {},\n): Record<string, Tool<any, any, any, any>> {\n const factoryTools = createFactoryTools({ scope, deps: deps.tools }) as Record<string, Tool<any, any, any, any>>;\n const tools: Record<string, Tool<any, any, any, any>> = {};\n for (const [name, tool] of Object.entries(factoryTools)) {\n if (EXCLUDED_TOOLS.has(name)) continue;\n // Starting a sub-session needs a real parent session row to file it under.\n if (name === 'factory_start_session' && options.persistedSession === false) continue;\n tools[name] = tool;\n }\n Object.assign(tools, createSearchFetchTools(scope, deps, factoryTools.factory_inspect_work_item));\n for (const [name, tool] of Object.entries(tools)) {\n const annotations = FACTORY_TOOL_ANNOTATIONS[name];\n if (annotations) tool.mcp = { ...tool.mcp, annotations };\n }\n return tools;\n}\n\nfunction resourceMetadataUrl(deps: FactoryMcpRoutesDeps, mcpPath: string): string {\n return `${deps.publicOrigin}${PROTECTED_RESOURCE_PREFIX}${mcpPath}`;\n}\n\nfunction unauthorized(deps: FactoryMcpRoutesDeps, mcpPath: string, error = 'unauthorized'): Response {\n return new Response(JSON.stringify({ error }), {\n status: 401,\n headers: {\n 'Content-Type': 'application/json',\n 'WWW-Authenticate': `Bearer resource_metadata=\"${resourceMetadataUrl(deps, mcpPath)}\"`,\n },\n });\n}\n\nasync function handleMcp(deps: FactoryMcpRoutesDeps, c: Context): Promise<Response> {\n const factoryProjectId = c.req.param('projectId') ?? '';\n const mcpPath = new URL(c.req.url).pathname;\n\n await deps.auth.ensureUser(c);\n const tenant = deps.auth.tenant(c);\n if (!tenant) return unauthorized(deps, mcpPath);\n if (!tenant.orgId) return c.json({ error: 'organization_required' }, 403);\n\n const project = await deps.projects.get({ orgId: tenant.orgId, id: factoryProjectId });\n if (!project) return c.json({ error: 'not_found' }, 404);\n\n const { sessionId, persisted } = await ensureConnectorSession(deps, {\n orgId: tenant.orgId,\n userId: tenant.userId,\n factoryProjectId,\n });\n const actorProfile = auditActorProfile(getFactoryAuthUser(c));\n const scope: FactoryToolScope = {\n orgId: tenant.orgId,\n factoryProjectId,\n userId: tenant.userId,\n sessionId,\n // A user session's memory lives under its owner.\n resourceId: tenant.userId,\n threadId: sessionId,\n kind: 'user',\n // A signed-in person is driving the client: the same reach as a web UI turn.\n interactive: true,\n ...(actorProfile ? { actorProfile } : {}),\n };\n\n const server = new MCPServer({\n id: `factory-${factoryProjectId}`,\n name: `${project.name ?? 'Mastra'} Factory`,\n version: FACTORY_MCP_SERVER_VERSION,\n description: 'Manage work items, sessions and decisions in a Mastra Factory.',\n instructions: FACTORY_MCP_INSTRUCTIONS,\n // VS Code and Cursor still open with 2025-era `initialize`; serve them statelessly.\n legacy: 'stateless',\n tools: createFactoryMcpTools(scope, deps, { persistedSession: persisted }),\n events: {\n 'factory.activity': factoryActivityEvent({\n orgId: tenant.orgId,\n factoryProjectId,\n audit: deps.tools.audit,\n workItems: deps.tools.workItems,\n sessions: deps.tools.sessions,\n viewer: { orgId: tenant.orgId, userId: tenant.userId },\n }),\n },\n });\n\n const { req, res } = toReqRes(c.req.raw);\n const done = server\n .startHTTP({ url: new URL(c.req.url), httpPath: mcpPath, req, res })\n .catch(error => {\n console.warn('[factory] MCP request failed:', error);\n if (!res.headersSent) {\n res.writeHead(500, { 'Content-Type': 'application/json' });\n res.end(\n JSON.stringify({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null }),\n );\n }\n })\n .finally(() => void server.close());\n const response = propagateClientDisconnect(await toFetchResponse(res), res);\n if (res.writableEnded) await done;\n return response;\n}\n\n/**\n * The Factory's MCP endpoint: Streamable HTTP at\n * `/web/factory/projects/:projectId/mcp`, plus its RFC 9728 protected-resource\n * metadata. Callers sign in with OAuth through the Factory's auth provider and\n * get the tools a web UI session would, under the same permissions.\n */\nexport function buildFactoryMcpRoutes(deps: FactoryMcpRoutesDeps): ApiRoute[] {\n const handler = (c: unknown) => handleMcp(deps, c as Context);\n return [\n ...(['POST', 'GET', 'DELETE'] as const).map(method =>\n registerApiRoute(FACTORY_MCP_PATH, { method, requiresAuth: false, handler }),\n ),\n registerApiRoute(`${PROTECTED_RESOURCE_PREFIX}${FACTORY_MCP_PATH}`, {\n method: 'GET',\n requiresAuth: false,\n handler: c => {\n const mcpPath = new URL(c.req.url).pathname.slice(PROTECTED_RESOURCE_PREFIX.length);\n return c.json({\n resource: `${deps.publicOrigin}${mcpPath}`,\n authorization_servers: deps.authorizationServers,\n bearer_methods_supported: ['header'],\n resource_name: 'Mastra Factory',\n });\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAyBA,MAAa,mBAAmB;AAChC,MAAM,4BAA4B;;;;;AAMlC,MAAM,iCAAiB,IAAI,IAAI,CAAC,wBAAwB,CAAC;;;;;AAmBzD,MAAM,6BAA6B;;AAGnC,MAAM,2BAA2B;CAC/B;CAC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AK,CAAC,CACxG;EACF;CACF,CAAC,CAAC,CACD,cAAc,KAAK,OAAO,MAAM,CAAC;CACpC,MAAM,WAAW,0BAA0B,MAAM,gBAAgB,GAAG,GAAG,GAAG;CAC1E,IAAI,IAAI,eAAe,MAAM;CAC7B,OAAO;AACT;;;;;;;AAQA,SAAgB,sBAAsB,MAAwC;CAC5E,MAAM,WAAW,MAAe,UAAU,MAAM,CAAY;CAC5D,OAAO,CACL,GAAI;EAAC;EAAQ;EAAO;CAAQ,CAAC,CAAW,KAAI,WAC1C,iBAAiB,kBAAkB;EAAE;EAAQ,cAAc;EAAO;CAAQ,CAAC,CAC7E,GACA,iBAAiB,GAAG,4BAA4B,oBAAoB;EAClE,QAAQ;EACR,cAAc;EACd,UAAS,MAAK;GACZ,MAAM,UAAU,IAAI,IAAI,EAAE,IAAI,GAAG,CAAC,CAAC,SAAS,MAAM,EAAgC;GAClF,OAAO,EAAE,KAAK;IACZ,UAAU,GAAG,KAAK,eAAe;IACjC,uBAAuB,KAAK;IAC5B,0BAA0B,CAAC,QAAQ;IACnC,eAAe;GACjB,CAAC;EACH;CACF,CAAC,CACH;AACF"}
@@ -9,7 +9,18 @@ export interface BoardSnapshot {
9
9
  * polling an unchanged board shares one serialization and one gzip, and its
10
10
  * ETag lets the browser revalidate instead of downloading the board again.
11
11
  */
12
- export declare function boardSnapshot(items: readonly Card[], toWire: (item: Card) => unknown, runningSessionIds: readonly string[], parkedSessionIds: readonly string[]): BoardSnapshot;
12
+ export declare function boardSnapshot(items: readonly Card[], toWire: (item: Card) => unknown, runningSessionIds: readonly string[], parkedSessionIds: readonly string[], cursor?: string): BoardSnapshot;
13
+ /**
14
+ * The wire body for the cards a scoped listing picked. Its ETag names the cards by a hash of
15
+ * their body, not by the board version: a write to a card outside the scope leaves it unchanged,
16
+ * so the tab gets a 304. A caller that passes the same list again shares its serialization.
17
+ * `total` is how many cards matched when `items` is only the first of them.
18
+ */
19
+ export declare function scopedSnapshot(items: readonly Card[], toWire: (item: Card) => unknown, runningSessionIds: readonly string[], parkedSessionIds: readonly string[], total?: number): BoardSnapshot;
20
+ /** What moved on a board, for the one reader whose cursor it answers: nothing of it is kept. */
21
+ export declare function movedBody(body: unknown): Pick<BoardSnapshot, 'json' | 'gzipped'>;
22
+ /** {@link boardCheck} of a cached list, computed once for every reader that sends its cursor. */
23
+ export declare function listCheck(items: readonly Card[]): string;
13
24
  /** Whether an `If-None-Match` header names this ETag (weak comparison, as for GET). */
14
25
  export declare function matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean;
15
26
  //# sourceMappingURL=board-snapshot.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"board-snapshot.d.ts","sourceRoot":"","sources":["../../src/routes/board-snapshot.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAWlE,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CAC5B;AAMD;;;;GAIG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,EAC/B,iBAAiB,EAAE,SAAS,MAAM,EAAE,EACpC,gBAAgB,EAAE,SAAS,MAAM,EAAE,GAClC,aAAa,CAef;AAED,uFAAuF;AACvF,wBAAgB,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAIlF"}
1
+ {"version":3,"file":"board-snapshot.d.ts","sourceRoot":"","sources":["../../src/routes/board-snapshot.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAYlE,MAAM,WAAW,aAAa;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;CAC5B;AAMD;;;;GAIG;AACH,wBAAgB,aAAa,CAC3B,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,EAC/B,iBAAiB,EAAE,SAAS,MAAM,EAAE,EACpC,gBAAgB,EAAE,SAAS,MAAM,EAAE,EACnC,MAAM,CAAC,EAAE,MAAM,GACd,aAAa,CAGf;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAC5B,KAAK,EAAE,SAAS,IAAI,EAAE,EACtB,MAAM,EAAE,CAAC,IAAI,EAAE,IAAI,KAAK,OAAO,EAC/B,iBAAiB,EAAE,SAAS,MAAM,EAAE,EACpC,gBAAgB,EAAE,SAAS,MAAM,EAAE,EACnC,KAAK,CAAC,EAAE,MAAM,GACb,aAAa,CAEf;AAED,gGAAgG;AAChG,wBAAgB,SAAS,CAAC,IAAI,EAAE,OAAO,GAAG,IAAI,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC,CAGhF;AAID,iGAAiG;AACjG,wBAAgB,SAAS,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,GAAG,MAAM,CAIxD;AAgCD,uFAAuF;AACvF,wBAAgB,WAAW,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAIlF"}
@@ -1,3 +1,4 @@
1
+ import { boardCheck } from "../work-items/board-check.js";
1
2
  import { createHash, randomUUID } from "crypto";
2
3
  import { promisify } from "util";
3
4
  import { gzip } from "zlib";
@@ -9,19 +10,51 @@ const cardsJson = /* @__PURE__ */ new WeakMap();
9
10
  * polling an unchanged board shares one serialization and one gzip, and its
10
11
  * ETag lets the browser revalidate instead of downloading the board again.
11
12
  */
12
- function boardSnapshot(items, toWire, runningSessionIds, parkedSessionIds) {
13
+ function boardSnapshot(items, toWire, runningSessionIds, parkedSessionIds, cursor) {
14
+ return snapshot(items, toWire, runningSessionIds, parkedSessionIds, () => randomUUID(), { cursor });
15
+ }
16
+ /**
17
+ * The wire body for the cards a scoped listing picked. Its ETag names the cards by a hash of
18
+ * their body, not by the board version: a write to a card outside the scope leaves it unchanged,
19
+ * so the tab gets a 304. A caller that passes the same list again shares its serialization.
20
+ * `total` is how many cards matched when `items` is only the first of them.
21
+ */
22
+ function scopedSnapshot(items, toWire, runningSessionIds, parkedSessionIds, total) {
23
+ return snapshot(items, toWire, runningSessionIds, parkedSessionIds, sha1, { total });
24
+ }
25
+ /** What moved on a board, for the one reader whose cursor it answers: nothing of it is kept. */
26
+ function movedBody(body) {
27
+ const json = JSON.stringify(body);
28
+ return {
29
+ json,
30
+ gzipped: () => gzip$1(json)
31
+ };
32
+ }
33
+ const checks = /* @__PURE__ */ new WeakMap();
34
+ /** {@link boardCheck} of a cached list, computed once for every reader that sends its cursor. */
35
+ function listCheck(items) {
36
+ let check = checks.get(items);
37
+ if (check === void 0) checks.set(items, check = boardCheck(items));
38
+ return check;
39
+ }
40
+ function snapshot(items, toWire, runningSessionIds, parkedSessionIds, cardsId, more) {
13
41
  let cards = cardsJson.get(items);
14
42
  if (!cards) {
43
+ const json = JSON.stringify(items.map(toWire));
15
44
  cards = {
16
- id: randomUUID(),
17
- json: JSON.stringify(items.map(toWire))
45
+ id: cardsId(json),
46
+ json
18
47
  };
19
48
  cardsJson.set(items, cards);
20
49
  }
21
- const activity = JSON.stringify([runningSessionIds, parkedSessionIds]);
22
- const etag = `W/"${cards.id}.${createHash("sha1").update(activity).digest("base64url")}"`;
50
+ const rest = JSON.stringify({
51
+ runningSessionIds,
52
+ parkedSessionIds,
53
+ ...more
54
+ });
55
+ const etag = `W/"${cards.id}.${sha1(rest)}"`;
23
56
  if (cards.latest?.etag === etag) return cards.latest;
24
- const json = `{"workItems":${cards.json},"runningSessionIds":${JSON.stringify(runningSessionIds)},"parkedSessionIds":${JSON.stringify(parkedSessionIds)}}`;
57
+ const json = `{"workItems":${cards.json},${rest.slice(1)}`;
25
58
  let gzipped;
26
59
  cards.latest = {
27
60
  etag,
@@ -30,12 +63,15 @@ function boardSnapshot(items, toWire, runningSessionIds, parkedSessionIds) {
30
63
  };
31
64
  return cards.latest;
32
65
  }
66
+ function sha1(text) {
67
+ return createHash("sha1").update(text).digest("base64url");
68
+ }
33
69
  /** Whether an `If-None-Match` header names this ETag (weak comparison, as for GET). */
34
70
  function matchesEtag(ifNoneMatch, etag) {
35
71
  if (!ifNoneMatch) return false;
36
72
  const bare = (tag) => tag.trim().replace(/^W\//, "");
37
73
  return ifNoneMatch.split(",").some((tag) => tag.trim() === "*" || bare(tag) === bare(etag));
38
74
  }
39
- export { boardSnapshot, matchesEtag };
75
+ export { boardSnapshot, listCheck, matchesEtag, movedBody, scopedSnapshot };
40
76
 
41
77
  //# sourceMappingURL=board-snapshot.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"board-snapshot.js","names":["gzip","gzipCallback"],"sources":["../../src/routes/board-snapshot.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { promisify } from 'node:util';\nimport { gzip as gzipCallback } from 'node:zlib';\n\nimport type { Card } from '../storage/domains/work-items/base.js';\n\nconst gzip = promisify(gzipCallback);\n\ninterface CardsJson {\n /** Random per cached list, so an ETag from before a restart never matches a different board. */\n id: string;\n json: string;\n latest?: BoardSnapshot;\n}\n\nexport interface BoardSnapshot {\n etag: string;\n json: string;\n gzipped(): Promise<Buffer>;\n}\n\n// Keyed on the list `listShared` returns: one frozen array per board version, so a new\n// version or an evicted list drops its entry with it.\nconst cardsJson = new WeakMap<readonly Card[], CardsJson>();\n\n/**\n * The listing's wire body for one board version and its run activity. Every tab\n * polling an unchanged board shares one serialization and one gzip, and its\n * ETag lets the browser revalidate instead of downloading the board again.\n */\nexport function boardSnapshot(\n items: readonly Card[],\n toWire: (item: Card) => unknown,\n runningSessionIds: readonly string[],\n parkedSessionIds: readonly string[],\n): BoardSnapshot {\n let cards = cardsJson.get(items);\n if (!cards) {\n cards = { id: randomUUID(), json: JSON.stringify(items.map(toWire)) };\n cardsJson.set(items, cards);\n }\n const activity = JSON.stringify([runningSessionIds, parkedSessionIds]);\n const etag = `W/\"${cards.id}.${createHash('sha1').update(activity).digest('base64url')}\"`;\n if (cards.latest?.etag === etag) return cards.latest;\n\n const json = `{\"workItems\":${cards.json},\"runningSessionIds\":${JSON.stringify(runningSessionIds)},\"parkedSessionIds\":${JSON.stringify(parkedSessionIds)}}`;\n let gzipped: Promise<Buffer> | undefined;\n // zlib runs on the libuv pool, off the event loop.\n cards.latest = { etag, json, gzipped: () => (gzipped ??= gzip(json)) };\n return cards.latest;\n}\n\n/** Whether an `If-None-Match` header names this ETag (weak comparison, as for GET). */\nexport function matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean {\n if (!ifNoneMatch) return false;\n const bare = (tag: string) => tag.trim().replace(/^W\\//, '');\n return ifNoneMatch.split(',').some(tag => tag.trim() === '*' || bare(tag) === bare(etag));\n}\n"],"mappings":";;;;AAMA,MAAMA,SAAO,UAAUC,IAAY;AAiBnC,MAAM,4BAAY,IAAI,QAAoC;;;;;;AAO1D,SAAgB,cACd,OACA,QACA,mBACA,kBACe;CACf,IAAI,QAAQ,UAAU,IAAI,KAAK;CAC/B,IAAI,CAAC,OAAO;EACV,QAAQ;GAAE,IAAI,WAAW;GAAG,MAAM,KAAK,UAAU,MAAM,IAAI,MAAM,CAAC;EAAE;EACpE,UAAU,IAAI,OAAO,KAAK;CAC5B;CACA,MAAM,WAAW,KAAK,UAAU,CAAC,mBAAmB,gBAAgB,CAAC;CACrE,MAAM,OAAO,MAAM,MAAM,GAAG,GAAG,WAAW,MAAM,CAAC,CAAC,OAAO,QAAQ,CAAC,CAAC,OAAO,WAAW,EAAE;CACvF,IAAI,MAAM,QAAQ,SAAS,MAAM,OAAO,MAAM;CAE9C,MAAM,OAAO,gBAAgB,MAAM,KAAK,uBAAuB,KAAK,UAAU,iBAAiB,EAAE,sBAAsB,KAAK,UAAU,gBAAgB,EAAE;CACxJ,IAAI;CAEJ,MAAM,SAAS;EAAE;EAAM;EAAM,eAAgB,YAAYD,OAAK,IAAI;CAAG;CACrE,OAAO,MAAM;AACf;;AAGA,SAAgB,YAAY,aAAiC,MAAuB;CAClF,IAAI,CAAC,aAAa,OAAO;CACzB,MAAM,QAAQ,QAAgB,IAAI,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAC3D,OAAO,YAAY,MAAM,GAAG,CAAC,CAAC,MAAK,QAAO,IAAI,KAAK,MAAM,OAAO,KAAK,GAAG,MAAM,KAAK,IAAI,CAAC;AAC1F"}
1
+ {"version":3,"file":"board-snapshot.js","names":["gzip","gzipCallback"],"sources":["../../src/routes/board-snapshot.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { promisify } from 'node:util';\nimport { gzip as gzipCallback } from 'node:zlib';\n\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport { boardCheck } from '../work-items/board-check.js';\n\nconst gzip = promisify(gzipCallback);\n\ninterface CardsJson {\n /** Names the cards in the ETag. */\n id: string;\n json: string;\n latest?: BoardSnapshot;\n}\n\nexport interface BoardSnapshot {\n etag: string;\n json: string;\n gzipped(): Promise<Buffer>;\n}\n\n// Keyed on the list a caller keeps per board version: `listShared` returns one frozen array until\n// a card changes, so a new version or an evicted list drops its entry with it.\nconst cardsJson = new WeakMap<readonly Card[], CardsJson>();\n\n/**\n * The listing's wire body for one board version and its run activity. Every tab\n * polling an unchanged board shares one serialization and one gzip, and its\n * ETag lets the browser revalidate instead of downloading the board again.\n */\nexport function boardSnapshot(\n items: readonly Card[],\n toWire: (item: Card) => unknown,\n runningSessionIds: readonly string[],\n parkedSessionIds: readonly string[],\n cursor?: string,\n): BoardSnapshot {\n // Random per cached list, so an ETag from before a restart never matches a different board.\n return snapshot(items, toWire, runningSessionIds, parkedSessionIds, () => randomUUID(), { cursor });\n}\n\n/**\n * The wire body for the cards a scoped listing picked. Its ETag names the cards by a hash of\n * their body, not by the board version: a write to a card outside the scope leaves it unchanged,\n * so the tab gets a 304. A caller that passes the same list again shares its serialization.\n * `total` is how many cards matched when `items` is only the first of them.\n */\nexport function scopedSnapshot(\n items: readonly Card[],\n toWire: (item: Card) => unknown,\n runningSessionIds: readonly string[],\n parkedSessionIds: readonly string[],\n total?: number,\n): BoardSnapshot {\n return snapshot(items, toWire, runningSessionIds, parkedSessionIds, sha1, { total });\n}\n\n/** What moved on a board, for the one reader whose cursor it answers: nothing of it is kept. */\nexport function movedBody(body: unknown): Pick<BoardSnapshot, 'json' | 'gzipped'> {\n const json = JSON.stringify(body);\n return { json, gzipped: () => gzip(json) };\n}\n\nconst checks = new WeakMap<readonly Card[], string>();\n\n/** {@link boardCheck} of a cached list, computed once for every reader that sends its cursor. */\nexport function listCheck(items: readonly Card[]): string {\n let check = checks.get(items);\n if (check === undefined) checks.set(items, (check = boardCheck(items)));\n return check;\n}\n\nfunction snapshot(\n items: readonly Card[],\n toWire: (item: Card) => unknown,\n runningSessionIds: readonly string[],\n parkedSessionIds: readonly string[],\n cardsId: (json: string) => string,\n more: { total?: number; cursor?: string },\n): BoardSnapshot {\n let cards = cardsJson.get(items);\n if (!cards) {\n const json = JSON.stringify(items.map(toWire));\n cards = { id: cardsId(json), json };\n cardsJson.set(items, cards);\n }\n // Everything the body holds beside the cards: a 304 must never hide a change to any of it.\n const rest = JSON.stringify({ runningSessionIds, parkedSessionIds, ...more });\n const etag = `W/\"${cards.id}.${sha1(rest)}\"`;\n if (cards.latest?.etag === etag) return cards.latest;\n\n const json = `{\"workItems\":${cards.json},${rest.slice(1)}`;\n let gzipped: Promise<Buffer> | undefined;\n // zlib runs on the libuv pool, off the event loop.\n cards.latest = { etag, json, gzipped: () => (gzipped ??= gzip(json)) };\n return cards.latest;\n}\n\nfunction sha1(text: string): string {\n return createHash('sha1').update(text).digest('base64url');\n}\n\n/** Whether an `If-None-Match` header names this ETag (weak comparison, as for GET). */\nexport function matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean {\n if (!ifNoneMatch) return false;\n const bare = (tag: string) => tag.trim().replace(/^W\\//, '');\n return ifNoneMatch.split(',').some(tag => tag.trim() === '*' || bare(tag) === bare(etag));\n}\n"],"mappings":";;;;;AAOA,MAAMA,SAAO,UAAUC,IAAY;AAiBnC,MAAM,4BAAY,IAAI,QAAoC;;;;;;AAO1D,SAAgB,cACd,OACA,QACA,mBACA,kBACA,QACe;CAEf,OAAO,SAAS,OAAO,QAAQ,mBAAmB,wBAAwB,WAAW,GAAG,EAAE,OAAO,CAAC;AACpG;;;;;;;AAQA,SAAgB,eACd,OACA,QACA,mBACA,kBACA,OACe;CACf,OAAO,SAAS,OAAO,QAAQ,mBAAmB,kBAAkB,MAAM,EAAE,MAAM,CAAC;AACrF;;AAGA,SAAgB,UAAU,MAAwD;CAChF,MAAM,OAAO,KAAK,UAAU,IAAI;CAChC,OAAO;EAAE;EAAM,eAAeD,OAAK,IAAI;CAAE;AAC3C;AAEA,MAAM,yBAAS,IAAI,QAAiC;;AAGpD,SAAgB,UAAU,OAAgC;CACxD,IAAI,QAAQ,OAAO,IAAI,KAAK;CAC5B,IAAI,UAAU,KAAA,GAAW,OAAO,IAAI,OAAQ,QAAQ,WAAW,KAAK,CAAE;CACtE,OAAO;AACT;AAEA,SAAS,SACP,OACA,QACA,mBACA,kBACA,SACA,MACe;CACf,IAAI,QAAQ,UAAU,IAAI,KAAK;CAC/B,IAAI,CAAC,OAAO;EACV,MAAM,OAAO,KAAK,UAAU,MAAM,IAAI,MAAM,CAAC;EAC7C,QAAQ;GAAE,IAAI,QAAQ,IAAI;GAAG;EAAK;EAClC,UAAU,IAAI,OAAO,KAAK;CAC5B;CAEA,MAAM,OAAO,KAAK,UAAU;EAAE;EAAmB;EAAkB,GAAG;CAAK,CAAC;CAC5E,MAAM,OAAO,MAAM,MAAM,GAAG,GAAG,KAAK,IAAI,EAAE;CAC1C,IAAI,MAAM,QAAQ,SAAS,MAAM,OAAO,MAAM;CAE9C,MAAM,OAAO,gBAAgB,MAAM,KAAK,GAAG,KAAK,MAAM,CAAC;CACvD,IAAI;CAEJ,MAAM,SAAS;EAAE;EAAM;EAAM,eAAgB,YAAYA,OAAK,IAAI;CAAG;CACrE,OAAO,MAAM;AACf;AAEA,SAAS,KAAK,MAAsB;CAClC,OAAO,WAAW,MAAM,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,OAAO,WAAW;AAC3D;;AAGA,SAAgB,YAAY,aAAiC,MAAuB;CAClF,IAAI,CAAC,aAAa,OAAO;CACzB,MAAM,QAAQ,QAAgB,IAAI,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAC3D,OAAO,YAAY,MAAM,GAAG,CAAC,CAAC,MAAK,QAAO,IAAI,KAAK,MAAM,OAAO,KAAK,GAAG,MAAM,KAAK,IAAI,CAAC;AAC1F"}
@@ -1570,6 +1570,35 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
1570
1570
  readonly pathSchema: z.ZodObject<{
1571
1571
  id: z.ZodString;
1572
1572
  }, z.core.$strip>;
1573
+ readonly querySchema: z.ZodPipe<z.ZodObject<{
1574
+ sessionId: z.ZodOptional<z.ZodArray<z.ZodString>>;
1575
+ scope: z.ZodOptional<z.ZodEnum<{
1576
+ sessions: "sessions";
1577
+ }>>;
1578
+ started: z.ZodOptional<z.ZodEnum<{
1579
+ false: "false";
1580
+ }>>;
1581
+ q: z.ZodOptional<z.ZodString>;
1582
+ limit: z.ZodPipe<z.ZodOptional<z.ZodString>, z.ZodTransform<number, string | undefined>>;
1583
+ source: z.ZodOptional<z.ZodArray<z.ZodString>>;
1584
+ since: z.ZodCatch<z.ZodOptional<z.ZodString>>;
1585
+ }, z.core.$strip>, z.ZodTransform<{
1586
+ sessionId?: string[] | undefined;
1587
+ scope?: "sessions" | undefined;
1588
+ started?: "false" | undefined;
1589
+ q?: string | undefined;
1590
+ limit: number;
1591
+ source?: string[] | undefined;
1592
+ since?: string | undefined;
1593
+ }, {
1594
+ sessionId?: string[] | undefined;
1595
+ scope?: "sessions" | undefined;
1596
+ started?: "false" | undefined;
1597
+ q?: string | undefined;
1598
+ limit: number;
1599
+ source?: string[] | undefined;
1600
+ since?: string | undefined;
1601
+ }>>;
1573
1602
  readonly responseSchema: z.ZodObject<{
1574
1603
  workItems: z.ZodArray<z.ZodObject<{
1575
1604
  workItem: z.ZodOptional<z.ZodObject<{
@@ -1584,6 +1613,10 @@ export declare const FACTORY_ROUTE_CONTRACTS: {
1584
1613
  }, z.core.$loose>>;
1585
1614
  runningSessionIds: z.ZodArray<z.ZodString>;
1586
1615
  parkedSessionIds: z.ZodArray<z.ZodString>;
1616
+ total: z.ZodOptional<z.ZodNumber>;
1617
+ cursor: z.ZodOptional<z.ZodString>;
1618
+ removedIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
1619
+ check: z.ZodOptional<z.ZodString>;
1587
1620
  }, z.core.$strip>;
1588
1621
  };
1589
1622
  readonly workItemCreate: {
@@ -1 +1 @@
1
- {"version":3,"file":"contracts.d.ts","sourceRoot":"","sources":["../../src/routes/contracts.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEtE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AASxB,eAAO,MAAM,eAAe,EAA4B,CAAC,oBAAoB,EAAE,GAAG,oBAAoB,EAAE,CAAC,CAAC;AAE1G,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,OAAO,GAAG,QAAQ,CAAC;IACpD,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC;IACvB,WAAW,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC;IACxB,UAAU,CAAC,EAAE,CAAC,CAAC,OAAO,CAAC;IACvB,cAAc,EAAE,CAAC,CAAC,OAAO,CAAC;CAC3B,CAAC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max(512)
382
382
  });
383
+ const boundedLimitSchema = (defaultValue, max) => z.string().optional().transform((value) => {
384
+ const parsed = value ? Number.parseInt(value, 10) : defaultValue;
385
+ return Number.isFinite(parsed) ? Math.max(1, Math.min(max, parsed)) : defaultValue;
386
+ });
387
+ /** Without `sessionId`, `scope`, `started` or `source`, the list is the whole board. */
388
+ const workItemListQuerySchema = z.object({
389
+ /** Repeatable. Narrows the list to the cards that hold these sessions and the cards related to them. */
390
+ sessionId: z.array(sessionSchema.shape.sessionId).optional(),
391
+ /** `sessions` narrows the list to the cards that hold any session and the cards related to them. */
392
+ scope: z.enum(["sessions"]).optional(),
393
+ /** `false` narrows the list to the cards that hold no session, most recently updated first. */
394
+ started: z.enum(["false"]).optional(),
395
+ /** With `started=false`: words that must all be in the card's title, key, number or source id. */
396
+ q: z.string().max(200).optional(),
397
+ /** With `started=false`: how many cards to send. */
398
+ limit: boundedLimitSchema(20, 50),
399
+ /** Repeatable. Narrows the list to the cards filed from these sources, each named by its id or its URL. */
400
+ source: z.array(z.string().min(1).max(512)).min(1).max(100).optional(),
401
+ /**
402
+ * The `cursor` of the whole board this reader holds: the answer is then what moved since. One
403
+ * this server did not issue reads as none, and the board answers whole.
404
+ */
405
+ since: z.string().regex(/^\d{1,15}$/).optional().catch(void 0)
406
+ }).refine((query) => !(query.scope && query.sessionId), {
407
+ path: ["scope"],
408
+ message: "Send scope or sessionId, not both"
409
+ }).refine((query) => !(query.started && (query.scope || query.sessionId)), {
410
+ path: ["started"],
411
+ message: "Send started without scope or sessionId"
412
+ }).refine((query) => query.q === void 0 || query.started !== void 0, {
413
+ path: ["q"],
414
+ message: "Send q only with started=false"
415
+ }).refine((query) => !(query.source && (query.started || query.scope || query.sessionId)), {
416
+ path: ["source"],
417
+ message: "Send source without started, scope or sessionId"
418
+ }).transform((query) => query.sessionId || query.scope || query.started || query.source ? {
419
+ ...query,
420
+ since: void 0
421
+ } : query);
383
422
  const sessionsSchema = z.record(z.string().min(1).max(64), sessionSchema);
384
423
  const metadataSchema = z.union([z.record(z.string(), z.unknown()), z.null()]).refine((value) => {
385
424
  try {
@@ -460,10 +499,6 @@ const decisionStatusSchema = z.enum([
460
499
  "succeeded",
461
500
  "failed"
462
501
  ]);
463
- const boundedLimitSchema = (defaultValue, max) => z.string().optional().transform((value) => {
464
- const parsed = value ? Number.parseInt(value, 10) : defaultValue;
465
- return Number.isFinite(parsed) ? Math.max(1, Math.min(max, parsed)) : defaultValue;
466
- });
467
502
  const decisionCursorSchema = z.string().optional().transform((value, context) => {
468
503
  if (!value) return void 0;
469
504
  try {
@@ -890,10 +925,20 @@ const FACTORY_ROUTE_CONTRACTS = {
890
925
  path: "/web/factory/projects/:id/work-items",
891
926
  description: "List Factory work items and running sessions",
892
927
  pathSchema: projectPathSchema,
928
+ querySchema: workItemListQuerySchema,
893
929
  responseSchema: z.object({
930
+ /** Every listed card, or with `removedIds` only the cards changed since the `since` sent. */
894
931
  workItems: z.array(cardSchema),
895
932
  runningSessionIds: z.array(z.string()),
896
- parkedSessionIds: z.array(z.string())
933
+ parkedSessionIds: z.array(z.string()),
934
+ /** With `started=false`: how many cards matched, of which `workItems` holds the first `limit`. */
935
+ total: z.number().int().nonnegative().optional(),
936
+ /** Names this read of the whole board. Absent when the next read must list it whole again. */
937
+ cursor: z.string().optional(),
938
+ /** Cards gone since the `since` sent. Its presence marks an answer that holds only what moved. */
939
+ removedIds: z.array(z.string()).optional(),
940
+ /** With `removedIds`: `boardCheck` of the whole board, for a reader to check its merged copy against. */
941
+ check: z.string().optional()
897
942
  })
898
943
  },
899
944
  workItemCreate: {