@granular-software/sdk 0.4.76 → 0.4.78

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.
@@ -4047,6 +4047,347 @@ var GranularApiError = class extends Error {
4047
4047
  idempotencyKey;
4048
4048
  };
4049
4049
 
4050
+ // src/users-provider.ts
4051
+ var UsersProvider = class {
4052
+ constructor(handler, options = {}) {
4053
+ this.handler = handler;
4054
+ this.options = options;
4055
+ if (typeof handler !== "function")
4056
+ throw new Error("register_users requires a user-list callback.");
4057
+ }
4058
+ binding;
4059
+ bind(value, sandboxId, providerId) {
4060
+ const entry = value;
4061
+ if (!entry || entry.sandboxId !== sandboxId || entry.providerId !== providerId)
4062
+ throw new Error(
4063
+ "User directory registration does not match the provider connection."
4064
+ );
4065
+ return this.binding = Object.freeze({ sandboxId, providerId });
4066
+ }
4067
+ get registration() {
4068
+ return this.binding;
4069
+ }
4070
+ unbind() {
4071
+ this.binding = void 0;
4072
+ }
4073
+ async invoke(page) {
4074
+ const binding = this.binding;
4075
+ if (!binding) throw new Error("User directory is not registered.");
4076
+ if (page && (!Number.isSafeInteger(page.limit) || page.limit < 1 || page.limit > 100 || page.cursor !== void 0 && (typeof page.cursor !== "string" || !page.cursor || page.cursor.length > 1024) || page.search !== void 0 && (typeof page.search !== "string" || page.search.length > 200)))
4077
+ throw new Error("Invalid user directory page request.");
4078
+ const paged = page && this.options.listPage ? await this.options.listPage(Object.freeze({ ...page })) : null;
4079
+ if (page && this.options.listPage && (!paged || typeof paged !== "object" || Array.isArray(paged)))
4080
+ throw new Error("User directory returned an invalid page.");
4081
+ const result = paged ? paged.users : await this.handler();
4082
+ if (this.binding !== binding)
4083
+ throw new Error("User directory connection changed.");
4084
+ if (!Array.isArray(result) || result.length > 1e4)
4085
+ throw new Error("User directory must return at most 10000 users.");
4086
+ if (paged && (paged.truncated !== void 0 && typeof paged.truncated !== "boolean" || result.length > page.limit || !(paged.nextCursor === null || typeof paged.nextCursor === "string" && !!paged.nextCursor && paged.nextCursor.length <= 1024)))
4087
+ throw new Error("User directory returned an invalid page.");
4088
+ const seen = /* @__PURE__ */ new Set();
4089
+ const users2 = result.map((user) => {
4090
+ if (!user || typeof user.id !== "string" || !user.id.trim() || typeof user.name !== "string" || !user.name.trim() || user.email !== void 0 && typeof user.email !== "string" || seen.has(user.id))
4091
+ throw new Error(
4092
+ "User directory requires unique ids and display names."
4093
+ );
4094
+ seen.add(user.id);
4095
+ return {
4096
+ id: user.id,
4097
+ name: user.name,
4098
+ ...user.email !== void 0 ? { email: user.email } : {}
4099
+ };
4100
+ });
4101
+ if (!page) return users2;
4102
+ if (paged) return { users: users2, nextCursor: paged.nextCursor, ...paged.truncated ? { truncated: true } : {} };
4103
+ const query = page.search?.toLocaleLowerCase();
4104
+ const filtered = query ? users2.filter(
4105
+ (user) => [user.name, user.email, user.id].some(
4106
+ (v) => v?.toLocaleLowerCase().includes(query)
4107
+ )
4108
+ ) : users2;
4109
+ if (page.cursor && !/^legacy:[0-9]+$/.test(page.cursor))
4110
+ throw new Error("Invalid legacy directory cursor.");
4111
+ const start = page.cursor ? Number(page.cursor.slice(7)) : 0;
4112
+ if (!Number.isSafeInteger(start) || start > filtered.length)
4113
+ throw new Error("Invalid legacy directory cursor.");
4114
+ const end = Math.min(start + page.limit, filtered.length);
4115
+ return {
4116
+ users: filtered.slice(start, end),
4117
+ nextCursor: end < filtered.length ? `legacy:${end}` : null
4118
+ };
4119
+ }
4120
+ async resolveMembership(input) {
4121
+ const binding = this.binding;
4122
+ if (!binding || !this.options.resolveMembership)
4123
+ throw new Error("Product membership resolution is not registered.");
4124
+ if (!input || input.environment !== "dev" || ![input.tenantId, input.integrationId, input.providerSubject].every(
4125
+ (value) => typeof value === "string" && !!value.trim()
4126
+ ))
4127
+ throw new Error("Invalid verified customer membership scope.");
4128
+ const member = await this.options.resolveMembership(input);
4129
+ if (this.binding !== binding)
4130
+ throw new Error("User directory connection changed.");
4131
+ if (member === null) return null;
4132
+ if (!member || typeof member.identityId !== "string" || !member.identityId.trim() || member.identityId.length > 200 || typeof member.active !== "boolean")
4133
+ throw new Error("Invalid product membership response.");
4134
+ return { identityId: member.identityId, active: member.active };
4135
+ }
4136
+ };
4137
+
4138
+ // src/onboarding-postcondition.ts
4139
+ var object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
4140
+ var id = (v) => typeof v === "string" && v.length > 0 && v.length <= 500 && v.trim() === v && !/[\u0000-\u001f\u007f]/u.test(v);
4141
+ var scalar = (v) => v === null || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v) || typeof v === "string" && v.length <= 4e3;
4142
+ var only = (v, keys2) => Object.keys(v).every((k) => keys2.includes(k));
4143
+ function validOnboardingPostcondition(v) {
4144
+ if (!object(v) || !only(v, ["verifierId", "verifierRevision", "className", "targetId", "expected", "additionalChecks"]) || ![v.verifierId, v.verifierRevision, v.className, v.targetId].every(id) || !object(v.expected) || !only(v.expected, ["field", "equals"]) || !id(v.expected.field) || !scalar(v.expected.equals)) return false;
4145
+ if (v.additionalChecks === void 0) return true;
4146
+ if (!Array.isArray(v.additionalChecks) || v.additionalChecks.length < 1 || v.additionalChecks.length > 20) return false;
4147
+ const seen = /* @__PURE__ */ new Set([JSON.stringify([v.className, v.targetId, v.expected.field])]);
4148
+ return v.additionalChecks.every((check) => {
4149
+ if (!object(check) || !only(check, ["className", "targetId", "targetFromCommit", "field", "equals"]) || ![check.className, check.field].every(id) || !scalar(check.equals) || !(id(check.targetId) && check.targetFromCommit === void 0 || check.targetId === void 0 && check.targetFromCommit === "unique-created")) return false;
4150
+ const key = JSON.stringify([check.className, check.targetId ?? { from: check.targetFromCommit }, check.field]);
4151
+ if (seen.has(key)) return false;
4152
+ seen.add(key);
4153
+ return true;
4154
+ });
4155
+ }
4156
+ function validOnboardingObservations(spec, value, additional) {
4157
+ if (!scalar(value)) return false;
4158
+ const expected = spec.additionalChecks ?? [];
4159
+ if (!expected.length) return additional === void 0 || Array.isArray(additional) && additional.length === 0;
4160
+ return Array.isArray(additional) && additional.length === expected.length && expected.every((check, index) => {
4161
+ const observed = additional[index];
4162
+ return object(observed) && id(check.targetId) && only(observed, ["className", "targetId", "field", "value"]) && observed.className === check.className && observed.targetId === check.targetId && observed.field === check.field && scalar(observed.value);
4163
+ });
4164
+ }
4165
+
4166
+ // src/development-provider.ts
4167
+ var row = (v) => !!v && typeof v === "object" && !Array.isArray(v);
4168
+ var id2 = (v) => typeof v === "string" && v.length > 0 && v.length <= 500 && v.trim() === v && !/[\u0000-\u001f\u007f]/u.test(v);
4169
+ var keys = [
4170
+ "runId",
4171
+ "tenantId",
4172
+ "sandboxId",
4173
+ "buildId",
4174
+ "operatorPrincipalId",
4175
+ "providerId",
4176
+ "environment"
4177
+ ];
4178
+ var generation = (v) => typeof v === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(v);
4179
+ function developmentPreparationOperationKey(runId, userId, generationId) {
4180
+ if (!id2(runId) || !id2(userId) || !generation(generationId))
4181
+ throw new Error("Exact development run, user and generation are required.");
4182
+ return `onboarding-development:${runId}:${encodeURIComponent(userId)}:${generationId}`;
4183
+ }
4184
+ function users(value) {
4185
+ if (!Array.isArray(value) || value.length > 1e4)
4186
+ throw new Error(
4187
+ "Development user handler must return at most 10000 canonical users."
4188
+ );
4189
+ const seen = /* @__PURE__ */ new Set();
4190
+ return value.map((v) => {
4191
+ if (!row(v) || !id2(v.id) || v.id.length > 200 || !id2(v.name) || v.email !== void 0 && !id2(v.email) || seen.has(v.id))
4192
+ throw new Error("Development users need unique canonical ids and names.");
4193
+ seen.add(v.id);
4194
+ return {
4195
+ id: v.id,
4196
+ name: v.name,
4197
+ ...v.email !== void 0 ? { email: v.email } : {}
4198
+ };
4199
+ });
4200
+ }
4201
+ function progress(value) {
4202
+ if (!row(value) || !["queued", "collecting", "importing", "ready", "failed"].includes(
4203
+ String(value.stage)
4204
+ ) || !(value.subjectId === null || id2(value.subjectId)) || !(value.environmentId === null || id2(value.environmentId)) || value.setupRunId !== void 0 && value.setupRunId !== null && !id2(value.setupRunId) || value.importIds !== void 0 && (!Array.isArray(value.importIds) || !value.importIds.every(id2) || new Set(value.importIds).size !== value.importIds.length) || ["completedRecords", "totalRecords"].some(
4205
+ (k) => value[k] !== void 0 && (!Number.isSafeInteger(value[k]) || Number(value[k]) < 0)
4206
+ ))
4207
+ throw new Error("Development handler returned invalid reported progress.");
4208
+ return {
4209
+ stage: value.stage,
4210
+ subjectId: value.subjectId,
4211
+ environmentId: value.environmentId,
4212
+ ...value.setupRunId !== void 0 ? { setupRunId: value.setupRunId } : {},
4213
+ ...value.importIds !== void 0 ? { importIds: [...value.importIds] } : {},
4214
+ ...value.completedRecords !== void 0 ? { completedRecords: Number(value.completedRecords) } : {},
4215
+ ...value.totalRecords !== void 0 ? { totalRecords: Number(value.totalRecords) } : {}
4216
+ };
4217
+ }
4218
+ var DevelopmentProvider = class {
4219
+ binding;
4220
+ options;
4221
+ constructor(options) {
4222
+ if (!options || options.environment !== "dev" || ![options.runId, options.buildId, options.operatorPrincipalId].every(
4223
+ id2
4224
+ ) || [
4225
+ options.authorize,
4226
+ options.listUsers,
4227
+ options.createEnvironment,
4228
+ options.getProgress
4229
+ ].some((v) => typeof v !== "function"))
4230
+ throw new Error(
4231
+ "Explicit dev scope and all authorized product callbacks are required."
4232
+ );
4233
+ this.options = Object.freeze({ ...options });
4234
+ }
4235
+ registrationParams() {
4236
+ const { runId, buildId, operatorPrincipalId, environment } = this.options;
4237
+ const handlers = ["listUsers", "createEnvironment", "getProgress"];
4238
+ if (this.options.findUser) handlers.push("findUser");
4239
+ if (this.options.authorizeCustomerReadback && this.options.readCustomerPostcondition)
4240
+ handlers.push("readPostcondition");
4241
+ if (this.options.authorizeCustomerCollection && this.options.readCustomerCollection)
4242
+ handlers.push("readCollection");
4243
+ if (this.options.getIncrementalStatus) handlers.push("incrementalStatus");
4244
+ const postconditionVerifiers = this.options.authorizeCustomerReadback && this.options.readCustomerPostcondition ? this.options.postconditionVerifiers || [] : [];
4245
+ if (postconditionVerifiers.length > 100 || postconditionVerifiers.some(
4246
+ (v) => !id2(v.verifierId) || !id2(v.verifierRevision) || !id2(v.className) || !id2(v.label) || !Array.isArray(v.fields) || !v.fields.length || v.fields.length > 100 || v.fields.some((f) => !id2(f))
4247
+ ))
4248
+ throw new Error("Invalid product postcondition verifier catalog");
4249
+ return {
4250
+ runId,
4251
+ buildId,
4252
+ operatorPrincipalId,
4253
+ environment,
4254
+ handlers,
4255
+ postconditionVerifiers
4256
+ };
4257
+ }
4258
+ bind(value, sandboxId, providerId) {
4259
+ if (!row(value) || value.environment !== "dev" || !keys.filter((k) => k !== "environment").every((k) => id2(value[k])) || value.runId !== this.options.runId || value.buildId !== this.options.buildId || value.operatorPrincipalId !== this.options.operatorPrincipalId || value.sandboxId !== sandboxId || value.providerId !== providerId)
4260
+ throw new Error(
4261
+ "Development registration response does not match the owned dev scope."
4262
+ );
4263
+ const binding = Object.fromEntries(
4264
+ keys.map((k) => [k, value[k]])
4265
+ );
4266
+ this.binding = Object.freeze(binding);
4267
+ return this.binding;
4268
+ }
4269
+ get registration() {
4270
+ return this.binding;
4271
+ }
4272
+ unbind() {
4273
+ this.binding = void 0;
4274
+ }
4275
+ async invoke(value) {
4276
+ if (!this.binding || !row(value) || !row(value.context) || !keys.every(
4277
+ (k) => value.context && value.context[k] === this.binding[k]
4278
+ ) || ![
4279
+ "listUsers",
4280
+ "findUser",
4281
+ "createEnvironment",
4282
+ "getProgress",
4283
+ "readPostcondition",
4284
+ "readCollection",
4285
+ "incrementalStatus"
4286
+ ].includes(String(value.operation)))
4287
+ throw new Error(
4288
+ "Development invocation does not match the registered dev/operator scope."
4289
+ );
4290
+ const binding = this.binding;
4291
+ const context = Object.freeze({ ...binding });
4292
+ if (await this.options.authorize(context) === false)
4293
+ throw new Error("Development operator is not authorized.");
4294
+ const useLookup = value.operation !== "listUsers" && !!this.options.findUser;
4295
+ if (useLookup && !id2(value.userId)) throw new Error("A current selected user is required.");
4296
+ const selected = useLookup ? await this.options.findUser(context, value.userId) : void 0;
4297
+ if (useLookup && selected === void 0) throw new Error("Invalid selected user response.");
4298
+ const listed = useLookup ? users(selected === null ? [] : [selected]) : users(await this.options.listUsers(context));
4299
+ if (this.binding !== binding)
4300
+ throw new Error("Development registration changed during invocation.");
4301
+ if (value.operation === "listUsers") return listed;
4302
+ const user = listed.find((u) => u.id === value.userId);
4303
+ if (value.operation === "findUser") return user ?? null;
4304
+ if (value.operation === "incrementalStatus") {
4305
+ if (!user || !this.options.getIncrementalStatus) throw new Error("Incremental status is unavailable");
4306
+ const result2 = await this.options.getIncrementalStatus(context, user.id);
4307
+ if (this.binding !== binding || await this.options.authorize(context) === false) throw new Error("Development authorization changed during incremental status");
4308
+ if (!Array.isArray(result2) || result2.length > 100) throw new Error("Invalid incremental status");
4309
+ const seen = /* @__PURE__ */ new Set();
4310
+ for (const item of result2) {
4311
+ if (!row(item) || !["classId", "environmentId", "subjectId"].every((k) => id2(item[k])) || !["not_started", "checking", "catching_up", "source_current", "pending", "failed", "unknown"].includes(String(item.status)) || item.checkedAt !== void 0 && (!Number.isSafeInteger(item.checkedAt) || Number(item.checkedAt) < 0) || item.status === "source_current" && item.checkedAt === void 0 || seen.has(String(item.classId)) || Object.keys(item).some((k) => !["classId", "environmentId", "subjectId", "status", "checkedAt"].includes(k))) throw new Error("Invalid incremental status");
4312
+ seen.add(String(item.classId));
4313
+ }
4314
+ return result2.map((item) => ({ ...item }));
4315
+ }
4316
+ if (value.operation === "readCollection") {
4317
+ const input2 = value.readback;
4318
+ if (!user || !row(input2) || input2.identityId !== user.id || !["identityId", "subjectId", "environmentId", "setupRunId", "generationId"].every((k) => id2(input2[k])) || Object.keys(input2).some((k) => !["identityId", "subjectId", "environmentId", "setupRunId", "generationId"].includes(k)))
4319
+ throw new Error("Invalid customer collection binding");
4320
+ if (!this.options.authorizeCustomerCollection || !this.options.readCustomerCollection) return { status: "unavailable" };
4321
+ const collection = Object.freeze(structuredClone(input2));
4322
+ if (await this.options.authorizeCustomerCollection(collection, context) !== true) throw new Error("Customer collection is not authorized");
4323
+ const result2 = await this.options.readCustomerCollection(collection, context);
4324
+ if (this.binding !== binding || await this.options.authorizeCustomerCollection(collection, context) !== true)
4325
+ throw new Error("Customer binding changed during collection receipt read");
4326
+ if (result2.status === "unavailable") return result2;
4327
+ if (result2.status !== "complete" || !row(result2.classCounts) || Object.keys(result2.classCounts).length > 500 || Object.entries(result2.classCounts).some(([key, count]) => !id2(key) || !Number.isSafeInteger(count) || Number(count) < 0))
4328
+ throw new Error("Invalid product collection receipt");
4329
+ return { status: "complete", classCounts: { ...result2.classCounts } };
4330
+ }
4331
+ if (value.operation === "readPostcondition") {
4332
+ const input2 = value.readback;
4333
+ if (!user || !row(input2) || input2.identityId !== user.id || ![
4334
+ "requestId",
4335
+ "invocationId",
4336
+ "sessionId",
4337
+ "jobId",
4338
+ "subjectId",
4339
+ "environmentId",
4340
+ "identityId",
4341
+ "effectKey"
4342
+ ].every((k) => id2(input2[k])) || !validOnboardingPostcondition(input2.postcondition))
4343
+ throw new Error("Invalid customer postcondition readback binding");
4344
+ if (!this.options.authorizeCustomerReadback || !this.options.readCustomerPostcondition)
4345
+ return { status: "unavailable" };
4346
+ const spec = input2.postcondition;
4347
+ const checks = [{ className: spec.className, field: spec.expected.field }, ...spec.additionalChecks ?? []];
4348
+ if (!checks.every((check) => this.options.postconditionVerifiers?.some((v) => v.verifierId === spec.verifierId && v.verifierRevision === spec.verifierRevision && v.className === check.className && v.fields.includes(check.field))))
4349
+ return { status: "unavailable" };
4350
+ const copy = structuredClone(input2);
4351
+ Object.freeze(copy.postcondition.expected);
4352
+ if (copy.postcondition.additionalChecks) {
4353
+ copy.postcondition.additionalChecks.forEach(Object.freeze);
4354
+ Object.freeze(copy.postcondition.additionalChecks);
4355
+ }
4356
+ Object.freeze(copy.postcondition);
4357
+ const readback = Object.freeze(copy);
4358
+ if (await this.options.authorizeCustomerReadback(readback, context) !== true)
4359
+ throw new Error("Customer product readback is not authorized");
4360
+ const result2 = await this.options.readCustomerPostcondition(
4361
+ readback,
4362
+ context
4363
+ );
4364
+ if (this.binding !== binding || await this.options.authorizeCustomerReadback(readback, context) !== true)
4365
+ throw new Error("Customer binding changed during product readback");
4366
+ if (!row(result2) || result2.status !== "unavailable" && (result2.status !== "observed" || !validOnboardingObservations(spec, result2.value, result2.additional)))
4367
+ throw new Error("Invalid product readback result");
4368
+ return result2.status === "observed" ? { status: "observed", value: result2.value, ...result2.additional ? { additional: result2.additional } : {} } : { status: "unavailable" };
4369
+ }
4370
+ if (!user || !generation(value.generationId) || value.operationKey !== developmentPreparationOperationKey(
4371
+ context.runId,
4372
+ user.id,
4373
+ value.generationId
4374
+ ))
4375
+ throw new Error(
4376
+ "Selected development user or generation is not current."
4377
+ );
4378
+ const input = {
4379
+ context,
4380
+ user: Object.freeze(user),
4381
+ operationKey: value.operationKey,
4382
+ generationId: value.generationId
4383
+ };
4384
+ const result = await (value.operation === "createEnvironment" ? this.options.createEnvironment(input) : this.options.getProgress(input));
4385
+ if (this.binding !== binding)
4386
+ throw new Error("Development registration changed during invocation.");
4387
+ return progress(result);
4388
+ }
4389
+ };
4390
+
4050
4391
  // ../../node_modules/zod/v3/external.js
