@granular-software/sdk 0.4.81 → 0.4.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -22,8 +22,16 @@ function _interopNamespace(e) {
22
22
 
23
23
  var Automerge__namespace = /*#__PURE__*/_interopNamespace(Automerge);
24
24
 
25
+ var __create = Object.create;
25
26
  var __defProp = Object.defineProperty;
27
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
26
28
  var __getOwnPropNames = Object.getOwnPropertyNames;
29
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
30
+ var __typeError = (msg) => {
31
+ throw TypeError(msg);
32
+ };
33
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
34
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
27
35
  var __esm = (fn, res) => function __init() {
28
36
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
29
37
  };
@@ -31,6 +39,306 @@ var __export = (target, all) => {
31
39
  for (var name in all)
32
40
  __defProp(target, name, { get: all[name], enumerable: true });
33
41
  };
42
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
43
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
44
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
45
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
46
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
47
+ var __runInitializers = (array, flags, self, value) => {
48
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
49
+ return value;
50
+ };
51
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
52
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
53
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
54
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
55
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
56
+ return __privateGet(this, extra);
57
+ }, set [name](x) {
58
+ return __privateSet(this, extra, x);
59
+ } }, name));
60
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
61
+ for (var i = decorators.length - 1; i >= 0; i--) {
62
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
63
+ if (k) {
64
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
65
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
66
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
67
+ }
68
+ it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
69
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
70
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
71
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
72
+ }
73
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
74
+ };
75
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
76
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
77
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
78
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
79
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
80
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
81
+
82
+ // ../fractory/dist/annotations.js
83
+ function publish(event, adapter) {
84
+ try {
85
+ adapter?.emit(event);
86
+ } catch {
87
+ }
88
+ for (const listener of listeners) {
89
+ try {
90
+ listener(event);
91
+ } catch {
92
+ }
93
+ }
94
+ }
95
+ function identity(value) {
96
+ if (!value.trim())
97
+ throw new Error("Fractal identity must not be empty");
98
+ return value;
99
+ }
100
+ function Block(id3, options = {}) {
101
+ const definition = typeof id3 === "string" ? { ...options, id: identity(id3) } : { ...id3, id: identity(id3.id) };
102
+ return (target, _context) => {
103
+ blocks.set(target, definition);
104
+ return target;
105
+ };
106
+ }
107
+ function makeInterface(owner, name, options) {
108
+ return Object.freeze({
109
+ [interfaceBrand]: true,
110
+ name,
111
+ options: Object.freeze({ ...options }),
112
+ get blockId() {
113
+ const definition = blocks.get(owner());
114
+ if (!definition)
115
+ throw new Error(`Interface ${name} needs an annotated block`);
116
+ return definition.id;
117
+ },
118
+ get id() {
119
+ return options.id || `${this.blockId}::${name}`;
120
+ }
121
+ });
122
+ }
123
+ function Interface(options = {}, details = {}) {
124
+ if (typeof options === "string") {
125
+ const id3 = identity(options), name = id3.split("/").slice(-1)[0];
126
+ if (details.parent)
127
+ return makeInterface(details.parent, name, { ...details, id: id3 });
128
+ return Object.freeze({
129
+ [interfaceBrand]: true,
130
+ id: id3,
131
+ name,
132
+ blockId: id3.includes("/") ? id3.slice(0, id3.lastIndexOf("/")) : "factory",
133
+ options: Object.freeze({ ...details, id: id3 })
134
+ });
135
+ }
136
+ if ("parent" in options)
137
+ return makeInterface(options.parent, identity(options.id).split("/").slice(-1)[0], options);
138
+ return interfaceDecorator(options);
139
+ }
140
+ function interfaceDecorator(options) {
141
+ function decorate(target, context) {
142
+ if (typeof context === "object") {
143
+ if (!context.static || context.private)
144
+ throw new Error("@Interface requires a public static field");
145
+ context.addInitializer(function() {
146
+ const owner = this;
147
+ if (!owner[context.name]?.[interfaceBrand])
148
+ Object.defineProperty(owner, context.name, {
149
+ value: makeInterface(() => owner, String(context.name), options),
150
+ writable: false,
151
+ configurable: true
152
+ });
153
+ });
154
+ return function() {
155
+ return makeInterface(() => this, String(context.name), options);
156
+ };
157
+ }
158
+ const value = makeInterface(() => target, String(context), options);
159
+ Object.defineProperty(target, context, {
160
+ value,
161
+ writable: false,
162
+ configurable: true
163
+ });
164
+ return void 0;
165
+ }
166
+ return decorate;
167
+ }
168
+ function validate(parser, value) {
169
+ const result = parser?.parse(value);
170
+ if (result && typeof result.then === "function") {
171
+ void Promise.resolve(result).catch(() => {
172
+ });
173
+ throw new Error("Fractal runtime validators must be synchronous");
174
+ }
175
+ }
176
+ function wrap(fn, name, reference, process2, options = {}) {
177
+ const previous = wrappers.get(fn);
178
+ if (previous) {
179
+ fn = previous.original;
180
+ reference ||= previous.reference;
181
+ process2 ||= previous.process;
182
+ options = { ...previous.options, ...options };
183
+ }
184
+ const wrapped = function(...args) {
185
+ const api = reference?.();
186
+ if (reference && (!api || api[interfaceBrand] !== true))
187
+ throw new Error("@Method requires an initialized typed interface reference");
188
+ const adapter = host;
189
+ if (!listeners.size && !options.contract && !api?.options.auth)
190
+ return fn.apply(this, args);
191
+ const id3 = crypto.randomUUID();
192
+ const frame = {
193
+ targetId: process2?.id || `${api.id}#${options.name || name || fn.name || "call"}`,
194
+ traceId: id3,
195
+ runId: id3
196
+ };
197
+ let codeRevision;
198
+ try {
199
+ codeRevision = adapter?.codeRevision?.();
200
+ } catch {
201
+ }
202
+ const started = performance.now();
203
+ let terminal = false;
204
+ const base = {
205
+ targetId: frame.targetId,
206
+ ...{},
207
+ id: id3,
208
+ traceId: frame.traceId,
209
+ ...codeRevision ? { codeRevision } : {},
210
+ runId: frame.runId,
211
+ ...{},
212
+ ...{},
213
+ blockId: process2?.id || api.blockId,
214
+ ...api ? { interfaceId: api.id } : {},
215
+ method: options.name || name || fn.name || "call"
216
+ };
217
+ const emit = (status, failure) => {
218
+ if (status !== "started") {
219
+ if (terminal)
220
+ return;
221
+ terminal = true;
222
+ frame.finished = true;
223
+ }
224
+ publish({
225
+ ...base,
226
+ timestamp: Date.now(),
227
+ status,
228
+ ...status !== "started" ? { durationMs: performance.now() - started } : {},
229
+ ...failure ? { failure } : {}
230
+ }, adapter);
231
+ };
232
+ const execute = () => {
233
+ emit("started");
234
+ let phase = "auth";
235
+ const failed = (error) => {
236
+ emit("failed", phase);
237
+ throw error;
238
+ };
239
+ const invoke = () => {
240
+ phase = "input";
241
+ validate(options.contract?.args, args);
242
+ phase = "execution";
243
+ const value = fn.apply(this, args);
244
+ const complete = (result) => {
245
+ phase = "output";
246
+ validate(options.contract?.result, result);
247
+ emit("completed");
248
+ return result;
249
+ };
250
+ if (value && typeof value.then === "function") {
251
+ if (options.contract?.result)
252
+ return Promise.resolve(value).then(complete).catch(failed);
253
+ void Promise.resolve(value).then(() => emit("completed"), () => emit("failed", "execution"));
254
+ return value;
255
+ }
256
+ return complete(value);
257
+ };
258
+ try {
259
+ const authorized = api?.options.auth?.({
260
+ receiver: this,
261
+ args,
262
+ context: adapter?.context?.()
263
+ });
264
+ if (authorized && typeof authorized === "object" && typeof authorized.then === "function") {
265
+ if (fn.constructor.name !== "AsyncFunction") {
266
+ void authorized.catch(() => {
267
+ });
268
+ throw new Error("Async auth requires an async method");
269
+ }
270
+ return authorized.then((allowed) => {
271
+ if (allowed === false)
272
+ throw new FactoryViolation("auth", false);
273
+ return invoke();
274
+ }).catch(failed);
275
+ }
276
+ if (authorized === false)
277
+ throw new FactoryViolation("auth", false);
278
+ return invoke();
279
+ } catch (error) {
280
+ return failed(error);
281
+ }
282
+ };
283
+ const run = () => execute();
284
+ try {
285
+ return run();
286
+ } catch (error) {
287
+ if (fn.constructor.name === "AsyncFunction")
288
+ return Promise.reject(error);
289
+ throw error;
290
+ }
291
+ };
292
+ Object.defineProperty(wrapped, "name", {
293
+ value: options.name || name || fn.name,
294
+ configurable: true
295
+ });
296
+ Object.defineProperty(wrapped, "length", {
297
+ value: fn.length,
298
+ configurable: true
299
+ });
300
+ if (process2)
301
+ blocks.set(wrapped, process2);
302
+ wrappers.set(wrapped, { original: fn, reference, process: process2, options });
303
+ return wrapped;
304
+ }
305
+ function callableDecorator(reference, process2, options = {}) {
306
+ function decorate(target, context, descriptor) {
307
+ if (descriptor) {
308
+ descriptor.value = wrap(descriptor.value, String(context), reference, process2, options);
309
+ return descriptor;
310
+ }
311
+ const fn = target;
312
+ return wrap(fn, typeof context === "object" ? String(context.name) : fn.name, reference, process2, options);
313
+ }
314
+ return decorate;
315
+ }
316
+ function Method(reference, options = {}) {
317
+ return callableDecorator(reference, void 0, options);
318
+ }
319
+ function Process(id3, options = {}) {
320
+ const definition = typeof id3 === "string" ? { ...options, id: identity(id3) } : { ...id3, id: identity(id3.id) };
321
+ return callableDecorator(void 0, definition);
322
+ }
323
+ var interfaceBrand, blocks, wrappers, listeners, host, FactoryViolation;
324
+ var init_annotations = __esm({
325
+ "../fractory/dist/annotations.js"() {
326
+ interfaceBrand = Symbol("fractal.interface");
327
+ blocks = /* @__PURE__ */ new WeakMap();
328
+ wrappers = /* @__PURE__ */ new WeakMap();
329
+ listeners = /* @__PURE__ */ new Set();
330
+ FactoryViolation = class extends Error {
331
+ phase;
332
+ cause;
333
+ constructor(phase, cause) {
334
+ super(`Fractal ${phase} requirement failed`);
335
+ this.phase = phase;
336
+ this.cause = cause;
337
+ this.name = "FactoryViolation";
338
+ }
339
+ };
340
+ }
341
+ });
34
342
 
35
343
  // ../policy-engine/src/index.ts
36
344
  var src_exports = {};
@@ -720,138 +1028,6 @@ function normalizeSourceProfiles(sources) {
720
1028
  );
721
1029
  return [...getBuiltinPermissionProfiles(), ...nonBuiltin];
722
1030
  }
