@paperclipai/shared 2026.1202.0 → 2026.1203.0-beta.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.
Files changed (327) hide show
  1. package/dist/.paperclip-build-complete +1 -1
  2. package/dist/adapter-login.d.ts +6 -0
  3. package/dist/adapter-login.d.ts.map +1 -0
  4. package/dist/adapter-login.js +22 -0
  5. package/dist/adapter-login.js.map +1 -0
  6. package/dist/agent-configuration.d.ts +3 -0
  7. package/dist/agent-configuration.d.ts.map +1 -1
  8. package/dist/agent-runner.d.ts +4 -0
  9. package/dist/agent-runner.d.ts.map +1 -1
  10. package/dist/agent-runner.js +9 -7
  11. package/dist/agent-runner.js.map +1 -1
  12. package/dist/agent-setup-progress.d.ts +97 -0
  13. package/dist/agent-setup-progress.d.ts.map +1 -0
  14. package/dist/agent-setup-progress.js +47 -0
  15. package/dist/agent-setup-progress.js.map +1 -0
  16. package/dist/aggregator-app-catalog.d.ts +2 -0
  17. package/dist/aggregator-app-catalog.d.ts.map +1 -1
  18. package/dist/aggregator-app-catalog.js +4 -3
  19. package/dist/aggregator-app-catalog.js.map +1 -1
  20. package/dist/ai-connections.d.ts +5 -0
  21. package/dist/ai-connections.d.ts.map +1 -1
  22. package/dist/ai-connections.js +13 -0
  23. package/dist/ai-connections.js.map +1 -1
  24. package/dist/ai-provider-routing.d.ts.map +1 -1
  25. package/dist/ai-provider-routing.js +5 -1
  26. package/dist/ai-provider-routing.js.map +1 -1
  27. package/dist/antigravity-models.d.ts +63 -0
  28. package/dist/antigravity-models.d.ts.map +1 -0
  29. package/dist/antigravity-models.generated.d.ts +138 -0
  30. package/dist/antigravity-models.generated.d.ts.map +1 -0
  31. package/dist/antigravity-models.generated.js +211 -0
  32. package/dist/antigravity-models.generated.js.map +1 -0
  33. package/dist/antigravity-models.js +141 -0
  34. package/dist/antigravity-models.js.map +1 -0
  35. package/dist/antigravity-models.test.d.ts +2 -0
  36. package/dist/antigravity-models.test.d.ts.map +1 -0
  37. package/dist/antigravity-models.test.js +81 -0
  38. package/dist/antigravity-models.test.js.map +1 -0
  39. package/dist/app-definitions/anthropic.json +2 -2
  40. package/dist/app-definitions/{google.json → antigravity.json} +8 -8
  41. package/dist/app-definitions/asana.json +1 -0
  42. package/dist/app-definitions/aws.json +0 -1
  43. package/dist/app-definitions/google-workspace.json +2 -3
  44. package/dist/app-definitions/railway.json +2 -1
  45. package/dist/app-definitions/slack.json +3 -3
  46. package/dist/app-definitions/speko.json +2 -2
  47. package/dist/app-definitions.generated.js +1 -1
  48. package/dist/app-definitions.generated.js.map +1 -1
  49. package/dist/app-definitions.js +1 -1
  50. package/dist/app-definitions.js.map +1 -1
  51. package/dist/app-definitions.test.js +36 -3
  52. package/dist/app-definitions.test.js.map +1 -1
  53. package/dist/cloud-inference.d.ts +143 -0
  54. package/dist/cloud-inference.d.ts.map +1 -0
  55. package/dist/cloud-inference.js +175 -0
  56. package/dist/cloud-inference.js.map +1 -0
  57. package/dist/connector-availability.d.ts.map +1 -1
  58. package/dist/connector-availability.js +1 -3
  59. package/dist/connector-availability.js.map +1 -1
  60. package/dist/connector-availability.test.js +3 -0
  61. package/dist/connector-availability.test.js.map +1 -1
  62. package/dist/constants.d.ts +16 -3
  63. package/dist/constants.d.ts.map +1 -1
  64. package/dist/constants.js +23 -0
  65. package/dist/constants.js.map +1 -1
  66. package/dist/customer-success.d.ts +76 -1
  67. package/dist/customer-success.d.ts.map +1 -1
  68. package/dist/customer-success.js +118 -3
  69. package/dist/customer-success.js.map +1 -1
  70. package/dist/environment-support.d.ts +31 -2
  71. package/dist/environment-support.d.ts.map +1 -1
  72. package/dist/environment-support.js +40 -2
  73. package/dist/environment-support.js.map +1 -1
  74. package/dist/environment-support.test.js +51 -7
  75. package/dist/environment-support.test.js.map +1 -1
  76. package/dist/feature-catalog.d.ts.map +1 -1
  77. package/dist/feature-catalog.js +22 -8
  78. package/dist/feature-catalog.js.map +1 -1
  79. package/dist/google-sign-in-deployment.d.ts +7 -0
  80. package/dist/google-sign-in-deployment.d.ts.map +1 -0
  81. package/dist/google-sign-in-deployment.js +12 -0
  82. package/dist/google-sign-in-deployment.js.map +1 -0
  83. package/dist/google-sign-in-deployment.test.d.ts +2 -0
  84. package/dist/google-sign-in-deployment.test.d.ts.map +1 -0
  85. package/dist/google-sign-in-deployment.test.js +33 -0
  86. package/dist/google-sign-in-deployment.test.js.map +1 -0
  87. package/dist/google-workspace-connectors.d.ts +4 -0
  88. package/dist/google-workspace-connectors.d.ts.map +1 -1
  89. package/dist/google-workspace-connectors.js +33 -0
  90. package/dist/google-workspace-connectors.js.map +1 -1
  91. package/dist/google-workspace-connectors.test.js +19 -3
  92. package/dist/google-workspace-connectors.test.js.map +1 -1
  93. package/dist/google-workspace-setup-links.test.d.ts +2 -0
  94. package/dist/google-workspace-setup-links.test.d.ts.map +1 -0
  95. package/dist/google-workspace-setup-links.test.js +26 -0
  96. package/dist/google-workspace-setup-links.test.js.map +1 -0
  97. package/dist/headless/channels.d.ts +142 -0
  98. package/dist/headless/channels.d.ts.map +1 -0
  99. package/dist/headless/channels.js +103 -0
  100. package/dist/headless/channels.js.map +1 -0
  101. package/dist/headless/events.d.ts +48 -0
  102. package/dist/headless/events.d.ts.map +1 -0
  103. package/dist/headless/events.js +29 -0
  104. package/dist/headless/events.js.map +1 -0
  105. package/dist/headless/headless.test.d.ts +2 -0
  106. package/dist/headless/headless.test.d.ts.map +1 -0
  107. package/dist/headless/headless.test.js +240 -0
  108. package/dist/headless/headless.test.js.map +1 -0
  109. package/dist/headless/identity.d.ts +41 -0
  110. package/dist/headless/identity.d.ts.map +1 -0
  111. package/dist/headless/identity.js +17 -0
  112. package/dist/headless/identity.js.map +1 -0
  113. package/dist/headless/index.d.ts +8 -0
  114. package/dist/headless/index.d.ts.map +1 -0
  115. package/dist/headless/index.js +8 -0
  116. package/dist/headless/index.js.map +1 -0
  117. package/dist/headless/labels.d.ts +41 -0
  118. package/dist/headless/labels.d.ts.map +1 -0
  119. package/dist/headless/labels.js +133 -0
  120. package/dist/headless/labels.js.map +1 -0
  121. package/dist/headless/leases.d.ts +317 -0
  122. package/dist/headless/leases.d.ts.map +1 -0
  123. package/dist/headless/leases.js +194 -0
  124. package/dist/headless/leases.js.map +1 -0
  125. package/dist/headless/plans.d.ts +108 -0
  126. package/dist/headless/plans.d.ts.map +1 -0
  127. package/dist/headless/plans.js +230 -0
  128. package/dist/headless/plans.js.map +1 -0
  129. package/dist/headless/pure.d.ts +28 -0
  130. package/dist/headless/pure.d.ts.map +1 -0
  131. package/dist/headless/pure.js +111 -0
  132. package/dist/headless/pure.js.map +1 -0
  133. package/dist/headless/schemas.d.ts +59 -0
  134. package/dist/headless/schemas.d.ts.map +1 -0
  135. package/dist/headless/schemas.js +471 -0
  136. package/dist/headless/schemas.js.map +1 -0
  137. package/dist/index.d.ts +21 -8
  138. package/dist/index.d.ts.map +1 -1
  139. package/dist/index.js +18 -6
  140. package/dist/index.js.map +1 -1
  141. package/dist/issue-creation-source.d.ts +9 -0
  142. package/dist/issue-creation-source.d.ts.map +1 -1
  143. package/dist/issue-creation-source.js +14 -0
  144. package/dist/issue-creation-source.js.map +1 -1
  145. package/dist/issue-references.d.ts.map +1 -1
  146. package/dist/issue-references.js +2 -0
  147. package/dist/issue-references.js.map +1 -1
  148. package/dist/issue-references.test.js +10 -0
  149. package/dist/issue-references.test.js.map +1 -1
  150. package/dist/leading-user-command.d.ts +49 -0
  151. package/dist/leading-user-command.d.ts.map +1 -0
  152. package/dist/leading-user-command.js +35 -0
  153. package/dist/leading-user-command.js.map +1 -0
  154. package/dist/leading-user-command.test.d.ts +2 -0
  155. package/dist/leading-user-command.test.d.ts.map +1 -0
  156. package/dist/leading-user-command.test.js +52 -0
  157. package/dist/leading-user-command.test.js.map +1 -0
  158. package/dist/onboarding-telemetry.d.ts +288 -0
  159. package/dist/onboarding-telemetry.d.ts.map +1 -0
  160. package/dist/onboarding-telemetry.js +356 -0
  161. package/dist/onboarding-telemetry.js.map +1 -0
  162. package/dist/question-set.d.ts +1 -0
  163. package/dist/question-set.d.ts.map +1 -1
  164. package/dist/question-set.js +22 -0
  165. package/dist/question-set.js.map +1 -1
  166. package/dist/run-diagnostics.d.ts +16 -0
  167. package/dist/run-diagnostics.d.ts.map +1 -0
  168. package/dist/run-diagnostics.js +59 -0
  169. package/dist/run-diagnostics.js.map +1 -0
  170. package/dist/run-failure-cause.d.ts +4 -0
  171. package/dist/run-failure-cause.d.ts.map +1 -1
  172. package/dist/run-failure-cause.js +7 -0
  173. package/dist/run-failure-cause.js.map +1 -1
  174. package/dist/run-failure-cause.test.js +8 -1
  175. package/dist/run-failure-cause.test.js.map +1 -1
  176. package/dist/sdk/client.d.ts +3 -0
  177. package/dist/sdk/client.d.ts.map +1 -0
  178. package/dist/sdk/client.js +869 -0
  179. package/dist/sdk/client.js.map +1 -0
  180. package/dist/sdk/env.d.ts +33 -0
  181. package/dist/sdk/env.d.ts.map +1 -0
  182. package/dist/sdk/env.js +254 -0
  183. package/dist/sdk/env.js.map +1 -0
  184. package/dist/sdk/index.d.ts +5 -0
  185. package/dist/sdk/index.d.ts.map +1 -0
  186. package/dist/sdk/index.js +5 -0
  187. package/dist/sdk/index.js.map +1 -0
  188. package/dist/sdk/lite.d.ts +6 -0
  189. package/dist/sdk/lite.d.ts.map +1 -0
  190. package/dist/sdk/lite.js +5 -0
  191. package/dist/sdk/lite.js.map +1 -0
  192. package/dist/sdk/memory-backend.d.ts +54 -0
  193. package/dist/sdk/memory-backend.d.ts.map +1 -0
  194. package/dist/sdk/memory-backend.js +2020 -0
  195. package/dist/sdk/memory-backend.js.map +1 -0
  196. package/dist/sdk/sdk.test.d.ts +2 -0
  197. package/dist/sdk/sdk.test.d.ts.map +1 -0
  198. package/dist/sdk/sdk.test.js +626 -0
  199. package/dist/sdk/sdk.test.js.map +1 -0
  200. package/dist/sdk/sse.d.ts +3 -0
  201. package/dist/sdk/sse.d.ts.map +1 -0
  202. package/dist/sdk/sse.js +80 -0
  203. package/dist/sdk/sse.js.map +1 -0
  204. package/dist/sdk/types.d.ts +210 -0
  205. package/dist/sdk/types.d.ts.map +1 -0
  206. package/dist/sdk/types.js +19 -0
  207. package/dist/sdk/types.js.map +1 -0
  208. package/dist/telemetry/connector-events.test.js +23 -1
  209. package/dist/telemetry/connector-events.test.js.map +1 -1
  210. package/dist/telemetry/events.d.ts +13 -0
  211. package/dist/telemetry/events.d.ts.map +1 -1
  212. package/dist/telemetry/events.js +14 -0
  213. package/dist/telemetry/events.js.map +1 -1
  214. package/dist/telemetry/generated/paperclip-telemetry.d.ts +57 -3
  215. package/dist/telemetry/generated/paperclip-telemetry.d.ts.map +1 -1
  216. package/dist/telemetry/generated/paperclip-telemetry.js +39 -0
  217. package/dist/telemetry/generated/paperclip-telemetry.js.map +1 -1
  218. package/dist/telemetry/index.d.ts +1 -1
  219. package/dist/telemetry/index.d.ts.map +1 -1
  220. package/dist/telemetry/index.js +1 -1
  221. package/dist/telemetry/index.js.map +1 -1
  222. package/dist/telemetry/retention.d.ts.map +1 -1
  223. package/dist/telemetry/retention.js +2 -0
  224. package/dist/telemetry/retention.js.map +1 -1
  225. package/dist/tool-catalog-availability.d.ts +10 -0
  226. package/dist/tool-catalog-availability.d.ts.map +1 -0
  227. package/dist/tool-catalog-availability.js +10 -0
  228. package/dist/tool-catalog-availability.js.map +1 -0
  229. package/dist/tool-catalog-availability.test.d.ts +2 -0
  230. package/dist/tool-catalog-availability.test.d.ts.map +1 -0
  231. package/dist/tool-catalog-availability.test.js +17 -0
  232. package/dist/tool-catalog-availability.test.js.map +1 -0
  233. package/dist/types/attention.d.ts +28 -1
  234. package/dist/types/attention.d.ts.map +1 -1
  235. package/dist/types/attention.js.map +1 -1
  236. package/dist/types/document-annotation.d.ts +13 -1
  237. package/dist/types/document-annotation.d.ts.map +1 -1
  238. package/dist/types/execution-projection.d.ts +1 -1
  239. package/dist/types/execution-projection.d.ts.map +1 -1
  240. package/dist/types/heartbeat.d.ts +19 -1
  241. package/dist/types/heartbeat.d.ts.map +1 -1
  242. package/dist/types/index.d.ts +5 -5
  243. package/dist/types/index.d.ts.map +1 -1
  244. package/dist/types/index.js.map +1 -1
  245. package/dist/types/instance.d.ts +13 -1
  246. package/dist/types/instance.d.ts.map +1 -1
  247. package/dist/types/instance.js.map +1 -1
  248. package/dist/types/issue.d.ts +31 -2
  249. package/dist/types/issue.d.ts.map +1 -1
  250. package/dist/types/plugin.d.ts +5 -0
  251. package/dist/types/plugin.d.ts.map +1 -1
  252. package/dist/types/responsibility.d.ts +4 -2
  253. package/dist/types/responsibility.d.ts.map +1 -1
  254. package/dist/types/tool-access.d.ts +21 -2
  255. package/dist/types/tool-access.d.ts.map +1 -1
  256. package/dist/types/tool-access.js.map +1 -1
  257. package/dist/upstream-failure-codes.d.ts +30 -0
  258. package/dist/upstream-failure-codes.d.ts.map +1 -0
  259. package/dist/upstream-failure-codes.js +82 -0
  260. package/dist/upstream-failure-codes.js.map +1 -0
  261. package/dist/upstream-failure-codes.test.d.ts +2 -0
  262. package/dist/upstream-failure-codes.test.d.ts.map +1 -0
  263. package/dist/upstream-failure-codes.test.js +55 -0
  264. package/dist/upstream-failure-codes.test.js.map +1 -0
  265. package/dist/validators/access.d.ts +12 -0
  266. package/dist/validators/access.d.ts.map +1 -1
  267. package/dist/validators/access.js +6 -0
  268. package/dist/validators/access.js.map +1 -1
  269. package/dist/validators/access.test.js +17 -0
  270. package/dist/validators/access.test.js.map +1 -1
  271. package/dist/validators/agent.d.ts +4 -0
  272. package/dist/validators/agent.d.ts.map +1 -1
  273. package/dist/validators/agent.js +2 -1
  274. package/dist/validators/agent.js.map +1 -1
  275. package/dist/validators/agent.test.js +17 -1
  276. package/dist/validators/agent.test.js.map +1 -1
  277. package/dist/validators/app-definition.d.ts +4 -0
  278. package/dist/validators/app-definition.d.ts.map +1 -1
  279. package/dist/validators/chat-channels.test.js +11 -1
  280. package/dist/validators/chat-channels.test.js.map +1 -1
  281. package/dist/validators/company-portability.d.ts +5 -0
  282. package/dist/validators/company-portability.d.ts.map +1 -1
  283. package/dist/validators/document-annotation.d.ts +6 -0
  284. package/dist/validators/document-annotation.d.ts.map +1 -1
  285. package/dist/validators/document-annotation.js +2 -1
  286. package/dist/validators/document-annotation.js.map +1 -1
  287. package/dist/validators/index.d.ts +4 -4
  288. package/dist/validators/index.d.ts.map +1 -1
  289. package/dist/validators/index.js +4 -4
  290. package/dist/validators/index.js.map +1 -1
  291. package/dist/validators/instance.d.ts +6 -0
  292. package/dist/validators/instance.d.ts.map +1 -1
  293. package/dist/validators/instance.js +8 -2
  294. package/dist/validators/instance.js.map +1 -1
  295. package/dist/validators/instance.test.js +4 -2
  296. package/dist/validators/instance.test.js.map +1 -1
  297. package/dist/validators/issue.d.ts +211 -0
  298. package/dist/validators/issue.d.ts.map +1 -1
  299. package/dist/validators/issue.js +81 -4
  300. package/dist/validators/issue.js.map +1 -1
  301. package/dist/validators/issue.test.js +114 -1
  302. package/dist/validators/issue.test.js.map +1 -1
  303. package/dist/validators/plugin.d.ts +15 -0
  304. package/dist/validators/plugin.d.ts.map +1 -1
  305. package/dist/validators/plugin.js +28 -0
  306. package/dist/validators/plugin.js.map +1 -1
  307. package/dist/validators/plugin.test.js +31 -0
  308. package/dist/validators/plugin.test.js.map +1 -1
  309. package/dist/validators/secret.d.ts +4 -0
  310. package/dist/validators/secret.d.ts.map +1 -1
  311. package/dist/validators/secret.js +27 -0
  312. package/dist/validators/secret.js.map +1 -1
  313. package/dist/validators/tool-access.d.ts +6 -0
  314. package/dist/validators/tool-access.d.ts.map +1 -1
  315. package/dist/validators/tool-access.js +5 -7
  316. package/dist/validators/tool-access.js.map +1 -1
  317. package/dist/validators/tool-access.test.js +4 -1
  318. package/dist/validators/tool-access.test.js.map +1 -1
  319. package/package.json +9 -1
  320. package/dist/connection-intent-guidance.test.d.ts +0 -2
  321. package/dist/connection-intent-guidance.test.d.ts.map +0 -1
  322. package/dist/connection-intent-guidance.test.js +0 -24
  323. package/dist/connection-intent-guidance.test.js.map +0 -1
  324. package/dist/telemetry/readme-contract.test.d.ts +0 -2
  325. package/dist/telemetry/readme-contract.test.d.ts.map +0 -1
  326. package/dist/telemetry/readme-contract.test.js +0 -17
  327. package/dist/telemetry/readme-contract.test.js.map +0 -1
