@mastra/factory 0.0.0 → 0.1.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (287) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/LICENSE.md +30 -0
  3. package/dist/auth.d.ts +181 -0
  4. package/dist/auth.d.ts.map +1 -0
  5. package/dist/auth.js +370 -0
  6. package/dist/auth.js.map +1 -0
  7. package/dist/capabilities/connection.d.ts +9 -0
  8. package/dist/capabilities/connection.d.ts.map +1 -0
  9. package/dist/capabilities/connection.js +1 -0
  10. package/dist/capabilities/connection.js.map +1 -0
  11. package/dist/capabilities/intake.d.ts +93 -0
  12. package/dist/capabilities/intake.d.ts.map +1 -0
  13. package/dist/capabilities/intake.js +1 -0
  14. package/dist/capabilities/intake.js.map +1 -0
  15. package/dist/capabilities/version-control.d.ts +239 -0
  16. package/dist/capabilities/version-control.d.ts.map +1 -0
  17. package/dist/capabilities/version-control.js +1 -0
  18. package/dist/capabilities/version-control.js.map +1 -0
  19. package/dist/factory.d.ts +145 -0
  20. package/dist/factory.d.ts.map +1 -0
  21. package/dist/factory.js +38245 -0
  22. package/dist/factory.js.map +1 -0
  23. package/dist/index.d.ts +3 -0
  24. package/dist/index.d.ts.map +1 -0
  25. package/dist/index.js +38245 -0
  26. package/dist/index.js.map +1 -0
  27. package/dist/integrations/base.d.ts +197 -0
  28. package/dist/integrations/base.d.ts.map +1 -0
  29. package/dist/integrations/base.js +1 -0
  30. package/dist/integrations/base.js.map +1 -0
  31. package/dist/integrations/github/config.d.ts +60 -0
  32. package/dist/integrations/github/config.d.ts.map +1 -0
  33. package/dist/integrations/github/config.js +28 -0
  34. package/dist/integrations/github/config.js.map +1 -0
  35. package/dist/integrations/github/factory-session.d.ts +12 -0
  36. package/dist/integrations/github/factory-session.d.ts.map +1 -0
  37. package/dist/integrations/github/factory-session.js +41 -0
  38. package/dist/integrations/github/factory-session.js.map +1 -0
  39. package/dist/integrations/github/integration.d.ts +191 -0
  40. package/dist/integrations/github/integration.d.ts.map +1 -0
  41. package/dist/integrations/github/integration.js +3001 -0
  42. package/dist/integrations/github/integration.js.map +1 -0
  43. package/dist/integrations/github/issue-triage.d.ts +27 -0
  44. package/dist/integrations/github/issue-triage.d.ts.map +1 -0
  45. package/dist/integrations/github/issue-triage.js +82 -0
  46. package/dist/integrations/github/issue-triage.js.map +1 -0
  47. package/dist/integrations/github/project-lock.d.ts +78 -0
  48. package/dist/integrations/github/project-lock.d.ts.map +1 -0
  49. package/dist/integrations/github/project-lock.js +70 -0
  50. package/dist/integrations/github/project-lock.js.map +1 -0
  51. package/dist/integrations/github/provenance.d.ts +27 -0
  52. package/dist/integrations/github/provenance.d.ts.map +1 -0
  53. package/dist/integrations/github/provenance.js +104 -0
  54. package/dist/integrations/github/provenance.js.map +1 -0
  55. package/dist/integrations/github/routes.d.ts +72 -0
  56. package/dist/integrations/github/routes.d.ts.map +1 -0
  57. package/dist/integrations/github/routes.js +1834 -0
  58. package/dist/integrations/github/routes.js.map +1 -0
  59. package/dist/integrations/github/sandbox.d.ts +268 -0
  60. package/dist/integrations/github/sandbox.d.ts.map +1 -0
  61. package/dist/integrations/github/sandbox.js +381 -0
  62. package/dist/integrations/github/sandbox.js.map +1 -0
  63. package/dist/integrations/github/session-subscriptions.d.ts +23 -0
  64. package/dist/integrations/github/session-subscriptions.d.ts.map +1 -0
  65. package/dist/integrations/github/session-subscriptions.js +190 -0
  66. package/dist/integrations/github/session-subscriptions.js.map +1 -0
  67. package/dist/integrations/github/subscriptions.d.ts +54 -0
  68. package/dist/integrations/github/subscriptions.d.ts.map +1 -0
  69. package/dist/integrations/github/subscriptions.js +70 -0
  70. package/dist/integrations/github/subscriptions.js.map +1 -0
  71. package/dist/integrations/github/webhook.d.ts +87 -0
  72. package/dist/integrations/github/webhook.d.ts.map +1 -0
  73. package/dist/integrations/github/webhook.js +381 -0
  74. package/dist/integrations/github/webhook.js.map +1 -0
  75. package/dist/integrations/linear/agent-tools.d.ts +34 -0
  76. package/dist/integrations/linear/agent-tools.d.ts.map +1 -0
  77. package/dist/integrations/linear/agent-tools.js +108 -0
  78. package/dist/integrations/linear/agent-tools.js.map +1 -0
  79. package/dist/integrations/linear/integration.d.ts +233 -0
  80. package/dist/integrations/linear/integration.d.ts.map +1 -0
  81. package/dist/integrations/linear/integration.js +962 -0
  82. package/dist/integrations/linear/integration.js.map +1 -0
  83. package/dist/integrations/linear/routes.d.ts +61 -0
  84. package/dist/integrations/linear/routes.d.ts.map +1 -0
  85. package/dist/integrations/linear/routes.js +242 -0
  86. package/dist/integrations/linear/routes.js.map +1 -0
  87. package/dist/integrations/linear/storage.d.ts +65 -0
  88. package/dist/integrations/linear/storage.d.ts.map +1 -0
  89. package/dist/integrations/linear/storage.js +1 -0
  90. package/dist/integrations/linear/storage.js.map +1 -0
  91. package/dist/integrations/platform/api-client.d.ts +24 -0
  92. package/dist/integrations/platform/api-client.d.ts.map +1 -0
  93. package/dist/integrations/platform/api-client.js +153 -0
  94. package/dist/integrations/platform/api-client.js.map +1 -0
  95. package/dist/integrations/platform/github/event-worker.d.ts +44 -0
  96. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -0
  97. package/dist/integrations/platform/github/event-worker.js +585 -0
  98. package/dist/integrations/platform/github/event-worker.js.map +1 -0
  99. package/dist/integrations/platform/github/integration.d.ts +36 -0
  100. package/dist/integrations/platform/github/integration.d.ts.map +1 -0
  101. package/dist/integrations/platform/github/integration.js +3253 -0
  102. package/dist/integrations/platform/github/integration.js.map +1 -0
  103. package/dist/integrations/platform/linear/integration.d.ts +46 -0
  104. package/dist/integrations/platform/linear/integration.d.ts.map +1 -0
  105. package/dist/integrations/platform/linear/integration.js +891 -0
  106. package/dist/integrations/platform/linear/integration.js.map +1 -0
  107. package/dist/integrations/workos/integration.d.ts +39 -0
  108. package/dist/integrations/workos/integration.d.ts.map +1 -0
  109. package/dist/integrations/workos/integration.js +96 -0
  110. package/dist/integrations/workos/integration.js.map +1 -0
  111. package/dist/routes/config.d.ts +220 -0
  112. package/dist/routes/config.d.ts.map +1 -0
  113. package/dist/routes/config.js +770 -0
  114. package/dist/routes/config.js.map +1 -0
  115. package/dist/routes/fs.d.ts +105 -0
  116. package/dist/routes/fs.d.ts.map +1 -0
  117. package/dist/routes/fs.js +294 -0
  118. package/dist/routes/fs.js.map +1 -0
  119. package/dist/routes/intake.d.ts +23 -0
  120. package/dist/routes/intake.d.ts.map +1 -0
  121. package/dist/routes/intake.js +179 -0
  122. package/dist/routes/intake.js.map +1 -0
  123. package/dist/routes/oauth.d.ts +43 -0
  124. package/dist/routes/oauth.d.ts.map +1 -0
  125. package/dist/routes/oauth.js +25058 -0
  126. package/dist/routes/oauth.js.map +1 -0
  127. package/dist/routes/projects.d.ts +19 -0
  128. package/dist/routes/projects.d.ts.map +1 -0
  129. package/dist/routes/projects.js +395 -0
  130. package/dist/routes/projects.js.map +1 -0
  131. package/dist/routes/provider-credentials.d.ts +81 -0
  132. package/dist/routes/provider-credentials.d.ts.map +1 -0
  133. package/dist/routes/provider-credentials.js +68 -0
  134. package/dist/routes/provider-credentials.js.map +1 -0
  135. package/dist/routes/route.d.ts +48 -0
  136. package/dist/routes/route.d.ts.map +1 -0
  137. package/dist/routes/route.js +11 -0
  138. package/dist/routes/route.js.map +1 -0
  139. package/dist/routes/skills.d.ts +30 -0
  140. package/dist/routes/skills.d.ts.map +1 -0
  141. package/dist/routes/skills.js +181 -0
  142. package/dist/routes/skills.js.map +1 -0
  143. package/dist/routes/surface.d.ts +83 -0
  144. package/dist/routes/surface.d.ts.map +1 -0
  145. package/dist/routes/surface.js +28519 -0
  146. package/dist/routes/surface.js.map +1 -0
  147. package/dist/routes/tenant-credentials.d.ts +74 -0
  148. package/dist/routes/tenant-credentials.d.ts.map +1 -0
  149. package/dist/routes/tenant-credentials.js +181 -0
  150. package/dist/routes/tenant-credentials.js.map +1 -0
  151. package/dist/routes/work-items.d.ts +40 -0
  152. package/dist/routes/work-items.d.ts.map +1 -0
  153. package/dist/routes/work-items.js +902 -0
  154. package/dist/routes/work-items.js.map +1 -0
  155. package/dist/rules/binding-context.d.ts +5 -0
  156. package/dist/rules/binding-context.d.ts.map +1 -0
  157. package/dist/rules/binding-context.js +40 -0
  158. package/dist/rules/binding-context.js.map +1 -0
  159. package/dist/rules/defaults.d.ts +9 -0
  160. package/dist/rules/defaults.d.ts.map +1 -0
  161. package/dist/rules/defaults.js +334 -0
  162. package/dist/rules/defaults.js.map +1 -0
  163. package/dist/rules/dispatcher.d.ts +40 -0
  164. package/dist/rules/dispatcher.d.ts.map +1 -0
  165. package/dist/rules/dispatcher.js +695 -0
  166. package/dist/rules/dispatcher.js.map +1 -0
  167. package/dist/rules/github-service.d.ts +29 -0
  168. package/dist/rules/github-service.d.ts.map +1 -0
  169. package/dist/rules/github-service.js +474 -0
  170. package/dist/rules/github-service.js.map +1 -0
  171. package/dist/rules/index.d.ts +7 -0
  172. package/dist/rules/index.d.ts.map +1 -0
  173. package/dist/rules/index.js +583 -0
  174. package/dist/rules/index.js.map +1 -0
  175. package/dist/rules/linear-service.d.ts +27 -0
  176. package/dist/rules/linear-service.d.ts.map +1 -0
  177. package/dist/rules/linear-service.js +343 -0
  178. package/dist/rules/linear-service.js.map +1 -0
  179. package/dist/rules/processor.d.ts +54 -0
  180. package/dist/rules/processor.d.ts.map +1 -0
  181. package/dist/rules/processor.js +629 -0
  182. package/dist/rules/processor.js.map +1 -0
  183. package/dist/rules/resolve.d.ts +17 -0
  184. package/dist/rules/resolve.d.ts.map +1 -0
  185. package/dist/rules/resolve.js +27 -0
  186. package/dist/rules/resolve.js.map +1 -0
  187. package/dist/rules/start-coordinator.d.ts +58 -0
  188. package/dist/rules/start-coordinator.d.ts.map +1 -0
  189. package/dist/rules/start-coordinator.js +136 -0
  190. package/dist/rules/start-coordinator.js.map +1 -0
  191. package/dist/rules/tools.d.ts +10 -0
  192. package/dist/rules/tools.d.ts.map +1 -0
  193. package/dist/rules/tools.js +93 -0
  194. package/dist/rules/tools.js.map +1 -0
  195. package/dist/rules/transition-service.d.ts +32 -0
  196. package/dist/rules/transition-service.d.ts.map +1 -0
  197. package/dist/rules/transition-service.js +474 -0
  198. package/dist/rules/transition-service.js.map +1 -0
  199. package/dist/rules/types.d.ts +225 -0
  200. package/dist/rules/types.d.ts.map +1 -0
  201. package/dist/rules/types.js +33 -0
  202. package/dist/rules/types.js.map +1 -0
  203. package/dist/rules/validation.d.ts +11 -0
  204. package/dist/rules/validation.d.ts.map +1 -0
  205. package/dist/rules/validation.js +310 -0
  206. package/dist/rules/validation.js.map +1 -0
  207. package/dist/sandbox/fleet.d.ts +208 -0
  208. package/dist/sandbox/fleet.d.ts.map +1 -0
  209. package/dist/sandbox/fleet.js +259 -0
  210. package/dist/sandbox/fleet.js.map +1 -0
  211. package/dist/sandbox/reattach.d.ts +3 -0
  212. package/dist/sandbox/reattach.d.ts.map +1 -0
  213. package/dist/sandbox/reattach.js +9 -0
  214. package/dist/sandbox/reattach.js.map +1 -0
  215. package/dist/server-error.d.ts +12 -0
  216. package/dist/server-error.d.ts.map +1 -0
  217. package/dist/server-error.js +20 -0
  218. package/dist/server-error.js.map +1 -0
  219. package/dist/skills/service.d.ts +48 -0
  220. package/dist/skills/service.d.ts.map +1 -0
  221. package/dist/skills/service.js +45 -0
  222. package/dist/skills/service.js.map +1 -0
  223. package/dist/spa-static.d.ts +34 -0
  224. package/dist/spa-static.d.ts.map +1 -0
  225. package/dist/spa-static.js +73 -0
  226. package/dist/spa-static.js.map +1 -0
  227. package/dist/state-signing.d.ts +48 -0
  228. package/dist/state-signing.d.ts.map +1 -0
  229. package/dist/state-signing.js +48 -0
  230. package/dist/state-signing.js.map +1 -0
  231. package/dist/storage/domains/audit/agent-audit.d.ts +27 -0
  232. package/dist/storage/domains/audit/agent-audit.d.ts.map +1 -0
  233. package/dist/storage/domains/audit/agent-audit.js +65 -0
  234. package/dist/storage/domains/audit/agent-audit.js.map +1 -0
  235. package/dist/storage/domains/audit/base.d.ts +140 -0
  236. package/dist/storage/domains/audit/base.d.ts.map +1 -0
  237. package/dist/storage/domains/audit/base.js +127 -0
  238. package/dist/storage/domains/audit/base.js.map +1 -0
  239. package/dist/storage/domains/audit/domain.d.ts +69 -0
  240. package/dist/storage/domains/audit/domain.d.ts.map +1 -0
  241. package/dist/storage/domains/audit/domain.js +165 -0
  242. package/dist/storage/domains/audit/domain.js.map +1 -0
  243. package/dist/storage/domains/credentials/base.d.ts +134 -0
  244. package/dist/storage/domains/credentials/base.d.ts.map +1 -0
  245. package/dist/storage/domains/credentials/base.js +257 -0
  246. package/dist/storage/domains/credentials/base.js.map +1 -0
  247. package/dist/storage/domains/intake/base.d.ts +38 -0
  248. package/dist/storage/domains/intake/base.d.ts.map +1 -0
  249. package/dist/storage/domains/intake/base.js +62 -0
  250. package/dist/storage/domains/intake/base.js.map +1 -0
  251. package/dist/storage/domains/integrations/base.d.ts +126 -0
  252. package/dist/storage/domains/integrations/base.d.ts.map +1 -0
  253. package/dist/storage/domains/integrations/base.js +252 -0
  254. package/dist/storage/domains/integrations/base.js.map +1 -0
  255. package/dist/storage/domains/model-packs/base.d.ts +49 -0
  256. package/dist/storage/domains/model-packs/base.d.ts.map +1 -0
  257. package/dist/storage/domains/model-packs/base.js +95 -0
  258. package/dist/storage/domains/model-packs/base.js.map +1 -0
  259. package/dist/storage/domains/projects/base.d.ts +55 -0
  260. package/dist/storage/domains/projects/base.d.ts.map +1 -0
  261. package/dist/storage/domains/projects/base.js +99 -0
  262. package/dist/storage/domains/projects/base.js.map +1 -0
  263. package/dist/storage/domains/queue-health/base.d.ts +52 -0
  264. package/dist/storage/domains/queue-health/base.d.ts.map +1 -0
  265. package/dist/storage/domains/queue-health/base.js +87 -0
  266. package/dist/storage/domains/queue-health/base.js.map +1 -0
  267. package/dist/storage/domains/source-control/base.d.ts +288 -0
  268. package/dist/storage/domains/source-control/base.d.ts.map +1 -0
  269. package/dist/storage/domains/source-control/base.js +722 -0
  270. package/dist/storage/domains/source-control/base.js.map +1 -0
  271. package/dist/storage/domains/source-control/inmemory.d.ts +158 -0
  272. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -0
  273. package/dist/storage/domains/source-control/inmemory.js +348 -0
  274. package/dist/storage/domains/source-control/inmemory.js.map +1 -0
  275. package/dist/storage/domains/work-items/base.d.ts +412 -0
  276. package/dist/storage/domains/work-items/base.d.ts.map +1 -0
  277. package/dist/storage/domains/work-items/base.js +1174 -0
  278. package/dist/storage/domains/work-items/base.js.map +1 -0
  279. package/dist/storage/domains/work-items/metrics.d.ts +101 -0
  280. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -0
  281. package/dist/storage/domains/work-items/metrics.js +203 -0
  282. package/dist/storage/domains/work-items/metrics.js.map +1 -0
  283. package/dist/workspace.d.ts +20 -0
  284. package/dist/workspace.d.ts.map +1 -0
  285. package/dist/workspace.js +364 -0
  286. package/dist/workspace.js.map +1 -0
  287. package/package.json +19 -19
