@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.
@@ -3,11 +3,58 @@ import path from 'path';
3
3
  import OpenAI from 'openai';
4
4
  import * as Automerge from '@automerge/automerge';
5
5
 
6
+ var __create = Object.create;
6
7
  var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
10
+ var __typeError = (msg) => {
11
+ throw TypeError(msg);
12
+ };
13
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
14
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
7
15
  var __export = (target, all) => {
8
16
  for (var name in all)
9
17
  __defProp(target, name, { get: all[name], enumerable: true });
10
18
  };
19
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
20
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
21
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
22
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
23
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
24
+ var __runInitializers = (array, flags, self, value) => {
25
+ 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);
26
+ return value;
27
+ };
28
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
29
+ var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
30
+ var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
31
+ var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
32
+ var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
33
+ return __privateGet(this, extra);
34
+ }, set [name](x) {
35
+ return __privateSet(this, extra, x);
36
+ } }, name));
37
+ k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
38
+ for (var i = decorators.length - 1; i >= 0; i--) {
39
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
40
+ if (k) {
41
+ ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
42
+ if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
43
+ if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
44
+ }
45
+ 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;
46
+ if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
47
+ else if (typeof it !== "object" || it === null) __typeError("Object expected");
48
+ else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
49
+ }
50
+ return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
51
+ };
52
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
53
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
54
+ var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
55
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
56
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
57
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
11
58
 
12
59
  // src/customer-skill-authorization.ts
13
60
  var secret = () => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
@@ -7390,7 +7437,7 @@ function requireTransientFeedbackItem(value) {
7390
7437
  }
7391
7438
  return item;
7392
7439
  }
