@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.
@@ -29,11 +29,58 @@ var path__default = /*#__PURE__*/_interopDefault(path);
29
29
  var OpenAI__default = /*#__PURE__*/_interopDefault(OpenAI);
30
30
  var Automerge__namespace = /*#__PURE__*/_interopNamespace(Automerge);
31
31
 
32
+ var __create = Object.create;
32
33
  var __defProp = Object.defineProperty;
34
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
35
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
36
+ var __typeError = (msg) => {
37
+ throw TypeError(msg);
38
+ };
39
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
40
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
33
41
  var __export = (target, all) => {
34
42
  for (var name in all)
35
43
  __defProp(target, name, { get: all[name], enumerable: true });
36
44
  };
45
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
46
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
47
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
48
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
49
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
50
+ var __runInitializers = (array, flags, self, value) => {
51
+ 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);
52
+ return value;
53
+ };
54
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
55
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
56
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
57
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
58
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
59
+ return __privateGet(this, extra);
60
+ }, set [name](x) {
61
+ return __privateSet(this, extra, x);
62
+ } }, name));
63
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
64
+ for (var i = decorators.length - 1; i >= 0; i--) {
65
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
66
+ if (k) {
67
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
68
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
69
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
70
+ }
71
+ 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;
72
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
73
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
74
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
75
+ }
76
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
77
+ };
78
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
79
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
80
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
81
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
82
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
83
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
37
84
 
38
85
  // src/customer-skill-authorization.ts
39
86
  var secret = () => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
@@ -7416,7 +7463,7 @@ function requireTransientFeedbackItem(value) {
7416
7463
  }
7417
7464
  return item;
7418
7465
  }