4051
4392
  var external_exports = {};
4052
4393
  __export(external_exports, {
@@ -4191,14 +4532,14 @@ var util;
4191
4532
  return obj[e];
4192
4533
  });
4193
4534
  };
4194
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
4195
- const keys = [];
4196
- for (const key in object) {
4197
- if (Object.prototype.hasOwnProperty.call(object, key)) {
4198
- keys.push(key);
4535
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
4536
+ const keys2 = [];
4537
+ for (const key in object2) {
4538
+ if (Object.prototype.hasOwnProperty.call(object2, key)) {
4539
+ keys2.push(key);
4199
4540
  }
4200
4541
  }
4201
- return keys;
4542
+ return keys2;
4202
4543
  };
4203
4544
  util2.find = (arr, checker) => {
4204
4545
  for (const item of arr) {
@@ -6426,8 +6767,8 @@ var ZodObject = class _ZodObject extends ZodType {
6426
6767
  if (this._cached !== null)
6427
6768
  return this._cached;
6428
6769
  const shape = this._def.shape();
6429
- const keys = util.objectKeys(shape);
6430
- this._cached = { shape, keys };
6770
+ const keys2 = util.objectKeys(shape);
6771
+ this._cached = { shape, keys: keys2 };
6431
6772
  return this._cached;
6432
6773
  }
6433
6774
  _parse(input) {
@@ -8790,8 +9131,8 @@ function isArtifactWorkflowNodeActionable(node) {
8790
9131
  );
8791
9132
  }
8792
9133
  function getArtifactWorkflowNodes(workflow) {
8793
- const visit = (id) => {
8794
- const node = workflow.nodesById[id];
9134
+ const visit = (id3) => {
9135
+ const node = workflow.nodesById[id3];
8795
9136
  return node ? [node, ...node.childIds.flatMap(visit)] : [];
8796
9137
  };
8797
9138
  return workflow.rootNodeIds.flatMap(visit);
@@ -8805,22 +9146,22 @@ function assertArtifactWorkflow(workflow) {
8805
9146
  const visited = /* @__PURE__ */ new Set();
8806
9147
  const visiting = /* @__PURE__ */ new Set();
8807
9148
  const nodes = [];
8808
- const visit = (id, expectedParentId) => {
8809
- const node = workflow.nodesById[id];
8810
- if (!node) throw new Error(`Artifact workflow node ${id} does not exist`);
8811
- if (visiting.has(id)) throw new Error("Artifact workflow contains a cycle");
8812
- if (visited.has(id))
9149
+ const visit = (id3, expectedParentId) => {
9150
+ const node = workflow.nodesById[id3];
9151
+ if (!node) throw new Error(`Artifact workflow node ${id3} does not exist`);
9152
+ if (visiting.has(id3)) throw new Error("Artifact workflow contains a cycle");
9153
+ if (visited.has(id3))
8813
9154
  throw new Error("Artifact workflow contains a duplicate node reference");
8814
9155
  if (node.parentId !== expectedParentId) {
8815
- throw new Error(`Artifact workflow node ${id} has an invalid parent`);
9156
+ throw new Error(`Artifact workflow node ${id3} has an invalid parent`);
8816
9157
  }
8817
- visiting.add(id);
9158
+ visiting.add(id3);
8818
9159
  nodes.push(node);
8819
- node.childIds.forEach((childId) => visit(childId, id));
8820
- visiting.delete(id);
8821
- visited.add(id);
9160
+ node.childIds.forEach((childId) => visit(childId, id3));
9161
+ visiting.delete(id3);
9162
+ visited.add(id3);
8822
9163
  };
8823
- workflow.rootNodeIds.forEach((id) => visit(id, null));
9164
+ workflow.rootNodeIds.forEach((id3) => visit(id3, null));
8824
9165
  if (visited.size !== Object.keys(workflow.nodesById).length) {
8825
9166
  throw new Error("Artifact workflow contains unreachable nodes");
8826
9167
  }
@@ -8924,12 +9265,12 @@ function toRecordSearchResult(className, node) {
8924
9265
  const realIdField = fields.find(
8925
9266
  (field) => normalizeGraphPathSegment(field.name) === "real_id" && typeof field.value === "string" && field.value.trim()
8926
9267
  );
8927
- const id = typeof realIdField?.value === "string" ? realIdField.value.trim() : graphPathId;
8928
- const label = typeof node.label === "string" && node.label.trim() ? node.label.trim() : path2 || id;
9268
+ const id3 = typeof realIdField?.value === "string" ? realIdField.value.trim() : graphPathId;
9269
+ const label = typeof node.label === "string" && node.label.trim() ? node.label.trim() : path2 || id3;
8929
9270
  return {
8930
9271
  path: path2,
8931
9272
  className,
8932
- id,
9273
+ id: id3,
8933
9274
  label,
8934
9275
  description: typeof node.description === "string" && node.description.trim() ? node.description : null,
8935
9276
  fields
@@ -8944,12 +9285,12 @@ function rankRecordSearchResult(result, query, index) {
8944
9285
  return index;
8945
9286
  }
8946
9287
  const label = normalizeRecordSearchText(result.label || "");
8947
- const id = normalizeRecordSearchText(result.id || "");
9288
+ const id3 = normalizeRecordSearchText(result.id || "");
8948
9289
  const path2 = normalizeRecordSearchText(result.path || "");
8949
9290
  const className = normalizeRecordSearchText(result.className || "");
8950
- const searchable = [label, id, path2, className].filter(Boolean);
9291
+ const searchable = [label, id3, path2, className].filter(Boolean);
8951
9292
  if (label === normalizedQuery) return index;
8952
- if (id === normalizedQuery || path2 === normalizedQuery) return 100 + index;
9293
+ if (id3 === normalizedQuery || path2 === normalizedQuery) return 100 + index;
8953
9294
  if (label.startsWith(normalizedQuery)) return 200 + index;
8954
9295
  if (searchable.some((value) => value.startsWith(normalizedQuery))) {
8955
9296
  return 300 + index;
@@ -9603,22 +9944,22 @@ function orderTransientFeedItems(items) {
9603
9944
  const ordinalById = /* @__PURE__ */ new Map();
9604
9945
  const idByOrdinal = /* @__PURE__ */ new Map();
9605
9946
  for (const item of items) {
9606
- const id = String(item.id || "");
9947
+ const id3 = String(item.id || "");
9607
9948
  const ordinal = requirePositiveFeedPosition(item.ordinal);
9608
- const knownOrdinal = ordinalById.get(id);
9949
+ const knownOrdinal = ordinalById.get(id3);
9609
9950
  const ordinalOwner = idByOrdinal.get(ordinal);
9610
- if (!id || knownOrdinal !== void 0 && knownOrdinal !== ordinal || ordinalOwner && ordinalOwner !== id) {
9951
+ if (!id3 || knownOrdinal !== void 0 && knownOrdinal !== ordinal || ordinalOwner && ordinalOwner !== id3) {
9611
9952
  throw new Error("Invalid feed chronology.");
9612
9953
  }
9613
- ordinalById.set(id, ordinal);
9614
- idByOrdinal.set(ordinal, id);
9615
- const existing = byId.get(id);
9954
+ ordinalById.set(id3, ordinal);
9955
+ idByOrdinal.set(ordinal, id3);
9956
+ const existing = byId.get(id3);
9616
9957
  if (existing && item.revision === existing.revision && stableValueFingerprint(item) !== stableValueFingerprint(existing)) {
9617
9958
  throw new Error(
9618
9959
  "Invalid feed chronology: conflicting transient revision."
9619
9960
  );
9620
9961
  }
9621
- if (!existing || item.revision > existing.revision) byId.set(id, item);
9962
+ if (!existing || item.revision > existing.revision) byId.set(id3, item);
9622
9963
  }
9623
9964
  return [...byId.values()].sort((left, right) => left.ordinal - right.ordinal);
9624
9965
  }
@@ -9672,21 +10013,21 @@ function cloneAndFreeze(value, seen = /* @__PURE__ */ new WeakMap()) {
9672
10013
  if (!value || typeof value !== "object") {
9673
10014
  return value;
9674
10015
  }
9675
- const object = value;
9676
- const cached = seen.get(object);
10016
+ const object2 = value;
10017
+ const cached = seen.get(object2);
9677
10018
  if (cached) {
9678
10019
  return cached;
9679
10020
  }
9680
10021
  if (Array.isArray(value)) {
9681
10022
  const result2 = [];
9682
- seen.set(object, result2);
10023
+ seen.set(object2, result2);
9683
10024
  for (const entry of value) {
9684
10025
  result2.push(cloneAndFreeze(entry, seen));
9685
10026
  }
9686
10027
  return Object.freeze(result2);
9687
10028
  }
9688
10029
  const result = /* @__PURE__ */ Object.create(null);
9689
- seen.set(object, result);
10030
+ seen.set(object2, result);
9690
10031
  for (const [key, entry] of Object.entries(value)) {
9691
10032
  result[key] = cloneAndFreeze(entry, seen);
9692
10033
  }
@@ -10591,9 +10932,9 @@ var SessionFeedController = class {
10591
10932
  targetSequence,
10592
10933
  repairAvailable: true
10593
10934
  });
10594
- const generation = ++this.repairGeneration;
10595
- this.repairPromise = this.repair(targetSequence, generation).finally(() => {
10596
- if (generation === this.repairGeneration) {
10935
+ const generation2 = ++this.repairGeneration;
10936
+ this.repairPromise = this.repair(targetSequence, generation2).finally(() => {
10937
+ if (generation2 === this.repairGeneration) {
10597
10938
  this.repairPromise = null;
10598
10939
  if (this.deliveredThrough < this.snapshot.lastSequence) {
10599
10940
  if (this.snapshot.error) {
@@ -10641,13 +10982,13 @@ var SessionFeedController = class {
10641
10982
  }, delayMs);
10642
10983
  this.repairRetryHandle = handle;
10643
10984
  }
10644
- async repair(targetSequence, generation) {
10985
+ async repair(targetSequence, generation2) {
10645
10986
  const startedAt = this.diagnosticNow();
10646
10987
  let pageCount = 0;
10647
10988
  let outcome = "success";
10648
10989
  try {
10649
10990
  let attempts = 0;
10650
- while (generation === this.repairGeneration && this.deliveredThrough < targetSequence) {
10991
+ while (generation2 === this.repairGeneration && this.deliveredThrough < targetSequence) {
10651
10992
  if (++attempts > 100) {
10652
10993
  throw new Error("Feed gap repair exceeded its page limit.");
10653
10994
  }
@@ -10656,7 +10997,7 @@ var SessionFeedController = class {
10656
10997
  limit: 500
10657
10998
  });
10658
10999
  pageCount += 1;
10659
- if (generation !== this.repairGeneration) {
11000
+ if (generation2 !== this.repairGeneration) {
10660
11001
  outcome = "cancelled";
10661
11002
  return;
10662
11003
  }
@@ -10690,12 +11031,12 @@ var SessionFeedController = class {
10690
11031
  );
10691
11032
  }
10692
11033
  }
10693
- if (generation !== this.repairGeneration) {
11034
+ if (generation2 !== this.repairGeneration) {
10694
11035
  outcome = "cancelled";
10695
11036
  return;
10696
11037
  }
10697
11038
  } catch (error) {
10698
- if (generation !== this.repairGeneration) {
11039
+ if (generation2 !== this.repairGeneration) {
10699
11040
  outcome = "cancelled";
10700
11041
  return;
10701
11042
  }
@@ -11919,10 +12260,10 @@ function buildPolicyMutations(effectKey, spec) {
11919
12260
  rules.forEach((rule, index) => {
11920
12261
  const condition = normalizeCondition(rule.when);
11921
12262
  const summary = rule.reason || summarizeCondition(condition);
11922
- const id = rule.id || `${effectKey}:${outcome}:${index + 1}`;
12263
+ const id3 = rule.id || `${effectKey}:${outcome}:${index + 1}`;
11923
12264
  mutations.push({
11924
12265
  label: `set policy ${outcome} on ${effectKey}`,
11925
- query: `mutation { set_policy_rule(effect_key: ${escapeGraphqlString(effectKey)}, policy_id: ${escapeGraphqlString(id)}, outcome: ${escapeGraphqlString(outcome)}, reason: ${escapeGraphqlString(summary)}, condition_json: ${escapeGraphqlString(JSON.stringify(condition))}) }`
12266
+ query: `mutation { set_policy_rule(effect_key: ${escapeGraphqlString(effectKey)}, policy_id: ${escapeGraphqlString(id3)}, outcome: ${escapeGraphqlString(outcome)}, reason: ${escapeGraphqlString(summary)}, condition_json: ${escapeGraphqlString(JSON.stringify(condition))}) }`
11926
12267
  });
11927
12268
  });
11928
12269
  };
@@ -13116,8 +13457,8 @@ function normalizePrompt(rawValue) {
13116
13457
  if (!raw) return null;
13117
13458
  const promptRecord = asRecord2(raw.prompt);
13118
13459
  const source = promptRecord || raw;
13119
- const id = typeof source.id === "string" ? source.id : typeof raw.id === "string" ? raw.id : typeof raw.promptId === "string" ? raw.promptId : "";
13120
- if (!id) return null;
13460
+ const id3 = typeof source.id === "string" ? source.id : typeof raw.id === "string" ? raw.id : typeof raw.promptId === "string" ? raw.promptId : "";
13461
+ if (!id3) return null;
13121
13462
  const jobId = typeof source.jobId === "string" && source.jobId.trim() ? source.jobId.trim() : typeof raw.jobId === "string" && raw.jobId.trim() ? raw.jobId.trim() : void 0;
13122
13463
  const turnId = typeof source.turnId === "string" && source.turnId.trim() ? source.turnId.trim() : typeof raw.turnId === "string" && raw.turnId.trim() ? raw.turnId.trim() : void 0;
13123
13464
  const type = normalizePromptType(
@@ -13125,7 +13466,7 @@ function normalizePrompt(rawValue) {
13125
13466
  );
13126
13467
  if (!type) return null;
13127
13468
  return {
13128
- id,
13469
+ id: id3,
13129
13470
  ...jobId ? { jobId } : {},
13130
13471
  ...turnId ? { turnId } : {},
13131
13472
  type,
@@ -13594,8 +13935,8 @@ var Session = class {
13594
13935
  input.operationId,
13595
13936
  "operationId"
13596
13937
  );
13597
- const id = requestedId || (requestedOperationId ? void 0 : reserveUserMessageId());
13598
- const operationId2 = requestedOperationId || `conversation.append:${id}`;
13938
+ const id3 = requestedId || (requestedOperationId ? void 0 : reserveUserMessageId());
13939
+ const operationId2 = requestedOperationId || `conversation.append:${id3}`;
13599
13940
  const {
13600
13941
  id: _ignoredInputId,
13601
13942
  operationId: _ignoredInputOperationId,
@@ -13604,7 +13945,7 @@ var Session = class {
13604
13945
  return this.client.call("conversation.append", {
13605
13946
  ...message,
13606
13947
  role: "user",
13607
- ...id ? { id } : {},
13948
+ ...id3 ? { id: id3 } : {},
13608
13949
  operationId: operationId2
13609
13950
  });
13610
13951
  }
@@ -13804,6 +14145,43 @@ var Session = class {
13804
14145
  }
13805
14146
  return summary;
13806
14147
  }
14148
+ /** Hosted-harness module context for an external subject agent. */
14149
+ async getHarnessContext() {
14150
+ return this.client.call("domain.getHarnessContext", {});
14151
+ }
14152
+ /** Submit external agent code through the hosted harness import preparation. */
14153
+ async submitSubjectJob(code, options = {}) {
14154
+ const result = await this.client.call("job.submitSubject", {
14155
+ code,
14156
+ domainRevision: options.domainRevision,
14157
+ metadata: options.metadata
14158
+ });
14159
+ if (result.rejected) {
14160
+ const error = new Error(result.rejected.message);
14161
+ error.code = result.rejected.code;
14162
+ throw error;
14163
+ }
14164
+ if (!result.jobId) throw new Error("Failed to submit subject job: no jobId returned");
14165
+ const job = new JobImplementation(result.jobId, this.client, {
14166
+ code,
14167
+ domainRevision: options.domainRevision || this.currentDomainRevision || "",
14168
+ createdAt: Date.now()
14169
+ });
14170
+ this.jobsMap.set(result.jobId, job);
14171
+ job.reconcileCanonicalState(
14172
+ this.client.doc?.jobs?.byId?.[result.jobId]
14173
+ );
14174
+ return job;
14175
+ }
14176
+ /** A canonical job read also reconciles a handle whose terminal event was missed. */
14177
+ reconcileCanonicalJobRead(jobId, record) {
14178
+ this.jobsMap.get(jobId)?.reconcileCanonicalState(record);
14179
+ }
14180
+ rejectTerminalJobRead(jobId, error) {
14181
+ if (error?.code === "SUBJECT_SESSION_ENDED") {
14182
+ this.jobsMap.get(jobId)?.rejectResultAccess(error);
14183
+ }
14184
+ }
13807
14185
  /**
13808
14186
  * Fetch a domain package part from the backend (no fallback).
13809
14187
  */
@@ -14135,8 +14513,11 @@ import { ${tools[0]?.name || "example"} } from "@granular/actions/backend";
14135
14513
  this.emit("prompt:answered", { ...prompt, status: "answered" });
14136
14514
  return;
14137
14515
  }
14516
+ const previous = this.promptCache.get(prompt.id);
14138
14517
  this.promptCache.set(prompt.id, prompt);
14139
- this.emit("prompt", prompt);
14518
+ if (!previous || promptSnapshotFingerprint(previous) !== promptSnapshotFingerprint(prompt)) {
14519
+ this.emit("prompt", prompt);
14520
+ }
14140
14521
  };
14141
14522
  this.client.on("prompt", emitPrompt);
14142
14523
  this.client.on("prompt.request", emitPrompt);
@@ -14294,8 +14675,8 @@ var JobImplementation = class {
14294
14675
  eventListeners = /* @__PURE__ */ new Map();
14295
14676
  resultSettled = false;
14296
14677
  metadata;
14297
- constructor(id, client, initialState) {
14298
- this.id = id;
14678
+ constructor(id3, client, initialState) {
14679
+ this.id = id3;
14299
14680
  this.client = client;
14300
14681
  this.metadata = {
14301
14682
  source: "sdk",
@@ -14313,7 +14694,7 @@ var JobImplementation = class {
14313
14694
  });
14314
14695
  this.client.on("exec.completed", (data) => {
14315
14696
  const execData = data;
14316
- if (execData.execId === id || execData.jobId === id) {
14697
+ if (execData.execId === id3 || execData.jobId === id3) {
14317
14698
  if (execData.error) {
14318
14699
  this.finalize("failed", void 0, execData.error);
14319
14700
  } else {
@@ -14326,7 +14707,7 @@ var JobImplementation = class {
14326
14707
  });
14327
14708
  this.client.on("exec.progress", (data) => {
14328
14709
  const progressData = data;
14329
- if (progressData.execId === id || progressData.jobId === id) {
14710
+ if (progressData.execId === id3 || progressData.jobId === id3) {
14330
14711
  if (progressData.stdout) {
14331
14712
  this.markStarted();
14332
14713
  this.metadata.stdout = [
@@ -14345,7 +14726,7 @@ var JobImplementation = class {
14345
14726
  }
14346
14727
  }
14347
14728
  });
14348
- this.client.on(`job.${id}.status`, (status) => {
14729
+ this.client.on(`job.${id3}.status`, (status) => {
14349
14730
  const normalizedStatus = normalizeJobStatus(status);
14350
14731
  this.status = normalizedStatus;
14351
14732
  this.metadata.status = normalizedStatus;
@@ -14357,7 +14738,7 @@ var JobImplementation = class {
14357
14738
  }
14358
14739
  this.emit("status", normalizedStatus);
14359
14740
  });
14360
- this.client.on(`job.${id}.stdout`, (line) => {
14741
+ this.client.on(`job.${id3}.stdout`, (line) => {
14361
14742
  this.markStarted();
14362
14743
  this.metadata.stdout = [
14363
14744
  ...this.metadata.stdout,
@@ -14365,7 +14746,7 @@ var JobImplementation = class {
14365
14746
  ].slice(-100);
14366
14747
  this.emit("stdout", line);
14367
14748
  });
14368
- this.client.on(`job.${id}.stderr`, (line) => {
14749
+ this.client.on(`job.${id3}.stderr`, (line) => {
14369
14750
  this.markStarted();
14370
14751
  this.metadata.stderr = [
14371
14752
  ...this.metadata.stderr,
@@ -14373,15 +14754,15 @@ var JobImplementation = class {
14373
14754
  ].slice(-100);
14374
14755
  this.emit("stderr", line);
14375
14756
  });
14376
- this.client.on(`job.${id}.result`, (result) => {
14757
+ this.client.on(`job.${id3}.result`, (result) => {
14377
14758
  this.finalize("succeeded", result, void 0, { hasResult: true });
14378
14759
  });
14379
- this.client.on(`job.${id}.error`, (error) => {
14760
+ this.client.on(`job.${id3}.error`, (error) => {
14380
14761
  this.finalize("failed", void 0, error);
14381
14762
  });
14382
14763
  this.client.on("job.status", (data) => {
14383
14764
  const jobData = data;
14384
- if (jobData.jobId !== id) {
14765
+ if (jobData.jobId !== id3) {
14385
14766
  return;
14386
14767
  }
14387
14768
  const normalizedStatus = normalizeJobStatus(jobData.status);
@@ -14394,7 +14775,7 @@ var JobImplementation = class {
14394
14775
  });
14395
14776
  this.client.on("job.completed", (data) => {
14396
14777
  const jobData = data;
14397
- if (jobData.jobId === id) {
14778
+ if (jobData.jobId === id3) {
14398
14779
  this.finalize("succeeded", jobData.result, void 0, {
14399
14780
  hasResult: true
14400
14781
  });
@@ -14403,7 +14784,7 @@ var JobImplementation = class {
14403
14784
  });
14404
14785
  this.client.on("job.failed", (data) => {
14405
14786
  const jobData = data;
14406
- if (jobData.jobId === id) {
14787
+ if (jobData.jobId === id3) {
14407
14788
  this.finalize(
14408
14789
  "failed",
14409
14790
  void 0,
@@ -14414,7 +14795,7 @@ var JobImplementation = class {
14414
14795
  });
14415
14796
  this.client.on("tool.call.start", (data) => {
14416
14797
  const d = data;
14417
- if (d.jobId === id) {
14798
+ if (d.jobId === id3) {
14418
14799
  this.metadata.toolCalls = this.upsertToolCall({
14419
14800
  callId: d.callId,
14420
14801
  toolName: d.toolName,
@@ -14431,7 +14812,7 @@ var JobImplementation = class {
14431
14812
  });
14432
14813
  this.client.on("tool.call.end", (data) => {
14433
14814
  const d = data;
14434
- if (d.jobId === id) {
14815
+ if (d.jobId === id3) {
14435
14816
  const completedAt = d.timestamp || Date.now();
14436
14817
  this.metadata.toolCalls = this.upsertToolCall({
14437
14818
  callId: d.callId,
@@ -14452,6 +14833,23 @@ var JobImplementation = class {
14452
14833
  }
14453
14834
  });
14454
14835
  }
14836
+ rejectResultAccess(error) {
14837
+ if (this.resultSettled) return;
14838
+ this.resultSettled = true;
14839
+ this._rejectResult(error);
14840
+ }
14841
+ reconcileCanonicalState(record) {
14842
+ if (this.resultSettled) return;
14843
+ const value = recordFromUnknown(record);
14844
+ if (!value || value.jobId !== this.id) return;
14845
+ const status = normalizeJobStatus(value.status);
14846
+ if (status === "succeeded") {
14847
+ this.finalize(status, value.result, void 0, { hasResult: true });
14848
+ } else if (status === "failed" || status === "timeout" || status === "canceled") {
14849
+ this.finalize(status, void 0, value.error);
14850
+ } else return;
14851
+ this.emit("status", this.status);
14852
+ }
14455
14853
  get result() {
14456
14854
  return this._resultPromise;
14457
14855
  }
@@ -14676,7 +15074,7 @@ function artifactSummaryLine(artifactId, record) {
14676
15074
  const target = asRecord3(record.target);
14677
15075
  const metadata = asRecord3(record.metadata) || {};
14678
15076
  const subArtifactIds = Array.isArray(record.subArtifactIds) ? record.subArtifactIds.filter(
14679
- (id) => typeof id === "string" && id.trim().length > 0
15077
+ (id3) => typeof id3 === "string" && id3.trim().length > 0
14680
15078
  ).slice(0, 8) : [];
14681
15079
  const relationships = compactJson(record.relationships, 220);
14682
15080
  const pieces = [
@@ -15107,9 +15505,9 @@ var WSClient = class {
15107
15505
  hasRecentlyPendingRpcPeriod(maxAgeMs, now = Date.now()) {
15108
15506
  return this.messageQueue.length > 0 && this.pendingRpcPeriodStartedAt !== null && now - this.pendingRpcPeriodStartedAt <= maxAgeMs;
15109
15507
  }
15110
- removePendingRpc(id) {
15508
+ removePendingRpc(id3) {
15111
15509
  this.messageQueue = this.messageQueue.filter(
15112
- (pending) => pending.id !== id
15510
+ (pending) => pending.id !== id3
15113
15511
  );
15114
15512
  if (this.messageQueue.length === 0) this.pendingRpcPeriodStartedAt = null;
15115
15513
  }
@@ -15948,19 +16346,19 @@ var WSClient = class {
15948
16346
  if (!this.ws || this.ws.readyState !== READY_STATE_OPEN) {
15949
16347
  throw new Error("WebSocket not connected");
15950
16348
  }
15951
- const id = `rpc-${this.nextRpcId++}`;
16349
+ const id3 = `rpc-${this.nextRpcId++}`;
15952
16350
  const request = {
15953
16351
  type: "rpc",
15954
16352
  method,
15955
16353
  params,
15956
- id
16354
+ id: id3
15957
16355
  };
15958
16356
  return new Promise((resolve, reject) => {
15959
16357
  const timeoutMs = rpcTimeoutMsForMethod(method);
15960
16358
  const timeout = setTimeout(() => {
15961
- const pending = this.messageQueue.find((q) => q.id === id);
16359
+ const pending = this.messageQueue.find((q) => q.id === id3);
15962
16360
  if (pending) {
15963
- this.removePendingRpc(id);
16361
+ this.removePendingRpc(id3);
15964
16362
  reject(new Error(`RPC timeout: ${method}`));
15965
16363
  }
15966
16364
  }, timeoutMs);
@@ -15970,14 +16368,14 @@ var WSClient = class {
15970
16368
  this.messageQueue.push({
15971
16369
  resolve,
15972
16370
  reject,
15973
- id,
16371
+ id: id3,
15974
16372
  timeout
15975
16373
  });
15976
16374
  try {
15977
16375
  this.ws.send(JSON.stringify(request));
15978
16376
  } catch (error) {
15979
16377
  clearTimeout(timeout);
15980
- this.removePendingRpc(id);
16378
+ this.removePendingRpc(id3);
15981
16379
  reject(error instanceof Error ? error : new Error(String(error)));
15982
16380
  }
15983
16381
  });
@@ -16098,6 +16496,45 @@ var WSClient = class {
16098
16496
  }
16099
16497
  };
16100
16498
 
16499
+ // src/events-feed.ts
16500
+ var EventsFeed = class {
16501
+ constructor(request) {
16502
+ this.request = request;
16503
+ }
16504
+ list(filter = {}) {
16505
+ return this.request(`/control/events-feed/problems${eventsFeedSearch(filter)}`);
16506
+ }
16507
+ get(problemId, filter = {}) {
16508
+ return this.request(`/control/events-feed/problems/${encodeURIComponent(problemId)}${eventsFeedSearch(filter)}`);
16509
+ }
16510
+ update(problemId, input) {
16511
+ return this.request(`/control/events-feed/problems/${encodeURIComponent(problemId)}`, {
16512
+ method: "PATCH",
16513
+ body: JSON.stringify(input)
16514
+ });
16515
+ }
16516
+ metrics(filter = {}) {
16517
+ return this.request(`/control/events-feed/metrics${eventsFeedSearch(filter)}`);
16518
+ }
16519
+ health() {
16520
+ return this.request("/control/events-feed/health");
16521
+ }
16522
+ /** Sends SQL and positional parameters unchanged. The server enforces read-only tenant scope. */
16523
+ query(input) {
16524
+ return this.request("/control/events-feed/query", {
16525
+ method: "POST",
16526
+ body: JSON.stringify(input)
16527
+ });
16528
+ }
16529
+ };
16530
+ function eventsFeedSearch(filter) {
16531
+ const search = new URLSearchParams();
16532
+ for (const [key, value] of Object.entries(filter)) {
16533
+ if (value !== void 0) search.set(key, String(value));
16534
+ }
16535
+ return search.size ? `?${search.toString()}` : "";
16536
+ }
16537
+
16101
16538
  // src/client.ts
16102
16539
  var DEFAULT_CONVERSATION_SESSION_LIST_LIMIT = 100;
16103
16540
  var MAX_CONVERSATION_SESSION_LIST_LIMIT = 500;
@@ -16289,7 +16726,7 @@ function computeEffectRegistrationKey(effect) {
16289
16726
  function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId, effectHostUrl) {
16290
16727
  const overrideUrl = effectHostUrl || process.env.GRANULAR_EFFECT_HOST_URL || process.env.EFFECT_HOST_URL;
16291
16728
  const api = new URL(apiUrl);
16292
- const localRuntimeBase = process.env.RUNTIME_ORCHESTRATOR_URL || "";
16729
+ const localRuntimeBase = isLocalControlUrl(apiUrl) && api.port === "8787" ? "" : process.env.RUNTIME_ORCHESTRATOR_URL || "";
16293
16730
  const url = new URL(overrideUrl || localRuntimeBase || apiUrl);
16294
16731
  if (url.protocol === "https:") {
16295
16732
  url.protocol = "wss:";
@@ -16991,8 +17428,8 @@ var Environment = class _Environment {
16991
17428
  * Keep the original customer/system ID in `real_id`; graph paths are stable
16992
17429
  * internal addresses, not the source of truth for business identity.
16993
17430
  */
16994
- static toGraphPath(className, id) {
16995
- return `${_Environment.normalizeGraphPathSegment(className)}_${_Environment.normalizeGraphPathSegment(id)}`;
17431
+ static toGraphPath(className, id3) {
17432
+ return `${_Environment.normalizeGraphPathSegment(className)}_${_Environment.normalizeGraphPathSegment(id3)}`;
16996
17433
  }
16997
17434
  /**
16998
17435
  * Best-effort extraction of an ID-like suffix from a graph path.
@@ -18104,6 +18541,14 @@ var EnvironmentSession = class extends Session {
18104
18541
  const error = new Error(
18105
18542
  `Session data API Error (${response.status}): ${errorText}`
18106
18543
  );
18544
+ if (response.status === 403) {
18545
+ try {
18546
+ if (JSON.parse(errorText)?.error === "SUBJECT_SESSION_ENDED") {
18547
+ error.code = "SUBJECT_SESSION_ENDED";
18548
+ }
18549
+ } catch {
18550
+ }
18551
+ }
18107
18552
  if (isLocalControlUrl(url) && isRetryableSessionDataError(error) && attempt < SESSION_DATA_REQUEST_RETRY_COUNT) {
18108
18553
  await sleep(SESSION_DATA_REQUEST_RETRY_DELAY_MS * attempt);
18109
18554
  continue;
@@ -18153,7 +18598,7 @@ var EnvironmentSession = class extends Session {
18153
18598
  "Assistant replies require a server API-key session connection."
18154
18599
  );
18155
18600
  }
18156
- const id = requiredAssistantReplyString(input.id, "id");
18601
+ const id3 = requiredAssistantReplyString(input.id, "id");
18157
18602
  const operationId2 = requiredAssistantReplyString(
18158
18603
  input.operationId,
18159
18604
  "operationId"
@@ -18164,7 +18609,7 @@ var EnvironmentSession = class extends Session {
18164
18609
  void 0,
18165
18610
  {
18166
18611
  method: "POST",
18167
- body: { id, operationId: operationId2, text }
18612
+ body: { id: id3, operationId: operationId2, text }
18168
18613
  }
18169
18614
  );
18170
18615
  }
@@ -18179,9 +18624,18 @@ var EnvironmentSession = class extends Session {
18179
18624
  "/jobs",
18180
18625
  options
18181
18626
  ),
18182
- get: (jobId) => this.sessionDataRequest(
18183
- `/jobs/${encodeURIComponent(jobId)}`
18184
- ),
18627
+ get: async (jobId) => {
18628
+ try {
18629
+ const record = await this.sessionDataRequest(
18630
+ `/jobs/${encodeURIComponent(jobId)}`
18631
+ );
18632
+ this.reconcileCanonicalJobRead(jobId, record);
18633
+ return record;
18634
+ } catch (error) {
18635
+ this.rejectTerminalJobRead(jobId, error);
18636
+ throw error;
18637
+ }
18638
+ },
18185
18639
  latest: async (options = {}) => {
18186
18640
  const page = await this.sessionDataRequest("/jobs", {
18187
18641
  status: options.status || "all",
@@ -18604,8 +19058,22 @@ var OntologyHandle = class {
18604
19058
  disconnect: async () => this.granular.disconnectEffects(this.ontologyNameOrId)
18605
19059
  };
18606
19060
  }
19061
+ /** Register the product-owned user directory on the existing SDK connection. */
19062
+ register_users(handler, options) {
19063
+ return this.granular.registerUsers(this.ontologyNameOrId, handler, options);
19064
+ }
19065
+ get development() {
19066
+ return {
19067
+ register: (options) => this.granular.registerDevelopmentProvider(this.ontologyNameOrId, options)
19068
+ };
19069
+ }
18607
19070
  get importer() {
18608
19071
  return {
19072
+ /** Register and publish on the existing backend provider connection. */
19073
+ register: async (handler) => {
19074
+ this.granular.registerEnvironmentImporter(this.ontologyNameOrId, handler);
19075
+ await this.granular.connectEnvironmentImporter(this.ontologyNameOrId);
19076
+ },
18609
19077
  onEnvironmentCreate: (handler) => this.granular.registerEnvironmentImporter(
18610
19078
  this.ontologyNameOrId,
18611
19079
  handler
@@ -18615,6 +19083,10 @@ var OntologyHandle = class {
18615
19083
  }
18616
19084
  };
18617
19085
  var Granular = class _Granular {
19086
+ /** Tenant events feed, authenticated with this client's credentials. */
19087
+ eventsFeed = new EventsFeed(
19088
+ (path2, options) => this.request(path2, options)
19089
+ );
18618
19090
  apiKey;
18619
19091
  apiUrl;
18620
19092
  httpUrl;
@@ -18629,6 +19101,8 @@ var Granular = class _Granular {
18629
19101
  sandboxEffects = /* @__PURE__ */ new Map();
18630
19102
  /** Live sandbox-scoped effect hosts keyed by sandboxId */
18631
19103
  sandboxEffectHosts = /* @__PURE__ */ new Map();
19104
+ developmentProviders = /* @__PURE__ */ new Map();
19105
+ usersProviders = /* @__PURE__ */ new Map();
18632
19106
  /** In-flight host connection promises to avoid duplicate concurrent connects */
18633
19107
  sandboxEffectHostPromises = /* @__PURE__ */ new Map();
18634
19108
  /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
@@ -18680,6 +19154,13 @@ var Granular = class _Granular {
18680
19154
  }
18681
19155
  }
18682
19156
  }
19157
+ async connectEnvironmentImporter(ontologyNameOrId) {
19158
+ const sandboxId = await this._resolveSandboxId(ontologyNameOrId);
19159
+ const importer = this.resolveEnvironmentImporter(ontologyNameOrId, sandboxId);
19160
+ if (!importer) throw new Error("No environment importer registered.");
19161
+ const host = await this.ensureSandboxEffectHost(sandboxId);
19162
+ await host.wsClient.call("environment.importer.register", {});
19163
+ }
18683
19164
  clearEnvironmentImporter(ontologyNameOrId) {
18684
19165
  this.ontologyImporters.delete(ontologyNameOrId);
18685
19166
  for (const [sandboxId, importer] of this.sandboxImporters.entries()) {
@@ -18984,7 +19465,24 @@ var Granular = class _Granular {
18984
19465
  * `getRecordImportSummary()`.
18985
19466
  */
18986
19467
  async runEnvironmentImporterForEnvironment(environmentId, options = {}) {
19468
+ return this.runBoundEnvironmentImporter(environmentId, options);
19469
+ }
19470
+ /** Only the authenticated server-created reverse-RPC binding supplies this
19471
+ * product identity. Ordinary public callers retain legacy identity checks. */
19472
+ async runBoundEnvironmentImporter(environmentId, options, verifiedIdentity) {
18987
19473
  const environmentData = await this.environments.get(environmentId);
19474
+ if (options.expectedSubjectId && environmentData.subjectId !== options.expectedSubjectId) {
19475
+ throw new Error("Importer environment does not match the authenticated subject.");
19476
+ }
19477
+ const subject = await this.request(
19478
+ `/control/subjects/${encodeURIComponent(environmentData.subjectId)}`
19479
+ );
19480
+ if (verifiedIdentity && subject.identityId !== verifiedIdentity.identityId)
19481
+ throw new Error("Importer canonical identity changed.");
19482
+ const externalUserId = verifiedIdentity?.externalUserId || subject.userId || subject.identityId;
19483
+ if ((subject.subjectId || subject.granularId) !== environmentData.subjectId || !externalUserId || options.expectedExternalUserId && options.expectedExternalUserId !== externalUserId) {
19484
+ throw new Error("Importer subject has no matching canonical product identity.");
19485
+ }
18988
19486
  const environment = this.bindEnvironmentHandle(environmentData);
18989
19487
  const requestedOntology = options.ontology || environmentData.ontologyId || environmentData.sandboxId;
18990
19488
  return this.runEnvironmentImporter(
@@ -18993,9 +19491,10 @@ var Granular = class _Granular {
18993
19491
  requestedOntology,
18994
19492
  sandboxId: environmentData.sandboxId,
18995
19493
  subjectId: environmentData.subjectId,
18996
- externalUserId: environmentData.subjectId,
19494
+ externalUserId,
18997
19495
  setupTriggerReason: options.reason || "new_environment",
18998
- setupOperationKey: options.operationKey
19496
+ setupOperationKey: options.operationKey,
19497
+ existingSetupRunId: options.setupRunId
18999
19498
  },
19000
19499
  environment
19001
19500
  );
@@ -19310,7 +19809,7 @@ var Granular = class _Granular {
19310
19809
  }
19311
19810
  if (status !== "all") query.set("status", status);
19312
19811
  const res = await this.request(`/control/sessions?${query.toString()}`);
19313
- const items = Array.isArray(res.items) ? res.items.map((row) => this.normalizeConversationSession(row)) : [];
19812
+ const items = Array.isArray(res.items) ? res.items.map((row2) => this.normalizeConversationSession(row2)) : [];
19314
19813
  const nextCursor = res.nextCursor ?? null;
19315
19814
  if (nextCursor === cursor) {
19316
19815
  throw new Error("Session pagination cursor did not advance");
@@ -19368,26 +19867,26 @@ var Granular = class _Granular {
19368
19867
  result.readThroughSequenceBySessionId
19369
19868
  );
19370
19869
  }
19371
- normalizeConversationSession(row) {
19372
- const sessionId = String(row.sessionId ?? row.session_id ?? "");
19373
- const environmentId = String(row.environmentId ?? row.environment_id ?? "");
19870
+ normalizeConversationSession(row2) {
19871
+ const sessionId = String(row2.sessionId ?? row2.session_id ?? "");
19872
+ const environmentId = String(row2.environmentId ?? row2.environment_id ?? "");
19374
19873
  return {
19375
19874
  sessionId,
19376
- tenantId: row.tenantId != null ? String(row.tenantId) : void 0,
19875
+ tenantId: row2.tenantId != null ? String(row2.tenantId) : void 0,
19377
19876
  environmentId,
19378
- versionId: row.versionId != null ? String(row.versionId) : null,
19379
- docId: String(row.docId ?? row.doc_id ?? ""),
19380
- status: row.status || "active",
19381
- createdAt: _Granular.coerceIsoDate(row.createdAt ?? row.created_at),
19382
- lastSeenAt: _Granular.coerceIsoDate(row.lastSeenAt ?? row.last_seen_at),
19383
- summary: row.summary != null ? String(row.summary) : null,
19384
- summaryUpdatedAt: row.summaryUpdatedAt != null || row.summary_updated_at != null ? _Granular.coerceIsoDate(
19385
- row.summaryUpdatedAt ?? row.summary_updated_at
19877
+ versionId: row2.versionId != null ? String(row2.versionId) : null,
19878
+ docId: String(row2.docId ?? row2.doc_id ?? ""),
19879
+ status: row2.status || "active",
19880
+ createdAt: _Granular.coerceIsoDate(row2.createdAt ?? row2.created_at),
19881
+ lastSeenAt: _Granular.coerceIsoDate(row2.lastSeenAt ?? row2.last_seen_at),
19882
+ summary: row2.summary != null ? String(row2.summary) : null,
19883
+ summaryUpdatedAt: row2.summaryUpdatedAt != null || row2.summary_updated_at != null ? _Granular.coerceIsoDate(
19884
+ row2.summaryUpdatedAt ?? row2.summary_updated_at
19386
19885
  ) : null,
19387
- subjectId: row.subjectId != null ? String(row.subjectId) : null,
19388
- sessionScope: row.sessionScope != null || row.session_scope != null ? String(row.sessionScope ?? row.session_scope) : null,
19389
- jobCount: typeof row.jobCount === "number" ? row.jobCount : void 0,
19390
- toolCallCount: typeof row.toolCallCount === "number" ? row.toolCallCount : void 0
19886
+ subjectId: row2.subjectId != null ? String(row2.subjectId) : null,
19887
+ sessionScope: row2.sessionScope != null || row2.session_scope != null ? String(row2.sessionScope ?? row2.session_scope) : null,
19888
+ jobCount: typeof row2.jobCount === "number" ? row2.jobCount : void 0,
19889
+ toolCallCount: typeof row2.toolCallCount === "number" ? row2.toolCallCount : void 0
19391
19890
  };
19392
19891
  }
19393
19892
  normalizeUserEnvironmentState(state) {
@@ -19566,7 +20065,7 @@ var Granular = class _Granular {
19566
20065
  if (!importer) {
19567
20066
  return null;
19568
20067
  }
19569
- const setupRun = await this.request(
20068
+ const setupRun = resolved.existingSetupRunId ? resolved.environment.setup : await this.request(
19570
20069
  `/control/environments/${environment.environmentId}/setup-runs`,
19571
20070
  {
19572
20071
  method: "POST",
@@ -19576,6 +20075,8 @@ var Granular = class _Granular {
19576
20075
  })
19577
20076
  }
19578
20077
  );
20078
+ if (!setupRun || resolved.existingSetupRunId && setupRun.setupRunId !== resolved.existingSetupRunId || setupRun.environmentId !== environment.environmentId || setupRun.sandboxId !== resolved.sandboxId || setupRun.subjectId !== resolved.subjectId)
20079
+ throw new Error("Importer setup does not match the canonical environment.");
19579
20080
  const setupRunId = setupRun.setupRunId;
19580
20081
  let claim = null;
19581
20082
  for (let attempt = 0; attempt < 3; attempt += 1) {
@@ -19618,6 +20119,8 @@ var Granular = class _Granular {
19618
20119
  sandboxId: environment.sandboxId,
19619
20120
  subjectId: environment.subjectId,
19620
20121
  externalUserId: resolved.externalUserId,
20122
+ setupRunId,
20123
+ setupOperationKey: setupRun.operationKey ?? null,
19621
20124
  reason: resolved.setupTriggerReason,
19622
20125
  incrementTotalObjectsToImportCount: async (n) => {
19623
20126
  const safeIncrement = Math.max(0, Math.trunc(n));
@@ -19907,6 +20410,56 @@ var Granular = class _Granular {
19907
20410
  host.heartbeatTimer = null;
19908
20411
  host.heartbeatInFlight = false;
19909
20412
  }
20413
+ async registerUsers(ontologyNameOrId, handler, options) {
20414
+ const provider = new UsersProvider(handler, options);
20415
+ const sandboxId = await this._resolveSandboxId(ontologyNameOrId);
20416
+ const previous = this.usersProviders.get(sandboxId);
20417
+ this.usersProviders.set(sandboxId, provider);
20418
+ try {
20419
+ const host = await this.ensureSandboxEffectHost(sandboxId);
20420
+ if (provider.registration?.providerId !== host.effectClientId) await this.registerUsersOnHost(host, provider);
20421
+ if (!provider.registration) throw new Error("User directory registration is no longer live.");
20422
+ return provider.registration;
20423
+ } catch (error) {
20424
+ if (this.usersProviders.get(sandboxId) === provider) {
20425
+ if (previous) this.usersProviders.set(sandboxId, previous);
20426
+ else this.usersProviders.delete(sandboxId);
20427
+ }
20428
+ throw error;
20429
+ }
20430
+ }
20431
+ async registerUsersOnHost(host, provider) {
20432
+ const registration = await host.wsClient.call("users.register", {});
20433
+ if (this.usersProviders.get(host.sandboxId) !== provider) throw new Error("User directory registration was replaced.");
20434
+ provider.bind(registration, host.sandboxId, host.effectClientId);
20435
+ }
20436
+ /** Register product-owned dev operator callbacks on the existing provider socket. */
20437
+ async registerDevelopmentProvider(ontologyNameOrId, options) {
20438
+ const provider = new DevelopmentProvider(options);
20439
+ const sandboxId = await this._resolveSandboxId(ontologyNameOrId);
20440
+ const previous = this.developmentProviders.get(sandboxId);
20441
+ this.developmentProviders.set(sandboxId, provider);
20442
+ try {
20443
+ const host = await this.ensureSandboxEffectHost(sandboxId);
20444
+ if (this.developmentProviders.get(sandboxId) !== provider) throw new Error("Development registration was replaced.");
20445
+ if (provider.registration?.providerId !== host.effectClientId) {
20446
+ await this.registerDevelopmentOnHost(host, provider);
20447
+ }
20448
+ if (!provider.registration) throw new Error("Development provider registration is no longer live.");
20449
+ return provider.registration;
20450
+ } catch (error) {
20451
+ if (this.developmentProviders.get(sandboxId) === provider) {
20452
+ if (previous) this.developmentProviders.set(sandboxId, previous);
20453
+ else this.developmentProviders.delete(sandboxId);
20454
+ }
20455
+ throw error;
20456
+ }
20457
+ }
20458
+ async registerDevelopmentOnHost(host, provider) {
20459
+ const registration = await host.wsClient.call("onboarding.register", provider.registrationParams());
20460
+ if (this.developmentProviders.get(host.sandboxId) !== provider) throw new Error("Development registration was replaced.");
20461
+ provider.bind(registration, host.sandboxId, host.effectClientId);
20462
+ }
19910
20463
  async synchronizeEffectHost(host) {
19911
20464
  if (host.syncPromise) {
19912
20465
  return host.syncPromise;
@@ -19917,6 +20470,12 @@ var Granular = class _Granular {
19917
20470
  protocolVersion: "2.0"
19918
20471
  });
19919
20472
  await this.publishSandboxEffectCatalog(host);
20473
+ if (this.resolveEnvironmentImporter(host.sandboxId, host.sandboxId))
20474
+ await host.wsClient.call("environment.importer.register", {});
20475
+ const users2 = this.usersProviders.get(host.sandboxId);
20476
+ if (users2) await this.registerUsersOnHost(host, users2);
20477
+ const development = this.developmentProviders.get(host.sandboxId);
20478
+ if (development) await this.registerDevelopmentOnHost(host, development);
19920
20479
  this.startEffectHostHeartbeat(host);
19921
20480
  })();
19922
20481
  try {
@@ -19964,6 +20523,29 @@ var Granular = class _Granular {
19964
20523
  recovering: false,
19965
20524
  syncPromise: null
19966
20525
  };
20526
+ wsClient.registerRpcHandler("environment.import", async (params) => {
20527
+ const p = params;
20528
+ if (!p || p.sandboxId !== sandboxId || !p.environmentId || !p.setupRunId || !p.subjectId || !p.identityId || !p.externalUserId) throw new Error("Invalid importer scope.");
20529
+ const current = await this.environments.get(p.environmentId);
20530
+ if (current.sandboxId !== sandboxId || current.buildId !== p.buildId || (current.envName || current.environment) !== p.environment || current.subjectId !== p.subjectId) throw new Error("Importer environment changed.");
20531
+ return this.runBoundEnvironmentImporter(p.environmentId, { ontology: sandboxId, setupRunId: p.setupRunId, expectedSubjectId: p.subjectId, expectedExternalUserId: p.externalUserId }, { identityId: p.identityId, externalUserId: p.externalUserId });
20532
+ });
20533
+ wsClient.registerRpcHandler("users.invoke", async (params) => {
20534
+ const provider = this.usersProviders.get(sandboxId);
20535
+ if (!provider) throw new Error("No user directory is registered for this ontology.");
20536
+ const input = params;
20537
+ return input?.page ? provider.invoke(input.page) : provider.invoke();
20538
+ });
20539
+ wsClient.registerRpcHandler("users.resolveMembership", async (params) => {
20540
+ const provider = this.usersProviders.get(sandboxId);
20541
+ if (!provider) throw new Error("No user directory is registered for this ontology.");
20542
+ return provider.resolveMembership(params);
20543
+ });
20544
+ wsClient.registerRpcHandler("onboarding.invoke", async (params) => {
20545
+ const provider = this.developmentProviders.get(sandboxId);
20546
+ if (!provider) throw new Error("No development handlers are registered for this sandbox.");
20547
+ return provider.invoke(params);
20548
+ });
19967
20549
  wsClient.registerRpcHandler("effect.invoke", async (params) => {
19968
20550
  const request = params;
19969
20551
  let commitReceipt;
@@ -20031,6 +20613,10 @@ var Granular = class _Granular {
20031
20613
  });
20032
20614
  wsClient.on("disconnect", () => {
20033
20615
  this.stopEffectHostHeartbeat(host);
20616
+ const users2 = this.usersProviders.get(sandboxId);
20617
+ if (users2?.registration?.providerId === host.effectClientId) users2.unbind();
20618
+ const provider = this.developmentProviders.get(sandboxId);
20619
+ if (provider?.registration?.providerId === host.effectClientId) provider.unbind();
20034
20620
  });
20035
20621
  try {
20036
20622
  await withTimeout(
@@ -20245,8 +20831,8 @@ var Granular = class _Granular {
20245
20831
  list: async () => {
20246
20832
  return this.request("/control/sandboxes");
20247
20833
  },
20248
- get: async (id) => {
20249
- return this.request(`/control/sandboxes/${id}`);
20834
+ get: async (id3) => {
20835
+ return this.request(`/control/sandboxes/${id3}`);
20250
20836
  },
20251
20837
  create: async (data) => {
20252
20838
  return this.request("/control/sandboxes", {
@@ -20254,14 +20840,14 @@ var Granular = class _Granular {
20254
20840
  body: JSON.stringify(data)
20255
20841
  });
20256
20842
  },
20257
- update: async (id, data) => {
20258
- return this.request(`/control/sandboxes/${id}`, {
20843
+ update: async (id3, data) => {
20844
+ return this.request(`/control/sandboxes/${id3}`, {
20259
20845
  method: "PATCH",
20260
20846
  body: JSON.stringify(data)
20261
20847
  });
20262
20848
  },
20263
- delete: async (id) => {
20264
- return this.request(`/control/sandboxes/${id}`, {
20849
+ delete: async (id3) => {
20850
+ return this.request(`/control/sandboxes/${id3}`, {
20265
20851
  method: "DELETE"
20266
20852
  });
20267
20853
  }
@@ -20411,17 +20997,17 @@ var Granular = class _Granular {
20411
20997
  const result = await this.request(
20412
20998
  `/control/stream-events?${query.toString()}`
20413
20999
  );
20414
- return (result.items || []).map((row) => ({
20415
- eventId: row.event_id,
20416
- streamName: row.stream_name,
20417
- eventType: row.event_type,
20418
- payload: typeof row.payload === "string" ? JSON.parse(row.payload) : row.payload,
20419
- environmentId: row.environment_id,
20420
- sessionId: row.session_id,
20421
- subjectId: row.subject_id,
20422
- source: row.source,
20423
- isAcked: Boolean(row.is_acked),
20424
- createdAt: row.created_at
21000
+ return (result.items || []).map((row2) => ({
21001
+ eventId: row2.event_id,
21002
+ streamName: row2.stream_name,
21003
+ eventType: row2.event_type,
21004
+ payload: typeof row2.payload === "string" ? JSON.parse(row2.payload) : row2.payload,
21005
+ environmentId: row2.environment_id,
21006
+ sessionId: row2.session_id,
21007
+ subjectId: row2.subject_id,
21008
+ source: row2.source,
21009
+ isAcked: Boolean(row2.is_acked),
21010
+ createdAt: row2.created_at
20425
21011
  }));
20426
21012
  },
20427
21013
  subscribe: (params) => {
@@ -20489,13 +21075,13 @@ var Granular = class _Granular {
20489
21075
  const result = await this.request(
20490
21076
  `/control/stream-events/stats?${query.toString()}`
20491
21077
  );
20492
- return (result.items || []).map((row) => ({
20493
- streamName: row.stream_name,
20494
- eventType: row.event_type,
20495
- total: Number(row.total),
20496
- last1h: Number(row.last_1h),
20497
- last24h: Number(row.last_24h),
20498
- unacked: Number(row.unacked)
21078
+ return (result.items || []).map((row2) => ({
21079
+ streamName: row2.stream_name,
21080
+ eventType: row2.event_type,
21081
+ total: Number(row2.total),
21082
+ last1h: Number(row2.last_1h),
21083
+ last24h: Number(row2.last_24h),
21084
+ unacked: Number(row2.unacked)
20499
21085
  }));
20500
21086
  }
20501
21087
  };
@@ -20534,9 +21120,9 @@ var Granular = class _Granular {
20534
21120
  })
20535
21121
  );
20536
21122
  },
20537
- get: async (id) => {
21123
+ get: async (id3) => {
20538
21124
  return normalizeSubject(
20539
- await this.request(`/control/subjects/${id}`)
21125
+ await this.request(`/control/subjects/${id3}`)
20540
21126
  );
20541
21127
  }
20542
21128
  };
@@ -22160,7 +22746,7 @@ function buildGranularAgentManualActionMemorySummary(input) {
22160
22746
  failureCount: typeof suggestion.failureCount === "number" && Number.isFinite(suggestion.failureCount) ? suggestion.failureCount : null,
22161
22747
  lastOccurredAt: typeof suggestion.lastOccurredAt === "number" && Number.isFinite(suggestion.lastOccurredAt) ? suggestion.lastOccurredAt : null,
22162
22748
  sampleTargetIds: Array.isArray(suggestion.sampleTargetIds) ? suggestion.sampleTargetIds.filter(
22163
- (id) => typeof id === "string" && id.trim().length > 0
22749
+ (id3) => typeof id3 === "string" && id3.trim().length > 0
22164
22750
  ).slice(0, 6) : []
22165
22751
  }));
22166
22752
  return [
@@ -23256,8 +23842,8 @@ function collectReferencesFromRecord(record, refs) {
23256
23842
  for (const key of VARIABLE_ARRAY_KEY_CANDIDATES)
23257
23843
  pushStringArray(refs.variableNames, record[key]);
23258
23844
  }
23259
- function stringValue(record, keys) {
23260
- for (const key of keys) {
23845
+ function stringValue(record, keys2) {
23846
+ for (const key of keys2) {
23261
23847
  const value = record[key];
23262
23848
  if (typeof value === "string" && value.trim()) {
23263
23849
  return value.trim();
@@ -23270,8 +23856,8 @@ function findEntryPathForRecord(record, heap) {
23270
23856
  if (directPath && heap.entriesByPath?.[directPath]) {
23271
23857
  return directPath;
23272
23858
  }
23273
- const id = stringValue(record, ["id", "_id", "recordId", "objectId"]);
23274
- if (!id) {
23859
+ const id3 = stringValue(record, ["id", "_id", "recordId", "objectId"]);
23860
+ if (!id3) {
23275
23861
  return null;
23276
23862
  }
23277
23863
  const className = stringValue(record, [
@@ -23283,12 +23869,12 @@ function findEntryPathForRecord(record, heap) {
23283
23869
  ]);
23284
23870
  const entries = Object.values(heap.entriesByPath || {});
23285
23871
  const exact = entries.find(
23286
- (entry) => entry.id === id && (!className || entry.className === className || entry.prototypes?.includes(className))
23872
+ (entry) => entry.id === id3 && (!className || entry.className === className || entry.prototypes?.includes(className))
23287
23873
  );
23288
23874
  if (exact?.path) {
23289
23875
  return exact.path;
23290
23876
  }
23291
- const idOnlyMatches = entries.filter((entry) => entry.id === id);
23877
+ const idOnlyMatches = entries.filter((entry) => entry.id === id3);
23292
23878
  return idOnlyMatches.length === 1 ? idOnlyMatches[0].path : null;
23293
23879
  }
23294
23880
  function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__ */ new Set()) {
@@ -23853,8 +24439,8 @@ function aggregateConversationTokenUsage(conversation) {
23853
24439
  )
23854
24440
  );
23855
24441
  }
23856
- function tokenUsageForGenerationOutput(generation) {
23857
- const attempts = generation.generationAttempts?.length ? generation.generationAttempts : [{ raw: generation.raw }];
24442
+ function tokenUsageForGenerationOutput(generation2) {
24443
+ const attempts = generation2.generationAttempts?.length ? generation2.generationAttempts : [{ raw: generation2.raw }];
23858
24444
  return aggregateTokenUsage(
23859
24445
  attempts.map((attempt) => extractTokenUsageFromRaw(attempt.raw))
23860
24446
  );
@@ -24342,11 +24928,11 @@ function normalizeHeapSnapshot2(heap) {
24342
24928
  function targetFromUiContext(context) {
24343
24929
  const target = asRecord7(context?.target) || asRecord7(context?.currentPageObject) || asRecord7(context?.commentaryTarget);
24344
24930
  const className = typeof target?.className === "string" ? target.className : "";
24345
- const id = typeof target?.id === "string" ? target.id : "";
24346
- if (!className || !id) return null;
24931
+ const id3 = typeof target?.id === "string" ? target.id : "";
24932
+ if (!className || !id3) return null;
24347
24933
  return {
24348
24934
  className,
24349
- id,
24935
+ id: id3,
24350
24936
  label: typeof target?.label === "string" ? target.label : void 0
24351
24937
  };
24352
24938
  }
@@ -25162,14 +25748,14 @@ function isTransientEvalError(error) {
25162
25748
  const message = error instanceof Error ? error.message : String(error);
25163
25749
  return /socket connection was closed unexpectedly/i.test(message) || /timed out after/i.test(message) || /ECONNRESET/i.test(message) || /network/i.test(message) || /429/.test(message);
25164
25750
  }
25165
- function assertionPassed(id, run) {
25751
+ function assertionPassed(id3, run) {
25166
25752
  try {
25167
- run(id);
25168
- return { id, label: id, status: "passed" };
25753
+ run(id3);
25754
+ return { id: id3, label: id3, status: "passed" };
25169
25755
  } catch (error) {
25170
25756
  return {
25171
- id,
25172
- label: id,
25757
+ id: id3,
25758
+ label: id3,
25173
25759
  status: "failed",
25174
25760
  message: error instanceof Error ? error.message : String(error)
25175
25761
  };
@@ -26095,7 +26681,7 @@ function createAgentEvalHarness(options) {
26095
26681
  });
26096
26682
  };
26097
26683
  const generationStartedAt = Date.now();
26098
- const generation = await withTimeout2(
26684
+ const generation2 = await withTimeout2(
26099
26685
  generateTurnWithRepair(options.generator, {
26100
26686
  systemPrompt,
26101
26687
  history: buildHistory(conversation.history),
@@ -26146,16 +26732,16 @@ function createAgentEvalHarness(options) {
26146
26732
  iteration: iteration + 1,
26147
26733
  templateId: renderedPrompt.templateId,
26148
26734
  templateVersion: renderedPrompt.templateVersion,
26149
- title: generation.code ? "Generated job code" : "Generated text reply",
26150
- message: generation.code || generation.reply || "",
26735
+ title: generation2.code ? "Generated job code" : "Generated text reply",
26736
+ message: generation2.code || generation2.reply || "",
26151
26737
  data: {
26152
- reply: generation.reply,
26153
- code: generation.code,
26154
- attempts: generation.generationAttempts,
26155
- usage: tokenUsageForGenerationOutput(generation)
26738
+ reply: generation2.reply,
26739
+ code: generation2.code,
26740
+ attempts: generation2.generationAttempts,
26741
+ usage: tokenUsageForGenerationOutput(generation2)
26156
26742
  }
26157
26743
  });
26158
- const generatedReasoningLines = generation.code ? consumeGranularReasoningOnlyChunk("", generation.code, {
26744
+ const generatedReasoningLines = generation2.code ? consumeGranularReasoningOnlyChunk("", generation2.code, {
26159
26745
  final: true
26160
26746
  }).reasoningLines : [];
26161
26747
  for (const line of generatedReasoningLines) {
@@ -26170,18 +26756,18 @@ function createAgentEvalHarness(options) {
26170
26756
  templateVersion: renderedPrompt.templateVersion,
26171
26757
  templateHash: renderedPrompt.templateHash,
26172
26758
  promptInstanceHash: renderedPrompt.promptInstanceHash,
26173
- generationReply: generation.reply,
26174
- generatedCode: generation.code,
26175
- rawGeneration: generation.raw,
26176
- generationAttempts: generation.generationAttempts,
26177
- tokenUsage: tokenUsageForGenerationOutput(generation)
26759
+ generationReply: generation2.reply,
26760
+ generatedCode: generation2.code,
26761
+ rawGeneration: generation2.raw,
26762
+ generationAttempts: generation2.generationAttempts,
26763
+ tokenUsage: tokenUsageForGenerationOutput(generation2)
26178
26764
  };
26179
26765
  turnLog.iterations.push(iterationLog);
26180
26766
  await writeJson(
26181
26767
  path__default.default.join(turnDir, `iteration-${iteration + 1}-generation.json`),
26182
- generation
26768
+ generation2
26183
26769
  );
26184
- if (!generation.code) {
26770
+ if (!generation2.code) {
26185
26771
  const responseText2 = "";
26186
26772
  const completed = {
26187
26773
  conversation,
@@ -26231,7 +26817,7 @@ function createAgentEvalHarness(options) {
26231
26817
  return completed;
26232
26818
  }
26233
26819
  const session = conversation.environment;
26234
- const job = await session.submitJob(generation.code, {
26820
+ const job = await session.submitJob(generation2.code, {
26235
26821
  agent: {
26236
26822
  userRequest: input.request,
26237
26823
  generationRequest: request,
@@ -26241,9 +26827,9 @@ function createAgentEvalHarness(options) {
26241
26827
  turnId,
26242
26828
  iteration: iteration + 1,
26243
26829
  tools,
26244
- generationReply: generation.reply,
26245
- rawGeneration: generation.raw,
26246
- repairIssues: generation.generationAttempts?.flatMap(
26830
+ generationReply: generation2.reply,
26831
+ rawGeneration: generation2.raw,
26832
+ repairIssues: generation2.generationAttempts?.flatMap(
26247
26833
  (attempt) => attempt.repairIssues || []
26248
26834
  )
26249
26835
  }
@@ -26259,7 +26845,7 @@ function createAgentEvalHarness(options) {
26259
26845
  templateVersion: renderedPrompt.templateVersion,
26260
26846
  title: "Submitted Granular job",
26261
26847
  message: job.id,
26262
- data: { code: generation.code }
26848
+ data: { code: generation2.code }
26263
26849
  });
26264
26850
  const outcome = await waitForJobOutcome({
26265
26851
  environment: conversation.environment,
@@ -26283,7 +26869,7 @@ function createAgentEvalHarness(options) {
26283
26869
  request: input.request,
26284
26870
  turnDir,
26285
26871
  boundaryTimestamp,
26286
- finalCode: generation.code,
26872
+ finalCode: generation2.code,
26287
26873
  stdout: outcome.stdout,
26288
26874
  stderr: outcome.stderr,
26289
26875
  prompts: outcome.prompts,
@@ -26303,7 +26889,7 @@ function createAgentEvalHarness(options) {
26303
26889
  request: input.request,
26304
26890
  turnDir,
26305
26891
  boundaryTimestamp,
26306
- finalCode: generation.code,
26892
+ finalCode: generation2.code,
26307
26893
  stdout: outcome.stdout,
26308
26894
  stderr: outcome.stderr,
26309
26895
  prompts: outcome.prompts,
@@ -26358,7 +26944,7 @@ function createAgentEvalHarness(options) {
26358
26944
  });
26359
26945
  const responseText = presentation.responseText ?? "";
26360
26946
  const verifierSnapshot = createHarnessVerifierSnapshot({
26361
- finalCode: generation.code,
26947
+ finalCode: generation2.code,
26362
26948
  resultPreview: JSON.stringify(outcome.result, null, 2),
26363
26949
  liveDoc: settledLiveDoc,
26364
26950
  projectionOptions: { boundaryTimestamp }
@@ -26411,7 +26997,7 @@ function createAgentEvalHarness(options) {
26411
26997
  conversation.history.push({
26412
26998
  role: "assistant",
26413
26999
  content: responseText,
26414
- code: generation.code,
27000
+ code: generation2.code,
26415
27001
  jobStatus: "succeeded",
26416
27002
  jobResultPreview: JSON.stringify(outcome.result, null, 2)
26417
27003
  });
@@ -26437,7 +27023,7 @@ function createAgentEvalHarness(options) {
26437
27023
  turnDir,
26438
27024
  responseText,
26439
27025
  terminalKind: getCurrentClosureId(settledLiveDoc) ? "closure" : "reply",
26440
- finalCode: generation.code,
27026
+ finalCode: generation2.code,
26441
27027
  actionSummary: latestCheckpoint.latestActionSummary || [],
26442
27028
  promptInteractions: [],
26443
27029
  verification: null,