@@ -0,0 +1,2020 @@
1
+ import { applyKvLabelMutation, BUILT_IN_COMPANY_SCHEMAS, canonicalizeJsonSchema, CHANNEL_VISIBILITIES, channelPostInputSchema, createChannelInputSchema, createCompanySchemaInputSchema, formatEventCursor, KvLabelMutationSchema, matchesLabelFilter, normalizeChannelPath, OneLineAskSchema, OneLineConfirmSchema, parseDurationMs, parseEventCursor, parseSchemaRef, SchedulePostSchema, SCHEMA_REF_REGEX, splitMessageIntoTitleAndDescription, TaskClaimRequestSchema, TaskCompleteSchema, TaskFailSchema, TaskReleaseSchema, TaskRenewSchema, validateAgainstJsonSchema, validateAndSortBatchPlan, } from "../headless/index.js";
2
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3
+ const PRIORITY_RANK = {
4
+ critical: 0,
5
+ high: 1,
6
+ medium: 2,
7
+ low: 3,
8
+ };
9
+ function makeUuid(counter) {
10
+ const hex = counter.toString(16).padStart(12, "0");
11
+ return `00000000-0000-4000-8000-${hex}`;
12
+ }
13
+ function jsonResponse(body, status = 200) {
14
+ if (status === 204) {
15
+ return new Response(null, { status: 204 });
16
+ }
17
+ return new Response(JSON.stringify(body), {
18
+ status,
19
+ headers: { "content-type": "application/json" },
20
+ });
21
+ }
22
+ function errorResponse(status, error, message, extra) {
23
+ return jsonResponse({ error, message, ...(extra ?? {}) }, status);
24
+ }
25
+ function channelMatchesPattern(channelPath, pattern) {
26
+ if (pattern === "*" || pattern === channelPath)
27
+ return true;
28
+ if (pattern.endsWith("/*")) {
29
+ const prefix = pattern.slice(0, -2);
30
+ return channelPath === prefix || channelPath.startsWith(`${prefix}/`);
31
+ }
32
+ if (pattern.endsWith("/")) {
33
+ const prefix = pattern.slice(0, -1);
34
+ return channelPath === prefix || channelPath.startsWith(`${prefix}/`);
35
+ }
36
+ return false;
37
+ }
38
+ export function createInMemoryPaperclipBackend(opts = {}) {
39
+ let uuidSeq = 1;
40
+ let issueNumSeq = 0;
41
+ let eventSeq = 0;
42
+ let currentNowMs = opts.initialTimeMs ?? 1_770_000_000_000;
43
+ const companyId = opts.companyId ?? makeUuid(uuidSeq++);
44
+ const companyName = opts.companyName ?? "Default";
45
+ const companyPrefix = (opts.companyPrefix ?? "PAP").toUpperCase();
46
+ let agentIdentityPolicy = opts.agentIdentityPolicy ?? "open_local_profiles";
47
+ const agents = new Map();
48
+ const boardTokens = new Map();
49
+ const projects = new Map();
50
+ const channels = new Map();
51
+ const issues = new Map();
52
+ const issueByIdentifier = new Map();
53
+ const commentsByIssue = new Map();
54
+ const interactionsByIssue = new Map();
55
+ const schemasByRef = new Map();
56
+ const schedules = new Map();
57
+ const batchIdempotency = new Map();
58
+ const postIdempotency = new Map();
59
+ const commentIdempotency = new Map();
60
+ const events = [];
61
+ const listeners = new Set();
62
+ const nowIso = () => new Date(currentNowMs).toISOString();
63
+ for (const builtIn of BUILT_IN_COMPANY_SCHEMAS) {
64
+ schemasByRef.set(builtIn.ref, {
65
+ id: makeUuid(uuidSeq++),
66
+ companyId: null,
67
+ name: builtIn.name,
68
+ version: builtIn.version,
69
+ ref: builtIn.ref,
70
+ description: builtIn.description,
71
+ jsonSchema: builtIn.jsonSchema,
72
+ builtIn: true,
73
+ createdAt: nowIso(),
74
+ });
75
+ }
76
+ const publicIssueView = (issue) => {
77
+ const { claimToken: _hidden, sourceTrust: _trust, ...view } = issue;
78
+ return {
79
+ ...view,
80
+ kvLabels: { ...view.kvLabels },
81
+ tagLabels: [...view.tagLabels],
82
+ blocks: [...view.blocks],
83
+ blockedByIssueIds: [...view.blockedByIssueIds],
84
+ };
85
+ };
86
+ const emitEvent = (type, actor, data) => {
87
+ eventSeq += 1;
88
+ const evt = {
89
+ cursor: formatEventCursor(eventSeq),
90
+ seq: eventSeq,
91
+ type,
92
+ companyId,
93
+ channel: data.channel ?? null,
94
+ issueId: data.issueId ?? null,
95
+ identifier: data.identifier ?? null,
96
+ actor: {
97
+ type: actor.agentId ? "agent" : actor.userId ? "user" : "system",
98
+ id: actor.agentId ?? actor.userId,
99
+ name: actor.agentName,
100
+ profile: actor.actorProfile,
101
+ },
102
+ payload: data.payload ?? {},
103
+ createdAt: nowIso(),
104
+ };
105
+ events.push(evt);
106
+ for (const listener of [...listeners]) {
107
+ listener(evt);
108
+ }
109
+ return evt;
110
+ };
111
+ const findIssue = (idOrIdentifier) => {
112
+ const trimmed = idOrIdentifier.trim();
113
+ if (issues.has(trimmed))
114
+ return issues.get(trimmed);
115
+ const byId = issueByIdentifier.get(trimmed.toUpperCase());
116
+ if (byId && issues.has(byId))
117
+ return issues.get(byId);
118
+ return null;
119
+ };
120
+ const findProject = (idOrSlug) => {
121
+ const trimmed = idOrSlug.trim();
122
+ for (const proj of projects.values()) {
123
+ if (proj.id === trimmed || proj.slug === trimmed) {
124
+ return proj;
125
+ }
126
+ }
127
+ return null;
128
+ };
129
+ const authenticate = (headers) => {
130
+ const authHeader = headers.get("authorization");
131
+ const bearer = authHeader?.startsWith("Bearer ")
132
+ ? authHeader.slice(7).trim()
133
+ : null;
134
+ const requestedProfile = headers.get("x-paperclip-actor-profile")?.trim() || null;
135
+ const rawScopes = headers.get("x-paperclip-actor-scopes");
136
+ let headerScopes = null;
137
+ if (rawScopes) {
138
+ try {
139
+ headerScopes = JSON.parse(rawScopes);
140
+ }
141
+ catch {
142
+ return {
143
+ ok: false,
144
+ response: errorResponse(400, "invalid_scopes", "Malformed X-Paperclip-Actor-Scopes header"),
145
+ };
146
+ }
147
+ }
148
+ if (bearer) {
149
+ for (const agent of agents.values()) {
150
+ if (agent.apiKey === bearer) {
151
+ return {
152
+ ok: true,
153
+ actor: {
154
+ principalType: "agent",
155
+ userId: null,
156
+ agentId: agent.id,
157
+ agentName: agent.name,
158
+ actorProfile: requestedProfile ?? agent.name,
159
+ scopes: headerScopes,
160
+ },
161
+ };
162
+ }
163
+ }
164
+ const boardToken = boardTokens.get(bearer);
165
+ if (!boardToken) {
166
+ return {
167
+ ok: false,
168
+ response: errorResponse(401, "unauthorized", "Invalid bearer token"),
169
+ };
170
+ }
171
+ const effectiveProfile = boardToken.lockedProfile ?? requestedProfile;
172
+ if (effectiveProfile) {
173
+ const lower = effectiveProfile.toLowerCase();
174
+ for (const agent of agents.values()) {
175
+ if (agent.name.toLowerCase() === lower) {
176
+ return {
177
+ ok: false,
178
+ response: errorResponse(409, "profile_matches_registered_agent", `Profile "${effectiveProfile}" matches registered agent @${agent.name}`, {
179
+ next: [
180
+ `pc agent connect ${agent.name}`,
181
+ `Pick a distinct profile name with --as`,
182
+ ],
183
+ }),
184
+ };
185
+ }
186
+ }
187
+ if (agentIdentityPolicy === "strict_agent_keys") {
188
+ return {
189
+ ok: false,
190
+ response: errorResponse(403, "agent_key_required", `Company policy strict_agent_keys requires a dedicated agent API key for profile "${effectiveProfile}"`, { next: [`pc agent connect ${effectiveProfile}`] }),
191
+ };
192
+ }
193
+ }
194
+ return {
195
+ ok: true,
196
+ actor: {
197
+ principalType: "user",
198
+ userId: boardToken.userId,
199
+ agentId: null,
200
+ agentName: null,
201
+ actorProfile: effectiveProfile,
202
+ scopes: boardToken.scopes ?? headerScopes,
203
+ },
204
+ };
205
+ }
206
+ // No bearer token
207
+ if (agentIdentityPolicy !== "open_local_profiles") {
208
+ return {
209
+ ok: false,
210
+ response: errorResponse(401, "unauthorized", `Policy ${agentIdentityPolicy} rejects unauthenticated requests`, { next: ["pc auth login"] }),
211
+ };
212
+ }
213
+ if (requestedProfile) {
214
+ const lower = requestedProfile.toLowerCase();
215
+ for (const agent of agents.values()) {
216
+ if (agent.name.toLowerCase() === lower) {
217
+ return {
218
+ ok: false,
219
+ response: errorResponse(409, "profile_matches_registered_agent", `Profile "${requestedProfile}" matches registered agent @${agent.name}`),
220
+ };
221
+ }
222
+ }
223
+ }
224
+ return {
225
+ ok: true,
226
+ actor: {
227
+ principalType: "local_trusted",
228
+ userId: "local-board",
229
+ agentId: null,
230
+ agentName: null,
231
+ actorProfile: requestedProfile,
232
+ scopes: headerScopes,
233
+ },
234
+ };
235
+ };
236
+ const checkScopes = (actor, action, channelPath) => {
237
+ const scopes = actor.scopes;
238
+ if (!scopes)
239
+ return null;
240
+ if (Array.isArray(scopes.actions) && !scopes.actions.includes(action)) {
241
+ return errorResponse(403, "scope_denied", `Token scopes do not allow action "${action}"`);
242
+ }
243
+ if (channelPath &&
244
+ Array.isArray(scopes.channels) &&
245
+ !scopes.channels.some((pat) => channelMatchesPattern(channelPath, pat))) {
246
+ return errorResponse(403, "scope_denied", `Token scopes do not allow channel "${channelPath}"`);
247
+ }
248
+ return null;
249
+ };
250
+ const ensureChannel = (rawPath, actor, optsArg) => {
251
+ const { path } = normalizeChannelPath(rawPath, { allowSubtreePrefix: false });
252
+ const existing = channels.get(path);
253
+ if (existing) {
254
+ existing.lastActivityAt = nowIso();
255
+ existing.updatedAt = nowIso();
256
+ if (optsArg?.description !== undefined)
257
+ existing.description = optsArg.description;
258
+ if (optsArg?.visibility !== undefined)
259
+ existing.visibility = optsArg.visibility;
260
+ if (optsArg?.defaultProjectId !== undefined) {
261
+ existing.defaultProjectId = optsArg.defaultProjectId;
262
+ }
263
+ if (optsArg?.queueConfig !== undefined)
264
+ existing.queueConfig = optsArg.queueConfig;
265
+ return existing;
266
+ }
267
+ // Inherit private visibility if any ancestor path is private
268
+ let inheritedPrivate = false;
269
+ const parts = path.split("/");
270
+ for (let i = 1; i < parts.length; i += 1) {
271
+ const parentPath = parts.slice(0, i).join("/");
272
+ const parent = channels.get(parentPath);
273
+ if (parent?.visibility === "private") {
274
+ inheritedPrivate = true;
275
+ break;
276
+ }
277
+ }
278
+ const visibility = optsArg?.visibility ?? (inheritedPrivate ? "private" : "open");
279
+ const ts = nowIso();
280
+ const created = {
281
+ id: makeUuid(uuidSeq++),
282
+ companyId,
283
+ path,
284
+ description: optsArg?.description ?? null,
285
+ visibility: CHANNEL_VISIBILITIES.includes(visibility) ? visibility : "open",
286
+ defaultProjectId: optsArg?.defaultProjectId ?? null,
287
+ queueConfig: optsArg?.queueConfig ?? {},
288
+ threadCount: 0,
289
+ openTaskCount: 0,
290
+ readyTaskCount: 0,
291
+ lastActivityAt: ts,
292
+ createdAt: ts,
293
+ updatedAt: ts,
294
+ members: new Set([actor.userId, actor.agentId].filter((v) => Boolean(v))),
295
+ };
296
+ channels.set(path, created);
297
+ return created;
298
+ };
299
+ const validateBlocks = (blocks) => {
300
+ if (!blocks || blocks.length === 0)
301
+ return null;
302
+ for (const block of blocks) {
303
+ const ref = `${block.schema}@${block.version}`;
304
+ const schemaEntry = schemasByRef.get(ref);
305
+ if (!schemaEntry) {
306
+ return errorResponse(404, "schema_not_found", `Schema "${ref}" is not registered`);
307
+ }
308
+ const check = validateAgainstJsonSchema(schemaEntry.jsonSchema, block.data);
309
+ if (!check.valid) {
310
+ return errorResponse(400, "invalid_schema_block", `Block ${ref} failed schema validation: ${check.errors.join("; ")}`, { errors: check.errors, schema: ref });
311
+ }
312
+ }
313
+ return null;
314
+ };
315
+ const isTaskBlocked = (issue) => {
316
+ if (issue.blockedByIssueIds.length === 0)
317
+ return false;
318
+ return issue.blockedByIssueIds.some((blockerId) => {
319
+ const blocker = issues.get(blockerId);
320
+ return blocker ? blocker.status !== "done" : true;
321
+ });
322
+ };
323
+ const isTaskReadyInPool = (issue) => {
324
+ if (issue.scope === "chat")
325
+ return false;
326
+ if (issue.status !== "todo")
327
+ return false;
328
+ if (issue.assigneeAgentId !== null || issue.assigneeUserId !== null) {
329
+ return false;
330
+ }
331
+ if (issue.claimToken !== null || issue.claimLeaseExpiresAt !== null) {
332
+ return false;
333
+ }
334
+ if (isTaskBlocked(issue))
335
+ return false;
336
+ return true;
337
+ };
338
+ const refreshChannelCounts = (ch) => {
339
+ let threads = 0;
340
+ let openTasks = 0;
341
+ let readyTasks = 0;
342
+ for (const issue of issues.values()) {
343
+ if (issue.channelId !== ch.id)
344
+ continue;
345
+ threads += 1;
346
+ if (issue.status !== "done" && issue.status !== "cancelled") {
347
+ openTasks += 1;
348
+ }
349
+ if (isTaskReadyInPool(issue)) {
350
+ readyTasks += 1;
351
+ }
352
+ }
353
+ ch.threadCount = threads;
354
+ ch.openTaskCount = openTasks;
355
+ ch.readyTaskCount = readyTasks;
356
+ };
357
+ const unblockDependents = (completedIssue, actor) => {
358
+ for (const candidate of issues.values()) {
359
+ if (!candidate.blockedByIssueIds.includes(completedIssue.id))
360
+ continue;
361
+ if (!isTaskBlocked(candidate) && candidate.status === "todo") {
362
+ candidate.cursor = formatEventCursor(eventSeq + 1);
363
+ emitEvent("task.unblocked", actor, {
364
+ channel: candidate.channel,
365
+ issueId: candidate.id,
366
+ identifier: candidate.identifier,
367
+ payload: { unblockedBy: completedIssue.identifier },
368
+ });
369
+ if (isTaskReadyInPool(candidate)) {
370
+ candidate.cursor = formatEventCursor(eventSeq + 1);
371
+ emitEvent("task.ready", actor, {
372
+ channel: candidate.channel,
373
+ issueId: candidate.id,
374
+ identifier: candidate.identifier,
375
+ payload: {},
376
+ });
377
+ }
378
+ }
379
+ }
380
+ };
381
+ const expireLeases = () => {
382
+ const emitted = [];
383
+ const sysActor = {
384
+ principalType: "local_trusted",
385
+ userId: null,
386
+ agentId: null,
387
+ agentName: "lease-reconciler",
388
+ actorProfile: null,
389
+ scopes: null,
390
+ };
391
+ for (const issue of issues.values()) {
392
+ if (issue.status !== "in_progress" || !issue.claimLeaseExpiresAt)
393
+ continue;
394
+ const expMs = Date.parse(issue.claimLeaseExpiresAt);
395
+ if (Number.isFinite(expMs) && expMs <= currentNowMs) {
396
+ const ch = issue.channel ? channels.get(issue.channel) : undefined;
397
+ const maxAttempts = ch?.queueConfig.maxClaimAttempts ?? 3;
398
+ issue.claimEpoch += 1;
399
+ issue.claimToken = null;
400
+ issue.claimHolderAgentId = null;
401
+ issue.claimHolderUserId = null;
402
+ issue.claimHolderProfile = null;
403
+ issue.claimLeaseExpiresAt = null;
404
+ issue.updatedAt = nowIso();
405
+ if (issue.claimAttemptCount >= maxAttempts) {
406
+ issue.status = "blocked";
407
+ const evt = emitEvent("task.lease_poison_blocked", sysActor, {
408
+ channel: issue.channel,
409
+ issueId: issue.id,
410
+ identifier: issue.identifier,
411
+ payload: { attemptCount: issue.claimAttemptCount, maxAttempts },
412
+ });
413
+ issue.cursor = evt.cursor;
414
+ emitted.push(evt);
415
+ }
416
+ else {
417
+ issue.status = "todo";
418
+ const evtExpired = emitEvent("task.lease_expired_requeued", sysActor, {
419
+ channel: issue.channel,
420
+ issueId: issue.id,
421
+ identifier: issue.identifier,
422
+ payload: { attemptCount: issue.claimAttemptCount },
423
+ });
424
+ const evtReady = emitEvent("task.ready", sysActor, {
425
+ channel: issue.channel,
426
+ issueId: issue.id,
427
+ identifier: issue.identifier,
428
+ payload: { requeued: true },
429
+ });
430
+ issue.cursor = evtReady.cursor;
431
+ emitted.push(evtExpired, evtReady);
432
+ }
433
+ }
434
+ }
435
+ return emitted;
436
+ };
437
+ const matchesEventFilters = (evt, params) => {
438
+ const issueIdParam = params.get("issueId");
439
+ if (issueIdParam) {
440
+ const target = findIssue(issueIdParam);
441
+ if (target) {
442
+ if (evt.issueId !== target.id)
443
+ return false;
444
+ }
445
+ else if (evt.issueId !== issueIdParam && evt.identifier !== issueIdParam.toUpperCase()) {
446
+ return false;
447
+ }
448
+ }
449
+ const channelParam = params.get("channel");
450
+ if (channelParam) {
451
+ const norm = normalizeChannelPath(channelParam, { allowSubtreePrefix: true });
452
+ if (!evt.channel)
453
+ return false;
454
+ if (norm.isSubtreePrefix) {
455
+ if (evt.channel !== norm.path && !evt.channel.startsWith(`${norm.path}/`)) {
456
+ return false;
457
+ }
458
+ }
459
+ else if (evt.channel !== norm.path) {
460
+ return false;
461
+ }
462
+ }
463
+ const eventTypes = params.getAll("event");
464
+ if (eventTypes.length > 0 && !eventTypes.includes(evt.type)) {
465
+ return false;
466
+ }
467
+ const labelFilters = params.getAll("label");
468
+ if (labelFilters.length > 0) {
469
+ const issue = evt.issueId ? issues.get(evt.issueId) : undefined;
470
+ if (!issue)
471
+ return false;
472
+ if (!labelFilters.every((expr) => matchesLabelFilter(issue.kvLabels, issue.tagLabels, expr))) {
473
+ return false;
474
+ }
475
+ }
476
+ const schemaParam = params.get("schema");
477
+ if (schemaParam) {
478
+ const issue = evt.issueId ? issues.get(evt.issueId) : undefined;
479
+ const issueMatch = issue?.blocks.some((b) => `${b.schema}@${b.version}` === schemaParam);
480
+ const payloadBlocks = Array.isArray(evt.payload?.blocks)
481
+ ? evt.payload.blocks
482
+ : [];
483
+ const payloadMatch = payloadBlocks.some((b) => `${b.schema}@${b.version}` === schemaParam);
484
+ if (!issueMatch && !payloadMatch)
485
+ return false;
486
+ }
487
+ return true;
488
+ };
489
+ const checkClaimMutationAuth = (issue, actor, claimTokenHeader, bodyToken, bodyEpoch) => {
490
+ expireLeases();
491
+ if (issue.status !== "in_progress") {
492
+ return errorResponse(409, "claim_lost", "Task is no longer in progress", { claimEpoch: issue.claimEpoch, status: issue.status });
493
+ }
494
+ const token = claimTokenHeader ?? bodyToken ?? null;
495
+ if (!token || !issue.claimToken || token !== issue.claimToken) {
496
+ return errorResponse(409, "claim_lost", "Task claim token is invalid, expired, or superseded", { claimEpoch: issue.claimEpoch });
497
+ }
498
+ if (bodyEpoch !== undefined && bodyEpoch !== issue.claimEpoch) {
499
+ return errorResponse(409, "claim_lost", "Task claim epoch has changed", { claimEpoch: issue.claimEpoch });
500
+ }
501
+ if (agentIdentityPolicy === "delegated_profiles" &&
502
+ actor.actorProfile &&
503
+ issue.claimHolderProfile &&
504
+ actor.actorProfile !== issue.claimHolderProfile) {
505
+ return errorResponse(403, "profile_mismatch", `Claim is held by profile "${issue.claimHolderProfile}", not "${actor.actorProfile}"`);
506
+ }
507
+ return null;
508
+ };
509
+ const fetchHandler = async (input, init) => {
510
+ const reqUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
511
+ const url = new URL(reqUrl, "http://127.0.0.1:3100");
512
+ const method = (init?.method ?? "GET").toUpperCase();
513
+ const headers = new Headers(init?.headers);
514
+ const pathname = url.pathname;
515
+ let bodyJson = undefined;
516
+ if (typeof init?.body === "string" && init.body.length > 0) {
517
+ try {
518
+ bodyJson = JSON.parse(init.body);
519
+ }
520
+ catch {
521
+ return errorResponse(400, "invalid_json", "Invalid JSON request body");
522
+ }
523
+ }
524
+ const auth = authenticate(headers);
525
+ if (!auth.ok)
526
+ return auth.response;
527
+ const actor = auth.actor;
528
+ // 1. Resolve default company
529
+ if (method === "GET" && pathname === "/api/companies/resolve-default") {
530
+ const requested = url.searchParams.get("company")?.trim();
531
+ if (requested) {
532
+ if (requested.toLowerCase() !== companyId &&
533
+ requested.toUpperCase() !== companyPrefix) {
534
+ return errorResponse(404, "company_not_found", `Company "${requested}" not found`);
535
+ }
536
+ }
537
+ const res = {
538
+ id: companyId,
539
+ name: companyName,
540
+ issuePrefix: companyPrefix,
541
+ agentIdentityPolicy,
542
+ };
543
+ return jsonResponse(res);
544
+ }
545
+ // 2. WhoAmI
546
+ if (method === "GET" && pathname === "/api/whoami") {
547
+ const res = {
548
+ apiBase: url.origin,
549
+ companyId,
550
+ companyPrefix,
551
+ companyName,
552
+ principalType: actor.principalType,
553
+ userId: actor.userId,
554
+ agentId: actor.agentId,
555
+ agentName: actor.agentName,
556
+ actorProfile: actor.actorProfile,
557
+ agentIdentityPolicy,
558
+ scopes: actor.scopes,
559
+ };
560
+ return jsonResponse(res);
561
+ }
562
+ // 3. Channels list & create
563
+ const channelsMatch = /^\/api\/companies\/([^/]+)\/channels$/.exec(pathname);
564
+ if (channelsMatch) {
565
+ if (channelsMatch[1] !== companyId) {
566
+ return errorResponse(404, "company_not_found", "Company not found");
567
+ }
568
+ if (method === "GET") {
569
+ const scopeErr = checkScopes(actor, "read");
570
+ if (scopeErr)
571
+ return scopeErr;
572
+ const prefixParam = url.searchParams.get("prefix");
573
+ const prefixNorm = prefixParam
574
+ ? normalizeChannelPath(prefixParam, { allowSubtreePrefix: true })
575
+ : null;
576
+ const items = [];
577
+ for (const ch of channels.values()) {
578
+ if (prefixNorm) {
579
+ if (ch.path !== prefixNorm.path &&
580
+ !ch.path.startsWith(`${prefixNorm.path}/`)) {
581
+ continue;
582
+ }
583
+ }
584
+ refreshChannelCounts(ch);
585
+ const { members: _m, ...view } = ch;
586
+ items.push(view);
587
+ }
588
+ items.sort((a, b) => a.path.localeCompare(b.path));
589
+ return jsonResponse({ items });
590
+ }
591
+ if (method === "POST") {
592
+ const parsed = createChannelInputSchema.safeParse(bodyJson);
593
+ if (!parsed.success) {
594
+ return errorResponse(400, "validation_error", parsed.error.message);
595
+ }
596
+ const scopeErr = checkScopes(actor, "post", parsed.data.path);
597
+ if (scopeErr)
598
+ return scopeErr;
599
+ const ch = ensureChannel(parsed.data.path, actor, parsed.data);
600
+ refreshChannelCounts(ch);
601
+ const { members: _m, ...view } = ch;
602
+ return jsonResponse(view, 201);
603
+ }
604
+ }
605
+ // 4. Channel threads list
606
+ const threadsMatch = /^\/api\/companies\/([^/]+)\/channels\/threads$/.exec(pathname);
607
+ if (threadsMatch && method === "GET") {
608
+ if (threadsMatch[1] !== companyId) {
609
+ return errorResponse(404, "company_not_found", "Company not found");
610
+ }
611
+ const rawChannel = url.searchParams.get("channel") ?? "general";
612
+ const norm = normalizeChannelPath(rawChannel, { allowSubtreePrefix: true });
613
+ const scopeErr = checkScopes(actor, "read", norm.path);
614
+ if (scopeErr)
615
+ return scopeErr;
616
+ const labelFilters = url.searchParams.getAll("label");
617
+ const statusFilters = url.searchParams.getAll("status");
618
+ const afterCursor = url.searchParams.get("after");
619
+ const afterSeq = afterCursor ? parseEventCursor(afterCursor) : null;
620
+ const limit = Number.parseInt(url.searchParams.get("limit") ?? "50", 10);
621
+ const matchedIssues = [];
622
+ for (const issue of issues.values()) {
623
+ if (!issue.channel)
624
+ continue;
625
+ if (norm.isSubtreePrefix) {
626
+ if (issue.channel !== norm.path &&
627
+ !issue.channel.startsWith(`${norm.path}/`)) {
628
+ continue;
629
+ }
630
+ }
631
+ else if (issue.channel !== norm.path) {
632
+ continue;
633
+ }
634
+ if (statusFilters.length > 0 && !statusFilters.includes(issue.status)) {
635
+ continue;
636
+ }
637
+ if (labelFilters.length > 0 &&
638
+ !labelFilters.every((expr) => matchesLabelFilter(issue.kvLabels, issue.tagLabels, expr))) {
639
+ continue;
640
+ }
641
+ if (afterSeq !== null) {
642
+ const issueSeq = parseEventCursor(issue.cursor) ?? 0;
643
+ if (issueSeq <= afterSeq)
644
+ continue;
645
+ }
646
+ const comments = commentsByIssue.get(issue.id) ?? [];
647
+ matchedIssues.push({
648
+ ...publicIssueView(issue),
649
+ replyCount: comments.length,
650
+ latestReply: comments.length > 0 ? comments[comments.length - 1] : null,
651
+ });
652
+ }
653
+ const sliced = matchedIssues.slice(0, Math.max(1, limit));
654
+ const page = {
655
+ kind: "channel",
656
+ channel: norm.isSubtreePrefix ? `${norm.path}/` : norm.path,
657
+ items: sliced,
658
+ cursor: formatEventCursor(eventSeq),
659
+ };
660
+ return jsonResponse(page);
661
+ }
662
+ // 5. Channel posts (and tasks.create in channel)
663
+ const postsMatch = /^\/api\/companies\/([^/]+)\/channels\/posts$/.exec(pathname);
664
+ if (postsMatch && method === "POST") {
665
+ if (postsMatch[1] !== companyId) {
666
+ return errorResponse(404, "company_not_found", "Company not found");
667
+ }
668
+ const rawBody = (bodyJson ?? {});
669
+ const requestedStatus = rawBody.status === "todo" ? "todo" : "backlog";
670
+ const resultSchemaRef = typeof rawBody.resultSchema === "string" ? rawBody.resultSchema : undefined;
671
+ if (resultSchemaRef && !SCHEMA_REF_REGEX.test(resultSchemaRef.trim())) {
672
+ return errorResponse(400, "invalid_schema_ref", `Invalid resultSchema "${resultSchemaRef}"`);
673
+ }
674
+ const { status: _s, resultSchema: _rs, for: _for, assigneeAgentId: rawAssigneeAgentId, ...restForPostSchema } = rawBody;
675
+ const parsed = channelPostInputSchema.safeParse(restForPostSchema);
676
+ if (!parsed.success) {
677
+ return errorResponse(400, "validation_error", parsed.error.message);
678
+ }
679
+ const scopeErr = checkScopes(actor, requestedStatus === "todo" ? "create_task" : "post", parsed.data.channel);
680
+ if (scopeErr)
681
+ return scopeErr;
682
+ if (parsed.data.idempotencyKey && postIdempotency.has(parsed.data.idempotencyKey)) {
683
+ const existingId = postIdempotency.get(parsed.data.idempotencyKey);
684
+ const existingIssue = issues.get(existingId);
685
+ return jsonResponse(publicIssueView(existingIssue), 200);
686
+ }
687
+ const combinedBlocks = [...(parsed.data.blocks ?? [])];
688
+ if (parsed.data.schema) {
689
+ const sRef = parseSchemaRef(parsed.data.schema.ref);
690
+ combinedBlocks.push({
691
+ schema: sRef.name,
692
+ version: sRef.version,
693
+ data: parsed.data.schema.data,
694
+ });
695
+ }
696
+ const blockErr = validateBlocks(combinedBlocks);
697
+ if (blockErr)
698
+ return blockErr;
699
+ const ch = ensureChannel(parsed.data.channel, actor);
700
+ const rawText = parsed.data.text ?? parsed.data.description ?? "";
701
+ let title;
702
+ let description;
703
+ if (parsed.data.title && parsed.data.title.trim()) {
704
+ title = parsed.data.title.trim();
705
+ description = rawText.trim() ? rawText : null;
706
+ }
707
+ else {
708
+ const fallback = combinedBlocks[0]
709
+ ? `[${combinedBlocks[0].schema}@${combinedBlocks[0].version}]`
710
+ : "Untitled post";
711
+ const split = splitMessageIntoTitleAndDescription(rawText, fallback);
712
+ title = split.title;
713
+ description = split.description;
714
+ }
715
+ let resolvedProjectId = ch.defaultProjectId;
716
+ if (parsed.data.projectId !== undefined) {
717
+ if (parsed.data.projectId === null) {
718
+ resolvedProjectId = null;
719
+ }
720
+ else {
721
+ const proj = findProject(parsed.data.projectId);
722
+ resolvedProjectId = proj ? proj.id : parsed.data.projectId;
723
+ }
724
+ }
725
+ issueNumSeq += 1;
726
+ const id = makeUuid(uuidSeq++);
727
+ const identifier = `${companyPrefix}-${issueNumSeq}`;
728
+ const ts = nowIso();
729
+ const scope = parsed.data.board ? "board" : "channel";
730
+ const assigneeAgentId = typeof rawAssigneeAgentId === "string" ? rawAssigneeAgentId : null;
731
+ const stored = {
732
+ id,
733
+ companyId,
734
+ identifier,
735
+ title,
736
+ description,
737
+ status: requestedStatus,
738
+ scope,
739
+ priority: parsed.data.priority ?? "medium",
740
+ channelId: ch.id,
741
+ channel: ch.path,
742
+ projectId: resolvedProjectId,
743
+ assigneeAgentId,
744
+ assigneeUserId: null,
745
+ actorProfile: actor.actorProfile,
746
+ kvLabels: { ...(parsed.data.labels ?? {}) },
747
+ tagLabels: [...(parsed.data.tagLabels ?? [])],
748
+ blocks: combinedBlocks,
749
+ resultSchemaRef: resultSchemaRef ?? null,
750
+ blockedByIssueIds: [],
751
+ isPassivePost: requestedStatus === "backlog" && assigneeAgentId === null,
752
+ claimEpoch: 0,
753
+ claimHolderProfile: null,
754
+ claimHolderAgentId: null,
755
+ claimHolderUserId: null,
756
+ claimLeaseExpiresAt: null,
757
+ claimAttemptCount: 0,
758
+ cursor: "evt_0",
759
+ createdAt: ts,
760
+ updatedAt: ts,
761
+ claimToken: null,
762
+ sourceTrust: parsed.data.sourceTrust ?? "trusted",
763
+ };
764
+ issues.set(id, stored);
765
+ issueByIdentifier.set(identifier, id);
766
+ if (parsed.data.idempotencyKey) {
767
+ postIdempotency.set(parsed.data.idempotencyKey, id);
768
+ }
769
+ const primaryEvent = emitEvent(requestedStatus === "todo" ? "task.created" : "thread.posted", actor, {
770
+ channel: ch.path,
771
+ issueId: id,
772
+ identifier,
773
+ payload: {
774
+ blocks: combinedBlocks,
775
+ labels: stored.kvLabels,
776
+ },
777
+ });
778
+ stored.cursor = primaryEvent.cursor;
779
+ if (requestedStatus === "todo" && isTaskReadyInPool(stored)) {
780
+ const readyEvt = emitEvent("task.ready", actor, {
781
+ channel: ch.path,
782
+ issueId: id,
783
+ identifier,
784
+ payload: {},
785
+ });
786
+ stored.cursor = readyEvt.cursor;
787
+ }
788
+ return jsonResponse(publicIssueView(stored), 201);
789
+ }
790
+ // 6. Batch task DAG plan
791
+ const batchMatch = /^\/api\/companies\/([^/]+)\/issues\/batch$/.exec(pathname);
792
+ if (batchMatch && method === "POST") {
793
+ if (batchMatch[1] !== companyId) {
794
+ return errorResponse(404, "company_not_found", "Company not found");
795
+ }
796
+ const sortedResult = validateAndSortBatchPlan(bodyJson);
797
+ if (!sortedResult.ok) {
798
+ return errorResponse(400, sortedResult.code, sortedResult.message, {
799
+ duplicateKeys: sortedResult.duplicateKeys,
800
+ unknownDependencies: sortedResult.unknownDependencies,
801
+ cycleKeys: sortedResult.cycleKeys,
802
+ });
803
+ }
804
+ const scopeErr = checkScopes(actor, "create_task", sortedResult.channel ?? null);
805
+ if (scopeErr)
806
+ return scopeErr;
807
+ if (sortedResult.idempotencyKey) {
808
+ const payloadHash = JSON.stringify(bodyJson);
809
+ const existing = batchIdempotency.get(sortedResult.idempotencyKey);
810
+ if (existing) {
811
+ if (existing.payloadHash !== payloadHash) {
812
+ return errorResponse(409, "duplicate_idempotency_key", `Idempotency key "${sortedResult.idempotencyKey}" already used with a different payload`);
813
+ }
814
+ return jsonResponse({ ...existing.result, idempotentReplay: true }, 200);
815
+ }
816
+ }
817
+ // Resolve projectIds upfront before mutating
818
+ const resolvedTaskProjectIds = new Map();
819
+ const ch = sortedResult.channel
820
+ ? ensureChannel(sortedResult.channel, actor)
821
+ : null;
822
+ for (const task of sortedResult.tasks) {
823
+ if (task.projectId === null) {
824
+ resolvedTaskProjectIds.set(task.index, null);
825
+ }
826
+ else if (task.projectId !== undefined) {
827
+ const proj = findProject(task.projectId);
828
+ if (!proj && projects.size > 0 && !UUID_RE.test(task.projectId)) {
829
+ return errorResponse(404, "project_not_found", `Project "${task.projectId}" not found`);
830
+ }
831
+ resolvedTaskProjectIds.set(task.index, proj ? proj.id : task.projectId);
832
+ }
833
+ else {
834
+ resolvedTaskProjectIds.set(task.index, ch?.defaultProjectId ?? null);
835
+ }
836
+ }
837
+ const createdByKey = new Map();
838
+ const createdItems = [];
839
+ for (const task of sortedResult.tasks) {
840
+ const blockErr = validateBlocks(task.blocks);
841
+ if (blockErr)
842
+ return blockErr;
843
+ const blockedByIssueIds = [];
844
+ for (const depKey of task.localNeeds) {
845
+ const depIssue = createdByKey.get(depKey);
846
+ if (depIssue)
847
+ blockedByIssueIds.push(depIssue.id);
848
+ }
849
+ for (const extRef of task.externalNeeds) {
850
+ const extIssue = findIssue(extRef);
851
+ if (!extIssue) {
852
+ return errorResponse(404, "issue_not_found", `External dependency "${extRef}" not found`);
853
+ }
854
+ blockedByIssueIds.push(extIssue.id);
855
+ }
856
+ issueNumSeq += 1;
857
+ const id = makeUuid(uuidSeq++);
858
+ const identifier = `${companyPrefix}-${issueNumSeq}`;
859
+ const ts = nowIso();
860
+ const scope = task.board ? "board" : ch ? "channel" : "board";
861
+ const stored = {
862
+ id,
863
+ companyId,
864
+ identifier,
865
+ title: task.title,
866
+ description: task.description,
867
+ status: "todo",
868
+ scope,
869
+ priority: task.priority,
870
+ channelId: ch?.id ?? null,
871
+ channel: ch?.path ?? null,
872
+ projectId: resolvedTaskProjectIds.get(task.index) ?? null,
873
+ assigneeAgentId: task.assigneeAgentId ?? null,
874
+ assigneeUserId: null,
875
+ actorProfile: actor.actorProfile,
876
+ kvLabels: { ...task.labels },
877
+ tagLabels: [...task.tagLabels],
878
+ blocks: [...task.blocks],
879
+ resultSchemaRef: task.resultSchema ?? null,
880
+ blockedByIssueIds,
881
+ isPassivePost: false,
882
+ claimEpoch: 0,
883
+ claimHolderProfile: null,
884
+ claimHolderAgentId: null,
885
+ claimHolderUserId: null,
886
+ claimLeaseExpiresAt: null,
887
+ claimAttemptCount: 0,
888
+ cursor: "evt_0",
889
+ createdAt: ts,
890
+ updatedAt: ts,
891
+ claimToken: null,
892
+ sourceTrust: "trusted",
893
+ };
894
+ issues.set(id, stored);
895
+ issueByIdentifier.set(identifier, id);
896
+ if (task.key)
897
+ createdByKey.set(task.key, stored);
898
+ const evt = emitEvent("task.created", actor, {
899
+ channel: stored.channel,
900
+ issueId: id,
901
+ identifier,
902
+ payload: { key: task.key, blockedByIssueIds },
903
+ });
904
+ stored.cursor = evt.cursor;
905
+ if (isTaskReadyInPool(stored)) {
906
+ const readyEvt = emitEvent("task.ready", actor, {
907
+ channel: stored.channel,
908
+ issueId: id,
909
+ identifier,
910
+ payload: {},
911
+ });
912
+ stored.cursor = readyEvt.cursor;
913
+ }
914
+ createdItems.push({
915
+ key: task.key,
916
+ id,
917
+ identifier,
918
+ cursor: stored.cursor,
919
+ issue: publicIssueView(stored),
920
+ });
921
+ }
922
+ const result = {
923
+ tasks: createdItems,
924
+ cursor: formatEventCursor(eventSeq),
925
+ idempotentReplay: false,
926
+ };
927
+ if (sortedResult.idempotencyKey) {
928
+ batchIdempotency.set(sortedResult.idempotencyKey, {
929
+ payloadHash: JSON.stringify(bodyJson),
930
+ result,
931
+ });
932
+ }
933
+ return jsonResponse(result, 201);
934
+ }
935
+ // 7. Issues list
936
+ const issuesListMatch = /^\/api\/companies\/([^/]+)\/issues$/.exec(pathname);
937
+ if (issuesListMatch && method === "GET") {
938
+ if (issuesListMatch[1] !== companyId) {
939
+ return errorResponse(404, "company_not_found", "Company not found");
940
+ }
941
+ const scopeErr = checkScopes(actor, "read");
942
+ if (scopeErr)
943
+ return scopeErr;
944
+ const channelParam = url.searchParams.get("channel");
945
+ const channelNorm = channelParam
946
+ ? normalizeChannelPath(channelParam, { allowSubtreePrefix: true })
947
+ : null;
948
+ const statusFilters = url.searchParams.getAll("status");
949
+ const labelFilters = url.searchParams.getAll("label");
950
+ const projectFilter = url.searchParams.get("project");
951
+ const readyFilter = url.searchParams.get("ready") === "true";
952
+ const items = [];
953
+ for (const issue of issues.values()) {
954
+ if (channelNorm) {
955
+ if (!issue.channel)
956
+ continue;
957
+ if (channelNorm.isSubtreePrefix) {
958
+ if (issue.channel !== channelNorm.path &&
959
+ !issue.channel.startsWith(`${channelNorm.path}/`)) {
960
+ continue;
961
+ }
962
+ }
963
+ else if (issue.channel !== channelNorm.path) {
964
+ continue;
965
+ }
966
+ }
967
+ if (statusFilters.length > 0 && !statusFilters.includes(issue.status)) {
968
+ continue;
969
+ }
970
+ if (labelFilters.length > 0 &&
971
+ !labelFilters.every((expr) => matchesLabelFilter(issue.kvLabels, issue.tagLabels, expr))) {
972
+ continue;
973
+ }
974
+ if (projectFilter) {
975
+ const proj = findProject(projectFilter);
976
+ const expectedId = proj ? proj.id : projectFilter;
977
+ if (issue.projectId !== expectedId)
978
+ continue;
979
+ }
980
+ if (readyFilter && !isTaskReadyInPool(issue)) {
981
+ continue;
982
+ }
983
+ items.push(publicIssueView(issue));
984
+ }
985
+ return jsonResponse({ items, cursor: formatEventCursor(eventSeq) });
986
+ }
987
+ // 8. Issue detail / patch
988
+ const singleIssueMatch = /^\/api\/issues\/([^/]+)$/.exec(pathname);
989
+ if (singleIssueMatch) {
990
+ const issue = findIssue(decodeURIComponent(singleIssueMatch[1]));
991
+ if (!issue) {
992
+ return errorResponse(404, "issue_not_found", "Issue not found");
993
+ }
994
+ if (method === "GET") {
995
+ const scopeErr = checkScopes(actor, "read", issue.channel);
996
+ if (scopeErr)
997
+ return scopeErr;
998
+ const detail = {
999
+ kind: "thread",
1000
+ issue: publicIssueView(issue),
1001
+ comments: [...(commentsByIssue.get(issue.id) ?? [])],
1002
+ interactions: [...(interactionsByIssue.get(issue.id) ?? [])],
1003
+ cursor: formatEventCursor(eventSeq),
1004
+ };
1005
+ return jsonResponse(detail);
1006
+ }
1007
+ if (method === "PATCH") {
1008
+ const scopeErr = checkScopes(actor, "create_task", issue.channel);
1009
+ if (scopeErr)
1010
+ return scopeErr;
1011
+ const patch = (bodyJson ?? {});
1012
+ const prevStatus = issue.status;
1013
+ if (typeof patch.status === "string") {
1014
+ issue.status = patch.status;
1015
+ if (issue.status !== "in_progress" && issue.claimToken !== null) {
1016
+ issue.claimToken = null;
1017
+ issue.claimHolderAgentId = null;
1018
+ issue.claimHolderUserId = null;
1019
+ issue.claimHolderProfile = null;
1020
+ issue.claimLeaseExpiresAt = null;
1021
+ }
1022
+ }
1023
+ if (typeof patch.priority === "string") {
1024
+ issue.priority = patch.priority;
1025
+ }
1026
+ if (typeof patch.scope === "string") {
1027
+ issue.scope = patch.scope;
1028
+ }
1029
+ if (patch.projectId !== undefined) {
1030
+ if (patch.projectId === null) {
1031
+ issue.projectId = null;
1032
+ }
1033
+ else if (typeof patch.projectId === "string") {
1034
+ const proj = findProject(patch.projectId);
1035
+ issue.projectId = proj ? proj.id : patch.projectId;
1036
+ }
1037
+ }
1038
+ if (patch.labels && typeof patch.labels === "object") {
1039
+ Object.assign(issue.kvLabels, patch.labels);
1040
+ }
1041
+ if (typeof patch.resultSchema === "string") {
1042
+ issue.resultSchemaRef = patch.resultSchema;
1043
+ }
1044
+ if (patch.assigneeAgentId !== undefined) {
1045
+ issue.assigneeAgentId =
1046
+ typeof patch.assigneeAgentId === "string" ? patch.assigneeAgentId : null;
1047
+ }
1048
+ issue.isPassivePost =
1049
+ issue.status === "backlog" &&
1050
+ issue.assigneeAgentId === null &&
1051
+ issue.assigneeUserId === null;
1052
+ issue.updatedAt = nowIso();
1053
+ if (prevStatus === "backlog" && issue.status === "todo" && isTaskReadyInPool(issue)) {
1054
+ const evt = emitEvent("task.ready", actor, {
1055
+ channel: issue.channel,
1056
+ issueId: issue.id,
1057
+ identifier: issue.identifier,
1058
+ payload: { promotedFromBacklog: true },
1059
+ });
1060
+ issue.cursor = evt.cursor;
1061
+ }
1062
+ return jsonResponse(publicIssueView(issue));
1063
+ }
1064
+ }
1065
+ // 9. Comments (reply)
1066
+ const commentsMatch = /^\/api\/issues\/([^/]+)\/comments$/.exec(pathname);
1067
+ if (commentsMatch) {
1068
+ const issue = findIssue(decodeURIComponent(commentsMatch[1]));
1069
+ if (!issue) {
1070
+ return errorResponse(404, "issue_not_found", "Issue not found");
1071
+ }
1072
+ if (method === "GET") {
1073
+ return jsonResponse({ items: commentsByIssue.get(issue.id) ?? [] });
1074
+ }
1075
+ if (method === "POST") {
1076
+ const scopeErr = checkScopes(actor, "post", issue.channel);
1077
+ if (scopeErr)
1078
+ return scopeErr;
1079
+ const body = (bodyJson ?? {});
1080
+ const idempKey = typeof body.idempotencyKey === "string"
1081
+ ? body.idempotencyKey
1082
+ : typeof body.clientRequestId === "string"
1083
+ ? body.clientRequestId
1084
+ : undefined;
1085
+ if (idempKey && commentIdempotency.has(idempKey)) {
1086
+ return jsonResponse(commentIdempotency.get(idempKey), 200);
1087
+ }
1088
+ const existingComments = commentsByIssue.get(issue.id) ?? [];
1089
+ const afterId = typeof body.afterCommentId === "string"
1090
+ ? body.afterCommentId
1091
+ : typeof body.after === "string"
1092
+ ? body.after
1093
+ : undefined;
1094
+ if (afterId) {
1095
+ const latest = existingComments.length > 0
1096
+ ? existingComments[existingComments.length - 1].id
1097
+ : null;
1098
+ if (latest !== afterId) {
1099
+ return errorResponse(409, "newer_message", "Newer comments have been posted since the provided cursor", { latestCommentId: latest });
1100
+ }
1101
+ }
1102
+ const blocks = Array.isArray(body.blocks)
1103
+ ? body.blocks
1104
+ : undefined;
1105
+ const blockErr = validateBlocks(blocks);
1106
+ if (blockErr)
1107
+ return blockErr;
1108
+ const kvLabels = body.kvLabels && typeof body.kvLabels === "object"
1109
+ ? body.kvLabels
1110
+ : {};
1111
+ const comment = {
1112
+ id: makeUuid(uuidSeq++),
1113
+ issueId: issue.id,
1114
+ identifier: issue.identifier,
1115
+ body: typeof body.body === "string" ? body.body : "",
1116
+ authorType: actor.agentId ? "agent" : "user",
1117
+ authorUserId: actor.userId,
1118
+ authorAgentId: actor.agentId,
1119
+ actorProfile: actor.actorProfile,
1120
+ kvLabels,
1121
+ blocks: blocks ?? [],
1122
+ internal: Boolean(body.internal),
1123
+ cursor: "evt_0",
1124
+ createdAt: nowIso(),
1125
+ };
1126
+ existingComments.push(comment);
1127
+ commentsByIssue.set(issue.id, existingComments);
1128
+ const evt = emitEvent("comment.posted", actor, {
1129
+ channel: issue.channel,
1130
+ issueId: issue.id,
1131
+ identifier: issue.identifier,
1132
+ payload: { commentId: comment.id, blocks: comment.blocks },
1133
+ });
1134
+ comment.cursor = evt.cursor;
1135
+ issue.cursor = evt.cursor;
1136
+ issue.updatedAt = nowIso();
1137
+ if (idempKey) {
1138
+ commentIdempotency.set(idempKey, comment);
1139
+ }
1140
+ return jsonResponse(comment, 201);
1141
+ }
1142
+ }
1143
+ // 10. CAS kv-labels
1144
+ const kvLabelsMatch = /^\/api\/issues\/([^/]+)\/kv-labels$/.exec(pathname);
1145
+ if (kvLabelsMatch && method === "PATCH") {
1146
+ const issue = findIssue(decodeURIComponent(kvLabelsMatch[1]));
1147
+ if (!issue) {
1148
+ return errorResponse(404, "issue_not_found", "Issue not found");
1149
+ }
1150
+ const scopeErr = checkScopes(actor, "label", issue.channel);
1151
+ if (scopeErr)
1152
+ return scopeErr;
1153
+ // Check reserved label prefix explicitly to return 400 reserved_label
1154
+ const rawMut = (bodyJson ?? {});
1155
+ for (const field of ["set", "unset"]) {
1156
+ const val = rawMut[field];
1157
+ const keys = field === "set" && val && typeof val === "object"
1158
+ ? Object.keys(val)
1159
+ : field === "unset" && Array.isArray(val)
1160
+ ? val.filter((k) => typeof k === "string")
1161
+ : [];
1162
+ if (keys.some((k) => k.startsWith("paperclip."))) {
1163
+ return errorResponse(400, "reserved_label", "Label keys starting with 'paperclip.' are reserved for server metadata");
1164
+ }
1165
+ }
1166
+ const parsed = KvLabelMutationSchema.safeParse(bodyJson);
1167
+ if (!parsed.success) {
1168
+ return errorResponse(400, "validation_error", parsed.error.message);
1169
+ }
1170
+ const applied = applyKvLabelMutation(issue.kvLabels, parsed.data);
1171
+ if (!applied.ok) {
1172
+ return errorResponse(409, "label_conflict", `Compare-and-swap failed on keys: ${applied.conflictingKeys.join(", ")}`, { conflictingKeys: applied.conflictingKeys });
1173
+ }
1174
+ issue.kvLabels = applied.labels;
1175
+ issue.updatedAt = nowIso();
1176
+ const evt = emitEvent("labels.changed", actor, {
1177
+ channel: issue.channel,
1178
+ issueId: issue.id,
1179
+ identifier: issue.identifier,
1180
+ payload: { kvLabels: issue.kvLabels },
1181
+ });
1182
+ issue.cursor = evt.cursor;
1183
+ return jsonResponse({
1184
+ id: issue.id,
1185
+ kvLabels: { ...issue.kvLabels },
1186
+ cursor: evt.cursor,
1187
+ });
1188
+ }
1189
+ // 11. Claim task (specific or ready pool pop)
1190
+ const claimMatch = /^\/api\/companies\/([^/]+)\/tasks\/claim$/.exec(pathname);
1191
+ if (claimMatch && method === "POST") {
1192
+ if (claimMatch[1] !== companyId) {
1193
+ return errorResponse(404, "company_not_found", "Company not found");
1194
+ }
1195
+ expireLeases();
1196
+ const parsed = TaskClaimRequestSchema.safeParse(bodyJson ?? {});
1197
+ if (!parsed.success) {
1198
+ return errorResponse(400, "validation_error", parsed.error.message);
1199
+ }
1200
+ const reqData = parsed.data;
1201
+ const scopeErr = checkScopes(actor, "claim", reqData.channel ?? null);
1202
+ if (scopeErr)
1203
+ return scopeErr;
1204
+ const tryClaim = () => {
1205
+ expireLeases();
1206
+ let target = null;
1207
+ if (reqData.issueId) {
1208
+ const found = findIssue(reqData.issueId);
1209
+ if (!found) {
1210
+ return {
1211
+ error: errorResponse(404, "issue_not_found", `Task "${reqData.issueId}" not found`),
1212
+ };
1213
+ }
1214
+ if (found.status === "done" || found.status === "cancelled") {
1215
+ return {
1216
+ error: errorResponse(409, "task_finished", "Task is already finished"),
1217
+ };
1218
+ }
1219
+ if (found.status === "blocked") {
1220
+ return {
1221
+ error: errorResponse(409, "task_blocked", "Task is blocked"),
1222
+ };
1223
+ }
1224
+ if (found.assigneeAgentId || found.assigneeUserId) {
1225
+ if (found.assigneeAgentId !== actor.agentId) {
1226
+ return {
1227
+ error: errorResponse(409, "task_assigned", "Task is assigned to another actor"),
1228
+ };
1229
+ }
1230
+ }
1231
+ if (found.claimToken !== null || found.status === "in_progress") {
1232
+ return {
1233
+ error: errorResponse(409, "task_claimed", "Task is already claimed"),
1234
+ };
1235
+ }
1236
+ if (isTaskBlocked(found)) {
1237
+ return {
1238
+ error: errorResponse(409, "task_waiting", "Task has unresolved blockers"),
1239
+ };
1240
+ }
1241
+ if (found.status !== "todo") {
1242
+ return {
1243
+ error: errorResponse(409, "task_not_ready", `Task status is "${found.status}", expected "todo"`),
1244
+ };
1245
+ }
1246
+ target = found;
1247
+ }
1248
+ else {
1249
+ const channelNorm = reqData.channel
1250
+ ? normalizeChannelPath(reqData.channel, { allowSubtreePrefix: true })
1251
+ : null;
1252
+ const projectMatchId = reqData.projectId
1253
+ ? findProject(reqData.projectId)?.id ?? reqData.projectId
1254
+ : null;
1255
+ const labelFilters = reqData.labels ?? [];
1256
+ const candidates = [];
1257
+ for (const issue of issues.values()) {
1258
+ if (!isTaskReadyInPool(issue))
1259
+ continue;
1260
+ if (!reqData.includeUntrusted && issue.sourceTrust !== "trusted") {
1261
+ continue;
1262
+ }
1263
+ if (channelNorm) {
1264
+ if (!issue.channel)
1265
+ continue;
1266
+ if (channelNorm.isSubtreePrefix) {
1267
+ if (issue.channel !== channelNorm.path &&
1268
+ !issue.channel.startsWith(`${channelNorm.path}/`)) {
1269
+ continue;
1270
+ }
1271
+ }
1272
+ else if (issue.channel !== channelNorm.path) {
1273
+ continue;
1274
+ }
1275
+ }
1276
+ if (projectMatchId && issue.projectId !== projectMatchId)
1277
+ continue;
1278
+ if (labelFilters.length > 0 &&
1279
+ !labelFilters.every((expr) => matchesLabelFilter(issue.kvLabels, issue.tagLabels, expr))) {
1280
+ continue;
1281
+ }
1282
+ candidates.push(issue);
1283
+ }
1284
+ const chObj = channelNorm && !channelNorm.isSubtreePrefix
1285
+ ? channels.get(channelNorm.path)
1286
+ : undefined;
1287
+ const ordering = chObj?.queueConfig.ordering ?? "priority_fifo";
1288
+ candidates.sort((a, b) => {
1289
+ if (ordering === "priority_fifo") {
1290
+ const pDiff = PRIORITY_RANK[a.priority] - PRIORITY_RANK[b.priority];
1291
+ if (pDiff !== 0)
1292
+ return pDiff;
1293
+ }
1294
+ const tDiff = a.createdAt.localeCompare(b.createdAt);
1295
+ if (tDiff !== 0)
1296
+ return tDiff;
1297
+ return a.id.localeCompare(b.id);
1298
+ });
1299
+ target = candidates[0] ?? null;
1300
+ }
1301
+ if (!target) {
1302
+ return {};
1303
+ }
1304
+ const ch = target.channel ? channels.get(target.channel) : undefined;
1305
+ const defaultLeaseSec = ch?.queueConfig.defaultLeaseSec ?? 300;
1306
+ const requestedLeaseSec = reqData.leaseSec ??
1307
+ (reqData.lease !== undefined
1308
+ ? Math.max(1, Math.round(parseDurationMs(reqData.lease) / 1000))
1309
+ : defaultLeaseSec);
1310
+ const maxLeaseSec = ch?.queueConfig.maxLeaseSec ?? 3600;
1311
+ const leaseSec = Math.min(requestedLeaseSec, maxLeaseSec);
1312
+ const claimToken = `clm_${makeUuid(uuidSeq++)}`;
1313
+ target.status = "in_progress";
1314
+ target.claimEpoch += 1;
1315
+ target.claimToken = claimToken;
1316
+ target.claimHolderAgentId = actor.agentId;
1317
+ target.claimHolderUserId = actor.userId;
1318
+ target.claimHolderProfile = actor.actorProfile;
1319
+ target.claimLeaseExpiresAt = new Date(currentNowMs + leaseSec * 1000).toISOString();
1320
+ target.claimAttemptCount += 1;
1321
+ target.updatedAt = nowIso();
1322
+ const evt = emitEvent("task.claimed", actor, {
1323
+ channel: target.channel,
1324
+ issueId: target.id,
1325
+ identifier: target.identifier,
1326
+ payload: {
1327
+ claimEpoch: target.claimEpoch,
1328
+ leaseExpiresAt: target.claimLeaseExpiresAt,
1329
+ },
1330
+ });
1331
+ target.cursor = evt.cursor;
1332
+ return {
1333
+ claim: {
1334
+ issue: publicIssueView(target),
1335
+ claimToken,
1336
+ claimEpoch: target.claimEpoch,
1337
+ leaseExpiresAt: target.claimLeaseExpiresAt,
1338
+ cursor: evt.cursor,
1339
+ },
1340
+ };
1341
+ };
1342
+ const first = tryClaim();
1343
+ if (first.error)
1344
+ return first.error;
1345
+ if (first.claim)
1346
+ return jsonResponse(first.claim, 200);
1347
+ const waitMs = reqData.waitSec !== undefined
1348
+ ? Math.max(0, reqData.waitSec * 1000)
1349
+ : reqData.wait !== undefined
1350
+ ? parseDurationMs(reqData.wait)
1351
+ : 0;
1352
+ if (waitMs <= 0) {
1353
+ return jsonResponse(null, 204);
1354
+ }
1355
+ return new Promise((resolve) => {
1356
+ let settled = false;
1357
+ const cleanup = () => {
1358
+ listeners.delete(onEvent);
1359
+ clearTimeout(timer);
1360
+ init?.signal?.removeEventListener("abort", onAbort);
1361
+ };
1362
+ const onAbort = () => {
1363
+ if (settled)
1364
+ return;
1365
+ settled = true;
1366
+ cleanup();
1367
+ resolve(jsonResponse(null, 204));
1368
+ };
1369
+ const onEvent = (evt) => {
1370
+ if (settled)
1371
+ return;
1372
+ if (evt.type !== "task.ready" &&
1373
+ evt.type !== "task.created" &&
1374
+ evt.type !== "task.unblocked") {
1375
+ return;
1376
+ }
1377
+ const attempt = tryClaim();
1378
+ if (attempt.claim) {
1379
+ settled = true;
1380
+ cleanup();
1381
+ resolve(jsonResponse(attempt.claim, 200));
1382
+ }
1383
+ };
1384
+ const timer = setTimeout(() => {
1385
+ if (settled)
1386
+ return;
1387
+ settled = true;
1388
+ cleanup();
1389
+ resolve(jsonResponse(null, 204));
1390
+ }, waitMs);
1391
+ if (init?.signal?.aborted) {
1392
+ onAbort();
1393
+ return;
1394
+ }
1395
+ init?.signal?.addEventListener("abort", onAbort, { once: true });
1396
+ listeners.add(onEvent);
1397
+ });
1398
+ }
1399
+ // 12. Renew / Release / Complete / Fail claim
1400
+ const claimActionMatch = /^\/api\/issues\/([^/]+)\/claim\/(renew|release|complete|fail)$/.exec(pathname);
1401
+ if (claimActionMatch && method === "POST") {
1402
+ const issue = findIssue(decodeURIComponent(claimActionMatch[1]));
1403
+ if (!issue) {
1404
+ return errorResponse(404, "issue_not_found", "Issue not found");
1405
+ }
1406
+ const action = claimActionMatch[2];
1407
+ const claimTokenHeader = headers.get("x-paperclip-claim-token");
1408
+ if (action === "renew") {
1409
+ const parsed = TaskRenewSchema.safeParse(bodyJson ?? {});
1410
+ if (!parsed.success) {
1411
+ return errorResponse(400, "validation_error", parsed.error.message);
1412
+ }
1413
+ const authErr = checkClaimMutationAuth(issue, actor, claimTokenHeader, parsed.data.claimToken, parsed.data.claimEpoch);
1414
+ if (authErr)
1415
+ return authErr;
1416
+ const ch = issue.channel ? channels.get(issue.channel) : undefined;
1417
+ const maxLeaseSec = ch?.queueConfig.maxLeaseSec ?? 3600;
1418
+ const leaseSec = Math.min(parsed.data.leaseSec ??
1419
+ (parsed.data.lease !== undefined
1420
+ ? Math.max(1, Math.round(parseDurationMs(parsed.data.lease) / 1000))
1421
+ : ch?.queueConfig.defaultLeaseSec ?? 300), maxLeaseSec);
1422
+ issue.claimLeaseExpiresAt = new Date(currentNowMs + leaseSec * 1000).toISOString();
1423
+ issue.updatedAt = nowIso();
1424
+ const evt = emitEvent("task.lease_renewed", actor, {
1425
+ channel: issue.channel,
1426
+ issueId: issue.id,
1427
+ identifier: issue.identifier,
1428
+ payload: { leaseExpiresAt: issue.claimLeaseExpiresAt },
1429
+ });
1430
+ issue.cursor = evt.cursor;
1431
+ return jsonResponse({
1432
+ issue: publicIssueView(issue),
1433
+ claimToken: issue.claimToken,
1434
+ claimEpoch: issue.claimEpoch,
1435
+ leaseExpiresAt: issue.claimLeaseExpiresAt,
1436
+ cursor: evt.cursor,
1437
+ });
1438
+ }
1439
+ if (action === "release") {
1440
+ const parsed = TaskReleaseSchema.safeParse(bodyJson ?? {});
1441
+ if (!parsed.success) {
1442
+ return errorResponse(400, "validation_error", parsed.error.message);
1443
+ }
1444
+ const authErr = checkClaimMutationAuth(issue, actor, claimTokenHeader, parsed.data.claimToken, parsed.data.claimEpoch);
1445
+ if (authErr)
1446
+ return authErr;
1447
+ issue.status = "todo";
1448
+ issue.claimEpoch += 1;
1449
+ issue.claimToken = null;
1450
+ issue.claimHolderAgentId = null;
1451
+ issue.claimHolderUserId = null;
1452
+ issue.claimHolderProfile = null;
1453
+ issue.claimLeaseExpiresAt = null;
1454
+ issue.updatedAt = nowIso();
1455
+ emitEvent("task.lease_released", actor, {
1456
+ channel: issue.channel,
1457
+ issueId: issue.id,
1458
+ identifier: issue.identifier,
1459
+ payload: { comment: parsed.data.comment ?? null },
1460
+ });
1461
+ const readyEvt = emitEvent("task.ready", actor, {
1462
+ channel: issue.channel,
1463
+ issueId: issue.id,
1464
+ identifier: issue.identifier,
1465
+ payload: {},
1466
+ });
1467
+ issue.cursor = readyEvt.cursor;
1468
+ return jsonResponse({ released: true, cursor: readyEvt.cursor });
1469
+ }
1470
+ if (action === "complete") {
1471
+ const parsed = TaskCompleteSchema.safeParse(bodyJson ?? {});
1472
+ if (!parsed.success) {
1473
+ return errorResponse(400, "validation_error", parsed.error.message);
1474
+ }
1475
+ const authErr = checkClaimMutationAuth(issue, actor, claimTokenHeader, parsed.data.claimToken, parsed.data.claimEpoch);
1476
+ if (authErr)
1477
+ return authErr;
1478
+ if (issue.resultSchemaRef &&
1479
+ parsed.data.resultSchema &&
1480
+ parsed.data.resultSchema !== issue.resultSchemaRef) {
1481
+ return errorResponse(409, "result_schema_mismatch", `Task requires saved result schema "${issue.resultSchemaRef}", not "${parsed.data.resultSchema}"`);
1482
+ }
1483
+ const completionBlocks = [...(parsed.data.blocks ?? [])];
1484
+ if (parsed.data.data && issue.resultSchemaRef) {
1485
+ const refParsed = parseSchemaRef(issue.resultSchemaRef);
1486
+ completionBlocks.push({
1487
+ schema: refParsed.name,
1488
+ version: refParsed.version,
1489
+ data: parsed.data.data,
1490
+ });
1491
+ }
1492
+ else if (parsed.data.data && parsed.data.resultSchema) {
1493
+ const refParsed = parseSchemaRef(parsed.data.resultSchema);
1494
+ completionBlocks.push({
1495
+ schema: refParsed.name,
1496
+ version: refParsed.version,
1497
+ data: parsed.data.data,
1498
+ });
1499
+ }
1500
+ if (issue.resultSchemaRef) {
1501
+ const expected = parseSchemaRef(issue.resultSchemaRef);
1502
+ const matchingBlock = completionBlocks.find((b) => b.schema === expected.name && b.version === expected.version);
1503
+ if (!matchingBlock) {
1504
+ return errorResponse(422, "missing_or_invalid_result_schema", `Task requires completion data matching schema "${issue.resultSchemaRef}"`);
1505
+ }
1506
+ const schemaEntry = schemasByRef.get(issue.resultSchemaRef);
1507
+ if (!schemaEntry) {
1508
+ return errorResponse(422, "missing_or_invalid_result_schema", `Schema "${issue.resultSchemaRef}" is not registered`);
1509
+ }
1510
+ const check = validateAgainstJsonSchema(schemaEntry.jsonSchema, matchingBlock.data);
1511
+ if (!check.valid) {
1512
+ return errorResponse(422, "missing_or_invalid_result_schema", `Result data failed schema ${issue.resultSchemaRef}: ${check.errors.join("; ")}`, { errors: check.errors });
1513
+ }
1514
+ }
1515
+ const blockErr = validateBlocks(completionBlocks);
1516
+ if (blockErr)
1517
+ return blockErr;
1518
+ if (parsed.data.prUrl) {
1519
+ issue.kvLabels["paperclip.pr"] = parsed.data.prUrl;
1520
+ }
1521
+ if (completionBlocks.length > 0) {
1522
+ issue.blocks.push(...completionBlocks);
1523
+ }
1524
+ const note = parsed.data.message ?? parsed.data.comment;
1525
+ if (note || completionBlocks.length > 0) {
1526
+ const list = commentsByIssue.get(issue.id) ?? [];
1527
+ list.push({
1528
+ id: makeUuid(uuidSeq++),
1529
+ issueId: issue.id,
1530
+ identifier: issue.identifier,
1531
+ body: note ?? `Completed (${issue.resultSchemaRef ?? "done"})`,
1532
+ authorType: actor.agentId ? "agent" : "user",
1533
+ authorUserId: actor.userId,
1534
+ authorAgentId: actor.agentId,
1535
+ actorProfile: actor.actorProfile,
1536
+ kvLabels: {},
1537
+ blocks: completionBlocks,
1538
+ internal: false,
1539
+ cursor: formatEventCursor(eventSeq + 1),
1540
+ createdAt: nowIso(),
1541
+ });
1542
+ commentsByIssue.set(issue.id, list);
1543
+ }
1544
+ issue.status = "done";
1545
+ issue.claimEpoch += 1;
1546
+ issue.claimToken = null;
1547
+ issue.claimHolderAgentId = null;
1548
+ issue.claimHolderUserId = null;
1549
+ issue.claimHolderProfile = null;
1550
+ issue.claimLeaseExpiresAt = null;
1551
+ issue.updatedAt = nowIso();
1552
+ const evt = emitEvent("task.completed", actor, {
1553
+ channel: issue.channel,
1554
+ issueId: issue.id,
1555
+ identifier: issue.identifier,
1556
+ payload: { blocks: completionBlocks, prUrl: parsed.data.prUrl ?? null },
1557
+ });
1558
+ issue.cursor = evt.cursor;
1559
+ unblockDependents(issue, actor);
1560
+ return jsonResponse(publicIssueView(issue));
1561
+ }
1562
+ if (action === "fail") {
1563
+ const parsed = TaskFailSchema.safeParse(bodyJson ?? {});
1564
+ if (!parsed.success) {
1565
+ return errorResponse(400, "validation_error", parsed.error.message);
1566
+ }
1567
+ const authErr = checkClaimMutationAuth(issue, actor, claimTokenHeader, parsed.data.claimToken, parsed.data.claimEpoch);
1568
+ if (authErr)
1569
+ return authErr;
1570
+ const ch = issue.channel ? channels.get(issue.channel) : undefined;
1571
+ const maxAttempts = ch?.queueConfig.maxClaimAttempts ?? 3;
1572
+ const shouldRequeue = Boolean(parsed.data.requeue) && issue.claimAttemptCount < maxAttempts;
1573
+ issue.status = shouldRequeue ? "todo" : "blocked";
1574
+ issue.claimEpoch += 1;
1575
+ issue.claimToken = null;
1576
+ issue.claimHolderAgentId = null;
1577
+ issue.claimHolderUserId = null;
1578
+ issue.claimHolderProfile = null;
1579
+ issue.claimLeaseExpiresAt = null;
1580
+ issue.updatedAt = nowIso();
1581
+ const failEvt = emitEvent("task.failed", actor, {
1582
+ channel: issue.channel,
1583
+ issueId: issue.id,
1584
+ identifier: issue.identifier,
1585
+ payload: { reason: parsed.data.reason, requeued: shouldRequeue },
1586
+ });
1587
+ if (shouldRequeue) {
1588
+ const readyEvt = emitEvent("task.ready", actor, {
1589
+ channel: issue.channel,
1590
+ issueId: issue.id,
1591
+ identifier: issue.identifier,
1592
+ payload: { requeued: true },
1593
+ });
1594
+ issue.cursor = readyEvt.cursor;
1595
+ }
1596
+ else {
1597
+ const blockedEvt = emitEvent("task.blocked", actor, {
1598
+ channel: issue.channel,
1599
+ issueId: issue.id,
1600
+ identifier: issue.identifier,
1601
+ payload: { reason: parsed.data.reason },
1602
+ });
1603
+ issue.cursor = blockedEvt.cursor;
1604
+ }
1605
+ void failEvt;
1606
+ return jsonResponse(publicIssueView(issue));
1607
+ }
1608
+ }
1609
+ // 13. Ask / Confirm / Approve / Reject
1610
+ const interactionMatch = /^\/api\/issues\/([^/]+)\/(ask|confirm|approve|reject)$/.exec(pathname);
1611
+ if (interactionMatch && method === "POST") {
1612
+ const issue = findIssue(decodeURIComponent(interactionMatch[1]));
1613
+ if (!issue) {
1614
+ return errorResponse(404, "issue_not_found", "Issue not found");
1615
+ }
1616
+ const action = interactionMatch[2];
1617
+ const list = interactionsByIssue.get(issue.id) ?? [];
1618
+ if (action === "ask") {
1619
+ const parsed = OneLineAskSchema.safeParse(bodyJson ?? {});
1620
+ if (!parsed.success) {
1621
+ return errorResponse(400, "validation_error", parsed.error.message);
1622
+ }
1623
+ const hadPoolLease = issue.claimToken !== null && issue.assigneeAgentId === null;
1624
+ if (hadPoolLease) {
1625
+ issue.claimEpoch += 1;
1626
+ issue.claimToken = null;
1627
+ issue.claimHolderAgentId = null;
1628
+ issue.claimHolderUserId = null;
1629
+ issue.claimHolderProfile = null;
1630
+ issue.claimLeaseExpiresAt = null;
1631
+ }
1632
+ issue.status = "in_review";
1633
+ issue.updatedAt = nowIso();
1634
+ const interaction = {
1635
+ id: makeUuid(uuidSeq++),
1636
+ issueId: issue.id,
1637
+ identifier: issue.identifier,
1638
+ kind: "ask_user_questions",
1639
+ status: "pending",
1640
+ prompt: parsed.data.question,
1641
+ choices: parsed.data.choices,
1642
+ resolverPolicy: parsed.data.humanOnly ? "human_only" : "anyone",
1643
+ continuationPolicy: parsed.data.continuationPolicy ??
1644
+ (hadPoolLease || issue.assigneeAgentId === null
1645
+ ? "requeue_on_resolve"
1646
+ : "wake_assignee"),
1647
+ cursor: "evt_0",
1648
+ createdAt: nowIso(),
1649
+ resolvedAt: null,
1650
+ };
1651
+ list.push(interaction);
1652
+ interactionsByIssue.set(issue.id, list);
1653
+ const evt = emitEvent("interaction.created", actor, {
1654
+ channel: issue.channel,
1655
+ issueId: issue.id,
1656
+ identifier: issue.identifier,
1657
+ payload: { interactionId: interaction.id, kind: interaction.kind },
1658
+ });
1659
+ interaction.cursor = evt.cursor;
1660
+ issue.cursor = evt.cursor;
1661
+ return jsonResponse(interaction, 201);
1662
+ }
1663
+ if (action === "confirm") {
1664
+ const parsed = OneLineConfirmSchema.safeParse(bodyJson ?? {});
1665
+ if (!parsed.success) {
1666
+ return errorResponse(400, "validation_error", parsed.error.message);
1667
+ }
1668
+ const hadPoolLease = issue.claimToken !== null && issue.assigneeAgentId === null;
1669
+ if (hadPoolLease) {
1670
+ issue.claimEpoch += 1;
1671
+ issue.claimToken = null;
1672
+ issue.claimHolderAgentId = null;
1673
+ issue.claimHolderUserId = null;
1674
+ issue.claimHolderProfile = null;
1675
+ issue.claimLeaseExpiresAt = null;
1676
+ }
1677
+ issue.status = "in_review";
1678
+ issue.updatedAt = nowIso();
1679
+ const interaction = {
1680
+ id: makeUuid(uuidSeq++),
1681
+ issueId: issue.id,
1682
+ identifier: issue.identifier,
1683
+ kind: "request_confirmation",
1684
+ status: "pending",
1685
+ prompt: parsed.data.prompt,
1686
+ resolverPolicy: parsed.data.humanOnly ? "human_only" : "anyone",
1687
+ continuationPolicy: parsed.data.continuationPolicy ??
1688
+ (hadPoolLease || issue.assigneeAgentId === null
1689
+ ? "requeue_on_resolve"
1690
+ : parsed.data.wakeOnAccept
1691
+ ? "wake_assignee_on_accept"
1692
+ : "wake_assignee"),
1693
+ cursor: "evt_0",
1694
+ createdAt: nowIso(),
1695
+ resolvedAt: null,
1696
+ };
1697
+ list.push(interaction);
1698
+ interactionsByIssue.set(issue.id, list);
1699
+ const evt = emitEvent("interaction.created", actor, {
1700
+ channel: issue.channel,
1701
+ issueId: issue.id,
1702
+ identifier: issue.identifier,
1703
+ payload: { interactionId: interaction.id, kind: interaction.kind },
1704
+ });
1705
+ interaction.cursor = evt.cursor;
1706
+ issue.cursor = evt.cursor;
1707
+ return jsonResponse(interaction, 201);
1708
+ }
1709
+ if (action === "approve" || action === "reject") {
1710
+ const body = (bodyJson ?? {});
1711
+ const pending = [...list]
1712
+ .reverse()
1713
+ .find((item) => item.status === "pending" &&
1714
+ (!body.interactionId || item.id === body.interactionId));
1715
+ if (!pending) {
1716
+ return errorResponse(404, "interaction_not_found", "No pending interaction found on this issue");
1717
+ }
1718
+ if (pending.resolverPolicy === "human_only" && actor.agentId !== null) {
1719
+ return errorResponse(403, "human_only_interaction", "Only a human user may resolve this interaction");
1720
+ }
1721
+ pending.status = action === "approve" ? "accepted" : "rejected";
1722
+ pending.note = body.note ?? body.reason ?? null;
1723
+ pending.resolvedAt = nowIso();
1724
+ const resEvt = emitEvent("interaction.resolved", actor, {
1725
+ channel: issue.channel,
1726
+ issueId: issue.id,
1727
+ identifier: issue.identifier,
1728
+ payload: { interactionId: pending.id, status: pending.status },
1729
+ });
1730
+ pending.cursor = resEvt.cursor;
1731
+ issue.cursor = resEvt.cursor;
1732
+ if (pending.continuationPolicy === "requeue_on_resolve" && action === "approve") {
1733
+ issue.status = "todo";
1734
+ const readyEvt = emitEvent("task.ready", actor, {
1735
+ channel: issue.channel,
1736
+ issueId: issue.id,
1737
+ identifier: issue.identifier,
1738
+ payload: { resolvedInteractionId: pending.id },
1739
+ });
1740
+ issue.cursor = readyEvt.cursor;
1741
+ }
1742
+ else if (action === "reject") {
1743
+ issue.status = "blocked";
1744
+ }
1745
+ issue.updatedAt = nowIso();
1746
+ return jsonResponse(pending);
1747
+ }
1748
+ }
1749
+ // 14. Schemas list / get / create
1750
+ const schemasMatch = /^\/api\/companies\/([^/]+)\/schemas(?:\/([^/]+))?$/.exec(pathname);
1751
+ if (schemasMatch) {
1752
+ if (schemasMatch[1] !== companyId) {
1753
+ return errorResponse(404, "company_not_found", "Company not found");
1754
+ }
1755
+ const refParam = schemasMatch[2]
1756
+ ? decodeURIComponent(schemasMatch[2])
1757
+ : undefined;
1758
+ if (method === "GET" && refParam) {
1759
+ const schema = schemasByRef.get(refParam);
1760
+ if (!schema) {
1761
+ return errorResponse(404, "schema_not_found", `Schema "${refParam}" not found`);
1762
+ }
1763
+ return jsonResponse(schema);
1764
+ }
1765
+ if (method === "GET") {
1766
+ return jsonResponse({ items: [...schemasByRef.values()] });
1767
+ }
1768
+ if (method === "POST") {
1769
+ const parsed = createCompanySchemaInputSchema.safeParse(bodyJson);
1770
+ if (!parsed.success) {
1771
+ return errorResponse(400, "validation_error", parsed.error.message);
1772
+ }
1773
+ const { name, version, ref } = parsed.data.ref
1774
+ ? parseSchemaRef(parsed.data.ref)
1775
+ : parseSchemaRef(`${parsed.data.name}@${parsed.data.version}`);
1776
+ const existing = schemasByRef.get(ref);
1777
+ if (existing) {
1778
+ if (canonicalizeJsonSchema(existing.jsonSchema) ===
1779
+ canonicalizeJsonSchema(parsed.data.jsonSchema)) {
1780
+ return jsonResponse({ schema: existing, created: false }, 200);
1781
+ }
1782
+ return errorResponse(409, "schema_immutable", `Schema "${ref}" already exists with a different definition; register ${name}@${version + 1} instead`);
1783
+ }
1784
+ const created = {
1785
+ id: makeUuid(uuidSeq++),
1786
+ companyId,
1787
+ name,
1788
+ version,
1789
+ ref,
1790
+ description: parsed.data.description ?? null,
1791
+ jsonSchema: parsed.data.jsonSchema,
1792
+ builtIn: false,
1793
+ createdAt: nowIso(),
1794
+ };
1795
+ schemasByRef.set(ref, created);
1796
+ return jsonResponse({ schema: created, created: true }, 201);
1797
+ }
1798
+ }
1799
+ // 15. Schedules
1800
+ const schedulesMatch = /^\/api\/companies\/([^/]+)\/schedules(?:\/([^/]+))?$/.exec(pathname);
1801
+ if (schedulesMatch) {
1802
+ if (schedulesMatch[1] !== companyId) {
1803
+ return errorResponse(404, "company_not_found", "Company not found");
1804
+ }
1805
+ const schedId = schedulesMatch[2]
1806
+ ? decodeURIComponent(schedulesMatch[2])
1807
+ : undefined;
1808
+ if (method === "GET") {
1809
+ const target = url.searchParams.get("target");
1810
+ const items = [...schedules.values()].filter((s) => !target || s.target === target);
1811
+ return jsonResponse({ items });
1812
+ }
1813
+ if (method === "POST") {
1814
+ const parsed = SchedulePostSchema.safeParse(bodyJson);
1815
+ if (!parsed.success) {
1816
+ return errorResponse(400, "validation_error", parsed.error.message);
1817
+ }
1818
+ const delayMs = parsed.data.in !== undefined
1819
+ ? parseDurationMs(parsed.data.in)
1820
+ : parsed.data.every !== undefined
1821
+ ? parseDurationMs(parsed.data.every)
1822
+ : 0;
1823
+ const nextRunAt = parsed.data.at
1824
+ ? new Date(parsed.data.at).toISOString()
1825
+ : new Date(currentNowMs + delayMs).toISOString();
1826
+ const intervalMs = parsed.data.every !== undefined
1827
+ ? parseDurationMs(parsed.data.every)
1828
+ : null;
1829
+ const created = {
1830
+ id: makeUuid(uuidSeq++),
1831
+ companyId,
1832
+ target: parsed.data.target,
1833
+ message: parsed.data.message,
1834
+ nextRunAt,
1835
+ intervalMs,
1836
+ untilAt: parsed.data.until ?? null,
1837
+ post: Boolean(parsed.data.post),
1838
+ status: "scheduled",
1839
+ createdAt: nowIso(),
1840
+ };
1841
+ schedules.set(created.id, created);
1842
+ return jsonResponse(created, 201);
1843
+ }
1844
+ if (method === "DELETE" && schedId) {
1845
+ const existing = schedules.get(schedId);
1846
+ if (!existing) {
1847
+ return errorResponse(404, "schedule_not_found", "Schedule not found");
1848
+ }
1849
+ existing.status = "cancelled";
1850
+ return jsonResponse({ cancelled: true });
1851
+ }
1852
+ }
1853
+ // 16. Event Wait (long-poll with cursor replay)
1854
+ const waitMatch = /^\/api\/companies\/([^/]+)\/events\/wait$/.exec(pathname);
1855
+ if (waitMatch && method === "GET") {
1856
+ if (waitMatch[1] !== companyId) {
1857
+ return errorResponse(404, "company_not_found", "Company not found");
1858
+ }
1859
+ const afterRaw = url.searchParams.get("after");
1860
+ const afterSeq = afterRaw ? parseEventCursor(afterRaw) ?? 0 : eventSeq;
1861
+ const timeoutMs = Number.parseInt(url.searchParams.get("timeoutMs") ?? "30000", 10);
1862
+ for (const evt of events) {
1863
+ if (evt.seq > afterSeq && matchesEventFilters(evt, url.searchParams)) {
1864
+ return jsonResponse(evt, 200);
1865
+ }
1866
+ }
1867
+ if (timeoutMs <= 0) {
1868
+ return jsonResponse(null, 204);
1869
+ }
1870
+ return new Promise((resolve) => {
1871
+ let settled = false;
1872
+ const cleanup = () => {
1873
+ listeners.delete(onEvent);
1874
+ clearTimeout(timer);
1875
+ init?.signal?.removeEventListener("abort", onAbort);
1876
+ };
1877
+ const onAbort = () => {
1878
+ if (settled)
1879
+ return;
1880
+ settled = true;
1881
+ cleanup();
1882
+ resolve(jsonResponse(null, 204));
1883
+ };
1884
+ const onEvent = (evt) => {
1885
+ if (settled)
1886
+ return;
1887
+ if (evt.seq > afterSeq && matchesEventFilters(evt, url.searchParams)) {
1888
+ settled = true;
1889
+ cleanup();
1890
+ resolve(jsonResponse(evt, 200));
1891
+ }
1892
+ };
1893
+ const timer = setTimeout(() => {
1894
+ if (settled)
1895
+ return;
1896
+ settled = true;
1897
+ cleanup();
1898
+ resolve(jsonResponse(null, 204));
1899
+ }, timeoutMs);
1900
+ if (init?.signal?.aborted) {
1901
+ onAbort();
1902
+ return;
1903
+ }
1904
+ init?.signal?.addEventListener("abort", onAbort, { once: true });
1905
+ listeners.add(onEvent);
1906
+ });
1907
+ }
1908
+ // 17. Event Stream (SSE)
1909
+ const streamMatch = /^\/api\/companies\/([^/]+)\/events\/stream$/.exec(pathname);
1910
+ if (streamMatch && method === "GET") {
1911
+ if (streamMatch[1] !== companyId) {
1912
+ return errorResponse(404, "company_not_found", "Company not found");
1913
+ }
1914
+ const afterRaw = url.searchParams.get("after");
1915
+ const afterSeq = afterRaw ? parseEventCursor(afterRaw) ?? 0 : eventSeq;
1916
+ const encoder = new TextEncoder();
1917
+ let listenerRef = null;
1918
+ const stream = new ReadableStream({
1919
+ start(controller) {
1920
+ const pushEvent = (evt) => {
1921
+ const chunk = `id: ${evt.cursor}\nevent: ${evt.type}\ndata: ${JSON.stringify(evt)}\n\n`;
1922
+ controller.enqueue(encoder.encode(chunk));
1923
+ };
1924
+ for (const evt of events) {
1925
+ if (evt.seq > afterSeq && matchesEventFilters(evt, url.searchParams)) {
1926
+ pushEvent(evt);
1927
+ }
1928
+ }
1929
+ listenerRef = (evt) => {
1930
+ if (evt.seq > afterSeq && matchesEventFilters(evt, url.searchParams)) {
1931
+ pushEvent(evt);
1932
+ }
1933
+ };
1934
+ listeners.add(listenerRef);
1935
+ if (init?.signal) {
1936
+ const onAbort = () => {
1937
+ if (listenerRef) {
1938
+ listeners.delete(listenerRef);
1939
+ listenerRef = null;
1940
+ }
1941
+ try {
1942
+ controller.close();
1943
+ }
1944
+ catch {
1945
+ // already closed
1946
+ }
1947
+ };
1948
+ if (init.signal.aborted) {
1949
+ onAbort();
1950
+ }
1951
+ else {
1952
+ init.signal.addEventListener("abort", onAbort, { once: true });
1953
+ }
1954
+ }
1955
+ },
1956
+ cancel() {
1957
+ if (listenerRef) {
1958
+ listeners.delete(listenerRef);
1959
+ listenerRef = null;
1960
+ }
1961
+ },
1962
+ });
1963
+ return new Response(stream, {
1964
+ status: 200,
1965
+ headers: {
1966
+ "content-type": "text/event-stream",
1967
+ "cache-control": "no-cache",
1968
+ },
1969
+ });
1970
+ }
1971
+ return errorResponse(404, "not_found", `No in-memory handler for ${method} ${pathname}`);
1972
+ };
1973
+ return {
1974
+ fetch: fetchHandler,
1975
+ companyId,
1976
+ companyPrefix,
1977
+ advanceTime(ms) {
1978
+ currentNowMs += ms;
1979
+ expireLeases();
1980
+ return currentNowMs;
1981
+ },
1982
+ nowMs() {
1983
+ return currentNowMs;
1984
+ },
1985
+ expireLeases,
1986
+ setPolicy(policy) {
1987
+ agentIdentityPolicy = policy;
1988
+ },
1989
+ seedAgent(input) {
1990
+ const stored = {
1991
+ id: input.id ?? makeUuid(uuidSeq++),
1992
+ name: input.name,
1993
+ role: input.role ?? "general",
1994
+ apiKey: input.apiKey,
1995
+ };
1996
+ agents.set(stored.id, stored);
1997
+ return stored;
1998
+ },
1999
+ seedBoardToken(input) {
2000
+ boardTokens.set(input.token, input);
2001
+ },
2002
+ seedProject(input) {
2003
+ const stored = {
2004
+ id: input.id ?? makeUuid(uuidSeq++),
2005
+ slug: input.slug,
2006
+ name: input.name ?? input.slug,
2007
+ };
2008
+ projects.set(stored.id, stored);
2009
+ return stored;
2010
+ },
2011
+ getState() {
2012
+ return {
2013
+ channels: [...channels.values()].map(({ members: _m, ...c }) => ({ ...c })),
2014
+ issues: [...issues.values()].map(publicIssueView),
2015
+ events: [...events],
2016
+ };
2017
+ },
2018
+ };
2019
+ }
2020
+ //# sourceMappingURL=memory-backend.js.map