@primitive.ai/prim 0.1.0-alpha.1 → 0.1.0-alpha.100

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 (47) hide show
  1. package/README.md +413 -37
  2. package/SKILL.md +272 -0
  3. package/dist/chunk-2IRLFOEL.js +766 -0
  4. package/dist/chunk-2Q3OGSTV.js +164 -0
  5. package/dist/chunk-4GLVJLEQ.js +55 -0
  6. package/dist/chunk-5HFTJEA6.js +168 -0
  7. package/dist/chunk-5LRKJTLA.js +155 -0
  8. package/dist/chunk-6C3CCVDI.js +264 -0
  9. package/dist/chunk-7VIMU2HR.js +209 -0
  10. package/dist/chunk-C4D2LMTS.js +511 -0
  11. package/dist/chunk-EZXEWFDG.js +210 -0
  12. package/dist/chunk-GSBHBU7N.js +18982 -0
  13. package/dist/chunk-H6JAQVW4.js +258 -0
  14. package/dist/chunk-IDMLJ4TM.js +36 -0
  15. package/dist/chunk-JJI7FU24.js +439 -0
  16. package/dist/chunk-K4JWJ6OM.js +1496 -0
  17. package/dist/chunk-KGBMU76T.js +175 -0
  18. package/dist/chunk-MXVCP33E.js +847 -0
  19. package/dist/chunk-MZEVEPL3.js +262 -0
  20. package/dist/chunk-O2WV5SQZ.js +1876 -0
  21. package/dist/chunk-OYHYCK4K.js +13 -0
  22. package/dist/chunk-QIHXTYRD.js +135 -0
  23. package/dist/chunk-XG7S3LIL.js +1372 -0
  24. package/dist/daemon/server.js +22644 -0
  25. package/dist/hook-runtime/daemon/server.js +22644 -0
  26. package/dist/hook-runtime/hooks/post-commit.js +20133 -0
  27. package/dist/hook-runtime/hooks/post-rewrite.js +20032 -0
  28. package/dist/hook-runtime/hooks/post-tool-use.js +27307 -0
  29. package/dist/hook-runtime/hooks/pre-commit.js +1657 -0
  30. package/dist/hook-runtime/hooks/pre-tool-use.js +26714 -0
  31. package/dist/hook-runtime/hooks/prim-hook.js +27367 -0
  32. package/dist/hook-runtime/hooks/session-end.js +1176 -0
  33. package/dist/hook-runtime/hooks/session-start.js +30167 -0
  34. package/dist/hook-runtime/index.js +53486 -0
  35. package/dist/hook-runtime/statusline-main.js +886 -0
  36. package/dist/hooks/post-commit.js +196 -0
  37. package/dist/hooks/post-rewrite.js +205 -0
  38. package/dist/hooks/post-tool-use.js +285 -0
  39. package/dist/hooks/pre-commit.js +21 -74
  40. package/dist/hooks/pre-tool-use.js +387 -0
  41. package/dist/hooks/prim-hook.js +235 -0
  42. package/dist/hooks/session-end.js +64 -0
  43. package/dist/hooks/session-start.js +309 -0
  44. package/dist/index.js +9721 -423
  45. package/dist/statusline-main.js +886 -0
  46. package/package.json +46 -23
  47. package/dist/chunk-3APLWTLB.js +0 -165