723
- async function compilePolicyBundle(input) {
724
- const errors = [];
725
- const warnings = [];
726
- const effects = [...input.effects].sort(
727
- (left, right) => left.effectKey.localeCompare(right.effectKey)
728
- );
729
- const profiles = flattenProfiles(
730
- normalizeSourceProfiles(input.profileSources),
731
- errors
732
- );
733
- const manifestRules = {};
734
- for (const effect of effects) {
735
- try {
736
- const rules = manifestPolicyRulesForEffect(effect, input.manifestId);
737
- if (rules.length > 0) manifestRules[effect.effectKey] = rules;
738
- } catch (error) {
739
- errors.push(String(error instanceof Error ? error.message : error));
740
- }
741
- }
742
- const compiledProfiles = {};
743
- for (const profile of profiles) {
744
- try {
745
- const defaultActionPolicy = profile.defaults?.actionPolicy;
746
- if (defaultActionPolicy !== void 0 && !normalizeDecision(defaultActionPolicy)) {
747
- throw new Error(
748
- `Permission profile "${profile.name}" has invalid defaults.actionPolicy`
749
- );
750
- }
751
- const compiled = compileProfile({
752
- profile,
753
- effects,
754
- manifestRules,
755
- warnings
756
- });
757
- compiled.digest = await digestJson({
758
- profile: compiled.flattened,
759
- actionRules: compiled.actionRules,
760
- defaultActionPolicy: compiled.defaultActionPolicy
761
- });
762
- compiledProfiles[profile.name] = compiled;
763
- } catch (error) {
764
- errors.push(String(error instanceof Error ? error.message : error));
765
- }
766
- }
767
- const permissionProfilesDigest = await digestJson(
768
- Object.values(compiledProfiles).map((profile) => ({
769
- name: profile.name,
770
- digest: profile.digest,
771
- source: profile.source
772
- }))
773
- );
774
- const bundleWithoutDigest = {
775
- schemaVersion: 1,
776
- buildId: input.buildId,
777
- sandboxId: input.sandboxId,
778
- manifestDigest: input.manifestDigest,
779
- permissionProfilesDigest,
780
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
781
- effects: effects.map((effect) => ({
782
- effectKey: effect.effectKey,
783
- name: effect.name,
784
- attachedClass: normalizeAttachedClass(effect.attachedClass),
785
- isStatic: effect.isStatic === true
786
- })),
787
- manifestRules,
788
- profiles: compiledProfiles
789
- };
790
- const bundleDigest = await digestJson(bundleWithoutDigest);
791
- return {
792
- bundle: { ...bundleWithoutDigest, bundleDigest },
793
- errors,
794
- warnings
795
- };
796
- }
797
- function evaluateCompiledPolicyBundle(input) {
798
- const profile = input.bundle.profiles[input.profileName];
799
- if (!profile) {
800
- return {
801
- outcome: "deny",
802
- matches: [
803
- {
804
- id: "missing-profile",
805
- outcome: "deny",
806
- origin: {
807
- kind: "permissionProfile",
808
- profileName: input.profileName,
809
- source: "permissionProfile"
810
- },
811
- reason: `Permission profile "${input.profileName}" does not exist in this version`,
812
- summary: `Permission profile "${input.profileName}" does not exist in this version`
813
- }
814
- ]
815
- };
816
- }
817
- if (!profile.actionVisibility.includes(input.effectKey)) {
818
- return {
819
- outcome: "deny",
820
- matches: [
821
- {
822
- id: "action-not-visible",
823
- outcome: "deny",
824
- origin: {
825
- kind: "permissionProfile",
826
- profileName: input.profileName,
827
- source: profile.source
828
- },
829
- reason: `Action ${input.effectKey} is not visible for ${input.profileName}`,
830
- summary: `Action ${input.effectKey} is not visible for ${input.profileName}`
831
- }
832
- ]
833
- };
834
- }
835
- const decision = evaluatePolicies({
836
- manifestRules: input.bundle.manifestRules[input.effectKey] || [],
837
- profileRules: profile.actionRules[input.effectKey] || [],
838
- defaultActionPolicy: profile.defaultActionPolicy,
839
- context: input.context
840
- });
841
- return {
842
- outcome: decision.outcome,
843
- matches: decision.matches.map(
844
- (match) => match.id === `profile-default-${decision.outcome}` ? {
845
- ...match,
846
- origin: {
847
- kind: "permissionProfile",
848
- profileName: profile.name,
849
- source: profile.source
850
- }
851
- } : match
852
- )
853
- };
854
- }
855
1031
  function extractManifestEffects(manifest) {
856
1032
  const effects = [];
857
1033
  for (const volume of manifest.volumes || []) {
@@ -875,11 +1051,156 @@ function extractManifestEffects(manifest) {
875
1051
  function listVisibleActionsForProfile(bundle, profileName) {
876
1052
  return [...bundle.profiles[profileName]?.actionVisibility || []];
877
1053
  }
878
- var DECISIONS, BUILTIN_PROFILE_NAMES;
1054
+ var DECISIONS, BUILTIN_PROFILE_NAMES, compilePolicyBundle, evaluateCompiledPolicyBundle;
879
1055
  var init_src = __esm({
880
1056
  "../policy-engine/src/index.ts"() {
1057
+ init_annotations();
881
1058
  DECISIONS = /* @__PURE__ */ new Set(["allow", "confirm", "deny"]);
882
1059
  BUILTIN_PROFILE_NAMES = ["allow-all", "confirm-all", "deny-all"];
1060
+ compilePolicyBundle = Process({
1061
+ description: "Compile product permission rules into a bundle that runtime checks can evaluate.",
1062
+ id: "granular-product/compilation/metamodels-policy-compilation/compile",
1063
+ label: "Compile policy bundle",
1064
+ benchmarks: ["./compile.bench.ts"],
1065
+ tests: ["./index.test.ts"]
1066
+ })(async function compilePolicyBundle2(input) {
1067
+ const errors = [];
1068
+ const warnings = [];
1069
+ const effects = [...input.effects].sort(
1070
+ (left, right) => left.effectKey.localeCompare(right.effectKey)
1071
+ );
1072
+ const profiles = flattenProfiles(
1073
+ normalizeSourceProfiles(input.profileSources),
1074
+ errors
1075
+ );
1076
+ const manifestRules = {};
1077
+ for (const effect of effects) {
1078
+ try {
1079
+ const rules = manifestPolicyRulesForEffect(effect, input.manifestId);
1080
+ if (rules.length > 0) manifestRules[effect.effectKey] = rules;
1081
+ } catch (error) {
1082
+ errors.push(String(error instanceof Error ? error.message : error));
1083
+ }
1084
+ }
1085
+ const compiledProfiles = {};
1086
+ for (const profile of profiles) {
1087
+ try {
1088
+ const defaultActionPolicy = profile.defaults?.actionPolicy;
1089
+ if (defaultActionPolicy !== void 0 && !normalizeDecision(defaultActionPolicy)) {
1090
+ throw new Error(
1091
+ `Permission profile "${profile.name}" has invalid defaults.actionPolicy`
1092
+ );
1093
+ }
1094
+ const compiled = compileProfile({
1095
+ profile,
1096
+ effects,
1097
+ manifestRules,
1098
+ warnings
1099
+ });
1100
+ compiled.digest = await digestJson({
1101
+ profile: compiled.flattened,
1102
+ actionRules: compiled.actionRules,
1103
+ defaultActionPolicy: compiled.defaultActionPolicy
1104
+ });
1105
+ compiledProfiles[profile.name] = compiled;
1106
+ } catch (error) {
1107
+ errors.push(String(error instanceof Error ? error.message : error));
1108
+ }
1109
+ }
1110
+ const permissionProfilesDigest = await digestJson(
1111
+ Object.values(compiledProfiles).map((profile) => ({
1112
+ name: profile.name,
1113
+ digest: profile.digest,
1114
+ source: profile.source
1115
+ }))
1116
+ );
1117
+ const bundleWithoutDigest = {
1118
+ schemaVersion: 1,
1119
+ buildId: input.buildId,
1120
+ sandboxId: input.sandboxId,
1121
+ manifestDigest: input.manifestDigest,
1122
+ permissionProfilesDigest,
1123
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
1124
+ effects: effects.map((effect) => ({
1125
+ effectKey: effect.effectKey,
1126
+ name: effect.name,
1127
+ attachedClass: normalizeAttachedClass(effect.attachedClass),
1128
+ isStatic: effect.isStatic === true
1129
+ })),
1130
+ manifestRules,
1131
+ profiles: compiledProfiles
1132
+ };
1133
+ const bundleDigest = await digestJson(bundleWithoutDigest);
1134
+ return {
1135
+ bundle: { ...bundleWithoutDigest, bundleDigest },
1136
+ errors,
1137
+ warnings
1138
+ };
1139
+ });
1140
+ evaluateCompiledPolicyBundle = Process({
1141
+ description: "Evaluate compiled permission rules for an action and its current context.",
1142
+ id: "granular-product/effects/authorization-contracts/compiled-evaluation",
1143
+ label: "Evaluate compiled policies",
1144
+ benchmarks: ["./evaluation.bench.ts"],
1145
+ tests: ["./index.test.ts"]
1146
+ })(function evaluateCompiledPolicyBundle2(input) {
1147
+ const profile = input.bundle.profiles[input.profileName];
1148
+ if (!profile) {
1149
+ return {
1150
+ outcome: "deny",
1151
+ matches: [
1152
+ {
1153
+ id: "missing-profile",
1154
+ outcome: "deny",
1155
+ origin: {
1156
+ kind: "permissionProfile",
1157
+ profileName: input.profileName,
1158
+ source: "permissionProfile"
1159
+ },
1160
+ reason: `Permission profile "${input.profileName}" does not exist in this version`,
1161
+ summary: `Permission profile "${input.profileName}" does not exist in this version`
1162
+ }
1163
+ ]
1164
+ };
1165
+ }
1166
+ if (!profile.actionVisibility.includes(input.effectKey)) {
1167
+ return {
1168
+ outcome: "deny",
1169
+ matches: [
1170
+ {
1171
+ id: "action-not-visible",
1172
+ outcome: "deny",
1173
+ origin: {
1174
+ kind: "permissionProfile",
1175
+ profileName: input.profileName,
1176
+ source: profile.source
1177
+ },
1178
+ reason: `Action ${input.effectKey} is not visible for ${input.profileName}`,
1179
+ summary: `Action ${input.effectKey} is not visible for ${input.profileName}`
1180
+ }
1181
+ ]
1182
+ };
1183
+ }
1184
+ const decision = evaluatePolicies({
1185
+ manifestRules: input.bundle.manifestRules[input.effectKey] || [],
1186
+ profileRules: profile.actionRules[input.effectKey] || [],
1187
+ defaultActionPolicy: profile.defaultActionPolicy,
1188
+ context: input.context
1189
+ });
1190
+ return {
1191
+ outcome: decision.outcome,
1192
+ matches: decision.matches.map(
1193
+ (match) => match.id === `profile-default-${decision.outcome}` ? {
1194
+ ...match,
1195
+ origin: {
1196
+ kind: "permissionProfile",
1197
+ profileName: profile.name,
1198
+ source: profile.source
1199
+ }
1200
+ } : match
1201
+ )
1202
+ };
1203
+ });
883
1204
  }
884
1205
  });
885
1206
 
@@ -9162,7 +9483,7 @@ function requireTransientFeedbackItem(value) {
9162
9483
  }
9163
9484
  return item;
9164
9485
  }
9165
- function createFeedPublisher(publish) {
9486
+ function createFeedPublisher(publish2) {
9166
9487
  const makeHandle = (initial) => {
9167
9488
  let current = initial;
9168
9489
  let mutationQueue = Promise.resolve();
@@ -9188,7 +9509,7 @@ function createFeedPublisher(publish) {
9188
9509
  const reservedOperationId = options.operationId || operationId("feed_transient_update");
9189
9510
  const reservedOptions = { ...options };
9190
9511
  return enqueueMutation(async () => {
9191
- const response = await publish("feed.transient.update", {
9512
+ const response = await publish2("feed.transient.update", {
9192
9513
  transientId: current.id,
9193
9514
  expectedRevision: current.revision,
9194
9515
  text: text6,
@@ -9203,7 +9524,7 @@ function createFeedPublisher(publish) {
9203
9524
  const reservedOperationId = options.operationId || operationId("feed_transient_settle");
9204
9525
  const reservedOptions = { ...options };
9205
9526
  return enqueueMutation(async () => {
9206
- const response = await publish("feed.transient.settle", {
9527
+ const response = await publish2("feed.transient.settle", {
9207
9528
  transientId: current.id,
9208
9529
  expectedRevision: current.revision,
9209
9530
  ...text6 === void 0 ? {} : { text: text6 },
@@ -9226,7 +9547,7 @@ function createFeedPublisher(publish) {
9226
9547
  return {
9227
9548
  async feedback(text6, options = {}) {
9228
9549
  return requireFeedbackItem(
9229
- await publish("feed.feedback", {
9550
+ await publish2("feed.feedback", {
9230
9551
  text: text6,
9231
9552
  ...options,
9232
9553
  operationId: options.operationId || operationId("feed_feedback")
@@ -9235,7 +9556,7 @@ function createFeedPublisher(publish) {
9235
9556
  },
9236
9557
  async transientFeedback(text6, options = {}) {
9237
9558
  const item = requireTransientFeedbackItem(
9238
- await publish("feed.transient.create", {
9559
+ await publish2("feed.transient.create", {
9239
9560
  text: text6,
9240
9561
  ...options,
9241
9562
  operationId: options.operationId || operationId("feed_transient_create")
@@ -12570,11 +12891,11 @@ var Session = class {
12570
12891
  }
12571
12892
  this.eventListeners.get("effects:changed").push(handler);
12572
12893
  return () => {
12573
- const listeners = this.eventListeners.get("effects:changed");
12574
- if (listeners) {
12894
+ const listeners2 = this.eventListeners.get("effects:changed");
12895
+ if (listeners2) {
12575
12896
  this.eventListeners.set(
12576
12897
  "effects:changed",
12577
- listeners.filter((h) => h !== handler)
12898
+ listeners2.filter((h) => h !== handler)
12578
12899
  );
12579
12900
  }
12580
12901
  };
@@ -12589,11 +12910,11 @@ var Session = class {
12589
12910
  }
12590
12911
  this.eventListeners.get("tools:changed").push(handler);
12591
12912
  return () => {
12592
- const listeners = this.eventListeners.get("tools:changed");
12593
- if (listeners) {
12913
+ const listeners2 = this.eventListeners.get("tools:changed");
12914
+ if (listeners2) {
12594
12915
  this.eventListeners.set(
12595
12916
  "tools:changed",
12596
- listeners.filter((h) => h !== handler)
12917
+ listeners2.filter((h) => h !== handler)
12597
12918
  );
12598
12919
  }
12599
12920
  };
@@ -15017,6 +15338,7 @@ var WSClient = class {
15017
15338
  };
15018
15339
 
15019
15340
  // src/client.ts
15341
+ init_annotations();
15020
15342
  var DEFAULT_CONVERSATION_SESSION_LIST_LIMIT = 100;
15021
15343
  var MAX_CONVERSATION_SESSION_LIST_LIMIT = 500;
15022
15344
  function requireUserEnvironmentSequence(value, field) {
@@ -15158,7 +15480,11 @@ function isUnsupportedEffectCatalogMutation(error) {
15158
15480
  const message = error instanceof Error ? error.message : String(error);
15159
15481
  return message.includes("Unknown RPC method: effects.resetCatalog") || message.includes("Unknown RPC method: effects.addCatalog") || message.includes("Method not found: effects.resetCatalog") || message.includes("Method not found: effects.addCatalog");
15160
15482
  }
15161
- function planRecordObjectsChunks(records, batchSize) {
15483
+ var planRecordObjectsChunks = Process({
15484
+ id: "granular-product/authoring/importers-record-apis/record-objects/plan",
15485
+ label: "Plan record chunks",
15486
+ parent: () => Environment.prototype.recordObjects
15487
+ })(function planRecordObjectsChunks2(records, batchSize) {
15162
15488
  const total = records.length;
15163
15489
  const size = Math.max(1, Math.min(batchSize, total));
15164
15490
  const chunkCount = Math.ceil(total / size);
@@ -15168,7 +15494,7 @@ function planRecordObjectsChunks(records, batchSize) {
15168
15494
  plans.push({ chunkIndex, chunkCount, offset, slice });
15169
15495
  }
15170
15496
  return plans;
15171
- }
15497
+ });
15172
15498
  function preserveRecordObjectRealId(record4) {
15173
15499
  const realId = record4.id.trim();
15174
15500
  if (!realId) {
@@ -15393,15 +15719,54 @@ function isGraphQLMutationDocument(query) {
15393
15719
  }
15394
15720
  return false;
15395
15721
  }
15396
- var Environment = class _Environment {
15397
- granular;
15398
- envData;
15399
- _apiKey;
15400
- _apiEndpoint;
15401
- _tokenProvider;
15402
- _beforeMutationSend;
15403
- _graphqlIdempotencyKey;
15722
+ var _cancelRecordImport_dec, _getRecordImport_dec, _listRecordImports_dec, _enqueueRecordImport_dec, _executeRecordObjectsChunk_dec, _recordObjects_dec, _recordObject_dec, _listRelated_dec, _detach_dec, _attach_dec, _getRelationships_dec, _defineRelationship_dec, _searchRecords_dec, _graphql_dec, _closeSession_dec, _connectSession_dec, _createSession_dec, _getUserEnvironmentState_dec, _listSessions_dec, _recordState_dec, _records_dec, _imports_dec, _relationships_dec, _sessions_dec, _stateChanges_dec, _queries_dec, _Environment_decorators, _init;
15723
+ _Environment_decorators = [Block({
15724
+ description: "Expose records, imports, queries, relationships and sessions for one product environment.",
15725
+ id: "granular-product/authoring/importers-record-apis",
15726
+ label: "Environment client",
15727
+ exposedBy: [() => Granular],
15728
+ tests: [
15729
+ "./record-objects.cancellation.test.ts",
15730
+ "./environment.feed.test.ts"
15731
+ ],
15732
+ parent: () => Granular
15733
+ })], _queries_dec = [Interface({
15734
+ label: "Queries & search",
15735
+ description: "Query the environment\u2019s graph or search its records."
15736
+ })], _stateChanges_dec = [Interface({
15737
+ label: "User state",
15738
+ description: "Record changes to user state and read the environment\u2019s current state."
15739
+ })], _sessions_dec = [Interface({
15740
+ label: "Sessions",
15741
+ description: "Create, connect, list and close conversations in this environment."
15742
+ })], _relationships_dec = [Interface({
15743
+ label: "Relationships",
15744
+ description: "Define, read, attach and detach relationships between records."
15745
+ })], _imports_dec = [Interface({
15746
+ id: "granular-product/ingestion/importer-lifecycle",
15747
+ label: "Background imports",
15748
+ description: "Submit a background record import and inspect or cancel its progress."
15749
+ })], _records_dec = [Interface({
15750
+ label: "Records",
15751
+ description: "Write customer records into the environment, including bounded batch requests."
15752
+ })], _recordState_dec = [Method(() => _Environment.stateChanges)], _listSessions_dec = [Method(() => _Environment.sessions, { description: "List conversations using the supplied environment, product and user filters." })], _getUserEnvironmentState_dec = [Method(() => _Environment.stateChanges, { description: "Read the user's environment projection and selected session scope." })], _createSession_dec = [Method(() => _Environment.sessions, { description: "Activate the requested environment and create a scoped conversation connection." })], _connectSession_dec = [Method(() => _Environment.sessions, { description: "Mint scoped connection credentials and open the existing conversation." })], _closeSession_dec = [Method(() => _Environment.sessions, { description: "Close an active conversation connection or request closure through the session API." })], _graphql_dec = [Method(() => _Environment.queries)], _searchRecords_dec = [Method(() => _Environment.queries, { description: "Search records through the current environment connection." })], _defineRelationship_dec = [Method(() => _Environment.relationships)], _getRelationships_dec = [Method(() => _Environment.relationships)], _attach_dec = [Method(() => _Environment.relationships)], _detach_dec = [Method(() => _Environment.relationships)], _listRelated_dec = [Method(() => _Environment.relationships)], _recordObject_dec = [Method(() => _Environment.records)], _recordObjects_dec = [Process({
15753
+ id: "granular-product/authoring/importers-record-apis/record-objects",
15754
+ label: "Write record batches"
15755
+ }), Method(() => _Environment.records)], _executeRecordObjectsChunk_dec = [Process({
15756
+ id: "granular-product/authoring/importers-record-apis/record-objects/write-chunk",
15757
+ label: "Write chunk with retry",
15758
+ parent: () => _Environment.prototype.recordObjects
15759
+ })], _enqueueRecordImport_dec = [Method(() => _Environment.imports)], _listRecordImports_dec = [Method(() => _Environment.imports)], _getRecordImport_dec = [Method(() => _Environment.imports)], _cancelRecordImport_dec = [Method(() => _Environment.imports)];
15760
+ var _Environment = class _Environment {
15404
15761
  constructor(granular, envData, apiKey, apiEndpoint, tokenProvider, beforeMutationSend, graphqlIdempotencyKey) {
15762
+ __runInitializers(_init, 5, this);
15763
+ __publicField(this, "granular");
15764
+ __publicField(this, "envData");
15765
+ __publicField(this, "_apiKey");
15766
+ __publicField(this, "_apiEndpoint");
15767
+ __publicField(this, "_tokenProvider");
15768
+ __publicField(this, "_beforeMutationSend");
15769
+ __publicField(this, "_graphqlIdempotencyKey");
15405
15770
  this.granular = granular;
15406
15771
  this.envData = envData;
15407
15772
  this._apiKey = apiKey;
@@ -15651,10 +16016,6 @@ var Environment = class _Environment {
15651
16016
  }
15652
16017
  );
15653
16018
  }
15654
- /**
15655
- * Mirror product-owned workflow state into Granular without making Granular
15656
- * own the customer application's state machine.
15657
- */
15658
16019
  async recordState(input) {
15659
16020
  const { machine, state, ...target } = input;
15660
16021
  if (!machine.trim()) {
@@ -15926,30 +16287,6 @@ var Environment = class _Environment {
15926
16287
  const prefix = `${className}_`;
15927
16288
  return graphPath.startsWith(prefix) ? graphPath.substring(prefix.length) : graphPath;
15928
16289
  }
15929
- /**
15930
- * Execute a GraphQL query against the environment's graph.
15931
- *
15932
- * The query uses the Granular graph query language (based on Cypher/GraphQL).
15933
- * Authentication is handled automatically using the SDK's API key.
15934
- *
15935
- * @param query - The GraphQL query string
15936
- * @param variables - Optional variables for the query
15937
- * @returns The query result data
15938
- *
15939
- * @example
15940
- * ```typescript
15941
- * // Read the workspace
15942
- * const result = await env.graphql(
15943
- * `query { model(path: "workspace") { path label submodels { path label } } }`
15944
- * );
15945
- * console.log(result.data);
15946
- *
15947
- * // Create a model
15948
- * const created = await env.graphql(
15949
- * `mutation { at(path: "workspace") { create_submodel(subpath: "my_node", label: "My Node", prototype: "Model") { model { path label } } } }`
15950
- * );
15951
- * ```
15952
- */
15953
16290
  async graphql(query, variables, options) {
15954
16291
  const authToken = await this.resolveAuthToken();
15955
16292
  if (this._beforeMutationSend && isGraphQLMutationDocument(query)) {
@@ -16042,27 +16379,6 @@ var Environment = class _Environment {
16042
16379
  rank: rankRecordSearchResult(result, normalizedQuery, index)
16043
16380
  })).sort((left, right) => left.rank - right.rank).map((item) => item.result).slice(0, limit);
16044
16381
  }
16045
- // ==================== RELATIONSHIP METHODS ====================
16046
- /**
16047
- * Define a relationship between two model types.
16048
- *
16049
- * Creates both submodels (if they don't exist) and links them with
16050
- * a RelationshipDef node that encodes cardinality.
16051
- *
16052
- * @example
16053
- * ```typescript
16054
- * // Author has many Books, Book has one Author
16055
- * const rel = await env.defineRelationship({
16056
- * model: 'author',
16057
- * localSubmodel: 'books',
16058
- * localIsMany: true,
16059
- * foreignModel: 'book',
16060
- * foreignSubmodel: 'author',
16061
- * foreignIsMany: false,
16062
- * });
16063
- * console.log(rel.relationship_kind); // "one_to_many"
16064
- * ```
16065
- */
16066
16382
  async defineRelationship(options) {
16067
16383
  const result = await this.graphql(
16068
16384
  `mutation DefineRelationship(
@@ -16108,20 +16424,6 @@ var Environment = class _Environment {
16108
16424
  }
16109
16425
  return result.data.at.define_relationship;
16110
16426
  }
16111
- /**
16112
- * Get all relationships for a model type.
16113
- *
16114
- * @param modelPath - The model type path (e.g., "author")
16115
- * @returns Array of relationships from this model's perspective
16116
- *
16117
- * @example
16118
- * ```typescript
16119
- * const rels = await env.getRelationships('author');
16120
- * for (const rel of rels) {
16121
- * console.log(`${rel.local_submodel.path} -> ${rel.foreign_model.path} (${rel.relationship_kind})`);
16122
- * }
16123
- * ```
16124
- */
16125
16427
  async getRelationships(modelPath) {
16126
16428
  const result = await this.graphql(
16127
16429
  `query GetRelationships($path: String) {
@@ -16146,27 +16448,6 @@ var Environment = class _Environment {
16146
16448
  }
16147
16449
  return result.data?.model?.relationships || [];
16148
16450
  }
16149
- /**
16150
- * Attach a target model to a relationship submodel.
16151
- *
16152
- * Handles cardinality automatically:
16153
- * - "One" side: sets/replaces the reference
16154
- * - "Many" side: adds the target to the collection
16155
- *
16156
- * If the target model doesn't exist, it's created as an instance of the foreign type.
16157
- * Bidirectional sync is automatic.
16158
- *
16159
- * @param modelPath - The model instance path (e.g., "tolkien")
16160
- * @param submodelPath - The relationship submodel (e.g., "books")
16161
- * @param targetPath - The target model to attach (e.g., "lord_of_the_rings")
16162
- *
16163
- * @example
16164
- * ```typescript
16165
- * // Attach a book to an author (many side)
16166
- * await env.attach('tolkien', 'books', 'lord_of_the_rings');
16167
- * // This also automatically sets lord_of_the_rings:author -> tolkien
16168
- * ```
16169
- */
16170
16451
  async attach(modelPath, submodelPath, targetPath) {
16171
16452
  const result = await this.graphql(
16172
16453
  `mutation Attach($target: String!) {
@@ -16186,24 +16467,6 @@ var Environment = class _Environment {
16186
16467
  );
16187
16468
  }
16188
16469
  }
16189
- /**
16190
- * Detach a target model from a relationship submodel.
16191
- *
16192
- * Handles bidirectional cleanup automatically.
16193
- *
16194
- * @param modelPath - The model instance path
16195
- * @param submodelPath - The relationship submodel
16196
- * @param targetPath - The target to detach (optional for "one" side; omit on "many" side to detach all)
16197
- *
16198
- * @example
16199
- * ```typescript
16200
- * // Detach a specific book
16201
- * await env.detach('tolkien', 'books', 'lord_of_the_rings');
16202
- *
16203
- * // Detach all books
16204
- * await env.detach('tolkien', 'books');
16205
- * ```
16206
- */
16207
16470
  async detach(modelPath, submodelPath, targetPath) {
16208
16471
  const targetArg = targetPath ? `target: "${targetPath}"` : "";
16209
16472
  const result = await this.graphql(
@@ -16223,19 +16486,6 @@ var Environment = class _Environment {
16223
16486
  );
16224
16487
  }
16225
16488
  }
16226
- /**
16227
- * List all related models through a relationship submodel.
16228
- *
16229
- * @param modelPath - The model instance path
16230
- * @param submodelPath - The relationship submodel
16231
- * @returns Array of related model references
16232
- *
16233
- * @example
16234
- * ```typescript
16235
- * const books = await env.listRelated('tolkien', 'books');
16236
- * console.log(books); // [{ path: "lord_of_the_rings", label: "Lord of the Rings" }, ...]
16237
- * ```
16238
- */
16239
16489
  async listRelated(modelPath, submodelPath) {
16240
16490
  const result = await this.graphql(
16241
16491
  `mutation ListRelated {
@@ -16657,38 +16907,6 @@ var Environment = class _Environment {
16657
16907
  }
16658
16908
  }
16659
16909
  }
16660
- // ==================== RECORD OBJECT ====================
16661
- /**
16662
- * Create or update an instance of a class in the graph.
16663
- *
16664
- * Uses `instantiate` under the hood, which has find-or-create semantics:
16665
- * if an instance with the given `id` already exists for the class it is
16666
- * returned; otherwise a new instance is created. Fields are then set
16667
- * (overwriting previous values) and relationships are attached.
16668
- *
16669
- * The graph path is derived as `{className}_{id}` to ensure uniqueness
16670
- * across classes (two objects of different classes may share the same
16671
- * real-world ID). Relationship targets are also resolved automatically
16672
- * using the foreign class from the relationship definition.
16673
- *
16674
- * @param options - The object specification
16675
- * @returns The graph path, real-world ID, and creation status
16676
- *
16677
- * @example
16678
- * ```typescript
16679
- * // Create an author with fields
16680
- * const result = await env.recordObject({
16681
- * className: 'author',
16682
- * id: 'tolkien',
16683
- * label: 'J.R.R. Tolkien',
16684
- * fields: { name: 'J.R.R. Tolkien', birth_year: 1892 },
16685
- * relationships: { books: ['lotr', 'silmarillion'] },
16686
- * });
16687
- * // result.path → 'author_tolkien' (internal graph path)
16688
- * // result.id → 'tolkien' (real-world ID)
16689
- * // result.created → true
16690
- * ```
16691
- */
16692
16910
  async recordObject(options) {
16693
16911
  const results = await this.recordObjects([options]);
16694
16912
  const result = results[0];
@@ -16697,24 +16915,6 @@ var Environment = class _Environment {
16697
16915
  }
16698
16916
  return result;
16699
16917
  }
16700
- /**
16701
- * Batch version of `recordObject()`.
16702
- *
16703
- * Sends rows through the control-plane **`/records/batch`** endpoint in **chunks** (default
16704
- * **100** records per HTTP request) so individual requests stay bounded and gateway timeouts are
16705
- * unlikely. Each chunk is retried on transient network / worker errors.
16706
- *
16707
- * Use the optional second argument to:
16708
- * - **`batchSize`** — rows per POST (smaller = more progress events; larger = fewer round trips).
16709
- * - **`concurrency`** — run up to N chunk POSTs in parallel (capped at 16) when you want lower wall time.
16710
- * - **`onChunkComplete`** — hook for UIs after each chunk succeeds (row order in the returned array
16711
- * always matches `records`; chunk **completion** order may differ when `concurrency > 1`).
16712
- *
16713
- * For **asynchronous** ingestion with worker-side batching and aggregate counters (`queued`,
16714
- * `completed`, …), use **`enqueueRecordImport`** and poll **`getRecordImport`** /
16715
- * **`getRecordImportSummary`** — best for very large fire-and-forget loads when immediate
16716
- * synchronous commit of every row is not required.
16717
- */
16718
16918
  async recordObjects(records, options) {
16719
16919
  options?.signal?.throwIfAborted();
16720
16920
  if (!Array.isArray(records) || records.length === 0) {
@@ -16799,15 +16999,6 @@ var Environment = class _Environment {
16799
16999
  }
16800
17000
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
16801
17001
  }
16802
- /**
16803
- * Queue a background record import for this environment (async worker pipeline).
16804
- *
16805
- * **vs `recordObjects`:** this path accepts the full payload in one request, returns an
16806
- * **`importId`**, and processes rows in the background — use **`getRecordImport`** /
16807
- * **`getRecordImportSummary`** for progress. Choose it for large bulk loads where you do not
16808
- * need every row committed before the HTTP call returns. Use **`recordObjects`** when you need
16809
- * synchronous upserts and fine-grained chunk progress via **`onChunkComplete`**.
16810
- */
16811
17002
  async enqueueRecordImport(records, options = {}) {
16812
17003
  const recordsToImport = records.map(preserveRecordObjectRealId);
16813
17004
  return this.controlPlaneRequest(
@@ -16824,9 +17015,6 @@ var Environment = class _Environment {
16824
17015
  }
16825
17016
  );
16826
17017
  }
16827
- /**
16828
- * List queued or completed record imports for this environment.
16829
- */
16830
17018
  async listRecordImports(status) {
16831
17019
  const suffix = status ? `?status=${encodeURIComponent(status)}` : "";
16832
17020
  const response = await this.controlPlaneRequest(
@@ -16849,9 +17037,6 @@ var Environment = class _Environment {
16849
17037
  const summary = await this.getRecordImportSummary();
16850
17038
  return summary.awaitingRecords;
16851
17039
  }
16852
- /**
16853
- * Fetch a single record import by id.
16854
- */
16855
17040
  async getRecordImport(importId) {
16856
17041
  return this.controlPlaneRequest(
16857
17042
  `/control/record-imports/${importId}`
@@ -16866,9 +17051,6 @@ var Environment = class _Environment {
16866
17051
  const response = await this.controlPlaneRequest(`/control/record-imports/${importId}/items${suffix}`);
16867
17052
  return Array.isArray(response.items) ? response.items : [];
16868
17053
  }
16869
- /**
16870
- * Cancel a queued/background record import.
16871
- */
16872
17054
  async cancelRecordImport(importId) {
16873
17055
  return this.controlPlaneRequest(
16874
17056
  `/control/record-imports/${importId}/cancel`,
@@ -16878,17 +17060,75 @@ var Environment = class _Environment {
16878
17060
  );
16879
17061
  }
16880
17062
  };
16881
- var EnvironmentSession = class extends Session {
16882
- environment;
16883
- sessionDataRoutePrefix;
16884
- sessionDataHeaders;
16885
- beforeMutationSend;
16886
- heartbeatTimer = null;
16887
- heartbeatProbeInFlight = false;
16888
- /** The last known graph container status, updated by checkReadiness(). */
16889
- graphContainerStatus = null;
17063
+ _init = __decoratorStart(null);
17064
+ __decorateElement(_init, 1, "recordState", _recordState_dec, _Environment);
17065
+ __decorateElement(_init, 1, "listSessions", _listSessions_dec, _Environment);
17066
+ __decorateElement(_init, 1, "getUserEnvironmentState", _getUserEnvironmentState_dec, _Environment);
17067
+ __decorateElement(_init, 1, "createSession", _createSession_dec, _Environment);
17068
+ __decorateElement(_init, 1, "connectSession", _connectSession_dec, _Environment);
17069
+ __decorateElement(_init, 1, "closeSession", _closeSession_dec, _Environment);
17070
+ __decorateElement(_init, 1, "graphql", _graphql_dec, _Environment);
17071
+ __decorateElement(_init, 1, "searchRecords", _searchRecords_dec, _Environment);
17072
+ __decorateElement(_init, 1, "defineRelationship", _defineRelationship_dec, _Environment);
17073
+ __decorateElement(_init, 1, "getRelationships", _getRelationships_dec, _Environment);
17074
+ __decorateElement(_init, 1, "attach", _attach_dec, _Environment);
17075
+ __decorateElement(_init, 1, "detach", _detach_dec, _Environment);
17076
+ __decorateElement(_init, 1, "listRelated", _listRelated_dec, _Environment);
17077
+ __decorateElement(_init, 1, "recordObject", _recordObject_dec, _Environment);
17078
+ __decorateElement(_init, 1, "recordObjects", _recordObjects_dec, _Environment);
17079
+ __decorateElement(_init, 1, "executeRecordObjectsChunk", _executeRecordObjectsChunk_dec, _Environment);
17080
+ __decorateElement(_init, 1, "enqueueRecordImport", _enqueueRecordImport_dec, _Environment);
17081
+ __decorateElement(_init, 1, "listRecordImports", _listRecordImports_dec, _Environment);
17082
+ __decorateElement(_init, 1, "getRecordImport", _getRecordImport_dec, _Environment);
17083
+ __decorateElement(_init, 1, "cancelRecordImport", _cancelRecordImport_dec, _Environment);
17084
+ __decorateElement(_init, 13, "queries", _queries_dec, _Environment);
17085
+ __decorateElement(_init, 13, "stateChanges", _stateChanges_dec, _Environment);
17086
+ __decorateElement(_init, 13, "sessions", _sessions_dec, _Environment);
17087
+ __decorateElement(_init, 13, "relationships", _relationships_dec, _Environment);
17088
+ __decorateElement(_init, 13, "imports", _imports_dec, _Environment);
17089
+ __decorateElement(_init, 13, "records", _records_dec, _Environment);
17090
+ _Environment = __decorateElement(_init, 0, "Environment", _Environment_decorators, _Environment);
17091
+ __publicField(_Environment, "queries", __runInitializers(_init, 8, _Environment)), __runInitializers(_init, 11, _Environment);
17092
+ __publicField(_Environment, "stateChanges", __runInitializers(_init, 12, _Environment)), __runInitializers(_init, 15, _Environment);
17093
+ __publicField(_Environment, "sessions", __runInitializers(_init, 16, _Environment)), __runInitializers(_init, 19, _Environment);
17094
+ __publicField(_Environment, "relationships", __runInitializers(_init, 20, _Environment)), __runInitializers(_init, 23, _Environment);
17095
+ __publicField(_Environment, "imports", __runInitializers(_init, 24, _Environment)), __runInitializers(_init, 27, _Environment);
17096
+ __publicField(_Environment, "records", __runInitializers(_init, 28, _Environment)), __runInitializers(_init, 31, _Environment);
17097
+ __runInitializers(_init, 1, _Environment);
17098
+ var Environment = _Environment;
17099
+ var _checkReadiness_dec, _close_dec, _disconnect_dec, _recordObjects_dec2, _mentionRecord_dec, _publishAssistantReply_dec, _getDocument_dec, _getHeap_dec, _conversation_dec, _records_dec2, _lifecycle_dec, _a, _EnvironmentSession_decorators, _init2;
17100
+ _EnvironmentSession_decorators = [Block({
17101
+ description: "Expose conversation messages, selected data and lifecycle operations for one environment session.",
17102
+ id: "granular-product/authoring/importers-record-apis/session-client",
17103
+ label: "Session client",
17104
+ exposedBy: [() => Environment, () => Granular],
17105
+ tests: [
17106
+ "./environment.feed.test.ts",
17107
+ "./environment.assistant-reply.test.ts"
17108
+ ],
17109
+ parent: () => Environment
17110
+ })];
17111
+ var _EnvironmentSession = class _EnvironmentSession extends (_a = Session, _lifecycle_dec = [Interface({
17112
+ label: "Connection lifecycle",
17113
+ description: "Check session readiness and close or disconnect the session client."
17114
+ })], _records_dec2 = [Interface({
17115
+ label: "Session records",
17116
+ description: "Write records or mention an existing record in the current conversation."
17117
+ })], _conversation_dec = [Interface({
17118
+ label: "Conversation data",
17119
+ description: "Read the conversation document and selected data, and publish assistant replies."
17120
+ })], _getHeap_dec = [Method(() => _EnvironmentSession.conversation)], _getDocument_dec = [Method(() => _EnvironmentSession.conversation)], _publishAssistantReply_dec = [Method(() => _EnvironmentSession.conversation)], _mentionRecord_dec = [Method(() => _EnvironmentSession.records, { description: "Add an existing record to the conversation's selected working context." })], _recordObjects_dec2 = [Method(() => _EnvironmentSession.records, { description: "Write a batch of records through the current environment's record-ingestion API." })], _disconnect_dec = [Method(() => _EnvironmentSession.lifecycle)], _close_dec = [Method(() => _EnvironmentSession.lifecycle)], _checkReadiness_dec = [Method(() => _EnvironmentSession.lifecycle)], _a) {
16890
17121
  constructor(client, environment, clientId, options = {}) {
16891
17122
  super(client, clientId, { initialQuota: options.initialQuota });
17123
+ __runInitializers(_init2, 5, this);
17124
+ __publicField(this, "environment");
17125
+ __publicField(this, "sessionDataRoutePrefix");
17126
+ __publicField(this, "sessionDataHeaders");
17127
+ __publicField(this, "beforeMutationSend");
17128
+ __publicField(this, "heartbeatTimer", null);
17129
+ __publicField(this, "heartbeatProbeInFlight", false);
17130
+ /** The last known graph container status, updated by checkReadiness(). */
17131
+ __publicField(this, "graphContainerStatus", null);
16892
17132
  this.environment = environment;
16893
17133
  this.sessionDataRoutePrefix = options.sessionDataRoutePrefix || "/orchestrator/ws/sessions";
16894
17134
  this.sessionDataHeaders = options.sessionDataHeaders || {};
@@ -16986,9 +17226,6 @@ var EnvironmentSession = class extends Session {
16986
17226
  get feedback() {
16987
17227
  return this.environment.feedback;
16988
17228
  }
16989
- /**
16990
- * Return a plain JS copy of the synced session heap.
16991
- */
16992
17229
  getHeap() {
16993
17230
  const doc = this.document;
16994
17231
  return normalizeHeapSnapshot(doc?.heap);
@@ -17063,22 +17300,9 @@ var EnvironmentSession = class extends Session {
17063
17300
  });
17064
17301
  return response.json();
17065
17302
  }
17066
- /**
17067
- * Fetch the live session document from the runtime DO.
17068
- *
17069
- * For presentation history use `feed.list()` or `transcript.list()`.
17070
- * Timeline and job collections are diagnostic/execution data only.
17071
- */
17072
17303
  async getDocument() {
17073
17304
  return this.sessionDataRequest("/document");
17074
17305
  }
17075
- /**
17076
- * Publish one terminal assistant reply from a trusted server integration.
17077
- *
17078
- * This uses the API-key-authenticated HTTP session boundary. Delegated
17079
- * browser sessions cannot use it and never receive assistant feed-authoring
17080
- * capability through their WebSocket.
17081
- */
17082
17306
  async publishAssistantReply(input) {
17083
17307
  if (this.sessionDataRoutePrefix === "/sdk/browser-sessions") {
17084
17308
  throw new Error(
@@ -17460,13 +17684,6 @@ var EnvironmentSession = class extends Session {
17460
17684
  async listFeedback() {
17461
17685
  return this.environment.listFeedback();
17462
17686
  }
17463
- /**
17464
- * Close the session and disconnect from the sandbox.
17465
- *
17466
- * Sends `client.goodbye` over WebSocket first, then issues an HTTP fallback
17467
- * to the runtime goodbye endpoint if no definitive WS-side runtime notify
17468
- * acknowledgement was observed.
17469
- */
17470
17687
  async disconnect() {
17471
17688
  this.stopHeartbeat();
17472
17689
  this.disposeSessionFeed();
@@ -17510,15 +17727,9 @@ var EnvironmentSession = class extends Session {
17510
17727
  this.stopHeartbeat();
17511
17728
  this.client.disconnect({ reason: "Transport detach" });
17512
17729
  }
17513
- /**
17514
- * Backwards-compatible alias for `disconnect()`.
17515
- */
17516
17730
  async close() {
17517
17731
  await this.disconnect();
17518
17732
  }
17519
- /**
17520
- * Check if the graph container is ready and warm.
17521
- */
17522
17733
  async checkReadiness() {
17523
17734
  const result = await this.client.call("client.heartbeat", {});
17524
17735
  const containerStatus = result?.graphContainerStatus ?? {
@@ -17530,6 +17741,24 @@ var EnvironmentSession = class extends Session {
17530
17741
  return containerStatus;
17531
17742
  }
17532
17743
  };
17744
+ _init2 = __decoratorStart(_a);
17745
+ __decorateElement(_init2, 1, "getHeap", _getHeap_dec, _EnvironmentSession);
17746
+ __decorateElement(_init2, 1, "getDocument", _getDocument_dec, _EnvironmentSession);
17747
+ __decorateElement(_init2, 1, "publishAssistantReply", _publishAssistantReply_dec, _EnvironmentSession);
17748
+ __decorateElement(_init2, 1, "mentionRecord", _mentionRecord_dec, _EnvironmentSession);
17749
+ __decorateElement(_init2, 1, "recordObjects", _recordObjects_dec2, _EnvironmentSession);
17750
+ __decorateElement(_init2, 1, "disconnect", _disconnect_dec, _EnvironmentSession);
17751
+ __decorateElement(_init2, 1, "close", _close_dec, _EnvironmentSession);
17752
+ __decorateElement(_init2, 1, "checkReadiness", _checkReadiness_dec, _EnvironmentSession);
17753
+ __decorateElement(_init2, 13, "lifecycle", _lifecycle_dec, _EnvironmentSession);
17754
+ __decorateElement(_init2, 13, "records", _records_dec2, _EnvironmentSession);
17755
+ __decorateElement(_init2, 13, "conversation", _conversation_dec, _EnvironmentSession);
17756
+ _EnvironmentSession = __decorateElement(_init2, 0, "EnvironmentSession", _EnvironmentSession_decorators, _EnvironmentSession);
17757
+ __publicField(_EnvironmentSession, "lifecycle", __runInitializers(_init2, 8, _EnvironmentSession)), __runInitializers(_init2, 11, _EnvironmentSession);
17758
+ __publicField(_EnvironmentSession, "records", __runInitializers(_init2, 12, _EnvironmentSession)), __runInitializers(_init2, 15, _EnvironmentSession);
17759
+ __publicField(_EnvironmentSession, "conversation", __runInitializers(_init2, 16, _EnvironmentSession)), __runInitializers(_init2, 19, _EnvironmentSession);
17760
+ __runInitializers(_init2, 1, _EnvironmentSession);
17761
+ var EnvironmentSession = _EnvironmentSession;
17533
17762
  var OntologyHandle = class {
17534
17763
  granular;
17535
17764
  ontologyNameOrId;
@@ -17581,40 +17810,62 @@ var OntologyHandle = class {
17581
17810
  };
17582
17811
  }
17583
17812
  };
17584
- var Granular = class _Granular {
17585
- /** Tenant events feed, authenticated with this client's credentials. */
17586
- eventsFeed = new EventsFeed(
17587
- (path, options) => this.request(path, options)
17588
- );
17589
- apiKey;
17590
- apiUrl;
17591
- httpUrl;
17592
- tokenProvider;
17593
- WebSocketCtor;
17594
- onUnexpectedClose;
17595
- onReconnectError;
17596
- effectHostUrl;
17597
- graphqlIdempotencyKey;
17598
- debugHttp = process.env.GRANULAR_DEBUG_HTTP === "1";
17599
- /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
17600
- sandboxEffects = /* @__PURE__ */ new Map();
17601
- /** Live sandbox-scoped effect hosts keyed by sandboxId */
17602
- sandboxEffectHosts = /* @__PURE__ */ new Map();
17603
- developmentProviders = /* @__PURE__ */ new Map();
17604
- usersProviders = /* @__PURE__ */ new Map();
17605
- /** In-flight host connection promises to avoid duplicate concurrent connects */
17606
- sandboxEffectHostPromises = /* @__PURE__ */ new Map();
17607
- effectHostGenerations = /* @__PURE__ */ new Map();
17608
- effectHostRecovery = /* @__PURE__ */ new Map();
17609
- /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
17610
- ontologyImporters = /* @__PURE__ */ new Map();
17611
- /** Resolved importer hooks keyed by sandboxId for fast lookups during openEnvironment(). */
17612
- sandboxImporters = /* @__PURE__ */ new Map();
17813
+ var _request_dec, _disconnectEffects_dec, _unregisterEffect_dec, _registerEffects_dec, _registerEffect_dec, _reopenSession_dec, _closeSession_dec2, _connectSession_dec2, _createSession_dec2, _listSessions_dec2, _connect_dec, _adoptEnvironmentForUser_dec, _getEnvironmentForUser_dec, _getActiveEnvironmentForUser_dec, _openEnvironment_dec, _environmentAccess_dec, _sessions_dec2, _effectHosts_dec, _transport_dec, _Granular_decorators, _init3;
17814
+ _Granular_decorators = [Block({
17815
+ description: "Authenticate an application and provide access to its environments, sessions and registered action handlers.",
17816
+ id: "granular-product/authoring/sdk-ontology-facade",
17817
+ label: "Granular client",
17818
+ tests: ["./environment.opening.test.ts"],
17819
+ docs: "../README.md"
17820
+ })], _transport_dec = [Interface({
17821
+ label: "HTTP requests",
17822
+ description: "Send authenticated SDK requests to the configured Granular API."
17823
+ })], _effectHosts_dec = [Interface({
17824
+ id: "granular-product/authoring/live-effect-hosts",
17825
+ label: "Application action handlers",
17826
+ description: "Register application functions that Granular may invoke as actions, and disconnect handlers when they are no longer available."
17827
+ })], _sessions_dec2 = [Interface({
17828
+ label: "Sessions",
17829
+ description: "Create, list, connect and close product sessions through the SDK."
17830
+ })], _environmentAccess_dec = [Interface({
17831
+ label: "Environment access",
17832
+ description: "Resolve a user\u2019s assigned environment or open a connection to it."
17833
+ })], _openEnvironment_dec = [Method(() => _Granular.environmentAccess)], _getActiveEnvironmentForUser_dec = [Method(() => _Granular.environmentAccess)], _getEnvironmentForUser_dec = [Method(() => _Granular.environmentAccess)], _adoptEnvironmentForUser_dec = [Method(() => _Granular.environmentAccess)], _connect_dec = [Method(() => _Granular.environmentAccess)], _listSessions_dec2 = [Method(() => _Granular.sessions)], _createSession_dec2 = [Method(() => _Granular.sessions, { benchmarks: ["./session-ready.bench.ts"] })], _connectSession_dec2 = [Method(() => _Granular.sessions)], _closeSession_dec2 = [Method(() => _Granular.sessions)], _reopenSession_dec = [Method(() => _Granular.sessions)], _registerEffect_dec = [Method(() => _Granular.effectHosts)], _registerEffects_dec = [Method(() => _Granular.effectHosts)], _unregisterEffect_dec = [Method(() => _Granular.effectHosts)], _disconnectEffects_dec = [Method(() => _Granular.effectHosts)], _request_dec = [Method(() => _Granular.transport)];
17834
+ var _Granular = class _Granular {
17613
17835
  /**
17614
17836
  * Create a new Granular client
17615
17837
  * @param options - Client configuration
17616
17838
  */
17617
17839
  constructor(options) {
17840
+ __runInitializers(_init3, 5, this);
17841
+ /** Tenant events feed, authenticated with this client's credentials. */
17842
+ __publicField(this, "eventsFeed", new EventsFeed(
17843
+ (path, options) => this.request(path, options)
17844
+ ));
17845
+ __publicField(this, "apiKey");
17846
+ __publicField(this, "apiUrl");
17847
+ __publicField(this, "httpUrl");
17848
+ __publicField(this, "tokenProvider");
17849
+ __publicField(this, "WebSocketCtor");
17850
+ __publicField(this, "onUnexpectedClose");
17851
+ __publicField(this, "onReconnectError");
17852
+ __publicField(this, "effectHostUrl");
17853
+ __publicField(this, "graphqlIdempotencyKey");
17854
+ __publicField(this, "debugHttp", process.env.GRANULAR_DEBUG_HTTP === "1");
17855
+ /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
17856
+ __publicField(this, "sandboxEffects", /* @__PURE__ */ new Map());
17857
+ /** Live sandbox-scoped effect hosts keyed by sandboxId */
17858
+ __publicField(this, "sandboxEffectHosts", /* @__PURE__ */ new Map());
17859
+ __publicField(this, "developmentProviders", /* @__PURE__ */ new Map());
17860
+ __publicField(this, "usersProviders", /* @__PURE__ */ new Map());
17861
+ /** In-flight host connection promises to avoid duplicate concurrent connects */
17862
+ __publicField(this, "sandboxEffectHostPromises", /* @__PURE__ */ new Map());
17863
+ __publicField(this, "effectHostGenerations", /* @__PURE__ */ new Map());
17864
+ __publicField(this, "effectHostRecovery", /* @__PURE__ */ new Map());
17865
+ /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
17866
+ __publicField(this, "ontologyImporters", /* @__PURE__ */ new Map());
17867
+ /** Resolved importer hooks keyed by sandboxId for fast lookups during openEnvironment(). */
17868
+ __publicField(this, "sandboxImporters", /* @__PURE__ */ new Map());
17618
17869
  const auth = options.token ?? options.apiKey;
17619
17870
  if (!auth) {
17620
17871
  throw new Error(
@@ -17662,8 +17913,8 @@ var Granular = class _Granular {
17662
17913
  sandboxId
17663
17914
  );
17664
17915
  if (!importer) throw new Error("No environment importer registered.");
17665
- const host = await this.ensureSandboxEffectHost(sandboxId);
17666
- await host.wsClient.call("environment.importer.register", {});
17916
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
17917
+ await host2.wsClient.call("environment.importer.register", {});
17667
17918
  }
17668
17919
  clearEnvironmentImporter(ontologyNameOrId) {
17669
17920
  this.ontologyImporters.delete(ontologyNameOrId);
@@ -17765,29 +18016,6 @@ var Granular = class _Granular {
17765
18016
  "openEnvironment() requires either userId, granularId, or a user object returned by recordUser()."
17766
18017
  );
17767
18018
  }
17768
- /**
17769
- * Open or resolve an ontology environment for one user without opening a session.
17770
- *
17771
- * @example
17772
- * ```typescript
17773
- * const environment = await granular.openEnvironment({
17774
- * ontology: 'my-ontology',
17775
- * tag: 'dev',
17776
- * userId: 'user_123',
17777
- * permissions: ['agent'],
17778
- * });
17779
- *
17780
- * await environment.data.record({
17781
- * className: 'customer',
17782
- * id: 'acme',
17783
- * fields: { name: 'Acme' },
17784
- * });
17785
- *
17786
- * const session = await environment.sessions.create();
17787
- * const job = await session.submitJob(`return "hello";`);
17788
- * console.log(await job.result);
17789
- * ```
17790
- */
17791
18019
  async openEnvironment(options) {
17792
18020
  const resolved = await this.resolveOpenEnvironmentData(
17793
18021
  options,
@@ -17797,11 +18025,6 @@ var Granular = class _Granular {
17797
18025
  await this.maybeRunEnvironmentImporter(resolved, environment);
17798
18026
  return environment;
17799
18027
  }
17800
- /**
17801
- * Read the active environment selected by Granular for an already-recorded
17802
- * external user. This is intentionally read-only: browser/login code must
17803
- * not create subjects or environments as a side effect.
17804
- */
17805
18028
  async getActiveEnvironmentForUser(options) {
17806
18029
  const sandboxId = options.sandboxId.trim();
17807
18030
  const tagName = options.tag.trim();
@@ -17847,13 +18070,6 @@ var Granular = class _Granular {
17847
18070
  throw error;
17848
18071
  }
17849
18072
  }
17850
- /**
17851
- * Resolve one exact environment only when Granular confirms that it belongs
17852
- * to the given external user in the requested sandbox (and, optionally,
17853
- * tag). This is deliberately read-only: callers use it to keep an already
17854
- * opened delegated workspace stable while a newer active environment is
17855
- * being prepared in the background.
17856
- */
17857
18073
  async getEnvironmentForUser(options) {
17858
18074
  const sandboxId = options.sandboxId.trim();
17859
18075
  const userId = options.userId.trim();
@@ -17896,11 +18112,6 @@ var Granular = class _Granular {
17896
18112
  }
17897
18113
  return this.bindEnvironmentHandle(environment);
17898
18114
  }
17899
- /**
17900
- * Register one reviewed, pre-existing environment as the active workspace
17901
- * for an external user. This is for a controlled migration only: it does
17902
- * not create an environment and it does not run an importer.
17903
- */
17904
18115
  async adoptEnvironmentForUser(options) {
17905
18116
  const sandboxId = options.sandboxId.trim();
17906
18117
  const tagName = options.tag.trim();
@@ -17947,11 +18158,6 @@ var Granular = class _Granular {
17947
18158
  normalizeEnvironmentData(payload.environment)
17948
18159
  );
17949
18160
  }
17950
- /**
17951
- * Deprecated compatibility alias for `openEnvironment()`.
17952
- *
17953
- * `connect()` no longer opens a runtime session automatically.
17954
- */
17955
18161
  async connect(options) {
17956
18162
  return this.openEnvironment({
17957
18163
  ...options,
@@ -18255,9 +18461,6 @@ var Granular = class _Granular {
18255
18461
  setupOperationKey: resetKey
18256
18462
  };
18257
18463
  }
18258
- /**
18259
- * List indexed sessions using ownership filters and bounded pagination.
18260
- */
18261
18464
  async listSessions(options) {
18262
18465
  const items = [];
18263
18466
  let cursor = options.cursor?.trim() || void 0;
@@ -18454,10 +18657,6 @@ var Granular = class _Granular {
18454
18657
  }
18455
18658
  return (/* @__PURE__ */ new Date(0)).toISOString();
18456
18659
  }
18457
- /**
18458
- * Create a new session (conversation) for an existing environment and connect to it.
18459
- * The runtime graph is shared across all sessions for the same environment.
18460
- */
18461
18660
  async createSession(options) {
18462
18661
  const clientId = options.clientId || `client_${Date.now()}`;
18463
18662
  const sessionScope = options.sessionScope?.trim() || void 0;
@@ -18478,9 +18677,6 @@ var Granular = class _Granular {
18478
18677
  });
18479
18678
  return this.bindWebSocketEnvironmentSession(environment, clientId, session);
18480
18679
  }
18481
- /**
18482
- * Connect to an existing open session (same conversation thread) using a freshly minted WebSocket token.
18483
- */
18484
18680
  async connectSession(options) {
18485
18681
  const clientId = options.clientId || `client_${Date.now()}`;
18486
18682
  const minted = await this.request(`/ws/sessions/${encodeURIComponent(options.sessionId)}/token`, {
@@ -18507,7 +18703,6 @@ var Granular = class _Granular {
18507
18703
  metadata: options?.metadata
18508
18704
  });
18509
18705
  }
18510
- /** End a session through the runtime, or disconnect its connected handle. */
18511
18706
  async closeSession(sessionId, environment) {
18512
18707
  if (environment && environment.sessionId === sessionId) {
18513
18708
  await environment.disconnect();
@@ -18518,9 +18713,6 @@ var Granular = class _Granular {
18518
18713
  { method: "POST" }
18519
18714
  );
18520
18715
  }
18521
- /**
18522
- * Re-open a closed session in the index and connect to its existing runtime document.
18523
- */
18524
18716
  async reopenSession(sessionId, options) {
18525
18717
  await this.request(`/control/sessions/${encodeURIComponent(sessionId)}`, {
18526
18718
  method: "PATCH",
@@ -18761,25 +18953,25 @@ var Granular = class _Granular {
18761
18953
  }
18762
18954
  return serialized2;
18763
18955
  }
18764
- async publishSandboxEffectCatalog(host) {
18956
+ async publishSandboxEffectCatalog(host2) {
18765
18957
  const effects = Array.from(
18766
- this.getSandboxEffectMap(host.sandboxId).values()
18958
+ this.getSandboxEffectMap(host2.sandboxId).values()
18767
18959
  ).map((effect) => this.serializeEffect(effect));
18768
18960
  let acceptedCount = 0;
18769
18961
  const rejected = [];
18770
18962
  try {
18771
18963
  await withTimeout(
18772
- host.wsClient.call("effects.resetCatalog", {}),
18964
+ host2.wsClient.call("effects.resetCatalog", {}),
18773
18965
  EFFECT_CATALOG_SYNC_TIMEOUT_MS,
18774
- `effects.resetCatalog for sandbox ${host.sandboxId}`
18966
+ `effects.resetCatalog for sandbox ${host2.sandboxId}`
18775
18967
  );
18776
18968
  for (const batch of chunkItems(effects, EFFECT_CATALOG_SYNC_BATCH_SIZE)) {
18777
18969
  const result = await withTimeout(
18778
- host.wsClient.call("effects.addCatalog", {
18970
+ host2.wsClient.call("effects.addCatalog", {
18779
18971
  effects: batch
18780
18972
  }),
18781
18973
  EFFECT_CATALOG_SYNC_TIMEOUT_MS,
18782
- `effects.addCatalog for sandbox ${host.sandboxId}`
18974
+ `effects.addCatalog for sandbox ${host2.sandboxId}`
18783
18975
  );
18784
18976
  acceptedCount += typeof result?.acceptedCount === "number" ? result.acceptedCount : 0;
18785
18977
  if (Array.isArray(result?.rejected)) {
@@ -18791,11 +18983,11 @@ var Granular = class _Granular {
18791
18983
  throw error;
18792
18984
  }
18793
18985
  const result = await withTimeout(
18794
- host.wsClient.call("effects.publishCatalog", {
18986
+ host2.wsClient.call("effects.publishCatalog", {
18795
18987
  effects
18796
18988
  }),
18797
18989
  EFFECT_CATALOG_SYNC_TIMEOUT_MS,
18798
- `effects.publishCatalog for sandbox ${host.sandboxId}`
18990
+ `effects.publishCatalog for sandbox ${host2.sandboxId}`
18799
18991
  );
18800
18992
  acceptedCount = typeof result?.acceptedCount === "number" ? result.acceptedCount : 0;
18801
18993
  if (Array.isArray(result?.rejected)) {
@@ -18807,12 +18999,12 @@ var Granular = class _Granular {
18807
18999
  (entry) => `${entry.name || "unknown"}: ${entry.reason || "rejected"}`
18808
19000
  ).join("; ");
18809
19001
  throw new Error(
18810
- `Failed to publish live effects for sandbox ${host.sandboxId}: ${detail}`
19002
+ `Failed to publish live effects for sandbox ${host2.sandboxId}: ${detail}`
18811
19003
  );
18812
19004
  }
18813
19005
  if (rejected.length > 0) {
18814
19006
  console.warn(
18815
- `[Granular] Some live effects were rejected for sandbox ${host.sandboxId}:`,
19007
+ `[Granular] Some live effects were rejected for sandbox ${host2.sandboxId}:`,
18816
19008
  rejected
18817
19009
  );
18818
19010
  }
@@ -18821,8 +19013,8 @@ var Granular = class _Granular {
18821
19013
  let lastError;
18822
19014
  for (let attempt = 1; attempt <= EFFECT_CATALOG_SYNC_RETRY_COUNT; attempt += 1) {
18823
19015
  try {
18824
- const host = await this.ensureSandboxEffectHost(sandboxId);
18825
- await this.publishSandboxEffectCatalog(host);
19016
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
19017
+ await this.publishSandboxEffectCatalog(host2);
18826
19018
  return;
18827
19019
  } catch (error) {
18828
19020
  lastError = error;
@@ -18839,11 +19031,11 @@ var Granular = class _Granular {
18839
19031
  }
18840
19032
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
18841
19033
  }
18842
- recoverEffectHost(host, error) {
18843
- const sandboxId = host.sandboxId;
18844
- if (host.recovering || this.sandboxEffectHosts.get(sandboxId) !== host)
19034
+ recoverEffectHost(host2, error) {
19035
+ const sandboxId = host2.sandboxId;
19036
+ if (host2.recovering || this.sandboxEffectHosts.get(sandboxId) !== host2)
18845
19037
  return;
18846
- host.recovering = true;
19038
+ host2.recovering = true;
18847
19039
  this.disconnectSandboxEffectHost(sandboxId);
18848
19040
  const state = {
18849
19041
  attempt: 0,
@@ -18866,7 +19058,7 @@ var Granular = class _Granular {
18866
19058
  );
18867
19059
  try {
18868
19060
  this.onReconnectError?.({
18869
- sessionId: `effect-host:${host.effectClientId}`,
19061
+ sessionId: `effect-host:${host2.effectClientId}`,
18870
19062
  error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError),
18871
19063
  timestamp: Date.now(),
18872
19064
  terminal: !retryable
@@ -18919,13 +19111,13 @@ var Granular = class _Granular {
18919
19111
  )
18920
19112
  };
18921
19113
  }
18922
- async recoverSourceCommits(host) {
19114
+ async recoverSourceCommits(host2) {
18923
19115
  const stores = new Set(
18924
- Array.from(this.getSandboxEffectMap(host.sandboxId).values()).map((effect) => effect.commit?.storage).filter(Boolean)
19116
+ Array.from(this.getSandboxEffectMap(host2.sandboxId).values()).map((effect) => effect.commit?.storage).filter(Boolean)
18925
19117
  );
18926
19118
  for (const store of stores) {
18927
19119
  try {
18928
- await store.recover(this.effectCommitTransport(), host.sandboxId);
19120
+ await store.recover(this.effectCommitTransport(), host2.sandboxId);
18929
19121
  } catch (error) {
18930
19122
  console.warn(
18931
19123
  "[Granular] Source commit delivery remains pending:",
@@ -18934,43 +19126,43 @@ var Granular = class _Granular {
18934
19126
  }
18935
19127
  }
18936
19128
  }
18937
- startEffectHostHeartbeat(host) {
18938
- if (host.heartbeatTimer) {
18939
- clearInterval(host.heartbeatTimer);
19129
+ startEffectHostHeartbeat(host2) {
19130
+ if (host2.heartbeatTimer) {
19131
+ clearInterval(host2.heartbeatTimer);
18940
19132
  }
18941
- host.heartbeatInFlight = false;
19133
+ host2.heartbeatInFlight = false;
18942
19134
  const sendHeartbeat = (failureLabel, recoverOnFailure) => {
18943
- if (host.heartbeatInFlight || host.recovering) {
19135
+ if (host2.heartbeatInFlight || host2.recovering) {
18944
19136
  return;
18945
19137
  }
18946
- host.heartbeatInFlight = true;
18947
- host.wsClient.call("client.heartbeat", {}).then(() => this.recoverSourceCommits(host)).catch((error) => {
18948
- console.warn(`${failureLabel} ${host.sandboxId}:`, error);
19138
+ host2.heartbeatInFlight = true;
19139
+ host2.wsClient.call("client.heartbeat", {}).then(() => this.recoverSourceCommits(host2)).catch((error) => {
19140
+ console.warn(`${failureLabel} ${host2.sandboxId}:`, error);
18949
19141
  if (recoverOnFailure) {
18950
- this.recoverEffectHost(host, error);
19142
+ this.recoverEffectHost(host2, error);
18951
19143
  }
18952
19144
  }).finally(() => {
18953
- host.heartbeatInFlight = false;
19145
+ host2.heartbeatInFlight = false;
18954
19146
  });
18955
19147
  };
18956
19148
  sendHeartbeat(
18957
19149
  "[Granular] Initial effect host heartbeat failed for sandbox",
18958
19150
  false
18959
19151
  );
18960
- host.heartbeatTimer = setInterval(() => {
19152
+ host2.heartbeatTimer = setInterval(() => {
18961
19153
  sendHeartbeat(
18962
19154
  "[Granular] Effect host heartbeat failed for sandbox",
18963
19155
  true
18964
19156
  );
18965
19157
  }, 1e4);
18966
19158
  }
18967
- stopEffectHostHeartbeat(host) {
18968
- if (!host?.heartbeatTimer) {
19159
+ stopEffectHostHeartbeat(host2) {
19160
+ if (!host2?.heartbeatTimer) {
18969
19161
  return;
18970
19162
  }
18971
- clearInterval(host.heartbeatTimer);
18972
- host.heartbeatTimer = null;
18973
- host.heartbeatInFlight = false;
19163
+ clearInterval(host2.heartbeatTimer);
19164
+ host2.heartbeatTimer = null;
19165
+ host2.heartbeatInFlight = false;
18974
19166
  }
18975
19167
  async registerUsers(ontologyNameOrId, handler, options) {
18976
19168
  const provider = new UsersProvider(handler, options);
@@ -18978,8 +19170,8 @@ var Granular = class _Granular {
18978
19170
  const previous = this.usersProviders.get(sandboxId);
18979
19171
  this.usersProviders.set(sandboxId, provider);
18980
19172
  try {
18981
- const host = await this.ensureSandboxEffectHost(sandboxId);
18982
- if (provider.registration?.providerId !== host.effectClientId) await this.registerUsersOnHost(host, provider);
19173
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
19174
+ if (provider.registration?.providerId !== host2.effectClientId) await this.registerUsersOnHost(host2, provider);
18983
19175
  if (!provider.registration) throw new Error("User directory registration is no longer live.");
18984
19176
  return provider.registration;
18985
19177
  } catch (error) {
@@ -18990,10 +19182,10 @@ var Granular = class _Granular {
18990
19182
  throw error;
18991
19183
  }
18992
19184
  }
18993
- async registerUsersOnHost(host, provider) {
18994
- const registration = await host.wsClient.call("users.register", {});
18995
- if (this.usersProviders.get(host.sandboxId) !== provider) throw new Error("User directory registration was replaced.");
18996
- provider.bind(registration, host.sandboxId, host.effectClientId);
19185
+ async registerUsersOnHost(host2, provider) {
19186
+ const registration = await host2.wsClient.call("users.register", {});
19187
+ if (this.usersProviders.get(host2.sandboxId) !== provider) throw new Error("User directory registration was replaced.");
19188
+ provider.bind(registration, host2.sandboxId, host2.effectClientId);
18997
19189
  }
18998
19190
  /** Publish only public setup metadata; product session authority stays in resolveLaunch. */
18999
19191
  async registerCustomerSkill(ontologyNameOrId, options) {
@@ -19045,10 +19237,10 @@ var Granular = class _Granular {
19045
19237
  const previous = this.developmentProviders.get(sandboxId);
19046
19238
  this.developmentProviders.set(sandboxId, provider);
19047
19239
  try {
19048
- const host = await this.ensureSandboxEffectHost(sandboxId);
19240
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
19049
19241
  if (this.developmentProviders.get(sandboxId) !== provider) throw new Error("Development registration was replaced.");
19050
- if (provider.registration?.providerId !== host.effectClientId) {
19051
- await this.registerDevelopmentOnHost(host, provider);
19242
+ if (provider.registration?.providerId !== host2.effectClientId) {
19243
+ await this.registerDevelopmentOnHost(host2, provider);
19052
19244
  }
19053
19245
  if (!provider.registration) throw new Error("Development provider registration is no longer live.");
19054
19246
  return provider.registration;
@@ -19060,38 +19252,38 @@ var Granular = class _Granular {
19060
19252
  throw error;
19061
19253
  }
19062
19254
  }
19063
- async registerDevelopmentOnHost(host, provider) {
19064
- const registration = await host.wsClient.call(
19255
+ async registerDevelopmentOnHost(host2, provider) {
19256
+ const registration = await host2.wsClient.call(
19065
19257
  "onboarding.register",
19066
19258
  provider.registrationParams()
19067
19259
  );
19068
- if (this.developmentProviders.get(host.sandboxId) !== provider)
19260
+ if (this.developmentProviders.get(host2.sandboxId) !== provider)
19069
19261
  throw new Error("Development registration was replaced.");
19070
- provider.bind(registration, host.sandboxId, host.effectClientId);
19262
+ provider.bind(registration, host2.sandboxId, host2.effectClientId);
19071
19263
  }
19072
- async synchronizeEffectHost(host) {
19073
- if (host.syncPromise) {
19074
- return host.syncPromise;
19264
+ async synchronizeEffectHost(host2) {
19265
+ if (host2.syncPromise) {
19266
+ return host2.syncPromise;
19075
19267
  }
19076
- host.syncPromise = (async () => {
19077
- await host.wsClient.call("client.hello", {
19078
- clientId: host.clientId,
19268
+ host2.syncPromise = (async () => {
19269
+ await host2.wsClient.call("client.hello", {
19270
+ clientId: host2.clientId,
19079
19271
  protocolVersion: "2.0"
19080
19272
  });
19081
- await this.publishSandboxEffectCatalog(host);
19082
- if (this.resolveEnvironmentImporter(host.sandboxId, host.sandboxId))
19083
- await host.wsClient.call("environment.importer.register", {});
19084
- const users2 = this.usersProviders.get(host.sandboxId);
19085
- if (users2) await this.registerUsersOnHost(host, users2);
19086
- const development = this.developmentProviders.get(host.sandboxId);
19087
- if (development) await this.registerDevelopmentOnHost(host, development);
19088
- this.startEffectHostHeartbeat(host);
19273
+ await this.publishSandboxEffectCatalog(host2);
19274
+ if (this.resolveEnvironmentImporter(host2.sandboxId, host2.sandboxId))
19275
+ await host2.wsClient.call("environment.importer.register", {});
19276
+ const users2 = this.usersProviders.get(host2.sandboxId);
19277
+ if (users2) await this.registerUsersOnHost(host2, users2);
19278
+ const development = this.developmentProviders.get(host2.sandboxId);
19279
+ if (development) await this.registerDevelopmentOnHost(host2, development);
19280
+ this.startEffectHostHeartbeat(host2);
19089
19281
  })();
19090
19282
  try {
19091
- await host.syncPromise;
19283
+ await host2.syncPromise;
19092
19284
  } finally {
19093
- if (host.syncPromise) {
19094
- host.syncPromise = null;
19285
+ if (host2.syncPromise) {
19286
+ host2.syncPromise = null;
19095
19287
  }
19096
19288
  }
19097
19289
  }
@@ -19121,7 +19313,7 @@ var Granular = class _Granular {
19121
19313
  onUnexpectedClose: this.onUnexpectedClose,
19122
19314
  onReconnectError: this.onReconnectError
19123
19315
  });
19124
- const host = {
19316
+ const host2 = {
19125
19317
  generation: generation2,
19126
19318
  sandboxId,
19127
19319
  effectClientId,
@@ -19208,20 +19400,20 @@ var Granular = class _Granular {
19208
19400
  };
19209
19401
  });
19210
19402
  wsClient.on("open", () => {
19211
- void this.synchronizeEffectHost(host).catch((error) => {
19403
+ void this.synchronizeEffectHost(host2).catch((error) => {
19212
19404
  console.error(
19213
19405
  `[Granular] Failed to re-sync effect host for sandbox ${sandboxId}:`,
19214
19406
  error
19215
19407
  );
19216
- this.recoverEffectHost(host, error);
19408
+ this.recoverEffectHost(host2, error);
19217
19409
  });
19218
19410
  });
19219
19411
  wsClient.on("disconnect", () => {
19220
- this.stopEffectHostHeartbeat(host);
19412
+ this.stopEffectHostHeartbeat(host2);
19221
19413
  const users2 = this.usersProviders.get(sandboxId);
19222
- if (users2?.registration?.providerId === host.effectClientId) users2.unbind();
19414
+ if (users2?.registration?.providerId === host2.effectClientId) users2.unbind();
19223
19415
  const provider = this.developmentProviders.get(sandboxId);
19224
- if (provider?.registration?.providerId === host.effectClientId) provider.unbind();
19416
+ if (provider?.registration?.providerId === host2.effectClientId) provider.unbind();
19225
19417
  });
19226
19418
  try {
19227
19419
  await withTimeout(
@@ -19229,13 +19421,13 @@ var Granular = class _Granular {
19229
19421
  EFFECT_HOST_CONNECT_TIMEOUT_MS,
19230
19422
  `effect host WebSocket connect for sandbox ${sandboxId}`
19231
19423
  );
19232
- await this.synchronizeEffectHost(host);
19424
+ await this.synchronizeEffectHost(host2);
19233
19425
  if ((this.effectHostGenerations.get(sandboxId) || 0) !== generation2)
19234
19426
  throw new Error("Effect host connection was canceled");
19235
- this.sandboxEffectHosts.set(sandboxId, host);
19236
- return host;
19427
+ this.sandboxEffectHosts.set(sandboxId, host2);
19428
+ return host2;
19237
19429
  } catch (error) {
19238
- this.stopEffectHostHeartbeat(host);
19430
+ this.stopEffectHostHeartbeat(host2);
19239
19431
  wsClient.disconnect({ reason: "Effect host initialization failed" });
19240
19432
  throw error;
19241
19433
  }
@@ -19259,20 +19451,14 @@ var Granular = class _Granular {
19259
19451
  const recovering = this.effectHostRecovery.get(sandboxId);
19260
19452
  if (recovering?.timer) clearTimeout(recovering.timer);
19261
19453
  this.effectHostRecovery.delete(sandboxId);
19262
- const host = this.sandboxEffectHosts.get(sandboxId);
19263
- if (!host) {
19454
+ const host2 = this.sandboxEffectHosts.get(sandboxId);
19455
+ if (!host2) {
19264
19456
  return;
19265
19457
  }
19266
19458
  this.sandboxEffectHosts.delete(sandboxId);
19267
- this.stopEffectHostHeartbeat(host);
19268
- host.wsClient.disconnect();
19459
+ this.stopEffectHostHeartbeat(host2);
19460
+ host2.wsClient.disconnect();
19269
19461
  }
19270
- /**
19271
- * Register an effect (tool) for a specific sandbox.
19272
- *
19273
- * @param sandboxNameOrId - The name or ID of the sandbox
19274
- * @param effect - The tool definition and handler
19275
- */
19276
19462
  async registerEffect(sandboxNameOrId, effect) {
19277
19463
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
19278
19464
  const sandboxId = sandbox.sandboxId;
@@ -19282,11 +19468,6 @@ var Granular = class _Granular {
19282
19468
  );
19283
19469
  await this.syncSandboxEffectCatalog(sandboxId);
19284
19470
  }
19285
- /**
19286
- * Register multiple effects (tools) for a specific sandbox.
19287
- *
19288
- * batch version of `registerEffect`.
19289
- */
19290
19471
  async registerEffects(sandboxNameOrId, effects) {
19291
19472
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
19292
19473
  const sandboxId = sandbox.sandboxId;
@@ -19296,12 +19477,6 @@ var Granular = class _Granular {
19296
19477
  }
19297
19478
  await this.syncSandboxEffectCatalog(sandboxId);
19298
19479
  }
19299
- /**
19300
- * Unregister an effect from a sandbox.
19301
- *
19302
- * Removes it from the local sandbox registry and updates the
19303
- * sandbox-scoped live catalog.
19304
- */
19305
19480
  async unregisterEffect(sandboxNameOrId, name) {
19306
19481
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
19307
19482
  const sandboxId = sandbox.sandboxId;
@@ -19324,12 +19499,6 @@ var Granular = class _Granular {
19324
19499
  }
19325
19500
  await this.syncSandboxEffectCatalog(sandboxId);
19326
19501
  }
19327
- /**
19328
- * Disconnect one sandbox-scoped effect host, or all of them when no sandbox is provided.
19329
- *
19330
- * This is primarily useful for long-lived helper processes such as generated
19331
- * `granular-effects.ts` scripts that need to shut down cleanly on SIGINT/SIGTERM.
19332
- */
19333
19502
  async disconnectEffects(sandboxNameOrId) {
19334
19503
  if (sandboxNameOrId) {
19335
19504
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
@@ -19754,9 +19923,6 @@ var Granular = class _Granular {
19754
19923
  throw new Error(`Ontology not found: ${ontologyNameOrId}`);
19755
19924
  return result.items[0].sandboxId;
19756
19925
  }
19757
- /**
19758
- * Make an authenticated API request
19759
- */
19760
19926
  async request(path, options = {}) {
19761
19927
  const url = `${this.httpUrl}${path}`;
19762
19928
  if (this.debugHttp) {
@@ -19806,6 +19972,33 @@ var Granular = class _Granular {
19806
19972
  throw new Error(`Granular API Error: exhausted retries for ${url}`);
19807
19973
  }
19808
19974
  };
19975
+ _init3 = __decoratorStart(null);
19976
+ __decorateElement(_init3, 1, "openEnvironment", _openEnvironment_dec, _Granular);
19977
+ __decorateElement(_init3, 1, "getActiveEnvironmentForUser", _getActiveEnvironmentForUser_dec, _Granular);
19978
+ __decorateElement(_init3, 1, "getEnvironmentForUser", _getEnvironmentForUser_dec, _Granular);
19979
+ __decorateElement(_init3, 1, "adoptEnvironmentForUser", _adoptEnvironmentForUser_dec, _Granular);
19980
+ __decorateElement(_init3, 1, "connect", _connect_dec, _Granular);
19981
+ __decorateElement(_init3, 1, "listSessions", _listSessions_dec2, _Granular);
19982
+ __decorateElement(_init3, 1, "createSession", _createSession_dec2, _Granular);
19983
+ __decorateElement(_init3, 1, "connectSession", _connectSession_dec2, _Granular);
19984
+ __decorateElement(_init3, 1, "closeSession", _closeSession_dec2, _Granular);
19985
+ __decorateElement(_init3, 1, "reopenSession", _reopenSession_dec, _Granular);
19986
+ __decorateElement(_init3, 1, "registerEffect", _registerEffect_dec, _Granular);
19987
+ __decorateElement(_init3, 1, "registerEffects", _registerEffects_dec, _Granular);
19988
+ __decorateElement(_init3, 1, "unregisterEffect", _unregisterEffect_dec, _Granular);
19989
+ __decorateElement(_init3, 1, "disconnectEffects", _disconnectEffects_dec, _Granular);
19990
+ __decorateElement(_init3, 1, "request", _request_dec, _Granular);
19991
+ __decorateElement(_init3, 13, "transport", _transport_dec, _Granular);
19992
+ __decorateElement(_init3, 13, "effectHosts", _effectHosts_dec, _Granular);
19993
+ __decorateElement(_init3, 13, "sessions", _sessions_dec2, _Granular);
19994
+ __decorateElement(_init3, 13, "environmentAccess", _environmentAccess_dec, _Granular);
19995
+ _Granular = __decorateElement(_init3, 0, "Granular", _Granular_decorators, _Granular);
19996
+ __publicField(_Granular, "transport", __runInitializers(_init3, 8, _Granular)), __runInitializers(_init3, 11, _Granular);
19997
+ __publicField(_Granular, "effectHosts", __runInitializers(_init3, 12, _Granular)), __runInitializers(_init3, 15, _Granular);
19998
+ __publicField(_Granular, "sessions", __runInitializers(_init3, 16, _Granular)), __runInitializers(_init3, 19, _Granular);
19999
+ __publicField(_Granular, "environmentAccess", __runInitializers(_init3, 20, _Granular)), __runInitializers(_init3, 23, _Granular);
20000
+ __runInitializers(_init3, 1, _Granular);
20001
+ var Granular = _Granular;
19809
20002
 
19810
20003
  // src/environment-setup.ts
19811
20004
  var EnvironmentSetupTerminalError = class extends Error {
@@ -24558,7 +24751,7 @@ function createOnboardingIncrementalRunner(options) {
24558
24751
  let again = false;
24559
24752
  let generation2 = 0;
24560
24753
  let unsubscribe;
24561
- const publish = (next) => {
24754
+ const publish2 = (next) => {
24562
24755
  status = next;
24563
24756
  try {
24564
24757
  options.onStatus?.(next);
@@ -24573,21 +24766,21 @@ function createOnboardingIncrementalRunner(options) {
24573
24766
  try {
24574
24767
  if (active) options.source.scheduleRetry(wake);
24575
24768
  } catch {
24576
- return publish({
24769
+ return publish2({
24577
24770
  status: "unknown",
24578
24771
  message: "Product retry scheduler is unavailable."
24579
24772
  });
24580
24773
  }
24581
- return publish(value);
24774
+ return publish2(value);
24582
24775
  };
24583
24776
  const execute = async () => {
24584
24777
  const started = generation2;
24585
24778
  const interrupted = () => started !== generation2;
24586
- const stopped = () => publish({
24779
+ const stopped = () => publish2({
24587
24780
  status: "unknown",
24588
24781
  message: "Change source is stopped; freshness is unknown."
24589
24782
  });
24590
- publish({ status: "checking" });
24783
+ publish2({ status: "checking" });
24591
24784
  let cursor;
24592
24785
  try {
24593
24786
  cursor = await options.source.readCheckpoint();
@@ -24655,7 +24848,7 @@ function createOnboardingIncrementalRunner(options) {
24655
24848
  eventId: item.change.eventId,
24656
24849
  observationId: receipt.observationId
24657
24850
  };
24658
- return next.status === "failed" ? publish(next) : defer(next);
24851
+ return next.status === "failed" ? publish2(next) : defer(next);
24659
24852
  }
24660
24853
  try {
24661
24854
  if (!await options.source.advanceCheckpoint(cursor, item.cursor))
@@ -24678,13 +24871,13 @@ function createOnboardingIncrementalRunner(options) {
24678
24871
  visited.add(cursor);
24679
24872
  }
24680
24873
  if (page.caughtUp)
24681
- return publish({ status: "source_current", checkedAt: Date.now() });
24874
+ return publish2({ status: "source_current", checkedAt: Date.now() });
24682
24875
  if (!page.events.length)
24683
24876
  return defer({
24684
24877
  status: "unknown",
24685
24878
  message: "Source has not established a current high-water mark."
24686
24879
  });
24687
- publish({ status: "catching_up" });
24880
+ publish2({ status: "catching_up" });
24688
24881
  }
24689
24882
  return defer({ status: "catching_up" });
24690
24883
  };
@@ -24711,7 +24904,7 @@ function createOnboardingIncrementalRunner(options) {
24711
24904
  try {
24712
24905
  await options.retryObservation(status.observationId);
24713
24906
  } catch {
24714
- return publish({
24907
+ return publish2({
24715
24908
  status: "unknown",
24716
24909
  message: "Projection retry could not be confirmed; retain the source checkpoint.",
24717
24910
  observationId: status.observationId
@@ -24728,7 +24921,7 @@ function createOnboardingIncrementalRunner(options) {
24728
24921
  } catch {
24729
24922
  active = false;
24730
24923
  unsubscribe = void 0;
24731
- publish({ status: "unknown", message: "Change source subscription is unavailable; retry start." });
24924
+ publish2({ status: "unknown", message: "Change source subscription is unavailable; retry start." });
24732
24925
  return;
24733
24926
  }
24734
24927
  wake();
@@ -24738,7 +24931,7 @@ function createOnboardingIncrementalRunner(options) {
24738
24931
  generation2++;
24739
24932
  unsubscribe?.();
24740
24933
  unsubscribe = void 0;
24741
- publish({
24934
+ publish2({
24742
24935
  status: "unknown",
24743
24936
  message: "Change source is stopped; freshness is unknown."
24744
24937
  });
@@ -24832,7 +25025,7 @@ var SourceMutationRejected = class extends Error {
24832
25025
  this.providerFailure = providerFailure;
24833
25026
  }
24834
25027
  };
24835
- function identity(i) {
25028
+ function identity2(i) {
24836
25029
  if (!i.context.sandboxId || !i.context.environmentId || !i.context.user?.subjectId || !i.operationId || !i.effectKey)
24837
25030
  throw Error("Source commit storage requires trusted invocation scope");
24838
25031
  return {
@@ -24881,7 +25074,7 @@ function sqliteCommitStorage(db) {
24881
25074
  accepted INTEGER NOT NULL DEFAULT 0, attempts INTEGER NOT NULL DEFAULT 0, last_error TEXT,
24882
25075
  PRIMARY KEY(scope,operation_id), UNIQUE(scope,invocation_id));`);
24883
25076
  const prior = (i) => {
24884
- const k = identity(i);
25077
+ const k = identity2(i);
24885
25078
  const row3 = db.query(
24886
25079
  "SELECT * FROM granular_source_commits WHERE scope=? AND operation_id=?"
24887
25080
  ).get(k.scope, i.operationId);
@@ -24890,7 +25083,7 @@ function sqliteCommitStorage(db) {
24890
25083
  return row3;
24891
25084
  };
24892
25085
  const save2 = (i, receipt, request) => {
24893
- const k = identity(i);
25086
+ const k = identity2(i);
24894
25087
  db.query(
24895
25088
  "INSERT INTO granular_source_commits(scope,operation_id,fingerprint,sandbox_id,invocation_id,receipt_json,commit_json) VALUES(?,?,?,?,?,?,?)"
24896
25089
  ).run(