@@ -0,0 +1,695 @@
1
+ // src/rules/dispatcher.ts
2
+ import { randomUUID } from "crypto";
3
+ import { RequestContext } from "@mastra/core/request-context";
4
+
5
+ // src/skills/service.ts
6
+ import { formatSkillActivation } from "@mastra/core/workspace";
7
+ var SkillInvocationError = class extends Error {
8
+ code;
9
+ constructor(code, message) {
10
+ super(message);
11
+ this.name = "SkillInvocationError";
12
+ this.code = code;
13
+ }
14
+ };
15
+ function escapeSkillBoundary(value) {
16
+ return value.replaceAll("</skill>", "&lt;/skill&gt;");
17
+ }
18
+ async function resolveSkillInvocation(controller, input) {
19
+ const session = await controller.getSessionByResource(input.resourceId, input.scope);
20
+ if (!session) throw new SkillInvocationError("session_not_found", "Agent controller session not found.");
21
+ const skills = session.getWorkspace().skills;
22
+ await skills?.maybeRefresh();
23
+ const skill = await skills?.get(input.name);
24
+ if (!skill || skill["user-invocable"] === false) {
25
+ throw new SkillInvocationError("skill_not_found", `Skill not found: ${input.name}.`);
26
+ }
27
+ const args = input.arguments?.trim();
28
+ const content = `${formatSkillActivation(skill)}${args ? `
29
+
30
+ ARGUMENTS: ${args}` : ""}`.trim();
31
+ return {
32
+ session,
33
+ skillName: skill.name,
34
+ message: `<skill name="${skill.name}">
35
+ ${escapeSkillBoundary(content)}
36
+ </skill>`
37
+ };
38
+ }
39
+
40
+ // src/rules/types.ts
41
+ var FACTORY_RULE_STAGES = ["intake", "triage", "planning", "execute", "review", "done", "canceled"];
42
+ var FACTORY_RULE_BOARDS = ["work", "review"];
43
+
44
+ // src/rules/validation.ts
45
+ var MAX_FACTORY_RULE_CAUSAL_DEPTH = 8;
46
+ var MAX_IDEMPOTENCY_KEY_LENGTH = 256;
47
+ var MAX_REASON_LENGTH = 512;
48
+ var MAX_TITLE_LENGTH = 512;
49
+ var MAX_MESSAGE_LENGTH = 8192;
50
+ var MAX_ARGUMENTS_LENGTH = 4096;
51
+ var MAX_ROLE_LENGTH = 32;
52
+ var MAX_SKILL_NAME_LENGTH = 128;
53
+ var MAX_SOURCE_KEY_LENGTH = 256;
54
+ var MAX_URL_LENGTH = 2048;
55
+ var MAX_METADATA_JSON_LENGTH = 16384;
56
+ var MAX_JSON_DEPTH = 8;
57
+ var MAX_JSON_COLLECTION_SIZE = 100;
58
+ var IDENTIFIER_RE = /^[a-z0-9][a-z0-9_-]*$/i;
59
+ var SKILL_NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
60
+ var SENSITIVE_KEY_RE = /(?:authorization|cookie|credential|password|secret|token)/i;
61
+ var WORK_ITEM_SOURCES = ["github-issue", "github-pr", "linear-issue", "manual"];
62
+ var REJECTION_CODES = [
63
+ "forbidden",
64
+ "invalid_transition",
65
+ "missing_binding",
66
+ "stale",
67
+ "timeout",
68
+ "rule_error",
69
+ "causal_depth_exceeded",
70
+ "repeated_transition"
71
+ ];
72
+ var FactoryRuleValidationError = class extends Error {
73
+ code = "invalid_factory_rule";
74
+ constructor(message) {
75
+ super(message);
76
+ this.name = "FactoryRuleValidationError";
77
+ }
78
+ };
79
+ function isPlainObject(value) {
80
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
81
+ const prototype = Object.getPrototypeOf(value);
82
+ return prototype === Object.prototype || prototype === null;
83
+ }
84
+ function assertExactKeys(value, keys, label) {
85
+ const allowed = new Set(keys);
86
+ if (Object.keys(value).some((key) => !allowed.has(key))) {
87
+ throw new FactoryRuleValidationError(`${label} contains an unsupported field.`);
88
+ }
89
+ }
90
+ function boundedString(value, label, max, pattern) {
91
+ if (typeof value !== "string") throw new FactoryRuleValidationError(`${label} must be a string.`);
92
+ const normalized = value.trim();
93
+ if (normalized.length === 0 || normalized.length > max || pattern && !pattern.test(normalized)) {
94
+ throw new FactoryRuleValidationError(`${label} is invalid.`);
95
+ }
96
+ return normalized;
97
+ }
98
+ function optionalBoundedString(value, label, max) {
99
+ if (value === void 0) return void 0;
100
+ return boundedString(value, label, max);
101
+ }
102
+ function enumValue(value, allowed, label) {
103
+ if (typeof value !== "string" || !allowed.includes(value)) {
104
+ throw new FactoryRuleValidationError(`${label} is invalid.`);
105
+ }
106
+ return value;
107
+ }
108
+ function normalizeFactoryRuleJsonValue(value, depth = 0, seen = /* @__PURE__ */ new Set()) {
109
+ if (value === null || typeof value === "boolean" || typeof value === "string") return value;
110
+ if (typeof value === "number") {
111
+ if (!Number.isFinite(value)) throw new FactoryRuleValidationError("Rule metadata must contain finite numbers.");
112
+ return value;
113
+ }
114
+ if (depth >= MAX_JSON_DEPTH || typeof value !== "object" && !Array.isArray(value)) {
115
+ throw new FactoryRuleValidationError("Rule metadata is not bounded JSON.");
116
+ }
117
+ if (seen.has(value)) throw new FactoryRuleValidationError("Rule metadata must not contain cycles.");
118
+ seen.add(value);
119
+ try {
120
+ if (Array.isArray(value)) {
121
+ if (value.length > MAX_JSON_COLLECTION_SIZE) {
122
+ throw new FactoryRuleValidationError("Rule metadata contains too many entries.");
123
+ }
124
+ return value.map((entry) => normalizeFactoryRuleJsonValue(entry, depth + 1, seen));
125
+ }
126
+ if (!isPlainObject(value)) throw new FactoryRuleValidationError("Rule metadata must use plain objects.");
127
+ const entries = Object.entries(value);
128
+ if (entries.length > MAX_JSON_COLLECTION_SIZE) {
129
+ throw new FactoryRuleValidationError("Rule metadata contains too many fields.");
130
+ }
131
+ const sanitized = {};
132
+ for (const [key, entry] of entries) {
133
+ const normalizedKey = boundedString(key, "Rule metadata key", 128, IDENTIFIER_RE);
134
+ sanitized[normalizedKey] = SENSITIVE_KEY_RE.test(normalizedKey) ? "[REDACTED]" : normalizeFactoryRuleJsonValue(entry, depth + 1, seen);
135
+ }
136
+ return sanitized;
137
+ } finally {
138
+ seen.delete(value);
139
+ }
140
+ }
141
+ function sanitizeMetadata(value) {
142
+ if (value === void 0) return void 0;
143
+ const sanitized = normalizeFactoryRuleJsonValue(value);
144
+ if (!isPlainObject(sanitized)) throw new FactoryRuleValidationError("Rule metadata must be an object.");
145
+ if (JSON.stringify(sanitized).length > MAX_METADATA_JSON_LENGTH) {
146
+ throw new FactoryRuleValidationError("Rule metadata is too large.");
147
+ }
148
+ return sanitized;
149
+ }
150
+ function commonCommitFields(value) {
151
+ return {
152
+ idempotencyKey: boundedString(value.idempotencyKey, "Factory decision idempotencyKey", MAX_IDEMPOTENCY_KEY_LENGTH)
153
+ };
154
+ }
155
+ function validateFactoryRuleDecision(value, causalDepth = 0) {
156
+ if (causalDepth > MAX_FACTORY_RULE_CAUSAL_DEPTH) {
157
+ throw new FactoryRuleValidationError("Factory rule causal depth exceeded.");
158
+ }
159
+ if (!isPlainObject(value)) throw new FactoryRuleValidationError("Factory rule decision must be an object.");
160
+ const type = value.type;
161
+ if (typeof type !== "string") throw new FactoryRuleValidationError("Factory rule decision type is required.");
162
+ switch (type) {
163
+ case "reject": {
164
+ assertExactKeys(value, ["type", "code", "reason"], "Factory reject decision");
165
+ return {
166
+ type,
167
+ code: enumValue(value.code, REJECTION_CODES, "Factory rejection code"),
168
+ reason: boundedString(value.reason, "Factory rejection reason", MAX_REASON_LENGTH)
169
+ };
170
+ }
171
+ case "transition": {
172
+ assertExactKeys(value, ["type", "idempotencyKey", "board", "stage"], "Factory transition decision");
173
+ return {
174
+ type,
175
+ ...commonCommitFields(value),
176
+ board: enumValue(value.board, FACTORY_RULE_BOARDS, "Factory transition board"),
177
+ stage: enumValue(value.stage, FACTORY_RULE_STAGES, "Factory transition stage")
178
+ };
179
+ }
180
+ case "upsertLinkedWorkItem": {
181
+ assertExactKeys(
182
+ value,
183
+ ["type", "idempotencyKey", "board", "source", "sourceKey", "title", "url", "stage", "metadata"],
184
+ "Factory linked work item decision"
185
+ );
186
+ const url = value.url;
187
+ if (url !== null && (typeof url !== "string" || url.length > MAX_URL_LENGTH || !/^https?:\/\//.test(url))) {
188
+ throw new FactoryRuleValidationError("Factory linked work item URL is invalid.");
189
+ }
190
+ const metadata = sanitizeMetadata(value.metadata);
191
+ return {
192
+ type,
193
+ ...commonCommitFields(value),
194
+ board: enumValue(value.board, FACTORY_RULE_BOARDS, "Factory linked work item board"),
195
+ source: enumValue(value.source, WORK_ITEM_SOURCES, "Factory linked work item source"),
196
+ sourceKey: boundedString(value.sourceKey, "Factory linked work item sourceKey", MAX_SOURCE_KEY_LENGTH),
197
+ title: boundedString(value.title, "Factory linked work item title", MAX_TITLE_LENGTH),
198
+ url,
199
+ stage: enumValue(value.stage, FACTORY_RULE_STAGES, "Factory linked work item stage"),
200
+ ...metadata ? { metadata } : {}
201
+ };
202
+ }
203
+ case "invokeSkill": {
204
+ assertExactKeys(
205
+ value,
206
+ ["type", "idempotencyKey", "role", "skillName", "arguments", "precedingMessage"],
207
+ "Factory invoke skill decision"
208
+ );
209
+ const args = optionalBoundedString(value.arguments, "Factory skill arguments", MAX_ARGUMENTS_LENGTH);
210
+ const precedingMessage = optionalBoundedString(
211
+ value.precedingMessage,
212
+ "Factory skill preceding message",
213
+ MAX_MESSAGE_LENGTH
214
+ );
215
+ return {
216
+ type,
217
+ ...commonCommitFields(value),
218
+ role: boundedString(value.role, "Factory skill role", MAX_ROLE_LENGTH, IDENTIFIER_RE),
219
+ skillName: boundedString(value.skillName, "Factory skill name", MAX_SKILL_NAME_LENGTH, SKILL_NAME_RE),
220
+ ...args ? { arguments: args } : {},
221
+ ...precedingMessage ? { precedingMessage } : {}
222
+ };
223
+ }
224
+ case "sendMessage": {
225
+ assertExactKeys(
226
+ value,
227
+ ["type", "idempotencyKey", "role", "message", "priority", "idleBehavior", "prepareBinding"],
228
+ "Factory send message decision"
229
+ );
230
+ const priority = value.priority === void 0 ? void 0 : enumValue(value.priority, ["medium", "high", "urgent"], "Factory message priority");
231
+ const idleBehavior = value.idleBehavior === void 0 ? void 0 : enumValue(value.idleBehavior, ["persist", "wake"], "Factory message idle behavior");
232
+ if (value.prepareBinding !== void 0 && typeof value.prepareBinding !== "boolean") {
233
+ throw new FactoryRuleValidationError("Factory message prepareBinding must be a boolean.");
234
+ }
235
+ return {
236
+ type,
237
+ ...commonCommitFields(value),
238
+ role: boundedString(value.role, "Factory message role", MAX_ROLE_LENGTH, IDENTIFIER_RE),
239
+ message: boundedString(value.message, "Factory message", MAX_MESSAGE_LENGTH),
240
+ ...priority ? { priority } : {},
241
+ ...idleBehavior ? { idleBehavior } : {},
242
+ ...value.prepareBinding === true ? { prepareBinding: true } : {}
243
+ };
244
+ }
245
+ case "notify": {
246
+ assertExactKeys(value, ["type", "idempotencyKey", "title", "body", "level"], "Factory notify decision");
247
+ const body = optionalBoundedString(value.body, "Factory notification body", MAX_MESSAGE_LENGTH);
248
+ const level = value.level === void 0 ? void 0 : enumValue(value.level, ["info", "warning", "error"], "Factory notification level");
249
+ return {
250
+ type,
251
+ ...commonCommitFields(value),
252
+ title: boundedString(value.title, "Factory notification title", MAX_TITLE_LENGTH),
253
+ ...body ? { body } : {},
254
+ ...level ? { level } : {}
255
+ };
256
+ }
257
+ default:
258
+ throw new FactoryRuleValidationError("Factory rule decision type is unsupported.");
259
+ }
260
+ }
261
+
262
+ // src/rules/dispatcher.ts
263
+ var LEASE_MS = 3e4;
264
+ var POLL_MS = 1e3;
265
+ var BATCH_SIZE = 10;
266
+ var MAX_ATTEMPTS = 5;
267
+ var MAX_ERROR_LENGTH = 512;
268
+ var MAX_BACKOFF_MS = 6e4;
269
+ function sanitizeDispatchError(error) {
270
+ const message = error instanceof Error ? error.message : String(error);
271
+ return message.replace(/\b(?:bearer|token|api[-_ ]?key|authorization)\s*[:=]?\s*[^\s,;]+/gi, "[redacted]").slice(0, MAX_ERROR_LENGTH);
272
+ }
273
+ function retryAt(now, attempts) {
274
+ return new Date(now.getTime() + Math.min(1e3 * 2 ** Math.max(0, attempts - 1), MAX_BACKOFF_MS));
275
+ }
276
+ function externalSourceForDecision(decision) {
277
+ const [integrationId, type] = decision.source === "github-pr" ? ["github", "pull-request"] : decision.source === "github-issue" ? ["github", "issue"] : decision.source === "linear-issue" ? ["linear", "issue"] : ["factory", "manual"];
278
+ return { integrationId, type, externalId: decision.sourceKey, url: decision.url ?? void 0 };
279
+ }
280
+ function deferredActor(record) {
281
+ const actor = record.actor;
282
+ if (actor?.type === "github" && typeof actor.login === "string" && typeof actor.trusted === "boolean" && typeof actor.factoryAuthored === "boolean") {
283
+ return {
284
+ type: "github",
285
+ login: actor.login,
286
+ trusted: actor.trusted,
287
+ factoryAuthored: actor.factoryAuthored
288
+ };
289
+ }
290
+ return { type: "system", id: "factory-rule-dispatcher" };
291
+ }
292
+ function leaseIdentity(record, ownerId) {
293
+ return { id: record.id, orgId: record.orgId, factoryProjectId: record.factoryProjectId, ownerId };
294
+ }
295
+ async function awaitNotification(result, requireDelivery = false) {
296
+ await result.persisted;
297
+ if (!result.accepted) {
298
+ if (requireDelivery) throw new Error("Factory notification was persisted without agent delivery.");
299
+ return;
300
+ }
301
+ const accepted = await result.accepted;
302
+ if (!requireDelivery) return;
303
+ if (accepted.action === "wake") {
304
+ await accepted.output.consumeStream();
305
+ return;
306
+ }
307
+ if (accepted.action !== "deliver") {
308
+ throw new Error(`Factory notification did not reach the agent (${String(accepted.action)}).`);
309
+ }
310
+ }
311
+ var FactoryDecisionDispatcher = class {
312
+ #controller;
313
+ #transitionService;
314
+ #storage;
315
+ #ownerId;
316
+ #reconcileToolResults;
317
+ #prepareBinding;
318
+ #primeCredentials;
319
+ #timer;
320
+ #activeRun;
321
+ constructor(options) {
322
+ this.#controller = options.controller;
323
+ this.#transitionService = options.transitionService;
324
+ this.#storage = options.storage;
325
+ this.#ownerId = options.ownerId ?? `factory-dispatcher:${randomUUID()}`;
326
+ this.#reconcileToolResults = options.reconcileToolResults;
327
+ this.#prepareBinding = options.prepareBinding;
328
+ this.#primeCredentials = options.primeCredentials;
329
+ }
330
+ start() {
331
+ if (this.#timer) return;
332
+ void this.#tick();
333
+ this.#timer = setInterval(() => void this.#tick(), POLL_MS);
334
+ this.#timer.unref?.();
335
+ }
336
+ async stop() {
337
+ if (this.#timer) clearInterval(this.#timer);
338
+ this.#timer = void 0;
339
+ await this.#activeRun;
340
+ }
341
+ async runOnce(now = /* @__PURE__ */ new Date()) {
342
+ await this.#reconcileToolResults?.();
343
+ const leaseExpiresAt = new Date(now.getTime() + LEASE_MS);
344
+ const [decisions, starts] = await Promise.all([
345
+ this.#storage.claimDeferredDecisions({
346
+ ownerId: this.#ownerId,
347
+ now,
348
+ leaseExpiresAt,
349
+ limit: BATCH_SIZE
350
+ }),
351
+ this.#storage.claimPendingStarts({
352
+ ownerId: this.#ownerId,
353
+ now,
354
+ leaseExpiresAt,
355
+ limit: BATCH_SIZE
356
+ })
357
+ ]);
358
+ await Promise.all([
359
+ ...decisions.map((decision) => this.#dispatchDecision(decision, now)),
360
+ ...starts.map((start) => this.#dispatchPendingStart(start, now))
361
+ ]);
362
+ }
363
+ async #tick() {
364
+ if (this.#activeRun) return;
365
+ this.#activeRun = this.runOnce().catch((error) => {
366
+ console.error("Factory decision dispatch cycle failed", sanitizeDispatchError(error));
367
+ });
368
+ try {
369
+ await this.#activeRun;
370
+ } finally {
371
+ this.#activeRun = void 0;
372
+ }
373
+ }
374
+ async #dispatchDecision(record, now) {
375
+ try {
376
+ const decision = validateFactoryRuleDecision(record.decision, record.causalChain.length);
377
+ if (decision.type === "reject") throw new Error("Deferred Factory decisions cannot reject.");
378
+ await this.#withLease(
379
+ async (leaseExpiresAt) => this.#storage.renewDeferredDecisionLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt),
380
+ async () => this.#executeDecision(record, decision)
381
+ );
382
+ const completed = await this.#storage.completeDeferredDecision(leaseIdentity(record, this.#ownerId), /* @__PURE__ */ new Date());
383
+ if (!completed) throw new Error("Factory decision lease was lost before completion.");
384
+ } catch (error) {
385
+ const terminal = record.attempts >= MAX_ATTEMPTS;
386
+ await this.#storage.failDeferredDecision({
387
+ ...leaseIdentity(record, this.#ownerId),
388
+ now: /* @__PURE__ */ new Date(),
389
+ availableAt: retryAt(now, record.attempts),
390
+ lastError: sanitizeDispatchError(error),
391
+ terminal
392
+ });
393
+ }
394
+ }
395
+ async #executeDecision(record, decision) {
396
+ const nextChain = [
397
+ ...record.causalChain,
398
+ { ingressId: record.idempotencyKey, decisionType: decision.type }
399
+ ];
400
+ if (nextChain.length > MAX_FACTORY_RULE_CAUSAL_DEPTH) throw new Error("Factory rule causal depth exceeded.");
401
+ switch (decision.type) {
402
+ case "transition": {
403
+ const item = await this.#requireItem(record);
404
+ const result = await this.#transitionService.transition({
405
+ orgId: record.orgId,
406
+ factoryProjectId: record.factoryProjectId,
407
+ workItemId: item.id,
408
+ board: decision.board,
409
+ stage: decision.stage,
410
+ expectedRevision: item.revision,
411
+ actor: { type: "system", id: "factory-rule-dispatcher" },
412
+ ingress: { type: "rule", identity: `decision:${record.idempotencyKey}` },
413
+ cause: "rule_decision",
414
+ causalChain: nextChain
415
+ });
416
+ if (result.status === "rejected") throw new Error(`${result.code}: ${result.reason}`);
417
+ return;
418
+ }
419
+ case "upsertLinkedWorkItem": {
420
+ await this.#upsertLinkedItem(record, decision, nextChain);
421
+ return;
422
+ }
423
+ case "invokeSkill": {
424
+ const binding = await this.#requireOrPrepareBinding(record, decision.role);
425
+ const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;
426
+ const startedBy = item?.sessions[binding.role]?.startedBy;
427
+ if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);
428
+ await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });
429
+ const requestContext = new RequestContext();
430
+ requestContext.set("user", { workosId: startedBy, organizationId: record.orgId });
431
+ const resolved = await resolveSkillInvocation(this.#controller, {
432
+ resourceId: binding.resourceId,
433
+ name: decision.skillName,
434
+ arguments: decision.arguments
435
+ });
436
+ const session = resolved.session;
437
+ await this.#switchThread(session, binding);
438
+ const delivered = await session.thread.listActiveMessages();
439
+ if (delivered.some((message) => message.id === record.id)) return;
440
+ if (decision.precedingMessage) {
441
+ await awaitNotification(
442
+ await session.sendNotificationSignal(
443
+ {
444
+ source: "factory",
445
+ kind: "stage-transition",
446
+ summary: decision.precedingMessage,
447
+ priority: "medium",
448
+ payload: { message: decision.precedingMessage },
449
+ sourceId: `${record.id}:stage-transition`,
450
+ dedupeKey: `${record.idempotencyKey}:stage-transition`
451
+ },
452
+ {
453
+ ifActive: { behavior: "deliver" },
454
+ ifIdle: { behavior: "persist" },
455
+ requestContext
456
+ }
457
+ )
458
+ );
459
+ }
460
+ const result = session.sendSignal(
461
+ {
462
+ id: record.id,
463
+ type: "user",
464
+ tagName: "user",
465
+ contents: resolved.message
466
+ },
467
+ { requestContext }
468
+ );
469
+ await result.accepted;
470
+ return;
471
+ }
472
+ case "sendMessage": {
473
+ const binding = decision.prepareBinding ? await this.#requireOrPrepareBinding(record, decision.role) : await this.#requireBinding(record, decision.role);
474
+ const item = record.workItemId ? await this.#storage.get({ orgId: record.orgId, id: record.workItemId }) : null;
475
+ const startedBy = item?.sessions[binding.role]?.startedBy;
476
+ if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);
477
+ await this.#primeCredentials?.({ orgId: record.orgId, userId: startedBy });
478
+ const requestContext = new RequestContext();
479
+ requestContext.set("user", { workosId: startedBy, organizationId: record.orgId });
480
+ const session = await this.#requireSession(binding);
481
+ await awaitNotification(
482
+ await session.sendNotificationSignal(
483
+ {
484
+ source: "factory",
485
+ kind: "rule-message",
486
+ summary: decision.message,
487
+ priority: decision.priority ?? "high",
488
+ payload: { message: decision.message },
489
+ sourceId: record.id,
490
+ dedupeKey: record.idempotencyKey
491
+ },
492
+ {
493
+ ifActive: { behavior: "deliver" },
494
+ ifIdle: { behavior: decision.idleBehavior ?? "wake" },
495
+ requestContext
496
+ }
497
+ ),
498
+ true
499
+ );
500
+ return;
501
+ }
502
+ case "notify": {
503
+ const binding = await this.#requireBinding(record);
504
+ const session = await this.#requireSession(binding);
505
+ await awaitNotification(
506
+ await session.sendNotificationSignal({
507
+ source: "factory",
508
+ kind: "rule-notification",
509
+ summary: decision.title,
510
+ payload: { body: decision.body, level: decision.level },
511
+ sourceId: record.id,
512
+ dedupeKey: record.idempotencyKey
513
+ })
514
+ );
515
+ }
516
+ }
517
+ }
518
+ async #upsertLinkedItem(record, decision, causalChain) {
519
+ const result = await this.#storage.upsert({
520
+ orgId: record.orgId,
521
+ userId: "factory-rule-dispatcher",
522
+ factoryProjectId: record.factoryProjectId,
523
+ input: {
524
+ externalSource: externalSourceForDecision(decision),
525
+ parentWorkItemId: record.workItemId,
526
+ title: decision.title,
527
+ stages: ["intake"],
528
+ sessions: {},
529
+ metadata: { ...decision.metadata, factoryRuleMaterializationKey: record.idempotencyKey }
530
+ },
531
+ reuseMode: "preserve"
532
+ });
533
+ const materializedByDecision = result.item.metadata?.factoryRuleMaterializationKey === record.idempotencyKey;
534
+ if (!materializedByDecision && (decision.stage === "intake" || !result.item.stages.includes("intake"))) return;
535
+ const board = decision.board;
536
+ let expectedRevision = result.item.revision;
537
+ if (materializedByDecision) {
538
+ const initial = await this.#transitionService.transition({
539
+ orgId: record.orgId,
540
+ factoryProjectId: record.factoryProjectId,
541
+ workItemId: result.item.id,
542
+ board,
543
+ stage: "intake",
544
+ expectedRevision,
545
+ actor: deferredActor(record),
546
+ ingress: { type: "rule", identity: `decision:${record.idempotencyKey}:${result.item.id}:initial-entry` },
547
+ cause: "linked_item_materialized",
548
+ causalChain,
549
+ initialEntry: true
550
+ });
551
+ if (initial.status === "rejected") {
552
+ if (result.created) await this.#storage.delete({ orgId: record.orgId, id: result.item.id });
553
+ throw new Error(`${initial.code}: ${initial.reason}`);
554
+ }
555
+ expectedRevision = initial.revision;
556
+ }
557
+ if (decision.stage === "intake") return;
558
+ const moved = await this.#transitionService.transition({
559
+ orgId: record.orgId,
560
+ factoryProjectId: record.factoryProjectId,
561
+ workItemId: result.item.id,
562
+ board,
563
+ stage: decision.stage,
564
+ expectedRevision,
565
+ actor: { type: "system", id: "factory-rule-dispatcher" },
566
+ ingress: { type: "rule", identity: `decision:${record.idempotencyKey}:${result.item.id}:destination` },
567
+ cause: materializedByDecision ? "linked_item_materialized" : "linked_item_reconciled",
568
+ causalChain
569
+ });
570
+ if (moved.status === "rejected") throw new Error(`${moved.code}: ${moved.reason}`);
571
+ }
572
+ async #requireItem(record) {
573
+ if (!record.workItemId) throw new Error("Factory decision is not linked to a work item.");
574
+ const item = await this.#storage.get({ orgId: record.orgId, id: record.workItemId });
575
+ if (!item) throw new Error("Factory work item not found.");
576
+ return item;
577
+ }
578
+ async #findBinding(record, role) {
579
+ if (!record.workItemId) throw new Error("Factory decision is not linked to a work item.");
580
+ const bindings = await this.#storage.listRunBindings(record.orgId, record.factoryProjectId, record.workItemId);
581
+ return bindings.filter((candidate) => candidate.status === "active" && (role === void 0 || candidate.role === role)).sort((left, right) => {
582
+ if (role === void 0 && left.role === "work" && right.role !== "work") return -1;
583
+ if (role === void 0 && right.role === "work" && left.role !== "work") return 1;
584
+ return right.createdAt.getTime() - left.createdAt.getTime() || left.id.localeCompare(right.id);
585
+ })[0];
586
+ }
587
+ async #requireBinding(record, role) {
588
+ const binding = await this.#findBinding(record, role);
589
+ if (!binding) throw new Error(role ? `No active Factory binding for role ${role}.` : "No active Factory binding.");
590
+ return binding;
591
+ }
592
+ async #requireOrPrepareBinding(record, role) {
593
+ const binding = await this.#findBinding(record, role);
594
+ if (binding) {
595
+ const session = await this.#controller.getSessionByResource(binding.resourceId);
596
+ if (session) return binding;
597
+ }
598
+ if (!this.#prepareBinding) {
599
+ throw new Error(binding ? "Bound Factory session not found." : `No active Factory binding for role ${role}.`);
600
+ }
601
+ const item = await this.#requireItem(record);
602
+ await this.#prepareBinding({ record, item, role });
603
+ return this.#requireBinding(record, role);
604
+ }
605
+ async #requireSession(binding) {
606
+ const session = await this.#controller.getSessionByResource(binding.resourceId);
607
+ if (!session) throw new Error("Bound Factory session not found.");
608
+ await this.#switchThread(session, binding);
609
+ return session;
610
+ }
611
+ async #switchThread(session, binding) {
612
+ await session.thread.switch({ threadId: binding.threadId });
613
+ }
614
+ async #withLease(renew, effect) {
615
+ let renewalFailure;
616
+ let renewal = Promise.resolve();
617
+ const timer = setInterval(
618
+ () => {
619
+ renewal = renewal.then(async () => {
620
+ try {
621
+ const renewed = await renew(new Date(Date.now() + LEASE_MS));
622
+ if (!renewed) renewalFailure = new Error("Factory dispatch lease was lost during execution.");
623
+ } catch (error) {
624
+ renewalFailure = error;
625
+ }
626
+ });
627
+ },
628
+ Math.floor(LEASE_MS / 3)
629
+ );
630
+ timer.unref?.();
631
+ try {
632
+ await effect();
633
+ await renewal;
634
+ if (renewalFailure) throw renewalFailure;
635
+ } finally {
636
+ clearInterval(timer);
637
+ await renewal;
638
+ }
639
+ }
640
+ async #dispatchPendingStart(record, now) {
641
+ try {
642
+ await this.#withLease(
643
+ async (leaseExpiresAt) => this.#storage.renewPendingStartLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt),
644
+ async () => {
645
+ if (record.message === null) return;
646
+ const bindings = await this.#storage.listRunBindings(record.orgId, record.factoryProjectId);
647
+ const binding = bindings.find(
648
+ (candidate) => candidate.id === record.bindingId && candidate.status === "active"
649
+ );
650
+ if (!binding) throw new Error("Prepared Factory binding is unavailable or revoked.");
651
+ const session = await this.#requireSession(binding);
652
+ await awaitNotification(
653
+ await session.sendNotificationSignal(
654
+ {
655
+ source: "factory",
656
+ kind: "run-kickoff",
657
+ summary: record.message,
658
+ priority: "high",
659
+ payload: { message: record.message },
660
+ sourceId: record.id,
661
+ dedupeKey: `factory-kickoff:${record.kickoffKey}`
662
+ },
663
+ { ifActive: { behavior: "deliver" }, ifIdle: { behavior: "wake" } }
664
+ ),
665
+ true
666
+ );
667
+ }
668
+ );
669
+ const completed = await this.#storage.completePendingStart(leaseIdentity(record, this.#ownerId), /* @__PURE__ */ new Date());
670
+ if (!completed) throw new Error("Factory kickoff lease was lost before completion.");
671
+ } catch (error) {
672
+ await this.#storage.failPendingStart({
673
+ ...leaseIdentity(record, this.#ownerId),
674
+ now: /* @__PURE__ */ new Date(),
675
+ availableAt: retryAt(now, record.attempts),
676
+ lastError: sanitizeDispatchError(error),
677
+ terminal: record.attempts >= MAX_ATTEMPTS
678
+ });
679
+ }
680
+ }
681
+ };
682
+ var FACTORY_DISPATCH_CONSTANTS = {
683
+ leaseMs: LEASE_MS,
684
+ pollMs: POLL_MS,
685
+ batchSize: BATCH_SIZE,
686
+ maxAttempts: MAX_ATTEMPTS,
687
+ maxErrorLength: MAX_ERROR_LENGTH,
688
+ maxBackoffMs: MAX_BACKOFF_MS,
689
+ stages: FACTORY_RULE_STAGES
690
+ };
691
+ export {
692
+ FACTORY_DISPATCH_CONSTANTS,
693
+ FactoryDecisionDispatcher
694
+ };
695
+ //# sourceMappingURL=dispatcher.js.map