@@ -0,0 +1,264 @@
1
+ import {
2
+ cursorHooksPath,
3
+ hasExactCursorHandler,
4
+ readCursorHooks
5
+ } from "./chunk-K4JWJ6OM.js";
6
+ import {
7
+ resolveRepositoryContext
8
+ } from "./chunk-XG7S3LIL.js";
9
+
10
+ // src/hooks/agent.ts
11
+ function parseAgent(argv) {
12
+ const i = argv.indexOf("--agent");
13
+ const value = i !== -1 ? argv[i + 1] : void 0;
14
+ if (value === "codex" || value === "cursor" || value === "hermes") {
15
+ return value;
16
+ }
17
+ return "claude_code";
18
+ }
19
+
20
+ // src/hooks/cursor-coexistence.ts
21
+ var CURSOR_EVENTS = /* @__PURE__ */ new Set([
22
+ "sessionStart",
23
+ "beforeSubmitPrompt",
24
+ "preToolUse",
25
+ "postToolUse",
26
+ "postToolUseFailure",
27
+ "afterAgentResponse",
28
+ "subagentStop",
29
+ "stop",
30
+ "sessionEnd"
31
+ ]);
32
+ function cursorEvidence(parsed) {
33
+ return typeof parsed.cursor_version === "string" && parsed.cursor_version.length > 0 && typeof parsed.conversation_id === "string" && parsed.conversation_id.length > 0 && typeof parsed.generation_id === "string" && parsed.generation_id.length > 0 && Array.isArray(parsed.workspace_roots) && typeof parsed.hook_event_name === "string" && CURSOR_EVENTS.has(parsed.hook_event_name);
34
+ }
35
+ function uniqueProjectRoot(parsed) {
36
+ if (!Array.isArray(parsed.workspace_roots)) return;
37
+ const roots = new Set(
38
+ parsed.workspace_roots.filter((value) => typeof value === "string" && value.length > 0).map((value) => resolveRepositoryContext(value)?.repoRoot).filter((value) => !!value)
39
+ );
40
+ return roots.size === 1 ? [...roots][0] : void 0;
41
+ }
42
+ function shouldSuppressImportedCursorHandler(parsed, bin) {
43
+ if (!cursorEvidence(parsed)) return false;
44
+ const project = uniqueProjectRoot(parsed);
45
+ if (project) {
46
+ try {
47
+ if (hasExactCursorHandler(
48
+ readCursorHooks(cursorHooksPath("project", project)),
49
+ parsed.hook_event_name,
50
+ bin,
51
+ "project"
52
+ )) {
53
+ return true;
54
+ }
55
+ } catch {
56
+ }
57
+ }
58
+ try {
59
+ return hasExactCursorHandler(
60
+ readCursorHooks(cursorHooksPath("user")),
61
+ parsed.hook_event_name,
62
+ bin,
63
+ "user"
64
+ );
65
+ } catch {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ // src/hooks/hook-stdin.ts
71
+ var DEFAULT_MAX_BYTES = 1024 * 1024;
72
+ function readHookStdin(timeoutMs = 1e3, maxBytes = DEFAULT_MAX_BYTES) {
73
+ return new Promise((resolve2, reject) => {
74
+ const chunks = [];
75
+ let bytes = 0;
76
+ let settled = false;
77
+ const finish = (error) => {
78
+ if (settled) return;
79
+ settled = true;
80
+ clearTimeout(timer);
81
+ process.stdin.removeAllListeners("data");
82
+ process.stdin.removeAllListeners("end");
83
+ process.stdin.removeAllListeners("error");
84
+ if (error) reject(error);
85
+ else resolve2(Buffer.concat(chunks, bytes).toString("utf-8"));
86
+ };
87
+ const timer = setTimeout(() => finish(new Error("stdin read timeout")), timeoutMs);
88
+ process.stdin.on("data", (chunk) => {
89
+ bytes += chunk.length;
90
+ if (bytes > maxBytes) {
91
+ finish(new Error("stdin envelope exceeds size limit"));
92
+ return;
93
+ }
94
+ chunks.push(chunk);
95
+ });
96
+ process.stdin.on("end", () => finish());
97
+ process.stdin.on("error", (error) => finish(error));
98
+ });
99
+ }
100
+
101
+ // src/hooks/normalize.ts
102
+ import { createHash } from "crypto";
103
+ import { realpathSync } from "fs";
104
+ import { isAbsolute, resolve } from "path";
105
+ var HERMES_EVENT_MAP = {
106
+ on_session_start: "SessionStart",
107
+ on_session_end: "SessionEnd",
108
+ pre_llm_call: "UserPromptSubmit",
109
+ post_llm_call: "Stop",
110
+ pre_tool_call: "PreToolUse",
111
+ post_tool_call: "PostToolUse",
112
+ subagent_stop: "SubagentStop"
113
+ };
114
+ var CURSOR_EVENT_MAP = {
115
+ sessionStart: "SessionStart",
116
+ beforeSubmitPrompt: "UserPromptSubmit",
117
+ preToolUse: "PreToolUse",
118
+ postToolUse: "PostToolUse",
119
+ postToolUseFailure: "PostToolUseFailure",
120
+ afterAgentResponse: "AssistantResponse",
121
+ subagentStop: "SubagentStop",
122
+ stop: "Stop",
123
+ sessionEnd: "SessionEnd"
124
+ };
125
+ var CURSOR_TOOL_EVENTS = /* @__PURE__ */ new Set(["PreToolUse", "PostToolUse", "PostToolUseFailure"]);
126
+ var SAFE_CORRELATION_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/u;
127
+ var CURSOR_LOCAL_ONLY_FIELDS = /* @__PURE__ */ new Set([
128
+ "conversation_id",
129
+ "generation_id",
130
+ "user_email",
131
+ "account_email",
132
+ "transcript_path",
133
+ "transcript",
134
+ "thought",
135
+ "thoughts",
136
+ "thinking",
137
+ "tool_output"
138
+ ]);
139
+ function requiredId(value, field) {
140
+ if (typeof value !== "string" || value.length === 0) {
141
+ throw new TypeError(`Cursor hook envelope is missing ${field}`);
142
+ }
143
+ return value;
144
+ }
145
+ function cursorToolUseId(value) {
146
+ if (SAFE_CORRELATION_ID_RE.test(value)) return value;
147
+ return `cursor:tool:v1:${createHash("sha256").update(value).digest("hex")}`;
148
+ }
149
+ function workspaceCandidates(value) {
150
+ if (!Array.isArray(value)) return [];
151
+ const roots = value.filter((item) => typeof item === "string" && item.length > 0);
152
+ if (roots.some((root) => !isAbsolute(root))) {
153
+ throw new TypeError("Cursor workspace roots must be absolute");
154
+ }
155
+ return roots;
156
+ }
157
+ function pathIdentity(path) {
158
+ try {
159
+ return realpathSync.native(path);
160
+ } catch {
161
+ return resolve(path);
162
+ }
163
+ }
164
+ function resolveCursorCwd(parsed) {
165
+ const roots = workspaceCandidates(parsed.workspace_roots).map(pathIdentity);
166
+ const rootRepositories = roots.map((root) => resolveRepositoryContext(root)?.repoRoot);
167
+ const repositoryRoots = new Set(rootRepositories.filter((root) => !!root));
168
+ if (repositoryRoots.size > 1) {
169
+ throw new TypeError("Cursor hook envelope spans multiple repositories");
170
+ }
171
+ if (roots.length > 1 && rootRepositories.some((root) => root === void 0)) {
172
+ throw new TypeError("Cursor hook envelope has ambiguous workspace roots");
173
+ }
174
+ const expectedRepo = [...repositoryRoots][0];
175
+ const rawCwd = typeof parsed.cwd === "string" && parsed.cwd.length > 0 ? parsed.cwd : void 0;
176
+ if (rawCwd && !isAbsolute(rawCwd)) {
177
+ throw new TypeError("Cursor hook cwd must be absolute");
178
+ }
179
+ const envelopeCwd = rawCwd ? pathIdentity(rawCwd) : void 0;
180
+ const input = typeof parsed.tool_input === "object" && parsed.tool_input !== null && !Array.isArray(parsed.tool_input) ? parsed.tool_input : void 0;
181
+ const rawToolCwd = parsed.tool_name === "Shell" && typeof input?.working_directory === "string" ? input.working_directory : void 0;
182
+ const base = envelopeCwd ?? (roots.length === 1 ? roots[0] : expectedRepo);
183
+ if (rawToolCwd && !isAbsolute(rawToolCwd) && !base) {
184
+ throw new TypeError("relative Cursor tool cwd has no workspace base");
185
+ }
186
+ const toolCwd = rawToolCwd ? pathIdentity(isAbsolute(rawToolCwd) ? rawToolCwd : resolve(base, rawToolCwd)) : void 0;
187
+ const selected = toolCwd ?? envelopeCwd ?? (roots.length === 1 ? roots[0] : expectedRepo);
188
+ if (!selected) {
189
+ throw new TypeError("Cursor hook envelope has no unambiguous workspace");
190
+ }
191
+ const selectedRepo = resolveRepositoryContext(selected)?.repoRoot;
192
+ if (expectedRepo && selectedRepo !== expectedRepo) {
193
+ throw new TypeError("Cursor hook cwd conflicts with workspace repository");
194
+ }
195
+ return selected;
196
+ }
197
+ function normalizeCursorEnvelope(parsed) {
198
+ const rawEvent = requiredId(parsed.hook_event_name, "hook_event_name");
199
+ const event = CURSOR_EVENT_MAP[rawEvent];
200
+ if (!event) throw new TypeError(`unsupported Cursor hook event: ${rawEvent}`);
201
+ const sessionId = requiredId(parsed.conversation_id, "conversation_id");
202
+ const turnId = requiredId(parsed.generation_id, "generation_id");
203
+ if (parsed.session_id !== void 0 && parsed.session_id !== sessionId) {
204
+ throw new TypeError("Cursor conversation_id conflicts with session_id");
205
+ }
206
+ if (parsed.turn_id !== void 0 && parsed.turn_id !== turnId) {
207
+ throw new TypeError("Cursor generation_id conflicts with turn_id");
208
+ }
209
+ const rawToolUseId = CURSOR_TOOL_EVENTS.has(event) ? requiredId(parsed.tool_use_id, "tool_use_id") : void 0;
210
+ const normalized = {
211
+ ...Object.fromEntries(
212
+ Object.entries(parsed).filter(([key]) => !CURSOR_LOCAL_ONLY_FIELDS.has(key))
213
+ ),
214
+ hook_event_name: event,
215
+ session_id: sessionId,
216
+ turn_id: turnId,
217
+ cwd: resolveCursorCwd(parsed),
218
+ ...rawToolUseId === void 0 ? {} : { tool_use_id: cursorToolUseId(rawToolUseId) }
219
+ };
220
+ if (typeof parsed.tool_output === "string") {
221
+ try {
222
+ normalized.tool_response = JSON.parse(parsed.tool_output);
223
+ } catch {
224
+ normalized.tool_response = parsed.tool_output;
225
+ }
226
+ }
227
+ return normalized;
228
+ }
229
+ function normalizeEnvelope(parsed, agent) {
230
+ if (agent === "cursor") {
231
+ return normalizeCursorEnvelope(parsed);
232
+ }
233
+ if (agent === "codex") {
234
+ const event = parsed.hook_event_name;
235
+ if ((event === "PreToolUse" || event === "PostToolUse") && (typeof parsed.tool_use_id !== "string" || parsed.tool_use_id.length === 0)) {
236
+ const stableToolIdentity = JSON.stringify([
237
+ parsed.session_id ?? null,
238
+ parsed.turn_id ?? null,
239
+ parsed.tool_name ?? null,
240
+ parsed.tool_input ?? null
241
+ ]);
242
+ return {
243
+ ...parsed,
244
+ tool_use_id: `codex:fallback:v1:${createHash("sha256").update(stableToolIdentity).digest("hex")}`
245
+ };
246
+ }
247
+ return parsed;
248
+ }
249
+ if (agent !== "hermes") {
250
+ return parsed;
251
+ }
252
+ const raw = parsed.hook_event_name;
253
+ if (typeof raw === "string" && raw in HERMES_EVENT_MAP) {
254
+ return { ...parsed, hook_event_name: HERMES_EVENT_MAP[raw] };
255
+ }
256
+ return parsed;
257
+ }
258
+
259
+ export {
260
+ parseAgent,
261
+ shouldSuppressImportedCursorHandler,
262
+ readHookStdin,
263
+ normalizeEnvelope
264
+ };
@@ -0,0 +1,209 @@
1
+ import {
2
+ getClient,
3
+ isTerminalSafeText,
4
+ terminalSafeLine,
5
+ terminalSafeText
6
+ } from "./chunk-2IRLFOEL.js";
7
+
8
+ // src/decisions/feedback.ts
9
+ var FEEDBACK_PROTOCOL_VERSION = 2;
10
+ var FEEDBACK_MIN_PROTOCOL_VERSION = 1;
11
+ var FEEDBACK_DEADLINE_MS = 3e3;
12
+ var MAX_FEEDBACK_EVENTS = 40;
13
+ var MAX_FEEDBACK_MESSAGE_CODE_POINTS = 8e3;
14
+ var MAX_FEEDBACK_INTENT_CODE_POINTS = 180;
15
+ var LEASE_PATH = "/api/cli/decisions/feedback/lease";
16
+ var ACK_PATH = "/api/cli/decisions/feedback/ack";
17
+ var STATUS_PATH = "/api/cli/decisions/feedback/status";
18
+ var SHORT_ID = /^[0-9a-f]{8}$/u;
19
+ var MAX_EVENT_ID_CHARS = 128;
20
+ var MAX_RAW_INTENT_CODE_UNITS = 512;
21
+ var MAX_FEEDBACK_WEB_URL_CHARS = 2048;
22
+ var SAFE_PUBLISH_DECISION_ID = /^[A-Za-z0-9_-]+$/u;
23
+ function isRecord(value) {
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
25
+ }
26
+ function isSupportedProtocolVersion(value) {
27
+ return Number.isSafeInteger(value) && Number(value) >= FEEDBACK_MIN_PROTOCOL_VERSION && Number(value) <= FEEDBACK_PROTOCOL_VERSION;
28
+ }
29
+ function normalizeFeedbackIntent(value) {
30
+ const withoutControls = terminalSafeLine(value);
31
+ const points = Array.from(withoutControls);
32
+ if (points.length <= MAX_FEEDBACK_INTENT_CODE_POINTS) {
33
+ return withoutControls;
34
+ }
35
+ return `${points.slice(0, MAX_FEEDBACK_INTENT_CODE_POINTS - 1).join("")}\u2026`;
36
+ }
37
+ function parseFeedbackWebUrl(value) {
38
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_FEEDBACK_WEB_URL_CHARS || !/^https:\/\//iu.test(value) || /\s/u.test(value) || !isTerminalSafeText(value)) {
39
+ return void 0;
40
+ }
41
+ try {
42
+ const url = new URL(value);
43
+ if (url.protocol !== "https:" || !url.hostname || url.username.length > 0 || url.password.length > 0) {
44
+ return void 0;
45
+ }
46
+ } catch {
47
+ return void 0;
48
+ }
49
+ return value;
50
+ }
51
+ function parseFeedbackDecisionId(value) {
52
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_EVENT_ID_CHARS || terminalSafeText(value) !== value || !SAFE_PUBLISH_DECISION_ID.test(value)) {
53
+ return void 0;
54
+ }
55
+ return value;
56
+ }
57
+ function parseEvent(value, protocolVersion) {
58
+ if (!isRecord(value)) return void 0;
59
+ if (typeof value.eventId !== "string" || value.eventId.length === 0 || value.eventId.length > MAX_EVENT_ID_CHARS || terminalSafeText(value.eventId) !== value.eventId) {
60
+ return void 0;
61
+ }
62
+ if (!Number.isSafeInteger(value.leaseVersion) || Number(value.leaseVersion) < 1) {
63
+ return void 0;
64
+ }
65
+ if (typeof value.shortId !== "string" || !SHORT_ID.test(value.shortId)) {
66
+ return void 0;
67
+ }
68
+ if (typeof value.intent !== "string" || value.intent.length > MAX_RAW_INTENT_CODE_UNITS) {
69
+ return void 0;
70
+ }
71
+ const intent = normalizeFeedbackIntent(value.intent);
72
+ if (!intent) return void 0;
73
+ const webUrl = value.webUrl === void 0 ? void 0 : parseFeedbackWebUrl(value.webUrl);
74
+ if (value.webUrl !== void 0 && webUrl === void 0) return void 0;
75
+ const kind = value.kind === void 0 && protocolVersion === 1 ? "confirm_prompt" : value.kind;
76
+ if (kind !== "confirm_prompt" && kind !== "publish_prompt") return void 0;
77
+ if (protocolVersion === 1 && kind === "publish_prompt") return void 0;
78
+ const decisionId = value.decisionId === void 0 ? void 0 : parseFeedbackDecisionId(value.decisionId);
79
+ if (value.decisionId !== void 0 && decisionId === void 0) return void 0;
80
+ if (decisionId !== void 0 && (protocolVersion !== 2 || kind !== "publish_prompt")) {
81
+ return void 0;
82
+ }
83
+ if (protocolVersion === 2 && kind === "publish_prompt" && decisionId === void 0) {
84
+ return void 0;
85
+ }
86
+ return {
87
+ eventId: value.eventId,
88
+ leaseVersion: Number(value.leaseVersion),
89
+ shortId: value.shortId,
90
+ intent,
91
+ ...webUrl === void 0 ? {} : { webUrl },
92
+ ...decisionId === void 0 ? {} : { decisionId },
93
+ kind
94
+ };
95
+ }
96
+ function parseFeedbackLease(value) {
97
+ if (!isRecord(value) || !isSupportedProtocolVersion(value.protocolVersion)) return void 0;
98
+ const protocolVersion = value.protocolVersion;
99
+ if (value.status === "empty") {
100
+ return value.hasMore === false ? { protocolVersion, events: [], hasMore: false } : void 0;
101
+ }
102
+ if (value.status === "unavailable") {
103
+ return value.reason === "organization_unbound" ? { protocolVersion, events: [], hasMore: false } : void 0;
104
+ }
105
+ if (value.status !== "leased" || typeof value.hasMore !== "boolean") return void 0;
106
+ if (!Array.isArray(value.events) || value.events.length === 0 || value.events.length > MAX_FEEDBACK_EVENTS) {
107
+ return void 0;
108
+ }
109
+ const events = value.events.map((event) => parseEvent(event, protocolVersion));
110
+ if (events.some((event) => event === void 0)) return void 0;
111
+ const parsedEvents = events;
112
+ if (new Set(parsedEvents.map((event) => event.eventId)).size !== parsedEvents.length) {
113
+ return void 0;
114
+ }
115
+ return { protocolVersion, events: parsedEvents, hasMore: value.hasMore };
116
+ }
117
+ function renderFeedback(lease) {
118
+ const lines = [];
119
+ const deliveries = [];
120
+ let pointCount = 0;
121
+ for (const event of lease.events) {
122
+ const decisionId = event.kind === "publish_prompt" ? parseFeedbackDecisionId(event.decisionId) : void 0;
123
+ if (event.kind === "publish_prompt" && decisionId === void 0) continue;
124
+ const identifier = `dec_${event.shortId}`;
125
+ const detail = `${event.intent}${event.webUrl ? ` (${event.webUrl})` : ""}`;
126
+ const line = event.kind === "publish_prompt" ? `[prim] publish this Decision draft (${identifier})? ${detail} Run \`prim decisions publish ${decisionId}\` to share it with your team.` : `[prim] response \u2192 created Decision (${identifier}): ${detail}`;
127
+ const extra = Array.from(line).length + (lines.length === 0 ? 0 : 1);
128
+ if (pointCount + extra > MAX_FEEDBACK_MESSAGE_CODE_POINTS) break;
129
+ lines.push(line);
130
+ deliveries.push({ eventId: event.eventId, leaseVersion: event.leaseVersion });
131
+ pointCount += extra;
132
+ }
133
+ if (lines.length === 0) return void 0;
134
+ return { protocolVersion: lease.protocolVersion, systemMessage: lines.join("\n"), deliveries };
135
+ }
136
+ async function leaseDecisionFeedback(input, dependencies = {}) {
137
+ try {
138
+ const response = await (dependencies.client ?? getClient()).post(
139
+ LEASE_PATH,
140
+ {
141
+ protocolVersion: FEEDBACK_PROTOCOL_VERSION,
142
+ workspaceId: input.workspaceId,
143
+ currentSessionId: input.currentSessionId
144
+ },
145
+ { signal: input.signal, quietRefresh: true }
146
+ );
147
+ const parsed = parseFeedbackLease(response);
148
+ if (!parsed) {
149
+ dependencies.onError?.(
150
+ new Error("server returned an unsupported decision-feedback contract")
151
+ );
152
+ }
153
+ return parsed;
154
+ } catch (error) {
155
+ dependencies.onError?.(error);
156
+ return void 0;
157
+ }
158
+ }
159
+ async function acknowledgeDecisionFeedback(input, dependencies = {}) {
160
+ if (!isSupportedProtocolVersion(input.protocolVersion) || input.deliveries.length === 0 || input.deliveries.length > MAX_FEEDBACK_EVENTS) {
161
+ return false;
162
+ }
163
+ try {
164
+ const response = await (dependencies.client ?? getClient()).post(
165
+ ACK_PATH,
166
+ {
167
+ protocolVersion: input.protocolVersion,
168
+ workspaceId: input.workspaceId,
169
+ deliveries: input.deliveries
170
+ },
171
+ { signal: input.signal, quietRefresh: true }
172
+ );
173
+ const acknowledgedEventIds = isRecord(response) ? response.acknowledgedEventIds : void 0;
174
+ const expectedEventIds = new Set(input.deliveries.map((delivery) => delivery.eventId));
175
+ const valid = isRecord(response) && response.protocolVersion === input.protocolVersion && response.status === "acked" && Array.isArray(acknowledgedEventIds) && acknowledgedEventIds.length <= input.deliveries.length && acknowledgedEventIds.every(
176
+ (id) => typeof id === "string" && id.length > 0 && id.length <= MAX_EVENT_ID_CHARS && expectedEventIds.has(id)
177
+ ) && new Set(acknowledgedEventIds).size === acknowledgedEventIds.length;
178
+ if (!valid) {
179
+ dependencies.onError?.(
180
+ new Error("server returned an unsupported decision-feedback acknowledgement")
181
+ );
182
+ }
183
+ return valid;
184
+ } catch (error) {
185
+ dependencies.onError?.(error);
186
+ return false;
187
+ }
188
+ }
189
+ function parseFeedbackCapability(value) {
190
+ if (!isRecord(value) || !isSupportedProtocolVersion(value.protocolVersion)) return void 0;
191
+ if (value.status === "available") return { status: "available" };
192
+ if (value.status === "unavailable" && value.reason === "organization_unbound") {
193
+ return { status: "unavailable", reason: "organization_unbound" };
194
+ }
195
+ return void 0;
196
+ }
197
+ async function fetchFeedbackCapability(signal, client = getClient()) {
198
+ const result = parseFeedbackCapability(await client.get(STATUS_PATH, { signal }));
199
+ if (!result) throw new Error("server returned an unsupported decision-feedback contract");
200
+ return result;
201
+ }
202
+
203
+ export {
204
+ FEEDBACK_DEADLINE_MS,
205
+ renderFeedback,
206
+ leaseDecisionFeedback,
207
+ acknowledgeDecisionFeedback,
208
+ fetchFeedbackCapability
209
+ };