@mastra/factory 0.10.0-alpha.1 → 0.10.0-alpha.13
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/CHANGELOG.md +212 -0
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +2 -1
- package/dist/auth.js.map +1 -1
- package/dist/factory.d.ts +8 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +25 -8
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/integrations/base.d.ts +3 -1
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/github/integration.d.ts +14 -0
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +48 -1
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/provenance.d.ts +7 -2
- package/dist/integrations/github/provenance.d.ts.map +1 -1
- package/dist/integrations/github/provenance.js +16 -2
- package/dist/integrations/github/provenance.js.map +1 -1
- package/dist/integrations/github/routes.d.ts +8 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +228 -7
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +193 -127
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.d.ts +9 -0
- package/dist/integrations/github/session-subscriptions.d.ts.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +39 -1
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +50 -0
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +3 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +33 -0
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/routes/attention.d.ts +17 -0
- package/dist/routes/attention.d.ts.map +1 -0
- package/dist/routes/attention.js +305 -0
- package/dist/routes/attention.js.map +1 -0
- package/dist/routes/intake.d.ts +5 -0
- package/dist/routes/intake.d.ts.map +1 -1
- package/dist/routes/intake.js +70 -19
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/surface.d.ts +6 -5
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +62 -43
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +35 -14
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/defaults.js +5 -5
- package/dist/rules/defaults.js.map +1 -1
- package/dist/rules/dispatch-errors.d.ts +13 -0
- package/dist/rules/dispatch-errors.d.ts.map +1 -0
- package/dist/rules/dispatch-errors.js +77 -0
- package/dist/rules/dispatch-errors.js.map +1 -0
- package/dist/rules/dispatcher.d.ts +9 -0
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +118 -45
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +30 -14
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/terminal-cleanup.d.ts +1 -1
- package/dist/rules/terminal-cleanup.d.ts.map +1 -1
- package/dist/rules/terminal-cleanup.js +2 -2
- package/dist/rules/terminal-cleanup.js.map +1 -1
- package/dist/rules/tools.d.ts.map +1 -1
- package/dist/rules/tools.js +9 -5
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.d.ts +5 -2
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +15 -2
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +6 -1
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +25 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/secret-encryption.d.ts +25 -0
- package/dist/secret-encryption.d.ts.map +1 -0
- package/dist/secret-encryption.js +96 -0
- package/dist/secret-encryption.js.map +1 -0
- package/dist/session/factory-session.d.ts +13 -3
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +15 -6
- package/dist/session/factory-session.js.map +1 -1
- package/dist/session/first-exec-capture.d.ts +16 -10
- package/dist/session/first-exec-capture.d.ts.map +1 -1
- package/dist/session/first-exec-capture.js +74 -14
- package/dist/session/first-exec-capture.js.map +1 -1
- package/dist/session/first-message-capture.d.ts +14 -10
- package/dist/session/first-message-capture.d.ts.map +1 -1
- package/dist/session/first-message-capture.js +17 -11
- package/dist/session/first-message-capture.js.map +1 -1
- package/dist/session/session-title.d.ts +7 -0
- package/dist/session/session-title.d.ts.map +1 -0
- package/dist/session/session-title.js +14 -0
- package/dist/session/session-title.js.map +1 -0
- package/dist/session/thread-title-mirror.d.ts +35 -0
- package/dist/session/thread-title-mirror.d.ts.map +1 -0
- package/dist/session/thread-title-mirror.js +51 -0
- package/dist/session/thread-title-mirror.js.map +1 -0
- package/dist/storage/domains/credentials/base.d.ts +3 -1
- package/dist/storage/domains/credentials/base.d.ts.map +1 -1
- package/dist/storage/domains/credentials/base.js +33 -15
- package/dist/storage/domains/credentials/base.js.map +1 -1
- package/dist/storage/domains/custom-providers/base.d.ts +3 -1
- package/dist/storage/domains/custom-providers/base.d.ts.map +1 -1
- package/dist/storage/domains/custom-providers/base.js +45 -25
- package/dist/storage/domains/custom-providers/base.js.map +1 -1
- package/dist/storage/domains/integrations/base.d.ts +3 -1
- package/dist/storage/domains/integrations/base.d.ts.map +1 -1
- package/dist/storage/domains/integrations/base.js +28 -12
- package/dist/storage/domains/integrations/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +8 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +14 -2
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +7 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +120 -12
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +514 -44
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/work-item-branch.d.ts +23 -0
- package/dist/work-item-branch.d.ts.map +1 -0
- package/dist/work-item-branch.js +39 -0
- package/dist/work-item-branch.js.map +1 -0
- package/factory-skills/factory-rereview/SKILL.md +2 -0
- package/factory-skills/factory-review/SKILL.md +2 -0
- package/factory-skills/factory-triage/SKILL.md +7 -17
- package/package.json +5 -5
|
@@ -22,6 +22,11 @@ export interface EnsureFactorySourceSessionArgs {
|
|
|
22
22
|
branch: string;
|
|
23
23
|
/** Pick a specific linked repository by slug. Defaults to the first linked repository. */
|
|
24
24
|
repositorySlug?: string;
|
|
25
|
+
/**
|
|
26
|
+
* Attribute the run to this user instead of the repo connector. Set when the
|
|
27
|
+
* run has an interactive user — e.g. the person who approved a proposed run.
|
|
28
|
+
*/
|
|
29
|
+
attributeToUserId?: string;
|
|
25
30
|
}
|
|
26
31
|
export interface EnsuredFactorySourceSession {
|
|
27
32
|
sessionId: string;
|
|
@@ -30,6 +35,10 @@ export interface EnsuredFactorySourceSession {
|
|
|
30
35
|
branch: string;
|
|
31
36
|
baseBranch: string;
|
|
32
37
|
}
|
|
38
|
+
export declare class FactorySourceSessionResolutionError extends Error {
|
|
39
|
+
readonly reason: 'connection' | 'repository';
|
|
40
|
+
constructor(reason: 'connection' | 'repository');
|
|
41
|
+
}
|
|
33
42
|
export interface ResolvedFactorySourceRepository {
|
|
34
43
|
projectRepositoryId: string;
|
|
35
44
|
/** The repository's pinned branch, else its default branch. */
|
|
@@ -90,9 +99,10 @@ export declare function resolveFactoryProjectForSession(args: {
|
|
|
90
99
|
* its linked repositories, and a session on the requested branch with the
|
|
91
100
|
* repository's pinned or default branch as the base.
|
|
92
101
|
*
|
|
93
|
-
* The run is attributed to
|
|
94
|
-
* (
|
|
95
|
-
*
|
|
102
|
+
* The run is attributed to `attributeToUserId` when the caller has an
|
|
103
|
+
* interactive user (e.g. the approver of a proposed run), and otherwise falls
|
|
104
|
+
* back to whoever connected the repository (`connection.createdByUserId`),
|
|
105
|
+
* because a genuinely autonomous run has no interactive user of its own.
|
|
96
106
|
*/
|
|
97
107
|
export declare function ensureFactorySourceSession(args: EnsureFactorySourceSessionArgs): Promise<EnsuredFactorySourceSession>;
|
|
98
108
|
export interface HydrateFactorySessionArgs {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory-session.d.ts","sourceRoot":"","sources":["../../src/session/factory-session.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAGrE,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,4CAA4C,CAAC;AACxF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAG5F,KAAK,cAAc,GAAG,OAAO,CAAC,UAAU,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;AAE7F;;;GAGG;AACH,wBAAsB,4BAA4B,CAChD,QAAQ,EAAE,sBAAsB,GAAG,SAAS,EAC5C,gBAAgB,EAAE,MAAM,GAAG,SAAS,GACnC,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAQ7B;AAED,MAAM,WAAW,8BAA8B;IAC7C;;;;;OAKG;IACH,aAAa,EAAE,0BAA0B,CAAC;IAC1C,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,0FAA0F;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c,CAAC,EAAE,qBAAqB,CAAC;CACxC;AAED;;;;;;;GAOG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE,cAAc,EAAE,IAAI,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC,CA8BnH"}
|
|
@@ -15,6 +15,14 @@ async function resolveFactoryDefaultModelId(projects, factoryProjectId) {
|
|
|
15
15
|
return;
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
|
+
var FactorySourceSessionResolutionError = class extends Error {
|
|
19
|
+
reason;
|
|
20
|
+
constructor(reason) {
|
|
21
|
+
super(reason === "connection" ? "Factory source-control connection not found." : "Factory source-control repository not found.");
|
|
22
|
+
this.reason = reason;
|
|
23
|
+
this.name = "FactorySourceSessionResolutionError";
|
|
24
|
+
}
|
|
25
|
+
};
|
|
18
26
|
/**
|
|
19
27
|
* Resolve which repository a factory project's source-control runs act on: the
|
|
20
28
|
* owner's connection on the project, then one of its linked repositories.
|
|
@@ -101,9 +109,10 @@ async function resolveFactoryProjectForSession(args) {
|
|
|
101
109
|
* its linked repositories, and a session on the requested branch with the
|
|
102
110
|
* repository's pinned or default branch as the base.
|
|
103
111
|
*
|
|
104
|
-
* The run is attributed to
|
|
105
|
-
* (
|
|
106
|
-
*
|
|
112
|
+
* The run is attributed to `attributeToUserId` when the caller has an
|
|
113
|
+
* interactive user (e.g. the approver of a proposed run), and otherwise falls
|
|
114
|
+
* back to whoever connected the repository (`connection.createdByUserId`),
|
|
115
|
+
* because a genuinely autonomous run has no interactive user of its own.
|
|
107
116
|
*/
|
|
108
117
|
async function ensureFactorySourceSession(args) {
|
|
109
118
|
const { sourceControl, orgId, factoryProjectId, branch, repositorySlug } = args;
|
|
@@ -113,8 +122,8 @@ async function ensureFactorySourceSession(args) {
|
|
|
113
122
|
factoryProjectId,
|
|
114
123
|
repositorySlug
|
|
115
124
|
});
|
|
116
|
-
if (!resolved.found) throw new
|
|
117
|
-
const userId = resolved.connectedByUserId;
|
|
125
|
+
if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);
|
|
126
|
+
const userId = args.attributeToUserId ?? resolved.connectedByUserId;
|
|
118
127
|
const session = await sourceControl.sessions.create({
|
|
119
128
|
sessionId: randomUUID(),
|
|
120
129
|
projectRepositoryId: resolved.projectRepositoryId,
|
|
@@ -161,6 +170,6 @@ async function hydrateFactorySession(session, args) {
|
|
|
161
170
|
}
|
|
162
171
|
}
|
|
163
172
|
//#endregion
|
|
164
|
-
export { ensureFactorySourceSession, hydrateFactorySession, resolveFactoryDefaultModelId, resolveFactoryProjectForSession, resolveFactorySourceRepository };
|
|
173
|
+
export { FactorySourceSessionResolutionError, ensureFactorySourceSession, hydrateFactorySession, resolveFactoryDefaultModelId, resolveFactoryProjectForSession, resolveFactorySourceRepository };
|
|
165
174
|
|
|
166
175
|
//# sourceMappingURL=factory-session.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { resolveProviderOMDefault } from '@mastra/code-sdk/onboarding/packs';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport { factoryMemorySettingsUserId } from '../storage/domains/memory-settings/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { applyStoredMemorySettings } from './memory-settings-hydration.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\n/**\n * Read the factory project's default model. Best-effort: a missing project or an\n * uninitialized storage domain means \"no default\", never a failed run.\n */\nexport async function resolveFactoryDefaultModelId(\n projects: FactoryProjectsStorage | undefined,\n factoryProjectId: string | undefined,\n): Promise<string | undefined> {\n if (!projects || !factoryProjectId) return undefined;\n try {\n const project = await projects.getById({ id: factoryProjectId });\n return project?.defaultModelId ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolveFactorySourceRepository}. A miss carries which step\n * failed: callers differ on whether that is an error (an autonomous run cannot\n * proceed) or a routine fallback (a chat integration drops to a chat-only\n * session), and the two steps fail for different reasons worth reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * Resolve which repository a factory project's source-control runs act on: the\n * owner's connection on the project, then one of its linked repositories.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolveFactorySourceRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, repositorySlug } = args;\n\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n const candidates = connections.filter(candidate => candidate.integrationId === sourceControl.integrationId);\n if (candidates.length === 0) return { found: false, reason: 'connection' };\n\n // A project can carry stale connections: a provider-app reinstall leaves the\n // old connection pointing at an installation that no longer exists, and that\n // row can sit ahead of the healthy one. Try every candidate and skip the ones\n // that no longer resolve rather than failing on the first.\n for (const connection of candidates) {\n let resolved;\n try {\n const projectRepositories = await sourceControl.projectRepositories.list({ orgId, connectionId: connection.id });\n const resolvedRepositories = await Promise.all(\n projectRepositories.map(async projectRepository => ({\n projectRepository,\n repository: await sourceControl.repositories.get({ orgId, id: projectRepository.repositoryId }),\n })),\n );\n resolved = resolvedRepositories.find(\n candidate => candidate.repository && (!repositorySlug || candidate.repository.slug === repositorySlug),\n );\n } catch {\n // The connection no longer resolves (e.g. its installation was deleted).\n continue;\n }\n if (!resolved?.repository) continue;\n\n return {\n found: true,\n projectRepositoryId: resolved.projectRepository.id,\n baseBranch: resolved.projectRepository.branch ?? resolved.repository.defaultBranch,\n connectedByUserId: connection.createdByUserId,\n };\n }\n\n return { found: false, reason: 'repository' };\n}\n\n/**\n * Walk a Factory user-session id back to the project it belongs to.\n *\n * Repo-backed channel threads are keyed by their Factory session id, which is\n * the only handle a session-start hook gets. This turns that id back into the\n * project whose configuration the session should adopt. Durable by\n * construction — it reads the same rows the session was created from, so it\n * survives restarts without any in-memory mapping.\n */\nexport async function resolveFactoryProjectForSession(args: {\n sourceControl: SourceControlStorageHandle;\n sessionId: string;\n}): Promise<{ factoryProjectId: string; orgId: string; userId: string } | null> {\n const { sourceControl, sessionId } = args;\n\n const session = await sourceControl.sessions.getBySessionId(sessionId);\n if (!session) return null;\n const projectRepository = await sourceControl.projectRepositories.get({\n orgId: session.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) return null;\n const connection = await sourceControl.connections.get({ orgId: session.orgId, id: projectRepository.connectionId });\n if (!connection) return null;\n\n return { factoryProjectId: connection.factoryProjectId, orgId: session.orgId, userId: session.userId };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, one of\n * its linked repositories, and a session on the requested branch with the\n * repository's pinned or default branch as the base.\n *\n * The run is attributed to whoever connected the repository\n * (`connection.createdByUserId`), because an autonomous run has no interactive\n * user of its own.\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, repositorySlug } = args;\n\n const resolved = await resolveFactorySourceRepository({ sourceControl, orgId, factoryProjectId, repositorySlug });\n if (!resolved.found) {\n throw new Error(\n resolved.reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n }\n\n const userId = resolved.connectedByUserId;\n const session = await sourceControl.sessions.create({\n sessionId: randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n orgId,\n userId,\n branch,\n baseBranch: resolved.baseBranch,\n visibility: 'org',\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n /**\n * The factory project whose shared memory settings apply. Factory sessions\n * never read an individual user's personal memory settings — the project's\n * own row (or the built-in defaults) is what they run with.\n */\n factoryProjectId?: string;\n /** The factory project's default model. Without it the session keeps the SDK's built-in mode default. */\n defaultModelId?: string;\n /**\n * When provided, the factory project's stored memory-settings row is\n * applied. When omitted (or no row exists) the session is reset to the\n * built-in memory defaults.\n */\n memorySettings?: MemorySettingsStorage;\n}\n\n/**\n * Apply a factory project's configuration to a freshly created session:\n * observational-memory settings, then the project's default model.\n *\n * Both steps are best-effort. A retired model id or an unreachable settings row\n * must not sink a run that is otherwise ready — the session simply keeps the\n * default it was created with, and the reason is logged.\n */\nexport async function hydrateFactorySession(session: FactorySession, args: HydrateFactorySessionArgs): Promise<void> {\n try {\n const record =\n args.memorySettings && args.factoryProjectId\n ? await args.memorySettings.get({\n orgId: args.orgId,\n userId: factoryMemorySettingsUserId(args.factoryProjectId),\n })\n : null;\n // Without a stored row, fall back to the low-cost OM model of the factory\n // default model's provider — a factory connected only to Anthropic should\n // not observe with the (uncredentialed) built-in Google default.\n const provider = args.defaultModelId?.split('/')[0];\n const fallbackOmModelId = provider ? resolveProviderOMDefault(provider, args.defaultModelId).modelId : undefined;\n await applyStoredMemorySettings(session, record, fallbackOmModelId);\n } catch (error) {\n console.warn('[Factory Start] Failed to apply observational-memory settings', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (args.defaultModelId) {\n try {\n await session.model.switch({ modelId: args.defaultModelId });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply factory default model', {\n modelId: args.defaultModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;AAkBA,eAAsB,6BACpB,UACA,kBAC6B;CAC7B,IAAI,CAAC,YAAY,CAAC,kBAAkB,OAAO,KAAA;CAC3C,IAAI;EAEF,QAAO,MADe,SAAS,QAAQ,EAAE,IAAI,iBAAiB,CAAC,EAAA,EAC/C,kBAAkB,KAAA;CACpC,QAAQ;EACN;CACF;AACF;;;;;;;;AAkDA,eAAsB,+BAA+B,MAMV;CACzC,MAAM,EAAE,eAAe,OAAO,kBAAkB,mBAAmB;CAGnE,MAAM,cAAa,MADO,cAAc,YAAY,KAAK;EAAE;EAAO;CAAiB,CAAC,EAAA,CACrD,QAAO,cAAa,UAAU,kBAAkB,cAAc,aAAa;CAC1G,IAAI,WAAW,WAAW,GAAG,OAAO;EAAE,OAAO;EAAO,QAAQ;CAAa;CAMzE,KAAK,MAAM,cAAc,YAAY;EACnC,IAAI;EACJ,IAAI;GACF,MAAM,sBAAsB,MAAM,cAAc,oBAAoB,KAAK;IAAE;IAAO,cAAc,WAAW;GAAG,CAAC;GAO/G,YAAW,MANwB,QAAQ,IACzC,oBAAoB,IAAI,OAAM,uBAAsB;IAClD;IACA,YAAY,MAAM,cAAc,aAAa,IAAI;K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EACrB,YAAY;CACd,CAAC;CACD,OAAO;EACL,WAAW,QAAQ;EACnB;EACA,qBAAqB,SAAS;EAC9B,QAAQ,QAAQ;EAChB,YAAY,SAAS;CACvB;AACF;;;;;;;;;AA4BA,eAAsB,sBAAsB,SAAyB,MAAgD;CACnH,IAAI;EACF,MAAM,SACJ,KAAK,kBAAkB,KAAK,mBACxB,MAAM,KAAK,eAAe,IAAI;GAC5B,OAAO,KAAK;GACZ,QAAQ,4BAA4B,KAAK,gBAAgB;EAC3D,CAAC,IACD;EAIN,MAAM,WAAW,KAAK,gBAAgB,MAAM,GAAG,CAAC,CAAC;EAEjD,MAAM,0BAA0B,SAAS,QADf,WAAW,yBAAyB,UAAU,KAAK,cAAc,CAAC,CAAC,UAAU,KAAA,CACrC;CACpE,SAAS,OAAO;EACd,QAAQ,KAAK,iEAAiE,EAC5E,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAC9D,CAAC;CACH;CACA,IAAI,KAAK,gBACP,IAAI;EACF,MAAM,QAAQ,MAAM,OAAO,EAAE,SAAS,KAAK,eAAe,CAAC;CAC7D,SAAS,OAAO;EACd,QAAQ,KAAK,yDAAyD;GACpE,SAAS,KAAK;GACd,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;AAEJ"}
|
|
1
|
+
{"version":3,"file":"factory-session.js","names":[],"sources":["../../src/session/factory-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { resolveProviderOMDefault } from '@mastra/code-sdk/onboarding/packs';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\n\nimport { factoryMemorySettingsUserId } from '../storage/domains/memory-settings/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { applyStoredMemorySettings } from './memory-settings-hydration.js';\n\ntype FactorySession = Awaited<ReturnType<AgentController<MastraCodeState>['createSession']>>;\n\n/**\n * Read the factory project's default model. Best-effort: a missing project or an\n * uninitialized storage domain means \"no default\", never a failed run.\n */\nexport async function resolveFactoryDefaultModelId(\n projects: FactoryProjectsStorage | undefined,\n factoryProjectId: string | undefined,\n): Promise<string | undefined> {\n if (!projects || !factoryProjectId) return undefined;\n try {\n const project = await projects.getById({ id: factoryProjectId });\n return project?.defaultModelId ?? undefined;\n } catch {\n return undefined;\n }\n}\n\nexport interface EnsureFactorySourceSessionArgs {\n /**\n * Storage handle of the integration that owns source control. Nothing here is\n * provider-specific: the connection is matched by the handle's own\n * `integrationId`, so GitHub, Slack-on-behalf-of-GitHub, or any future owner\n * all resolve through the same traversal.\n */\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n branch: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n /**\n * Attribute the run to this user instead of the repo connector. Set when the\n * run has an interactive user — e.g. the person who approved a proposed run.\n */\n attributeToUserId?: string;\n}\n\nexport interface EnsuredFactorySourceSession {\n sessionId: string;\n userId: string;\n projectRepositoryId: string;\n branch: string;\n baseBranch: string;\n}\n\nexport class FactorySourceSessionResolutionError extends Error {\n constructor(readonly reason: 'connection' | 'repository') {\n super(\n reason === 'connection'\n ? 'Factory source-control connection not found.'\n : 'Factory source-control repository not found.',\n );\n this.name = 'FactorySourceSessionResolutionError';\n }\n}\n\nexport interface ResolvedFactorySourceRepository {\n projectRepositoryId: string;\n /** The repository's pinned branch, else its default branch. */\n baseBranch: string;\n /** Who connected the repository. The attribution for runs with no interactive user. */\n connectedByUserId: string;\n}\n\n/**\n * Outcome of {@link resolveFactorySourceRepository}. A miss carries which step\n * failed: callers differ on whether that is an error (an autonomous run cannot\n * proceed) or a routine fallback (a chat integration drops to a chat-only\n * session), and the two steps fail for different reasons worth reporting apart.\n */\nexport type FactorySourceRepositoryResult =\n | ({ found: true } & ResolvedFactorySourceRepository)\n | { found: false; reason: 'connection' | 'repository' };\n\n/**\n * Resolve which repository a factory project's source-control runs act on: the\n * owner's connection on the project, then one of its linked repositories.\n *\n * The owner is whichever integration owns source control, matched by the\n * handle's own `integrationId` — nothing here is provider-specific.\n */\nexport async function resolveFactorySourceRepository(args: {\n sourceControl: SourceControlStorageHandle;\n orgId: string;\n factoryProjectId: string;\n /** Pick a specific linked repository by slug. Defaults to the first linked repository. */\n repositorySlug?: string;\n}): Promise<FactorySourceRepositoryResult> {\n const { sourceControl, orgId, factoryProjectId, repositorySlug } = args;\n\n const connections = await sourceControl.connections.list({ orgId, factoryProjectId });\n const candidates = connections.filter(candidate => candidate.integrationId === sourceControl.integrationId);\n if (candidates.length === 0) return { found: false, reason: 'connection' };\n\n // A project can carry stale connections: a provider-app reinstall leaves the\n // old connection pointing at an installation that no longer exists, and that\n // row can sit ahead of the healthy one. Try every candidate and skip the ones\n // that no longer resolve rather than failing on the first.\n for (const connection of candidates) {\n let resolved;\n try {\n const projectRepositories = await sourceControl.projectRepositories.list({ orgId, connectionId: connection.id });\n const resolvedRepositories = await Promise.all(\n projectRepositories.map(async projectRepository => ({\n projectRepository,\n repository: await sourceControl.repositories.get({ orgId, id: projectRepository.repositoryId }),\n })),\n );\n resolved = resolvedRepositories.find(\n candidate => candidate.repository && (!repositorySlug || candidate.repository.slug === repositorySlug),\n );\n } catch {\n // The connection no longer resolves (e.g. its installation was deleted).\n continue;\n }\n if (!resolved?.repository) continue;\n\n return {\n found: true,\n projectRepositoryId: resolved.projectRepository.id,\n baseBranch: resolved.projectRepository.branch ?? resolved.repository.defaultBranch,\n connectedByUserId: connection.createdByUserId,\n };\n }\n\n return { found: false, reason: 'repository' };\n}\n\n/**\n * Walk a Factory user-session id back to the project it belongs to.\n *\n * Repo-backed channel threads are keyed by their Factory session id, which is\n * the only handle a session-start hook gets. This turns that id back into the\n * project whose configuration the session should adopt. Durable by\n * construction — it reads the same rows the session was created from, so it\n * survives restarts without any in-memory mapping.\n */\nexport async function resolveFactoryProjectForSession(args: {\n sourceControl: SourceControlStorageHandle;\n sessionId: string;\n}): Promise<{ factoryProjectId: string; orgId: string; userId: string } | null> {\n const { sourceControl, sessionId } = args;\n\n const session = await sourceControl.sessions.getBySessionId(sessionId);\n if (!session) return null;\n const projectRepository = await sourceControl.projectRepositories.get({\n orgId: session.orgId,\n id: session.projectRepositoryId,\n });\n if (!projectRepository) return null;\n const connection = await sourceControl.connections.get({ orgId: session.orgId, id: projectRepository.connectionId });\n if (!connection) return null;\n\n return { factoryProjectId: connection.factoryProjectId, orgId: session.orgId, userId: session.userId };\n}\n\n/**\n * Create the source-control session a repo-backed factory run needs.\n *\n * `FactoryStartCoordinator.prepare` requires this record to already exist —\n * `resolveSourceSession` throws `Factory session not found` otherwise — so every\n * autonomous entry point has to produce one before it can start a run. This is\n * that step, in one place: the owner's connection on the factory project, one of\n * its linked repositories, and a session on the requested branch with the\n * repository's pinned or default branch as the base.\n *\n * The run is attributed to `attributeToUserId` when the caller has an\n * interactive user (e.g. the approver of a proposed run), and otherwise falls\n * back to whoever connected the repository (`connection.createdByUserId`),\n * because a genuinely autonomous run has no interactive user of its own.\n */\nexport async function ensureFactorySourceSession(\n args: EnsureFactorySourceSessionArgs,\n): Promise<EnsuredFactorySourceSession> {\n const { sourceControl, orgId, factoryProjectId, branch, repositorySlug } = args;\n\n const resolved = await resolveFactorySourceRepository({ sourceControl, orgId, factoryProjectId, repositorySlug });\n if (!resolved.found) throw new FactorySourceSessionResolutionError(resolved.reason);\n\n const userId = args.attributeToUserId ?? resolved.connectedByUserId;\n const session = await sourceControl.sessions.create({\n sessionId: randomUUID(),\n projectRepositoryId: resolved.projectRepositoryId,\n orgId,\n userId,\n branch,\n baseBranch: resolved.baseBranch,\n visibility: 'org',\n });\n return {\n sessionId: session.sessionId,\n userId,\n projectRepositoryId: resolved.projectRepositoryId,\n branch: session.branch,\n baseBranch: resolved.baseBranch,\n };\n}\n\nexport interface HydrateFactorySessionArgs {\n orgId: string;\n /**\n * The factory project whose shared memory settings apply. Factory sessions\n * never read an individual user's personal memory settings — the project's\n * own row (or the built-in defaults) is what they run with.\n */\n factoryProjectId?: string;\n /** The factory project's default model. Without it the session keeps the SDK's built-in mode default. */\n defaultModelId?: string;\n /**\n * When provided, the factory project's stored memory-settings row is\n * applied. When omitted (or no row exists) the session is reset to the\n * built-in memory defaults.\n */\n memorySettings?: MemorySettingsStorage;\n}\n\n/**\n * Apply a factory project's configuration to a freshly created session:\n * observational-memory settings, then the project's default model.\n *\n * Both steps are best-effort. A retired model id or an unreachable settings row\n * must not sink a run that is otherwise ready — the session simply keeps the\n * default it was created with, and the reason is logged.\n */\nexport async function hydrateFactorySession(session: FactorySession, args: HydrateFactorySessionArgs): Promise<void> {\n try {\n const record =\n args.memorySettings && args.factoryProjectId\n ? await args.memorySettings.get({\n orgId: args.orgId,\n userId: factoryMemorySettingsUserId(args.factoryProjectId),\n })\n : null;\n // Without a stored row, fall back to the low-cost OM model of the factory\n // default model's provider — a factory connected only to Anthropic should\n // not observe with the (uncredentialed) built-in Google default.\n const provider = args.defaultModelId?.split('/')[0];\n const fallbackOmModelId = provider ? resolveProviderOMDefault(provider, args.defaultModelId).modelId : undefined;\n await applyStoredMemorySettings(session, record, fallbackOmModelId);\n } catch (error) {\n console.warn('[Factory Start] Failed to apply observational-memory settings', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n if (args.defaultModelId) {\n try {\n await session.model.switch({ modelId: args.defaultModelId });\n } catch (error) {\n console.warn('[Factory Start] Failed to apply factory default model', {\n modelId: args.defaultModelId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;AAkBA,eAAsB,6BACpB,UACA,kBAC6B;CAC7B,IAAI,CAAC,YAAY,CAAC,kBAAkB,OAAO,KAAA;CAC3C,IAAI;EAEF,QAAO,MADe,SAAS,QAAQ,EAAE,IAAI,iBAAiB,CAAC,EAAA,EAC/C,kBAAkB,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QAAQ,MAAM,UAAU,OAAO,KAAK,EAC9D,CAAC;CACH;CACA,IAAI,KAAK,gBACP,IAAI;EACF,MAAM,QAAQ,MAAM,OAAO,EAAE,SAAS,KAAK,eAAe,CAAC;CAC7D,SAAS,OAAO;EACd,QAAQ,KAAK,yDAAyD;GACpE,SAAS,KAAK;GACd,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH;AAEJ"}
|
|
@@ -12,18 +12,24 @@ export interface FirstExecCaptureDependencies {
|
|
|
12
12
|
};
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
|
-
* Record when a session's agent completed its first successful
|
|
16
|
-
* (the TTFME anchor — "time to first meaningful exec").
|
|
15
|
+
* Record when a session's agent completed its first successful meaningful
|
|
16
|
+
* tool call (the TTFME anchor — "time to first meaningful exec").
|
|
17
17
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
* the
|
|
22
|
-
*
|
|
23
|
-
*
|
|
18
|
+
* Meaningful = a workspace tool the agent invoked itself (filesystem,
|
|
19
|
+
* search, code intelligence, sandbox exec, process control). We accept any
|
|
20
|
+
* tool whose name starts with the workspace prefix `mastra_workspace_` or
|
|
21
|
+
* matches the post-remap mastracode tool names. Non-workspace tools (memory,
|
|
22
|
+
* notification inbox, subagent, etc.) and skill-loader / preflight /
|
|
23
|
+
* materializer `sandbox.executeCommand()` calls that never flow through the
|
|
24
|
+
* tool layer are intentionally excluded.
|
|
24
25
|
*
|
|
25
|
-
* Failed
|
|
26
|
-
*
|
|
26
|
+
* Failed tool calls (`isError === true`) don't count. Approval-denied and
|
|
27
|
+
* abort-while-parked tool completions (`denied === true`) also don't count:
|
|
28
|
+
* the run-engine emits `tool_end` with `isError: false` for those paths
|
|
29
|
+
* because the tool didn't fail, but it also never ran, so treating them as
|
|
30
|
+
* "meaningful exec" would re-introduce the same contamination this fix is
|
|
31
|
+
* removing on the message side. The listener stays subscribed until a
|
|
32
|
+
* successful qualifying end, then unsubscribes. The storage write is guarded
|
|
27
33
|
* (`first_meaningful_exec_at IS NULL`), so restarts, re-materialized
|
|
28
34
|
* sessions, and sessions without a source-control row are no-ops.
|
|
29
35
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"first-exec-capture.d.ts","sourceRoot":"","sources":["../../src/session/first-exec-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"first-exec-capture.d.ts","sourceRoot":"","sources":["../../src/session/first-exec-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAG1E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,QAAQ,EAAE;QAAE,aAAa,IAAI,MAAM,CAAA;KAAE,CAAC;IAC/C,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACxE;AAED,MAAM,WAAW,4BAA4B;IAC3C,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,yBAAyB,CAAC,CAAC;KACnF,CAAC;CACH;AAmCD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,uBAAuB,EAChC,EAAE,aAAa,EAAE,EAAE,4BAA4B,GAC9C,MAAM,IAAI,CAoDZ"}
|
|
@@ -1,27 +1,87 @@
|
|
|
1
|
+
import { WORKSPACE_TOOLS_PREFIX } from "@mastra/core/workspace";
|
|
1
2
|
//#region src/session/first-exec-capture.ts
|
|
2
3
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
4
|
+
* Tool names that count as "meaningful exec" independent of the workspace
|
|
5
|
+
* prefix. The workspace tools get remapped from `mastra_workspace_*` to
|
|
6
|
+
* mastracode-friendly names (see `mastracode/sdk/src/tool-names.ts`), and
|
|
7
|
+
* this listener runs on the emitted tool name after remap, so both spellings
|
|
8
|
+
* need to match.
|
|
9
|
+
*/
|
|
10
|
+
const MEANINGFUL_TOOL_NAMES = /* @__PURE__ */ new Set([
|
|
11
|
+
"view",
|
|
12
|
+
"write_file",
|
|
13
|
+
"string_replace_lsp",
|
|
14
|
+
"find_files",
|
|
15
|
+
"delete_file",
|
|
16
|
+
"file_stat",
|
|
17
|
+
"mkdir",
|
|
18
|
+
"search_content",
|
|
19
|
+
"ast_smart_edit",
|
|
20
|
+
"lsp_inspect",
|
|
21
|
+
"execute_command",
|
|
22
|
+
"get_process_output",
|
|
23
|
+
"kill_process"
|
|
24
|
+
]);
|
|
25
|
+
function isMeaningfulToolName(name) {
|
|
26
|
+
if (!name) return false;
|
|
27
|
+
if (name.startsWith(`${WORKSPACE_TOOLS_PREFIX}_`)) return true;
|
|
28
|
+
return MEANINGFUL_TOOL_NAMES.has(name);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Record when a session's agent completed its first successful meaningful
|
|
32
|
+
* tool call (the TTFME anchor — "time to first meaningful exec").
|
|
5
33
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* the
|
|
10
|
-
*
|
|
11
|
-
*
|
|
34
|
+
* Meaningful = a workspace tool the agent invoked itself (filesystem,
|
|
35
|
+
* search, code intelligence, sandbox exec, process control). We accept any
|
|
36
|
+
* tool whose name starts with the workspace prefix `mastra_workspace_` or
|
|
37
|
+
* matches the post-remap mastracode tool names. Non-workspace tools (memory,
|
|
38
|
+
* notification inbox, subagent, etc.) and skill-loader / preflight /
|
|
39
|
+
* materializer `sandbox.executeCommand()` calls that never flow through the
|
|
40
|
+
* tool layer are intentionally excluded.
|
|
12
41
|
*
|
|
13
|
-
* Failed
|
|
14
|
-
*
|
|
42
|
+
* Failed tool calls (`isError === true`) don't count. Approval-denied and
|
|
43
|
+
* abort-while-parked tool completions (`denied === true`) also don't count:
|
|
44
|
+
* the run-engine emits `tool_end` with `isError: false` for those paths
|
|
45
|
+
* because the tool didn't fail, but it also never ran, so treating them as
|
|
46
|
+
* "meaningful exec" would re-introduce the same contamination this fix is
|
|
47
|
+
* removing on the message side. The listener stays subscribed until a
|
|
48
|
+
* successful qualifying end, then unsubscribes. The storage write is guarded
|
|
15
49
|
* (`first_meaningful_exec_at IS NULL`), so restarts, re-materialized
|
|
16
50
|
* sessions, and sessions without a source-control row are no-ops.
|
|
17
51
|
*/
|
|
18
52
|
function observeSessionFirstExec(session, { sourceControl }) {
|
|
19
53
|
let seen = false;
|
|
54
|
+
const toolNames = /* @__PURE__ */ new Map();
|
|
55
|
+
const suspended = /* @__PURE__ */ new Set();
|
|
20
56
|
const unsubscribe = session.subscribe((event) => {
|
|
21
|
-
if (seen
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
57
|
+
if (seen) return;
|
|
58
|
+
switch (event.type) {
|
|
59
|
+
case "tool_start":
|
|
60
|
+
toolNames.set(event.toolCallId, event.toolName);
|
|
61
|
+
return;
|
|
62
|
+
case "tool_suspended":
|
|
63
|
+
suspended.add(event.toolCallId);
|
|
64
|
+
return;
|
|
65
|
+
case "tool_suspension_cancelled":
|
|
66
|
+
toolNames.delete(event.toolCallId);
|
|
67
|
+
suspended.delete(event.toolCallId);
|
|
68
|
+
return;
|
|
69
|
+
case "agent_end":
|
|
70
|
+
for (const id of toolNames.keys()) if (!suspended.has(id)) toolNames.delete(id);
|
|
71
|
+
return;
|
|
72
|
+
case "tool_end": {
|
|
73
|
+
const toolName = toolNames.get(event.toolCallId);
|
|
74
|
+
toolNames.delete(event.toolCallId);
|
|
75
|
+
suspended.delete(event.toolCallId);
|
|
76
|
+
if (event.isError) return;
|
|
77
|
+
if (event.denied) return;
|
|
78
|
+
if (!isMeaningfulToolName(toolName)) return;
|
|
79
|
+
seen = true;
|
|
80
|
+
unsubscribe();
|
|
81
|
+
sourceControl.sessions.markFirstMeaningfulExec({ sessionId: session.identity.getResourceId() }).catch((error) => console.warn("[Factory first-exec capture] Unable to persist first exec time.", error));
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
25
85
|
});
|
|
26
86
|
return unsubscribe;
|
|
27
87
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"first-exec-capture.js","names":[],"sources":["../../src/session/first-exec-capture.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\n\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nexport interface FirstExecCaptureSession {\n readonly identity: { getResourceId(): string };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\nexport interface FirstExecCaptureDependencies {\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'markFirstMeaningfulExec'>;\n };\n}\n\n/**\n * Record when a session's agent completed its first successful
|
|
1
|
+
{"version":3,"file":"first-exec-capture.js","names":[],"sources":["../../src/session/first-exec-capture.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\nimport { WORKSPACE_TOOLS_PREFIX } from '@mastra/core/workspace';\n\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nexport interface FirstExecCaptureSession {\n readonly identity: { getResourceId(): string };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\nexport interface FirstExecCaptureDependencies {\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'markFirstMeaningfulExec'>;\n };\n}\n\n/**\n * Tool names that count as \"meaningful exec\" independent of the workspace\n * prefix. The workspace tools get remapped from `mastra_workspace_*` to\n * mastracode-friendly names (see `mastracode/sdk/src/tool-names.ts`), and\n * this listener runs on the emitted tool name after remap, so both spellings\n * need to match.\n */\nconst MEANINGFUL_TOOL_NAMES: ReadonlySet<string> = new Set([\n // Filesystem (post-remap)\n 'view',\n 'write_file',\n 'string_replace_lsp',\n 'find_files',\n 'delete_file',\n 'file_stat',\n 'mkdir',\n // Search\n 'search_content',\n // Code intelligence\n 'ast_smart_edit',\n 'lsp_inspect',\n // Sandbox\n 'execute_command',\n 'get_process_output',\n 'kill_process',\n]);\n\nfunction isMeaningfulToolName(name: string | undefined): boolean {\n if (!name) return false;\n if (name.startsWith(`${WORKSPACE_TOOLS_PREFIX}_`)) return true;\n return MEANINGFUL_TOOL_NAMES.has(name);\n}\n\n/**\n * Record when a session's agent completed its first successful meaningful\n * tool call (the TTFME anchor — \"time to first meaningful exec\").\n *\n * Meaningful = a workspace tool the agent invoked itself (filesystem,\n * search, code intelligence, sandbox exec, process control). We accept any\n * tool whose name starts with the workspace prefix `mastra_workspace_` or\n * matches the post-remap mastracode tool names. Non-workspace tools (memory,\n * notification inbox, subagent, etc.) and skill-loader / preflight /\n * materializer `sandbox.executeCommand()` calls that never flow through the\n * tool layer are intentionally excluded.\n *\n * Failed tool calls (`isError === true`) don't count. Approval-denied and\n * abort-while-parked tool completions (`denied === true`) also don't count:\n * the run-engine emits `tool_end` with `isError: false` for those paths\n * because the tool didn't fail, but it also never ran, so treating them as\n * \"meaningful exec\" would re-introduce the same contamination this fix is\n * removing on the message side. The listener stays subscribed until a\n * successful qualifying end, then unsubscribes. The storage write is guarded\n * (`first_meaningful_exec_at IS NULL`), so restarts, re-materialized\n * sessions, and sessions without a source-control row are no-ops.\n */\nexport function observeSessionFirstExec(\n session: FirstExecCaptureSession,\n { sourceControl }: FirstExecCaptureDependencies,\n): () => void {\n let seen = false;\n // toolCallId -> toolName. Populated on `tool_start`, consumed on `tool_end`.\n // Suspended entries survive `agent_end` so the resumed run can still resolve\n // its tool name when the eventual `tool_end` arrives.\n const toolNames = new Map<string, string>();\n const suspended = new Set<string>();\n const unsubscribe = session.subscribe(event => {\n if (seen) return;\n switch (event.type) {\n case 'tool_start': {\n toolNames.set(event.toolCallId, event.toolName);\n return;\n }\n case 'tool_suspended': {\n suspended.add(event.toolCallId);\n return;\n }\n case 'tool_suspension_cancelled': {\n toolNames.delete(event.toolCallId);\n suspended.delete(event.toolCallId);\n return;\n }\n case 'agent_end': {\n // Drop any in-flight starts that will never see a matching `tool_end`\n // on this run. Genuinely suspended calls stay so their eventual\n // resume-time `tool_end` can still map back to a tool name. Without\n // this, sessions that repeatedly abort or error before a qualifying\n // completion would accumulate stale entries for the entire lifetime\n // of the subscription.\n for (const id of toolNames.keys()) {\n if (!suspended.has(id)) toolNames.delete(id);\n }\n return;\n }\n case 'tool_end': {\n const toolName = toolNames.get(event.toolCallId);\n toolNames.delete(event.toolCallId);\n suspended.delete(event.toolCallId);\n if (event.isError) return;\n if (event.denied) return;\n if (!isMeaningfulToolName(toolName)) return;\n seen = true;\n unsubscribe();\n void sourceControl.sessions\n .markFirstMeaningfulExec({ sessionId: session.identity.getResourceId() })\n .catch(error => console.warn('[Factory first-exec capture] Unable to persist first exec time.', error));\n return;\n }\n }\n });\n return unsubscribe;\n}\n"],"mappings":";;;;;;;;;AAuBA,MAAM,wCAA6C,IAAI,IAAI;CAEzD;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CAEA;CACA;CAEA;CACA;CACA;AACF,CAAC;AAED,SAAS,qBAAqB,MAAmC;CAC/D,IAAI,CAAC,MAAM,OAAO;CAClB,IAAI,KAAK,WAAW,GAAG,uBAAuB,EAAE,GAAG,OAAO;CAC1D,OAAO,sBAAsB,IAAI,IAAI;AACvC;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,wBACd,SACA,EAAE,iBACU;CACZ,IAAI,OAAO;CAIX,MAAM,4BAAY,IAAI,IAAoB;CAC1C,MAAM,4BAAY,IAAI,IAAY;CAClC,MAAM,cAAc,QAAQ,WAAU,UAAS;EAC7C,IAAI,MAAM;EACV,QAAQ,MAAM,MAAd;GACE,KAAK;IACH,UAAU,IAAI,MAAM,YAAY,MAAM,QAAQ;IAC9C;GAEF,KAAK;IACH,UAAU,IAAI,MAAM,UAAU;IAC9B;GAEF,KAAK;IACH,UAAU,OAAO,MAAM,UAAU;IACjC,UAAU,OAAO,MAAM,UAAU;IACjC;GAEF,KAAK;IAOH,KAAK,MAAM,MAAM,UAAU,KAAK,GAC9B,IAAI,CAAC,UAAU,IAAI,EAAE,GAAG,UAAU,OAAO,EAAE;IAE7C;GAEF,KAAK,YAAY;IACf,MAAM,WAAW,UAAU,IAAI,MAAM,UAAU;IAC/C,UAAU,OAAO,MAAM,UAAU;IACjC,UAAU,OAAO,MAAM,UAAU;IACjC,IAAI,MAAM,SAAS;IACnB,IAAI,MAAM,QAAQ;IAClB,IAAI,CAAC,qBAAqB,QAAQ,GAAG;IACrC,OAAO;IACP,YAAY;IACZ,cAAmB,SAChB,wBAAwB,EAAE,WAAW,QAAQ,SAAS,cAAc,EAAE,CAAC,CAAC,CACxE,OAAM,UAAS,QAAQ,KAAK,mEAAmE,KAAK,CAAC;IACxG;GACF;EACF;CACF,CAAC;CACD,OAAO;AACT"}
|
|
@@ -12,18 +12,22 @@ export interface FirstMessageCaptureDependencies {
|
|
|
12
12
|
};
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
|
-
* Record when a session's agent first
|
|
15
|
+
* Record when a session's agent first produced an actual conversational
|
|
16
|
+
* message (the TTFI anchor — "time to first interaction").
|
|
16
17
|
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
18
|
+
* We stamp on the first `message_start` whose role is `user` or `assistant`.
|
|
19
|
+
* The coordinator writes `role='signal'` rows into the thread (skill loads,
|
|
20
|
+
* phase markers, memory reminders) before the model is ever invoked; those
|
|
21
|
+
* signals used to trigger a stamp via `agent_start`, giving every session —
|
|
22
|
+
* including zero-message model-init failures — a false TTFI of a few seconds.
|
|
23
|
+
* Gating on real conversational roles keeps the TTFI column honest: sessions
|
|
24
|
+
* that never produced a user or assistant message stay NULL and drop out of
|
|
25
|
+
* TTFI percentiles instead of contaminating them.
|
|
23
26
|
*
|
|
24
|
-
* The listener unsubscribes after the first
|
|
25
|
-
* guarded (`first_message_at IS NULL`), so restarts, re-materialized
|
|
26
|
-
* and sessions without a source-control row (chat-only channels)
|
|
27
|
+
* The listener unsubscribes after the first qualifying message; the storage
|
|
28
|
+
* write is guarded (`first_message_at IS NULL`), so restarts, re-materialized
|
|
29
|
+
* sessions, and sessions without a source-control row (chat-only channels)
|
|
30
|
+
* are no-ops.
|
|
27
31
|
*/
|
|
28
32
|
export declare function observeSessionFirstMessage(session: FirstMessageCaptureSession, { sourceControl }: FirstMessageCaptureDependencies): () => void;
|
|
29
33
|
//# sourceMappingURL=first-message-capture.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"first-message-capture.d.ts","sourceRoot":"","sources":["../../src/session/first-message-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,QAAQ,EAAE;QAAE,aAAa,IAAI,MAAM,CAAA;KAAE,CAAC;IAC/C,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACxE;AAED,MAAM,WAAW,+BAA+B;IAC9C,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,kBAAkB,CAAC,CAAC;KAC5E,CAAC;CACH;AAED
|
|
1
|
+
{"version":3,"file":"first-message-capture.d.ts","sourceRoot":"","sources":["../../src/session/first-message-capture.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,QAAQ,EAAE;QAAE,aAAa,IAAI,MAAM,CAAA;KAAE,CAAC;IAC/C,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACxE;AAED,MAAM,WAAW,+BAA+B;IAC9C,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,kBAAkB,CAAC,CAAC;KAC5E,CAAC;CACH;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,0BAA0B,CACxC,OAAO,EAAE,0BAA0B,EACnC,EAAE,aAAa,EAAE,EAAE,+BAA+B,GACjD,MAAM,IAAI,CAaZ"}
|
|
@@ -1,22 +1,28 @@
|
|
|
1
1
|
//#region src/session/first-message-capture.ts
|
|
2
2
|
/**
|
|
3
|
-
* Record when a session's agent first
|
|
3
|
+
* Record when a session's agent first produced an actual conversational
|
|
4
|
+
* message (the TTFI anchor — "time to first interaction").
|
|
4
5
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
6
|
+
* We stamp on the first `message_start` whose role is `user` or `assistant`.
|
|
7
|
+
* The coordinator writes `role='signal'` rows into the thread (skill loads,
|
|
8
|
+
* phase markers, memory reminders) before the model is ever invoked; those
|
|
9
|
+
* signals used to trigger a stamp via `agent_start`, giving every session —
|
|
10
|
+
* including zero-message model-init failures — a false TTFI of a few seconds.
|
|
11
|
+
* Gating on real conversational roles keeps the TTFI column honest: sessions
|
|
12
|
+
* that never produced a user or assistant message stay NULL and drop out of
|
|
13
|
+
* TTFI percentiles instead of contaminating them.
|
|
11
14
|
*
|
|
12
|
-
* The listener unsubscribes after the first
|
|
13
|
-
* guarded (`first_message_at IS NULL`), so restarts, re-materialized
|
|
14
|
-
* and sessions without a source-control row (chat-only channels)
|
|
15
|
+
* The listener unsubscribes after the first qualifying message; the storage
|
|
16
|
+
* write is guarded (`first_message_at IS NULL`), so restarts, re-materialized
|
|
17
|
+
* sessions, and sessions without a source-control row (chat-only channels)
|
|
18
|
+
* are no-ops.
|
|
15
19
|
*/
|
|
16
20
|
function observeSessionFirstMessage(session, { sourceControl }) {
|
|
17
21
|
let seen = false;
|
|
18
22
|
const unsubscribe = session.subscribe((event) => {
|
|
19
|
-
if (seen || event.type !== "
|
|
23
|
+
if (seen || event.type !== "message_start") return;
|
|
24
|
+
const role = event.message.role;
|
|
25
|
+
if (role !== "user" && role !== "assistant") return;
|
|
20
26
|
seen = true;
|
|
21
27
|
unsubscribe();
|
|
22
28
|
sourceControl.sessions.markFirstMessage({ sessionId: session.identity.getResourceId() }).catch((error) => console.warn("[Factory first-message capture] Unable to persist first message time.", error));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"first-message-capture.js","names":[],"sources":["../../src/session/first-message-capture.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\n\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nexport interface FirstMessageCaptureSession {\n readonly identity: { getResourceId(): string };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\nexport interface FirstMessageCaptureDependencies {\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'markFirstMessage'>;\n };\n}\n\n/**\n * Record when a session's agent first
|
|
1
|
+
{"version":3,"file":"first-message-capture.js","names":[],"sources":["../../src/session/first-message-capture.ts"],"sourcesContent":["import type { AgentControllerEvent } from '@mastra/core/agent-controller';\n\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\n\nexport interface FirstMessageCaptureSession {\n readonly identity: { getResourceId(): string };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\nexport interface FirstMessageCaptureDependencies {\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'markFirstMessage'>;\n };\n}\n\n/**\n * Record when a session's agent first produced an actual conversational\n * message (the TTFI anchor — \"time to first interaction\").\n *\n * We stamp on the first `message_start` whose role is `user` or `assistant`.\n * The coordinator writes `role='signal'` rows into the thread (skill loads,\n * phase markers, memory reminders) before the model is ever invoked; those\n * signals used to trigger a stamp via `agent_start`, giving every session —\n * including zero-message model-init failures — a false TTFI of a few seconds.\n * Gating on real conversational roles keeps the TTFI column honest: sessions\n * that never produced a user or assistant message stay NULL and drop out of\n * TTFI percentiles instead of contaminating them.\n *\n * The listener unsubscribes after the first qualifying message; the storage\n * write is guarded (`first_message_at IS NULL`), so restarts, re-materialized\n * sessions, and sessions without a source-control row (chat-only channels)\n * are no-ops.\n */\nexport function observeSessionFirstMessage(\n session: FirstMessageCaptureSession,\n { sourceControl }: FirstMessageCaptureDependencies,\n): () => void {\n let seen = false;\n const unsubscribe = session.subscribe(event => {\n if (seen || event.type !== 'message_start') return;\n const role = event.message.role;\n if (role !== 'user' && role !== 'assistant') return;\n seen = true;\n unsubscribe();\n void sourceControl.sessions\n .markFirstMessage({ sessionId: session.identity.getResourceId() })\n .catch(error => console.warn('[Factory first-message capture] Unable to persist first message time.', error));\n });\n return unsubscribe;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,2BACd,SACA,EAAE,iBACU;CACZ,IAAI,OAAO;CACX,MAAM,cAAc,QAAQ,WAAU,UAAS;EAC7C,IAAI,QAAQ,MAAM,SAAS,iBAAiB;EAC5C,MAAM,OAAO,MAAM,QAAQ;EAC3B,IAAI,SAAS,UAAU,SAAS,aAAa;EAC7C,OAAO;EACP,YAAY;EACZ,cAAmB,SAChB,iBAAiB,EAAE,WAAW,QAAQ,SAAS,cAAc,EAAE,CAAC,CAAC,CACjE,OAAM,UAAS,QAAQ,KAAK,yEAAyE,KAAK,CAAC;CAChH,CAAC;CACD,OAAO;AACT"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one shape a session row's title may take, wherever it comes from — typed
|
|
3
|
+
* by a user at creation, generated for its thread, or refined by the observer.
|
|
4
|
+
* Returns null when nothing readable is left, so callers can reject or skip.
|
|
5
|
+
*/
|
|
6
|
+
export declare function normalizeSessionTitle(title: string): string | null;
|
|
7
|
+
//# sourceMappingURL=session-title.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-title.d.ts","sourceRoot":"","sources":["../../src/session/session-title.ts"],"names":[],"mappings":"AAEA;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAIlE"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/session/session-title.ts
|
|
2
|
+
const MAX_SESSION_TITLE_LENGTH = 80;
|
|
3
|
+
/**
|
|
4
|
+
* The one shape a session row's title may take, wherever it comes from — typed
|
|
5
|
+
* by a user at creation, generated for its thread, or refined by the observer.
|
|
6
|
+
* Returns null when nothing readable is left, so callers can reject or skip.
|
|
7
|
+
*/
|
|
8
|
+
function normalizeSessionTitle(title) {
|
|
9
|
+
return [...title.replace(/\s+/g, " ").trim()].slice(0, MAX_SESSION_TITLE_LENGTH).join("").trimEnd() || null;
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
12
|
+
export { normalizeSessionTitle };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=session-title.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"session-title.js","names":[],"sources":["../../src/session/session-title.ts"],"sourcesContent":["const MAX_SESSION_TITLE_LENGTH = 80;\n\n/**\n * The one shape a session row's title may take, wherever it comes from — typed\n * by a user at creation, generated for its thread, or refined by the observer.\n * Returns null when nothing readable is left, so callers can reject or skip.\n */\nexport function normalizeSessionTitle(title: string): string | null {\n // Cap code points, not UTF-16 units: an emoji straddling the cap would store a lone surrogate.\n const capped = [...title.replace(/\\s+/g, ' ').trim()].slice(0, MAX_SESSION_TITLE_LENGTH).join('');\n return capped.trimEnd() || null;\n}\n"],"mappings":";AAAA,MAAM,2BAA2B;;;;;;AAOjC,SAAgB,sBAAsB,OAA8B;CAGlE,OADe,CAAC,GAAG,MAAM,QAAQ,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,MAAM,GAAG,wBAAwB,CAAC,CAAC,KAAK,EAClF,CAAC,CAAC,QAAQ,KAAK;AAC7B"}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { AgentControllerEvent, AgentControllerThread } from '@mastra/core/agent-controller';
|
|
2
|
+
import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
|
|
3
|
+
export interface ThreadTitleMirrorSession {
|
|
4
|
+
readonly identity: {
|
|
5
|
+
getResourceId(): string;
|
|
6
|
+
};
|
|
7
|
+
readonly thread: {
|
|
8
|
+
getById(args: {
|
|
9
|
+
threadId: string;
|
|
10
|
+
}): Promise<AgentControllerThread | null>;
|
|
11
|
+
};
|
|
12
|
+
subscribe(listener: (event: AgentControllerEvent) => void): () => void;
|
|
13
|
+
}
|
|
14
|
+
export interface ThreadTitleMirrorDependencies {
|
|
15
|
+
sourceControl: {
|
|
16
|
+
sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId' | 'rename'>;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Project the bound thread's title onto its source-control session row, from
|
|
21
|
+
* whichever namer produced it — core on the first turn, the observational-memory
|
|
22
|
+
* observer as the thread grows, or an explicit rename.
|
|
23
|
+
*
|
|
24
|
+
* The factory sidebar reads the session row, which otherwise keeps the raw first
|
|
25
|
+
* prompt (chat sessions) or nothing at all (work sessions, which then show their
|
|
26
|
+
* branch). Binding a thread reconciles the row against the stored title, so a
|
|
27
|
+
* session started before this ran — or one whose rename event was missed — is
|
|
28
|
+
* named the next time it is opened.
|
|
29
|
+
*
|
|
30
|
+
* A session names threads it is no longer showing, and each write reads the row
|
|
31
|
+
* before replacing it. Titles for any other thread are therefore dropped, and
|
|
32
|
+
* writes run one at a time so the last event wins rather than the fastest.
|
|
33
|
+
*/
|
|
34
|
+
export declare function observeSessionThreadTitle(session: ThreadTitleMirrorSession, { sourceControl }: ThreadTitleMirrorDependencies): () => void;
|
|
35
|
+
//# sourceMappingURL=thread-title-mirror.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"thread-title-mirror.d.ts","sourceRoot":"","sources":["../../src/session/thread-title-mirror.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAEjG,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAG5F,MAAM,WAAW,wBAAwB;IACvC,QAAQ,CAAC,QAAQ,EAAE;QAAE,aAAa,IAAI,MAAM,CAAA;KAAE,CAAC;IAC/C,QAAQ,CAAC,MAAM,EAAE;QAAE,OAAO,CAAC,IAAI,EAAE;YAAE,QAAQ,EAAE,MAAM,CAAA;SAAE,GAAG,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC,CAAA;KAAE,CAAC;IAChG,SAAS,CAAC,QAAQ,EAAE,CAAC,KAAK,EAAE,oBAAoB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CACxE;AAED,MAAM,WAAW,6BAA6B;IAC5C,aAAa,EAAE;QACb,QAAQ,EAAE,IAAI,CAAC,0BAA0B,CAAC,UAAU,CAAC,EAAE,gBAAgB,GAAG,QAAQ,CAAC,CAAC;KACrF,CAAC;CACH;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,wBAAwB,EACjC,EAAE,aAAa,EAAE,EAAE,6BAA6B,GAC/C,MAAM,IAAI,CAuCZ"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { normalizeSessionTitle } from "./session-title.js";
|
|
2
|
+
//#region src/session/thread-title-mirror.ts
|
|
3
|
+
/**
|
|
4
|
+
* Project the bound thread's title onto its source-control session row, from
|
|
5
|
+
* whichever namer produced it — core on the first turn, the observational-memory
|
|
6
|
+
* observer as the thread grows, or an explicit rename.
|
|
7
|
+
*
|
|
8
|
+
* The factory sidebar reads the session row, which otherwise keeps the raw first
|
|
9
|
+
* prompt (chat sessions) or nothing at all (work sessions, which then show their
|
|
10
|
+
* branch). Binding a thread reconciles the row against the stored title, so a
|
|
11
|
+
* session started before this ran — or one whose rename event was missed — is
|
|
12
|
+
* named the next time it is opened.
|
|
13
|
+
*
|
|
14
|
+
* A session names threads it is no longer showing, and each write reads the row
|
|
15
|
+
* before replacing it. Titles for any other thread are therefore dropped, and
|
|
16
|
+
* writes run one at a time so the last event wins rather than the fastest.
|
|
17
|
+
*/
|
|
18
|
+
function observeSessionThreadTitle(session, { sourceControl }) {
|
|
19
|
+
const sessionId = session.identity.getResourceId();
|
|
20
|
+
let boundThreadId;
|
|
21
|
+
let writes = Promise.resolve();
|
|
22
|
+
const project = (threadId, rawTitle) => {
|
|
23
|
+
boundThreadId ??= threadId;
|
|
24
|
+
if (threadId !== boundThreadId) return;
|
|
25
|
+
const title = rawTitle ? normalizeSessionTitle(rawTitle) : null;
|
|
26
|
+
if (!title) return;
|
|
27
|
+
writes = writes.then(async () => {
|
|
28
|
+
if (threadId !== boundThreadId) return;
|
|
29
|
+
const row = await sourceControl.sessions.getBySessionId(sessionId);
|
|
30
|
+
if (!row || row.title === title) return;
|
|
31
|
+
await sourceControl.sessions.rename({
|
|
32
|
+
sessionId,
|
|
33
|
+
title
|
|
34
|
+
});
|
|
35
|
+
}).catch((error) => console.warn("[Factory thread-title mirror] Unable to persist the session title.", error));
|
|
36
|
+
};
|
|
37
|
+
return session.subscribe((event) => {
|
|
38
|
+
switch (event.type) {
|
|
39
|
+
case "thread_title_updated": return project(event.threadId, event.title);
|
|
40
|
+
case "om_thread_title_updated": return project(event.threadId, event.newTitle);
|
|
41
|
+
case "thread_changed":
|
|
42
|
+
boundThreadId = event.threadId;
|
|
43
|
+
session.thread.getById({ threadId: event.threadId }).then((thread) => project(event.threadId, thread?.title)).catch((error) => console.warn("[Factory thread-title mirror] Unable to read the bound thread.", error));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
//#endregion
|
|
49
|
+
export { observeSessionThreadTitle };
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=thread-title-mirror.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"thread-title-mirror.js","names":[],"sources":["../../src/session/thread-title-mirror.ts"],"sourcesContent":["import type { AgentControllerEvent, AgentControllerThread } from '@mastra/core/agent-controller';\n\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { normalizeSessionTitle } from './session-title.js';\n\nexport interface ThreadTitleMirrorSession {\n readonly identity: { getResourceId(): string };\n readonly thread: { getById(args: { threadId: string }): Promise<AgentControllerThread | null> };\n subscribe(listener: (event: AgentControllerEvent) => void): () => void;\n}\n\nexport interface ThreadTitleMirrorDependencies {\n sourceControl: {\n sessions: Pick<SourceControlStorageHandle['sessions'], 'getBySessionId' | 'rename'>;\n };\n}\n\n/**\n * Project the bound thread's title onto its source-control session row, from\n * whichever namer produced it — core on the first turn, the observational-memory\n * observer as the thread grows, or an explicit rename.\n *\n * The factory sidebar reads the session row, which otherwise keeps the raw first\n * prompt (chat sessions) or nothing at all (work sessions, which then show their\n * branch). Binding a thread reconciles the row against the stored title, so a\n * session started before this ran — or one whose rename event was missed — is\n * named the next time it is opened.\n *\n * A session names threads it is no longer showing, and each write reads the row\n * before replacing it. Titles for any other thread are therefore dropped, and\n * writes run one at a time so the last event wins rather than the fastest.\n */\nexport function observeSessionThreadTitle(\n session: ThreadTitleMirrorSession,\n { sourceControl }: ThreadTitleMirrorDependencies,\n): () => void {\n const sessionId = session.identity.getResourceId();\n let boundThreadId: string | undefined;\n let writes: Promise<void> = Promise.resolve();\n\n const project = (threadId: string, rawTitle: string | undefined): void => {\n // A thread can be named before anything binds one, so the first thread to\n // surface a title speaks for the row until `thread_changed` rebinds it.\n boundThreadId ??= threadId;\n if (threadId !== boundThreadId) return;\n const title = rawTitle ? normalizeSessionTitle(rawTitle) : null;\n if (!title) return;\n\n writes = writes\n .then(async () => {\n if (threadId !== boundThreadId) return;\n const row = await sourceControl.sessions.getBySessionId(sessionId);\n if (!row || row.title === title) return;\n await sourceControl.sessions.rename({ sessionId, title });\n })\n .catch(error => console.warn('[Factory thread-title mirror] Unable to persist the session title.', error));\n };\n\n return session.subscribe(event => {\n switch (event.type) {\n case 'thread_title_updated':\n return project(event.threadId, event.title);\n case 'om_thread_title_updated':\n return project(event.threadId, event.newTitle);\n case 'thread_changed': {\n boundThreadId = event.threadId;\n void session.thread\n .getById({ threadId: event.threadId })\n .then(thread => project(event.threadId, thread?.title))\n .catch(error => console.warn('[Factory thread-title mirror] Unable to read the bound thread.', error));\n return;\n }\n }\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,SAAgB,0BACd,SACA,EAAE,iBACU;CACZ,MAAM,YAAY,QAAQ,SAAS,cAAc;CACjD,IAAI;CACJ,IAAI,SAAwB,QAAQ,QAAQ;CAE5C,MAAM,WAAW,UAAkB,aAAuC;EAGxE,kBAAkB;EAClB,IAAI,aAAa,eAAe;EAChC,MAAM,QAAQ,WAAW,sBAAsB,QAAQ,IAAI;EAC3D,IAAI,CAAC,OAAO;EAEZ,SAAS,OACN,KAAK,YAAY;GAChB,IAAI,aAAa,eAAe;GAChC,MAAM,MAAM,MAAM,cAAc,SAAS,eAAe,SAAS;GACjE,IAAI,CAAC,OAAO,IAAI,UAAU,OAAO;GACjC,MAAM,cAAc,SAAS,OAAO;IAAE;IAAW;GAAM,CAAC;EAC1D,CAAC,CAAC,CACD,OAAM,UAAS,QAAQ,KAAK,sEAAsE,KAAK,CAAC;CAC7G;CAEA,OAAO,QAAQ,WAAU,UAAS;EAChC,QAAQ,MAAM,MAAd;GACE,KAAK,wBACH,OAAO,QAAQ,MAAM,UAAU,MAAM,KAAK;GAC5C,KAAK,2BACH,OAAO,QAAQ,MAAM,UAAU,MAAM,QAAQ;GAC/C,KAAK;IACH,gBAAgB,MAAM;IACtB,QAAa,OACV,QAAQ,EAAE,UAAU,MAAM,SAAS,CAAC,CAAC,CACrC,MAAK,WAAU,QAAQ,MAAM,UAAU,QAAQ,KAAK,CAAC,CAAC,CACtD,OAAM,UAAS,QAAQ,KAAK,kEAAkE,KAAK,CAAC;IACvG;EAEJ;CACF,CAAC;AACH"}
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
import type { AuthCredential, OAuthCredential } from '@mastra/code-sdk/auth/types';
|
|
26
26
|
import { FactoryStorageDomain } from '@mastra/core/storage';
|
|
27
27
|
import type { CollectionSchema } from '@mastra/core/storage';
|
|
28
|
+
import type { FactorySecretEncryption } from '../../../secret-encryption.js';
|
|
28
29
|
/** Owning tenant of a credential row. `userId` absent = org-scoped row. */
|
|
29
30
|
export interface CredentialTenant {
|
|
30
31
|
orgId: string;
|
|
@@ -88,7 +89,8 @@ export declare const OAUTH_LOGIN_SESSIONS_SCHEMA: CollectionSchema;
|
|
|
88
89
|
*/
|
|
89
90
|
export declare class ModelCredentialsStorage extends FactoryStorageDomain {
|
|
90
91
|
#private;
|
|
91
|
-
|
|
92
|
+
private readonly encryption;
|
|
93
|
+
constructor(encryption?: FactorySecretEncryption);
|
|
92
94
|
init(): Promise<void>;
|
|
93
95
|
dangerouslyClearAll(): Promise<void>;
|
|
94
96
|
/** Read the tenant's credential for a provider at exactly that scope. */
|