@mastra/factory 0.29.0-alpha.7 → 0.29.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +50 -20
- package/dist/boards/board-events.d.ts +23 -0
- package/dist/boards/board-events.d.ts.map +1 -1
- package/dist/boards/board-events.js +37 -3
- package/dist/boards/board-events.js.map +1 -1
- package/dist/boards/board-writes.d.ts +6 -4
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +9 -6
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/boards/intake-routing.d.ts +30 -16
- package/dist/boards/intake-routing.d.ts.map +1 -1
- package/dist/boards/intake-routing.js +41 -28
- package/dist/boards/intake-routing.js.map +1 -1
- package/dist/boards/project-boards.d.ts +15 -0
- package/dist/boards/project-boards.d.ts.map +1 -1
- package/dist/boards/project-boards.js +43 -7
- package/dist/boards/project-boards.js.map +1 -1
- package/dist/factory.d.ts +4 -14
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +22 -15
- package/dist/factory.js.map +1 -1
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +101 -0
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +7 -3
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts +7 -1
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +15 -1
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/github/session-subscriptions.js +1 -1
- package/dist/integrations/github/session-subscriptions.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +2 -1
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js +1 -1
- package/dist/integrations/gitlab/session-subscriptions.js.map +1 -1
- package/dist/integrations/slack/channel-reply-processor.d.ts +1 -0
- package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
- package/dist/integrations/slack/channel-reply-processor.js +4 -1
- package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
- package/dist/integrations/slack/run-error-card.js +6 -1
- package/dist/integrations/slack/run-error-card.js.map +1 -1
- package/dist/links.d.ts +4 -2
- package/dist/links.d.ts.map +1 -1
- package/dist/links.js +5 -3
- package/dist/links.js.map +1 -1
- package/dist/routes/boards.d.ts +1 -1
- package/dist/routes/boards.d.ts.map +1 -1
- package/dist/routes/boards.js.map +1 -1
- package/dist/routes/contracts.d.ts +32 -5
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +36 -9
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/intake-check.d.ts.map +1 -1
- package/dist/routes/intake-check.js +3 -1
- package/dist/routes/intake-check.js.map +1 -1
- package/dist/routes/intake-routes.d.ts +0 -3
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js +1 -1
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/skills.d.ts +1 -1
- package/dist/routes/skills.d.ts.map +1 -1
- package/dist/routes/skills.js +92 -28
- package/dist/routes/skills.js.map +1 -1
- package/dist/routes/surface.d.ts +0 -3
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +0 -1
- package/dist/routes/surface.js.map +1 -1
- package/dist/rules/dispatch-errors.d.ts +6 -0
- package/dist/rules/dispatch-errors.d.ts.map +1 -1
- package/dist/rules/dispatch-errors.js +10 -1
- package/dist/rules/dispatch-errors.js.map +1 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +74 -32
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/event-rules.d.ts +3 -2
- package/dist/rules/event-rules.d.ts.map +1 -1
- package/dist/rules/event-rules.js +5 -3
- package/dist/rules/event-rules.js.map +1 -1
- package/dist/rules/public-failure-reason.d.ts +11 -0
- package/dist/rules/public-failure-reason.d.ts.map +1 -0
- package/dist/rules/public-failure-reason.js +136 -0
- package/dist/rules/public-failure-reason.js.map +1 -0
- package/dist/rules/transition-service.d.ts +13 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +5 -1
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +12 -0
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +11 -2
- package/dist/rules/validation.js.map +1 -1
- package/dist/run-error.d.ts +1 -1
- package/dist/run-error.d.ts.map +1 -1
- package/dist/run-error.js +21 -12
- package/dist/run-error.js.map +1 -1
- package/dist/session/environment-state-processor.d.ts.map +1 -1
- package/dist/session/environment-state-processor.js +6 -2
- package/dist/session/environment-state-processor.js.map +1 -1
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +5 -3
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/skills/app-skills.d.ts +3 -2
- package/dist/skills/app-skills.d.ts.map +1 -1
- package/dist/skills/app-skills.js +5 -3
- package/dist/skills/app-skills.js.map +1 -1
- package/dist/skills/catalog.d.ts +23 -4
- package/dist/skills/catalog.d.ts.map +1 -1
- package/dist/skills/catalog.js +61 -28
- package/dist/skills/catalog.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +1 -1
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +6 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +12 -0
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +3 -0
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
- package/dist/storage/domains/boards/schemas.js +4 -0
- package/dist/storage/domains/boards/schemas.js.map +1 -1
- package/dist/storage/domains/skill-overrides/base.d.ts +28 -4
- package/dist/storage/domains/skill-overrides/base.d.ts.map +1 -1
- package/dist/storage/domains/skill-overrides/base.js +54 -1
- package/dist/storage/domains/skill-overrides/base.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +2 -0
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +13 -5
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/tools/audit-events-tool.d.ts +1 -1
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +0 -1
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +0 -3
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +2 -1
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/workspace.d.ts +5 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +69 -9
- package/dist/workspace.js.map +1 -1
- package/package.json +13 -13
package/dist/rules/validation.js
CHANGED
|
@@ -87,6 +87,7 @@ function boardEvent(value, label) {
|
|
|
87
87
|
"assignees",
|
|
88
88
|
"pullRequest",
|
|
89
89
|
"pullRequestTrusted",
|
|
90
|
+
"actorTrusted",
|
|
90
91
|
"closedIssue"
|
|
91
92
|
], `${label} event`);
|
|
92
93
|
const type = enumValue(value.type, STATUS_EVENTS, `${label} event type`);
|
|
@@ -95,6 +96,7 @@ function boardEvent(value, label) {
|
|
|
95
96
|
const labels = itemChange(value.labels, `${label} event labels`);
|
|
96
97
|
const assignees = itemChange(value.assignees, `${label} event assignees`);
|
|
97
98
|
if (value.pullRequestTrusted !== void 0 && typeof value.pullRequestTrusted !== "boolean") throw new FactoryRuleValidationError(`${label} event pullRequestTrusted must be a boolean.`);
|
|
99
|
+
if (value.actorTrusted !== void 0 && typeof value.actorTrusted !== "boolean") throw new FactoryRuleValidationError(`${label} event actorTrusted must be a boolean.`);
|
|
98
100
|
if (value.pullRequest !== void 0 && (typeof value.pullRequest !== "string" || value.pullRequest.length === 0)) throw new FactoryRuleValidationError(`${label} event pullRequest must be a non-empty string.`);
|
|
99
101
|
return {
|
|
100
102
|
type,
|
|
@@ -103,6 +105,7 @@ function boardEvent(value, label) {
|
|
|
103
105
|
...assignees ? { assignees } : {},
|
|
104
106
|
...typeof value.pullRequest === "string" ? { pullRequest: value.pullRequest } : {},
|
|
105
107
|
...typeof value.pullRequestTrusted === "boolean" ? { pullRequestTrusted: value.pullRequestTrusted } : {},
|
|
108
|
+
...typeof value.actorTrusted === "boolean" ? { actorTrusted: value.actorTrusted } : {},
|
|
106
109
|
...value.closedIssue !== void 0 ? { closedIssue: closedIssueFacts(value.closedIssue, label) } : {}
|
|
107
110
|
};
|
|
108
111
|
}
|
|
@@ -349,6 +352,7 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
349
352
|
"precedingMessage",
|
|
350
353
|
"cancelInFlight",
|
|
351
354
|
"startsAfterOwnMove",
|
|
355
|
+
"untrustedPullRequestEvent",
|
|
352
356
|
"resume",
|
|
353
357
|
"goal"
|
|
354
358
|
], "Factory invoke skill decision");
|
|
@@ -357,6 +361,7 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
357
361
|
const precedingMessage = optionalBoundedString(value.precedingMessage, "Factory skill preceding message", MAX_MESSAGE_LENGTH);
|
|
358
362
|
if (value.cancelInFlight !== void 0 && typeof value.cancelInFlight !== "boolean") throw new FactoryRuleValidationError("Factory skill cancelInFlight must be a boolean.");
|
|
359
363
|
if (value.startsAfterOwnMove !== void 0 && typeof value.startsAfterOwnMove !== "boolean") throw new FactoryRuleValidationError("Factory skill startsAfterOwnMove must be a boolean.");
|
|
364
|
+
if (value.untrustedPullRequestEvent !== void 0 && typeof value.untrustedPullRequestEvent !== "boolean") throw new FactoryRuleValidationError("Factory skill untrustedPullRequestEvent must be a boolean.");
|
|
360
365
|
if (value.resume !== void 0 && typeof value.resume !== "boolean") throw new FactoryRuleValidationError("Factory skill resume must be a boolean.");
|
|
361
366
|
if (value.resume === true && value.skillName === void 0) throw new FactoryRuleValidationError("Factory skill resume requires skillName.");
|
|
362
367
|
const goal = invokeSkillGoal(value.goal);
|
|
@@ -372,6 +377,7 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
372
377
|
...precedingMessage ? { precedingMessage } : {},
|
|
373
378
|
...value.cancelInFlight === true ? { cancelInFlight: true } : {},
|
|
374
379
|
...value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {},
|
|
380
|
+
...value.untrustedPullRequestEvent === true ? { untrustedPullRequestEvent: true } : {},
|
|
375
381
|
...goal ? { goal } : {}
|
|
376
382
|
};
|
|
377
383
|
}
|
|
@@ -383,7 +389,8 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
383
389
|
"message",
|
|
384
390
|
"priority",
|
|
385
391
|
"idleBehavior",
|
|
386
|
-
"prepareBinding"
|
|
392
|
+
"prepareBinding",
|
|
393
|
+
"untrustedPullRequestEvent"
|
|
387
394
|
], "Factory send message decision");
|
|
388
395
|
const priority = value.priority === void 0 ? void 0 : enumValue(value.priority, [
|
|
389
396
|
"medium",
|
|
@@ -392,6 +399,7 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
392
399
|
], "Factory message priority");
|
|
393
400
|
const idleBehavior = value.idleBehavior === void 0 ? void 0 : enumValue(value.idleBehavior, ["persist", "wake"], "Factory message idle behavior");
|
|
394
401
|
if (value.prepareBinding !== void 0 && typeof value.prepareBinding !== "boolean") throw new FactoryRuleValidationError("Factory message prepareBinding must be a boolean.");
|
|
402
|
+
if (value.untrustedPullRequestEvent !== void 0 && typeof value.untrustedPullRequestEvent !== "boolean") throw new FactoryRuleValidationError("Factory message untrustedPullRequestEvent must be a boolean.");
|
|
395
403
|
if (value.prepareBinding === true && value.role === void 0) throw new FactoryRuleValidationError("Factory message prepareBinding requires a role.");
|
|
396
404
|
const role = value.role === void 0 ? void 0 : boundedString(value.role, "Factory message role", 32, IDENTIFIER_RE);
|
|
397
405
|
return {
|
|
@@ -401,7 +409,8 @@ function validateFactoryRuleDecision(value, causalDepth = 0) {
|
|
|
401
409
|
message: boundedString(value.message, "Factory message", MAX_MESSAGE_LENGTH),
|
|
402
410
|
...priority ? { priority } : {},
|
|
403
411
|
...idleBehavior ? { idleBehavior } : {},
|
|
404
|
-
...value.prepareBinding === true ? { prepareBinding: true } : {}
|
|
412
|
+
...value.prepareBinding === true ? { prepareBinding: true } : {},
|
|
413
|
+
...value.untrustedPullRequestEvent === true ? { untrustedPullRequestEvent: true } : {}
|
|
405
414
|
};
|
|
406
415
|
}
|
|
407
416
|
case "notify": {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"validation.js","names":[],"sources":["../../src/rules/validation.ts"],"sourcesContent":["import { ACTIVITY_EVENTS, CLOSE_REASONS, isUpdateEvent, STATUS_EVENTS } from '../boards/board-events.js';\nimport type { BoardEventFacts, ItemChange } from '../boards/board-events.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleRejectionCode,\n FactoryRouteEventDecision,\n FactoryTransitionDecision,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_DESCRIPTION_LENGTH = 8000;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nexport const MAX_ROLE_LENGTH = 32;\nexport const MAX_TOOL_NAME_LENGTH = 128;\nexport const MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nexport const MAX_BOARD_IDENTIFIER_LENGTH = 128;\n/** A source reference such as `acme/app#12` or `group/sub/project#3`. */\nconst SOURCE_REFERENCE_RE = /^[a-z0-9_][a-z0-9_.\\/-]*#\\d+$/i;\n/** A provider login such as `octocat`, `dependabot[bot]`, `jane.doe` or GitLab's `_jane`. */\nconst LOGIN_RE = /^[a-z0-9_][a-z0-9_.-]*(\\[bot\\])?$/i;\nconst MAX_LOGIN_LENGTH = 100;\nexport const IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nexport const BOARD_IDENTIFIER_RE = IDENTIFIER_RE;\nexport const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = [\n 'github-issue',\n 'github-pr',\n 'gitlab-issue',\n 'gitlab-pr',\n 'linear-issue',\n 'jira-issue',\n 'incidentio-follow-up',\n 'github-dependabot-alert',\n 'vanta-vulnerability',\n 'detail-finding',\n 'manual',\n];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nexport function isBoardIdentifier(value: unknown): value is string {\n return typeof value === 'string' && value.length <= MAX_BOARD_IDENTIFIER_LENGTH && BOARD_IDENTIFIER_RE.test(value);\n}\n\nfunction boardIdentifier(value: unknown, label: string): string {\n if (!isBoardIdentifier(value)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value;\n}\n\nfunction boardEvent(value: unknown, label: string): BoardEventFacts {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event must be an object.`);\n assertExactKeys(\n value,\n ['type', 'reason', 'labels', 'assignees', 'pullRequest', 'pullRequestTrusted', 'closedIssue'],\n `${label} event`,\n );\n const type = enumValue(value.type, STATUS_EVENTS, `${label} event type`);\n const reason =\n value.reason === undefined ? undefined : enumValue(value.reason, CLOSE_REASONS, `${label} event reason`);\n if ((value.labels !== undefined || value.assignees !== undefined) && !isUpdateEvent(type)) {\n throw new FactoryRuleValidationError(`${label} event only carries changes on an update.`);\n }\n const labels = itemChange(value.labels, `${label} event labels`);\n const assignees = itemChange(value.assignees, `${label} event assignees`);\n if (value.pullRequestTrusted !== undefined && typeof value.pullRequestTrusted !== 'boolean') {\n throw new FactoryRuleValidationError(`${label} event pullRequestTrusted must be a boolean.`);\n }\n if (value.pullRequest !== undefined && (typeof value.pullRequest !== 'string' || value.pullRequest.length === 0)) {\n throw new FactoryRuleValidationError(`${label} event pullRequest must be a non-empty string.`);\n }\n return {\n type,\n ...(reason ? { reason } : {}),\n ...(labels ? { labels } : {}),\n ...(assignees ? { assignees } : {}),\n ...(typeof value.pullRequest === 'string' ? { pullRequest: value.pullRequest } : {}),\n ...(typeof value.pullRequestTrusted === 'boolean' ? { pullRequestTrusted: value.pullRequestTrusted } : {}),\n ...(value.closedIssue !== undefined ? { closedIssue: closedIssueFacts(value.closedIssue, label) } : {}),\n };\n}\n\nconst MAX_CHANGED_NAMES = 100;\nconst MAX_CHANGED_NAME_LENGTH = 500;\n\nfunction itemChange(value: unknown, label: string): ItemChange | undefined {\n if (value === undefined) return undefined;\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} must be an object.`);\n assertExactKeys(value, ['added', 'removed'], label);\n const names = (list: unknown, side: string) => {\n if (!Array.isArray(list) || list.length > MAX_CHANGED_NAMES) {\n throw new FactoryRuleValidationError(`${label} ${side} must be a list of at most ${MAX_CHANGED_NAMES} names.`);\n }\n return list.map(name => boundedString(name, `${label} ${side}`, MAX_CHANGED_NAME_LENGTH));\n };\n return { added: names(value.added, 'added'), removed: names(value.removed, 'removed') };\n}\n\nfunction closedIssueFacts(value: unknown, label: string): NonNullable<BoardEventFacts['closedIssue']> {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event closedIssue must be an object.`);\n assertExactKeys(value, ['phase', 'hasPullRequest'], `${label} event closedIssue`);\n if (value.phase !== null && !isBoardIdentifier(value.phase)) {\n throw new FactoryRuleValidationError(`${label} event closedIssue.phase is invalid.`);\n }\n if (typeof value.hasPullRequest !== 'boolean') {\n throw new FactoryRuleValidationError(`${label} event closedIssue.hasPullRequest must be a boolean.`);\n }\n return { phase: value.phase, hasPullRequest: value.hasPullRequest };\n}\n\nfunction linkedItemReference(value: unknown, field: 'attachTo' | 'closesIssue'): { workItemId: string } | undefined {\n if (value === undefined) return undefined;\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new FactoryRuleValidationError(`Factory linked work item ${field} must be an object.`);\n }\n assertExactKeys(value as Record<string, unknown>, ['workItemId'], `Factory linked work item ${field}`);\n const { workItemId } = value as Record<string, unknown>;\n return { workItemId: boundedString(workItemId, `Factory linked work item ${field}.workItemId`, 128) };\n}\n\nexport function assertFactoryDecisionTarget(\n decision: FactoryRuleDecision,\n boards: BoardRegistry,\n itemBoard?: string | null,\n): void {\n if (decision.type !== 'transition' && decision.type !== 'upsertLinkedWorkItem') return;\n const board = boards.get(decision.board);\n if (!board) throw new FactoryRuleValidationError('Factory decision target board is not installed.');\n if (!Object.hasOwn(board.phases, decision.stage)) {\n throw new FactoryRuleValidationError('Factory decision target phase is not defined on its board.');\n }\n if (decision.type === 'transition' && itemBoard !== undefined && itemBoard !== decision.board) {\n throw new FactoryRuleValidationError('Factory transition cannot change the item board.');\n }\n}\n\nconst MAX_GOAL_OBJECTIVE_LENGTH = 2_000;\nconst MAX_GOAL_RUNS = 50;\n\nfunction invokeSkillGoal(value: unknown): { objective: string; maxRuns?: number } | undefined {\n if (value === undefined) return undefined;\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory skill goal must be an object.');\n assertExactKeys(value, ['objective', 'maxRuns'], 'Factory skill goal');\n const objective = boundedString(value.objective, 'Factory skill goal objective', MAX_GOAL_OBJECTIVE_LENGTH);\n const { maxRuns } = value;\n if (\n maxRuns !== undefined &&\n (typeof maxRuns !== 'number' || !Number.isInteger(maxRuns) || maxRuns < 1 || maxRuns > MAX_GOAL_RUNS)\n ) {\n throw new FactoryRuleValidationError('Factory skill goal maxRuns is invalid.');\n }\n return { objective, ...(maxRuns !== undefined ? { maxRuns } : {}) };\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nexport const DEFAULT_FACTORY_CONFIG_VERSION = 'factory-config-v1';\n\n/** Operator-maintained provenance label stamped on transition audit and deferred-decision rows. */\nexport function assertFactoryConfigVersion(value: unknown): string {\n return boundedString(value, 'Factory configVersion', MAX_VERSION_LENGTH);\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'stage', 'message', 'reenter', 'event'],\n 'Factory transition decision',\n );\n if (value.reenter !== undefined && typeof value.reenter !== 'boolean') {\n throw new FactoryRuleValidationError('Factory transition reenter must be a boolean.');\n }\n let message: { text: string; role?: string } | undefined;\n if (value.message !== undefined) {\n if (!isPlainObject(value.message)) {\n throw new FactoryRuleValidationError('Factory transition message must be an object.');\n }\n assertExactKeys(value.message, ['text', 'role'], 'Factory transition message');\n const role =\n value.message.role === undefined\n ? undefined\n : boundedString(value.message.role, 'Factory transition message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n message = {\n text: boundedString(value.message.text, 'Factory transition message text', MAX_MESSAGE_LENGTH),\n ...(role ? { role } : {}),\n };\n }\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory transition board'),\n stage: boardIdentifier(value.stage, 'Factory transition stage'),\n ...(message ? { message } : {}),\n ...(value.reenter === true ? { reenter: true } : {}),\n ...(value.event !== undefined ? { event: boardEvent(value.event, 'Factory transition') } : {}),\n };\n }\n case 'routeEvent': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'event', 'fromCardSession'], 'Factory routeEvent decision');\n const event = boardEvent(value.event, 'Factory routeEvent');\n if (value.fromCardSession !== undefined && (value.fromCardSession !== true || !isUpdateEvent(event.type))) {\n throw new FactoryRuleValidationError('Factory routeEvent fromCardSession is only true, on an update.');\n }\n return { type, ...commonCommitFields(value), event, ...(value.fromCardSession ? { fromCardSession: true } : {}) };\n }\n case 'signalActivity': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'event', 'reference', 'url', 'author', 'authorTrusted', 'idleBehavior'],\n 'Factory signalActivity decision',\n );\n const url = value.url;\n if (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\/\\S+$/.test(url)) {\n throw new FactoryRuleValidationError('Factory signalActivity url must be an http(s) URL.');\n }\n if (typeof value.authorTrusted !== 'boolean') {\n throw new FactoryRuleValidationError('Factory signalActivity authorTrusted must be a boolean.');\n }\n const author =\n value.author === undefined\n ? undefined\n : boundedString(value.author, 'Factory signalActivity author', MAX_LOGIN_LENGTH, LOGIN_RE);\n return {\n type,\n ...commonCommitFields(value),\n event: enumValue(value.event, ACTIVITY_EVENTS, 'Factory signalActivity event'),\n reference: boundedString(\n value.reference,\n 'Factory signalActivity reference',\n MAX_SOURCE_KEY_LENGTH,\n SOURCE_REFERENCE_RE,\n ),\n url,\n ...(author ? { author } : {}),\n authorTrusted: value.authorTrusted,\n ...(value.idleBehavior === undefined\n ? {}\n : {\n idleBehavior: enumValue(\n value.idleBehavior,\n ['wake', 'persist'] as const,\n 'Factory signalActivity idleBehavior',\n ),\n }),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'board',\n 'source',\n 'sourceKey',\n // Decisions saved before claims were dropped still carry it; it is ignored.\n 'claimKey',\n 'title',\n 'description',\n 'url',\n 'stage',\n 'skipRules',\n 'attachTo',\n 'closesIssue',\n 'metadata',\n ],\n 'Factory linked work item decision',\n );\n if (value.skipRules !== undefined && typeof value.skipRules !== 'boolean') {\n throw new FactoryRuleValidationError('Factory linked work item skipRules must be a boolean.');\n }\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n const attachTo = linkedItemReference(value.attachTo, 'attachTo');\n const closesIssue = linkedItemReference(value.closesIssue, 'closesIssue');\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n ...(value.description === undefined\n ? {}\n : {\n description: boundedString(\n value.description,\n 'Factory linked work item description',\n MAX_DESCRIPTION_LENGTH,\n ),\n }),\n url,\n stage: boardIdentifier(value.stage, 'Factory linked work item stage'),\n ...(value.skipRules === true ? { skipRules: true } : {}),\n ...(attachTo ? { attachTo } : {}),\n ...(closesIssue ? { closesIssue } : {}),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'role',\n 'skillName',\n 'prompt',\n 'arguments',\n 'precedingMessage',\n 'cancelInFlight',\n 'startsAfterOwnMove',\n 'resume',\n 'goal',\n ],\n 'Factory invoke skill decision',\n );\n // A run activates a skill or carries a prompt, never both: they are two\n // ways to author the same kickoff message, so accepting both would leave\n // the dispatcher picking a winner.\n if ((value.skillName === undefined) === (value.prompt === undefined)) {\n throw new FactoryRuleValidationError('Factory skill invocation needs exactly one of skillName or prompt.');\n }\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n if (value.cancelInFlight !== undefined && typeof value.cancelInFlight !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill cancelInFlight must be a boolean.');\n }\n if (value.startsAfterOwnMove !== undefined && typeof value.startsAfterOwnMove !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill startsAfterOwnMove must be a boolean.');\n }\n if (value.resume !== undefined && typeof value.resume !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill resume must be a boolean.');\n }\n // Resume continues an already-active skill by name; a plain prompt run has no\n // skill to resume, so the dispatcher would silently ignore the flag.\n if (value.resume === true && value.skillName === undefined) {\n throw new FactoryRuleValidationError('Factory skill resume requires skillName.');\n }\n const goal = invokeSkillGoal(value.goal);\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n ...(value.skillName === undefined\n ? { prompt: boundedString(value.prompt, 'Factory skill prompt', MAX_MESSAGE_LENGTH) }\n : {\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(value.resume === true ? { resume: true } : {}),\n }),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n ...(value.cancelInFlight === true ? { cancelInFlight: true } : {}),\n ...(value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {}),\n ...(goal ? { goal } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'role', 'message', 'priority', 'idleBehavior', 'prepareBinding'],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n if (value.prepareBinding === true && value.role === undefined) {\n throw new FactoryRuleValidationError('Factory message prepareBinding requires a role.');\n }\n const role =\n value.role === undefined\n ? undefined\n : boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n return {\n type,\n ...commonCommitFields(value),\n ...(role ? { role } : {}),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n case 'dismissStaleReviews': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'installationId',\n 'repository',\n 'pullRequestNumber',\n 'approvingReviewId',\n 'approvingAuthor',\n ],\n 'Factory dismiss stale reviews decision',\n );\n for (const key of ['installationId', 'pullRequestNumber'] as const) {\n if (!Number.isSafeInteger(value[key]) || (value[key] as number) <= 0) {\n throw new FactoryRuleValidationError(`Factory dismiss stale reviews ${key} must be a positive integer.`);\n }\n }\n return {\n type,\n ...commonCommitFields(value),\n installationId: value.installationId as number,\n repository: boundedString(value.repository, 'Factory dismiss stale reviews repository', MAX_TITLE_LENGTH),\n pullRequestNumber: value.pullRequestNumber as number,\n approvingReviewId: boundedString(value.approvingReviewId, 'Factory approving review id', MAX_TITLE_LENGTH),\n approvingAuthor: boundedString(value.approvingAuthor, 'Factory approving review author', MAX_TITLE_LENGTH),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n"],"mappings":";;AAaA,MAAa,gCAAgC;AAE7C,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AACnC,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAC7B,MAAa,kBAAkB;AAC/B,MAAa,uBAAuB;AACpC,MAAa,wBAAwB;AACrC,MAAM,wBAAwB;AAC9B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AACjC,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AAEjC,MAAa,8BAA8B;;AAE3C,MAAM,sBAAsB;;AAE5B,MAAM,WAAW;AACjB,MAAM,mBAAmB;AACzB,MAAa,gBAAgB;AAC7B,MAAa,sBAAsB;AACnC,MAAa,gBAAgB;AAC7B,MAAM,mBAAmB;AACzB,MAAM,oBAA+C;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,kBAAuD;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAa,6BAAb,cAAgD,MAAM;CACpD,OAAgB;CAEhB,YAAY,SAAiB;EAC3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B,KAAK;IAC3B,OAAO,cAAc,MAAM,OAAO,8BAA8B,gBAAgB;IAChF,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;IACvB,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;GAC3B;EACF;EACA,KAAK;GACH,gBACE,OACA;IACE;IACA;IACA;IACA;IACA;IACA;IACA;GACF,GACA,wCACF;GACA,KAAK,MAAM,OAAO,CAAC,kBAAkB,mBAAmB,GACtD,IAAI,CAAC,OAAO,cAAc,MAAM,IAAI,KAAM,MAAM,QAAmB,GACjE,MAAM,IAAI,2BAA2B,iCAAiC,IAAI,6BAA6B;GAG3G,OAAO;IACL;IACA,GAAG,mBAAmB,KAAK;IAC3B,gBAAgB,MAAM;IACtB,YAAY,cAAc,MAAM,YAAY,4CAA4C,gBAAgB;IACxG,mBAAmB,MAAM;IACzB,mBAAmB,cAAc,MAAM,mBAAmB,+BAA+B,gBAAgB;IACzG,iBAAiB,cAAc,MAAM,iBAAiB,mCAAmC,gBAAgB;GAC3G;EAEF,SACE,MAAM,IAAI,2BAA2B,4CAA4C;CACrF;AACF;AAEA,SAAgB,6BAA6B,QAA4B,cAAc,GAA4B;CACjH,IAAI,OAAO,SAAS,0BAClB,MAAM,IAAI,2BAA2B,2CAA2C;CAElF,MAAM,YAAqC,CAAC;CAC5C,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,4BAA4B,OAAO,WAAW;EAC/D,IAAI,SAAS,SAAS,UACpB,MAAM,IAAI,2BAA2B,wDAAwD;EAE/F,UAAU,KAAK,QAAQ;CACzB;CACA,MAAM,OAAO,UAAU,KAAI,aAAY,SAAS,cAAc;CAC9D,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,SAAS,KAAK,QAC9B,MAAM,IAAI,2BAA2B,oDAAoD;CAE3F,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"validation.js","names":[],"sources":["../../src/rules/validation.ts"],"sourcesContent":["import { ACTIVITY_EVENTS, CLOSE_REASONS, isUpdateEvent, STATUS_EVENTS } from '../boards/board-events.js';\nimport type { BoardEventFacts, ItemChange } from '../boards/board-events.js';\nimport type { BoardRegistry } from '../boards/registry.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleRejectionCode,\n FactoryRouteEventDecision,\n FactoryTransitionDecision,\n WorkItemSource,\n} from './types.js';\n\nexport const MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;\n\nconst MAX_VERSION_LENGTH = 128;\nconst MAX_IDEMPOTENCY_KEY_LENGTH = 256;\nconst MAX_REASON_LENGTH = 512;\nconst MAX_TITLE_LENGTH = 512;\nconst MAX_DESCRIPTION_LENGTH = 8000;\nconst MAX_MESSAGE_LENGTH = 8_192;\nconst MAX_ARGUMENTS_LENGTH = 4_096;\nexport const MAX_ROLE_LENGTH = 32;\nexport const MAX_TOOL_NAME_LENGTH = 128;\nexport const MAX_SKILL_NAME_LENGTH = 128;\nconst MAX_SOURCE_KEY_LENGTH = 256;\nconst MAX_URL_LENGTH = 2_048;\nconst MAX_METADATA_JSON_LENGTH = 16_384;\nconst MAX_JSON_DEPTH = 8;\nconst MAX_JSON_COLLECTION_SIZE = 100;\n\nexport const MAX_BOARD_IDENTIFIER_LENGTH = 128;\n/** A source reference such as `acme/app#12` or `group/sub/project#3`. */\nconst SOURCE_REFERENCE_RE = /^[a-z0-9_][a-z0-9_.\\/-]*#\\d+$/i;\n/** A provider login such as `octocat`, `dependabot[bot]`, `jane.doe` or GitLab's `_jane`. */\nconst LOGIN_RE = /^[a-z0-9_][a-z0-9_.-]*(\\[bot\\])?$/i;\nconst MAX_LOGIN_LENGTH = 100;\nexport const IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;\nexport const BOARD_IDENTIFIER_RE = IDENTIFIER_RE;\nexport const SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;\nconst SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;\nconst WORK_ITEM_SOURCES: readonly WorkItemSource[] = [\n 'github-issue',\n 'github-pr',\n 'gitlab-issue',\n 'gitlab-pr',\n 'linear-issue',\n 'jira-issue',\n 'incidentio-follow-up',\n 'github-dependabot-alert',\n 'vanta-vulnerability',\n 'detail-finding',\n 'manual',\n];\nconst REJECTION_CODES: readonly FactoryRuleRejectionCode[] = [\n 'forbidden',\n 'invalid_transition',\n 'missing_binding',\n 'stale',\n 'timeout',\n 'rule_error',\n 'causal_depth_exceeded',\n 'repeated_transition',\n];\n\nexport class FactoryRuleValidationError extends Error {\n readonly code = 'invalid_factory_rule';\n\n constructor(message: string) {\n super(message);\n this.name = 'FactoryRuleValidationError';\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction assertExactKeys(value: Record<string, unknown>, keys: readonly string[], label: string): void {\n const allowed = new Set(keys);\n if (Object.keys(value).some(key => !allowed.has(key))) {\n throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);\n }\n}\n\nfunction boundedString(value: unknown, label: string, max: number, pattern?: RegExp): string {\n if (typeof value !== 'string') throw new FactoryRuleValidationError(`${label} must be a string.`);\n const normalized = value.trim();\n if (normalized.length === 0 || normalized.length > max || (pattern && !pattern.test(normalized))) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return normalized;\n}\n\nexport function isBoardIdentifier(value: unknown): value is string {\n return typeof value === 'string' && value.length <= MAX_BOARD_IDENTIFIER_LENGTH && BOARD_IDENTIFIER_RE.test(value);\n}\n\nfunction boardIdentifier(value: unknown, label: string): string {\n if (!isBoardIdentifier(value)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value;\n}\n\nfunction boardEvent(value: unknown, label: string): BoardEventFacts {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event must be an object.`);\n assertExactKeys(\n value,\n ['type', 'reason', 'labels', 'assignees', 'pullRequest', 'pullRequestTrusted', 'actorTrusted', 'closedIssue'],\n `${label} event`,\n );\n const type = enumValue(value.type, STATUS_EVENTS, `${label} event type`);\n const reason =\n value.reason === undefined ? undefined : enumValue(value.reason, CLOSE_REASONS, `${label} event reason`);\n if ((value.labels !== undefined || value.assignees !== undefined) && !isUpdateEvent(type)) {\n throw new FactoryRuleValidationError(`${label} event only carries changes on an update.`);\n }\n const labels = itemChange(value.labels, `${label} event labels`);\n const assignees = itemChange(value.assignees, `${label} event assignees`);\n if (value.pullRequestTrusted !== undefined && typeof value.pullRequestTrusted !== 'boolean') {\n throw new FactoryRuleValidationError(`${label} event pullRequestTrusted must be a boolean.`);\n }\n if (value.actorTrusted !== undefined && typeof value.actorTrusted !== 'boolean') {\n throw new FactoryRuleValidationError(`${label} event actorTrusted must be a boolean.`);\n }\n if (value.pullRequest !== undefined && (typeof value.pullRequest !== 'string' || value.pullRequest.length === 0)) {\n throw new FactoryRuleValidationError(`${label} event pullRequest must be a non-empty string.`);\n }\n return {\n type,\n ...(reason ? { reason } : {}),\n ...(labels ? { labels } : {}),\n ...(assignees ? { assignees } : {}),\n ...(typeof value.pullRequest === 'string' ? { pullRequest: value.pullRequest } : {}),\n ...(typeof value.pullRequestTrusted === 'boolean' ? { pullRequestTrusted: value.pullRequestTrusted } : {}),\n ...(typeof value.actorTrusted === 'boolean' ? { actorTrusted: value.actorTrusted } : {}),\n ...(value.closedIssue !== undefined ? { closedIssue: closedIssueFacts(value.closedIssue, label) } : {}),\n };\n}\n\nconst MAX_CHANGED_NAMES = 100;\nconst MAX_CHANGED_NAME_LENGTH = 500;\n\nfunction itemChange(value: unknown, label: string): ItemChange | undefined {\n if (value === undefined) return undefined;\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} must be an object.`);\n assertExactKeys(value, ['added', 'removed'], label);\n const names = (list: unknown, side: string) => {\n if (!Array.isArray(list) || list.length > MAX_CHANGED_NAMES) {\n throw new FactoryRuleValidationError(`${label} ${side} must be a list of at most ${MAX_CHANGED_NAMES} names.`);\n }\n return list.map(name => boundedString(name, `${label} ${side}`, MAX_CHANGED_NAME_LENGTH));\n };\n return { added: names(value.added, 'added'), removed: names(value.removed, 'removed') };\n}\n\nfunction closedIssueFacts(value: unknown, label: string): NonNullable<BoardEventFacts['closedIssue']> {\n if (!isPlainObject(value)) throw new FactoryRuleValidationError(`${label} event closedIssue must be an object.`);\n assertExactKeys(value, ['phase', 'hasPullRequest'], `${label} event closedIssue`);\n if (value.phase !== null && !isBoardIdentifier(value.phase)) {\n throw new FactoryRuleValidationError(`${label} event closedIssue.phase is invalid.`);\n }\n if (typeof value.hasPullRequest !== 'boolean') {\n throw new FactoryRuleValidationError(`${label} event closedIssue.hasPullRequest must be a boolean.`);\n }\n return { phase: value.phase, hasPullRequest: value.hasPullRequest };\n}\n\nfunction linkedItemReference(value: unknown, field: 'attachTo' | 'closesIssue'): { workItemId: string } | undefined {\n if (value === undefined) return undefined;\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new FactoryRuleValidationError(`Factory linked work item ${field} must be an object.`);\n }\n assertExactKeys(value as Record<string, unknown>, ['workItemId'], `Factory linked work item ${field}`);\n const { workItemId } = value as Record<string, unknown>;\n return { workItemId: boundedString(workItemId, `Factory linked work item ${field}.workItemId`, 128) };\n}\n\nexport function assertFactoryDecisionTarget(\n decision: FactoryRuleDecision,\n boards: BoardRegistry,\n itemBoard?: string | null,\n): void {\n if (decision.type !== 'transition' && decision.type !== 'upsertLinkedWorkItem') return;\n const board = boards.get(decision.board);\n if (!board) throw new FactoryRuleValidationError('Factory decision target board is not installed.');\n if (!Object.hasOwn(board.phases, decision.stage)) {\n throw new FactoryRuleValidationError('Factory decision target phase is not defined on its board.');\n }\n if (decision.type === 'transition' && itemBoard !== undefined && itemBoard !== decision.board) {\n throw new FactoryRuleValidationError('Factory transition cannot change the item board.');\n }\n}\n\nconst MAX_GOAL_OBJECTIVE_LENGTH = 2_000;\nconst MAX_GOAL_RUNS = 50;\n\nfunction invokeSkillGoal(value: unknown): { objective: string; maxRuns?: number } | undefined {\n if (value === undefined) return undefined;\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory skill goal must be an object.');\n assertExactKeys(value, ['objective', 'maxRuns'], 'Factory skill goal');\n const objective = boundedString(value.objective, 'Factory skill goal objective', MAX_GOAL_OBJECTIVE_LENGTH);\n const { maxRuns } = value;\n if (\n maxRuns !== undefined &&\n (typeof maxRuns !== 'number' || !Number.isInteger(maxRuns) || maxRuns < 1 || maxRuns > MAX_GOAL_RUNS)\n ) {\n throw new FactoryRuleValidationError('Factory skill goal maxRuns is invalid.');\n }\n return { objective, ...(maxRuns !== undefined ? { maxRuns } : {}) };\n}\n\nfunction optionalBoundedString(value: unknown, label: string, max: number): string | undefined {\n if (value === undefined) return undefined;\n return boundedString(value, label, max);\n}\n\nfunction enumValue<T extends string>(value: unknown, allowed: readonly T[], label: string): T {\n if (typeof value !== 'string' || !allowed.includes(value as T)) {\n throw new FactoryRuleValidationError(`${label} is invalid.`);\n }\n return value as T;\n}\n\nexport function normalizeFactoryRuleJsonValue(\n value: unknown,\n depth = 0,\n seen = new Set<object>(),\n): FactoryRuleJsonValue {\n if (value === null || typeof value === 'boolean' || typeof value === 'string') return value;\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) throw new FactoryRuleValidationError('Rule metadata must contain finite numbers.');\n return value;\n }\n if (depth >= MAX_JSON_DEPTH || (typeof value !== 'object' && !Array.isArray(value))) {\n throw new FactoryRuleValidationError('Rule metadata is not bounded JSON.');\n }\n if (seen.has(value as object)) throw new FactoryRuleValidationError('Rule metadata must not contain cycles.');\n seen.add(value as object);\n try {\n if (Array.isArray(value)) {\n if (value.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many entries.');\n }\n return value.map(entry => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Rule metadata must use plain objects.');\n const entries = Object.entries(value);\n if (entries.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Rule metadata contains too many fields.');\n }\n const sanitized: Record<string, FactoryRuleJsonValue> = {};\n for (const [key, entry] of entries) {\n const normalizedKey = boundedString(key, 'Rule metadata key', 128, IDENTIFIER_RE);\n sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey)\n ? '[REDACTED]'\n : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);\n }\n return sanitized;\n } finally {\n seen.delete(value as object);\n }\n}\n\nfunction sanitizeMetadata(value: unknown): Record<string, FactoryRuleJsonValue> | undefined {\n if (value === undefined) return undefined;\n const sanitized = normalizeFactoryRuleJsonValue(value);\n if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError('Rule metadata must be an object.');\n if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {\n throw new FactoryRuleValidationError('Rule metadata is too large.');\n }\n return sanitized;\n}\n\nexport const DEFAULT_FACTORY_CONFIG_VERSION = 'factory-config-v1';\n\n/** Operator-maintained provenance label stamped on transition audit and deferred-decision rows. */\nexport function assertFactoryConfigVersion(value: unknown): string {\n return boundedString(value, 'Factory configVersion', MAX_VERSION_LENGTH);\n}\n\nfunction commonCommitFields(value: Record<string, unknown>): { idempotencyKey: string } {\n return {\n idempotencyKey: boundedString(value.idempotencyKey, 'Factory decision idempotencyKey', MAX_IDEMPOTENCY_KEY_LENGTH),\n };\n}\n\nexport function validateFactoryRuleDecision(value: unknown, causalDepth = 0): FactoryRuleDecision {\n if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {\n throw new FactoryRuleValidationError('Factory rule causal depth exceeded.');\n }\n if (!isPlainObject(value)) throw new FactoryRuleValidationError('Factory rule decision must be an object.');\n const type = value.type;\n if (typeof type !== 'string') throw new FactoryRuleValidationError('Factory rule decision type is required.');\n\n switch (type) {\n case 'reject': {\n assertExactKeys(value, ['type', 'code', 'reason'], 'Factory reject decision');\n return {\n type,\n code: enumValue(value.code, REJECTION_CODES, 'Factory rejection code'),\n reason: boundedString(value.reason, 'Factory rejection reason', MAX_REASON_LENGTH),\n };\n }\n case 'transition': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'board', 'stage', 'message', 'reenter', 'event'],\n 'Factory transition decision',\n );\n if (value.reenter !== undefined && typeof value.reenter !== 'boolean') {\n throw new FactoryRuleValidationError('Factory transition reenter must be a boolean.');\n }\n let message: { text: string; role?: string } | undefined;\n if (value.message !== undefined) {\n if (!isPlainObject(value.message)) {\n throw new FactoryRuleValidationError('Factory transition message must be an object.');\n }\n assertExactKeys(value.message, ['text', 'role'], 'Factory transition message');\n const role =\n value.message.role === undefined\n ? undefined\n : boundedString(value.message.role, 'Factory transition message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n message = {\n text: boundedString(value.message.text, 'Factory transition message text', MAX_MESSAGE_LENGTH),\n ...(role ? { role } : {}),\n };\n }\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory transition board'),\n stage: boardIdentifier(value.stage, 'Factory transition stage'),\n ...(message ? { message } : {}),\n ...(value.reenter === true ? { reenter: true } : {}),\n ...(value.event !== undefined ? { event: boardEvent(value.event, 'Factory transition') } : {}),\n };\n }\n case 'routeEvent': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'event', 'fromCardSession'], 'Factory routeEvent decision');\n const event = boardEvent(value.event, 'Factory routeEvent');\n if (value.fromCardSession !== undefined && (value.fromCardSession !== true || !isUpdateEvent(event.type))) {\n throw new FactoryRuleValidationError('Factory routeEvent fromCardSession is only true, on an update.');\n }\n return { type, ...commonCommitFields(value), event, ...(value.fromCardSession ? { fromCardSession: true } : {}) };\n }\n case 'signalActivity': {\n assertExactKeys(\n value,\n ['type', 'idempotencyKey', 'event', 'reference', 'url', 'author', 'authorTrusted', 'idleBehavior'],\n 'Factory signalActivity decision',\n );\n const url = value.url;\n if (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\/\\S+$/.test(url)) {\n throw new FactoryRuleValidationError('Factory signalActivity url must be an http(s) URL.');\n }\n if (typeof value.authorTrusted !== 'boolean') {\n throw new FactoryRuleValidationError('Factory signalActivity authorTrusted must be a boolean.');\n }\n const author =\n value.author === undefined\n ? undefined\n : boundedString(value.author, 'Factory signalActivity author', MAX_LOGIN_LENGTH, LOGIN_RE);\n return {\n type,\n ...commonCommitFields(value),\n event: enumValue(value.event, ACTIVITY_EVENTS, 'Factory signalActivity event'),\n reference: boundedString(\n value.reference,\n 'Factory signalActivity reference',\n MAX_SOURCE_KEY_LENGTH,\n SOURCE_REFERENCE_RE,\n ),\n url,\n ...(author ? { author } : {}),\n authorTrusted: value.authorTrusted,\n ...(value.idleBehavior === undefined\n ? {}\n : {\n idleBehavior: enumValue(\n value.idleBehavior,\n ['wake', 'persist'] as const,\n 'Factory signalActivity idleBehavior',\n ),\n }),\n };\n }\n case 'upsertLinkedWorkItem': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'board',\n 'source',\n 'sourceKey',\n // Decisions saved before claims were dropped still carry it; it is ignored.\n 'claimKey',\n 'title',\n 'description',\n 'url',\n 'stage',\n 'skipRules',\n 'attachTo',\n 'closesIssue',\n 'metadata',\n ],\n 'Factory linked work item decision',\n );\n if (value.skipRules !== undefined && typeof value.skipRules !== 'boolean') {\n throw new FactoryRuleValidationError('Factory linked work item skipRules must be a boolean.');\n }\n const url = value.url;\n if (url !== null && (typeof url !== 'string' || url.length > MAX_URL_LENGTH || !/^https?:\\/\\//.test(url))) {\n throw new FactoryRuleValidationError('Factory linked work item URL is invalid.');\n }\n const metadata = sanitizeMetadata(value.metadata);\n const attachTo = linkedItemReference(value.attachTo, 'attachTo');\n const closesIssue = linkedItemReference(value.closesIssue, 'closesIssue');\n return {\n type,\n ...commonCommitFields(value),\n board: boardIdentifier(value.board, 'Factory linked work item board'),\n source: enumValue(value.source, WORK_ITEM_SOURCES, 'Factory linked work item source'),\n sourceKey: boundedString(value.sourceKey, 'Factory linked work item sourceKey', MAX_SOURCE_KEY_LENGTH),\n title: boundedString(value.title, 'Factory linked work item title', MAX_TITLE_LENGTH),\n ...(value.description === undefined\n ? {}\n : {\n description: boundedString(\n value.description,\n 'Factory linked work item description',\n MAX_DESCRIPTION_LENGTH,\n ),\n }),\n url,\n stage: boardIdentifier(value.stage, 'Factory linked work item stage'),\n ...(value.skipRules === true ? { skipRules: true } : {}),\n ...(attachTo ? { attachTo } : {}),\n ...(closesIssue ? { closesIssue } : {}),\n ...(metadata ? { metadata } : {}),\n };\n }\n case 'invokeSkill': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'role',\n 'skillName',\n 'prompt',\n 'arguments',\n 'precedingMessage',\n 'cancelInFlight',\n 'startsAfterOwnMove',\n 'untrustedPullRequestEvent',\n 'resume',\n 'goal',\n ],\n 'Factory invoke skill decision',\n );\n // A run activates a skill or carries a prompt, never both: they are two\n // ways to author the same kickoff message, so accepting both would leave\n // the dispatcher picking a winner.\n if ((value.skillName === undefined) === (value.prompt === undefined)) {\n throw new FactoryRuleValidationError('Factory skill invocation needs exactly one of skillName or prompt.');\n }\n const args = optionalBoundedString(value.arguments, 'Factory skill arguments', MAX_ARGUMENTS_LENGTH);\n const precedingMessage = optionalBoundedString(\n value.precedingMessage,\n 'Factory skill preceding message',\n MAX_MESSAGE_LENGTH,\n );\n if (value.cancelInFlight !== undefined && typeof value.cancelInFlight !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill cancelInFlight must be a boolean.');\n }\n if (value.startsAfterOwnMove !== undefined && typeof value.startsAfterOwnMove !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill startsAfterOwnMove must be a boolean.');\n }\n if (value.untrustedPullRequestEvent !== undefined && typeof value.untrustedPullRequestEvent !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill untrustedPullRequestEvent must be a boolean.');\n }\n if (value.resume !== undefined && typeof value.resume !== 'boolean') {\n throw new FactoryRuleValidationError('Factory skill resume must be a boolean.');\n }\n // Resume continues an already-active skill by name; a plain prompt run has no\n // skill to resume, so the dispatcher would silently ignore the flag.\n if (value.resume === true && value.skillName === undefined) {\n throw new FactoryRuleValidationError('Factory skill resume requires skillName.');\n }\n const goal = invokeSkillGoal(value.goal);\n return {\n type,\n ...commonCommitFields(value),\n role: boundedString(value.role, 'Factory skill role', MAX_ROLE_LENGTH, IDENTIFIER_RE),\n ...(value.skillName === undefined\n ? { prompt: boundedString(value.prompt, 'Factory skill prompt', MAX_MESSAGE_LENGTH) }\n : {\n skillName: boundedString(value.skillName, 'Factory skill name', MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),\n ...(value.resume === true ? { resume: true } : {}),\n }),\n ...(args ? { arguments: args } : {}),\n ...(precedingMessage ? { precedingMessage } : {}),\n ...(value.cancelInFlight === true ? { cancelInFlight: true } : {}),\n ...(value.startsAfterOwnMove === true ? { startsAfterOwnMove: true } : {}),\n ...(value.untrustedPullRequestEvent === true ? { untrustedPullRequestEvent: true } : {}),\n ...(goal ? { goal } : {}),\n };\n }\n case 'sendMessage': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'role',\n 'message',\n 'priority',\n 'idleBehavior',\n 'prepareBinding',\n 'untrustedPullRequestEvent',\n ],\n 'Factory send message decision',\n );\n const priority =\n value.priority === undefined\n ? undefined\n : enumValue(value.priority, ['medium', 'high', 'urgent'] as const, 'Factory message priority');\n const idleBehavior =\n value.idleBehavior === undefined\n ? undefined\n : enumValue(value.idleBehavior, ['persist', 'wake'] as const, 'Factory message idle behavior');\n if (value.prepareBinding !== undefined && typeof value.prepareBinding !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message prepareBinding must be a boolean.');\n }\n if (value.untrustedPullRequestEvent !== undefined && typeof value.untrustedPullRequestEvent !== 'boolean') {\n throw new FactoryRuleValidationError('Factory message untrustedPullRequestEvent must be a boolean.');\n }\n if (value.prepareBinding === true && value.role === undefined) {\n throw new FactoryRuleValidationError('Factory message prepareBinding requires a role.');\n }\n const role =\n value.role === undefined\n ? undefined\n : boundedString(value.role, 'Factory message role', MAX_ROLE_LENGTH, IDENTIFIER_RE);\n return {\n type,\n ...commonCommitFields(value),\n ...(role ? { role } : {}),\n message: boundedString(value.message, 'Factory message', MAX_MESSAGE_LENGTH),\n ...(priority ? { priority } : {}),\n ...(idleBehavior ? { idleBehavior } : {}),\n ...(value.prepareBinding === true ? { prepareBinding: true } : {}),\n ...(value.untrustedPullRequestEvent === true ? { untrustedPullRequestEvent: true } : {}),\n };\n }\n case 'notify': {\n assertExactKeys(value, ['type', 'idempotencyKey', 'title', 'body', 'level'], 'Factory notify decision');\n const body = optionalBoundedString(value.body, 'Factory notification body', MAX_MESSAGE_LENGTH);\n const level =\n value.level === undefined\n ? undefined\n : enumValue(value.level, ['info', 'warning', 'error'] as const, 'Factory notification level');\n return {\n type,\n ...commonCommitFields(value),\n title: boundedString(value.title, 'Factory notification title', MAX_TITLE_LENGTH),\n ...(body ? { body } : {}),\n ...(level ? { level } : {}),\n };\n }\n case 'dismissStaleReviews': {\n assertExactKeys(\n value,\n [\n 'type',\n 'idempotencyKey',\n 'installationId',\n 'repository',\n 'pullRequestNumber',\n 'approvingReviewId',\n 'approvingAuthor',\n ],\n 'Factory dismiss stale reviews decision',\n );\n for (const key of ['installationId', 'pullRequestNumber'] as const) {\n if (!Number.isSafeInteger(value[key]) || (value[key] as number) <= 0) {\n throw new FactoryRuleValidationError(`Factory dismiss stale reviews ${key} must be a positive integer.`);\n }\n }\n return {\n type,\n ...commonCommitFields(value),\n installationId: value.installationId as number,\n repository: boundedString(value.repository, 'Factory dismiss stale reviews repository', MAX_TITLE_LENGTH),\n pullRequestNumber: value.pullRequestNumber as number,\n approvingReviewId: boundedString(value.approvingReviewId, 'Factory approving review id', MAX_TITLE_LENGTH),\n approvingAuthor: boundedString(value.approvingAuthor, 'Factory approving review author', MAX_TITLE_LENGTH),\n };\n }\n default:\n throw new FactoryRuleValidationError('Factory rule decision type is unsupported.');\n }\n}\n\nexport function validateFactoryRuleDecisions(values: readonly unknown[], causalDepth = 0): FactoryCommitDecision[] {\n if (values.length > MAX_JSON_COLLECTION_SIZE) {\n throw new FactoryRuleValidationError('Factory rule produced too many decisions.');\n }\n const decisions: FactoryCommitDecision[] = [];\n for (const value of values) {\n const decision = validateFactoryRuleDecision(value, causalDepth);\n if (decision.type === 'reject') {\n throw new FactoryRuleValidationError('A rejection cannot be persisted with commit decisions.');\n }\n decisions.push(decision);\n }\n const keys = decisions.map(decision => decision.idempotencyKey);\n if (new Set(keys).size !== keys.length) {\n throw new FactoryRuleValidationError('Factory decisions require unique idempotency keys.');\n }\n return decisions;\n}\n"],"mappings":";;AAaA,MAAa,gCAAgC;AAE7C,MAAM,qBAAqB;AAC3B,MAAM,6BAA6B;AACnC,MAAM,oBAAoB;AAC1B,MAAM,mBAAmB;AACzB,MAAM,yBAAyB;AAC/B,MAAM,qBAAqB;AAC3B,MAAM,uBAAuB;AAC7B,MAAa,kBAAkB;AAC/B,MAAa,uBAAuB;AACpC,MAAa,wBAAwB;AACrC,MAAM,wBAAwB;AAC9B,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AACjC,MAAM,iBAAiB;AACvB,MAAM,2BAA2B;AAEjC,MAAa,8BAA8B;;AAE3C,MAAM,sBAAsB;;AAE5B,MAAM,WAAW;AACjB,MAAM,mBAAmB;AACzB,MAAa,gBAAgB;AAC7B,MAAa,sBAAsB;AACnC,MAAa,gBAAgB;AAC7B,MAAM,mBAAmB;AACzB,MAAM,oBAA+C;CACnD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,kBAAuD;CAC3D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAa,6BAAb,cAAgD,MAAM;CACpD,OAAgB;CAEhB,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAEA,S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2C;CAElF,MAAM,YAAqC,CAAC;CAC5C,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,WAAW,4BAA4B,OAAO,WAAW;EAC/D,IAAI,SAAS,SAAS,UACpB,MAAM,IAAI,2BAA2B,wDAAwD;EAE/F,UAAU,KAAK,QAAQ;CACzB;CACA,MAAM,OAAO,UAAU,KAAI,aAAY,SAAS,cAAc;CAC9D,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,SAAS,KAAK,QAC9B,MAAM,IAAI,2BAA2B,oDAAoD;CAE3F,OAAO;AACT"}
|
package/dist/run-error.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type RunErrorRecovery = 'continue' | 'credentials' | 'credits' | 'model' | 'new_session';
|
|
1
|
+
export type RunErrorRecovery = 'continue' | 'credentials' | 'credits' | 'model' | 'memory_model' | 'new_session';
|
|
2
2
|
export interface RunErrorDescription {
|
|
3
3
|
title: string;
|
|
4
4
|
message: string;
|
package/dist/run-error.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-error.d.ts","sourceRoot":"","sources":["../src/run-error.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG,aAAa,GAAG,SAAS,GAAG,OAAO,GAAG,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"run-error.d.ts","sourceRoot":"","sources":["../src/run-error.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,gBAAgB,GAAG,UAAU,GAAG,aAAa,GAAG,SAAS,GAAG,OAAO,GAAG,cAAc,GAAG,aAAa,CAAC;AAEjH,MAAM,WAAW,mBAAmB;IAClC,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,gBAAgB,EAAE,CAAC;IAC/B,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB;AASD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,gBAAgB,GAAG,mBAAmB,CAS7E"}
|
package/dist/run-error.js
CHANGED
|
@@ -4,23 +4,32 @@ import { PROVIDER_AUTH_REQUIRED_ERROR } from "@mastra/code-sdk/auth/provider-aut
|
|
|
4
4
|
// src/run-error.ts
|
|
5
5
|
const UNEXPECTED_ERROR = "An unexpected error stopped the run. Copy the error details to investigate.";
|
|
6
6
|
const NO_REASON_AVAILABLE = "The provider rejected the request. A specific reason isn’t available here. Copy the error details and check the server logs.";
|
|
7
|
+
/** How `SessionRunEngine.abortForOmFailure` wraps an observer or reflector failure. */
|
|
8
|
+
const MEMORY_MODEL_FAILURE = /^Observational memory \w+ \w+ failed: /;
|
|
7
9
|
function describeRunError(error) {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
+
const memoryFailure = MEMORY_MODEL_FAILURE.test(error.message);
|
|
11
|
+
const description = {
|
|
12
|
+
...explainRunError(error, memoryFailure),
|
|
10
13
|
model: providerModelId(error)
|
|
11
14
|
};
|
|
15
|
+
if (!memoryFailure) return description;
|
|
16
|
+
return {
|
|
17
|
+
...description,
|
|
18
|
+
recoveries: description.recoveries.map((recovery) => recovery === "model" ? "memory_model" : recovery)
|
|
19
|
+
};
|
|
12
20
|
}
|
|
13
|
-
function explainRunError(error) {
|
|
21
|
+
function explainRunError(error, memoryFailure) {
|
|
14
22
|
if (error.name === PROVIDER_AUTH_REQUIRED_ERROR) return {
|
|
15
23
|
title: "Provider sign-in required",
|
|
16
24
|
message: error.message,
|
|
17
25
|
recoveries: ["credentials", "model"]
|
|
18
26
|
};
|
|
27
|
+
const otherModel = memoryFailure ? "another memory model in Memory settings" : "another model";
|
|
19
28
|
switch (classifyProviderError(error)) {
|
|
20
29
|
case "quota":
|
|
21
30
|
if (isMastraGatewayError(error)) return {
|
|
22
31
|
title: "Out of Mastra Gateway credits",
|
|
23
|
-
message:
|
|
32
|
+
message: `Your organization has no gateway credits left. Add credits, then continue the run, or choose ${otherModel}.`,
|
|
24
33
|
recoveries: [
|
|
25
34
|
"credits",
|
|
26
35
|
"continue",
|
|
@@ -29,22 +38,22 @@ function explainRunError(error) {
|
|
|
29
38
|
};
|
|
30
39
|
return {
|
|
31
40
|
title: "Provider quota exhausted",
|
|
32
|
-
message: afterProviderReason(error, "Check the provider account’s billing or usage allowance, or use another credential or model."),
|
|
41
|
+
message: afterProviderReason(error, memoryFailure ? "Check the provider account’s billing or usage allowance, or use another credential or memory model in Memory settings." : "Check the provider account’s billing or usage allowance, or use another credential or model."),
|
|
33
42
|
recoveries: ["credentials", "model"]
|
|
34
43
|
};
|
|
35
44
|
case "auth": return {
|
|
36
45
|
title: "Provider access failed",
|
|
37
|
-
message: afterProviderReason(error, "Review the credentials and model access configured for this session."),
|
|
46
|
+
message: afterProviderReason(error, memoryFailure ? "Review the credentials and the memory model chosen in Memory settings." : "Review the credentials and model access configured for this session."),
|
|
38
47
|
recoveries: ["credentials", "model"]
|
|
39
48
|
};
|
|
40
49
|
case "context_overflow": return {
|
|
41
|
-
title: "Conversation exceeds the model’s limit",
|
|
42
|
-
message: "Choose a model with a larger context window or start a new session with a shorter prompt.",
|
|
50
|
+
title: memoryFailure ? "Conversation exceeds the memory model’s limit" : "Conversation exceeds the model’s limit",
|
|
51
|
+
message: memoryFailure ? "Choose a memory model with a larger context window in Memory settings, or start a new session." : "Choose a model with a larger context window or start a new session with a shorter prompt.",
|
|
43
52
|
recoveries: ["model", "new_session"]
|
|
44
53
|
};
|
|
45
54
|
case "model_rejected": return {
|
|
46
|
-
title: "Model not available",
|
|
47
|
-
message: afterProviderReason(error, "Choose another model for this session.", "The provider rejected this model."),
|
|
55
|
+
title: memoryFailure ? "Memory model not available" : "Model not available",
|
|
56
|
+
message: afterProviderReason(error, memoryFailure ? "Choose another memory model in Memory settings." : "Choose another model for this session.", "The provider rejected this model."),
|
|
48
57
|
recoveries: ["model"]
|
|
49
58
|
};
|
|
50
59
|
case "tool_history_rejected": return {
|
|
@@ -64,7 +73,7 @@ function explainRunError(error) {
|
|
|
64
73
|
};
|
|
65
74
|
case "rate_limited": return {
|
|
66
75
|
title: "Provider rate limit reached",
|
|
67
|
-
message: "The provider account behind this session’s credential hit a rate or usage limit. Continue once it resets, or use another credential or model.",
|
|
76
|
+
message: memoryFailure ? "The provider account behind the memory model’s credential hit a rate or usage limit. Continue once it resets, or use another credential or memory model in Memory settings." : "The provider account behind this session’s credential hit a rate or usage limit. Continue once it resets, or use another credential or model.",
|
|
68
77
|
recoveries: [
|
|
69
78
|
"continue",
|
|
70
79
|
"credentials",
|
|
@@ -73,7 +82,7 @@ function explainRunError(error) {
|
|
|
73
82
|
};
|
|
74
83
|
case "unavailable": return {
|
|
75
84
|
title: "Model provider temporarily unavailable",
|
|
76
|
-
message:
|
|
85
|
+
message: `The provider could not complete the request. Send a message to continue the run, or choose ${otherModel}.`,
|
|
77
86
|
recoveries: ["continue", "model"]
|
|
78
87
|
};
|
|
79
88
|
case "unknown": return describeUnclassifiedError(error);
|
package/dist/run-error.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run-error.js","names":[],"sources":["../src/run-error.ts"],"sourcesContent":["import { PROVIDER_AUTH_REQUIRED_ERROR } from '@mastra/code-sdk/auth/provider-auth-error';\nimport { MASTRA_GATEWAY_PREFIX } from '@mastra/code-sdk/providers/model-ids';\nimport {\n classifyProviderError,\n PROVIDER_CALL_ERROR_NAME,\n providerErrorReason,\n providerModelId,\n} from '@mastra/core/error';\n\nexport type RunErrorRecovery = 'continue' | 'credentials' | 'credits' | 'model' | 'new_session';\n\nexport interface RunErrorDescription {\n title: string;\n message: string;\n recoveries: RunErrorRecovery[];\n model?: string;\n}\n\nexport interface RunErrorIdentity {\n name: string;\n message: string;\n}\n\nconst UNEXPECTED_ERROR = 'An unexpected error stopped the run. Copy the error details to investigate.';\nconst NO_REASON_AVAILABLE =\n 'The provider rejected the request. A specific reason isn’t available here. Copy the error details and check the server logs.';\n\nexport function describeRunError(error: RunErrorIdentity): RunErrorDescription {\n
|
|
1
|
+
{"version":3,"file":"run-error.js","names":[],"sources":["../src/run-error.ts"],"sourcesContent":["import { PROVIDER_AUTH_REQUIRED_ERROR } from '@mastra/code-sdk/auth/provider-auth-error';\nimport { MASTRA_GATEWAY_PREFIX } from '@mastra/code-sdk/providers/model-ids';\nimport {\n classifyProviderError,\n PROVIDER_CALL_ERROR_NAME,\n providerErrorReason,\n providerModelId,\n} from '@mastra/core/error';\n\nexport type RunErrorRecovery = 'continue' | 'credentials' | 'credits' | 'model' | 'memory_model' | 'new_session';\n\nexport interface RunErrorDescription {\n title: string;\n message: string;\n recoveries: RunErrorRecovery[];\n model?: string;\n}\n\nexport interface RunErrorIdentity {\n name: string;\n message: string;\n}\n\nconst UNEXPECTED_ERROR = 'An unexpected error stopped the run. Copy the error details to investigate.';\nconst NO_REASON_AVAILABLE =\n 'The provider rejected the request. A specific reason isn’t available here. Copy the error details and check the server logs.';\n\n/** How `SessionRunEngine.abortForOmFailure` wraps an observer or reflector failure. */\nconst MEMORY_MODEL_FAILURE = /^Observational memory \\w+ \\w+ failed: /;\n\nexport function describeRunError(error: RunErrorIdentity): RunErrorDescription {\n const memoryFailure = MEMORY_MODEL_FAILURE.test(error.message);\n const description = { ...explainRunError(error, memoryFailure), model: providerModelId(error) };\n if (!memoryFailure) return description;\n // The memory model failed, not the session's: changing the session model can't fix it.\n return {\n ...description,\n recoveries: description.recoveries.map(recovery => (recovery === 'model' ? 'memory_model' : recovery)),\n };\n}\n\nfunction explainRunError(error: RunErrorIdentity, memoryFailure: boolean): Omit<RunErrorDescription, 'model'> {\n if (error.name === PROVIDER_AUTH_REQUIRED_ERROR) {\n return { title: 'Provider sign-in required', message: error.message, recoveries: ['credentials', 'model'] };\n }\n const otherModel = memoryFailure ? 'another memory model in Memory settings' : 'another model';\n switch (classifyProviderError(error)) {\n case 'quota':\n if (isMastraGatewayError(error)) {\n return {\n title: 'Out of Mastra Gateway credits',\n message: `Your organization has no gateway credits left. Add credits, then continue the run, or choose ${otherModel}.`,\n recoveries: ['credits', 'continue', 'model'],\n };\n }\n return {\n title: 'Provider quota exhausted',\n message: afterProviderReason(\n error,\n memoryFailure\n ? 'Check the provider account’s billing or usage allowance, or use another credential or memory model in Memory settings.'\n : 'Check the provider account’s billing or usage allowance, or use another credential or model.',\n ),\n recoveries: ['credentials', 'model'],\n };\n case 'auth':\n return {\n title: 'Provider access failed',\n message: afterProviderReason(\n error,\n memoryFailure\n ? 'Review the credentials and the memory model chosen in Memory settings.'\n : 'Review the credentials and model access configured for this session.',\n ),\n recoveries: ['credentials', 'model'],\n };\n case 'context_overflow':\n return {\n title: memoryFailure\n ? 'Conversation exceeds the memory model’s limit'\n : 'Conversation exceeds the model’s limit',\n message: memoryFailure\n ? 'Choose a memory model with a larger context window in Memory settings, or start a new session.'\n : 'Choose a model with a larger context window or start a new session with a shorter prompt.',\n recoveries: ['model', 'new_session'],\n };\n case 'model_rejected':\n return {\n title: memoryFailure ? 'Memory model not available' : 'Model not available',\n message: afterProviderReason(\n error,\n memoryFailure ? 'Choose another memory model in Memory settings.' : 'Choose another model for this session.',\n 'The provider rejected this model.',\n ),\n recoveries: ['model'],\n };\n case 'tool_history_rejected':\n return {\n title: 'Conversation history rejected',\n message:\n 'The provider could not match a tool call with its result. Start a new session to keep working, and copy the error details so this session can be investigated.',\n recoveries: ['new_session'],\n };\n case 'invalid_request':\n return {\n title: 'Model request rejected',\n message: providerErrorReason(error) ?? NO_REASON_AVAILABLE,\n recoveries: ['model'],\n };\n case 'timeout':\n return {\n title: 'Request timed out',\n message: 'The request took too long to complete. Send a message to continue the run.',\n recoveries: ['continue'],\n };\n case 'rate_limited':\n return {\n title: 'Provider rate limit reached',\n message: memoryFailure\n ? 'The provider account behind the memory model’s credential hit a rate or usage limit. Continue once it resets, or use another credential or memory model in Memory settings.'\n : 'The provider account behind this session’s credential hit a rate or usage limit. Continue once it resets, or use another credential or model.',\n recoveries: ['continue', 'credentials', 'model'],\n };\n case 'unavailable':\n return {\n title: 'Model provider temporarily unavailable',\n message: `The provider could not complete the request. Send a message to continue the run, or choose ${otherModel}.`,\n recoveries: ['continue', 'model'],\n };\n case 'unknown':\n return describeUnclassifiedError(error);\n }\n}\n\nconst MASTRA_GATEWAY_HOST = /(?:^|\\.)gateway(?:-api)?\\.mastra\\.ai$/;\n\n/**\n * The Mastra Gateway answered: a `mastra/…` model, a request sent to its host, or its billing reply\n * (which links to `gateway.mastra.ai`). The request reaches the gateway without the `mastra/` prefix.\n */\nfunction isMastraGatewayError(error: RunErrorIdentity): boolean {\n return (\n providerModelId(error)?.startsWith(MASTRA_GATEWAY_PREFIX) === true ||\n calledMastraGateway(error) ||\n /gateway\\.mastra\\.ai/.test(providerErrorReason(error) ?? error.message)\n );\n}\n\n/** Whether the request, or a provider error it wraps, went to the gateway's host. */\nfunction calledMastraGateway(error: unknown, depth = 0): boolean {\n if (depth > 4 || typeof error !== 'object' || error === null) return false;\n const url = 'url' in error ? error.url : undefined;\n const cause = 'cause' in error ? error.cause : undefined;\n return (typeof url === 'string' && MASTRA_GATEWAY_HOST.test(hostOf(url))) || calledMastraGateway(cause, depth + 1);\n}\n\nfunction hostOf(url: string): string {\n try {\n return new URL(url).hostname;\n } catch {\n return '';\n }\n}\n\nfunction afterProviderReason(error: RunErrorIdentity, next: string, fallback?: string): string {\n const reason = providerErrorReason(error) ?? fallback;\n return reason ? `${reason.replace(/\\.?$/, '.')} ${next}` : next;\n}\n\nfunction describeUnclassifiedError(error: RunErrorIdentity): Omit<RunErrorDescription, 'model'> {\n const message = providerErrorReason(error) ?? (error.message || UNEXPECTED_ERROR);\n const providerCall = PROVIDER_CALL_ERROR_NAME.test(error.name);\n return {\n title: providerCall ? 'Model request failed' : 'Run stopped',\n message,\n recoveries: providerCall ? ['model'] : [],\n };\n}\n"],"mappings":";;;;AAuBA,MAAM,mBAAmB;AACzB,MAAM,sBACJ;;AAGF,MAAM,uBAA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D,OAAO;EACL,OAAO,eAAe,yBAAyB;EAC/C;EACA,YAAY,eAAe,CAAC,OAAO,IAAI,CAAC;CAC1C;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"environment-state-processor.d.ts","sourceRoot":"","sources":["../../src/session/environment-state-processor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAK3G,MAAM,MAAM,gCAAgC,GAAG,IAAI,GAAG,QAAQ,GAAG,SAAS,CAAC;AAE3E,4GAA4G;AAC5G,MAAM,WAAW,iCAAiC;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,mEAAmE;IACnE,GAAG,EAAE,MAAM,CAAC;IACZ,kFAAkF;IAClF,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;IACtB,gGAAgG;IAChG,WAAW,EAAE,gCAAgC,CAAC;IAC9C,6EAA6E;IAC7E,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,uBAAuB;IACtC,wFAAwF;IACxF,gBAAgB,EAAE,MAAM,CAAC;IACzB,YAAY,EAAE,iCAAiC,EAAE,CAAC;IAClD,+FAA+F;IAC/F,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAQD,2GAA2G;AAC3G,MAAM,WAAW,0BAA0B;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,wBAAgB,wBAAwB,CACtC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,uBAAuB,EAC9B,QAAQ,GAAE,0BAA0B,EAAO,GAC1C,IAAI,CAEN;AAED;;;;;GAKG;AACH,wBAAgB,kCAAkC,CAChD,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAAE,GACpD,IAAI,CAaN;AAED,wGAAwG;AACxG,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAKtF;AAED,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAE/D;AAED,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,uBAAuB,GAAG,SAAS,CAE7F;AAED,sEAAsE;AACtE,wBAAgB,8BAA8B,CAAC,SAAS,EAAE,MAAM,GAAG,0BAA0B,EAAE,CAE9F;AAED,wBAAgB,kCAAkC,IAAI,IAAI,CAEzD;
|
|
1
|
+
{"version":3,"file":"environment-state-processor.d.ts","sourceRoot":"","sources":["../../src/session/environment-state-processor.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,wBAAwB,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAK3G,MAAM,MAAM,gCAAgC,GAAG,IAAI,GAAG,QAAQ,GAAG,SAAS,CAAC;AAE3E,4GAA4G;AAC5G,MAAM,WAAW,iCAAiC;IAChD,IAAI,EAAE,MAAM,CAAC;IACb,mEAAmE;IACnE,GAAG,EAAE,MAAM,CAAC;IACZ,kFAAkF;IAClF,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;IACtB,gGAAgG;IAChG,WAAW,EAAE,gCAAgC,CAAC;IAC9C,6EAA6E;IAC7E,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,uBAAuB;IACtC,wFAAwF;IACxF,gBAAgB,EAAE,MAAM,CAAC;IACzB,YAAY,EAAE,iCAAiC,EAAE,CAAC;IAClD,+FAA+F;IAC/F,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAQD,2GAA2G;AAC3G,MAAM,WAAW,0BAA0B;IACzC,IAAI,EAAE,MAAM,CAAC;IACb,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,wBAAgB,wBAAwB,CACtC,SAAS,EAAE,MAAM,EACjB,KAAK,EAAE,uBAAuB,EAC9B,QAAQ,GAAE,0BAA0B,EAAO,GAC1C,IAAI,CAEN;AAED;;;;;GAKG;AACH,wBAAgB,kCAAkC,CAChD,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE;IAAE,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAAE,GACpD,IAAI,CAaN;AAED,wGAAwG;AACxG,wBAAgB,yBAAyB,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAKtF;AAED,wBAAgB,uBAAuB,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAE/D;AAED,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,uBAAuB,GAAG,SAAS,CAE7F;AAED,sEAAsE;AACtE,wBAAgB,8BAA8B,CAAC,SAAS,EAAE,MAAM,GAAG,0BAA0B,EAAE,CAE9F;AAED,wBAAgB,kCAAkC,IAAI,IAAI,CAEzD;AA4BD;;;;;GAKG;AACH,qBAAa,gCAAiC,YAAW,SAAS,CAAC,qBAAqB,CAAC;IACvF,QAAQ,CAAC,EAAE,yBAAY;IACvB,QAAQ,CAAC,OAAO,yBAAY;IAEtB,kBAAkB,CAAC,IAAI,EAAE,sBAAsB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAoCxF;CACF"}
|
|
@@ -62,6 +62,9 @@ function sessionIdFromContext(requestContext) {
|
|
|
62
62
|
const controller = requestContext.get("controller");
|
|
63
63
|
return typeof controller?.sessionId === "string" && controller.sessionId ? controller.sessionId : null;
|
|
64
64
|
}
|
|
65
|
+
function isUntrustedCheckout(requestContext) {
|
|
66
|
+
return (requestContext?.get("controller"))?.getState?.().untrustedCheckout === true;
|
|
67
|
+
}
|
|
65
68
|
function environmentCacheKey(state) {
|
|
66
69
|
return `environment:${createHash("sha256").update(JSON.stringify(state)).digest("hex").slice(0, 16)}`;
|
|
67
70
|
}
|
|
@@ -79,11 +82,12 @@ var FactoryEnvironmentStateProcessor = class {
|
|
|
79
82
|
if (!sessionId) return;
|
|
80
83
|
const state = environments.get(sessionId)?.state;
|
|
81
84
|
if (!state) return;
|
|
82
|
-
const
|
|
85
|
+
const untrusted = isUntrustedCheckout(args.requestContext);
|
|
86
|
+
const cacheKey = environmentCacheKey(state) + (untrusted ? ":untrusted" : "");
|
|
83
87
|
if (Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey) return;
|
|
84
88
|
const lines = state.repositories.map((repo, index) => `${index + 1}. ${escapeText(repo.slug)} at ${escapeText(repo.dir)} on ${escapeText(repo.branch ?? "(detached)")} (default ${escapeText(repo.defaultBranch)}, setup ${repo.setupStatus})` + (repo.changeRequestUrl ? `, change request ${escapeText(repo.changeRequestUrl)}` : ""));
|
|
85
89
|
const only = state.repositories.length === 1 ? state.repositories[0] : void 0;
|
|
86
|
-
const contents = (only ? `Factory environment: 1 repository, ${escapeText(only.slug)} at ${escapeText(only.dir)}, your working directory.\n` : `Factory environment: ${state.repositories.length} repositories under ${escapeText(state.workingDirectory)}, your working directory.\n`) + lines.join("\n") + (only ? "" : "\nRun git and project commands inside the repository directory they belong to.") + (state.note ? `\n${escapeText(state.note)}` : "");
|
|
90
|
+
const contents = (only ? `Factory environment: 1 repository, ${escapeText(only.slug)} at ${escapeText(only.dir)}, your working directory.\n` : `Factory environment: ${state.repositories.length} repositories under ${escapeText(state.workingDirectory)}, your working directory.\n`) + lines.join("\n") + (only ? "" : "\nRun git and project commands inside the repository directory they belong to.") + (untrusted ? "" : "\nA directory's AGENTS.md loads after you open a file there with view or an edit tool, not through execute_command. Before your first change in a directory, read any AGENTS.md in it or its parent directories you have not seen yet.") + (state.note ? `\n${escapeText(state.note)}` : "");
|
|
87
91
|
return {
|
|
88
92
|
id: STATE_ID,
|
|
89
93
|
cacheKey,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"environment-state-processor.js","names":[],"sources":["../../src/session/environment-state-processor.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { ComputeStateSignalArgs, ComputeStateSignalResult, Processor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nconst STATE_ID = 'factory-environment';\n\nexport type EnvironmentRepositorySetupStatus = 'ok' | 'failed' | 'skipped';\n\n/** One repository of the booted environment as the agent is told about it: never a token or a clone URL. */\nexport interface SessionEnvironmentRepositoryState {\n slug: string;\n /** Absolute directory of the checkout under the workspace root. */\n dir: string;\n /** The branch the checkout ended on after boot; `null` when it stays detached. */\n branch: string | null;\n defaultBranch: string;\n /** `ok` ran or was already set up, `failed` exited non-zero, `skipped` has no setup command. */\n setupStatus: EnvironmentRepositorySetupStatus;\n /** The change request this session opened in the repository, once it has. */\n changeRequestUrl?: string;\n}\n\nexport interface SessionEnvironmentState {\n /** The workspace root, the session's working directory; repositories sit beneath it. */\n workingDirectory: string;\n repositories: SessionEnvironmentRepositoryState[];\n /** One free-form line the boot wants the agent to know (never a credential), rendered last. */\n note?: string;\n}\n\n// The boot records what it materialized, keyed by the factory session id (the\n// agent's resource id); the processor reads it on the next model step. Boot\n// runs on every sandbox start, so a replacement process re-learns the state\n// the first time the session's sandbox starts again.\nconst environments = new Map<string, { state: SessionEnvironmentState; teardown: SessionEnvironmentTeardown[] }>();\n\n/** A repository's teardown command and the directory it runs in; kept beside the state, never rendered. */\nexport interface SessionEnvironmentTeardown {\n slug: string;\n dir: string;\n command: string;\n}\n\nexport function recordSessionEnvironment(\n sessionId: string,\n state: SessionEnvironmentState,\n teardown: SessionEnvironmentTeardown[] = [],\n): void {\n environments.set(sessionId, { state, teardown });\n}\n\n/**\n * Record what a source-control tool did in one environment repository (the\n * branch it pushed, the change request it opened) so the next signal snapshot\n * tells the agent. A no-op when the session's environment is not recorded in\n * this process or the slug is not part of it.\n */\nexport function updateSessionEnvironmentRepository(\n sessionId: string,\n slug: string,\n patch: { branch?: string; changeRequestUrl?: string },\n): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const wanted = slug.toLowerCase();\n const repositories = entry.state.repositories.map(repo => {\n if (repo.slug.toLowerCase() !== wanted) return repo;\n return {\n ...repo,\n ...(patch.branch !== undefined ? { branch: patch.branch } : {}),\n ...(patch.changeRequestUrl !== undefined ? { changeRequestUrl: patch.changeRequestUrl } : {}),\n };\n });\n entry.state = { ...entry.state, repositories };\n}\n\n/** Set or clear the environment's note; a no-op when the session's environment is not recorded here. */\nexport function setSessionEnvironmentNote(sessionId: string, note: string | null): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const { note: _previous, ...rest } = entry.state;\n entry.state = note ? { ...rest, note } : rest;\n}\n\nexport function clearSessionEnvironment(sessionId: string): void {\n environments.delete(sessionId);\n}\n\nexport function peekSessionEnvironment(sessionId: string): SessionEnvironmentState | undefined {\n return environments.get(sessionId)?.state;\n}\n\n/** Teardown commands of the booted environment, in position order. */\nexport function peekSessionEnvironmentTeardown(sessionId: string): SessionEnvironmentTeardown[] {\n return environments.get(sessionId)?.teardown ?? [];\n}\n\nexport function __clearSessionEnvironmentsForTests(): void {\n environments.clear();\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');\n}\n\n// Unlike factory runs, a user session carries no `factoryProjectId` in its\n// controller state, and the environment is recorded for both, so only the\n// session id is required.\nfunction sessionIdFromContext(requestContext: RequestContext | undefined): string | null {\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const controller = requestContext.get('controller') as { sessionId?: unknown } | undefined;\n return typeof controller?.sessionId === 'string' && controller.sessionId ? controller.sessionId : null;\n}\n\nfunction environmentCacheKey(state: SessionEnvironmentState): string {\n return `environment:${createHash('sha256').update(JSON.stringify(state)).digest('hex').slice(0, 16)}`;\n}\n\n/**\n * Tells the agent which repositories its sandbox holds and where: the\n * workspace root is the session's working directory and every environment\n * repository is a directory beneath it. Snapshot mode only; a new snapshot\n * is emitted when the booted set changes (a start after an environment edit).\n */\nexport class FactoryEnvironmentStateProcessor implements Processor<'factory-environment'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const sessionId = sessionIdFromContext(args.requestContext);\n if (!sessionId) return;\n const state = environments.get(sessionId)?.state;\n if (!state) return;\n const cacheKey = environmentCacheKey(state);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n const lines = state.repositories.map(\n (repo, index) =>\n `${index + 1}. ${escapeText(repo.slug)} at ${escapeText(repo.dir)} on ${escapeText(repo.branch ?? '(detached)')} (default ${escapeText(repo.defaultBranch)}, setup ${repo.setupStatus})` +\n (repo.changeRequestUrl ? `, change request ${escapeText(repo.changeRequestUrl)}` : ''),\n );\n const only = state.repositories.length === 1 ? state.repositories[0] : undefined;\n const contents =\n (only\n ? `Factory environment: 1 repository, ${escapeText(only.slug)} at ${escapeText(only.dir)}, your working directory.\\n`\n : `Factory environment: ${state.repositories.length} repositories under ${escapeText(state.workingDirectory)}, your working directory.\\n`) +\n lines.join('\\n') +\n (only ? '' : '\\nRun git and project commands inside the repository directory they belong to.') +\n (state.note ? `\\n${escapeText(state.note)}` : '');\n return {\n id: STATE_ID,\n cacheKey,\n mode: 'snapshot',\n tagName: 'factory-environment',\n contents,\n value: { environment: state },\n attributes: { workingDirectory: only?.dir ?? state.workingDirectory, repositories: state.repositories.length },\n metadata: { value: { environment: state } },\n };\n }\n}\n"],"mappings":";;AAIA,MAAM,WAA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K,IAAI,KACd,OAAO,KAAK,qFACZ,MAAM,OAAO,KAAK,WAAW,MAAM,IAAI,MAAM;EAChD,OAAO;GACL,IAAI;GACJ;GACA,MAAM;GACN,SAAS;GACT;GACA,OAAO,EAAE,aAAa,MAAM;GAC5B,YAAY;IAAE,kBAAkB,MAAM,OAAO,MAAM;IAAkB,cAAc,MAAM,aAAa;GAAO;GAC7G,UAAU,EAAE,OAAO,EAAE,aAAa,MAAM,EAAE;EAC5C;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"environment-state-processor.js","names":[],"sources":["../../src/session/environment-state-processor.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport type { ComputeStateSignalArgs, ComputeStateSignalResult, Processor } from '@mastra/core/processors';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nconst STATE_ID = 'factory-environment';\n\nexport type EnvironmentRepositorySetupStatus = 'ok' | 'failed' | 'skipped';\n\n/** One repository of the booted environment as the agent is told about it: never a token or a clone URL. */\nexport interface SessionEnvironmentRepositoryState {\n slug: string;\n /** Absolute directory of the checkout under the workspace root. */\n dir: string;\n /** The branch the checkout ended on after boot; `null` when it stays detached. */\n branch: string | null;\n defaultBranch: string;\n /** `ok` ran or was already set up, `failed` exited non-zero, `skipped` has no setup command. */\n setupStatus: EnvironmentRepositorySetupStatus;\n /** The change request this session opened in the repository, once it has. */\n changeRequestUrl?: string;\n}\n\nexport interface SessionEnvironmentState {\n /** The workspace root, the session's working directory; repositories sit beneath it. */\n workingDirectory: string;\n repositories: SessionEnvironmentRepositoryState[];\n /** One free-form line the boot wants the agent to know (never a credential), rendered last. */\n note?: string;\n}\n\n// The boot records what it materialized, keyed by the factory session id (the\n// agent's resource id); the processor reads it on the next model step. Boot\n// runs on every sandbox start, so a replacement process re-learns the state\n// the first time the session's sandbox starts again.\nconst environments = new Map<string, { state: SessionEnvironmentState; teardown: SessionEnvironmentTeardown[] }>();\n\n/** A repository's teardown command and the directory it runs in; kept beside the state, never rendered. */\nexport interface SessionEnvironmentTeardown {\n slug: string;\n dir: string;\n command: string;\n}\n\nexport function recordSessionEnvironment(\n sessionId: string,\n state: SessionEnvironmentState,\n teardown: SessionEnvironmentTeardown[] = [],\n): void {\n environments.set(sessionId, { state, teardown });\n}\n\n/**\n * Record what a source-control tool did in one environment repository (the\n * branch it pushed, the change request it opened) so the next signal snapshot\n * tells the agent. A no-op when the session's environment is not recorded in\n * this process or the slug is not part of it.\n */\nexport function updateSessionEnvironmentRepository(\n sessionId: string,\n slug: string,\n patch: { branch?: string; changeRequestUrl?: string },\n): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const wanted = slug.toLowerCase();\n const repositories = entry.state.repositories.map(repo => {\n if (repo.slug.toLowerCase() !== wanted) return repo;\n return {\n ...repo,\n ...(patch.branch !== undefined ? { branch: patch.branch } : {}),\n ...(patch.changeRequestUrl !== undefined ? { changeRequestUrl: patch.changeRequestUrl } : {}),\n };\n });\n entry.state = { ...entry.state, repositories };\n}\n\n/** Set or clear the environment's note; a no-op when the session's environment is not recorded here. */\nexport function setSessionEnvironmentNote(sessionId: string, note: string | null): void {\n const entry = environments.get(sessionId);\n if (!entry) return;\n const { note: _previous, ...rest } = entry.state;\n entry.state = note ? { ...rest, note } : rest;\n}\n\nexport function clearSessionEnvironment(sessionId: string): void {\n environments.delete(sessionId);\n}\n\nexport function peekSessionEnvironment(sessionId: string): SessionEnvironmentState | undefined {\n return environments.get(sessionId)?.state;\n}\n\n/** Teardown commands of the booted environment, in position order. */\nexport function peekSessionEnvironmentTeardown(sessionId: string): SessionEnvironmentTeardown[] {\n return environments.get(sessionId)?.teardown ?? [];\n}\n\nexport function __clearSessionEnvironmentsForTests(): void {\n environments.clear();\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>');\n}\n\n// Unlike factory runs, a user session carries no `factoryProjectId` in its\n// controller state, and the environment is recorded for both, so only the\n// session id is required.\nfunction sessionIdFromContext(requestContext: RequestContext | undefined): string | null {\n if (!requestContext || typeof requestContext.get !== 'function') return null;\n const controller = requestContext.get('controller') as { sessionId?: unknown } | undefined;\n return typeof controller?.sessionId === 'string' && controller.sessionId ? controller.sessionId : null;\n}\n\n// An untrusted checkout (a pull request under review) can carry attacker-written\n// AGENTS.md files, which the SDK deliberately never loads from the working tree.\nfunction isUntrustedCheckout(requestContext: RequestContext | undefined): boolean {\n const controller = requestContext?.get('controller') as\n | { getState?: () => { untrustedCheckout?: unknown } }\n | undefined;\n return controller?.getState?.().untrustedCheckout === true;\n}\n\nfunction environmentCacheKey(state: SessionEnvironmentState): string {\n return `environment:${createHash('sha256').update(JSON.stringify(state)).digest('hex').slice(0, 16)}`;\n}\n\n/**\n * Tells the agent which repositories its sandbox holds and where: the\n * workspace root is the session's working directory and every environment\n * repository is a directory beneath it. Snapshot mode only; a new snapshot\n * is emitted when the booted set changes (a start after an environment edit).\n */\nexport class FactoryEnvironmentStateProcessor implements Processor<'factory-environment'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const sessionId = sessionIdFromContext(args.requestContext);\n if (!sessionId) return;\n const state = environments.get(sessionId)?.state;\n if (!state) return;\n const untrusted = isUntrustedCheckout(args.requestContext);\n const cacheKey = environmentCacheKey(state) + (untrusted ? ':untrusted' : '');\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n const lines = state.repositories.map(\n (repo, index) =>\n `${index + 1}. ${escapeText(repo.slug)} at ${escapeText(repo.dir)} on ${escapeText(repo.branch ?? '(detached)')} (default ${escapeText(repo.defaultBranch)}, setup ${repo.setupStatus})` +\n (repo.changeRequestUrl ? `, change request ${escapeText(repo.changeRequestUrl)}` : ''),\n );\n const only = state.repositories.length === 1 ? state.repositories[0] : undefined;\n const contents =\n (only\n ? `Factory environment: 1 repository, ${escapeText(only.slug)} at ${escapeText(only.dir)}, your working directory.\\n`\n : `Factory environment: ${state.repositories.length} repositories under ${escapeText(state.workingDirectory)}, your working directory.\\n`) +\n lines.join('\\n') +\n (only ? '' : '\\nRun git and project commands inside the repository directory they belong to.') +\n (untrusted\n ? ''\n : \"\\nA directory's AGENTS.md loads after you open a file there with view or an edit tool, not through execute_command. Before your first change in a directory, read any AGENTS.md in it or its parent directories you have not seen yet.\") +\n (state.note ? `\\n${escapeText(state.note)}` : '');\n return {\n id: STATE_ID,\n cacheKey,\n mode: 'snapshot',\n tagName: 'factory-environment',\n contents,\n value: { environment: state },\n attributes: { workingDirectory: only?.dir ?? state.workingDirectory, repositories: state.repositories.length },\n metadata: { value: { environment: state } },\n };\n }\n}\n"],"mappings":";;AAIA,MAAM,WAAW;AA8BjB,MAAM,+BAAe,IAAI,IAAwF;AASjH,SAAgB,yBACd,WACA,OACA,WAAyC,CAAC,GACpC;CACN,aAAa,IAAI,WAAW;EAAE;EAAO;CAAS,CAAC;AACjD;;;;;;;AAQA,SAAgB,mCACd,WACA,MACA,OACM;CACN,MAAM,QAAQ,aAAa,IAAI,SAAS;CACxC,IAAI,CAAC,OAAO;CACZ,MAAM,SAAS,KAAK,YAAY;CAChC,MAAM,eAAe,MAAM,MAAM,aAAa,KAAI,SAAQ;EACxD,IAAI,KAAK,KAAK,YAAY,MAAM,QAAQ,OAAO;EAC/C,OAAO;GACL,GAAG;GACH,GAAI,MAAM,WAAW,KAAA,IAAY,EAAE,QAAQ,MAAM,OAAO,IAAI,CAAC;GAC7D,GAAI,MAAM,qBAAqB,KAAA,IAAY,EAAE,kBAAkB,MAAM,iBAAiB,IAAI,CAAC;EAC7F;CACF,CAAC;CACD,MAAM,QAAQ;EAAE,GAAG,MAAM;EAAO;CAAa;AAC/C;;AAGA,SAAgB,0BAA0B,WAAmB,MAA2B;CACtF,MAAM,QAAQ,aAAa,IAAI,SAAS;CACxC,IAAI,CAAC,OAAO;CACZ,MAA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B,CAAC,aAAa,EAAE,0BAA0B,EAAE,MAAM,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;KAClG,CAAC;CACH,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAoe5B;AAED,qHAAqH;AACrH,MAAM,WAAW,qBAAqB;IACpC,mEAAmE;IACnE,QAAQ,EAAE,MAAM,CAAC;IACjB,2CAA2C;IAC3C,UAAU,EAAE,MAAM,CAAC;IACnB,gDAAgD;IAChD,eAAe,EAAE,MAAM,CAAC;IACxB,kDAAkD;IAClD,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,kBAAkB,CAAC,KAAK,EAAE,+BAA+B,GAAG,OAAO,CAAC,WAAW,CAAC,CAAC;CAClF;AAED,MAAM,WAAW,+BAA+B;IAC9C,kCAAkC;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,6DAA6D;IAC7D,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,iBAAiB,CAAC;IAC1B,KAAK,EAAE,MAAM,CAAC;IACd,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;;GAIG;AACH,wBAAsB,4BAA4B,CAAC,EACjD,cAAc,EACd,SAAS,EACT,oBAAoB,GACrB,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,SAAS,EAAE,SAAS,yBAAyB,EAAE,CAAC;IAChD,oBAAoB,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;CACzD,GAAG,OAAO,CAAC,qBAAqB,GAAG,SAAS,CAAC,CAmD7C"}
|
|
@@ -198,7 +198,7 @@ async function createSourceControlTools({ requestContext, providers, audit, work
|
|
|
198
198
|
}),
|
|
199
199
|
source_control_push_branch: createTool({
|
|
200
200
|
id: "source_control_push_branch",
|
|
201
|
-
description: `Push the active Factory session branch to its connected source-control provider. Credentials are resolved and scrubbed server-side; this tool takes no token, remote, or branch arguments. ${repositoryArgument}`,
|
|
201
|
+
description: `Push the active Factory session branch to its connected source-control provider. Credentials are resolved and scrubbed server-side; this tool takes no token, remote, or branch arguments. Returns the pushed \`commit\`; \`upToDate: true\` means the remote already had it and nothing new was pushed, so check that commit is the one you meant to push. Commit before pushing, not in parallel with it. ${repositoryArgument}`,
|
|
202
202
|
inputSchema: repositorySchema,
|
|
203
203
|
execute: async (input, { workspace }) => {
|
|
204
204
|
const target = await targetFor(input);
|
|
@@ -211,7 +211,7 @@ async function createSourceControlTools({ requestContext, providers, audit, work
|
|
|
211
211
|
if (!target.ownRepository && !await isCheckoutOf(sandbox, workdir, access.cloneUrl)) throw new Error(`There is no checkout of ${target.repository.slug} in this session.`);
|
|
212
212
|
const branch = target.session.branch;
|
|
213
213
|
await ensureLocalBranch(sandbox, workdir, branch);
|
|
214
|
-
await pushRepositoryBranch(sandbox, workdir, branch, access, target.repository.slug);
|
|
214
|
+
const { commit, upToDate } = await pushRepositoryBranch(sandbox, workdir, branch, access, target.repository.slug);
|
|
215
215
|
await target.provider.storage.sessionRepositories.upsert({
|
|
216
216
|
sessionId: target.session.sessionId,
|
|
217
217
|
projectRepositoryId: target.projectRepository.id,
|
|
@@ -234,7 +234,9 @@ async function createSourceControlTools({ requestContext, providers, audit, work
|
|
|
234
234
|
return {
|
|
235
235
|
pushed: true,
|
|
236
236
|
branch,
|
|
237
|
-
repository: target.repository.slug
|
|
237
|
+
repository: target.repository.slug,
|
|
238
|
+
commit,
|
|
239
|
+
upToDate
|
|
238
240
|
};
|
|
239
241
|
}
|
|
240
242
|
}),
|