7393
- function createFeedPublisher(publish) {
7440
+ function createFeedPublisher(publish2) {
7394
7441
  const makeHandle = (initial) => {
7395
7442
  let current = initial;
7396
7443
  let mutationQueue = Promise.resolve();
@@ -7416,7 +7463,7 @@ function createFeedPublisher(publish) {
7416
7463
  const reservedOperationId = options.operationId || operationId("feed_transient_update");
7417
7464
  const reservedOptions = { ...options };
7418
7465
  return enqueueMutation(async () => {
7419
- const response = await publish("feed.transient.update", {
7466
+ const response = await publish2("feed.transient.update", {
7420
7467
  transientId: current.id,
7421
7468
  expectedRevision: current.revision,
7422
7469
  text,
@@ -7431,7 +7478,7 @@ function createFeedPublisher(publish) {
7431
7478
  const reservedOperationId = options.operationId || operationId("feed_transient_settle");
7432
7479
  const reservedOptions = { ...options };
7433
7480
  return enqueueMutation(async () => {
7434
- const response = await publish("feed.transient.settle", {
7481
+ const response = await publish2("feed.transient.settle", {
7435
7482
  transientId: current.id,
7436
7483
  expectedRevision: current.revision,
7437
7484
  ...text === void 0 ? {} : { text },
@@ -7454,7 +7501,7 @@ function createFeedPublisher(publish) {
7454
7501
  return {
7455
7502
  async feedback(text, options = {}) {
7456
7503
  return requireFeedbackItem(
7457
- await publish("feed.feedback", {
7504
+ await publish2("feed.feedback", {
7458
7505
  text,
7459
7506
  ...options,
7460
7507
  operationId: options.operationId || operationId("feed_feedback")
@@ -7463,7 +7510,7 @@ function createFeedPublisher(publish) {
7463
7510
  },
7464
7511
  async transientFeedback(text, options = {}) {
7465
7512
  const item = requireTransientFeedbackItem(
7466
- await publish("feed.transient.create", {
7513
+ await publish2("feed.transient.create", {
7467
7514
  text,
7468
7515
  ...options,
7469
7516
  operationId: options.operationId || operationId("feed_transient_create")
@@ -8482,10 +8529,340 @@ var noteMetamodelPackage = defineMetamodelPackage({
8482
8529
  }
8483
8530
  });
8484
8531
 
8532
+ // ../fractory/dist/annotations.js
8533
+ var interfaceBrand = Symbol("fractal.interface");
8534
+ var blocks = /* @__PURE__ */ new WeakMap();
8535
+ var wrappers = /* @__PURE__ */ new WeakMap();
8536
+ var listeners = /* @__PURE__ */ new Set();
8537
+ var host;
8538
+ function publish(event, adapter) {
8539
+ try {
8540
+ adapter?.emit(event);
8541
+ } catch {
8542
+ }
8543
+ for (const listener of listeners) {
8544
+ try {
8545
+ listener(event);
8546
+ } catch {
8547
+ }
8548
+ }
8549
+ }
8550
+ function identity(value) {
8551
+ if (!value.trim())
8552
+ throw new Error("Fractal identity must not be empty");
8553
+ return value;
8554
+ }
8555
+ function Block(id3, options = {}) {
8556
+ const definition = typeof id3 === "string" ? { ...options, id: identity(id3) } : { ...id3, id: identity(id3.id) };
8557
+ return (target, _context) => {
8558
+ blocks.set(target, definition);
8559
+ return target;
8560
+ };
8561
+ }
8562
+ function makeInterface(owner, name, options) {
8563
+ return Object.freeze({
8564
+ [interfaceBrand]: true,
8565
+ name,
8566
+ options: Object.freeze({ ...options }),
8567
+ get blockId() {
8568
+ const definition = blocks.get(owner());
8569
+ if (!definition)
8570
+ throw new Error(`Interface ${name} needs an annotated block`);
8571
+ return definition.id;
8572
+ },
8573
+ get id() {
8574
+ return options.id || `${this.blockId}::${name}`;
8575
+ }
8576
+ });
8577
+ }
8578
+ function Interface(options = {}, details = {}) {
8579
+ if (typeof options === "string") {
8580
+ const id3 = identity(options), name = id3.split("/").slice(-1)[0];
8581
+ if (details.parent)
8582
+ return makeInterface(details.parent, name, { ...details, id: id3 });
8583
+ return Object.freeze({
8584
+ [interfaceBrand]: true,
8585
+ id: id3,
8586
+ name,
8587
+ blockId: id3.includes("/") ? id3.slice(0, id3.lastIndexOf("/")) : "factory",
8588
+ options: Object.freeze({ ...details, id: id3 })
8589
+ });
8590
+ }
8591
+ if ("parent" in options)
8592
+ return makeInterface(options.parent, identity(options.id).split("/").slice(-1)[0], options);
8593
+ return interfaceDecorator(options);
8594
+ }
8595
+ function interfaceDecorator(options) {
8596
+ function decorate(target, context) {
8597
+ if (typeof context === "object") {
8598
+ if (!context.static || context.private)
8599
+ throw new Error("@Interface requires a public static field");
8600
+ context.addInitializer(function() {
8601
+ const owner = this;
8602
+ if (!owner[context.name]?.[interfaceBrand])
8603
+ Object.defineProperty(owner, context.name, {
8604
+ value: makeInterface(() => owner, String(context.name), options),
8605
+ writable: false,
8606
+ configurable: true
8607
+ });
8608
+ });
8609
+ return function() {
8610
+ return makeInterface(() => this, String(context.name), options);
8611
+ };
8612
+ }
8613
+ const value = makeInterface(() => target, String(context), options);
8614
+ Object.defineProperty(target, context, {
8615
+ value,
8616
+ writable: false,
8617
+ configurable: true
8618
+ });
8619
+ return void 0;
8620
+ }
8621
+ return decorate;
8622
+ }
8623
+ var FactoryViolation = class extends Error {
8624
+ phase;
8625
+ cause;
8626
+ constructor(phase, cause) {
8627
+ super(`Fractal ${phase} requirement failed`);
8628
+ this.phase = phase;
8629
+ this.cause = cause;
8630
+ this.name = "FactoryViolation";
8631
+ }
8632
+ };
8633
+ function validate(parser, value) {
8634
+ const result = parser?.parse(value);
8635
+ if (result && typeof result.then === "function") {
8636
+ void Promise.resolve(result).catch(() => {
8637
+ });
8638
+ throw new Error("Fractal runtime validators must be synchronous");
8639
+ }
8640
+ }
8641
+ function wrap(fn, name, reference, process2, options = {}) {
8642
+ const previous = wrappers.get(fn);
8643
+ if (previous) {
8644
+ fn = previous.original;
8645
+ reference ||= previous.reference;
8646
+ process2 ||= previous.process;
8647
+ options = { ...previous.options, ...options };
8648
+ }
8649
+ const wrapped = function(...args) {
8650
+ const api = reference?.();
8651
+ if (reference && (!api || api[interfaceBrand] !== true))
8652
+ throw new Error("@Method requires an initialized typed interface reference");
8653
+ const adapter = host;
8654
+ if (!listeners.size && !options.contract && !api?.options.auth)
8655
+ return fn.apply(this, args);
8656
+ const id3 = crypto.randomUUID();
8657
+ const frame = {
8658
+ targetId: process2?.id || `${api.id}#${options.name || name || fn.name || "call"}`,
8659
+ traceId: id3,
8660
+ runId: id3
8661
+ };
8662
+ let codeRevision;
8663
+ try {
8664
+ codeRevision = adapter?.codeRevision?.();
8665
+ } catch {
8666
+ }
8667
+ const started = performance.now();
8668
+ let terminal = false;
8669
+ const base = {
8670
+ targetId: frame.targetId,
8671
+ ...{},
8672
+ id: id3,
8673
+ traceId: frame.traceId,
8674
+ ...codeRevision ? { codeRevision } : {},
8675
+ runId: frame.runId,
8676
+ ...{},
8677
+ ...{},
8678
+ blockId: process2?.id || api.blockId,
8679
+ ...api ? { interfaceId: api.id } : {},
8680
+ method: options.name || name || fn.name || "call"
8681
+ };
8682
+ const emit = (status, failure) => {
8683
+ if (status !== "started") {
8684
+ if (terminal)
8685
+ return;
8686
+ terminal = true;
8687
+ frame.finished = true;
8688
+ }
8689
+ publish({
8690
+ ...base,
8691
+ timestamp: Date.now(),
8692
+ status,
8693
+ ...status !== "started" ? { durationMs: performance.now() - started } : {},
8694
+ ...failure ? { failure } : {}
8695
+ }, adapter);
8696
+ };
8697
+ const execute = () => {
8698
+ emit("started");
8699
+ let phase = "auth";
8700
+ const failed = (error) => {
8701
+ emit("failed", phase);
8702
+ throw error;
8703
+ };
8704
+ const invoke = () => {
8705
+ phase = "input";
8706
+ validate(options.contract?.args, args);
8707
+ phase = "execution";
8708
+ const value = fn.apply(this, args);
8709
+ const complete = (result) => {
8710
+ phase = "output";
8711
+ validate(options.contract?.result, result);
8712
+ emit("completed");
8713
+ return result;
8714
+ };
8715
+ if (value && typeof value.then === "function") {
8716
+ if (options.contract?.result)
8717
+ return Promise.resolve(value).then(complete).catch(failed);
8718
+ void Promise.resolve(value).then(() => emit("completed"), () => emit("failed", "execution"));
8719
+ return value;
8720
+ }
8721
+ return complete(value);
8722
+ };
8723
+ try {
8724
+ const authorized = api?.options.auth?.({
8725
+ receiver: this,
8726
+ args,
8727
+ context: adapter?.context?.()
8728
+ });
8729
+ if (authorized && typeof authorized === "object" && typeof authorized.then === "function") {
8730
+ if (fn.constructor.name !== "AsyncFunction") {
8731
+ void authorized.catch(() => {
8732
+ });
8733
+ throw new Error("Async auth requires an async method");
8734
+ }
8735
+ return authorized.then((allowed) => {
8736
+ if (allowed === false)
8737
+ throw new FactoryViolation("auth", false);
8738
+ return invoke();
8739
+ }).catch(failed);
8740
+ }
8741
+ if (authorized === false)
8742
+ throw new FactoryViolation("auth", false);
8743
+ return invoke();
8744
+ } catch (error) {
8745
+ return failed(error);
8746
+ }
8747
+ };
8748
+ const run = () => execute();
8749
+ try {
8750
+ return run();
8751
+ } catch (error) {
8752
+ if (fn.constructor.name === "AsyncFunction")
8753
+ return Promise.reject(error);
8754
+ throw error;
8755
+ }
8756
+ };
8757
+ Object.defineProperty(wrapped, "name", {
8758
+ value: options.name || name || fn.name,
8759
+ configurable: true
8760
+ });
8761
+ Object.defineProperty(wrapped, "length", {
8762
+ value: fn.length,
8763
+ configurable: true
8764
+ });
8765
+ if (process2)
8766
+ blocks.set(wrapped, process2);
8767
+ wrappers.set(wrapped, { original: fn, reference, process: process2, options });
8768
+ return wrapped;
8769
+ }
8770
+ function callableDecorator(reference, process2, options = {}) {
8771
+ function decorate(target, context, descriptor) {
8772
+ if (descriptor) {
8773
+ descriptor.value = wrap(descriptor.value, String(context), reference, process2, options);
8774
+ return descriptor;
8775
+ }
8776
+ const fn = target;
8777
+ return wrap(fn, typeof context === "object" ? String(context.name) : fn.name, reference, process2, options);
8778
+ }
8779
+ return decorate;
8780
+ }
8781
+ function Method(reference, options = {}) {
8782
+ return callableDecorator(reference, void 0, options);
8783
+ }
8784
+ function Process(id3, options = {}) {
8785
+ const definition = typeof id3 === "string" ? { ...options, id: identity(id3) } : { ...id3, id: identity(id3.id) };
8786
+ return callableDecorator(void 0, definition);
8787
+ }
8788
+
8485
8789
  // ../policy-engine/src/index.ts
8790
+ var DECISIONS = /* @__PURE__ */ new Set(["allow", "confirm", "deny"]);
8791
+ var BUILTIN_PROFILE_NAMES = ["allow-all", "confirm-all", "deny-all"];
8792
+ function getBuiltinPermissionProfiles() {
8793
+ return [
8794
+ {
8795
+ schemaVersion: 1,
8796
+ name: "allow-all",
8797
+ label: "Allow all",
8798
+ description: "Every declared action is visible unless a manifest policy denies it.",
8799
+ source: "builtin",
8800
+ defaults: { actionPolicy: "allow" },
8801
+ policies: [],
8802
+ actions: []
8803
+ },
8804
+ {
8805
+ schemaVersion: 1,
8806
+ name: "confirm-all",
8807
+ label: "Confirm all",
8808
+ description: "Every declared action requires user confirmation before execution.",
8809
+ source: "builtin",
8810
+ defaults: { actionPolicy: "confirm" },
8811
+ policies: [],
8812
+ actions: []
8813
+ },
8814
+ {
8815
+ schemaVersion: 1,
8816
+ name: "deny-all",
8817
+ label: "Deny all",
8818
+ description: "No declared action is invocable.",
8819
+ source: "builtin",
8820
+ defaults: { actionPolicy: "deny" },
8821
+ policies: [],
8822
+ actions: []
8823
+ }
8824
+ ];
8825
+ }
8826
+ function stableStringify(value) {
8827
+ return JSON.stringify(sortJson(value));
8828
+ }
8829
+ async function digestJson(value) {
8830
+ const payload = stableStringify(value);
8831
+ const cryptoLike = globalThis.crypto;
8832
+ if (cryptoLike?.subtle) {
8833
+ const data = new TextEncoder().encode(payload);
8834
+ const hash3 = await cryptoLike.subtle.digest("SHA-256", data);
8835
+ const hex = Array.from(new Uint8Array(hash3)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
8836
+ return `sha256:${hex}`;
8837
+ }
8838
+ let hash2 = 2166136261;
8839
+ for (let index = 0; index < payload.length; index += 1) {
8840
+ hash2 ^= payload.charCodeAt(index);
8841
+ hash2 = Math.imul(hash2, 16777619);
8842
+ }
8843
+ return `fnv1a:${(hash2 >>> 0).toString(16).padStart(8, "0")}`;
8844
+ }
8845
+ function sortJson(value) {
8846
+ if (Array.isArray(value)) return value.map(sortJson);
8847
+ if (isRecord(value)) {
8848
+ return Object.fromEntries(
8849
+ Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => [key, sortJson(child)])
8850
+ );
8851
+ }
8852
+ return value;
8853
+ }
8486
8854
  function isRecord(value) {
8487
8855
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
8488
8856
  }
8857
+ function normalizeProfileName(name) {
8858
+ if (typeof name !== "string") return null;
8859
+ const trimmed = name.trim();
8860
+ if (!/^[a-z0-9][a-z0-9._-]{1,63}$/.test(trimmed)) return null;
8861
+ return trimmed;
8862
+ }
8863
+ function normalizeDecision(value) {
8864
+ return DECISIONS.has(value) ? value : null;
8865
+ }
8489
8866
  function normalizePath(value) {
8490
8867
  if (Array.isArray(value)) {
8491
8868
  return value.map((part) => String(part)).filter(Boolean);
@@ -8558,6 +8935,131 @@ function normalizeCondition(input) {
8558
8935
  "Policy condition must contain all, any, not, input, object, or stateMachine"
8559
8936
  );
8560
8937
  }
8938
+ function readPath(root, path2) {
8939
+ let current = root;
8940
+ for (const part of path2) {
8941
+ if (!isRecord(current) && !Array.isArray(current)) {
8942
+ return { exists: false, value: void 0 };
8943
+ }
8944
+ if (!(part in current)) {
8945
+ return { exists: false, value: void 0 };
8946
+ }
8947
+ current = current[part];
8948
+ }
8949
+ return { exists: true, value: current };
8950
+ }
8951
+ function evaluateCondition(condition, context) {
8952
+ switch (condition.kind) {
8953
+ case "always":
8954
+ return true;
8955
+ case "all":
8956
+ return condition.conditions.every(
8957
+ (child) => evaluateCondition(child, context)
8958
+ );
8959
+ case "any":
8960
+ return condition.conditions.some(
8961
+ (child) => evaluateCondition(child, context)
8962
+ );
8963
+ case "not":
8964
+ return !evaluateCondition(condition.condition, context);
8965
+ case "predicate":
8966
+ return evaluatePredicate(condition, context);
8967
+ }
8968
+ }
8969
+ function evaluatePredicate(predicate, context) {
8970
+ const target = predicate.source === "input" ? context.input : predicate.source === "object" ? context.object : context.stateMachines;
8971
+ const { exists, value } = readPath(target || {}, predicate.path);
8972
+ if (predicate.operator === "exists") return exists;
8973
+ if (!exists) return false;
8974
+ const expected = predicate.value;
8975
+ switch (predicate.operator) {
8976
+ case "eq":
8977
+ return value === expected;
8978
+ case "neq":
8979
+ return value !== expected;
8980
+ case "gt":
8981
+ return typeof value === "number" && typeof expected === "number" && value > expected;
8982
+ case "gte":
8983
+ return typeof value === "number" && typeof expected === "number" && value >= expected;
8984
+ case "lt":
8985
+ return typeof value === "number" && typeof expected === "number" && value < expected;
8986
+ case "lte":
8987
+ return typeof value === "number" && typeof expected === "number" && value <= expected;
8988
+ case "contains":
8989
+ return Array.isArray(value) ? value.includes(expected) : typeof value === "string" && typeof expected === "string" && value.includes(expected);
8990
+ case "not_contains":
8991
+ return Array.isArray(value) ? !value.includes(expected) : typeof value === "string" && typeof expected === "string" && !value.includes(expected);
8992
+ case "starts_with":
8993
+ return typeof value === "string" && typeof expected === "string" && value.startsWith(expected);
8994
+ case "ends_with":
8995
+ return typeof value === "string" && typeof expected === "string" && value.endsWith(expected);
8996
+ }
8997
+ }
8998
+ function matchRule(rule, context) {
8999
+ if (!evaluateCondition(rule.condition, context)) return null;
9000
+ return {
9001
+ id: rule.id,
9002
+ outcome: rule.outcome,
9003
+ origin: rule.origin,
9004
+ reason: rule.reason,
9005
+ summary: rule.summary
9006
+ };
9007
+ }
9008
+ function evaluatePolicies(input) {
9009
+ const context = input.context || {};
9010
+ const manifestRules = input.manifestRules || [];
9011
+ const profileRules = input.profileRules || [];
9012
+ const defaultActionPolicy = input.defaultActionPolicy || "deny";
9013
+ const buckets = [
9014
+ {
9015
+ outcome: "deny",
9016
+ rules: manifestRules.filter((rule) => rule.outcome === "deny")
9017
+ },
9018
+ {
9019
+ outcome: "deny",
9020
+ rules: profileRules.filter((rule) => rule.outcome === "deny")
9021
+ },
9022
+ {
9023
+ outcome: "confirm",
9024
+ rules: manifestRules.filter((rule) => rule.outcome === "confirm")
9025
+ },
9026
+ {
9027
+ outcome: "confirm",
9028
+ rules: profileRules.filter((rule) => rule.outcome === "confirm")
9029
+ },
9030
+ {
9031
+ outcome: "allow",
9032
+ rules: profileRules.filter((rule) => rule.outcome === "allow")
9033
+ }
9034
+ ];
9035
+ for (const bucket of buckets) {
9036
+ const matches = bucket.rules.map((rule) => matchRule(rule, context)).filter((match) => match !== null);
9037
+ if (matches.length > 0) return { outcome: bucket.outcome, matches };
9038
+ }
9039
+ return {
9040
+ outcome: defaultActionPolicy,
9041
+ matches: defaultActionPolicy === "deny" ? [] : [
9042
+ {
9043
+ id: `profile-default-${defaultActionPolicy}`,
9044
+ outcome: defaultActionPolicy,
9045
+ origin: {
9046
+ kind: "permissionProfile",
9047
+ profileName: "active",
9048
+ source: "permissionProfile"
9049
+ },
9050
+ summary: `Profile default policy is ${defaultActionPolicy}`
9051
+ }
9052
+ ]
9053
+ };
9054
+ }
9055
+ function ruleSummary(outcome, reason, condition) {
9056
+ if (reason) return reason;
9057
+ if (condition.kind === "always") return `${capitalize(outcome)} always`;
9058
+ return `${capitalize(outcome)} when ${summarizeCondition(condition)}`;
9059
+ }
9060
+ function capitalize(value) {
9061
+ return value.slice(0, 1).toUpperCase() + value.slice(1);
9062
+ }
8561
9063
  function summarizeCondition(condition) {
8562
9064
  switch (condition.kind) {
8563
9065
  case "always":
@@ -8575,6 +9077,534 @@ function summarizeCondition(condition) {
8575
9077
  }
8576
9078
  }
8577
9079
  }
9080
+ function makeRule(input) {
9081
+ const condition = input.condition || { kind: "always" };
9082
+ return {
9083
+ ...input,
9084
+ condition,
9085
+ summary: ruleSummary(input.outcome, input.reason, condition)
9086
+ };
9087
+ }
9088
+ function actionIdentity(action, on) {
9089
+ return on ? `${on}:${action}` : `global:${action}`;
9090
+ }
9091
+ function normalizeAttachedClass(value) {
9092
+ if (!value) return null;
9093
+ if (!value.startsWith("@")) return value;
9094
+ const slashIndex = value.indexOf("/");
9095
+ return slashIndex === -1 ? value : value.slice(slashIndex + 1);
9096
+ }
9097
+ function resolveEffectReference(effects, action, on) {
9098
+ const normalizedOn = normalizeAttachedClass(on);
9099
+ const matches = effects.filter((effect) => {
9100
+ if (effect.name !== action) return false;
9101
+ const attachedClass = normalizeAttachedClass(effect.attachedClass);
9102
+ return normalizedOn ? attachedClass === normalizedOn : !attachedClass;
9103
+ });
9104
+ if (matches.length === 1) return matches[0];
9105
+ if (!normalizedOn) {
9106
+ const byName = effects.filter((effect) => effect.name === action);
9107
+ if (byName.length > 1) {
9108
+ const classes = byName.map(
9109
+ (effect) => normalizeAttachedClass(effect.attachedClass) || "global"
9110
+ ).join(", ");
9111
+ throw new Error(
9112
+ `Action "${action}" exists on ${classes}. Add "on" to disambiguate.`
9113
+ );
9114
+ }
9115
+ }
9116
+ if (matches.length > 1) {
9117
+ throw new Error(`Action "${action}" on "${String(on)}" is ambiguous.`);
9118
+ }
9119
+ throw new Error(
9120
+ on ? `Action "${action}" on "${on}" was not found.` : `Global action "${action}" was not found.`
9121
+ );
9122
+ }
9123
+ function manifestPolicyRulesForEffect(effect, manifestId) {
9124
+ const policies = isRecord(effect.metamodels?.policies) ? effect.metamodels?.policies : null;
9125
+ if (!policies) return [];
9126
+ const rules = [];
9127
+ const add = (outcome, specs, prefix) => {
9128
+ if (!Array.isArray(specs)) return;
9129
+ specs.forEach((spec, index) => {
9130
+ if (!isRecord(spec)) {
9131
+ throw new Error(
9132
+ `Manifest policy ${prefix}[${index}] for ${effect.effectKey} must be an object`
9133
+ );
9134
+ }
9135
+ const condition = normalizeCondition(spec.when);
9136
+ rules.push(
9137
+ makeRule({
9138
+ id: typeof spec.id === "string" ? spec.id : `manifest-${prefix}-${effect.effectKey}-${index + 1}`,
9139
+ origin: { kind: "manifest", manifestId, effectKey: effect.effectKey },
9140
+ outcome,
9141
+ reason: typeof spec.reason === "string" ? spec.reason : void 0,
9142
+ condition
9143
+ })
9144
+ );
9145
+ });
9146
+ };
9147
+ add("deny", policies.denyWhen, "denyWhen");
9148
+ add("confirm", policies.confirmWhen, "confirmWhen");
9149
+ add("allow", policies.allowWhen, "allowWhen");
9150
+ return rules;
9151
+ }
9152
+ function inputSchemaHasField(effect, path2) {
9153
+ if (path2.length === 0) return false;
9154
+ const properties = isRecord(effect.inputSchema?.properties) ? effect.inputSchema?.properties : {};
9155
+ return path2[0] in properties;
9156
+ }
9157
+ function validateLimitBands(effect, action, warnings) {
9158
+ const limits = action.limits || [];
9159
+ const byInput = /* @__PURE__ */ new Map();
9160
+ limits.forEach((limit, index) => {
9161
+ const path2 = normalizePath(limit.input);
9162
+ if (path2.length === 0) {
9163
+ throw new Error(`Limit ${index + 1} on ${action.action} requires input`);
9164
+ }
9165
+ if (!inputSchemaHasField(effect, path2)) {
9166
+ throw new Error(
9167
+ `Limit ${index + 1} on ${action.action} references unsupported input field "${path2.join(".")}"`
9168
+ );
9169
+ }
9170
+ if (!normalizeDecision(limit.decision)) {
9171
+ throw new Error(
9172
+ `Limit ${index + 1} on ${action.action} has invalid decision`
9173
+ );
9174
+ }
9175
+ if (limit.upTo === void 0 === (limit.above === void 0)) {
9176
+ throw new Error(
9177
+ `Limit ${index + 1} on ${action.action} must define exactly one of upTo or above`
9178
+ );
9179
+ }
9180
+ if (limit.reason === void 0) {
9181
+ warnings.push(`Limit ${index + 1} on ${action.action} has no reason`);
9182
+ }
9183
+ const key = path2.join(".");
9184
+ byInput.set(key, [...byInput.get(key) || [], limit]);
9185
+ });
9186
+ for (const [input, bands] of byInput.entries()) {
9187
+ const thresholds = /* @__PURE__ */ new Set();
9188
+ let previousUpTo = -Infinity;
9189
+ for (const band of bands) {
9190
+ const value = band.upTo ?? band.above;
9191
+ const key = `${band.upTo === void 0 ? "above" : "upTo"}:${value}`;
9192
+ if (thresholds.has(key)) {
9193
+ throw new Error(
9194
+ `Duplicate limit threshold ${key} for input "${input}"`
9195
+ );
9196
+ }
9197
+ thresholds.add(key);
9198
+ if (band.upTo !== void 0) {
9199
+ if (band.upTo < previousUpTo) {
9200
+ throw new Error(`Unordered limit bands for input "${input}"`);
9201
+ }
9202
+ previousUpTo = band.upTo;
9203
+ }
9204
+ }
9205
+ }
9206
+ }
9207
+ function compileProfileActionRules(input) {
9208
+ const { profile, action, effect, warnings } = input;
9209
+ const origin = {
9210
+ kind: "permissionProfile",
9211
+ profileName: action.ownerProfileName || profile.name,
9212
+ source: profile.source || "permissionProfile"
9213
+ };
9214
+ const rules = [];
9215
+ const baseId = action.id || `${profile.name}-${effect.effectKey}`;
9216
+ if (action.allow === "always") {
9217
+ rules.push(
9218
+ makeRule({
9219
+ id: `${baseId}-allow`,
9220
+ origin,
9221
+ outcome: "allow",
9222
+ reason: action.reason
9223
+ })
9224
+ );
9225
+ }
9226
+ if (action.confirm === "always") {
9227
+ rules.push(
9228
+ makeRule({
9229
+ id: `${baseId}-confirm`,
9230
+ origin,
9231
+ outcome: "confirm",
9232
+ reason: action.reason
9233
+ })
9234
+ );
9235
+ }
9236
+ if (action.deny === "always") {
9237
+ rules.push(
9238
+ makeRule({
9239
+ id: `${baseId}-deny`,
9240
+ origin,
9241
+ outcome: "deny",
9242
+ reason: action.reason
9243
+ })
9244
+ );
9245
+ }
9246
+ const addConditional = (outcome, specs, suffix) => {
9247
+ (specs || []).forEach((spec, index) => {
9248
+ rules.push(
9249
+ makeRule({
9250
+ id: spec.id || `${baseId}-${suffix}-${index + 1}`,
9251
+ origin,
9252
+ outcome,
9253
+ reason: spec.reason,
9254
+ condition: normalizeCondition(spec.when)
9255
+ })
9256
+ );
9257
+ });
9258
+ };
9259
+ addConditional("allow", action.allowWhen, "allowWhen");
9260
+ addConditional("confirm", action.confirmWhen, "confirmWhen");
9261
+ addConditional("deny", action.denyWhen, "denyWhen");
9262
+ validateLimitBands(effect, action, warnings);
9263
+ const previousUpToByInput = /* @__PURE__ */ new Map();
9264
+ (action.limits || []).forEach((limit, index) => {
9265
+ const path2 = normalizePath(limit.input);
9266
+ const pathKey = path2.join(".");
9267
+ const lowerBound = previousUpToByInput.get(pathKey);
9268
+ const upperCondition = {
9269
+ kind: "predicate",
9270
+ source: "input",
9271
+ path: path2,
9272
+ operator: limit.upTo !== void 0 ? "lte" : "gt",
9273
+ value: limit.upTo ?? limit.above
9274
+ };
9275
+ const condition = lowerBound !== void 0 && limit.upTo !== void 0 ? {
9276
+ kind: "all",
9277
+ conditions: [
9278
+ {
9279
+ kind: "predicate",
9280
+ source: "input",
9281
+ path: path2,
9282
+ operator: "gt",
9283
+ value: lowerBound
9284
+ },
9285
+ upperCondition
9286
+ ]
9287
+ } : upperCondition;
9288
+ rules.push(
9289
+ makeRule({
9290
+ id: limit.id || `${baseId}-limit-${index + 1}`,
9291
+ origin,
9292
+ outcome: limit.decision,
9293
+ reason: limit.reason,
9294
+ condition
9295
+ })
9296
+ );
9297
+ if (limit.upTo !== void 0) previousUpToByInput.set(pathKey, limit.upTo);
9298
+ });
9299
+ return rules;
9300
+ }
9301
+ function flattenProfiles(profiles, errors) {
9302
+ const byName = /* @__PURE__ */ new Map();
9303
+ for (const profile of profiles) {
9304
+ const name = normalizeProfileName(profile.name);
9305
+ if (!name) {
9306
+ errors.push(`Invalid permission profile name: ${String(profile.name)}`);
9307
+ continue;
9308
+ }
9309
+ if (byName.has(name)) {
9310
+ errors.push(`Duplicate permission profile name: ${name}`);
9311
+ continue;
9312
+ }
9313
+ byName.set(name, {
9314
+ ...profile,
9315
+ name,
9316
+ defaultsOwnerName: profile.defaultsOwnerName || name,
9317
+ policies: (profile.policies || []).map((policy) => ({
9318
+ ...policy,
9319
+ ownerProfileName: policy.ownerProfileName || name
9320
+ })),
9321
+ actions: (profile.actions || []).map((action) => ({
9322
+ ...action,
9323
+ ownerProfileName: action.ownerProfileName || name
9324
+ }))
9325
+ });
9326
+ }
9327
+ const flattening = /* @__PURE__ */ new Set();
9328
+ const flattened = /* @__PURE__ */ new Map();
9329
+ const flatten = (name, depth) => {
9330
+ if (depth > 5) {
9331
+ errors.push(`Permission profile inheritance depth exceeds 5 at ${name}`);
9332
+ return null;
9333
+ }
9334
+ const existing = flattened.get(name);
9335
+ if (existing) return existing;
9336
+ const profile = byName.get(name);
9337
+ if (!profile) {
9338
+ errors.push(`Missing parent permission profile: ${name}`);
9339
+ return null;
9340
+ }
9341
+ if (flattening.has(name)) {
9342
+ errors.push(`Permission profile inheritance cycle detected at ${name}`);
9343
+ return null;
9344
+ }
9345
+ flattening.add(name);
9346
+ let result = profile;
9347
+ if (profile.extends) {
9348
+ if (profile.defaults !== void 0) {
9349
+ errors.push(
9350
+ `Permission profile "${name}" extends "${profile.extends}" and cannot define defaults`
9351
+ );
9352
+ }
9353
+ const parent = flatten(profile.extends, depth + 1);
9354
+ if (parent) {
9355
+ const actionMap = /* @__PURE__ */ new Map();
9356
+ for (const action of parent.actions || []) {
9357
+ actionMap.set(actionIdentity(action.action, action.on), action);
9358
+ }
9359
+ for (const action of profile.actions || []) {
9360
+ actionMap.set(actionIdentity(action.action, action.on), action);
9361
+ }
9362
+ result = {
9363
+ ...profile,
9364
+ defaults: parent.defaults,
9365
+ defaultsOwnerName: parent.defaultsOwnerName || parent.name,
9366
+ policies: [...parent.policies || [], ...profile.policies || []],
9367
+ actions: [...actionMap.values()]
9368
+ };
9369
+ }
9370
+ }
9371
+ flattening.delete(name);
9372
+ flattened.set(name, result);
9373
+ return result;
9374
+ };
9375
+ for (const name of byName.keys()) flatten(name, 0);
9376
+ return [...flattened.values()];
9377
+ }
9378
+ function compileProfile(input) {
9379
+ const { profile, effects, manifestRules, warnings } = input;
9380
+ const defaultActionPolicy = normalizeDecision(profile.defaults?.actionPolicy) || "deny";
9381
+ const actionRules = {};
9382
+ const addRules = (effectKey, rules) => {
9383
+ if (rules.length === 0) return;
9384
+ actionRules[effectKey] = [...actionRules[effectKey] || [], ...rules];
9385
+ };
9386
+ for (const policy of profile.policies || []) {
9387
+ const outcome = normalizeDecision(policy.outcome || policy.decision);
9388
+ if (!outcome)
9389
+ throw new Error(
9390
+ `Profile "${profile.name}" has a policy with invalid decision`
9391
+ );
9392
+ const condition = normalizeCondition(policy.when);
9393
+ const targetEffects = policy.action ? [resolveEffectReference(effects, policy.action, policy.on)] : effects;
9394
+ for (const effect of targetEffects) {
9395
+ addRules(effect.effectKey, [
9396
+ makeRule({
9397
+ id: policy.id || `${profile.name}-${effect.effectKey}-profile-policy`,
9398
+ origin: {
9399
+ kind: "permissionProfile",
9400
+ profileName: policy.ownerProfileName || profile.name,
9401
+ source: profile.source || "permissionProfile"
9402
+ },
9403
+ outcome,
9404
+ reason: policy.reason,
9405
+ condition
9406
+ })
9407
+ ]);
9408
+ }
9409
+ }
9410
+ for (const action of profile.actions || []) {
9411
+ const effect = resolveEffectReference(effects, action.action, action.on);
9412
+ addRules(
9413
+ effect.effectKey,
9414
+ compileProfileActionRules({ profile, action, effect, warnings })
9415
+ );
9416
+ }
9417
+ const actionVisibility = effects.filter((effect) => {
9418
+ const rules = actionRules[effect.effectKey] || [];
9419
+ const denyVisibilityRules = [
9420
+ ...manifestRules[effect.effectKey] || [],
9421
+ ...rules
9422
+ ];
9423
+ if (denyVisibilityRules.some(
9424
+ (rule) => rule.outcome === "deny" && rule.condition.kind === "always"
9425
+ )) {
9426
+ return false;
9427
+ }
9428
+ if (defaultActionPolicy === "allow" || defaultActionPolicy === "confirm")
9429
+ return true;
9430
+ return denyVisibilityRules.some(
9431
+ (rule) => rule.outcome === "allow" || rule.outcome === "confirm"
9432
+ );
9433
+ }).map((effect) => effect.effectKey).sort();
9434
+ const summaries = Object.entries(actionRules).flatMap(
9435
+ ([effectKey, rules]) => rules.map((rule) => `${effectKey}: ${rule.summary}`)
9436
+ ).sort();
9437
+ return {
9438
+ name: profile.name,
9439
+ label: profile.label,
9440
+ description: profile.description,
9441
+ source: profile.source || "permissionProfile",
9442
+ sourcePath: profile.sourcePath,
9443
+ defaultActionPolicy,
9444
+ defaultActionPolicyOwner: profile.defaultsOwnerName || profile.name,
9445
+ digest: "",
9446
+ actionRules,
9447
+ actionVisibility,
9448
+ summaries,
9449
+ flattened: profile
9450
+ };
9451
+ }
9452
+ function normalizeSourceProfiles(sources) {
9453
+ const sourceProfiles = (sources || []).filter((profile) => isRecord(profile)).map((profile) => ({
9454
+ ...profile,
9455
+ source: profile.source || "permissionProfile"
9456
+ }));
9457
+ const nonBuiltin = sourceProfiles.filter(
9458
+ (profile) => !BUILTIN_PROFILE_NAMES.includes(
9459
+ profile.name
9460
+ )
9461
+ );
9462
+ return [...getBuiltinPermissionProfiles(), ...nonBuiltin];
9463
+ }
9464
+ Process({
9465
+ description: "Compile product permission rules into a bundle that runtime checks can evaluate.",
9466
+ id: "granular-product/compilation/metamodels-policy-compilation/compile",
9467
+ label: "Compile policy bundle",
9468
+ benchmarks: ["./compile.bench.ts"],
9469
+ tests: ["./index.test.ts"]
9470
+ })(async function compilePolicyBundle2(input) {
9471
+ const errors = [];
9472
+ const warnings = [];
9473
+ const effects = [...input.effects].sort(
9474
+ (left, right) => left.effectKey.localeCompare(right.effectKey)
9475
+ );
9476
+ const profiles = flattenProfiles(
9477
+ normalizeSourceProfiles(input.profileSources),
9478
+ errors
9479
+ );
9480
+ const manifestRules = {};
9481
+ for (const effect of effects) {
9482
+ try {
9483
+ const rules = manifestPolicyRulesForEffect(effect, input.manifestId);
9484
+ if (rules.length > 0) manifestRules[effect.effectKey] = rules;
9485
+ } catch (error) {
9486
+ errors.push(String(error instanceof Error ? error.message : error));
9487
+ }
9488
+ }
9489
+ const compiledProfiles = {};
9490
+ for (const profile of profiles) {
9491
+ try {
9492
+ const defaultActionPolicy = profile.defaults?.actionPolicy;
9493
+ if (defaultActionPolicy !== void 0 && !normalizeDecision(defaultActionPolicy)) {
9494
+ throw new Error(
9495
+ `Permission profile "${profile.name}" has invalid defaults.actionPolicy`
9496
+ );
9497
+ }
9498
+ const compiled = compileProfile({
9499
+ profile,
9500
+ effects,
9501
+ manifestRules,
9502
+ warnings
9503
+ });
9504
+ compiled.digest = await digestJson({
9505
+ profile: compiled.flattened,
9506
+ actionRules: compiled.actionRules,
9507
+ defaultActionPolicy: compiled.defaultActionPolicy
9508
+ });
9509
+ compiledProfiles[profile.name] = compiled;
9510
+ } catch (error) {
9511
+ errors.push(String(error instanceof Error ? error.message : error));
9512
+ }
9513
+ }
9514
+ const permissionProfilesDigest = await digestJson(
9515
+ Object.values(compiledProfiles).map((profile) => ({
9516
+ name: profile.name,
9517
+ digest: profile.digest,
9518
+ source: profile.source
9519
+ }))
9520
+ );
9521
+ const bundleWithoutDigest = {
9522
+ schemaVersion: 1,
9523
+ buildId: input.buildId,
9524
+ sandboxId: input.sandboxId,
9525
+ manifestDigest: input.manifestDigest,
9526
+ permissionProfilesDigest,
9527
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
9528
+ effects: effects.map((effect) => ({
9529
+ effectKey: effect.effectKey,
9530
+ name: effect.name,
9531
+ attachedClass: normalizeAttachedClass(effect.attachedClass),
9532
+ isStatic: effect.isStatic === true
9533
+ })),
9534
+ manifestRules,
9535
+ profiles: compiledProfiles
9536
+ };
9537
+ const bundleDigest = await digestJson(bundleWithoutDigest);
9538
+ return {
9539
+ bundle: { ...bundleWithoutDigest, bundleDigest },
9540
+ errors,
9541
+ warnings
9542
+ };
9543
+ });
9544
+ Process({
9545
+ description: "Evaluate compiled permission rules for an action and its current context.",
9546
+ id: "granular-product/effects/authorization-contracts/compiled-evaluation",
9547
+ label: "Evaluate compiled policies",
9548
+ benchmarks: ["./evaluation.bench.ts"],
9549
+ tests: ["./index.test.ts"]
9550
+ })(function evaluateCompiledPolicyBundle2(input) {
9551
+ const profile = input.bundle.profiles[input.profileName];
9552
+ if (!profile) {
9553
+ return {
9554
+ outcome: "deny",
9555
+ matches: [
9556
+ {
9557
+ id: "missing-profile",
9558
+ outcome: "deny",
9559
+ origin: {
9560
+ kind: "permissionProfile",
9561
+ profileName: input.profileName,
9562
+ source: "permissionProfile"
9563
+ },
9564
+ reason: `Permission profile "${input.profileName}" does not exist in this version`,
9565
+ summary: `Permission profile "${input.profileName}" does not exist in this version`
9566
+ }
9567
+ ]
9568
+ };
9569
+ }
9570
+ if (!profile.actionVisibility.includes(input.effectKey)) {
9571
+ return {
9572
+ outcome: "deny",
9573
+ matches: [
9574
+ {
9575
+ id: "action-not-visible",
9576
+ outcome: "deny",
9577
+ origin: {
9578
+ kind: "permissionProfile",
9579
+ profileName: input.profileName,
9580
+ source: profile.source
9581
+ },
9582
+ reason: `Action ${input.effectKey} is not visible for ${input.profileName}`,
9583
+ summary: `Action ${input.effectKey} is not visible for ${input.profileName}`
9584
+ }
9585
+ ]
9586
+ };
9587
+ }
9588
+ const decision = evaluatePolicies({
9589
+ manifestRules: input.bundle.manifestRules[input.effectKey] || [],
9590
+ profileRules: profile.actionRules[input.effectKey] || [],
9591
+ defaultActionPolicy: profile.defaultActionPolicy,
9592
+ context: input.context
9593
+ });
9594
+ return {
9595
+ outcome: decision.outcome,
9596
+ matches: decision.matches.map(
9597
+ (match) => match.id === `profile-default-${decision.outcome}` ? {
9598
+ ...match,
9599
+ origin: {
9600
+ kind: "permissionProfile",
9601
+ profileName: profile.name,
9602
+ source: profile.source
9603
+ }
9604
+ } : match
9605
+ )
9606
+ };
9607
+ });
8578
9608
 
8579
9609
  // ../metamodel-policy/src/index.ts
8580
9610
  function escapeGraphqlString(value) {
@@ -10622,11 +11652,11 @@ var Session = class {
10622
11652
  }
10623
11653
  this.eventListeners.get("effects:changed").push(handler);
10624
11654
  return () => {
10625
- const listeners = this.eventListeners.get("effects:changed");
10626
- if (listeners) {
11655
+ const listeners2 = this.eventListeners.get("effects:changed");
11656
+ if (listeners2) {
10627
11657
  this.eventListeners.set(
10628
11658
  "effects:changed",
10629
- listeners.filter((h) => h !== handler)
11659
+ listeners2.filter((h) => h !== handler)
10630
11660
  );
10631
11661
  }
10632
11662
  };
@@ -10641,11 +11671,11 @@ var Session = class {
10641
11671
  }
10642
11672
  this.eventListeners.get("tools:changed").push(handler);
10643
11673
  return () => {
10644
- const listeners = this.eventListeners.get("tools:changed");
10645
- if (listeners) {
11674
+ const listeners2 = this.eventListeners.get("tools:changed");
11675
+ if (listeners2) {
10646
11676
  this.eventListeners.set(
10647
11677
  "tools:changed",
10648
- listeners.filter((h) => h !== handler)
11678
+ listeners2.filter((h) => h !== handler)
10649
11679
  );
10650
11680
  }
10651
11681
  };
@@ -13249,7 +14279,11 @@ function isUnsupportedEffectCatalogMutation(error) {
13249
14279
  const message = error instanceof Error ? error.message : String(error);
13250
14280
  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");
13251
14281
  }
13252
- function planRecordObjectsChunks(records, batchSize) {
14282
+ var planRecordObjectsChunks = Process({
14283
+ id: "granular-product/authoring/importers-record-apis/record-objects/plan",
14284
+ label: "Plan record chunks",
14285
+ parent: () => Environment.prototype.recordObjects
14286
+ })(function planRecordObjectsChunks2(records, batchSize) {
13253
14287
  const total = records.length;
13254
14288
  const size = Math.max(1, Math.min(batchSize, total));
13255
14289
  const chunkCount = Math.ceil(total / size);
@@ -13259,7 +14293,7 @@ function planRecordObjectsChunks(records, batchSize) {
13259
14293
  plans.push({ chunkIndex, chunkCount, offset, slice });
13260
14294
  }
13261
14295
  return plans;
13262
- }
14296
+ });
13263
14297
  function preserveRecordObjectRealId(record) {
13264
14298
  const realId = record.id.trim();
13265
14299
  if (!realId) {
@@ -13484,15 +14518,54 @@ function isGraphQLMutationDocument(query) {
13484
14518
  }
13485
14519
  return false;
13486
14520
  }
13487
- var Environment = class _Environment {
13488
- granular;
13489
- envData;
13490
- _apiKey;
13491
- _apiEndpoint;
13492
- _tokenProvider;
13493
- _beforeMutationSend;
13494
- _graphqlIdempotencyKey;
14521
+ 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;
14522
+ _Environment_decorators = [Block({
14523
+ description: "Expose records, imports, queries, relationships and sessions for one product environment.",
14524
+ id: "granular-product/authoring/importers-record-apis",
14525
+ label: "Environment client",
14526
+ exposedBy: [() => Granular],
14527
+ tests: [
14528
+ "./record-objects.cancellation.test.ts",
14529
+ "./environment.feed.test.ts"
14530
+ ],
14531
+ parent: () => Granular
14532
+ })], _queries_dec = [Interface({
14533
+ label: "Queries & search",
14534
+ description: "Query the environment\u2019s graph or search its records."
14535
+ })], _stateChanges_dec = [Interface({
14536
+ label: "User state",
14537
+ description: "Record changes to user state and read the environment\u2019s current state."
14538
+ })], _sessions_dec = [Interface({
14539
+ label: "Sessions",
14540
+ description: "Create, connect, list and close conversations in this environment."
14541
+ })], _relationships_dec = [Interface({
14542
+ label: "Relationships",
14543
+ description: "Define, read, attach and detach relationships between records."
14544
+ })], _imports_dec = [Interface({
14545
+ id: "granular-product/ingestion/importer-lifecycle",
14546
+ label: "Background imports",
14547
+ description: "Submit a background record import and inspect or cancel its progress."
14548
+ })], _records_dec = [Interface({
14549
+ label: "Records",
14550
+ description: "Write customer records into the environment, including bounded batch requests."
14551
+ })], _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({
14552
+ id: "granular-product/authoring/importers-record-apis/record-objects",
14553
+ label: "Write record batches"
14554
+ }), Method(() => _Environment.records)], _executeRecordObjectsChunk_dec = [Process({
14555
+ id: "granular-product/authoring/importers-record-apis/record-objects/write-chunk",
14556
+ label: "Write chunk with retry",
14557
+ parent: () => _Environment.prototype.recordObjects
14558
+ })], _enqueueRecordImport_dec = [Method(() => _Environment.imports)], _listRecordImports_dec = [Method(() => _Environment.imports)], _getRecordImport_dec = [Method(() => _Environment.imports)], _cancelRecordImport_dec = [Method(() => _Environment.imports)];
14559
+ var _Environment = class _Environment {
13495
14560
  constructor(granular, envData, apiKey, apiEndpoint, tokenProvider, beforeMutationSend, graphqlIdempotencyKey) {
14561
+ __runInitializers(_init, 5, this);
14562
+ __publicField(this, "granular");
14563
+ __publicField(this, "envData");
14564
+ __publicField(this, "_apiKey");
14565
+ __publicField(this, "_apiEndpoint");
14566
+ __publicField(this, "_tokenProvider");
14567
+ __publicField(this, "_beforeMutationSend");
14568
+ __publicField(this, "_graphqlIdempotencyKey");
13496
14569
  this.granular = granular;
13497
14570
  this.envData = envData;
13498
14571
  this._apiKey = apiKey;
@@ -13742,10 +14815,6 @@ var Environment = class _Environment {
13742
14815
  }
13743
14816
  );
13744
14817
  }
13745
- /**
13746
- * Mirror product-owned workflow state into Granular without making Granular
13747
- * own the customer application's state machine.
13748
- */
13749
14818
  async recordState(input) {
13750
14819
  const { machine, state, ...target } = input;
13751
14820
  if (!machine.trim()) {
@@ -14017,30 +15086,6 @@ var Environment = class _Environment {
14017
15086
  const prefix = `${className}_`;
14018
15087
  return graphPath.startsWith(prefix) ? graphPath.substring(prefix.length) : graphPath;
14019
15088
  }
14020
- /**
14021
- * Execute a GraphQL query against the environment's graph.
14022
- *
14023
- * The query uses the Granular graph query language (based on Cypher/GraphQL).
14024
- * Authentication is handled automatically using the SDK's API key.
14025
- *
14026
- * @param query - The GraphQL query string
14027
- * @param variables - Optional variables for the query
14028
- * @returns The query result data
14029
- *
14030
- * @example
14031
- * ```typescript
14032
- * // Read the workspace
14033
- * const result = await env.graphql(
14034
- * `query { model(path: "workspace") { path label submodels { path label } } }`
14035
- * );
14036
- * console.log(result.data);
14037
- *
14038
- * // Create a model
14039
- * const created = await env.graphql(
14040
- * `mutation { at(path: "workspace") { create_submodel(subpath: "my_node", label: "My Node", prototype: "Model") { model { path label } } } }`
14041
- * );
14042
- * ```
14043
- */
14044
15089
  async graphql(query, variables, options) {
14045
15090
  const authToken = await this.resolveAuthToken();
14046
15091
  if (this._beforeMutationSend && isGraphQLMutationDocument(query)) {
@@ -14133,27 +15178,6 @@ var Environment = class _Environment {
14133
15178
  rank: rankRecordSearchResult(result, normalizedQuery, index)
14134
15179
  })).sort((left, right) => left.rank - right.rank).map((item) => item.result).slice(0, limit);
14135
15180
  }
14136
- // ==================== RELATIONSHIP METHODS ====================
14137
- /**
14138
- * Define a relationship between two model types.
14139
- *
14140
- * Creates both submodels (if they don't exist) and links them with
14141
- * a RelationshipDef node that encodes cardinality.
14142
- *
14143
- * @example
14144
- * ```typescript
14145
- * // Author has many Books, Book has one Author
14146
- * const rel = await env.defineRelationship({
14147
- * model: 'author',
14148
- * localSubmodel: 'books',
14149
- * localIsMany: true,
14150
- * foreignModel: 'book',
14151
- * foreignSubmodel: 'author',
14152
- * foreignIsMany: false,
14153
- * });
14154
- * console.log(rel.relationship_kind); // "one_to_many"
14155
- * ```
14156
- */
14157
15181
  async defineRelationship(options) {
14158
15182
  const result = await this.graphql(
14159
15183
  `mutation DefineRelationship(
@@ -14199,20 +15223,6 @@ var Environment = class _Environment {
14199
15223
  }
14200
15224
  return result.data.at.define_relationship;
14201
15225
  }
14202
- /**
14203
- * Get all relationships for a model type.
14204
- *
14205
- * @param modelPath - The model type path (e.g., "author")
14206
- * @returns Array of relationships from this model's perspective
14207
- *
14208
- * @example
14209
- * ```typescript
14210
- * const rels = await env.getRelationships('author');
14211
- * for (const rel of rels) {
14212
- * console.log(`${rel.local_submodel.path} -> ${rel.foreign_model.path} (${rel.relationship_kind})`);
14213
- * }
14214
- * ```
14215
- */
14216
15226
  async getRelationships(modelPath) {
14217
15227
  const result = await this.graphql(
14218
15228
  `query GetRelationships($path: String) {
@@ -14237,27 +15247,6 @@ var Environment = class _Environment {
14237
15247
  }
14238
15248
  return result.data?.model?.relationships || [];
14239
15249
  }
14240
- /**
14241
- * Attach a target model to a relationship submodel.
14242
- *
14243
- * Handles cardinality automatically:
14244
- * - "One" side: sets/replaces the reference
14245
- * - "Many" side: adds the target to the collection
14246
- *
14247
- * If the target model doesn't exist, it's created as an instance of the foreign type.
14248
- * Bidirectional sync is automatic.
14249
- *
14250
- * @param modelPath - The model instance path (e.g., "tolkien")
14251
- * @param submodelPath - The relationship submodel (e.g., "books")
14252
- * @param targetPath - The target model to attach (e.g., "lord_of_the_rings")
14253
- *
14254
- * @example
14255
- * ```typescript
14256
- * // Attach a book to an author (many side)
14257
- * await env.attach('tolkien', 'books', 'lord_of_the_rings');
14258
- * // This also automatically sets lord_of_the_rings:author -> tolkien
14259
- * ```
14260
- */
14261
15250
  async attach(modelPath, submodelPath, targetPath) {
14262
15251
  const result = await this.graphql(
14263
15252
  `mutation Attach($target: String!) {
@@ -14277,24 +15266,6 @@ var Environment = class _Environment {
14277
15266
  );
14278
15267
  }
14279
15268
  }
14280
- /**
14281
- * Detach a target model from a relationship submodel.
14282
- *
14283
- * Handles bidirectional cleanup automatically.
14284
- *
14285
- * @param modelPath - The model instance path
14286
- * @param submodelPath - The relationship submodel
14287
- * @param targetPath - The target to detach (optional for "one" side; omit on "many" side to detach all)
14288
- *
14289
- * @example
14290
- * ```typescript
14291
- * // Detach a specific book
14292
- * await env.detach('tolkien', 'books', 'lord_of_the_rings');
14293
- *
14294
- * // Detach all books
14295
- * await env.detach('tolkien', 'books');
14296
- * ```
14297
- */
14298
15269
  async detach(modelPath, submodelPath, targetPath) {
14299
15270
  const targetArg = targetPath ? `target: "${targetPath}"` : "";
14300
15271
  const result = await this.graphql(
@@ -14314,19 +15285,6 @@ var Environment = class _Environment {
14314
15285
  );
14315
15286
  }
14316
15287
  }
14317
- /**
14318
- * List all related models through a relationship submodel.
14319
- *
14320
- * @param modelPath - The model instance path
14321
- * @param submodelPath - The relationship submodel
14322
- * @returns Array of related model references
14323
- *
14324
- * @example
14325
- * ```typescript
14326
- * const books = await env.listRelated('tolkien', 'books');
14327
- * console.log(books); // [{ path: "lord_of_the_rings", label: "Lord of the Rings" }, ...]
14328
- * ```
14329
- */
14330
15288
  async listRelated(modelPath, submodelPath) {
14331
15289
  const result = await this.graphql(
14332
15290
  `mutation ListRelated {
@@ -14748,38 +15706,6 @@ var Environment = class _Environment {
14748
15706
  }
14749
15707
  }
14750
15708
  }
14751
- // ==================== RECORD OBJECT ====================
14752
- /**
14753
- * Create or update an instance of a class in the graph.
14754
- *
14755
- * Uses `instantiate` under the hood, which has find-or-create semantics:
14756
- * if an instance with the given `id` already exists for the class it is
14757
- * returned; otherwise a new instance is created. Fields are then set
14758
- * (overwriting previous values) and relationships are attached.
14759
- *
14760
- * The graph path is derived as `{className}_{id}` to ensure uniqueness
14761
- * across classes (two objects of different classes may share the same
14762
- * real-world ID). Relationship targets are also resolved automatically
14763
- * using the foreign class from the relationship definition.
14764
- *
14765
- * @param options - The object specification
14766
- * @returns The graph path, real-world ID, and creation status
14767
- *
14768
- * @example
14769
- * ```typescript
14770
- * // Create an author with fields
14771
- * const result = await env.recordObject({
14772
- * className: 'author',
14773
- * id: 'tolkien',
14774
- * label: 'J.R.R. Tolkien',
14775
- * fields: { name: 'J.R.R. Tolkien', birth_year: 1892 },
14776
- * relationships: { books: ['lotr', 'silmarillion'] },
14777
- * });
14778
- * // result.path → 'author_tolkien' (internal graph path)
14779
- * // result.id → 'tolkien' (real-world ID)
14780
- * // result.created → true
14781
- * ```
14782
- */
14783
15709
  async recordObject(options) {
14784
15710
  const results = await this.recordObjects([options]);
14785
15711
  const result = results[0];
@@ -14788,24 +15714,6 @@ var Environment = class _Environment {
14788
15714
  }
14789
15715
  return result;
14790
15716
  }
14791
- /**
14792
- * Batch version of `recordObject()`.
14793
- *
14794
- * Sends rows through the control-plane **`/records/batch`** endpoint in **chunks** (default
14795
- * **100** records per HTTP request) so individual requests stay bounded and gateway timeouts are
14796
- * unlikely. Each chunk is retried on transient network / worker errors.
14797
- *
14798
- * Use the optional second argument to:
14799
- * - **`batchSize`** — rows per POST (smaller = more progress events; larger = fewer round trips).
14800
- * - **`concurrency`** — run up to N chunk POSTs in parallel (capped at 16) when you want lower wall time.
14801
- * - **`onChunkComplete`** — hook for UIs after each chunk succeeds (row order in the returned array
14802
- * always matches `records`; chunk **completion** order may differ when `concurrency > 1`).
14803
- *
14804
- * For **asynchronous** ingestion with worker-side batching and aggregate counters (`queued`,
14805
- * `completed`, …), use **`enqueueRecordImport`** and poll **`getRecordImport`** /
14806
- * **`getRecordImportSummary`** — best for very large fire-and-forget loads when immediate
14807
- * synchronous commit of every row is not required.
14808
- */
14809
15717
  async recordObjects(records, options) {
14810
15718
  options?.signal?.throwIfAborted();
14811
15719
  if (!Array.isArray(records) || records.length === 0) {
@@ -14890,15 +15798,6 @@ var Environment = class _Environment {
14890
15798
  }
14891
15799
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
14892
15800
  }
14893
- /**
14894
- * Queue a background record import for this environment (async worker pipeline).
14895
- *
14896
- * **vs `recordObjects`:** this path accepts the full payload in one request, returns an
14897
- * **`importId`**, and processes rows in the background — use **`getRecordImport`** /
14898
- * **`getRecordImportSummary`** for progress. Choose it for large bulk loads where you do not
14899
- * need every row committed before the HTTP call returns. Use **`recordObjects`** when you need
14900
- * synchronous upserts and fine-grained chunk progress via **`onChunkComplete`**.
14901
- */
14902
15801
  async enqueueRecordImport(records, options = {}) {
14903
15802
  const recordsToImport = records.map(preserveRecordObjectRealId);
14904
15803
  return this.controlPlaneRequest(
@@ -14915,9 +15814,6 @@ var Environment = class _Environment {
14915
15814
  }
14916
15815
  );
14917
15816
  }
14918
- /**
14919
- * List queued or completed record imports for this environment.
14920
- */
14921
15817
  async listRecordImports(status) {
14922
15818
  const suffix = status ? `?status=${encodeURIComponent(status)}` : "";
14923
15819
  const response = await this.controlPlaneRequest(
@@ -14940,9 +15836,6 @@ var Environment = class _Environment {
14940
15836
  const summary = await this.getRecordImportSummary();
14941
15837
  return summary.awaitingRecords;
14942
15838
  }
14943
- /**
14944
- * Fetch a single record import by id.
14945
- */
14946
15839
  async getRecordImport(importId) {
14947
15840
  return this.controlPlaneRequest(
14948
15841
  `/control/record-imports/${importId}`
@@ -14957,9 +15850,6 @@ var Environment = class _Environment {
14957
15850
  const response = await this.controlPlaneRequest(`/control/record-imports/${importId}/items${suffix}`);
14958
15851
  return Array.isArray(response.items) ? response.items : [];
14959
15852
  }
14960
- /**
14961
- * Cancel a queued/background record import.
14962
- */
14963
15853
  async cancelRecordImport(importId) {
14964
15854
  return this.controlPlaneRequest(
14965
15855
  `/control/record-imports/${importId}/cancel`,
@@ -14969,17 +15859,75 @@ var Environment = class _Environment {
14969
15859
  );
14970
15860
  }
14971
15861
  };
14972
- var EnvironmentSession = class extends Session {
14973
- environment;
14974
- sessionDataRoutePrefix;
14975
- sessionDataHeaders;
14976
- beforeMutationSend;
14977
- heartbeatTimer = null;
14978
- heartbeatProbeInFlight = false;
14979
- /** The last known graph container status, updated by checkReadiness(). */
14980
- graphContainerStatus = null;
15862
+ _init = __decoratorStart(null);
15863
+ __decorateElement(_init, 1, "recordState", _recordState_dec, _Environment);
15864
+ __decorateElement(_init, 1, "listSessions", _listSessions_dec, _Environment);
15865
+ __decorateElement(_init, 1, "getUserEnvironmentState", _getUserEnvironmentState_dec, _Environment);
15866
+ __decorateElement(_init, 1, "createSession", _createSession_dec, _Environment);
15867
+ __decorateElement(_init, 1, "connectSession", _connectSession_dec, _Environment);
15868
+ __decorateElement(_init, 1, "closeSession", _closeSession_dec, _Environment);
15869
+ __decorateElement(_init, 1, "graphql", _graphql_dec, _Environment);
15870
+ __decorateElement(_init, 1, "searchRecords", _searchRecords_dec, _Environment);
15871
+ __decorateElement(_init, 1, "defineRelationship", _defineRelationship_dec, _Environment);
15872
+ __decorateElement(_init, 1, "getRelationships", _getRelationships_dec, _Environment);
15873
+ __decorateElement(_init, 1, "attach", _attach_dec, _Environment);
15874
+ __decorateElement(_init, 1, "detach", _detach_dec, _Environment);
15875
+ __decorateElement(_init, 1, "listRelated", _listRelated_dec, _Environment);
15876
+ __decorateElement(_init, 1, "recordObject", _recordObject_dec, _Environment);
15877
+ __decorateElement(_init, 1, "recordObjects", _recordObjects_dec, _Environment);
15878
+ __decorateElement(_init, 1, "executeRecordObjectsChunk", _executeRecordObjectsChunk_dec, _Environment);
15879
+ __decorateElement(_init, 1, "enqueueRecordImport", _enqueueRecordImport_dec, _Environment);
15880
+ __decorateElement(_init, 1, "listRecordImports", _listRecordImports_dec, _Environment);
15881
+ __decorateElement(_init, 1, "getRecordImport", _getRecordImport_dec, _Environment);
15882
+ __decorateElement(_init, 1, "cancelRecordImport", _cancelRecordImport_dec, _Environment);
15883
+ __decorateElement(_init, 13, "queries", _queries_dec, _Environment);
15884
+ __decorateElement(_init, 13, "stateChanges", _stateChanges_dec, _Environment);
15885
+ __decorateElement(_init, 13, "sessions", _sessions_dec, _Environment);
15886
+ __decorateElement(_init, 13, "relationships", _relationships_dec, _Environment);
15887
+ __decorateElement(_init, 13, "imports", _imports_dec, _Environment);
15888
+ __decorateElement(_init, 13, "records", _records_dec, _Environment);
15889
+ _Environment = __decorateElement(_init, 0, "Environment", _Environment_decorators, _Environment);
15890
+ __publicField(_Environment, "queries", __runInitializers(_init, 8, _Environment)), __runInitializers(_init, 11, _Environment);
15891
+ __publicField(_Environment, "stateChanges", __runInitializers(_init, 12, _Environment)), __runInitializers(_init, 15, _Environment);
15892
+ __publicField(_Environment, "sessions", __runInitializers(_init, 16, _Environment)), __runInitializers(_init, 19, _Environment);
15893
+ __publicField(_Environment, "relationships", __runInitializers(_init, 20, _Environment)), __runInitializers(_init, 23, _Environment);
15894
+ __publicField(_Environment, "imports", __runInitializers(_init, 24, _Environment)), __runInitializers(_init, 27, _Environment);
15895
+ __publicField(_Environment, "records", __runInitializers(_init, 28, _Environment)), __runInitializers(_init, 31, _Environment);
15896
+ __runInitializers(_init, 1, _Environment);
15897
+ var Environment = _Environment;
15898
+ 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;
15899
+ _EnvironmentSession_decorators = [Block({
15900
+ description: "Expose conversation messages, selected data and lifecycle operations for one environment session.",
15901
+ id: "granular-product/authoring/importers-record-apis/session-client",
15902
+ label: "Session client",
15903
+ exposedBy: [() => Environment, () => Granular],
15904
+ tests: [
15905
+ "./environment.feed.test.ts",
15906
+ "./environment.assistant-reply.test.ts"
15907
+ ],
15908
+ parent: () => Environment
15909
+ })];
15910
+ var _EnvironmentSession = class _EnvironmentSession extends (_a = Session, _lifecycle_dec = [Interface({
15911
+ label: "Connection lifecycle",
15912
+ description: "Check session readiness and close or disconnect the session client."
15913
+ })], _records_dec2 = [Interface({
15914
+ label: "Session records",
15915
+ description: "Write records or mention an existing record in the current conversation."
15916
+ })], _conversation_dec = [Interface({
15917
+ label: "Conversation data",
15918
+ description: "Read the conversation document and selected data, and publish assistant replies."
15919
+ })], _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) {
14981
15920
  constructor(client, environment, clientId, options = {}) {
14982
15921
  super(client, clientId, { initialQuota: options.initialQuota });
15922
+ __runInitializers(_init2, 5, this);
15923
+ __publicField(this, "environment");
15924
+ __publicField(this, "sessionDataRoutePrefix");
15925
+ __publicField(this, "sessionDataHeaders");
15926
+ __publicField(this, "beforeMutationSend");
15927
+ __publicField(this, "heartbeatTimer", null);
15928
+ __publicField(this, "heartbeatProbeInFlight", false);
15929
+ /** The last known graph container status, updated by checkReadiness(). */
15930
+ __publicField(this, "graphContainerStatus", null);
14983
15931
  this.environment = environment;
14984
15932
  this.sessionDataRoutePrefix = options.sessionDataRoutePrefix || "/orchestrator/ws/sessions";
14985
15933
  this.sessionDataHeaders = options.sessionDataHeaders || {};
@@ -15077,9 +16025,6 @@ var EnvironmentSession = class extends Session {
15077
16025
  get feedback() {
15078
16026
  return this.environment.feedback;
15079
16027
  }
15080
- /**
15081
- * Return a plain JS copy of the synced session heap.
15082
- */
15083
16028
  getHeap() {
15084
16029
  const doc = this.document;
15085
16030
  return normalizeHeapSnapshot(doc?.heap);
@@ -15154,22 +16099,9 @@ var EnvironmentSession = class extends Session {
15154
16099
  });
15155
16100
  return response.json();
15156
16101
  }
15157
- /**
15158
- * Fetch the live session document from the runtime DO.
15159
- *
15160
- * For presentation history use `feed.list()` or `transcript.list()`.
15161
- * Timeline and job collections are diagnostic/execution data only.
15162
- */
15163
16102
  async getDocument() {
15164
16103
  return this.sessionDataRequest("/document");
15165
16104
  }
15166
- /**
15167
- * Publish one terminal assistant reply from a trusted server integration.
15168
- *
15169
- * This uses the API-key-authenticated HTTP session boundary. Delegated
15170
- * browser sessions cannot use it and never receive assistant feed-authoring
15171
- * capability through their WebSocket.
15172
- */
15173
16105
  async publishAssistantReply(input) {
15174
16106
  if (this.sessionDataRoutePrefix === "/sdk/browser-sessions") {
15175
16107
  throw new Error(
@@ -15551,13 +16483,6 @@ var EnvironmentSession = class extends Session {
15551
16483
  async listFeedback() {
15552
16484
  return this.environment.listFeedback();
15553
16485
  }
15554
- /**
15555
- * Close the session and disconnect from the sandbox.
15556
- *
15557
- * Sends `client.goodbye` over WebSocket first, then issues an HTTP fallback
15558
- * to the runtime goodbye endpoint if no definitive WS-side runtime notify
15559
- * acknowledgement was observed.
15560
- */
15561
16486
  async disconnect() {
15562
16487
  this.stopHeartbeat();
15563
16488
  this.disposeSessionFeed();
@@ -15601,15 +16526,9 @@ var EnvironmentSession = class extends Session {
15601
16526
  this.stopHeartbeat();
15602
16527
  this.client.disconnect({ reason: "Transport detach" });
15603
16528
  }
15604
- /**
15605
- * Backwards-compatible alias for `disconnect()`.
15606
- */
15607
16529
  async close() {
15608
16530
  await this.disconnect();
15609
16531
  }
15610
- /**
15611
- * Check if the graph container is ready and warm.
15612
- */
15613
16532
  async checkReadiness() {
15614
16533
  const result = await this.client.call("client.heartbeat", {});
15615
16534
  const containerStatus = result?.graphContainerStatus ?? {
@@ -15621,6 +16540,24 @@ var EnvironmentSession = class extends Session {
15621
16540
  return containerStatus;
15622
16541
  }
15623
16542
  };
16543
+ _init2 = __decoratorStart(_a);
16544
+ __decorateElement(_init2, 1, "getHeap", _getHeap_dec, _EnvironmentSession);
16545
+ __decorateElement(_init2, 1, "getDocument", _getDocument_dec, _EnvironmentSession);
16546
+ __decorateElement(_init2, 1, "publishAssistantReply", _publishAssistantReply_dec, _EnvironmentSession);
16547
+ __decorateElement(_init2, 1, "mentionRecord", _mentionRecord_dec, _EnvironmentSession);
16548
+ __decorateElement(_init2, 1, "recordObjects", _recordObjects_dec2, _EnvironmentSession);
16549
+ __decorateElement(_init2, 1, "disconnect", _disconnect_dec, _EnvironmentSession);
16550
+ __decorateElement(_init2, 1, "close", _close_dec, _EnvironmentSession);
16551
+ __decorateElement(_init2, 1, "checkReadiness", _checkReadiness_dec, _EnvironmentSession);
16552
+ __decorateElement(_init2, 13, "lifecycle", _lifecycle_dec, _EnvironmentSession);
16553
+ __decorateElement(_init2, 13, "records", _records_dec2, _EnvironmentSession);
16554
+ __decorateElement(_init2, 13, "conversation", _conversation_dec, _EnvironmentSession);
16555
+ _EnvironmentSession = __decorateElement(_init2, 0, "EnvironmentSession", _EnvironmentSession_decorators, _EnvironmentSession);
16556
+ __publicField(_EnvironmentSession, "lifecycle", __runInitializers(_init2, 8, _EnvironmentSession)), __runInitializers(_init2, 11, _EnvironmentSession);
16557
+ __publicField(_EnvironmentSession, "records", __runInitializers(_init2, 12, _EnvironmentSession)), __runInitializers(_init2, 15, _EnvironmentSession);
16558
+ __publicField(_EnvironmentSession, "conversation", __runInitializers(_init2, 16, _EnvironmentSession)), __runInitializers(_init2, 19, _EnvironmentSession);
16559
+ __runInitializers(_init2, 1, _EnvironmentSession);
16560
+ var EnvironmentSession = _EnvironmentSession;
15624
16561
  var OntologyHandle = class {
15625
16562
  granular;
15626
16563
  ontologyNameOrId;
@@ -15672,40 +16609,62 @@ var OntologyHandle = class {
15672
16609
  };
15673
16610
  }
15674
16611
  };
15675
- var Granular = class _Granular {
15676
- /** Tenant events feed, authenticated with this client's credentials. */
15677
- eventsFeed = new EventsFeed(
15678
- (path2, options) => this.request(path2, options)
15679
- );
15680
- apiKey;
15681
- apiUrl;
15682
- httpUrl;
15683
- tokenProvider;
15684
- WebSocketCtor;
15685
- onUnexpectedClose;
15686
- onReconnectError;
15687
- effectHostUrl;
15688
- graphqlIdempotencyKey;
15689
- debugHttp = process.env.GRANULAR_DEBUG_HTTP === "1";
15690
- /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
15691
- sandboxEffects = /* @__PURE__ */ new Map();
15692
- /** Live sandbox-scoped effect hosts keyed by sandboxId */
15693
- sandboxEffectHosts = /* @__PURE__ */ new Map();
15694
- developmentProviders = /* @__PURE__ */ new Map();
15695
- usersProviders = /* @__PURE__ */ new Map();
15696
- /** In-flight host connection promises to avoid duplicate concurrent connects */
15697
- sandboxEffectHostPromises = /* @__PURE__ */ new Map();
15698
- effectHostGenerations = /* @__PURE__ */ new Map();
15699
- effectHostRecovery = /* @__PURE__ */ new Map();
15700
- /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
15701
- ontologyImporters = /* @__PURE__ */ new Map();
15702
- /** Resolved importer hooks keyed by sandboxId for fast lookups during openEnvironment(). */
15703
- sandboxImporters = /* @__PURE__ */ new Map();
16612
+ 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;
16613
+ _Granular_decorators = [Block({
16614
+ description: "Authenticate an application and provide access to its environments, sessions and registered action handlers.",
16615
+ id: "granular-product/authoring/sdk-ontology-facade",
16616
+ label: "Granular client",
16617
+ tests: ["./environment.opening.test.ts"],
16618
+ docs: "../README.md"
16619
+ })], _transport_dec = [Interface({
16620
+ label: "HTTP requests",
16621
+ description: "Send authenticated SDK requests to the configured Granular API."
16622
+ })], _effectHosts_dec = [Interface({
16623
+ id: "granular-product/authoring/live-effect-hosts",
16624
+ label: "Application action handlers",
16625
+ description: "Register application functions that Granular may invoke as actions, and disconnect handlers when they are no longer available."
16626
+ })], _sessions_dec2 = [Interface({
16627
+ label: "Sessions",
16628
+ description: "Create, list, connect and close product sessions through the SDK."
16629
+ })], _environmentAccess_dec = [Interface({
16630
+ label: "Environment access",
16631
+ description: "Resolve a user\u2019s assigned environment or open a connection to it."
16632
+ })], _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)];
16633
+ var _Granular = class _Granular {
15704
16634
  /**
15705
16635
  * Create a new Granular client
15706
16636
  * @param options - Client configuration
15707
16637
  */
15708
16638
  constructor(options) {
16639
+ __runInitializers(_init3, 5, this);
16640
+ /** Tenant events feed, authenticated with this client's credentials. */
16641
+ __publicField(this, "eventsFeed", new EventsFeed(
16642
+ (path2, options) => this.request(path2, options)
16643
+ ));
16644
+ __publicField(this, "apiKey");
16645
+ __publicField(this, "apiUrl");
16646
+ __publicField(this, "httpUrl");
16647
+ __publicField(this, "tokenProvider");
16648
+ __publicField(this, "WebSocketCtor");
16649
+ __publicField(this, "onUnexpectedClose");
16650
+ __publicField(this, "onReconnectError");
16651
+ __publicField(this, "effectHostUrl");
16652
+ __publicField(this, "graphqlIdempotencyKey");
16653
+ __publicField(this, "debugHttp", process.env.GRANULAR_DEBUG_HTTP === "1");
16654
+ /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
16655
+ __publicField(this, "sandboxEffects", /* @__PURE__ */ new Map());
16656
+ /** Live sandbox-scoped effect hosts keyed by sandboxId */
16657
+ __publicField(this, "sandboxEffectHosts", /* @__PURE__ */ new Map());
16658
+ __publicField(this, "developmentProviders", /* @__PURE__ */ new Map());
16659
+ __publicField(this, "usersProviders", /* @__PURE__ */ new Map());
16660
+ /** In-flight host connection promises to avoid duplicate concurrent connects */
16661
+ __publicField(this, "sandboxEffectHostPromises", /* @__PURE__ */ new Map());
16662
+ __publicField(this, "effectHostGenerations", /* @__PURE__ */ new Map());
16663
+ __publicField(this, "effectHostRecovery", /* @__PURE__ */ new Map());
16664
+ /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
16665
+ __publicField(this, "ontologyImporters", /* @__PURE__ */ new Map());
16666
+ /** Resolved importer hooks keyed by sandboxId for fast lookups during openEnvironment(). */
16667
+ __publicField(this, "sandboxImporters", /* @__PURE__ */ new Map());
15709
16668
  const auth = options.token ?? options.apiKey;
15710
16669
  if (!auth) {
15711
16670
  throw new Error(
@@ -15753,8 +16712,8 @@ var Granular = class _Granular {
15753
16712
  sandboxId
15754
16713
  );
15755
16714
  if (!importer) throw new Error("No environment importer registered.");
15756
- const host = await this.ensureSandboxEffectHost(sandboxId);
15757
- await host.wsClient.call("environment.importer.register", {});
16715
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
16716
+ await host2.wsClient.call("environment.importer.register", {});
15758
16717
  }
15759
16718
  clearEnvironmentImporter(ontologyNameOrId) {
15760
16719
  this.ontologyImporters.delete(ontologyNameOrId);
@@ -15856,29 +16815,6 @@ var Granular = class _Granular {
15856
16815
  "openEnvironment() requires either userId, granularId, or a user object returned by recordUser()."
15857
16816
  );
15858
16817
  }
15859
- /**
15860
- * Open or resolve an ontology environment for one user without opening a session.
15861
- *
15862
- * @example
15863
- * ```typescript
15864
- * const environment = await granular.openEnvironment({
15865
- * ontology: 'my-ontology',
15866
- * tag: 'dev',
15867
- * userId: 'user_123',
15868
- * permissions: ['agent'],
15869
- * });
15870
- *
15871
- * await environment.data.record({
15872
- * className: 'customer',
15873
- * id: 'acme',
15874
- * fields: { name: 'Acme' },
15875
- * });
15876
- *
15877
- * const session = await environment.sessions.create();
15878
- * const job = await session.submitJob(`return "hello";`);
15879
- * console.log(await job.result);
15880
- * ```
15881
- */
15882
16818
  async openEnvironment(options) {
15883
16819
  const resolved = await this.resolveOpenEnvironmentData(
15884
16820
  options,
@@ -15888,11 +16824,6 @@ var Granular = class _Granular {
15888
16824
  await this.maybeRunEnvironmentImporter(resolved, environment);
15889
16825
  return environment;
15890
16826
  }
15891
- /**
15892
- * Read the active environment selected by Granular for an already-recorded
15893
- * external user. This is intentionally read-only: browser/login code must
15894
- * not create subjects or environments as a side effect.
15895
- */
15896
16827
  async getActiveEnvironmentForUser(options) {
15897
16828
  const sandboxId = options.sandboxId.trim();
15898
16829
  const tagName = options.tag.trim();
@@ -15938,13 +16869,6 @@ var Granular = class _Granular {
15938
16869
  throw error;
15939
16870
  }
15940
16871
  }
15941
- /**
15942
- * Resolve one exact environment only when Granular confirms that it belongs
15943
- * to the given external user in the requested sandbox (and, optionally,
15944
- * tag). This is deliberately read-only: callers use it to keep an already
15945
- * opened delegated workspace stable while a newer active environment is
15946
- * being prepared in the background.
15947
- */
15948
16872
  async getEnvironmentForUser(options) {
15949
16873
  const sandboxId = options.sandboxId.trim();
15950
16874
  const userId = options.userId.trim();
@@ -15987,11 +16911,6 @@ var Granular = class _Granular {
15987
16911
  }
15988
16912
  return this.bindEnvironmentHandle(environment);
15989
16913
  }
15990
- /**
15991
- * Register one reviewed, pre-existing environment as the active workspace
15992
- * for an external user. This is for a controlled migration only: it does
15993
- * not create an environment and it does not run an importer.
15994
- */
15995
16914
  async adoptEnvironmentForUser(options) {
15996
16915
  const sandboxId = options.sandboxId.trim();
15997
16916
  const tagName = options.tag.trim();
@@ -16038,11 +16957,6 @@ var Granular = class _Granular {
16038
16957
  normalizeEnvironmentData(payload.environment)
16039
16958
  );
16040
16959
  }
16041
- /**
16042
- * Deprecated compatibility alias for `openEnvironment()`.
16043
- *
16044
- * `connect()` no longer opens a runtime session automatically.
16045
- */
16046
16960
  async connect(options) {
16047
16961
  return this.openEnvironment({
16048
16962
  ...options,
@@ -16346,9 +17260,6 @@ var Granular = class _Granular {
16346
17260
  setupOperationKey: resetKey
16347
17261
  };
16348
17262
  }
16349
- /**
16350
- * List indexed sessions using ownership filters and bounded pagination.
16351
- */
16352
17263
  async listSessions(options) {
16353
17264
  const items = [];
16354
17265
  let cursor = options.cursor?.trim() || void 0;
@@ -16545,10 +17456,6 @@ var Granular = class _Granular {
16545
17456
  }
16546
17457
  return (/* @__PURE__ */ new Date(0)).toISOString();
16547
17458
  }
16548
- /**
16549
- * Create a new session (conversation) for an existing environment and connect to it.
16550
- * The runtime graph is shared across all sessions for the same environment.
16551
- */
16552
17459
  async createSession(options) {
16553
17460
  const clientId = options.clientId || `client_${Date.now()}`;
16554
17461
  const sessionScope = options.sessionScope?.trim() || void 0;
@@ -16569,9 +17476,6 @@ var Granular = class _Granular {
16569
17476
  });
16570
17477
  return this.bindWebSocketEnvironmentSession(environment, clientId, session);
16571
17478
  }
16572
- /**
16573
- * Connect to an existing open session (same conversation thread) using a freshly minted WebSocket token.
16574
- */
16575
17479
  async connectSession(options) {
16576
17480
  const clientId = options.clientId || `client_${Date.now()}`;
16577
17481
  const minted = await this.request(`/ws/sessions/${encodeURIComponent(options.sessionId)}/token`, {
@@ -16598,7 +17502,6 @@ var Granular = class _Granular {
16598
17502
  metadata: options?.metadata
16599
17503
  });
16600
17504
  }
16601
- /** End a session through the runtime, or disconnect its connected handle. */
16602
17505
  async closeSession(sessionId, environment) {
16603
17506
  if (environment && environment.sessionId === sessionId) {
16604
17507
  await environment.disconnect();
@@ -16609,9 +17512,6 @@ var Granular = class _Granular {
16609
17512
  { method: "POST" }
16610
17513
  );
16611
17514
  }
16612
- /**
16613
- * Re-open a closed session in the index and connect to its existing runtime document.
16614
- */
16615
17515
  async reopenSession(sessionId, options) {
16616
17516
  await this.request(`/control/sessions/${encodeURIComponent(sessionId)}`, {
16617
17517
  method: "PATCH",
@@ -16852,25 +17752,25 @@ var Granular = class _Granular {
16852
17752
  }
16853
17753
  return serialized;
16854
17754
  }
16855
- async publishSandboxEffectCatalog(host) {
17755
+ async publishSandboxEffectCatalog(host2) {
16856
17756
  const effects = Array.from(
16857
- this.getSandboxEffectMap(host.sandboxId).values()
17757
+ this.getSandboxEffectMap(host2.sandboxId).values()
16858
17758
  ).map((effect) => this.serializeEffect(effect));
16859
17759
  let acceptedCount = 0;
16860
17760
  const rejected = [];
16861
17761
  try {
16862
17762
  await withTimeout(
16863
- host.wsClient.call("effects.resetCatalog", {}),
17763
+ host2.wsClient.call("effects.resetCatalog", {}),
16864
17764
  EFFECT_CATALOG_SYNC_TIMEOUT_MS,
16865
- `effects.resetCatalog for sandbox ${host.sandboxId}`
17765
+ `effects.resetCatalog for sandbox ${host2.sandboxId}`
16866
17766
  );
16867
17767
  for (const batch of chunkItems(effects, EFFECT_CATALOG_SYNC_BATCH_SIZE)) {
16868
17768
  const result = await withTimeout(
16869
- host.wsClient.call("effects.addCatalog", {
17769
+ host2.wsClient.call("effects.addCatalog", {
16870
17770
  effects: batch
16871
17771
  }),
16872
17772
  EFFECT_CATALOG_SYNC_TIMEOUT_MS,
16873
- `effects.addCatalog for sandbox ${host.sandboxId}`
17773
+ `effects.addCatalog for sandbox ${host2.sandboxId}`
16874
17774
  );
16875
17775
  acceptedCount += typeof result?.acceptedCount === "number" ? result.acceptedCount : 0;
16876
17776
  if (Array.isArray(result?.rejected)) {
@@ -16882,11 +17782,11 @@ var Granular = class _Granular {
16882
17782
  throw error;
16883
17783
  }
16884
17784
  const result = await withTimeout(
16885
- host.wsClient.call("effects.publishCatalog", {
17785
+ host2.wsClient.call("effects.publishCatalog", {
16886
17786
  effects
16887
17787
  }),
16888
17788
  EFFECT_CATALOG_SYNC_TIMEOUT_MS,
16889
- `effects.publishCatalog for sandbox ${host.sandboxId}`
17789
+ `effects.publishCatalog for sandbox ${host2.sandboxId}`
16890
17790
  );
16891
17791
  acceptedCount = typeof result?.acceptedCount === "number" ? result.acceptedCount : 0;
16892
17792
  if (Array.isArray(result?.rejected)) {
@@ -16898,12 +17798,12 @@ var Granular = class _Granular {
16898
17798
  (entry) => `${entry.name || "unknown"}: ${entry.reason || "rejected"}`
16899
17799
  ).join("; ");
16900
17800
  throw new Error(
16901
- `Failed to publish live effects for sandbox ${host.sandboxId}: ${detail}`
17801
+ `Failed to publish live effects for sandbox ${host2.sandboxId}: ${detail}`
16902
17802
  );
16903
17803
  }
16904
17804
  if (rejected.length > 0) {
16905
17805
  console.warn(
16906
- `[Granular] Some live effects were rejected for sandbox ${host.sandboxId}:`,
17806
+ `[Granular] Some live effects were rejected for sandbox ${host2.sandboxId}:`,
16907
17807
  rejected
16908
17808
  );
16909
17809
  }
@@ -16912,8 +17812,8 @@ var Granular = class _Granular {
16912
17812
  let lastError;
16913
17813
  for (let attempt = 1; attempt <= EFFECT_CATALOG_SYNC_RETRY_COUNT; attempt += 1) {
16914
17814
  try {
16915
- const host = await this.ensureSandboxEffectHost(sandboxId);
16916
- await this.publishSandboxEffectCatalog(host);
17815
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
17816
+ await this.publishSandboxEffectCatalog(host2);
16917
17817
  return;
16918
17818
  } catch (error) {
16919
17819
  lastError = error;
@@ -16930,11 +17830,11 @@ var Granular = class _Granular {
16930
17830
  }
16931
17831
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
16932
17832
  }
16933
- recoverEffectHost(host, error) {
16934
- const sandboxId = host.sandboxId;
16935
- if (host.recovering || this.sandboxEffectHosts.get(sandboxId) !== host)
17833
+ recoverEffectHost(host2, error) {
17834
+ const sandboxId = host2.sandboxId;
17835
+ if (host2.recovering || this.sandboxEffectHosts.get(sandboxId) !== host2)
16936
17836
  return;
16937
- host.recovering = true;
17837
+ host2.recovering = true;
16938
17838
  this.disconnectSandboxEffectHost(sandboxId);
16939
17839
  const state = {
16940
17840
  attempt: 0,
@@ -16957,7 +17857,7 @@ var Granular = class _Granular {
16957
17857
  );
16958
17858
  try {
16959
17859
  this.onReconnectError?.({
16960
- sessionId: `effect-host:${host.effectClientId}`,
17860
+ sessionId: `effect-host:${host2.effectClientId}`,
16961
17861
  error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError),
16962
17862
  timestamp: Date.now(),
16963
17863
  terminal: !retryable
@@ -17010,13 +17910,13 @@ var Granular = class _Granular {
17010
17910
  )
17011
17911
  };
17012
17912
  }
17013
- async recoverSourceCommits(host) {
17913
+ async recoverSourceCommits(host2) {
17014
17914
  const stores = new Set(
17015
- Array.from(this.getSandboxEffectMap(host.sandboxId).values()).map((effect) => effect.commit?.storage).filter(Boolean)
17915
+ Array.from(this.getSandboxEffectMap(host2.sandboxId).values()).map((effect) => effect.commit?.storage).filter(Boolean)
17016
17916
  );
17017
17917
  for (const store of stores) {
17018
17918
  try {
17019
- await store.recover(this.effectCommitTransport(), host.sandboxId);
17919
+ await store.recover(this.effectCommitTransport(), host2.sandboxId);
17020
17920
  } catch (error) {
17021
17921
  console.warn(
17022
17922
  "[Granular] Source commit delivery remains pending:",
@@ -17025,43 +17925,43 @@ var Granular = class _Granular {
17025
17925
  }
17026
17926
  }
17027
17927
  }
17028
- startEffectHostHeartbeat(host) {
17029
- if (host.heartbeatTimer) {
17030
- clearInterval(host.heartbeatTimer);
17928
+ startEffectHostHeartbeat(host2) {
17929
+ if (host2.heartbeatTimer) {
17930
+ clearInterval(host2.heartbeatTimer);
17031
17931
  }
17032
- host.heartbeatInFlight = false;
17932
+ host2.heartbeatInFlight = false;
17033
17933
  const sendHeartbeat = (failureLabel, recoverOnFailure) => {
17034
- if (host.heartbeatInFlight || host.recovering) {
17934
+ if (host2.heartbeatInFlight || host2.recovering) {
17035
17935
  return;
17036
17936
  }
17037
- host.heartbeatInFlight = true;
17038
- host.wsClient.call("client.heartbeat", {}).then(() => this.recoverSourceCommits(host)).catch((error) => {
17039
- console.warn(`${failureLabel} ${host.sandboxId}:`, error);
17937
+ host2.heartbeatInFlight = true;
17938
+ host2.wsClient.call("client.heartbeat", {}).then(() => this.recoverSourceCommits(host2)).catch((error) => {
17939
+ console.warn(`${failureLabel} ${host2.sandboxId}:`, error);
17040
17940
  if (recoverOnFailure) {
17041
- this.recoverEffectHost(host, error);
17941
+ this.recoverEffectHost(host2, error);
17042
17942
  }
17043
17943
  }).finally(() => {
17044
- host.heartbeatInFlight = false;
17944
+ host2.heartbeatInFlight = false;
17045
17945
  });
17046
17946
  };
17047
17947
  sendHeartbeat(
17048
17948
  "[Granular] Initial effect host heartbeat failed for sandbox",
17049
17949
  false
17050
17950
  );
17051
- host.heartbeatTimer = setInterval(() => {
17951
+ host2.heartbeatTimer = setInterval(() => {
17052
17952
  sendHeartbeat(
17053
17953
  "[Granular] Effect host heartbeat failed for sandbox",
17054
17954
  true
17055
17955
  );
17056
17956
  }, 1e4);
17057
17957
  }
17058
- stopEffectHostHeartbeat(host) {
17059
- if (!host?.heartbeatTimer) {
17958
+ stopEffectHostHeartbeat(host2) {
17959
+ if (!host2?.heartbeatTimer) {
17060
17960
  return;
17061
17961
  }
17062
- clearInterval(host.heartbeatTimer);
17063
- host.heartbeatTimer = null;
17064
- host.heartbeatInFlight = false;
17962
+ clearInterval(host2.heartbeatTimer);
17963
+ host2.heartbeatTimer = null;
17964
+ host2.heartbeatInFlight = false;
17065
17965
  }
17066
17966
  async registerUsers(ontologyNameOrId, handler, options) {
17067
17967
  const provider = new UsersProvider(handler, options);
@@ -17069,8 +17969,8 @@ var Granular = class _Granular {
17069
17969
  const previous = this.usersProviders.get(sandboxId);
17070
17970
  this.usersProviders.set(sandboxId, provider);
17071
17971
  try {
17072
- const host = await this.ensureSandboxEffectHost(sandboxId);
17073
- if (provider.registration?.providerId !== host.effectClientId) await this.registerUsersOnHost(host, provider);
17972
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
17973
+ if (provider.registration?.providerId !== host2.effectClientId) await this.registerUsersOnHost(host2, provider);
17074
17974
  if (!provider.registration) throw new Error("User directory registration is no longer live.");
17075
17975
  return provider.registration;
17076
17976
  } catch (error) {
@@ -17081,10 +17981,10 @@ var Granular = class _Granular {
17081
17981
  throw error;
17082
17982
  }
17083
17983
  }
17084
- async registerUsersOnHost(host, provider) {
17085
- const registration = await host.wsClient.call("users.register", {});
17086
- if (this.usersProviders.get(host.sandboxId) !== provider) throw new Error("User directory registration was replaced.");
17087
- provider.bind(registration, host.sandboxId, host.effectClientId);
17984
+ async registerUsersOnHost(host2, provider) {
17985
+ const registration = await host2.wsClient.call("users.register", {});
17986
+ if (this.usersProviders.get(host2.sandboxId) !== provider) throw new Error("User directory registration was replaced.");
17987
+ provider.bind(registration, host2.sandboxId, host2.effectClientId);
17088
17988
  }
17089
17989
  /** Publish only public setup metadata; product session authority stays in resolveLaunch. */
17090
17990
  async registerCustomerSkill(ontologyNameOrId, options) {
@@ -17136,10 +18036,10 @@ var Granular = class _Granular {
17136
18036
  const previous = this.developmentProviders.get(sandboxId);
17137
18037
  this.developmentProviders.set(sandboxId, provider);
17138
18038
  try {
17139
- const host = await this.ensureSandboxEffectHost(sandboxId);
18039
+ const host2 = await this.ensureSandboxEffectHost(sandboxId);
17140
18040
  if (this.developmentProviders.get(sandboxId) !== provider) throw new Error("Development registration was replaced.");
17141
- if (provider.registration?.providerId !== host.effectClientId) {
17142
- await this.registerDevelopmentOnHost(host, provider);
18041
+ if (provider.registration?.providerId !== host2.effectClientId) {
18042
+ await this.registerDevelopmentOnHost(host2, provider);
17143
18043
  }
17144
18044
  if (!provider.registration) throw new Error("Development provider registration is no longer live.");
17145
18045
  return provider.registration;
@@ -17151,38 +18051,38 @@ var Granular = class _Granular {
17151
18051
  throw error;
17152
18052
  }
17153
18053
  }
17154
- async registerDevelopmentOnHost(host, provider) {
17155
- const registration = await host.wsClient.call(
18054
+ async registerDevelopmentOnHost(host2, provider) {
18055
+ const registration = await host2.wsClient.call(
17156
18056
  "onboarding.register",
17157
18057
  provider.registrationParams()
17158
18058
  );
17159
- if (this.developmentProviders.get(host.sandboxId) !== provider)
18059
+ if (this.developmentProviders.get(host2.sandboxId) !== provider)
17160
18060
  throw new Error("Development registration was replaced.");
17161
- provider.bind(registration, host.sandboxId, host.effectClientId);
18061
+ provider.bind(registration, host2.sandboxId, host2.effectClientId);
17162
18062
  }
17163
- async synchronizeEffectHost(host) {
17164
- if (host.syncPromise) {
17165
- return host.syncPromise;
18063
+ async synchronizeEffectHost(host2) {
18064
+ if (host2.syncPromise) {
18065
+ return host2.syncPromise;
17166
18066
  }
17167
- host.syncPromise = (async () => {
17168
- await host.wsClient.call("client.hello", {
17169
- clientId: host.clientId,
18067
+ host2.syncPromise = (async () => {
18068
+ await host2.wsClient.call("client.hello", {
18069
+ clientId: host2.clientId,
17170
18070
  protocolVersion: "2.0"
17171
18071
  });
17172
- await this.publishSandboxEffectCatalog(host);
17173
- if (this.resolveEnvironmentImporter(host.sandboxId, host.sandboxId))
17174
- await host.wsClient.call("environment.importer.register", {});
17175
- const users2 = this.usersProviders.get(host.sandboxId);
17176
- if (users2) await this.registerUsersOnHost(host, users2);
17177
- const development = this.developmentProviders.get(host.sandboxId);
17178
- if (development) await this.registerDevelopmentOnHost(host, development);
17179
- this.startEffectHostHeartbeat(host);
18072
+ await this.publishSandboxEffectCatalog(host2);
18073
+ if (this.resolveEnvironmentImporter(host2.sandboxId, host2.sandboxId))
18074
+ await host2.wsClient.call("environment.importer.register", {});
18075
+ const users2 = this.usersProviders.get(host2.sandboxId);
18076
+ if (users2) await this.registerUsersOnHost(host2, users2);
18077
+ const development = this.developmentProviders.get(host2.sandboxId);
18078
+ if (development) await this.registerDevelopmentOnHost(host2, development);
18079
+ this.startEffectHostHeartbeat(host2);
17180
18080
  })();
17181
18081
  try {
17182
- await host.syncPromise;
18082
+ await host2.syncPromise;
17183
18083
  } finally {
17184
- if (host.syncPromise) {
17185
- host.syncPromise = null;
18084
+ if (host2.syncPromise) {
18085
+ host2.syncPromise = null;
17186
18086
  }
17187
18087
  }
17188
18088
  }
@@ -17212,7 +18112,7 @@ var Granular = class _Granular {
17212
18112
  onUnexpectedClose: this.onUnexpectedClose,
17213
18113
  onReconnectError: this.onReconnectError
17214
18114
  });
17215
- const host = {
18115
+ const host2 = {
17216
18116
  generation: generation2,
17217
18117
  sandboxId,
17218
18118
  effectClientId,
@@ -17299,20 +18199,20 @@ var Granular = class _Granular {
17299
18199
  };
17300
18200
  });
17301
18201
  wsClient.on("open", () => {
17302
- void this.synchronizeEffectHost(host).catch((error) => {
18202
+ void this.synchronizeEffectHost(host2).catch((error) => {
17303
18203
  console.error(
17304
18204
  `[Granular] Failed to re-sync effect host for sandbox ${sandboxId}:`,
17305
18205
  error
17306
18206
  );
17307
- this.recoverEffectHost(host, error);
18207
+ this.recoverEffectHost(host2, error);
17308
18208
  });
17309
18209
  });
17310
18210
  wsClient.on("disconnect", () => {
17311
- this.stopEffectHostHeartbeat(host);
18211
+ this.stopEffectHostHeartbeat(host2);
17312
18212
  const users2 = this.usersProviders.get(sandboxId);
17313
- if (users2?.registration?.providerId === host.effectClientId) users2.unbind();
18213
+ if (users2?.registration?.providerId === host2.effectClientId) users2.unbind();
17314
18214
  const provider = this.developmentProviders.get(sandboxId);
17315
- if (provider?.registration?.providerId === host.effectClientId) provider.unbind();
18215
+ if (provider?.registration?.providerId === host2.effectClientId) provider.unbind();
17316
18216
  });
17317
18217
  try {
17318
18218
  await withTimeout(
@@ -17320,13 +18220,13 @@ var Granular = class _Granular {
17320
18220
  EFFECT_HOST_CONNECT_TIMEOUT_MS,
17321
18221
  `effect host WebSocket connect for sandbox ${sandboxId}`
17322
18222
  );
17323
- await this.synchronizeEffectHost(host);
18223
+ await this.synchronizeEffectHost(host2);
17324
18224
  if ((this.effectHostGenerations.get(sandboxId) || 0) !== generation2)
17325
18225
  throw new Error("Effect host connection was canceled");
17326
- this.sandboxEffectHosts.set(sandboxId, host);
17327
- return host;
18226
+ this.sandboxEffectHosts.set(sandboxId, host2);
18227
+ return host2;
17328
18228
  } catch (error) {
17329
- this.stopEffectHostHeartbeat(host);
18229
+ this.stopEffectHostHeartbeat(host2);
17330
18230
  wsClient.disconnect({ reason: "Effect host initialization failed" });
17331
18231
  throw error;
17332
18232
  }
@@ -17350,20 +18250,14 @@ var Granular = class _Granular {
17350
18250
  const recovering = this.effectHostRecovery.get(sandboxId);
17351
18251
  if (recovering?.timer) clearTimeout(recovering.timer);
17352
18252
  this.effectHostRecovery.delete(sandboxId);
17353
- const host = this.sandboxEffectHosts.get(sandboxId);
17354
- if (!host) {
18253
+ const host2 = this.sandboxEffectHosts.get(sandboxId);
18254
+ if (!host2) {
17355
18255
  return;
17356
18256
  }
17357
18257
  this.sandboxEffectHosts.delete(sandboxId);
17358
- this.stopEffectHostHeartbeat(host);
17359
- host.wsClient.disconnect();
18258
+ this.stopEffectHostHeartbeat(host2);
18259
+ host2.wsClient.disconnect();
17360
18260
  }
17361
- /**
17362
- * Register an effect (tool) for a specific sandbox.
17363
- *
17364
- * @param sandboxNameOrId - The name or ID of the sandbox
17365
- * @param effect - The tool definition and handler
17366
- */
17367
18261
  async registerEffect(sandboxNameOrId, effect) {
17368
18262
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
17369
18263
  const sandboxId = sandbox.sandboxId;
@@ -17373,11 +18267,6 @@ var Granular = class _Granular {
17373
18267
  );
17374
18268
  await this.syncSandboxEffectCatalog(sandboxId);
17375
18269
  }
17376
- /**
17377
- * Register multiple effects (tools) for a specific sandbox.
17378
- *
17379
- * batch version of `registerEffect`.
17380
- */
17381
18270
  async registerEffects(sandboxNameOrId, effects) {
17382
18271
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
17383
18272
  const sandboxId = sandbox.sandboxId;
@@ -17387,12 +18276,6 @@ var Granular = class _Granular {
17387
18276
  }
17388
18277
  await this.syncSandboxEffectCatalog(sandboxId);
17389
18278
  }
17390
- /**
17391
- * Unregister an effect from a sandbox.
17392
- *
17393
- * Removes it from the local sandbox registry and updates the
17394
- * sandbox-scoped live catalog.
17395
- */
17396
18279
  async unregisterEffect(sandboxNameOrId, name) {
17397
18280
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
17398
18281
  const sandboxId = sandbox.sandboxId;
@@ -17415,12 +18298,6 @@ var Granular = class _Granular {
17415
18298
  }
17416
18299
  await this.syncSandboxEffectCatalog(sandboxId);
17417
18300
  }
17418
- /**
17419
- * Disconnect one sandbox-scoped effect host, or all of them when no sandbox is provided.
17420
- *
17421
- * This is primarily useful for long-lived helper processes such as generated
17422
- * `granular-effects.ts` scripts that need to shut down cleanly on SIGINT/SIGTERM.
17423
- */
17424
18301
  async disconnectEffects(sandboxNameOrId) {
17425
18302
  if (sandboxNameOrId) {
17426
18303
  const sandbox = await this.findOrCreateSandbox(sandboxNameOrId);
@@ -17845,9 +18722,6 @@ var Granular = class _Granular {
17845
18722
  throw new Error(`Ontology not found: ${ontologyNameOrId}`);
17846
18723
  return result.items[0].sandboxId;
17847
18724
  }
17848
- /**
17849
- * Make an authenticated API request
17850
- */
17851
18725
  async request(path2, options = {}) {
17852
18726
  const url = `${this.httpUrl}${path2}`;
17853
18727
  if (this.debugHttp) {
@@ -17897,6 +18771,33 @@ var Granular = class _Granular {
17897
18771
  throw new Error(`Granular API Error: exhausted retries for ${url}`);
17898
18772
  }
17899
18773
  };
18774
+ _init3 = __decoratorStart(null);
18775
+ __decorateElement(_init3, 1, "openEnvironment", _openEnvironment_dec, _Granular);
18776
+ __decorateElement(_init3, 1, "getActiveEnvironmentForUser", _getActiveEnvironmentForUser_dec, _Granular);
18777
+ __decorateElement(_init3, 1, "getEnvironmentForUser", _getEnvironmentForUser_dec, _Granular);
18778
+ __decorateElement(_init3, 1, "adoptEnvironmentForUser", _adoptEnvironmentForUser_dec, _Granular);
18779
+ __decorateElement(_init3, 1, "connect", _connect_dec, _Granular);
18780
+ __decorateElement(_init3, 1, "listSessions", _listSessions_dec2, _Granular);
18781
+ __decorateElement(_init3, 1, "createSession", _createSession_dec2, _Granular);
18782
+ __decorateElement(_init3, 1, "connectSession", _connectSession_dec2, _Granular);
18783
+ __decorateElement(_init3, 1, "closeSession", _closeSession_dec2, _Granular);
18784
+ __decorateElement(_init3, 1, "reopenSession", _reopenSession_dec, _Granular);
18785
+ __decorateElement(_init3, 1, "registerEffect", _registerEffect_dec, _Granular);
18786
+ __decorateElement(_init3, 1, "registerEffects", _registerEffects_dec, _Granular);
18787
+ __decorateElement(_init3, 1, "unregisterEffect", _unregisterEffect_dec, _Granular);
18788
+ __decorateElement(_init3, 1, "disconnectEffects", _disconnectEffects_dec, _Granular);
18789
+ __decorateElement(_init3, 1, "request", _request_dec, _Granular);
18790
+ __decorateElement(_init3, 13, "transport", _transport_dec, _Granular);
18791
+ __decorateElement(_init3, 13, "effectHosts", _effectHosts_dec, _Granular);
18792
+ __decorateElement(_init3, 13, "sessions", _sessions_dec2, _Granular);
18793
+ __decorateElement(_init3, 13, "environmentAccess", _environmentAccess_dec, _Granular);
18794
+ _Granular = __decorateElement(_init3, 0, "Granular", _Granular_decorators, _Granular);
18795
+ __publicField(_Granular, "transport", __runInitializers(_init3, 8, _Granular)), __runInitializers(_init3, 11, _Granular);
18796
+ __publicField(_Granular, "effectHosts", __runInitializers(_init3, 12, _Granular)), __runInitializers(_init3, 15, _Granular);
18797
+ __publicField(_Granular, "sessions", __runInitializers(_init3, 16, _Granular)), __runInitializers(_init3, 19, _Granular);
18798
+ __publicField(_Granular, "environmentAccess", __runInitializers(_init3, 20, _Granular)), __runInitializers(_init3, 23, _Granular);
18799
+ __runInitializers(_init3, 1, _Granular);
18800
+ var Granular = _Granular;
17900
18801
 
17901
18802
  // src/agent-harness-templates/action-presentation/0.1.0/manifest.json
17902
18803
  var manifest_default = {
@@ -18263,15 +19164,15 @@ function uniqueStrings(values, maxCount) {
18263
19164
  }
18264
19165
  return output;
18265
19166
  }
18266
- function stableStringify(value) {
19167
+ function stableStringify2(value) {
18267
19168
  if (value === null || typeof value !== "object") {
18268
19169
  return JSON.stringify(value);
18269
19170
  }
18270
19171
  if (Array.isArray(value)) {
18271
- return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
19172
+ return `[${value.map((entry) => stableStringify2(entry)).join(",")}]`;
18272
19173
  }
18273
19174
  const record = value;
18274
- return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(",")}}`;
19175
+ return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableStringify2(record[key])}`).join(",")}}`;
18275
19176
  }
18276
19177
  function renderConstBlock(name, value) {
18277
19178
  return `const ${name} = ${JSON.stringify(value, null, 2)} as const;`;
@@ -20354,7 +21255,7 @@ var STABLE_AGENT_HARNESS_TEMPLATE_MANIFEST = defineHarnessTemplateManifest(
20354
21255
  "stable@1.0.0 manifest"
20355
21256
  );
20356
21257
  function hashHarnessTemplateValue(value) {
20357
- return hashString(stableStringify(value)) || "00000000";
21258
+ return hashString(stableStringify2(value)) || "00000000";
20358
21259
  }
20359
21260
  function renderStableHarnessPrompt(input) {
20360
21261
  const prompt = buildGranularAgentSystemPrompt(input);