7419
- function createFeedPublisher(publish) {
7466
+ function createFeedPublisher(publish2) {
7420
7467
  const makeHandle = (initial) => {
7421
7468
  let current = initial;
7422
7469
  let mutationQueue = Promise.resolve();
@@ -7442,7 +7489,7 @@ function createFeedPublisher(publish) {
7442
7489
  const reservedOperationId = options.operationId || operationId("feed_transient_update");
7443
7490
  const reservedOptions = { ...options };
7444
7491
  return enqueueMutation(async () => {
7445
- const response = await publish("feed.transient.update", {
7492
+ const response = await publish2("feed.transient.update", {
7446
7493
  transientId: current.id,
7447
7494
  expectedRevision: current.revision,
7448
7495
  text,
@@ -7457,7 +7504,7 @@ function createFeedPublisher(publish) {
7457
7504
  const reservedOperationId = options.operationId || operationId("feed_transient_settle");
7458
7505
  const reservedOptions = { ...options };
7459
7506
  return enqueueMutation(async () => {
7460
- const response = await publish("feed.transient.settle", {
7507
+ const response = await publish2("feed.transient.settle", {
7461
7508
  transientId: current.id,
7462
7509
  expectedRevision: current.revision,
7463
7510
  ...text === void 0 ? {} : { text },
@@ -7480,7 +7527,7 @@ function createFeedPublisher(publish) {
7480
7527
  return {
7481
7528
  async feedback(text, options = {}) {
7482
7529
  return requireFeedbackItem(
7483
- await publish("feed.feedback", {
7530
+ await publish2("feed.feedback", {
7484
7531
  text,
7485
7532
  ...options,
7486
7533
  operationId: options.operationId || operationId("feed_feedback")
@@ -7489,7 +7536,7 @@ function createFeedPublisher(publish) {
7489
7536
  },
7490
7537
  async transientFeedback(text, options = {}) {
7491
7538
  const item = requireTransientFeedbackItem(
7492
- await publish("feed.transient.create", {
7539
+ await publish2("feed.transient.create", {
7493
7540
  text,
7494
7541
  ...options,
7495
7542
  operationId: options.operationId || operationId("feed_transient_create")
@@ -8508,10 +8555,340 @@ var noteMetamodelPackage = defineMetamodelPackage({
8508
8555
  }
8509
8556
  });
8510
8557
 
8558
+ // ../fractory/dist/annotations.js
8559
+ var interfaceBrand = Symbol("fractal.interface");
8560
+ var blocks = /* @__PURE__ */ new WeakMap();
8561
+ var wrappers = /* @__PURE__ */ new WeakMap();
8562
+ var listeners = /* @__PURE__ */ new Set();
8563
+ var host;
8564
+ function publish(event, adapter) {
8565
+ try {
8566
+ adapter?.emit(event);
8567
+ } catch {
8568
+ }
8569
+ for (const listener of listeners) {
8570
+ try {
8571
+ listener(event);
8572
+ } catch {
8573
+ }
8574
+ }
8575
+ }
8576
+ function identity(value) {
8577
+ if (!value.trim())
8578
+ throw new Error("Fractal identity must not be empty");
8579
+ return value;
8580
+ }
8581
+ function Block(id3, options = {}) {
8582
+ const definition = typeof id3 === "string" ? { ...options, id: identity(id3) } : { ...id3, id: identity(id3.id) };
8583
+ return (target, _context) => {
8584
+ blocks.set(target, definition);
8585
+ return target;
8586
+ };
8587
+ }
8588
+ function makeInterface(owner, name, options) {
8589
+ return Object.freeze({
8590
+ [interfaceBrand]: true,
8591
+ name,
8592
+ options: Object.freeze({ ...options }),
8593
+ get blockId() {
8594
+ const definition = blocks.get(owner());
8595
+ if (!definition)
8596
+ throw new Error(`Interface ${name} needs an annotated block`);
8597
+ return definition.id;
8598
+ },
8599
+ get id() {
8600
+ return options.id || `${this.blockId}::${name}`;
8601
+ }
8602
+ });
8603
+ }
8604
+ function Interface(options = {}, details = {}) {
8605
+ if (typeof options === "string") {
8606
+ const id3 = identity(options), name = id3.split("/").slice(-1)[0];
8607
+ if (details.parent)
8608
+ return makeInterface(details.parent, name, { ...details, id: id3 });
8609
+ return Object.freeze({
8610
+ [interfaceBrand]: true,
8611
+ id: id3,
8612
+ name,
8613
+ blockId: id3.includes("/") ? id3.slice(0, id3.lastIndexOf("/")) : "factory",
8614
+ options: Object.freeze({ ...details, id: id3 })
8615
+ });
8616
+ }
8617
+ if ("parent" in options)
8618
+ return makeInterface(options.parent, identity(options.id).split("/").slice(-1)[0], options);
8619
+ return interfaceDecorator(options);
8620
+ }
8621
+ function interfaceDecorator(options) {
8622
+ function decorate(target, context) {
8623
+ if (typeof context === "object") {
8624
+ if (!context.static || context.private)
8625
+ throw new Error("@Interface requires a public static field");
8626
+ context.addInitializer(function() {
8627
+ const owner = this;
8628
+ if (!owner[context.name]?.[interfaceBrand])
8629
+ Object.defineProperty(owner, context.name, {
8630
+ value: makeInterface(() => owner, String(context.name), options),
8631
+ writable: false,
8632
+ configurable: true
8633
+ });
8634
+ });
8635
+ return function() {
8636
+ return makeInterface(() => this, String(context.name), options);
8637
+ };
8638
+ }
8639
+ const value = makeInterface(() => target, String(context), options);
8640
+ Object.defineProperty(target, context, {
8641
+ value,
8642
+ writable: false,
8643
+ configurable: true
8644
+ });
8645
+ return void 0;
8646
+ }
8647
+ return decorate;
8648
+ }
8649
+ var FactoryViolation = class extends Error {
8650
+ phase;
8651
+ cause;
8652
+ constructor(phase, cause) {
8653
+ super(`Fractal ${phase} requirement failed`);
8654
+ this.phase = phase;
8655
+ this.cause = cause;
8656
+ this.name = "FactoryViolation";
8657
+ }
8658
+ };
8659
+ function validate(parser, value) {
8660
+ const result = parser?.parse(value);
8661
+ if (result && typeof result.then === "function") {
8662
+ void Promise.resolve(result).catch(() => {
8663
+ });
8664
+ throw new Error("Fractal runtime validators must be synchronous");
8665
+ }
8666
+ }
8667
+ function wrap(fn, name, reference, process2, options = {}) {
8668
+ const previous = wrappers.get(fn);
8669
+ if (previous) {
8670
+ fn = previous.original;
8671
+ reference ||= previous.reference;
8672
+ process2 ||= previous.process;
8673
+ options = { ...previous.options, ...options };
8674
+ }
8675
+ const wrapped = function(...args) {
8676
+ const api = reference?.();
8677
+ if (reference && (!api || api[interfaceBrand] !== true))
8678
+ throw new Error("@Method requires an initialized typed interface reference");
8679
+ const adapter = host;
8680
+ if (!listeners.size && !options.contract && !api?.options.auth)
8681
+ return fn.apply(this, args);
8682
+ const id3 = crypto.randomUUID();
8683
+ const frame = {
8684
+ targetId: process2?.id || `${api.id}#${options.name || name || fn.name || "call"}`,
8685
+ traceId: id3,
8686
+ runId: id3
8687
+ };
8688
+ let codeRevision;
8689
+ try {
8690
+ codeRevision = adapter?.codeRevision?.();
8691
+ } catch {
8692
+ }
8693
+ const started = performance.now();
8694
+ let terminal = false;
8695
+ const base = {
8696
+ targetId: frame.targetId,
8697
+ ...{},
8698
+ id: id3,
8699
+ traceId: frame.traceId,
8700
+ ...codeRevision ? { codeRevision } : {},
8701
+ runId: frame.runId,
8702
+ ...{},
8703
+ ...{},
8704
+ blockId: process2?.id || api.blockId,
8705
+ ...api ? { interfaceId: api.id } : {},
8706
+ method: options.name || name || fn.name || "call"
8707
+ };
8708
+ const emit = (status, failure) => {
8709
+ if (status !== "started") {
8710
+ if (terminal)
8711
+ return;
8712
+ terminal = true;
8713
+ frame.finished = true;
8714
+ }
8715
+ publish({
8716
+ ...base,
8717
+ timestamp: Date.now(),
8718
+ status,
8719
+ ...status !== "started" ? { durationMs: performance.now() - started } : {},
8720
+ ...failure ? { failure } : {}
8721
+ }, adapter);
8722
+ };
8723
+ const execute = () => {
8724
+ emit("started");
8725
+ let phase = "auth";
8726
+ const failed = (error) => {
8727
+ emit("failed", phase);
8728
+ throw error;
8729
+ };
8730
+ const invoke = () => {
8731
+ phase = "input";
8732
+ validate(options.contract?.args, args);
8733
+ phase = "execution";
8734
+ const value = fn.apply(this, args);
8735
+ const complete = (result) => {
8736
+ phase = "output";
8737
+ validate(options.contract?.result, result);
8738
+ emit("completed");
8739
+ return result;
8740
+ };
8741
+ if (value && typeof value.then === "function") {
8742
+ if (options.contract?.result)
8743
+ return Promise.resolve(value).then(complete).catch(failed);
8744
+ void Promise.resolve(value).then(() => emit("completed"), () => emit("failed", "execution"));
8745
+ return value;
8746
+ }
8747
+ return complete(value);
8748
+ };
8749
+ try {
8750
+ const authorized = api?.options.auth?.({
8751
+ receiver: this,
8752
+ args,
8753
+ context: adapter?.context?.()
8754
+ });
8755
+ if (authorized && typeof authorized === "object" && typeof authorized.then === "function") {
8756
+ if (fn.constructor.name !== "AsyncFunction") {
8757
+ void authorized.catch(() => {
8758
+ });
8759
+ throw new Error("Async auth requires an async method");
8760
+ }
8761
+ return authorized.then((allowed) => {
8762
+ if (allowed === false)
8763
+ throw new FactoryViolation("auth", false);
8764
+ return invoke();
8765
+ }).catch(failed);
8766
+ }
8767
+ if (authorized === false)
8768
+ throw new FactoryViolation("auth", false);
8769
+ return invoke();
8770
+ } catch (error) {
8771
+ return failed(error);
8772
+ }
8773
+ };
8774
+ const run = () => execute();
8775
+ try {
8776
+ return run();
8777
+ } catch (error) {
8778
+ if (fn.constructor.name === "AsyncFunction")
8779
+ return Promise.reject(error);
8780
+ throw error;
8781
+ }
8782
+ };
8783
+ Object.defineProperty(wrapped, "name", {
8784
+ value: options.name || name || fn.name,
8785
+ configurable: true
8786
+ });
8787
+ Object.defineProperty(wrapped, "length", {
8788
+ value: fn.length,
8789
+ configurable: true
8790
+ });
8791
+ if (process2)
8792
+ blocks.set(wrapped, process2);
8793
+ wrappers.set(wrapped, { original: fn, reference, process: process2, options });
8794
+ return wrapped;
8795
+ }
8796
+ function callableDecorator(reference, process2, options = {}) {
8797
+ function decorate(target, context, descriptor) {
8798
+ if (descriptor) {
8799
+ descriptor.value = wrap(descriptor.value, String(context), reference, process2, options);
8800
+ return descriptor;
8801
+ }
8802
+ const fn = target;
8803
+ return wrap(fn, typeof context === "object" ? String(context.name) : fn.name, reference, process2, options);
8804
+ }
8805
+ return decorate;
8806
+ }
8807
+ function Method(reference, options = {}) {
8808
+ return callableDecorator(reference, void 0, options);
8809
+ }
8810
+ function Process(id3, options = {}) {
8811
+ const definition = typeof id3 === "string" ? { ...options, id: identity(id3) } : { ...id3, id: identity(id3.id) };
8812
+ return callableDecorator(void 0, definition);
8813
+ }
8814
+
8511
8815
  // ../policy-engine/src/index.ts
8816
+ var DECISIONS = /* @__PURE__ */ new Set(["allow", "confirm", "deny"]);
8817
+ var BUILTIN_PROFILE_NAMES = ["allow-all", "confirm-all", "deny-all"];
8818
+ function getBuiltinPermissionProfiles() {
8819
+ return [
8820
+ {
8821
+ schemaVersion: 1,
8822
+ name: "allow-all",
8823
+ label: "Allow all",
8824
+ description: "Every declared action is visible unless a manifest policy denies it.",
8825
+ source: "builtin",
8826
+ defaults: { actionPolicy: "allow" },
8827
+ policies: [],
8828
+ actions: []
8829
+ },
8830
+ {
8831
+ schemaVersion: 1,
8832
+ name: "confirm-all",
8833
+ label: "Confirm all",
8834
+ description: "Every declared action requires user confirmation before execution.",
8835
+ source: "builtin",
8836
+ defaults: { actionPolicy: "confirm" },
8837
+ policies: [],
8838
+ actions: []
8839
+ },
8840
+ {
8841
+ schemaVersion: 1,
8842
+ name: "deny-all",
8843
+ label: "Deny all",
8844
+ description: "No declared action is invocable.",
8845
+ source: "builtin",
8846
+ defaults: { actionPolicy: "deny" },
8847
+ policies: [],
8848
+ actions: []
8849
+ }
8850
+ ];
8851
+ }
8852
+ function stableStringify(value) {
8853
+ return JSON.stringify(sortJson(value));
8854
+ }
8855
+ async function digestJson(value) {
8856
+ const payload = stableStringify(value);
8857
+ const cryptoLike = globalThis.crypto;
8858
+ if (cryptoLike?.subtle) {
8859
+ const data = new TextEncoder().encode(payload);
8860
+ const hash3 = await cryptoLike.subtle.digest("SHA-256", data);
8861
+ const hex = Array.from(new Uint8Array(hash3)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
8862
+ return `sha256:${hex}`;
8863
+ }
8864
+ let hash2 = 2166136261;
8865
+ for (let index = 0; index < payload.length; index += 1) {
8866
+ hash2 ^= payload.charCodeAt(index);
8867
+ hash2 = Math.imul(hash2, 16777619);
8868
+ }
8869
+ return `fnv1a:${(hash2 >>> 0).toString(16).padStart(8, "0")}`;
8870
+ }
8871
+ function sortJson(value) {
8872
+ if (Array.isArray(value)) return value.map(sortJson);
8873
+ if (isRecord(value)) {
8874
+ return Object.fromEntries(
8875
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, sortJson(child)])
8876
+ );
8877
+ }
8878
+ return value;
8879
+ }
8512
8880
  function isRecord(value) {
8513
8881
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
8514
8882
  }
8883
+ function normalizeProfileName(name) {
8884
+ if (typeof name !== "string") return null;
8885
+ const trimmed = name.trim();
8886
+ if (!/^[a-z0-9][a-z0-9._-]{1,63}$/.test(trimmed)) return null;
8887
+ return trimmed;
8888
+ }
8889
+ function normalizeDecision(value) {
8890
+ return DECISIONS.has(value) ? value : null;
8891
+ }
8515
8892
  function normalizePath(value) {
8516
8893
  if (Array.isArray(value)) {
8517
8894
  return value.map((part) => String(part)).filter(Boolean);
@@ -8584,6 +8961,131 @@ function normalizeCondition(input) {
8584
8961
  "Policy condition must contain all, any, not, input, object, or stateMachine"
8585
8962
  );
8586
8963
  }
8964
+ function readPath(root, path2) {
8965
+ let current = root;
8966
+ for (const part of path2) {
8967
+ if (!isRecord(current) && !Array.isArray(current)) {
8968
+ return { exists: false, value: void 0 };
8969
+ }
8970
+ if (!(part in current)) {
8971
+ return { exists: false, value: void 0 };
8972
+ }
8973
+ current = current[part];
8974
+ }
8975
+ return { exists: true, value: current };
8976
+ }
8977
+ function evaluateCondition(condition, context) {
8978
+ switch (condition.kind) {
8979
+ case "always":
8980
+ return true;
8981
+ case "all":
8982
+ return condition.conditions.every(
8983
+ (child) => evaluateCondition(child, context)
8984
+ );
8985
+ case "any":
8986
+ return condition.conditions.some(
8987
+ (child) => evaluateCondition(child, context)
8988
+ );
8989
+ case "not":
8990
+ return !evaluateCondition(condition.condition, context);
8991
+ case "predicate":
8992
+ return evaluatePredicate(condition, context);
8993
+ }
8994
+ }
8995
+ function evaluatePredicate(predicate, context) {
8996
+ const target = predicate.source === "input" ? context.input : predicate.source === "object" ? context.object : context.stateMachines;
8997
+ const { exists, value } = readPath(target || {}, predicate.path);
8998
+ if (predicate.operator === "exists") return exists;
8999
+ if (!exists) return false;
9000
+ const expected = predicate.value;
9001
+ switch (predicate.operator) {
9002
+ case "eq":
9003
+ return value === expected;
9004
+ case "neq":
9005
+ return value !== expected;
9006
+ case "gt":
9007
+ return typeof value === "number" && typeof expected === "number" && value > expected;
9008
+ case "gte":
9009
+ return typeof value === "number" && typeof expected === "number" && value >= expected;
9010
+ case "lt":
9011
+ return typeof value === "number" && typeof expected === "number" && value < expected;
9012
+ case "lte":
9013
+ return typeof value === "number" && typeof expected === "number" && value <= expected;
9014
+ case "contains":
9015
+ return Array.isArray(value) ? value.includes(expected) : typeof value === "string" && typeof expected === "string" && value.includes(expected);
9016
+ case "not_contains":
9017
+ return Array.isArray(value) ? !value.includes(expected) : typeof value === "string" && typeof expected === "string" && !value.includes(expected);
9018
+ case "starts_with":
9019
+ return typeof value === "string" && typeof expected === "string" && value.startsWith(expected);
9020
+ case "ends_with":
9021
+ return typeof value === "string" && typeof expected === "string" && value.endsWith(expected);
9022
+ }
9023
+ }
9024
+ function matchRule(rule, context) {
9025
+ if (!evaluateCondition(rule.condition, context)) return null;
9026
+ return {
9027
+ id: rule.id,
9028
+ outcome: rule.outcome,
9029
+ origin: rule.origin,
9030
+ reason: rule.reason,
9031
+ summary: rule.summary
9032
+ };
9033
+ }
9034
+ function evaluatePolicies(input) {
9035
+ const context = input.context || {};
9036
+ const manifestRules = input.manifestRules || [];
9037
+ const profileRules = input.profileRules || [];
9038
+ const defaultActionPolicy = input.defaultActionPolicy || "deny";
9039
+ const buckets = [
9040
+ {
9041
+ outcome: "deny",
9042
+ rules: manifestRules.filter((rule) => rule.outcome === "deny")
9043
+ },
9044
+ {
9045
+ outcome: "deny",
9046
+ rules: profileRules.filter((rule) => rule.outcome === "deny")
9047
+ },
9048
+ {
9049
+ outcome: "confirm",
9050
+ rules: manifestRules.filter((rule) => rule.outcome === "confirm")
9051
+ },
9052
+ {
9053
+ outcome: "confirm",
9054
+ rules: profileRules.filter((rule) => rule.outcome === "confirm")
9055
+ },
9056
+ {
9057
+ outcome: "allow",
9058
+ rules: profileRules.filter((rule) => rule.outcome === "allow")
9059
+ }
9060
+ ];
9061
+ for (const bucket of buckets) {
9062
+ const matches = bucket.rules.map((rule) => matchRule(rule, context)).filter((match) => match !== null);
9063
+ if (matches.length > 0) return { outcome: bucket.outcome, matches };
9064
+ }
9065
+ return {
9066
+ outcome: defaultActionPolicy,
9067
+ matches: defaultActionPolicy === "deny" ? [] : [
9068
+ {
9069
+ id: `profile-default-${defaultActionPolicy}`,
9070
+ outcome: defaultActionPolicy,
9071
+ origin: {
9072
+ kind: "permissionProfile",
9073
+ profileName: "active",
9074
+ source: "permissionProfile"
9075
+ },
9076
+ summary: `Profile default policy is ${defaultActionPolicy}`
9077
+ }
9078
+ ]
9079
+ };
9080
+ }
9081
+ function ruleSummary(outcome, reason, condition) {
9082
+ if (reason) return reason;
9083
+ if (condition.kind === "always") return `${capitalize(outcome)} always`;
9084
+ return `${capitalize(outcome)} when ${summarizeCondition(condition)}`;
9085
+ }
9086
+ function capitalize(value) {
9087
+ return value.slice(0, 1).toUpperCase() + value.slice(1);
9088
+ }
8587
9089
  function summarizeCondition(condition) {
8588
9090
  switch (condition.kind) {
8589
9091
  case "always":
@@ -8601,6 +9103,534 @@ function summarizeCondition(condition) {
8601
9103
  }
8602
9104
  }
8603
9105
  }
9106
+ function makeRule(input) {
9107
+ const condition = input.condition || { kind: "always" };
9108
+ return {
9109
+ ...input,
9110
+ condition,
9111
+ summary: ruleSummary(input.outcome, input.reason, condition)
9112
+ };
9113
+ }
9114
+ function actionIdentity(action, on) {
9115
+ return on ? `${on}:${action}` : `global:${action}`;
9116
+ }
9117
+ function normalizeAttachedClass(value) {
9118
+ if (!value) return null;
9119
+ if (!value.startsWith("@")) return value;
9120
+ const slashIndex = value.indexOf("/");
9121
+ return slashIndex === -1 ? value : value.slice(slashIndex + 1);
9122
+ }
9123
+ function resolveEffectReference(effects, action, on) {
9124
+ const normalizedOn = normalizeAttachedClass(on);
9125
+ const matches = effects.filter((effect) => {
9126
+ if (effect.name !== action) return false;
9127
+ const attachedClass = normalizeAttachedClass(effect.attachedClass);
9128
+ return normalizedOn ? attachedClass === normalizedOn : !attachedClass;
9129
+ });
9130
+ if (matches.length === 1) return matches[0];
9131
+ if (!normalizedOn) {
9132
+ const byName = effects.filter((effect) => effect.name === action);
9133
+ if (byName.length > 1) {
9134
+ const classes = byName.map(
9135
+ (effect) => normalizeAttachedClass(effect.attachedClass) || "global"
9136
+ ).join(", ");
9137
+ throw new Error(
9138
+ `Action "${action}" exists on ${classes}. Add "on" to disambiguate.`
9139
+ );
9140
+ }
9141
+ }
9142
+ if (matches.length > 1) {
9143
+ throw new Error(`Action "${action}" on "${String(on)}" is ambiguous.`);
9144
+ }
9145
+ throw new Error(
9146
+ on ? `Action "${action}" on "${on}" was not found.` : `Global action "${action}" was not found.`
9147
+ );
9148
+ }
9149
+ function manifestPolicyRulesForEffect(effect, manifestId) {
9150
+ const policies = isRecord(effect.metamodels?.policies) ? effect.metamodels?.policies : null;
9151
+ if (!policies) return [];
9152
+ const rules = [];
9153
+ const add = (outcome, specs, prefix) => {
9154
+ if (!Array.isArray(specs)) return;
9155
+ specs.forEach((spec, index) => {
9156
+ if (!isRecord(spec)) {
9157
+ throw new Error(
9158
+ `Manifest policy ${prefix}[${index}] for ${effect.effectKey} must be an object`
9159
+ );
9160
+ }
9161
+ const condition = normalizeCondition(spec.when);
9162
+ rules.push(
9163
+ makeRule({
9164
+ id: typeof spec.id === "string" ? spec.id : `manifest-${prefix}-${effect.effectKey}-${index + 1}`,
9165
+ origin: { kind: "manifest", manifestId, effectKey: effect.effectKey },
9166
+ outcome,
9167
+ reason: typeof spec.reason === "string" ? spec.reason : void 0,
9168
+ condition
9169
+ })
9170
+ );
9171
+ });
9172
+ };
9173
+ add("deny", policies.denyWhen, "denyWhen");
9174
+ add("confirm", policies.confirmWhen, "confirmWhen");
9175
+ add("allow", policies.allowWhen, "allowWhen");
9176
+ return rules;
9177
+ }
9178
+ function inputSchemaHasField(effect, path2) {
9179
+ if (path2.length === 0) return false;
9180
+ const properties = isRecord(effect.inputSchema?.properties) ? effect.inputSchema?.properties : {};
9181
+ return path2[0] in properties;
9182
+ }
9183
+ function validateLimitBands(effect, action, warnings) {
9184
+ const limits = action.limits || [];
9185
+ const byInput = /* @__PURE__ */ new Map();
9186
+ limits.forEach((limit, index) => {
9187
+ const path2 = normalizePath(limit.input);
9188
+ if (path2.length === 0) {
9189
+ throw new Error(`Limit ${index + 1} on ${action.action} requires input`);
9190
+ }
9191
+ if (!inputSchemaHasField(effect, path2)) {
9192
+ throw new Error(
9193
+ `Limit ${index + 1} on ${action.action} references unsupported input field "${path2.join(".")}"`
9194
+ );
9195
+ }
9196
+ if (!normalizeDecision(limit.decision)) {
9197
+ throw new Error(
9198
+ `Limit ${index + 1} on ${action.action} has invalid decision`
9199
+ );
9200
+ }
9201
+ if (limit.upTo === void 0 === (limit.above === void 0)) {
9202
+ throw new Error(
9203
+ `Limit ${index + 1} on ${action.action} must define exactly one of upTo or above`
9204
+ );
9205
+ }
9206
+ if (limit.reason === void 0) {
9207
+ warnings.push(`Limit ${index + 1} on ${action.action} has no reason`);
9208
+ }
9209
+ const key = path2.join(".");
9210
+ byInput.set(key, [...byInput.get(key) || [], limit]);
9211
+ });
9212
+ for (const [input, bands] of byInput.entries()) {
9213
+ const thresholds = /* @__PURE__ */ new Set();
9214
+ let previousUpTo = -Infinity;
9215
+ for (const band of bands) {
9216
+ const value = band.upTo ?? band.above;
9217
+ const key = `${band.upTo === void 0 ? "above" : "upTo"}:${value}`;
9218
+ if (thresholds.has(key)) {
9219
+ throw new Error(
9220
+ `Duplicate limit threshold ${key} for input "${input}"`
9221
+ );
9222
+ }
9223
+ thresholds.add(key);
9224
+ if (band.upTo !== void 0) {
9225
+ if (band.upTo < previousUpTo) {
9226
+ throw new Error(`Unordered limit bands for input "${input}"`);
9227
+ }
9228
+ previousUpTo = band.upTo;
9229
+ }
9230
+ }
9231
+ }
9232
+ }
9233
+ function compileProfileActionRules(input) {
9234
+ const { profile, action, effect, warnings } = input;
9235
+ const origin = {
9236
+ kind: "permissionProfile",
9237
+ profileName: action.ownerProfileName || profile.name,
9238
+ source: profile.source || "permissionProfile"
9239
+ };
9240
+ const rules = [];
9241
+ const baseId = action.id || `${profile.name}-${effect.effectKey}`;
9242
+ if (action.allow === "always") {
9243
+ rules.push(
9244
+ makeRule({
9245
+ id: `${baseId}-allow`,
9246
+ origin,
9247
+ outcome: "allow",
9248
+ reason: action.reason
9249
+ })
9250
+ );
9251
+ }
9252
+ if (action.confirm === "always") {
9253
+ rules.push(
9254
+ makeRule({
9255
+ id: `${baseId}-confirm`,
9256
+ origin,
9257
+ outcome: "confirm",
9258
+ reason: action.reason
9259
+ })
9260
+ );
9261
+ }
9262
+ if (action.deny === "always") {
9263
+ rules.push(
9264
+ makeRule({
9265
+ id: `${baseId}-deny`,
9266
+ origin,
9267
+ outcome: "deny",
9268
+ reason: action.reason
9269
+ })
9270
+ );
9271
+ }
9272
+ const addConditional = (outcome, specs, suffix) => {
9273
+ (specs || []).forEach((spec, index) => {
9274
+ rules.push(
9275
+ makeRule({
9276
+ id: spec.id || `${baseId}-${suffix}-${index + 1}`,
9277
+ origin,
9278
+ outcome,
9279
+ reason: spec.reason,
9280
+ condition: normalizeCondition(spec.when)
9281
+ })
9282
+ );
9283
+ });
9284
+ };
9285
+ addConditional("allow", action.allowWhen, "allowWhen");
9286
+ addConditional("confirm", action.confirmWhen, "confirmWhen");
9287
+ addConditional("deny", action.denyWhen, "denyWhen");
9288
+ validateLimitBands(effect, action, warnings);
9289
+ const previousUpToByInput = /* @__PURE__ */ new Map();
9290
+ (action.limits || []).forEach((limit, index) => {
9291
+ const path2 = normalizePath(limit.input);
9292
+ const pathKey = path2.join(".");
9293
+ const lowerBound = previousUpToByInput.get(pathKey);
9294
+ const upperCondition = {
9295
+ kind: "predicate",
9296
+ source: "input",
9297
+ path: path2,
9298
+ operator: limit.upTo !== void 0 ? "lte" : "gt",
9299
+ value: limit.upTo ?? limit.above
9300
+ };
9301
+ const condition = lowerBound !== void 0 && limit.upTo !== void 0 ? {
9302
+ kind: "all",
9303
+ conditions: [
9304
+ {
9305
+ kind: "predicate",
9306
+ source: "input",
9307
+ path: path2,
9308
+ operator: "gt",
9309
+ value: lowerBound
9310
+ },
9311
+ upperCondition
9312
+ ]
9313
+ } : upperCondition;
9314
+ rules.push(
9315
+ makeRule({
9316
+ id: limit.id || `${baseId}-limit-${index + 1}`,
9317
+ origin,
9318
+ outcome: limit.decision,
9319
+ reason: limit.reason,
9320
+ condition
9321
+ })
9322
+ );
9323
+ if (limit.upTo !== void 0) previousUpToByInput.set(pathKey, limit.upTo);
9324
+ });
9325
+ return rules;
9326
+ }
9327
+ function flattenProfiles(profiles, errors) {
9328
+ const byName = /* @__PURE__ */ new Map();
9329
+ for (const profile of profiles) {
9330
+ const name = normalizeProfileName(profile.name);
9331
+ if (!name) {
9332
+ errors.push(`Invalid permission profile name: ${String(profile.name)}`);
9333
+ continue;
9334
+ }
9335
+ if (byName.has(name)) {
9336
+ errors.push(`Duplicate permission profile name: ${name}`);
9337
+ continue;
9338
+ }
9339
+ byName.set(name, {
9340
+ ...profile,
9341
+ name,
9342
+ defaultsOwnerName: profile.defaultsOwnerName || name,
9343
+ policies: (profile.policies || []).map((policy) => ({
9344
+ ...policy,
9345
+ ownerProfileName: policy.ownerProfileName || name
9346
+ })),
9347
+ actions: (profile.actions || []).map((action) => ({
9348
+ ...action,
9349
+ ownerProfileName: action.ownerProfileName || name
9350
+ }))
9351
+ });
9352
+ }
9353
+ const flattening = /* @__PURE__ */ new Set();
9354
+ const flattened = /* @__PURE__ */ new Map();
9355
+ const flatten = (name, depth) => {
9356
+ if (depth > 5) {
9357
+ errors.push(`Permission profile inheritance depth exceeds 5 at ${name}`);
9358
+ return null;
9359
+ }
9360
+ const existing = flattened.get(name);
9361
+ if (existing) return existing;
9362
+ const profile = byName.get(name);
9363
+ if (!profile) {
9364
+ errors.push(`Missing parent permission profile: ${name}`);
9365
+ return null;
9366
+ }
9367
+ if (flattening.has(name)) {
9368
+ errors.push(`Permission profile inheritance cycle detected at ${name}`);
9369
+ return null;
9370
+ }
9371
+ flattening.add(name);
9372
+ let result = profile;
9373
+ if (profile.extends) {
9374
+ if (profile.defaults !== void 0) {
9375
+ errors.push(
9376
+ `Permission profile "${name}" extends "${profile.extends}" and cannot define defaults`
9377
+ );
9378
+ }
9379
+ const parent = flatten(profile.extends, depth + 1);
9380
+ if (parent) {
9381
+ const actionMap = /* @__PURE__ */ new Map();
9382
+ for (const action of parent.actions || []) {
9383
+ actionMap.set(actionIdentity(action.action, action.on), action);
9384
+ }
9385
+ for (const action of profile.actions || []) {
9386
+ actionMap.set(actionIdentity(action.action, action.on), action);
9387
+ }
9388
+ result = {
9389
+ ...profile,
9390
+ defaults: parent.defaults,
9391
+ defaultsOwnerName: parent.defaultsOwnerName || parent.name,
9392
+ policies: [...parent.policies || [], ...profile.policies || []],
9393
+ actions: [...actionMap.values()]
9394
+ };
9395
+ }
9396
+ }
9397
+ flattening.delete(name);
9398
+ flattened.set(name, result);
9399
+ return result;
9400
+ };
9401
+ for (const name of byName.keys()) flatten(name, 0);
9402
+ return [...flattened.values()];
9403
+ }
9404
+ function compileProfile(input) {
9405
+ const { profile, effects, manifestRules, warnings } = input;
9406
+ const defaultActionPolicy = normalizeDecision(profile.defaults?.actionPolicy) || "deny";
9407
+ const actionRules = {};
9408
+ const addRules = (effectKey, rules) => {
9409
+ if (rules.length === 0) return;
9410
+ actionRules[effectKey] = [...actionRules[effectKey] || [], ...rules];
9411
+ };
9412
+ for (const policy of profile.policies || []) {
9413
+ const outcome = normalizeDecision(policy.outcome || policy.decision);
9414
+ if (!outcome)
9415
+ throw new Error(
9416
+ `Profile "${profile.name}" has a policy with invalid decision`
9417
+ );
9418
+ const condition = normalizeCondition(policy.when);
9419
+ const targetEffects = policy.action ? [resolveEffectReference(effects, policy.action, policy.on)] : effects;
9420
+ for (const effect of targetEffects) {
9421
+ addRules(effect.effectKey, [
9422
+ makeRule({
9423
+ id: policy.id || `${profile.name}-${effect.effectKey}-profile-policy`,
9424
+ origin: {
9425
+ kind: "permissionProfile",
9426
+ profileName: policy.ownerProfileName || profile.name,
9427
+ source: profile.source || "permissionProfile"
9428
+ },
9429
+ outcome,
9430
+ reason: policy.reason,
9431
+ condition
9432
+ })
9433
+ ]);
9434
+ }
9435
+ }
9436
+ for (const action of profile.actions || []) {
9437
+ const effect = resolveEffectReference(effects, action.action, action.on);
9438
+ addRules(
9439
+ effect.effectKey,
9440
+ compileProfileActionRules({ profile, action, effect, warnings })
9441
+ );
9442
+ }
9443
+ const actionVisibility = effects.filter((effect) => {
9444
+ const rules = actionRules[effect.effectKey] || [];
9445
+ const denyVisibilityRules = [
9446
+ ...manifestRules[effect.effectKey] || [],
9447
+ ...rules
9448
+ ];
9449
+ if (denyVisibilityRules.some(
9450
+ (rule) => rule.outcome === "deny" && rule.condition.kind === "always"
9451
+ )) {
9452
+ return false;
9453
+ }
9454
+ if (defaultActionPolicy === "allow" || defaultActionPolicy === "confirm")
9455
+ return true;
9456
+ return denyVisibilityRules.some(
9457
+ (rule) => rule.outcome === "allow" || rule.outcome === "confirm"
9458
+ );
9459
+ }).map((effect) => effect.effectKey).sort();
9460
+ const summaries = Object.entries(actionRules).flatMap(
9461
+ ([effectKey, rules]) => rules.map((rule) => `${effectKey}: ${rule.summary}`)
9462
+ ).sort();
9463
+ return {
9464
+ name: profile.name,
9465
+ label: profile.label,
9466
+ description: profile.description,
9467
+ source: profile.source || "permissionProfile",
9468
+ sourcePath: profile.sourcePath,
9469
+ defaultActionPolicy,
9470
+ defaultActionPolicyOwner: profile.defaultsOwnerName || profile.name,
9471
+ digest: "",
9472
+ actionRules,
9473
+ actionVisibility,
9474
+ summaries,
9475
+ flattened: profile
9476
+ };
9477
+ }
9478
+ function normalizeSourceProfiles(sources) {
9479
+ const sourceProfiles = (sources || []).filter((profile) => isRecord(profile)).map((profile) => ({
9480
+ ...profile,
9481
+ source: profile.source || "permissionProfile"
9482
+ }));
9483
+ const nonBuiltin = sourceProfiles.filter(
9484
+ (profile) => !BUILTIN_PROFILE_NAMES.includes(
9485
+ profile.name
9486
+ )
9487
+ );
9488
+ return [...getBuiltinPermissionProfiles(), ...nonBuiltin];
9489
+ }
9490
+ Process({
9491
+ description: "Compile product permission rules into a bundle that runtime checks can evaluate.",
9492
+ id: "granular-product/compilation/metamodels-policy-compilation/compile",
9493
+ label: "Compile policy bundle",
9494
+ benchmarks: ["./compile.bench.ts"],
9495
+ tests: ["./index.test.ts"]
9496
+ })(async function compilePolicyBundle2(input) {
9497
+ const errors = [];
9498
+ const warnings = [];
9499
+ const effects = [...input.effects].sort(
9500
+ (left, right) => left.effectKey.localeCompare(right.effectKey)
9501
+ );
9502
+ const profiles = flattenProfiles(
9503
+ normalizeSourceProfiles(input.profileSources),
9504
+ errors
9505
+ );
9506
+ const manifestRules = {};
9507
+ for (const effect of effects) {
9508
+ try {
9509
+ const rules = manifestPolicyRulesForEffect(effect, input.manifestId);
9510
+ if (rules.length > 0) manifestRules[effect.effectKey] = rules;
9511
+ } catch (error) {
9512
+ errors.push(String(error instanceof Error ? error.message : error));
9513
+ }
9514
+ }
9515
+ const compiledProfiles = {};
9516
+ for (const profile of profiles) {
9517
+ try {
9518
+ const defaultActionPolicy = profile.defaults?.actionPolicy;
9519
+ if (defaultActionPolicy !== void 0 && !normalizeDecision(defaultActionPolicy)) {
9520
+ throw new Error(
9521
+ `Permission profile "${profile.name}" has invalid defaults.actionPolicy`
9522
+ );
9523
+ }
9524
+ const compiled = compileProfile({
9525
+ profile,
9526
+ effects,
9527
+ manifestRules,
9528
+ warnings
9529
+ });
9530
+ compiled.digest = await digestJson({
9531
+ profile: compiled.flattened,
9532
+ actionRules: compiled.actionRules,
9533
+ defaultActionPolicy: compiled.defaultActionPolicy
9534
+ });
9535
+ compiledProfiles[profile.name] = compiled;
9536
+ } catch (error) {
9537
+ errors.push(String(error instanceof Error ? error.message : error));
9538
+ }
9539
+ }
9540
+ const permissionProfilesDigest = await digestJson(
9541
+ Object.values(compiledProfiles).map((profile) => ({
9542
+ name: profile.name,
9543
+ digest: profile.digest,
9544
+ source: profile.source
9545
+ }))
9546
+ );
9547
+ const bundleWithoutDigest = {
9548
+ schemaVersion: 1,
9549
+ buildId: input.buildId,
9550
+ sandboxId: input.sandboxId,
9551
+ manifestDigest: input.manifestDigest,
9552
+ permissionProfilesDigest,
9553
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
9554
+ effects: effects.map((effect) => ({
9555
+ effectKey: effect.effectKey,
9556
+ name: effect.name,
9557
+ attachedClass: normalizeAttachedClass(effect.attachedClass),
9558
+ isStatic: effect.isStatic === true
9559
+ })),
9560
+ manifestRules,
9561
+ profiles: compiledProfiles
9562
+ };
9563
+ const bundleDigest = await digestJson(bundleWithoutDigest);
9564
+ return {
9565
+ bundle: { ...bundleWithoutDigest, bundleDigest },
9566
+ errors,
9567
+ warnings
9568
+ };
9569
+ });
9570
+ Process({
9571
+ description: "Evaluate compiled permission rules for an action and its current context.",
9572
+ id: "granular-product/effects/authorization-contracts/compiled-evaluation",
9573
+ label: "Evaluate compiled policies",
9574
+ benchmarks: ["./evaluation.bench.ts"],
9575
+ tests: ["./index.test.ts"]
9576
+ })(function evaluateCompiledPolicyBundle2(input) {
9577
+ const profile = input.bundle.profiles[input.profileName];
9578
+ if (!profile) {
9579
+ return {
9580
+ outcome: "deny",
9581
+ matches: [
9582
+ {
9583
+ id: "missing-profile",
9584
+ outcome: "deny",
9585
+ origin: {
9586
+ kind: "permissionProfile",
9587
+ profileName: input.profileName,
9588
+ source: "permissionProfile"
9589
+ },
9590
+ reason: `Permission profile "${input.profileName}" does not exist in this version`,
9591
+ summary: `Permission profile "${input.profileName}" does not exist in this version`
9592
+ }
9593
+ ]
9594
+ };
9595
+ }
9596
+ if (!profile.actionVisibility.includes(input.effectKey)) {
9597
+ return {
9598
+ outcome: "deny",
9599
+ matches: [
9600
+ {
9601
+ id: "action-not-visible",
9602
+ outcome: "deny",
9603
+ origin: {
9604
+ kind: "permissionProfile",
9605
+ profileName: input.profileName,
9606
+ source: profile.source
9607
+ },
9608
+ reason: `Action ${input.effectKey} is not visible for ${input.profileName}`,
9609
+ summary: `Action ${input.effectKey} is not visible for ${input.profileName}`
9610
+ }
9611
+ ]
9612
+ };
9613
+ }
9614
+ const decision = evaluatePolicies({
9615
+ manifestRules: input.bundle.manifestRules[input.effectKey] || [],
9616
+ profileRules: profile.actionRules[input.effectKey] || [],
9617
+ defaultActionPolicy: profile.defaultActionPolicy,
9618
+ context: input.context
9619
+ });
9620
+ return {
9621
+ outcome: decision.outcome,
9622
+ matches: decision.matches.map(
9623
+ (match) => match.id === `profile-default-${decision.outcome}` ? {
9624
+ ...match,
9625
+ origin: {
9626
+ kind: "permissionProfile",
9627
+ profileName: profile.name,
9628
+ source: profile.source
9629
+ }
9630
+ } : match
9631
+ )
9632
+ };
9633
+ });
8604
9634
 
8605
9635
  // ../metamodel-policy/src/index.ts
8606
9636
  function escapeGraphqlString(value) {
@@ -10648,11 +11678,11 @@ var Session = class {
10648
11678
  }
10649
11679
  this.eventListeners.get("effects:changed").push(handler);
10650
11680
  return () => {
10651
- const listeners = this.eventListeners.get("effects:changed");
10652
- if (listeners) {
11681
+ const listeners2 = this.eventListeners.get("effects:changed");
11682
+ if (listeners2) {
10653
11683
  this.eventListeners.set(
10654
11684
  "effects:changed",
10655
- listeners.filter((h) => h !== handler)
11685
+ listeners2.filter((h) => h !== handler)
10656
11686
  );
10657
11687
  }
10658
11688
  };
@@ -10667,11 +11697,11 @@ var Session = class {
10667
11697
  }
10668
11698
  this.eventListeners.get("tools:changed").push(handler);
10669
11699
  return () => {
10670
- const listeners = this.eventListeners.get("tools:changed");
10671
- if (listeners) {
11700
+ const listeners2 = this.eventListeners.get("tools:changed");
11701
+ if (listeners2) {
10672
11702
  this.eventListeners.set(
10673
11703
  "tools:changed",
10674
- listeners.filter((h) => h !== handler)
11704
+ listeners2.filter((h) => h !== handler)
10675
11705
  );
10676
11706
  }
10677
11707
  };
@@ -13275,7 +14305,11 @@ function isUnsupportedEffectCatalogMutation(error) {
13275
14305
  const message = error instanceof Error ? error.message : String(error);
13276
14306
  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");
13277
14307
  }
13278
- function planRecordObjectsChunks(records, batchSize) {
14308
+ var planRecordObjectsChunks = Process({
14309
+ id: "granular-product/authoring/importers-record-apis/record-objects/plan",
14310
+ label: "Plan record chunks",
14311
+ parent: () => Environment.prototype.recordObjects
14312
+ })(function planRecordObjectsChunks2(records, batchSize) {
13279
14313
  const total = records.length;
13280
14314
  const size = Math.max(1, Math.min(batchSize, total));
13281
14315
  const chunkCount = Math.ceil(total / size);
@@ -13285,7 +14319,7 @@ function planRecordObjectsChunks(records, batchSize) {
13285
14319
  plans.push({ chunkIndex, chunkCount, offset, slice });
13286
14320
  }
13287
14321
  return plans;
13288
- }
14322
+ });
13289
14323
  function preserveRecordObjectRealId(record) {
13290
14324
  const realId = record.id.trim();
13291
14325
  if (!realId) {
@@ -13510,15 +14544,54 @@ function isGraphQLMutationDocument(query) {
13510
14544
  }
13511
14545
  return false;
13512
14546
  }
13513
- var Environment = class _Environment {
13514
- granular;
13515
- envData;
13516
- _apiKey;
13517
- _apiEndpoint;
13518
- _tokenProvider;
13519
- _beforeMutationSend;
13520
- _graphqlIdempotencyKey;
14547
+ 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;
14548
+ _Environment_decorators = [Block({
14549
+ description: "Expose records, imports, queries, relationships and sessions for one product environment.",
14550
+ id: "granular-product/authoring/importers-record-apis",
14551
+ label: "Environment client",
14552
+ exposedBy: [() => Granular],
14553
+ tests: [
14554
+ "./record-objects.cancellation.test.ts",
14555
+ "./environment.feed.test.ts"
14556
+ ],
14557
+ parent: () => Granular
14558
+ })], _queries_dec = [Interface({
14559
+ label: "Queries & search",
14560
+ description: "Query the environment\u2019s graph or search its records."
14561
+ })], _stateChanges_dec = [Interface({
14562
+ label: "User state",
14563
+ description: "Record changes to user state and read the environment\u2019s current state."
14564
+ })], _sessions_dec = [Interface({
14565
+ label: "Sessions",
14566
+ description: "Create, connect, list and close conversations in this environment."
14567
+ })], _relationships_dec = [Interface({
14568
+ label: "Relationships",
14569
+ description: "Define, read, attach and detach relationships between records."
14570
+ })], _imports_dec = [Interface({
14571
+ id: "granular-product/ingestion/importer-lifecycle",
14572
+ label: "Background imports",
14573
+ description: "Submit a background record import and inspect or cancel its progress."
14574
+ })], _records_dec = [Interface({
14575
+ label: "Records",
14576
+ description: "Write customer records into the environment, including bounded batch requests."
14577
+ })], _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({
14578
+ id: "granular-product/authoring/importers-record-apis/record-objects",
14579
+ label: "Write record batches"
14580
+ }), Method(() => _Environment.records)], _executeRecordObjectsChunk_dec = [Process({
14581
+ id: "granular-product/authoring/importers-record-apis/record-objects/write-chunk",
14582
+ label: "Write chunk with retry",
14583
+ parent: () => _Environment.prototype.recordObjects
14584
+ })], _enqueueRecordImport_dec = [Method(() => _Environment.imports)], _listRecordImports_dec = [Method(() => _Environment.imports)], _getRecordImport_dec = [Method(() => _Environment.imports)], _cancelRecordImport_dec = [Method(() => _Environment.imports)];
14585
+ var _Environment = class _Environment {
13521
14586
  constructor(granular, envData, apiKey, apiEndpoint, tokenProvider, beforeMutationSend, graphqlIdempotencyKey) {
14587
+ __runInitializers(_init, 5, this);
14588
+ __publicField(this, "granular");
14589
+ __publicField(this, "envData");
14590
+ __publicField(this, "_apiKey");
14591
+ __publicField(this, "_apiEndpoint");
14592
+ __publicField(this, "_tokenProvider");
14593
+ __publicField(this, "_beforeMutationSend");
14594
+ __publicField(this, "_graphqlIdempotencyKey");
13522
14595
  this.granular = granular;
13523
14596
  this.envData = envData;
13524
14597
  this._apiKey = apiKey;
@@ -13768,10 +14841,6 @@ var Environment = class _Environment {
13768
14841
  }
13769
14842
  );
13770
14843
  }
13771
- /**
13772
- * Mirror product-owned workflow state into Granular without making Granular
13773
- * own the customer application's state machine.
13774
- */
13775
14844
  async recordState(input) {
13776
14845
  const { machine, state, ...target } = input;
13777
14846
  if (!machine.trim()) {
@@ -14043,30 +15112,6 @@ var Environment = class _Environment {
14043
15112
  const prefix = `${className}_`;
14044
15113
  return graphPath.startsWith(prefix) ? graphPath.substring(prefix.length) : graphPath;
14045
15114
  }
14046
- /**
14047
- * Execute a GraphQL query against the environment's graph.
14048
- *
14049
- * The query uses the Granular graph query language (based on Cypher/GraphQL).
14050
- * Authentication is handled automatically using the SDK's API key.
14051
- *
14052
- * @param query - The GraphQL query string
14053
- * @param variables - Optional variables for the query
14054
- * @returns The query result data
14055
- *
14056
- * @example
14057
- * ```typescript
14058
- * // Read the workspace
14059
- * const result = await env.graphql(
14060
- * `query { model(path: "workspace") { path label submodels { path label } } }`
14061
- * );
14062
- * console.log(result.data);
14063
- *
14064
- * // Create a model
14065
- * const created = await env.graphql(
14066
- * `mutation { at(path: "workspace") { create_submodel(subpath: "my_node", label: "My Node", prototype: "Model") { model { path label } } } }`
14067
- * );
14068
- * ```
14069
- */
14070
15115
  async graphql(query, variables, options) {
14071
15116
  const authToken = await this.resolveAuthToken();
14072
15117
  if (this._beforeMutationSend && isGraphQLMutationDocument(query)) {
@@ -14159,27 +15204,6 @@ var Environment = class _Environment {
14159
15204
  rank: rankRecordSearchResult(result, normalizedQuery, index)
14160
15205
  })).sort((left, right) => left.rank - right.rank).map((item) => item.result).slice(0, limit);
14161
15206
  }
14162
- // ==================== RELATIONSHIP METHODS ====================
14163
- /**
14164
- * Define a relationship between two model types.
14165
- *
14166
- * Creates both submodels (if they don't exist) and links them with
14167
- * a RelationshipDef node that encodes cardinality.
14168
- *
14169
- * @example
14170
- * ```typescript
14171
- * // Author has many Books, Book has one Author
14172
- * const rel = await env.defineRelationship({
14173
- * model: 'author',
14174
- * localSubmodel: 'books',
14175
- * localIsMany: true,
14176
- * foreignModel: 'book',
14177
- * foreignSubmodel: 'author',
14178
- * foreignIsMany: false,
14179
- * });
14180
- * console.log(rel.relationship_kind); // "one_to_many"
14181
- * ```
14182
- */
14183
15207
  async defineRelationship(options) {
14184
15208
  const result = await this.graphql(
14185
15209
  `mutation DefineRelationship(
@@ -14225,20 +15249,6 @@ var Environment = class _Environment {
14225
15249
  }
14226
15250
  return result.data.at.define_relationship;
14227
15251
  }
14228
- /**
14229
- * Get all relationships for a model type.
14230
- *
14231
- * @param modelPath - The model type path (e.g., "author")
14232
- * @returns Array of relationships from this model's perspective
14233
- *
14234
- * @example
14235
- * ```typescript
14236
- * const rels = await env.getRelationships('author');
14237
- * for (const rel of rels) {
14238
- * console.log(`${rel.local_submodel.path} -> ${rel.foreign_model.path} (${rel.relationship_kind})`);
14239
- * }
14240
- * ```
14241
- */
14242
15252
  async getRelationships(modelPath) {
14243
15253
  const result = await this.graphql(
14244
15254
  `query GetRelationships($path: String) {
@@ -14263,27 +15273,6 @@ var Environment = class _Environment {
14263
15273
  }
14264
15274
  return result.data?.model?.relationships || [];
14265
15275
  }
14266
- /**
14267
- * Attach a target model to a relationship submodel.
14268
- *
14269
- * Handles cardinality automatically:
14270
- * - "One" side: sets/replaces the reference
14271
- * - "Many" side: adds the target to the collection
14272
- *
14273
- * If the target model doesn't exist, it's created as an instance of the foreign type.
14274
- * Bidirectional sync is automatic.
14275
- *
14276
- * @param modelPath - The model instance path (e.g., "tolkien")
14277
- * @param submodelPath - The relationship submodel (e.g., "books")
14278
- * @param targetPath - The target model to attach (e.g., "lord_of_the_rings")
14279
- *
14280
- * @example
14281
- * ```typescript
14282
- * // Attach a book to an author (many side)
14283
- * await env.attach('tolkien', 'books', 'lord_of_the_rings');
14284
- * // This also automatically sets lord_of_the_rings:author -> tolkien
14285
- * ```
14286
- */
14287
15276
  async attach(modelPath, submodelPath, targetPath) {
14288
15277
  const result = await this.graphql(
14289
15278
  `mutation Attach($target: String!) {
@@ -14303,24 +15292,6 @@ var Environment = class _Environment {
14303
15292
  );
14304
15293
  }
14305
15294
  }
14306
- /**
14307
- * Detach a target model from a relationship submodel.
14308
- *
14309
- * Handles bidirectional cleanup automatically.
14310
- *
14311
- * @param modelPath - The model instance path
14312
- * @param submodelPath - The relationship submodel
14313
- * @param targetPath - The target to detach (optional for "one" side; omit on "many" side to detach all)
14314
- *
14315
- * @example
14316
- * ```typescript
14317
- * // Detach a specific book
14318
- * await env.detach('tolkien', 'books', 'lord_of_the_rings');
14319
- *
14320
- * // Detach all books
14321
- * await env.detach('tolkien', 'books');
14322
- * ```
14323
- */
14324
15295
  async detach(modelPath, submodelPath, targetPath) {
14325
15296
  const targetArg = targetPath ? `target: "${targetPath}"` : "";
14326
15297
  const result = await this.graphql(
@@ -14340,19 +15311,6 @@ var Environment = class _Environment {
14340
15311
  );
14341
15312
  }
14342
15313
  }
14343
- /**
14344
- * List all related models through a relationship submodel.
14345
- *
14346
- * @param modelPath - The model instance path
14347
- * @param submodelPath - The relationship submodel
14348
- * @returns Array of related model references
14349
- *
14350
- * @example
14351
- * ```typescript
14352
- * const books = await env.listRelated('tolkien', 'books');
14353
- * console.log(books); // [{ path: "lord_of_the_rings", label: "Lord of the Rings" }, ...]
14354
- * ```
14355
- */
14356
15314
  async listRelated(modelPath, submodelPath) {
14357
15315
  const result = await this.graphql(
14358
15316
  `mutation ListRelated {
@@ -14774,38 +15732,6 @@ var Environment = class _Environment {
14774
15732
  }
14775
15733
  }
14776
15734
  }
14777
- // ==================== RECORD OBJECT ====================
14778
- /**
14779
- * Create or update an instance of a class in the graph.
14780
- *
14781
- * Uses `instantiate` under the hood, which has find-or-create semantics:
14782
- * if an instance with the given `id` already exists for the class it is
14783
- * returned; otherwise a new instance is created. Fields are then set
14784
- * (overwriting previous values) and relationships are attached.
14785
- *
14786
- * The graph path is derived as `{className}_{id}` to ensure uniqueness
14787
- * across classes (two objects of different classes may share the same
14788
- * real-world ID). Relationship targets are also resolved automatically
14789
- * using the foreign class from the relationship definition.
14790
- *
14791
- * @param options - The object specification
14792
- * @returns The graph path, real-world ID, and creation status
14793
- *
14794
- * @example
14795
- * ```typescript
14796
- * // Create an author with fields
14797
- * const result = await env.recordObject({
14798
- * className: 'author',
14799
- * id: 'tolkien',
14800
- * label: 'J.R.R. Tolkien',
14801
- * fields: { name: 'J.R.R. Tolkien', birth_year: 1892 },
14802
- * relationships: { books: ['lotr', 'silmarillion'] },
14803
- * });
14804
- * // result.path → 'author_tolkien' (internal graph path)
14805
- * // result.id → 'tolkien' (real-world ID)
14806
- * // result.created → true
14807
- * ```
14808
- */
14809
15735
  async recordObject(options) {
14810
15736
  const results = await this.recordObjects([options]);
14811
15737
  const result = results[0];
@@ -14814,24 +15740,6 @@ var Environment = class _Environment {
14814
15740
  }
14815
15741
  return result;
14816
15742
  }
14817
- /**
14818
- * Batch version of `recordObject()`.
14819
- *
14820
- * Sends rows through the control-plane **`/records/batch`** endpoint in **chunks** (default
14821
- * **100** records per HTTP request) so individual requests stay bounded and gateway timeouts are
14822
- * unlikely. Each chunk is retried on transient network / worker errors.
14823
- *
14824
- * Use the optional second argument to:
14825
- * - **`batchSize`** — rows per POST (smaller = more progress events; larger = fewer round trips).
14826
- * - **`concurrency`** — run up to N chunk POSTs in parallel (capped at 16) when you want lower wall time.
14827
- * - **`onChunkComplete`** — hook for UIs after each chunk succeeds (row order in the returned array
14828
- * always matches `records`; chunk **completion** order may differ when `concurrency > 1`).
14829
- *
14830
- * For **asynchronous** ingestion with worker-side batching and aggregate counters (`queued`,
14831
- * `completed`, …), use **`enqueueRecordImport`** and poll **`getRecordImport`** /
14832
- * **`getRecordImportSummary`** — best for very large fire-and-forget loads when immediate
14833
- * synchronous commit of every row is not required.
14834
- */
14835
15743
  async recordObjects(records, options) {
14836
15744
  options?.signal?.throwIfAborted();
14837
15745
  if (!Array.isArray(records) || records.length === 0) {
@@ -14916,15 +15824,6 @@ var Environment = class _Environment {
14916
15824
  }
14917
15825
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
14918
15826
  }
14919
- /**
14920
- * Queue a background record import for this environment (async worker pipeline).
14921
- *
14922
- * **vs `recordObjects`:** this path accepts the full payload in one request, returns an
14923
- * **`importId`**, and processes rows in the background — use **`getRecordImport`** /
14924
- * **`getRecordImportSummary`** for progress. Choose it for large bulk loads where you do not
14925
- * need every row committed before the HTTP call returns. Use **`recordObjects`** when you need
14926
- * synchronous upserts and fine-grained chunk progress via **`onChunkComplete`**.
14927
- */
14928
15827
  async enqueueRecordImport(records, options = {}) {
14929
15828
  const recordsToImport = records.map(preserveRecordObjectRealId);
14930
15829
  return this.controlPlaneRequest(
@@ -14941,9 +15840,6 @@ var Environment = class _Environment {
14941
15840
  }
14942
15841
  );
14943
15842
  }
14944
- /**
14945
- * List queued or completed record imports for this environment.
14946
- */
14947
15843
  async listRecordImports(status) {
14948
15844
  const suffix = status ? `?status=${encodeURIComponent(status)}` : "";
14949
15845
  const response = await this.controlPlaneRequest(
@@ -14966,9 +15862,6 @@ var Environment = class _Environment {
14966
15862
  const summary = await this.getRecordImportSummary();
14967
15863
  return summary.awaitingRecords;
14968
15864
  }
14969
- /**
14970
- * Fetch a single record import by id.
14971
- */
14972
15865
  async getRecordImport(importId) {
14973
15866
  return this.controlPlaneRequest(
14974
15867
  `/control/record-imports/${importId}`
@@ -14983,9 +15876,6 @@ var Environment = class _Environment {
14983
15876
  const response = await this.controlPlaneRequest(`/control/record-imports/${importId}/items${suffix}`);
14984
15877
  return Array.isArray(response.items) ? response.items : [];
14985
15878
  }
14986
- /**
14987
- * Cancel a queued/background record import.
14988
- */
14989
15879
  async cancelRecordImport(importId) {
14990
15880
  return this.controlPlaneRequest(
14991
15881
  `/control/record-imports/${importId}/cancel`,
@@ -14995,17 +15885,75 @@ var Environment = class _Environment {
14995
15885
  );
14996
15886
  }
14997
15887
  };
14998
- var EnvironmentSession = class extends Session {
14999
- environment;
15000
- sessionDataRoutePrefix;
15001
- sessionDataHeaders;
15002
- beforeMutationSend;
15003
- heartbeatTimer = null;
15004
- heartbeatProbeInFlight = false;
15005
- /** The last known graph container status, updated by checkReadiness(). */
15006
- graphContainerStatus = null;
15888
+ _init = __decoratorStart(null);
15889
+ __decorateElement(_init, 1, "recordState", _recordState_dec, _Environment);
15890
+ __decorateElement(_init, 1, "listSessions", _listSessions_dec, _Environment);
15891
+ __decorateElement(_init, 1, "getUserEnvironmentState", _getUserEnvironmentState_dec, _Environment);
15892
+ __decorateElement(_init, 1, "createSession", _createSession_dec, _Environment);
15893
+ __decorateElement(_init, 1, "connectSession", _connectSession_dec, _Environment);
15894
+ __decorateElement(_init, 1, "closeSession", _closeSession_dec, _Environment);
15895
+ __decorateElement(_init, 1, "graphql", _graphql_dec, _Environment);
15896
+ __decorateElement(_init, 1, "searchRecords", _searchRecords_dec, _Environment);
15897
+ __decorateElement(_init, 1, "defineRelationship", _defineRelationship_dec, _Environment);
15898
+ __decorateElement(_init, 1, "getRelationships", _getRelationships_dec, _Environment);
15899
+ __decorateElement(_init, 1, "attach", _attach_dec, _Environment);
15900
+ __decorateElement(_init, 1, "detach", _detach_dec, _Environment);
15901
+ __decorateElement(_init, 1, "listRelated", _listRelated_dec, _Environment);
15902
+ __decorateElement(_init, 1, "recordObject", _recordObject_dec, _Environment);
15903
+ __decorateElement(_init, 1, "recordObjects", _recordObjects_dec, _Environment);
15904
+ __decorateElement(_init, 1, "executeRecordObjectsChunk", _executeRecordObjectsChunk_dec, _Environment);
15905
+ __decorateElement(_init, 1, "enqueueRecordImport", _enqueueRecordImport_dec, _Environment);
15906
+ __decorateElement(_init, 1, "listRecordImports", _listRecordImports_dec, _Environment);
15907
+ __decorateElement(_init, 1, "getRecordImport", _getRecordImport_dec, _Environment);
15908
+ __decorateElement(_init, 1, "cancelRecordImport", _cancelRecordImport_dec, _Environment);
15909
+ __decorateElement(_init, 13, "queries", _queries_dec, _Environment);
15910
+ __decorateElement(_init, 13, "stateChanges", _stateChanges_dec, _Environment);
15911
+ __decorateElement(_init, 13, "sessions", _sessions_dec, _Environment);
15912
+ __decorateElement(_init, 13, "relationships", _relationships_dec, _Environment);
15913
+ __decorateElement(_init, 13, "imports", _imports_dec, _Environment);
15914
+ __decorateElement(_init, 13, "records", _records_dec, _Environment);
15915
+ _Environment = __decorateElement(_init, 0, "Environment", _Environment_decorators, _Environment);
15916
+ __publicField(_Environment, "queries", __runInitializers(_init, 8, _Environment)), __runInitializers(_init, 11, _Environment);
15917
+ __publicField(_Environment, "stateChanges", __runInitializers(_init, 12, _Environment)), __runInitializers(_init, 15, _Environment);
15918
+ __publicField(_Environment, "sessions", __runInitializers(_init, 16, _Environment)), __runInitializers(_init, 19, _Environment);
15919
+ __publicField(_Environment, "relationships", __runInitializers(_init, 20, _Environment)), __runInitializers(_init, 23, _Environment);
15920
+ __publicField(_Environment, "imports", __runInitializers(_init, 24, _Environment)), __runInitializers(_init, 27, _Environment);
15921
+ __publicField(_Environment, "records", __runInitializers(_init, 28, _Environment)), __runInitializers(_init, 31, _Environment);
15922
+ __runInitializers(_init, 1, _Environment);
15923
+ var Environment = _Environment;
15924
+ 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;
15925
+ _EnvironmentSession_decorators = [Block({
15926
+ description: "Expose conversation messages, selected data and lifecycle operations for one environment session.",
15927
+ id: "granular-product/authoring/importers-record-apis/session-client",
15928
+ label: "Session client",
15929
+ exposedBy: [() => Environment, () => Granular],
15930
+ tests: [
15931
+ "./environment.feed.test.ts",
15932
+ "./environment.assistant-reply.test.ts"
15933
+ ],
15934
+ parent: () => Environment
15935
+ })];
15936
+ var _EnvironmentSession = class _EnvironmentSession extends (_a = Session, _lifecycle_dec = [Interface({
15937
+ label: "Connection lifecycle",
15938
+ description: "Check session readiness and close or disconnect the session client."
15939
+ })], _records_dec2 = [Interface({
15940
+ label: "Session records",
15941
+ description: "Write records or mention an existing record in the current conversation."
15942
+ })], _conversation_dec = [Interface({
15943
+ label: "Conversation data",
15944
+ description: "Read the conversation document and selected data, and publish assistant replies."
15945
+ })], _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) {
15007
15946
  constructor(client, environment, clientId, options = {}) {
15008
15947
  super(client, clientId, { initialQuota: options.initialQuota });
15948
+ __runInitializers(_init2, 5, this);
15949
+ __publicField(this, "environment");
15950
+ __publicField(this, "sessionDataRoutePrefix");
15951
+ __publicField(this, "sessionDataHeaders");
15952
+ __publicField(this, "beforeMutationSend");
15953
+ __publicField(this, "heartbeatTimer", null);
15954
+ __publicField(this, "heartbeatProbeInFlight", false);
15955
+ /** The last known graph container status, updated by checkReadiness(). */
15956
+ __publicField(this, "graphContainerStatus", null);
15009
15957
  this.environment = environment;
15010
15958
  this.sessionDataRoutePrefix = options.sessionDataRoutePrefix || "/orchestrator/ws/sessions";
15011
15959
  this.sessionDataHeaders = options.sessionDataHeaders || {};
@@ -15103,9 +16051,6 @@ var EnvironmentSession = class extends Session {
15103
16051
  get feedback() {
15104
16052
  return this.environment.feedback;
15105
16053
  }
15106
- /**
15107
- * Return a plain JS copy of the synced session heap.
15108
- */
15109
16054
  getHeap() {
15110
16055
  const doc = this.document;
15111
16056
  return normalizeHeapSnapshot(doc?.heap);
@@ -15180,22 +16125,9 @@ var EnvironmentSession = class extends Session {
15180
16125
  });
15181
16126
  return response.json();
15182
16127
  }
15183
- /**
15184
- * Fetch the live session document from the runtime DO.
15185
- *
15186
- * For presentation history use `feed.list()` or `transcript.list()`.
15187
- * Timeline and job collections are diagnostic/execution data only.
15188
- */
15189
16128
  async getDocument() {
15190
16129
  return this.sessionDataRequest("/document");
15191
16130
  }
15192
- /**
15193
- * Publish one terminal assistant reply from a trusted server integration.
15194
- *
15195
- * This uses the API-key-authenticated HTTP session boundary. Delegated
15196
- * browser sessions cannot use it and never receive assistant feed-authoring
15197
- * capability through their WebSocket.
15198
- */
15199
16131
  async publishAssistantReply(input) {
15200
16132
  if (this.sessionDataRoutePrefix === "/sdk/browser-sessions") {
15201
16133
  throw new Error(
@@ -15577,13 +16509,6 @@ var EnvironmentSession = class extends Session {
15577
16509
  async listFeedback() {
15578
16510
  return this.environment.listFeedback();
15579
16511
  }
15580
- /**
15581
- * Close the session and disconnect from the sandbox.
15582
- *
15583
- * Sends `client.goodbye` over WebSocket first, then issues an HTTP fallback
15584
- * to the runtime goodbye endpoint if no definitive WS-side runtime notify
15585
- * acknowledgement was observed.
15586
- */
15587
16512
  async disconnect() {
15588
16513
  this.stopHeartbeat();
15589
16514
  this.disposeSessionFeed();
@@ -15627,15 +16552,9 @@ var EnvironmentSession = class extends Session {
15627
16552
  this.stopHeartbeat();
15628
16553
  this.client.disconnect({ reason: "Transport detach" });
15629
16554
  }
15630
- /**
15631
- * Backwards-compatible alias for `disconnect()`.
15632
- */
15633
16555
  async close() {
15634
16556
  await this.disconnect();
15635
16557
  }
15636
- /**
15637
- * Check if the graph container is ready and warm.
15638
- */
15639
16558
  async checkReadiness() {
15640
16559
  const result = await this.client.call("client.heartbeat", {});
15641
16560
  const containerStatus = result?.graphContainerStatus ?? {
@@ -15647,6 +16566,24 @@ var EnvironmentSession = class extends Session {
15647
16566
  return containerStatus;
15648
16567
  }
15649
16568
  };
16569
+ _init2 = __decoratorStart(_a);
16570
+ __decorateElement(_init2, 1, "getHeap", _getHeap_dec, _EnvironmentSession);
16571
+ __decorateElement(_init2, 1, "getDocument", _getDocument_dec, _EnvironmentSession);
16572
+ __decorateElement(_init2, 1, "publishAssistantReply", _publishAssistantReply_dec, _EnvironmentSession);
16573
+ __decorateElement(_init2, 1, "mentionRecord", _mentionRecord_dec, _EnvironmentSession);
16574
+ __decorateElement(_init2, 1, "recordObjects", _recordObjects_dec2, _EnvironmentSession);
16575
+ __decorateElement(_init2, 1, "disconnect", _disconnect_dec, _EnvironmentSession);
16576
+ __decorateElement(_init2, 1, "close", _close_dec, _EnvironmentSession);
16577
+ __decorateElement(_init2, 1, "checkReadiness", _checkReadiness_dec, _EnvironmentSession);
16578
+ __decorateElement(_init2, 13, "lifecycle", _lifecycle_dec, _EnvironmentSession);
16579
+ __decorateElement(_init2, 13, "records", _records_dec2, _EnvironmentSession);
16580
+ __decorateElement(_init2, 13, "conversation", _conversation_dec, _EnvironmentSession);
16581
+ _EnvironmentSession = __decorateElement(_init2, 0, "EnvironmentSession", _EnvironmentSession_decorators, _EnvironmentSession);
16582
+ __publicField(_EnvironmentSession, "lifecycle", __runInitializers(_init2, 8, _EnvironmentSession)), __runInitializers(_init2, 11, _EnvironmentSession);
16583
+ __publicField(_EnvironmentSession, "records", __runInitializers(_init2, 12, _EnvironmentSession)), __runInitializers(_init2, 15, _EnvironmentSession);
16584
+ __publicField(_EnvironmentSession, "conversation", __runInitializers(_init2, 16, _EnvironmentSession)), __runInitializers(_init2, 19, _EnvironmentSession);
16585
+ __runInitializers(_init2, 1, _EnvironmentSession);
16586
+ var EnvironmentSession = _EnvironmentSession;
15650
16587
  var OntologyHandle = class {
15651
16588
  granular;
15652
16589
  ontologyNameOrId;
@@ -15698,40 +16635,62 @@ var OntologyHandle = class {
15698
16635
  };
15699
16636
  }
15700
16637
  };
15701
- var Granular = class _Granular {
15702
- /** Tenant events feed, authenticated with this client's credentials. */
15703
- eventsFeed = new EventsFeed(
15704
- (path2, options) => this.request(path2, options)
15705
- );
15706
- apiKey;
15707
- apiUrl;
15708
- httpUrl;
15709
- tokenProvider;
15710
- WebSocketCtor;
15711
- onUnexpectedClose;
15712
- onReconnectError;
15713
- effectHostUrl;
15714
- graphqlIdempotencyKey;
15715
- debugHttp = process.env.GRANULAR_DEBUG_HTTP === "1";
15716
- /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
15717
- sandboxEffects = /* @__PURE__ */ new Map();
15718
- /** Live sandbox-scoped effect hosts keyed by sandboxId */
15719
- sandboxEffectHosts = /* @__PURE__ */ new Map();
15720
- developmentProviders = /* @__PURE__ */ new Map();
15721
- usersProviders = /* @__PURE__ */ new Map();
15722
- /** In-flight host connection promises to avoid duplicate concurrent connects */
15723
- sandboxEffectHostPromises = /* @__PURE__ */ new Map();
15724
- effectHostGenerations = /* @__PURE__ */ new Map();
15725
- effectHostRecovery = /* @__PURE__ */ new Map();
15726
- /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
15727
- ontologyImporters = /* @__PURE__ */ new Map();
15728
- /** Resolved importer hooks keyed by sandboxId for fast lookups during openEnvironment(). */
15729
- sandboxImporters = /* @__PURE__ */ new Map();
16638
+ 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;
16639
+ _Granular_decorators = [Block({
16640
+ description: "Authenticate an application and provide access to its environments, sessions and registered action handlers.",
16641
+ id: "granular-product/authoring/sdk-ontology-facade",
16642
+ label: "Granular client",
16643
+ tests: ["./environment.opening.test.ts"],
16644
+ docs: "../README.md"
16645
+ })], _transport_dec = [Interface({
16646
+ label: "HTTP requests",
16647
+ description: "Send authenticated SDK requests to the configured Granular API."
16648
+ })], _effectHosts_dec = [Interface({
16649
+ id: "granular-product/authoring/live-effect-hosts",
16650
+ label: "Application action handlers",
16651
+ description: "Register application functions that Granular may invoke as actions, and disconnect handlers when they are no longer available."
16652
+ })], _sessions_dec2 = [Interface({
16653
+ label: "Sessions",
16654
+ description: "Create, list, connect and close product sessions through the SDK."
16655
+ })], _environmentAccess_dec = [Interface({
16656
+ label: "Environment access",
16657
+ description: "Resolve a user\u2019s assigned environment or open a connection to it."
16658
+ })], _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)];
16659
+ var _Granular = class _Granular {
15730
16660
  /**
15731
16661
  * Create a new Granular client
15732
16662
  * @param options - Client configuration
15733
16663
  */
15734
16664
  constructor(options) {
16665
+ __runInitializers(_init3, 5, this);
16666
+ /** Tenant events feed, authenticated with this client's credentials. */
16667
+ __publicField(this, "eventsFeed", new EventsFeed(
16668
+ (path2, options) => this.request(path2, options)
16669
+ ));
16670
+ __publicField(this, "apiKey");
16671
+ __publicField(this, "apiUrl");
16672
+ __publicField(this, "httpUrl");
16673
+ __publicField(this, "tokenProvider");
16674
+ __publicField(this, "WebSocketCtor");
16675
+ __publicField(this, "onUnexpectedClose");
16676
+ __publicField(this, "onReconnectError");
16677
+ __publicField(this, "effectHostUrl");
16678
+ __publicField(this, "graphqlIdempotencyKey");
16679
+ __publicField(this, "debugHttp", process.env.GRANULAR_DEBUG_HTTP === "1");
16680
+ /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
16681
+ __publicField(this, "sandboxEffects", /* @__PURE__ */ new Map());
16682
+ /** Live sandbox-scoped effect hosts keyed by sandboxId */
16683
+ __publicField(this, "sandboxEffectHosts", /* @__PURE__ */ new Map());
16684
+ __publicField(this, "developmentProviders", /* @__PURE__ */ new Map());
16685
+ __publicField(this, "usersProviders", /* @__PURE__ */ new Map());
16686
+ /** In-flight host connection promises to avoid duplicate concurrent connects */
16687
+ __publicField(this, "sandboxEffectHostPromises", /* @__PURE__ */ new Map());
16688
+ __publicField(this, "effectHostGenerations", /* @__PURE__ */ new Map());
16689
+ __publicField(this, "effectHostRecovery", /* @__PURE__ */ new Map());
16690
+ /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
16691
+ __publicField(this, "ontologyImporters", /* @__PURE__ */ new Map());
16692
+ /** Resolved importer hooks keyed by sandboxId for fast lookups during openEnvironment(). */
16693
+ __publicField(this, "sandboxImporters", /* @__PURE__ */ new Map());
15735
16694
  const auth = options.token ?? options.apiKey;
15736
16695
  if (!auth) {
15737
16696
  throw new Error(
@@ -15779,8 +16738,8 @@ var Granular = class _Granular {
15779
16738
  sandboxId
15780
16739
  );
15781
16740
  if (!importer) throw new Error("No environment importer registered.");
15782
- const host = await this.ensureSandboxEffectHost(sandboxId);
15783
- await host.wsClient.call("environment.importer.register", {});
16741
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
16742
+ await host2.wsClient.call("environment.importer.register", {});
15784
16743
  }
15785
16744
  clearEnvironmentImporter(ontologyNameOrId) {
15786
16745
  this.ontologyImporters.delete(ontologyNameOrId);
@@ -15882,29 +16841,6 @@ var Granular = class _Granular {
15882
16841
  "openEnvironment() requires either userId, granularId, or a user object returned by recordUser()."
15883
16842
  );
15884
16843
  }
15885
- /**
15886
- * Open or resolve an ontology environment for one user without opening a session.
15887
- *
15888
- * @example
15889
- * ```typescript
15890
- * const environment = await granular.openEnvironment({
15891
- * ontology: 'my-ontology',
15892
- * tag: 'dev',
15893
- * userId: 'user_123',
15894
- * permissions: ['agent'],
15895
- * });
15896
- *
15897
- * await environment.data.record({
15898
- * className: 'customer',
15899
- * id: 'acme',
15900
- * fields: { name: 'Acme' },
15901
- * });
15902
- *
15903
- * const session = await environment.sessions.create();
15904
- * const job = await session.submitJob(`return "hello";`);
15905
- * console.log(await job.result);
15906
- * ```
15907
- */
15908
16844
  async openEnvironment(options) {
15909
16845
  const resolved = await this.resolveOpenEnvironmentData(
15910
16846
  options,
@@ -15914,11 +16850,6 @@ var Granular = class _Granular {
15914
16850
  await this.maybeRunEnvironmentImporter(resolved, environment);
15915
16851
  return environment;
15916
16852
  }
15917
- /**
15918
- * Read the active environment selected by Granular for an already-recorded
15919
- * external user. This is intentionally read-only: browser/login code must
15920
- * not create subjects or environments as a side effect.
15921
- */
15922
16853
  async getActiveEnvironmentForUser(options) {
15923
16854
  const sandboxId = options.sandboxId.trim();
15924
16855
  const tagName = options.tag.trim();
@@ -15964,13 +16895,6 @@ var Granular = class _Granular {
15964
16895
  throw error;
15965
16896
  }
15966
16897
  }
15967
- /**
15968
- * Resolve one exact environment only when Granular confirms that it belongs
15969
- * to the given external user in the requested sandbox (and, optionally,
15970
- * tag). This is deliberately read-only: callers use it to keep an already
15971
- * opened delegated workspace stable while a newer active environment is
15972
- * being prepared in the background.
15973
- */
15974
16898
  async getEnvironmentForUser(options) {
15975
16899
  const sandboxId = options.sandboxId.trim();
15976
16900
  const userId = options.userId.trim();
@@ -16013,11 +16937,6 @@ var Granular = class _Granular {
16013
16937
  }
16014
16938
  return this.bindEnvironmentHandle(environment);
16015
16939
  }
16016
- /**
16017
- * Register one reviewed, pre-existing environment as the active workspace
16018
- * for an external user. This is for a controlled migration only: it does
16019
- * not create an environment and it does not run an importer.
16020
- */
16021
16940
  async adoptEnvironmentForUser(options) {
16022
16941
  const sandboxId = options.sandboxId.trim();
16023
16942
  const tagName = options.tag.trim();
@@ -16064,11 +16983,6 @@ var Granular = class _Granular {
16064
16983
  normalizeEnvironmentData(payload.environment)
16065
16984
  );
16066
16985
  }
16067
- /**
16068
- * Deprecated compatibility alias for `openEnvironment()`.
16069
- *
16070
- * `connect()` no longer opens a runtime session automatically.
16071
- */
16072
16986
  async connect(options) {
16073
16987
  return this.openEnvironment({
16074
16988
  ...options,
@@ -16372,9 +17286,6 @@ var Granular = class _Granular {
16372
17286
  setupOperationKey: resetKey
16373
17287
  };
16374
17288
  }
16375
- /**
16376
- * List indexed sessions using ownership filters and bounded pagination.
16377
- */
16378
17289
  async listSessions(options) {
16379
17290
  const items = [];
16380
17291
  let cursor = options.cursor?.trim() || void 0;
@@ -16571,10 +17482,6 @@ var Granular = class _Granular {
16571
17482
  }
16572
17483
  return (/* @__PURE__ */ new Date(0)).toISOString();
16573
17484
  }
16574
- /**
16575
- * Create a new session (conversation) for an existing environment and connect to it.
16576
- * The runtime graph is shared across all sessions for the same environment.
16577
- */
16578
17485
  async createSession(options) {
16579
17486
  const clientId = options.clientId || `client_${Date.now()}`;
16580
17487
  const sessionScope = options.sessionScope?.trim() || void 0;
@@ -16595,9 +17502,6 @@ var Granular = class _Granular {
16595
17502
  });
16596
17503
  return this.bindWebSocketEnvironmentSession(environment, clientId, session);
16597
17504
  }
16598
- /**
16599
- * Connect to an existing open session (same conversation thread) using a freshly minted WebSocket token.
16600
- */
16601
17505
  async connectSession(options) {
16602
17506
  const clientId = options.clientId || `client_${Date.now()}`;
16603
17507
  const minted = await this.request(`/ws/sessions/${encodeURIComponent(options.sessionId)}/token`, {
@@ -16624,7 +17528,6 @@ var Granular = class _Granular {
16624
17528
  metadata: options?.metadata
16625
17529
  });
16626
17530
  }
16627
- /** End a session through the runtime, or disconnect its connected handle. */
16628
17531
  async closeSession(sessionId, environment) {
16629
17532
  if (environment && environment.sessionId === sessionId) {
16630
17533
  await environment.disconnect();
@@ -16635,9 +17538,6 @@ var Granular = class _Granular {
16635
17538
  { method: "POST" }
16636
17539
  );
16637
17540
  }
16638
- /**
16639
- * Re-open a closed session in the index and connect to its existing runtime document.
16640
- */
16641
17541
  async reopenSession(sessionId, options) {
16642
17542
  await this.request(`/control/sessions/${encodeURIComponent(sessionId)}`, {
16643
17543
  method: "PATCH",
@@ -16878,25 +17778,25 @@ var Granular = class _Granular {
16878
17778
  }
16879
17779
  return serialized;
16880
17780
  }
16881
- async publishSandboxEffectCatalog(host) {
17781
+ async publishSandboxEffectCatalog(host2) {
16882
17782
  const effects = Array.from(
16883
- this.getSandboxEffectMap(host.sandboxId).values()
17783
+ this.getSandboxEffectMap(host2.sandboxId).values()
16884
17784
  ).map((effect) => this.serializeEffect(effect));
16885
17785
  let acceptedCount = 0;
16886
17786
  const rejected = [];
16887
17787
  try {
16888
17788
  await withTimeout(
16889
- host.wsClient.call("effects.resetCatalog", {}),
17789
+ host2.wsClient.call("effects.resetCatalog", {}),
16890
17790
  EFFECT_CATALOG_SYNC_TIMEOUT_MS,
16891
- `effects.resetCatalog for sandbox ${host.sandboxId}`
17791
+ `effects.resetCatalog for sandbox ${host2.sandboxId}`
16892
17792
  );
16893
17793
  for (const batch of chunkItems(effects, EFFECT_CATALOG_SYNC_BATCH_SIZE)) {
16894
17794
  const result = await withTimeout(
16895
- host.wsClient.call("effects.addCatalog", {
17795
+ host2.wsClient.call("effects.addCatalog", {
16896
17796
  effects: batch
16897
17797
  }),
16898
17798
  EFFECT_CATALOG_SYNC_TIMEOUT_MS,
16899
- `effects.addCatalog for sandbox ${host.sandboxId}`
17799
+ `effects.addCatalog for sandbox ${host2.sandboxId}`
16900
17800
  );
16901
17801
  acceptedCount += typeof result?.acceptedCount === "number" ? result.acceptedCount : 0;
16902
17802
  if (Array.isArray(result?.rejected)) {
@@ -16908,11 +17808,11 @@ var Granular = class _Granular {
16908
17808
  throw error;
16909
17809
  }
16910
17810
  const result = await withTimeout(
16911
- host.wsClient.call("effects.publishCatalog", {
17811
+ host2.wsClient.call("effects.publishCatalog", {
16912
17812
  effects
16913
17813
  }),
16914
17814
  EFFECT_CATALOG_SYNC_TIMEOUT_MS,
16915
- `effects.publishCatalog for sandbox ${host.sandboxId}`
17815
+ `effects.publishCatalog for sandbox ${host2.sandboxId}`
16916
17816
  );
16917
17817
  acceptedCount = typeof result?.acceptedCount === "number" ? result.acceptedCount : 0;
16918
17818
  if (Array.isArray(result?.rejected)) {
@@ -16924,12 +17824,12 @@ var Granular = class _Granular {
16924
17824
  (entry) => `${entry.name || "unknown"}: ${entry.reason || "rejected"}`
16925
17825
  ).join("; ");
16926
17826
  throw new Error(
16927
- `Failed to publish live effects for sandbox ${host.sandboxId}: ${detail}`
17827
+ `Failed to publish live effects for sandbox ${host2.sandboxId}: ${detail}`
16928
17828
  );
16929
17829
  }
16930
17830
  if (rejected.length > 0) {
16931
17831
  console.warn(
16932
- `[Granular] Some live effects were rejected for sandbox ${host.sandboxId}:`,
17832
+ `[Granular] Some live effects were rejected for sandbox ${host2.sandboxId}:`,
16933
17833
  rejected
16934
17834
  );
16935
17835
  }
@@ -16938,8 +17838,8 @@ var Granular = class _Granular {
16938
17838
  let lastError;
16939
17839
  for (let attempt = 1; attempt <= EFFECT_CATALOG_SYNC_RETRY_COUNT; attempt += 1) {
16940
17840
  try {
16941
- const host = await this.ensureSandboxEffectHost(sandboxId);
16942
- await this.publishSandboxEffectCatalog(host);
17841
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
17842
+ await this.publishSandboxEffectCatalog(host2);
16943
17843
  return;
16944
17844
  } catch (error) {
16945
17845
  lastError = error;
@@ -16956,11 +17856,11 @@ var Granular = class _Granular {
16956
17856
  }
16957
17857
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
16958
17858
  }
16959
- recoverEffectHost(host, error) {
16960
- const sandboxId = host.sandboxId;
16961
- if (host.recovering || this.sandboxEffectHosts.get(sandboxId) !== host)
17859
+ recoverEffectHost(host2, error) {
17860
+ const sandboxId = host2.sandboxId;
17861
+ if (host2.recovering || this.sandboxEffectHosts.get(sandboxId) !== host2)
16962
17862
  return;
16963
- host.recovering = true;
17863
+ host2.recovering = true;
16964
17864
  this.disconnectSandboxEffectHost(sandboxId);
16965
17865
  const state = {
16966
17866
  attempt: 0,
@@ -16983,7 +17883,7 @@ var Granular = class _Granular {
16983
17883
  );
16984
17884
  try {
16985
17885
  this.onReconnectError?.({
16986
- sessionId: `effect-host:${host.effectClientId}`,
17886
+ sessionId: `effect-host:${host2.effectClientId}`,
16987
17887
  error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError),
16988
17888
  timestamp: Date.now(),
16989
17889
  terminal: !retryable
@@ -17036,13 +17936,13 @@ var Granular = class _Granular {
17036
17936
  )
17037
17937
  };
17038
17938
  }
17039
- async recoverSourceCommits(host) {
17939
+ async recoverSourceCommits(host2) {
17040
17940
  const stores = new Set(
17041
- Array.from(this.getSandboxEffectMap(host.sandboxId).values()).map((effect) => effect.commit?.storage).filter(Boolean)
17941
+ Array.from(this.getSandboxEffectMap(host2.sandboxId).values()).map((effect) => effect.commit?.storage).filter(Boolean)
17042
17942
  );
17043
17943
  for (const store of stores) {
17044
17944
  try {
17045
- await store.recover(this.effectCommitTransport(), host.sandboxId);
17945
+ await store.recover(this.effectCommitTransport(), host2.sandboxId);
17046
17946
  } catch (error) {
17047
17947
  console.warn(
17048
17948
  "[Granular] Source commit delivery remains pending:",
@@ -17051,43 +17951,43 @@ var Granular = class _Granular {
17051
17951
  }
17052
17952
  }
17053
17953
  }
17054
- startEffectHostHeartbeat(host) {
17055
- if (host.heartbeatTimer) {
17056
- clearInterval(host.heartbeatTimer);
17954
+ startEffectHostHeartbeat(host2) {
17955
+ if (host2.heartbeatTimer) {
17956
+ clearInterval(host2.heartbeatTimer);
17057
17957
  }
17058
- host.heartbeatInFlight = false;
17958
+ host2.heartbeatInFlight = false;
17059
17959
  const sendHeartbeat = (failureLabel, recoverOnFailure) => {
17060
- if (host.heartbeatInFlight || host.recovering) {
17960
+ if (host2.heartbeatInFlight || host2.recovering) {
17061
17961
  return;
17062
17962
  }
17063
- host.heartbeatInFlight = true;
17064
- host.wsClient.call("client.heartbeat", {}).then(() => this.recoverSourceCommits(host)).catch((error) => {
17065
- console.warn(`${failureLabel} ${host.sandboxId}:`, error);
17963
+ host2.heartbeatInFlight = true;
17964
+ host2.wsClient.call("client.heartbeat", {}).then(() => this.recoverSourceCommits(host2)).catch((error) => {
17965
+ console.warn(`${failureLabel} ${host2.sandboxId}:`, error);
17066
17966
  if (recoverOnFailure) {
17067
- this.recoverEffectHost(host, error);
17967
+ this.recoverEffectHost(host2, error);
17068
17968
  }
17069
17969
  }).finally(() => {
17070
- host.heartbeatInFlight = false;
17970
+ host2.heartbeatInFlight = false;
17071
17971
  });
17072
17972
  };
17073
17973
  sendHeartbeat(
17074
17974
  "[Granular] Initial effect host heartbeat failed for sandbox",
17075
17975
  false
17076
17976
  );
17077
- host.heartbeatTimer = setInterval(() => {
17977
+ host2.heartbeatTimer = setInterval(() => {
17078
17978
  sendHeartbeat(
17079
17979
  "[Granular] Effect host heartbeat failed for sandbox",
17080
17980
  true
17081
17981
  );
17082
17982
  }, 1e4);
17083
17983
  }
17084
- stopEffectHostHeartbeat(host) {
17085
- if (!host?.heartbeatTimer) {
17984
+ stopEffectHostHeartbeat(host2) {
17985
+ if (!host2?.heartbeatTimer) {
17086
17986
  return;
17087
17987
  }
17088
- clearInterval(host.heartbeatTimer);
17089
- host.heartbeatTimer = null;
17090
- host.heartbeatInFlight = false;
17988
+ clearInterval(host2.heartbeatTimer);
17989
+ host2.heartbeatTimer = null;
17990
+ host2.heartbeatInFlight = false;
17091
17991
  }
17092
17992
  async registerUsers(ontologyNameOrId, handler, options) {
17093
17993
  const provider = new UsersProvider(handler, options);
@@ -17095,8 +17995,8 @@ var Granular = class _Granular {
17095
17995
  const previous = this.usersProviders.get(sandboxId);
17096
17996
  this.usersProviders.set(sandboxId, provider);
17097
17997
  try {
17098
- const host = await this.ensureSandboxEffectHost(sandboxId);
17099
- if (provider.registration?.providerId !== host.effectClientId) await this.registerUsersOnHost(host, provider);
17998
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
17999
+ if (provider.registration?.providerId !== host2.effectClientId) await this.registerUsersOnHost(host2, provider);
17100
18000
  if (!provider.registration) throw new Error("User directory registration is no longer live.");
17101
18001
  return provider.registration;
17102
18002
  } catch (error) {
@@ -17107,10 +18007,10 @@ var Granular = class _Granular {
17107
18007
  throw error;
17108
18008
  }
17109
18009
  }
17110
- async registerUsersOnHost(host, provider) {
17111
- const registration = await host.wsClient.call("users.register", {});
17112
- if (this.usersProviders.get(host.sandboxId) !== provider) throw new Error("User directory registration was replaced.");
17113
- provider.bind(registration, host.sandboxId, host.effectClientId);
18010
+ async registerUsersOnHost(host2, provider) {
18011
+ const registration = await host2.wsClient.call("users.register", {});
18012
+ if (this.usersProviders.get(host2.sandboxId) !== provider) throw new Error("User directory registration was replaced.");
18013
+ provider.bind(registration, host2.sandboxId, host2.effectClientId);
17114
18014
  }
17115
18015
  /** Publish only public setup metadata; product session authority stays in resolveLaunch. */
17116
18016
  async registerCustomerSkill(ontologyNameOrId, options) {
@@ -17162,10 +18062,10 @@ var Granular = class _Granular {
17162
18062
  const previous = this.developmentProviders.get(sandboxId);
17163
18063
  this.developmentProviders.set(sandboxId, provider);
17164
18064
  try {
17165
- const host = await this.ensureSandboxEffectHost(sandboxId);
18065
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
17166
18066
  if (this.developmentProviders.get(sandboxId) !== provider) throw new Error("Development registration was replaced.");
17167
- if (provider.registration?.providerId !== host.effectClientId) {
17168
- await this.registerDevelopmentOnHost(host, provider);
18067
+ if (provider.registration?.providerId !== host2.effectClientId) {
18068
+ await this.registerDevelopmentOnHost(host2, provider);
17169
18069
  }
17170
18070
  if (!provider.registration) throw new Error("Development provider registration is no longer live.");
17171
18071
  return provider.registration;
@@ -17177,38 +18077,38 @@ var Granular = class _Granular {
17177
18077
  throw error;
17178
18078
  }
17179
18079
  }
17180
- async registerDevelopmentOnHost(host, provider) {
17181
- const registration = await host.wsClient.call(
18080
+ async registerDevelopmentOnHost(host2, provider) {
18081
+ const registration = await host2.wsClient.call(
17182
18082
  "onboarding.register",
17183
18083
  provider.registrationParams()
17184
18084
  );
17185
- if (this.developmentProviders.get(host.sandboxId) !== provider)
18085
+ if (this.developmentProviders.get(host2.sandboxId) !== provider)
17186
18086
  throw new Error("Development registration was replaced.");
17187
- provider.bind(registration, host.sandboxId, host.effectClientId);
18087
+ provider.bind(registration, host2.sandboxId, host2.effectClientId);
17188
18088
  }
17189
- async synchronizeEffectHost(host) {
17190
- if (host.syncPromise) {
17191
- return host.syncPromise;
18089
+ async synchronizeEffectHost(host2) {
18090
+ if (host2.syncPromise) {
18091
+ return host2.syncPromise;
17192
18092
  }
17193
- host.syncPromise = (async () => {
17194
- await host.wsClient.call("client.hello", {
17195
- clientId: host.clientId,
18093
+ host2.syncPromise = (async () => {
18094
+ await host2.wsClient.call("client.hello", {
18095
+ clientId: host2.clientId,
17196
18096
  protocolVersion: "2.0"
17197
18097
  });
17198
- await this.publishSandboxEffectCatalog(host);
17199
- if (this.resolveEnvironmentImporter(host.sandboxId, host.sandboxId))
17200
- await host.wsClient.call("environment.importer.register", {});
17201
- const users2 = this.usersProviders.get(host.sandboxId);
17202
- if (users2) await this.registerUsersOnHost(host, users2);
17203
- const development = this.developmentProviders.get(host.sandboxId);
17204
- if (development) await this.registerDevelopmentOnHost(host, development);
17205
- this.startEffectHostHeartbeat(host);
18098
+ await this.publishSandboxEffectCatalog(host2);
18099
+ if (this.resolveEnvironmentImporter(host2.sandboxId, host2.sandboxId))
18100
+ await host2.wsClient.call("environment.importer.register", {});
18101
+ const users2 = this.usersProviders.get(host2.sandboxId);
18102
+ if (users2) await this.registerUsersOnHost(host2, users2);
18103
+ const development = this.developmentProviders.get(host2.sandboxId);
18104
+ if (development) await this.registerDevelopmentOnHost(host2, development);
18105
+ this.startEffectHostHeartbeat(host2);
17206
18106
  })();
17207
18107
  try {
17208
- await host.syncPromise;
18108
+ await host2.syncPromise;
17209
18109
  } finally {
17210
- if (host.syncPromise) {
17211
- host.syncPromise = null;
18110
+ if (host2.syncPromise) {
18111
+ host2.syncPromise = null;
17212
18112
  }
17213
18113
  }
17214
18114
  }
@@ -17238,7 +18138,7 @@ var Granular = class _Granular {
17238
18138
  onUnexpectedClose: this.onUnexpectedClose,
17239
18139
  onReconnectError: this.onReconnectError
17240
18140
  });
17241
- const host = {
18141
+ const host2 = {
17242
18142
  generation: generation2,
17243
18143
  sandboxId,
17244
18144
  effectClientId,
@@ -17325,20 +18225,20 @@ var Granular = class _Granular {
17325
18225
  };
17326
18226
  });
17327
18227
  wsClient.on("open", () => {
17328
- void this.synchronizeEffectHost(host).catch((error) => {
18228
+ void this.synchronizeEffectHost(host2).catch((error) => {
17329
18229
  console.error(
17330
18230
  `[Granular] Failed to re-sync effect host for sandbox ${sandboxId}:`,
17331
18231
  error
17332
18232
  );
17333
- this.recoverEffectHost(host, error);
18233
+ this.recoverEffectHost(host2, error);
17334
18234
  });
17335
18235
  });
17336
18236
  wsClient.on("disconnect", () => {
17337
- this.stopEffectHostHeartbeat(host);
18237
+ this.stopEffectHostHeartbeat(host2);
17338
18238
  const users2 = this.usersProviders.get(sandboxId);
17339
- if (users2?.registration?.providerId === host.effectClientId) users2.unbind();
18239
+ if (users2?.registration?.providerId === host2.effectClientId) users2.unbind();
17340
18240
  const provider = this.developmentProviders.get(sandboxId);
17341
- if (provider?.registration?.providerId === host.effectClientId) provider.unbind();
18241
+ if (provider?.registration?.providerId === host2.effectClientId) provider.unbind();
17342
18242
  });
17343
18243
  try {
17344
18244
  await withTimeout(
@@ -17346,13 +18246,13 @@ var Granular = class _Granular {
17346
18246
  EFFECT_HOST_CONNECT_TIMEOUT_MS,
17347
18247
  `effect host WebSocket connect for sandbox ${sandboxId}`
17348
18248
  );
17349
- await this.synchronizeEffectHost(host);
18249
+ await this.synchronizeEffectHost(host2);
17350
18250
  if ((this.effectHostGenerations.get(sandboxId) || 0) !== generation2)
17351
18251
  throw new Error("Effect host connection was canceled");
17352
- this.sandboxEffectHosts.set(sandboxId, host);
17353
- return host;
18252
+ this.sandboxEffectHosts.set(sandboxId, host2);
18253
+ return host2;
17354
18254
  } catch (error) {
17355
- this.stopEffectHostHeartbeat(host);
18255
+ this.stopEffectHostHeartbeat(host2);
17356
18256
  wsClient.disconnect({ reason: "Effect host initialization failed" });
17357
18257
  throw error;
17358
18258
  }
@@ -17376,20 +18276,14 @@ var Granular = class _Granular {
17376
18276
  const recovering = this.effectHostRecovery.get(sandboxId);
17377
18277
  if (recovering?.timer) clearTimeout(recovering.timer);
17378
18278
  this.effectHostRecovery.delete(sandboxId);
17379
- const host = this.sandboxEffectHosts.get(sandboxId);
17380
- if (!host) {
18279
+ const host2 = this.sandboxEffectHosts.get(sandboxId);
18280
+ if (!host2) {
17381
18281
  return;
17382
18282
  }
17383
18283
  this.sandboxEffectHosts.delete(sandboxId);
17384
- this.stopEffectHostHeartbeat(host);
17385
- host.wsClient.disconnect();
18284
+ this.stopEffectHostHeartbeat(host2);
18285
+ host2.wsClient.disconnect();
17386
18286
  }
17387
- /**
17388
- * Register an effect (tool) for a specific sandbox.
17389
- *
17390
- * @param sandboxNameOrId - The name or ID of the sandbox
17391
- * @param effect - The tool definition and handler
17392
- */
17393
18287
  async registerEffect(sandboxNameOrId, effect) {
17394
18288
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
17395
18289
  const sandboxId = sandbox.sandboxId;
@@ -17399,11 +18293,6 @@ var Granular = class _Granular {
17399
18293
  );
17400
18294
  await this.syncSandboxEffectCatalog(sandboxId);
17401
18295
  }
17402
- /**
17403
- * Register multiple effects (tools) for a specific sandbox.
17404
- *
17405
- * batch version of `registerEffect`.
17406
- */
17407
18296
  async registerEffects(sandboxNameOrId, effects) {
17408
18297
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
17409
18298
  const sandboxId = sandbox.sandboxId;
@@ -17413,12 +18302,6 @@ var Granular = class _Granular {
17413
18302
  }
17414
18303
  await this.syncSandboxEffectCatalog(sandboxId);
17415
18304
  }
17416
- /**
17417
- * Unregister an effect from a sandbox.
17418
- *
17419
- * Removes it from the local sandbox registry and updates the
17420
- * sandbox-scoped live catalog.
17421
- */
17422
18305
  async unregisterEffect(sandboxNameOrId, name) {
17423
18306
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
17424
18307
  const sandboxId = sandbox.sandboxId;
@@ -17441,12 +18324,6 @@ var Granular = class _Granular {
17441
18324
  }
17442
18325
  await this.syncSandboxEffectCatalog(sandboxId);
17443
18326
  }
17444
- /**
17445
- * Disconnect one sandbox-scoped effect host, or all of them when no sandbox is provided.
17446
- *
17447
- * This is primarily useful for long-lived helper processes such as generated
17448
- * `granular-effects.ts` scripts that need to shut down cleanly on SIGINT/SIGTERM.
17449
- */
17450
18327
  async disconnectEffects(sandboxNameOrId) {
17451
18328
  if (sandboxNameOrId) {
17452
18329
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
@@ -17871,9 +18748,6 @@ var Granular = class _Granular {
17871
18748
  throw new Error(`Ontology not found: ${ontologyNameOrId}`);
17872
18749
  return result.items[0].sandboxId;
17873
18750
  }
17874
- /**
17875
- * Make an authenticated API request
17876
- */
17877
18751
  async request(path2, options = {}) {
17878
18752
  const url = `${this.httpUrl}${path2}`;
17879
18753
  if (this.debugHttp) {
@@ -17923,6 +18797,33 @@ var Granular = class _Granular {
17923
18797
  throw new Error(`Granular API Error: exhausted retries for ${url}`);
17924
18798
  }
17925
18799
  };
18800
+ _init3 = __decoratorStart(null);
18801
+ __decorateElement(_init3, 1, "openEnvironment", _openEnvironment_dec, _Granular);
18802
+ __decorateElement(_init3, 1, "getActiveEnvironmentForUser", _getActiveEnvironmentForUser_dec, _Granular);
18803
+ __decorateElement(_init3, 1, "getEnvironmentForUser", _getEnvironmentForUser_dec, _Granular);
18804
+ __decorateElement(_init3, 1, "adoptEnvironmentForUser", _adoptEnvironmentForUser_dec, _Granular);
18805
+ __decorateElement(_init3, 1, "connect", _connect_dec, _Granular);
18806
+ __decorateElement(_init3, 1, "listSessions", _listSessions_dec2, _Granular);
18807
+ __decorateElement(_init3, 1, "createSession", _createSession_dec2, _Granular);
18808
+ __decorateElement(_init3, 1, "connectSession", _connectSession_dec2, _Granular);
18809
+ __decorateElement(_init3, 1, "closeSession", _closeSession_dec2, _Granular);
18810
+ __decorateElement(_init3, 1, "reopenSession", _reopenSession_dec, _Granular);
18811
+ __decorateElement(_init3, 1, "registerEffect", _registerEffect_dec, _Granular);
18812
+ __decorateElement(_init3, 1, "registerEffects", _registerEffects_dec, _Granular);
18813
+ __decorateElement(_init3, 1, "unregisterEffect", _unregisterEffect_dec, _Granular);
18814
+ __decorateElement(_init3, 1, "disconnectEffects", _disconnectEffects_dec, _Granular);
18815
+ __decorateElement(_init3, 1, "request", _request_dec, _Granular);
18816
+ __decorateElement(_init3, 13, "transport", _transport_dec, _Granular);
18817
+ __decorateElement(_init3, 13, "effectHosts", _effectHosts_dec, _Granular);
18818
+ __decorateElement(_init3, 13, "sessions", _sessions_dec2, _Granular);
18819
+ __decorateElement(_init3, 13, "environmentAccess", _environmentAccess_dec, _Granular);
18820
+ _Granular = __decorateElement(_init3, 0, "Granular", _Granular_decorators, _Granular);
18821
+ __publicField(_Granular, "transport", __runInitializers(_init3, 8, _Granular)), __runInitializers(_init3, 11, _Granular);
18822
+ __publicField(_Granular, "effectHosts", __runInitializers(_init3, 12, _Granular)), __runInitializers(_init3, 15, _Granular);
18823
+ __publicField(_Granular, "sessions", __runInitializers(_init3, 16, _Granular)), __runInitializers(_init3, 19, _Granular);
18824
+ __publicField(_Granular, "environmentAccess", __runInitializers(_init3, 20, _Granular)), __runInitializers(_init3, 23, _Granular);
18825
+ __runInitializers(_init3, 1, _Granular);
18826
+ var Granular = _Granular;
17926
18827
 
17927
18828
  // src/agent-harness-templates/action-presentation/0.1.0/manifest.json
17928
18829
  var manifest_default = {
@@ -18289,15 +19190,15 @@ function uniqueStrings(values, maxCount) {
18289
19190
  }
18290
19191
  return output;
18291
19192
  }
18292
- function stableStringify(value) {
19193
+ function stableStringify2(value) {
18293
19194
  if (value === null || typeof value !== "object") {
18294
19195
  return JSON.stringify(value);
18295
19196
  }
18296
19197
  if (Array.isArray(value)) {
18297
- return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
19198
+ return `[${value.map((entry) => stableStringify2(entry)).join(",")}]`;
18298
19199
  }
18299
19200
  const record = value;
18300
- return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
19201
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify2(record[key])}`).join(",")}}`;
18301
19202
  }
18302
19203
  function renderConstBlock(name, value) {
18303
19204
  return `const ${name} = ${JSON.stringify(value, null, 2)} as const;`;
@@ -20380,7 +21281,7 @@ var STABLE_AGENT_HARNESS_TEMPLATE_MANIFEST = defineHarnessTemplateManifest(
20380
21281
  "stable@1.0.0 manifest"
20381
21282
  );
20382
21283
  function hashHarnessTemplateValue(value) {
20383
- return hashString(stableStringify(value)) || "00000000";
21284
+ return hashString(stableStringify2(value)) || "00000000";
20384
21285
  }
20385
21286
  function renderStableHarnessPrompt(input) {
20386
21287
  const prompt = buildGranularAgentSystemPrompt(input);