@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.
@@ -4021,6 +4021,347 @@ var GranularApiError = class extends Error {
4021
4021
  idempotencyKey;
4022
4022
  };
4023
4023
 
4024
+ // src/users-provider.ts
4025
+ var UsersProvider = class {
4026
+ constructor(handler, options = {}) {
4027
+ this.handler = handler;
4028
+ this.options = options;
4029
+ if (typeof handler !== "function")
4030
+ throw new Error("register_users requires a user-list callback.");
4031
+ }
4032
+ binding;
4033
+ bind(value, sandboxId, providerId) {
4034
+ const entry = value;
4035
+ if (!entry || entry.sandboxId !== sandboxId || entry.providerId !== providerId)
4036
+ throw new Error(
4037
+ "User directory registration does not match the provider connection."
4038
+ );
4039
+ return this.binding = Object.freeze({ sandboxId, providerId });
4040
+ }
4041
+ get registration() {
4042
+ return this.binding;
4043
+ }
4044
+ unbind() {
4045
+ this.binding = void 0;
4046
+ }
4047
+ async invoke(page) {
4048
+ const binding = this.binding;
4049
+ if (!binding) throw new Error("User directory is not registered.");
4050
+ 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)))
4051
+ throw new Error("Invalid user directory page request.");
4052
+ const paged = page && this.options.listPage ? await this.options.listPage(Object.freeze({ ...page })) : null;
4053
+ if (page && this.options.listPage && (!paged || typeof paged !== "object" || Array.isArray(paged)))
4054
+ throw new Error("User directory returned an invalid page.");
4055
+ const result = paged ? paged.users : await this.handler();
4056
+ if (this.binding !== binding)
4057
+ throw new Error("User directory connection changed.");
4058
+ if (!Array.isArray(result) || result.length > 1e4)
4059
+ throw new Error("User directory must return at most 10000 users.");
4060
+ 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)))
4061
+ throw new Error("User directory returned an invalid page.");
4062
+ const seen = /* @__PURE__ */ new Set();
4063
+ const users2 = result.map((user) => {
4064
+ 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))
4065
+ throw new Error(
4066
+ "User directory requires unique ids and display names."
4067
+ );
4068
+ seen.add(user.id);
4069
+ return {
4070
+ id: user.id,
4071
+ name: user.name,
4072
+ ...user.email !== void 0 ? { email: user.email } : {}
4073
+ };
4074
+ });
4075
+ if (!page) return users2;
4076
+ if (paged) return { users: users2, nextCursor: paged.nextCursor, ...paged.truncated ? { truncated: true } : {} };
4077
+ const query = page.search?.toLocaleLowerCase();
4078
+ const filtered = query ? users2.filter(
4079
+ (user) => [user.name, user.email, user.id].some(
4080
+ (v) => v?.toLocaleLowerCase().includes(query)
4081
+ )
4082
+ ) : users2;
4083
+ if (page.cursor && !/^legacy:[0-9]+$/.test(page.cursor))
4084
+ throw new Error("Invalid legacy directory cursor.");
4085
+ const start = page.cursor ? Number(page.cursor.slice(7)) : 0;
4086
+ if (!Number.isSafeInteger(start) || start > filtered.length)
4087
+ throw new Error("Invalid legacy directory cursor.");
4088
+ const end = Math.min(start + page.limit, filtered.length);
4089
+ return {
4090
+ users: filtered.slice(start, end),
4091
+ nextCursor: end < filtered.length ? `legacy:${end}` : null
4092
+ };
4093
+ }
4094
+ async resolveMembership(input) {
4095
+ const binding = this.binding;
4096
+ if (!binding || !this.options.resolveMembership)
4097
+ throw new Error("Product membership resolution is not registered.");
4098
+ if (!input || input.environment !== "dev" || ![input.tenantId, input.integrationId, input.providerSubject].every(
4099
+ (value) => typeof value === "string" && !!value.trim()
4100
+ ))
4101
+ throw new Error("Invalid verified customer membership scope.");
4102
+ const member = await this.options.resolveMembership(input);
4103
+ if (this.binding !== binding)
4104
+ throw new Error("User directory connection changed.");
4105
+ if (member === null) return null;
4106
+ if (!member || typeof member.identityId !== "string" || !member.identityId.trim() || member.identityId.length > 200 || typeof member.active !== "boolean")
4107
+ throw new Error("Invalid product membership response.");
4108
+ return { identityId: member.identityId, active: member.active };
4109
+ }
4110
+ };
4111
+
4112
+ // src/onboarding-postcondition.ts
4113
+ var object = (v) => !!v && typeof v === "object" && !Array.isArray(v);
4114
+ var id = (v) => typeof v === "string" && v.length > 0 && v.length <= 500 && v.trim() === v && !/[\u0000-\u001f\u007f]/u.test(v);
4115
+ var scalar = (v) => v === null || typeof v === "boolean" || typeof v === "number" && Number.isFinite(v) || typeof v === "string" && v.length <= 4e3;
4116
+ var only = (v, keys2) => Object.keys(v).every((k) => keys2.includes(k));
4117
+ function validOnboardingPostcondition(v) {
4118
+ 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;
4119
+ if (v.additionalChecks === void 0) return true;
4120
+ if (!Array.isArray(v.additionalChecks) || v.additionalChecks.length < 1 || v.additionalChecks.length > 20) return false;
4121
+ const seen = /* @__PURE__ */ new Set([JSON.stringify([v.className, v.targetId, v.expected.field])]);
4122
+ return v.additionalChecks.every((check) => {
4123
+ 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;
4124
+ const key = JSON.stringify([check.className, check.targetId ?? { from: check.targetFromCommit }, check.field]);
4125
+ if (seen.has(key)) return false;
4126
+ seen.add(key);
4127
+ return true;
4128
+ });
4129
+ }
4130
+ function validOnboardingObservations(spec, value, additional) {
4131
+ if (!scalar(value)) return false;
4132
+ const expected = spec.additionalChecks ?? [];
4133
+ if (!expected.length) return additional === void 0 || Array.isArray(additional) && additional.length === 0;
4134
+ return Array.isArray(additional) && additional.length === expected.length && expected.every((check, index) => {
4135
+ const observed = additional[index];
4136
+ 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);
4137
+ });
4138
+ }
4139
+
4140
+ // src/development-provider.ts
4141
+ var row = (v) => !!v && typeof v === "object" && !Array.isArray(v);
4142
+ var id2 = (v) => typeof v === "string" && v.length > 0 && v.length <= 500 && v.trim() === v && !/[\u0000-\u001f\u007f]/u.test(v);
4143
+ var keys = [
4144
+ "runId",
4145
+ "tenantId",
4146
+ "sandboxId",
4147
+ "buildId",
4148
+ "operatorPrincipalId",
4149
+ "providerId",
4150
+ "environment"
4151
+ ];
4152
+ var generation = (v) => typeof v === "string" && /^[A-Za-z0-9_-]{1,100}$/.test(v);
4153
+ function developmentPreparationOperationKey(runId, userId, generationId) {
4154
+ if (!id2(runId) || !id2(userId) || !generation(generationId))
4155
+ throw new Error("Exact development run, user and generation are required.");
4156
+ return `onboarding-development:${runId}:${encodeURIComponent(userId)}:${generationId}`;
4157
+ }
4158
+ function users(value) {
4159
+ if (!Array.isArray(value) || value.length > 1e4)
4160
+ throw new Error(
4161
+ "Development user handler must return at most 10000 canonical users."
4162
+ );
4163
+ const seen = /* @__PURE__ */ new Set();
4164
+ return value.map((v) => {
4165
+ if (!row(v) || !id2(v.id) || v.id.length > 200 || !id2(v.name) || v.email !== void 0 && !id2(v.email) || seen.has(v.id))
4166
+ throw new Error("Development users need unique canonical ids and names.");
4167
+ seen.add(v.id);
4168
+ return {
4169
+ id: v.id,
4170
+ name: v.name,
4171
+ ...v.email !== void 0 ? { email: v.email } : {}
4172
+ };
4173
+ });
4174
+ }
4175
+ function progress(value) {
4176
+ if (!row(value) || !["queued", "collecting", "importing", "ready", "failed"].includes(
4177
+ String(value.stage)
4178
+ ) || !(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(
4179
+ (k) => value[k] !== void 0 && (!Number.isSafeInteger(value[k]) || Number(value[k]) < 0)
4180
+ ))
4181
+ throw new Error("Development handler returned invalid reported progress.");
4182
+ return {
4183
+ stage: value.stage,
4184
+ subjectId: value.subjectId,
4185
+ environmentId: value.environmentId,
4186
+ ...value.setupRunId !== void 0 ? { setupRunId: value.setupRunId } : {},
4187
+ ...value.importIds !== void 0 ? { importIds: [...value.importIds] } : {},
4188
+ ...value.completedRecords !== void 0 ? { completedRecords: Number(value.completedRecords) } : {},
4189
+ ...value.totalRecords !== void 0 ? { totalRecords: Number(value.totalRecords) } : {}
4190
+ };
4191
+ }
4192
+ var DevelopmentProvider = class {
4193
+ binding;
4194
+ options;
4195
+ constructor(options) {
4196
+ if (!options || options.environment !== "dev" || ![options.runId, options.buildId, options.operatorPrincipalId].every(
4197
+ id2
4198
+ ) || [
4199
+ options.authorize,
4200
+ options.listUsers,
4201
+ options.createEnvironment,
4202
+ options.getProgress
4203
+ ].some((v) => typeof v !== "function"))
4204
+ throw new Error(
4205
+ "Explicit dev scope and all authorized product callbacks are required."
4206
+ );
4207
+ this.options = Object.freeze({ ...options });
4208
+ }
4209
+ registrationParams() {
4210
+ const { runId, buildId, operatorPrincipalId, environment } = this.options;
4211
+ const handlers = ["listUsers", "createEnvironment", "getProgress"];
4212
+ if (this.options.findUser) handlers.push("findUser");
4213
+ if (this.options.authorizeCustomerReadback && this.options.readCustomerPostcondition)
4214
+ handlers.push("readPostcondition");
4215
+ if (this.options.authorizeCustomerCollection && this.options.readCustomerCollection)
4216
+ handlers.push("readCollection");
4217
+ if (this.options.getIncrementalStatus) handlers.push("incrementalStatus");
4218
+ const postconditionVerifiers = this.options.authorizeCustomerReadback && this.options.readCustomerPostcondition ? this.options.postconditionVerifiers || [] : [];
4219
+ if (postconditionVerifiers.length > 100 || postconditionVerifiers.some(
4220
+ (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))
4221
+ ))
4222
+ throw new Error("Invalid product postcondition verifier catalog");
4223
+ return {
4224
+ runId,
4225
+ buildId,
4226
+ operatorPrincipalId,
4227
+ environment,
4228
+ handlers,
4229
+ postconditionVerifiers
4230
+ };
4231
+ }
4232
+ bind(value, sandboxId, providerId) {
4233
+ 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)
4234
+ throw new Error(
4235
+ "Development registration response does not match the owned dev scope."
4236
+ );
4237
+ const binding = Object.fromEntries(
4238
+ keys.map((k) => [k, value[k]])
4239
+ );
4240
+ this.binding = Object.freeze(binding);
4241
+ return this.binding;
4242
+ }
4243
+ get registration() {
4244
+ return this.binding;
4245
+ }
4246
+ unbind() {
4247
+ this.binding = void 0;
4248
+ }
4249
+ async invoke(value) {
4250
+ if (!this.binding || !row(value) || !row(value.context) || !keys.every(
4251
+ (k) => value.context && value.context[k] === this.binding[k]
4252
+ ) || ![
4253
+ "listUsers",
4254
+ "findUser",
4255
+ "createEnvironment",
4256
+ "getProgress",
4257
+ "readPostcondition",
4258
+ "readCollection",
4259
+ "incrementalStatus"
4260
+ ].includes(String(value.operation)))
4261
+ throw new Error(
4262
+ "Development invocation does not match the registered dev/operator scope."
4263
+ );
4264
+ const binding = this.binding;
4265
+ const context = Object.freeze({ ...binding });
4266
+ if (await this.options.authorize(context) === false)
4267
+ throw new Error("Development operator is not authorized.");
4268
+ const useLookup = value.operation !== "listUsers" && !!this.options.findUser;
4269
+ if (useLookup && !id2(value.userId)) throw new Error("A current selected user is required.");
4270
+ const selected = useLookup ? await this.options.findUser(context, value.userId) : void 0;
4271
+ if (useLookup && selected === void 0) throw new Error("Invalid selected user response.");
4272
+ const listed = useLookup ? users(selected === null ? [] : [selected]) : users(await this.options.listUsers(context));
4273
+ if (this.binding !== binding)
4274
+ throw new Error("Development registration changed during invocation.");
4275
+ if (value.operation === "listUsers") return listed;
4276
+ const user = listed.find((u) => u.id === value.userId);
4277
+ if (value.operation === "findUser") return user ?? null;
4278
+ if (value.operation === "incrementalStatus") {
4279
+ if (!user || !this.options.getIncrementalStatus) throw new Error("Incremental status is unavailable");
4280
+ const result2 = await this.options.getIncrementalStatus(context, user.id);
4281
+ if (this.binding !== binding || await this.options.authorize(context) === false) throw new Error("Development authorization changed during incremental status");
4282
+ if (!Array.isArray(result2) || result2.length > 100) throw new Error("Invalid incremental status");
4283
+ const seen = /* @__PURE__ */ new Set();
4284
+ for (const item of result2) {
4285
+ 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");
4286
+ seen.add(String(item.classId));
4287
+ }
4288
+ return result2.map((item) => ({ ...item }));
4289
+ }
4290
+ if (value.operation === "readCollection") {
4291
+ const input2 = value.readback;
4292
+ 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)))
4293
+ throw new Error("Invalid customer collection binding");
4294
+ if (!this.options.authorizeCustomerCollection || !this.options.readCustomerCollection) return { status: "unavailable" };
4295
+ const collection = Object.freeze(structuredClone(input2));
4296
+ if (await this.options.authorizeCustomerCollection(collection, context) !== true) throw new Error("Customer collection is not authorized");
4297
+ const result2 = await this.options.readCustomerCollection(collection, context);
4298
+ if (this.binding !== binding || await this.options.authorizeCustomerCollection(collection, context) !== true)
4299
+ throw new Error("Customer binding changed during collection receipt read");
4300
+ if (result2.status === "unavailable") return result2;
4301
+ 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))
4302
+ throw new Error("Invalid product collection receipt");
4303
+ return { status: "complete", classCounts: { ...result2.classCounts } };
4304
+ }
4305
+ if (value.operation === "readPostcondition") {
4306
+ const input2 = value.readback;
4307
+ if (!user || !row(input2) || input2.identityId !== user.id || ![
4308
+ "requestId",
4309
+ "invocationId",
4310
+ "sessionId",
4311
+ "jobId",
4312
+ "subjectId",
4313
+ "environmentId",
4314
+ "identityId",
4315
+ "effectKey"
4316
+ ].every((k) => id2(input2[k])) || !validOnboardingPostcondition(input2.postcondition))
4317
+ throw new Error("Invalid customer postcondition readback binding");
4318
+ if (!this.options.authorizeCustomerReadback || !this.options.readCustomerPostcondition)
4319
+ return { status: "unavailable" };
4320
+ const spec = input2.postcondition;
4321
+ const checks = [{ className: spec.className, field: spec.expected.field }, ...spec.additionalChecks ?? []];
4322
+ 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))))
4323
+ return { status: "unavailable" };
4324
+ const copy = structuredClone(input2);
4325
+ Object.freeze(copy.postcondition.expected);
4326
+ if (copy.postcondition.additionalChecks) {
4327
+ copy.postcondition.additionalChecks.forEach(Object.freeze);
4328
+ Object.freeze(copy.postcondition.additionalChecks);
4329
+ }
4330
+ Object.freeze(copy.postcondition);
4331
+ const readback = Object.freeze(copy);
4332
+ if (await this.options.authorizeCustomerReadback(readback, context) !== true)
4333
+ throw new Error("Customer product readback is not authorized");
4334
+ const result2 = await this.options.readCustomerPostcondition(
4335
+ readback,
4336
+ context
4337
+ );
4338
+ if (this.binding !== binding || await this.options.authorizeCustomerReadback(readback, context) !== true)
4339
+ throw new Error("Customer binding changed during product readback");
4340
+ if (!row(result2) || result2.status !== "unavailable" && (result2.status !== "observed" || !validOnboardingObservations(spec, result2.value, result2.additional)))
4341
+ throw new Error("Invalid product readback result");
4342
+ return result2.status === "observed" ? { status: "observed", value: result2.value, ...result2.additional ? { additional: result2.additional } : {} } : { status: "unavailable" };
4343
+ }
4344
+ if (!user || !generation(value.generationId) || value.operationKey !== developmentPreparationOperationKey(
4345
+ context.runId,
4346
+ user.id,
4347
+ value.generationId
4348
+ ))
4349
+ throw new Error(
4350
+ "Selected development user or generation is not current."
4351
+ );
4352
+ const input = {
4353
+ context,
4354
+ user: Object.freeze(user),
4355
+ operationKey: value.operationKey,
4356
+ generationId: value.generationId
4357
+ };
4358
+ const result = await (value.operation === "createEnvironment" ? this.options.createEnvironment(input) : this.options.getProgress(input));
4359
+ if (this.binding !== binding)
4360
+ throw new Error("Development registration changed during invocation.");
4361
+ return progress(result);
4362
+ }
4363
+ };
4364
+
4024
4365
  // ../../node_modules/zod/v3/external.js
4025
4366
  var external_exports = {};
4026
4367
  __export(external_exports, {
@@ -4165,14 +4506,14 @@ var util;
4165
4506
  return obj[e];
4166
4507
  });
4167
4508
  };
4168
- util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => {
4169
- const keys = [];
4170
- for (const key in object) {
4171
- if (Object.prototype.hasOwnProperty.call(object, key)) {
4172
- keys.push(key);
4509
+ util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object2) => {
4510
+ const keys2 = [];
4511
+ for (const key in object2) {
4512
+ if (Object.prototype.hasOwnProperty.call(object2, key)) {
4513
+ keys2.push(key);
4173
4514
  }
4174
4515
  }
4175
- return keys;
4516
+ return keys2;
4176
4517
  };
4177
4518
  util2.find = (arr, checker) => {
4178
4519
  for (const item of arr) {
@@ -6400,8 +6741,8 @@ var ZodObject = class _ZodObject extends ZodType {
6400
6741
  if (this._cached !== null)
6401
6742
  return this._cached;
6402
6743
  const shape = this._def.shape();
6403
- const keys = util.objectKeys(shape);
6404
- this._cached = { shape, keys };
6744
+ const keys2 = util.objectKeys(shape);
6745
+ this._cached = { shape, keys: keys2 };
6405
6746
  return this._cached;
6406
6747
  }
6407
6748
  _parse(input) {
@@ -8764,8 +9105,8 @@ function isArtifactWorkflowNodeActionable(node) {
8764
9105
  );
8765
9106
  }
8766
9107
  function getArtifactWorkflowNodes(workflow) {
8767
- const visit = (id) => {
8768
- const node = workflow.nodesById[id];
9108
+ const visit = (id3) => {
9109
+ const node = workflow.nodesById[id3];
8769
9110
  return node ? [node, ...node.childIds.flatMap(visit)] : [];
8770
9111
  };
8771
9112
  return workflow.rootNodeIds.flatMap(visit);
@@ -8779,22 +9120,22 @@ function assertArtifactWorkflow(workflow) {
8779
9120
  const visited = /* @__PURE__ */ new Set();
8780
9121
  const visiting = /* @__PURE__ */ new Set();
8781
9122
  const nodes = [];
8782
- const visit = (id, expectedParentId) => {
8783
- const node = workflow.nodesById[id];
8784
- if (!node) throw new Error(`Artifact workflow node ${id} does not exist`);
8785
- if (visiting.has(id)) throw new Error("Artifact workflow contains a cycle");
8786
- if (visited.has(id))
9123
+ const visit = (id3, expectedParentId) => {
9124
+ const node = workflow.nodesById[id3];
9125
+ if (!node) throw new Error(`Artifact workflow node ${id3} does not exist`);
9126
+ if (visiting.has(id3)) throw new Error("Artifact workflow contains a cycle");
9127
+ if (visited.has(id3))
8787
9128
  throw new Error("Artifact workflow contains a duplicate node reference");
8788
9129
  if (node.parentId !== expectedParentId) {
8789
- throw new Error(`Artifact workflow node ${id} has an invalid parent`);
9130
+ throw new Error(`Artifact workflow node ${id3} has an invalid parent`);
8790
9131
  }
8791
- visiting.add(id);
9132
+ visiting.add(id3);
8792
9133
  nodes.push(node);
8793
- node.childIds.forEach((childId) => visit(childId, id));
8794
- visiting.delete(id);
8795
- visited.add(id);
9134
+ node.childIds.forEach((childId) => visit(childId, id3));
9135
+ visiting.delete(id3);
9136
+ visited.add(id3);
8796
9137
  };
8797
- workflow.rootNodeIds.forEach((id) => visit(id, null));
9138
+ workflow.rootNodeIds.forEach((id3) => visit(id3, null));
8798
9139
  if (visited.size !== Object.keys(workflow.nodesById).length) {
8799
9140
  throw new Error("Artifact workflow contains unreachable nodes");
8800
9141
  }
@@ -8898,12 +9239,12 @@ function toRecordSearchResult(className, node) {
8898
9239
  const realIdField = fields.find(
8899
9240
  (field) => normalizeGraphPathSegment(field.name) === "real_id" && typeof field.value === "string" && field.value.trim()
8900
9241
  );
8901
- const id = typeof realIdField?.value === "string" ? realIdField.value.trim() : graphPathId;
8902
- const label = typeof node.label === "string" && node.label.trim() ? node.label.trim() : path2 || id;
9242
+ const id3 = typeof realIdField?.value === "string" ? realIdField.value.trim() : graphPathId;
9243
+ const label = typeof node.label === "string" && node.label.trim() ? node.label.trim() : path2 || id3;
8903
9244
  return {
8904
9245
  path: path2,
8905
9246
  className,
8906
- id,
9247
+ id: id3,
8907
9248
  label,
8908
9249
  description: typeof node.description === "string" && node.description.trim() ? node.description : null,
8909
9250
  fields
@@ -8918,12 +9259,12 @@ function rankRecordSearchResult(result, query, index) {
8918
9259
  return index;
8919
9260
  }
8920
9261
  const label = normalizeRecordSearchText(result.label || "");
8921
- const id = normalizeRecordSearchText(result.id || "");
9262
+ const id3 = normalizeRecordSearchText(result.id || "");
8922
9263
  const path2 = normalizeRecordSearchText(result.path || "");
8923
9264
  const className = normalizeRecordSearchText(result.className || "");
8924
- const searchable = [label, id, path2, className].filter(Boolean);
9265
+ const searchable = [label, id3, path2, className].filter(Boolean);
8925
9266
  if (label === normalizedQuery) return index;
8926
- if (id === normalizedQuery || path2 === normalizedQuery) return 100 + index;
9267
+ if (id3 === normalizedQuery || path2 === normalizedQuery) return 100 + index;
8927
9268
  if (label.startsWith(normalizedQuery)) return 200 + index;
8928
9269
  if (searchable.some((value) => value.startsWith(normalizedQuery))) {
8929
9270
  return 300 + index;
@@ -9577,22 +9918,22 @@ function orderTransientFeedItems(items) {
9577
9918
  const ordinalById = /* @__PURE__ */ new Map();
9578
9919
  const idByOrdinal = /* @__PURE__ */ new Map();
9579
9920
  for (const item of items) {
9580
- const id = String(item.id || "");
9921
+ const id3 = String(item.id || "");
9581
9922
  const ordinal = requirePositiveFeedPosition(item.ordinal);
9582
- const knownOrdinal = ordinalById.get(id);
9923
+ const knownOrdinal = ordinalById.get(id3);
9583
9924
  const ordinalOwner = idByOrdinal.get(ordinal);
9584
- if (!id || knownOrdinal !== void 0 && knownOrdinal !== ordinal || ordinalOwner && ordinalOwner !== id) {
9925
+ if (!id3 || knownOrdinal !== void 0 && knownOrdinal !== ordinal || ordinalOwner && ordinalOwner !== id3) {
9585
9926
  throw new Error("Invalid feed chronology.");
9586
9927
  }
9587
- ordinalById.set(id, ordinal);
9588
- idByOrdinal.set(ordinal, id);
9589
- const existing = byId.get(id);
9928
+ ordinalById.set(id3, ordinal);
9929
+ idByOrdinal.set(ordinal, id3);
9930
+ const existing = byId.get(id3);
9590
9931
  if (existing && item.revision === existing.revision && stableValueFingerprint(item) !== stableValueFingerprint(existing)) {
9591
9932
  throw new Error(
9592
9933
  "Invalid feed chronology: conflicting transient revision."
9593
9934
  );
9594
9935
  }
9595
- if (!existing || item.revision > existing.revision) byId.set(id, item);
9936
+ if (!existing || item.revision > existing.revision) byId.set(id3, item);
9596
9937
  }
9597
9938
  return [...byId.values()].sort((left, right) => left.ordinal - right.ordinal);
9598
9939
  }
@@ -9646,21 +9987,21 @@ function cloneAndFreeze(value, seen = /* @__PURE__ */ new WeakMap()) {
9646
9987
  if (!value || typeof value !== "object") {
9647
9988
  return value;
9648
9989
  }
9649
- const object = value;
9650
- const cached = seen.get(object);
9990
+ const object2 = value;
9991
+ const cached = seen.get(object2);
9651
9992
  if (cached) {
9652
9993
  return cached;
9653
9994
  }
9654
9995
  if (Array.isArray(value)) {
9655
9996
  const result2 = [];
9656
- seen.set(object, result2);
9997
+ seen.set(object2, result2);
9657
9998
  for (const entry of value) {
9658
9999
  result2.push(cloneAndFreeze(entry, seen));
9659
10000
  }
9660
10001
  return Object.freeze(result2);
9661
10002
  }
9662
10003
  const result = /* @__PURE__ */ Object.create(null);
9663
- seen.set(object, result);
10004
+ seen.set(object2, result);
9664
10005
  for (const [key, entry] of Object.entries(value)) {
9665
10006
  result[key] = cloneAndFreeze(entry, seen);
9666
10007
  }
@@ -10565,9 +10906,9 @@ var SessionFeedController = class {
10565
10906
  targetSequence,
10566
10907
  repairAvailable: true
10567
10908
  });
10568
- const generation = ++this.repairGeneration;
10569
- this.repairPromise = this.repair(targetSequence, generation).finally(() => {
10570
- if (generation === this.repairGeneration) {
10909
+ const generation2 = ++this.repairGeneration;
10910
+ this.repairPromise = this.repair(targetSequence, generation2).finally(() => {
10911
+ if (generation2 === this.repairGeneration) {
10571
10912
  this.repairPromise = null;
10572
10913
  if (this.deliveredThrough < this.snapshot.lastSequence) {
10573
10914
  if (this.snapshot.error) {
@@ -10615,13 +10956,13 @@ var SessionFeedController = class {
10615
10956
  }, delayMs);
10616
10957
  this.repairRetryHandle = handle;
10617
10958
  }
10618
- async repair(targetSequence, generation) {
10959
+ async repair(targetSequence, generation2) {
10619
10960
  const startedAt = this.diagnosticNow();
10620
10961
  let pageCount = 0;
10621
10962
  let outcome = "success";
10622
10963
  try {
10623
10964
  let attempts = 0;
10624
- while (generation === this.repairGeneration && this.deliveredThrough < targetSequence) {
10965
+ while (generation2 === this.repairGeneration && this.deliveredThrough < targetSequence) {
10625
10966
  if (++attempts > 100) {
10626
10967
  throw new Error("Feed gap repair exceeded its page limit.");
10627
10968
  }
@@ -10630,7 +10971,7 @@ var SessionFeedController = class {
10630
10971
  limit: 500
10631
10972
  });
10632
10973
  pageCount += 1;
10633
- if (generation !== this.repairGeneration) {
10974
+ if (generation2 !== this.repairGeneration) {
10634
10975
  outcome = "cancelled";
10635
10976
  return;
10636
10977
  }
@@ -10664,12 +11005,12 @@ var SessionFeedController = class {
10664
11005
  );
10665
11006
  }
10666
11007
  }
10667
- if (generation !== this.repairGeneration) {
11008
+ if (generation2 !== this.repairGeneration) {
10668
11009
  outcome = "cancelled";
10669
11010
  return;
10670
11011
  }
10671
11012
  } catch (error) {
10672
- if (generation !== this.repairGeneration) {
11013
+ if (generation2 !== this.repairGeneration) {
10673
11014
  outcome = "cancelled";
10674
11015
  return;
10675
11016
  }
@@ -11893,10 +12234,10 @@ function buildPolicyMutations(effectKey, spec) {
11893
12234
  rules.forEach((rule, index) => {
11894
12235
  const condition = normalizeCondition(rule.when);
11895
12236
  const summary = rule.reason || summarizeCondition(condition);
11896
- const id = rule.id || `${effectKey}:${outcome}:${index + 1}`;
12237
+ const id3 = rule.id || `${effectKey}:${outcome}:${index + 1}`;
11897
12238
  mutations.push({
11898
12239
  label: `set policy ${outcome} on ${effectKey}`,
11899
- 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))}) }`
12240
+ 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))}) }`
11900
12241
  });
11901
12242
  });
11902
12243
  };
@@ -13090,8 +13431,8 @@ function normalizePrompt(rawValue) {
13090
13431
  if (!raw) return null;
13091
13432
  const promptRecord = asRecord2(raw.prompt);
13092
13433
  const source = promptRecord || raw;
13093
- const id = typeof source.id === "string" ? source.id : typeof raw.id === "string" ? raw.id : typeof raw.promptId === "string" ? raw.promptId : "";
13094
- if (!id) return null;
13434
+ const id3 = typeof source.id === "string" ? source.id : typeof raw.id === "string" ? raw.id : typeof raw.promptId === "string" ? raw.promptId : "";
13435
+ if (!id3) return null;
13095
13436
  const jobId = typeof source.jobId === "string" && source.jobId.trim() ? source.jobId.trim() : typeof raw.jobId === "string" && raw.jobId.trim() ? raw.jobId.trim() : void 0;
13096
13437
  const turnId = typeof source.turnId === "string" && source.turnId.trim() ? source.turnId.trim() : typeof raw.turnId === "string" && raw.turnId.trim() ? raw.turnId.trim() : void 0;
13097
13438
  const type = normalizePromptType(
@@ -13099,7 +13440,7 @@ function normalizePrompt(rawValue) {
13099
13440
  );
13100
13441
  if (!type) return null;
13101
13442
  return {
13102
- id,
13443
+ id: id3,
13103
13444
  ...jobId ? { jobId } : {},
13104
13445
  ...turnId ? { turnId } : {},
13105
13446
  type,
@@ -13568,8 +13909,8 @@ var Session = class {
13568
13909
  input.operationId,
13569
13910
  "operationId"
13570
13911
  );
13571
- const id = requestedId || (requestedOperationId ? void 0 : reserveUserMessageId());
13572
- const operationId2 = requestedOperationId || `conversation.append:${id}`;
13912
+ const id3 = requestedId || (requestedOperationId ? void 0 : reserveUserMessageId());
13913
+ const operationId2 = requestedOperationId || `conversation.append:${id3}`;
13573
13914
  const {
13574
13915
  id: _ignoredInputId,
13575
13916
  operationId: _ignoredInputOperationId,
@@ -13578,7 +13919,7 @@ var Session = class {
13578
13919
  return this.client.call("conversation.append", {
13579
13920
  ...message,
13580
13921
  role: "user",
13581
- ...id ? { id } : {},
13922
+ ...id3 ? { id: id3 } : {},
13582
13923
  operationId: operationId2
13583
13924
  });
13584
13925
  }
@@ -13778,6 +14119,43 @@ var Session = class {
13778
14119
  }
13779
14120
  return summary;
13780
14121
  }
14122
+ /** Hosted-harness module context for an external subject agent. */
14123
+ async getHarnessContext() {
14124
+ return this.client.call("domain.getHarnessContext", {});
14125
+ }
14126
+ /** Submit external agent code through the hosted harness import preparation. */
14127
+ async submitSubjectJob(code, options = {}) {
14128
+ const result = await this.client.call("job.submitSubject", {
14129
+ code,
14130
+ domainRevision: options.domainRevision,
14131
+ metadata: options.metadata
14132
+ });
14133
+ if (result.rejected) {
14134
+ const error = new Error(result.rejected.message);
14135
+ error.code = result.rejected.code;
14136
+ throw error;
14137
+ }
14138
+ if (!result.jobId) throw new Error("Failed to submit subject job: no jobId returned");
14139
+ const job = new JobImplementation(result.jobId, this.client, {
14140
+ code,
14141
+ domainRevision: options.domainRevision || this.currentDomainRevision || "",
14142
+ createdAt: Date.now()
14143
+ });
14144
+ this.jobsMap.set(result.jobId, job);
14145
+ job.reconcileCanonicalState(
14146
+ this.client.doc?.jobs?.byId?.[result.jobId]
14147
+ );
14148
+ return job;
14149
+ }
14150
+ /** A canonical job read also reconciles a handle whose terminal event was missed. */
14151
+ reconcileCanonicalJobRead(jobId, record) {
14152
+ this.jobsMap.get(jobId)?.reconcileCanonicalState(record);
14153
+ }
14154
+ rejectTerminalJobRead(jobId, error) {
14155
+ if (error?.code === "SUBJECT_SESSION_ENDED") {
14156
+ this.jobsMap.get(jobId)?.rejectResultAccess(error);
14157
+ }
14158
+ }
13781
14159
  /**
13782
14160
  * Fetch a domain package part from the backend (no fallback).
13783
14161
  */
@@ -14109,8 +14487,11 @@ import { ${tools[0]?.name || "example"} } from "@granular/actions/backend";
14109
14487
  this.emit("prompt:answered", { ...prompt, status: "answered" });
14110
14488
  return;
14111
14489
  }
14490
+ const previous = this.promptCache.get(prompt.id);
14112
14491
  this.promptCache.set(prompt.id, prompt);
14113
- this.emit("prompt", prompt);
14492
+ if (!previous || promptSnapshotFingerprint(previous) !== promptSnapshotFingerprint(prompt)) {
14493
+ this.emit("prompt", prompt);
14494
+ }
14114
14495
  };
14115
14496
  this.client.on("prompt", emitPrompt);
14116
14497
  this.client.on("prompt.request", emitPrompt);
@@ -14268,8 +14649,8 @@ var JobImplementation = class {
14268
14649
  eventListeners = /* @__PURE__ */ new Map();
14269
14650
  resultSettled = false;
14270
14651
  metadata;
14271
- constructor(id, client, initialState) {
14272
- this.id = id;
14652
+ constructor(id3, client, initialState) {
14653
+ this.id = id3;
14273
14654
  this.client = client;
14274
14655
  this.metadata = {
14275
14656
  source: "sdk",
@@ -14287,7 +14668,7 @@ var JobImplementation = class {
14287
14668
  });
14288
14669
  this.client.on("exec.completed", (data) => {
14289
14670
  const execData = data;
14290
- if (execData.execId === id || execData.jobId === id) {
14671
+ if (execData.execId === id3 || execData.jobId === id3) {
14291
14672
  if (execData.error) {
14292
14673
  this.finalize("failed", void 0, execData.error);
14293
14674
  } else {
@@ -14300,7 +14681,7 @@ var JobImplementation = class {
14300
14681
  });
14301
14682
  this.client.on("exec.progress", (data) => {
14302
14683
  const progressData = data;
14303
- if (progressData.execId === id || progressData.jobId === id) {
14684
+ if (progressData.execId === id3 || progressData.jobId === id3) {
14304
14685
  if (progressData.stdout) {
14305
14686
  this.markStarted();
14306
14687
  this.metadata.stdout = [
@@ -14319,7 +14700,7 @@ var JobImplementation = class {
14319
14700
  }
14320
14701
  }
14321
14702
  });
14322
- this.client.on(`job.${id}.status`, (status) => {
14703
+ this.client.on(`job.${id3}.status`, (status) => {
14323
14704
  const normalizedStatus = normalizeJobStatus(status);
14324
14705
  this.status = normalizedStatus;
14325
14706
  this.metadata.status = normalizedStatus;
@@ -14331,7 +14712,7 @@ var JobImplementation = class {
14331
14712
  }
14332
14713
  this.emit("status", normalizedStatus);
14333
14714
  });
14334
- this.client.on(`job.${id}.stdout`, (line) => {
14715
+ this.client.on(`job.${id3}.stdout`, (line) => {
14335
14716
  this.markStarted();
14336
14717
  this.metadata.stdout = [
14337
14718
  ...this.metadata.stdout,
@@ -14339,7 +14720,7 @@ var JobImplementation = class {
14339
14720
  ].slice(-100);
14340
14721
  this.emit("stdout", line);
14341
14722
  });
14342
- this.client.on(`job.${id}.stderr`, (line) => {
14723
+ this.client.on(`job.${id3}.stderr`, (line) => {
14343
14724
  this.markStarted();
14344
14725
  this.metadata.stderr = [
14345
14726
  ...this.metadata.stderr,
@@ -14347,15 +14728,15 @@ var JobImplementation = class {
14347
14728
  ].slice(-100);
14348
14729
  this.emit("stderr", line);
14349
14730
  });
14350
- this.client.on(`job.${id}.result`, (result) => {
14731
+ this.client.on(`job.${id3}.result`, (result) => {
14351
14732
  this.finalize("succeeded", result, void 0, { hasResult: true });
14352
14733
  });
14353
- this.client.on(`job.${id}.error`, (error) => {
14734
+ this.client.on(`job.${id3}.error`, (error) => {
14354
14735
  this.finalize("failed", void 0, error);
14355
14736
  });
14356
14737
  this.client.on("job.status", (data) => {
14357
14738
  const jobData = data;
14358
- if (jobData.jobId !== id) {
14739
+ if (jobData.jobId !== id3) {
14359
14740
  return;
14360
14741
  }
14361
14742
  const normalizedStatus = normalizeJobStatus(jobData.status);
@@ -14368,7 +14749,7 @@ var JobImplementation = class {
14368
14749
  });
14369
14750
  this.client.on("job.completed", (data) => {
14370
14751
  const jobData = data;
14371
- if (jobData.jobId === id) {
14752
+ if (jobData.jobId === id3) {
14372
14753
  this.finalize("succeeded", jobData.result, void 0, {
14373
14754
  hasResult: true
14374
14755
  });
@@ -14377,7 +14758,7 @@ var JobImplementation = class {
14377
14758
  });
14378
14759
  this.client.on("job.failed", (data) => {
14379
14760
  const jobData = data;
14380
- if (jobData.jobId === id) {
14761
+ if (jobData.jobId === id3) {
14381
14762
  this.finalize(
14382
14763
  "failed",
14383
14764
  void 0,
@@ -14388,7 +14769,7 @@ var JobImplementation = class {
14388
14769
  });
14389
14770
  this.client.on("tool.call.start", (data) => {
14390
14771
  const d = data;
14391
- if (d.jobId === id) {
14772
+ if (d.jobId === id3) {
14392
14773
  this.metadata.toolCalls = this.upsertToolCall({
14393
14774
  callId: d.callId,
14394
14775
  toolName: d.toolName,
@@ -14405,7 +14786,7 @@ var JobImplementation = class {
14405
14786
  });
14406
14787
  this.client.on("tool.call.end", (data) => {
14407
14788
  const d = data;
14408
- if (d.jobId === id) {
14789
+ if (d.jobId === id3) {
14409
14790
  const completedAt = d.timestamp || Date.now();
14410
14791
  this.metadata.toolCalls = this.upsertToolCall({
14411
14792
  callId: d.callId,
@@ -14426,6 +14807,23 @@ var JobImplementation = class {
14426
14807
  }
14427
14808
  });
14428
14809
  }
14810
+ rejectResultAccess(error) {
14811
+ if (this.resultSettled) return;
14812
+ this.resultSettled = true;
14813
+ this._rejectResult(error);
14814
+ }
14815
+ reconcileCanonicalState(record) {
14816
+ if (this.resultSettled) return;
14817
+ const value = recordFromUnknown(record);
14818
+ if (!value || value.jobId !== this.id) return;
14819
+ const status = normalizeJobStatus(value.status);
14820
+ if (status === "succeeded") {
14821
+ this.finalize(status, value.result, void 0, { hasResult: true });
14822
+ } else if (status === "failed" || status === "timeout" || status === "canceled") {
14823
+ this.finalize(status, void 0, value.error);
14824
+ } else return;
14825
+ this.emit("status", this.status);
14826
+ }
14429
14827
  get result() {
14430
14828
  return this._resultPromise;
14431
14829
  }
@@ -14650,7 +15048,7 @@ function artifactSummaryLine(artifactId, record) {
14650
15048
  const target = asRecord3(record.target);
14651
15049
  const metadata = asRecord3(record.metadata) || {};
14652
15050
  const subArtifactIds = Array.isArray(record.subArtifactIds) ? record.subArtifactIds.filter(
14653
- (id) => typeof id === "string" && id.trim().length > 0
15051
+ (id3) => typeof id3 === "string" && id3.trim().length > 0
14654
15052
  ).slice(0, 8) : [];
14655
15053
  const relationships = compactJson(record.relationships, 220);
14656
15054
  const pieces = [
@@ -15081,9 +15479,9 @@ var WSClient = class {
15081
15479
  hasRecentlyPendingRpcPeriod(maxAgeMs, now = Date.now()) {
15082
15480
  return this.messageQueue.length > 0 && this.pendingRpcPeriodStartedAt !== null && now - this.pendingRpcPeriodStartedAt <= maxAgeMs;
15083
15481
  }
15084
- removePendingRpc(id) {
15482
+ removePendingRpc(id3) {
15085
15483
  this.messageQueue = this.messageQueue.filter(
15086
- (pending) => pending.id !== id
15484
+ (pending) => pending.id !== id3
15087
15485
  );
15088
15486
  if (this.messageQueue.length === 0) this.pendingRpcPeriodStartedAt = null;
15089
15487
  }
@@ -15922,19 +16320,19 @@ var WSClient = class {
15922
16320
  if (!this.ws || this.ws.readyState !== READY_STATE_OPEN) {
15923
16321
  throw new Error("WebSocket not connected");
15924
16322
  }
15925
- const id = `rpc-${this.nextRpcId++}`;
16323
+ const id3 = `rpc-${this.nextRpcId++}`;
15926
16324
  const request = {
15927
16325
  type: "rpc",
15928
16326
  method,
15929
16327
  params,
15930
- id
16328
+ id: id3
15931
16329
  };
15932
16330
  return new Promise((resolve, reject) => {
15933
16331
  const timeoutMs = rpcTimeoutMsForMethod(method);
15934
16332
  const timeout = setTimeout(() => {
15935
- const pending = this.messageQueue.find((q) => q.id === id);
16333
+ const pending = this.messageQueue.find((q) => q.id === id3);
15936
16334
  if (pending) {
15937
- this.removePendingRpc(id);
16335
+ this.removePendingRpc(id3);
15938
16336
  reject(new Error(`RPC timeout: ${method}`));
15939
16337
  }
15940
16338
  }, timeoutMs);
@@ -15944,14 +16342,14 @@ var WSClient = class {
15944
16342
  this.messageQueue.push({
15945
16343
  resolve,
15946
16344
  reject,
15947
- id,
16345
+ id: id3,
15948
16346
  timeout
15949
16347
  });
15950
16348
  try {
15951
16349
  this.ws.send(JSON.stringify(request));
15952
16350
  } catch (error) {
15953
16351
  clearTimeout(timeout);
15954
- this.removePendingRpc(id);
16352
+ this.removePendingRpc(id3);
15955
16353
  reject(error instanceof Error ? error : new Error(String(error)));
15956
16354
  }
15957
16355
  });
@@ -16072,6 +16470,45 @@ var WSClient = class {
16072
16470
  }
16073
16471
  };
16074
16472
 
16473
+ // src/events-feed.ts
16474
+ var EventsFeed = class {
16475
+ constructor(request) {
16476
+ this.request = request;
16477
+ }
16478
+ list(filter = {}) {
16479
+ return this.request(`/control/events-feed/problems${eventsFeedSearch(filter)}`);
16480
+ }
16481
+ get(problemId, filter = {}) {
16482
+ return this.request(`/control/events-feed/problems/${encodeURIComponent(problemId)}${eventsFeedSearch(filter)}`);
16483
+ }
16484
+ update(problemId, input) {
16485
+ return this.request(`/control/events-feed/problems/${encodeURIComponent(problemId)}`, {
16486
+ method: "PATCH",
16487
+ body: JSON.stringify(input)
16488
+ });
16489
+ }
16490
+ metrics(filter = {}) {
16491
+ return this.request(`/control/events-feed/metrics${eventsFeedSearch(filter)}`);
16492
+ }
16493
+ health() {
16494
+ return this.request("/control/events-feed/health");
16495
+ }
16496
+ /** Sends SQL and positional parameters unchanged. The server enforces read-only tenant scope. */
16497
+ query(input) {
16498
+ return this.request("/control/events-feed/query", {
16499
+ method: "POST",
16500
+ body: JSON.stringify(input)
16501
+ });
16502
+ }
16503
+ };
16504
+ function eventsFeedSearch(filter) {
16505
+ const search = new URLSearchParams();
16506
+ for (const [key, value] of Object.entries(filter)) {
16507
+ if (value !== void 0) search.set(key, String(value));
16508
+ }
16509
+ return search.size ? `?${search.toString()}` : "";
16510
+ }
16511
+
16075
16512
  // src/client.ts
16076
16513
  var DEFAULT_CONVERSATION_SESSION_LIST_LIMIT = 100;
16077
16514
  var MAX_CONVERSATION_SESSION_LIST_LIMIT = 500;
@@ -16263,7 +16700,7 @@ function computeEffectRegistrationKey(effect) {
16263
16700
  function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId, effectHostUrl) {
16264
16701
  const overrideUrl = effectHostUrl || process.env.GRANULAR_EFFECT_HOST_URL || process.env.EFFECT_HOST_URL;
16265
16702
  const api = new URL(apiUrl);
16266
- const localRuntimeBase = process.env.RUNTIME_ORCHESTRATOR_URL || "";
16703
+ const localRuntimeBase = isLocalControlUrl(apiUrl) && api.port === "8787" ? "" : process.env.RUNTIME_ORCHESTRATOR_URL || "";
16267
16704
  const url = new URL(overrideUrl || localRuntimeBase || apiUrl);
16268
16705
  if (url.protocol === "https:") {
16269
16706
  url.protocol = "wss:";
@@ -16965,8 +17402,8 @@ var Environment = class _Environment {
16965
17402
  * Keep the original customer/system ID in `real_id`; graph paths are stable
16966
17403
  * internal addresses, not the source of truth for business identity.
16967
17404
  */
16968
- static toGraphPath(className, id) {
16969
- return `${_Environment.normalizeGraphPathSegment(className)}_${_Environment.normalizeGraphPathSegment(id)}`;
17405
+ static toGraphPath(className, id3) {
17406
+ return `${_Environment.normalizeGraphPathSegment(className)}_${_Environment.normalizeGraphPathSegment(id3)}`;
16970
17407
  }
16971
17408
  /**
16972
17409
  * Best-effort extraction of an ID-like suffix from a graph path.
@@ -18078,6 +18515,14 @@ var EnvironmentSession = class extends Session {
18078
18515
  const error = new Error(
18079
18516
  `Session data API Error (${response.status}): ${errorText}`
18080
18517
  );
18518
+ if (response.status === 403) {
18519
+ try {
18520
+ if (JSON.parse(errorText)?.error === "SUBJECT_SESSION_ENDED") {
18521
+ error.code = "SUBJECT_SESSION_ENDED";
18522
+ }
18523
+ } catch {
18524
+ }
18525
+ }
18081
18526
  if (isLocalControlUrl(url) && isRetryableSessionDataError(error) && attempt < SESSION_DATA_REQUEST_RETRY_COUNT) {
18082
18527
  await sleep(SESSION_DATA_REQUEST_RETRY_DELAY_MS * attempt);
18083
18528
  continue;
@@ -18127,7 +18572,7 @@ var EnvironmentSession = class extends Session {
18127
18572
  "Assistant replies require a server API-key session connection."
18128
18573
  );
18129
18574
  }
18130
- const id = requiredAssistantReplyString(input.id, "id");
18575
+ const id3 = requiredAssistantReplyString(input.id, "id");
18131
18576
  const operationId2 = requiredAssistantReplyString(
18132
18577
  input.operationId,
18133
18578
  "operationId"
@@ -18138,7 +18583,7 @@ var EnvironmentSession = class extends Session {
18138
18583
  void 0,
18139
18584
  {
18140
18585
  method: "POST",
18141
- body: { id, operationId: operationId2, text }
18586
+ body: { id: id3, operationId: operationId2, text }
18142
18587
  }
18143
18588
  );
18144
18589
  }
@@ -18153,9 +18598,18 @@ var EnvironmentSession = class extends Session {
18153
18598
  "/jobs",
18154
18599
  options
18155
18600
  ),
18156
- get: (jobId) => this.sessionDataRequest(
18157
- `/jobs/${encodeURIComponent(jobId)}`
18158
- ),
18601
+ get: async (jobId) => {
18602
+ try {
18603
+ const record = await this.sessionDataRequest(
18604
+ `/jobs/${encodeURIComponent(jobId)}`
18605
+ );
18606
+ this.reconcileCanonicalJobRead(jobId, record);
18607
+ return record;
18608
+ } catch (error) {
18609
+ this.rejectTerminalJobRead(jobId, error);
18610
+ throw error;
18611
+ }
18612
+ },
18159
18613
  latest: async (options = {}) => {
18160
18614
  const page = await this.sessionDataRequest("/jobs", {
18161
18615
  status: options.status || "all",
@@ -18578,8 +19032,22 @@ var OntologyHandle = class {
18578
19032
  disconnect: async () => this.granular.disconnectEffects(this.ontologyNameOrId)
18579
19033
  };
18580
19034
  }
19035
+ /** Register the product-owned user directory on the existing SDK connection. */
19036
+ register_users(handler, options) {
19037
+ return this.granular.registerUsers(this.ontologyNameOrId, handler, options);
19038
+ }
19039
+ get development() {
19040
+ return {
19041
+ register: (options) => this.granular.registerDevelopmentProvider(this.ontologyNameOrId, options)
19042
+ };
19043
+ }
18581
19044
  get importer() {
18582
19045
  return {
19046
+ /** Register and publish on the existing backend provider connection. */
19047
+ register: async (handler) => {
19048
+ this.granular.registerEnvironmentImporter(this.ontologyNameOrId, handler);
19049
+ await this.granular.connectEnvironmentImporter(this.ontologyNameOrId);
19050
+ },
18583
19051
  onEnvironmentCreate: (handler) => this.granular.registerEnvironmentImporter(
18584
19052
  this.ontologyNameOrId,
18585
19053
  handler
@@ -18589,6 +19057,10 @@ var OntologyHandle = class {
18589
19057
  }
18590
19058
  };
18591
19059
  var Granular = class _Granular {
19060
+ /** Tenant events feed, authenticated with this client's credentials. */
19061
+ eventsFeed = new EventsFeed(
19062
+ (path2, options) => this.request(path2, options)
19063
+ );
18592
19064
  apiKey;
18593
19065
  apiUrl;
18594
19066
  httpUrl;
@@ -18603,6 +19075,8 @@ var Granular = class _Granular {
18603
19075
  sandboxEffects = /* @__PURE__ */ new Map();
18604
19076
  /** Live sandbox-scoped effect hosts keyed by sandboxId */
18605
19077
  sandboxEffectHosts = /* @__PURE__ */ new Map();
19078
+ developmentProviders = /* @__PURE__ */ new Map();
19079
+ usersProviders = /* @__PURE__ */ new Map();
18606
19080
  /** In-flight host connection promises to avoid duplicate concurrent connects */
18607
19081
  sandboxEffectHostPromises = /* @__PURE__ */ new Map();
18608
19082
  /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
@@ -18654,6 +19128,13 @@ var Granular = class _Granular {
18654
19128
  }
18655
19129
  }
18656
19130
  }
19131
+ async connectEnvironmentImporter(ontologyNameOrId) {
19132
+ const sandboxId = await this._resolveSandboxId(ontologyNameOrId);
19133
+ const importer = this.resolveEnvironmentImporter(ontologyNameOrId, sandboxId);
19134
+ if (!importer) throw new Error("No environment importer registered.");
19135
+ const host = await this.ensureSandboxEffectHost(sandboxId);
19136
+ await host.wsClient.call("environment.importer.register", {});
19137
+ }
18657
19138
  clearEnvironmentImporter(ontologyNameOrId) {
18658
19139
  this.ontologyImporters.delete(ontologyNameOrId);
18659
19140
  for (const [sandboxId, importer] of this.sandboxImporters.entries()) {
@@ -18958,7 +19439,24 @@ var Granular = class _Granular {
18958
19439
  * `getRecordImportSummary()`.
18959
19440
  */
18960
19441
  async runEnvironmentImporterForEnvironment(environmentId, options = {}) {
19442
+ return this.runBoundEnvironmentImporter(environmentId, options);
19443
+ }
19444
+ /** Only the authenticated server-created reverse-RPC binding supplies this
19445
+ * product identity. Ordinary public callers retain legacy identity checks. */
19446
+ async runBoundEnvironmentImporter(environmentId, options, verifiedIdentity) {
18961
19447
  const environmentData = await this.environments.get(environmentId);
19448
+ if (options.expectedSubjectId && environmentData.subjectId !== options.expectedSubjectId) {
19449
+ throw new Error("Importer environment does not match the authenticated subject.");
19450
+ }
19451
+ const subject = await this.request(
19452
+ `/control/subjects/${encodeURIComponent(environmentData.subjectId)}`
19453
+ );
19454
+ if (verifiedIdentity && subject.identityId !== verifiedIdentity.identityId)
19455
+ throw new Error("Importer canonical identity changed.");
19456
+ const externalUserId = verifiedIdentity?.externalUserId || subject.userId || subject.identityId;
19457
+ if ((subject.subjectId || subject.granularId) !== environmentData.subjectId || !externalUserId || options.expectedExternalUserId && options.expectedExternalUserId !== externalUserId) {
19458
+ throw new Error("Importer subject has no matching canonical product identity.");
19459
+ }
18962
19460
  const environment = this.bindEnvironmentHandle(environmentData);
18963
19461
  const requestedOntology = options.ontology || environmentData.ontologyId || environmentData.sandboxId;
18964
19462
  return this.runEnvironmentImporter(
@@ -18967,9 +19465,10 @@ var Granular = class _Granular {
18967
19465
  requestedOntology,
18968
19466
  sandboxId: environmentData.sandboxId,
18969
19467
  subjectId: environmentData.subjectId,
18970
- externalUserId: environmentData.subjectId,
19468
+ externalUserId,
18971
19469
  setupTriggerReason: options.reason || "new_environment",
18972
- setupOperationKey: options.operationKey
19470
+ setupOperationKey: options.operationKey,
19471
+ existingSetupRunId: options.setupRunId
18973
19472
  },
18974
19473
  environment
18975
19474
  );
@@ -19284,7 +19783,7 @@ var Granular = class _Granular {
19284
19783
  }
19285
19784
  if (status !== "all") query.set("status", status);
19286
19785
  const res = await this.request(`/control/sessions?${query.toString()}`);
19287
- const items = Array.isArray(res.items) ? res.items.map((row) => this.normalizeConversationSession(row)) : [];
19786
+ const items = Array.isArray(res.items) ? res.items.map((row2) => this.normalizeConversationSession(row2)) : [];
19288
19787
  const nextCursor = res.nextCursor ?? null;
19289
19788
  if (nextCursor === cursor) {
19290
19789
  throw new Error("Session pagination cursor did not advance");
@@ -19342,26 +19841,26 @@ var Granular = class _Granular {
19342
19841
  result.readThroughSequenceBySessionId
19343
19842
  );
19344
19843
  }
19345
- normalizeConversationSession(row) {
19346
- const sessionId = String(row.sessionId ?? row.session_id ?? "");
19347
- const environmentId = String(row.environmentId ?? row.environment_id ?? "");
19844
+ normalizeConversationSession(row2) {
19845
+ const sessionId = String(row2.sessionId ?? row2.session_id ?? "");
19846
+ const environmentId = String(row2.environmentId ?? row2.environment_id ?? "");
19348
19847
  return {
19349
19848
  sessionId,
19350
- tenantId: row.tenantId != null ? String(row.tenantId) : void 0,
19849
+ tenantId: row2.tenantId != null ? String(row2.tenantId) : void 0,
19351
19850
  environmentId,
19352
- versionId: row.versionId != null ? String(row.versionId) : null,
19353
- docId: String(row.docId ?? row.doc_id ?? ""),
19354
- status: row.status || "active",
19355
- createdAt: _Granular.coerceIsoDate(row.createdAt ?? row.created_at),
19356
- lastSeenAt: _Granular.coerceIsoDate(row.lastSeenAt ?? row.last_seen_at),
19357
- summary: row.summary != null ? String(row.summary) : null,
19358
- summaryUpdatedAt: row.summaryUpdatedAt != null || row.summary_updated_at != null ? _Granular.coerceIsoDate(
19359
- row.summaryUpdatedAt ?? row.summary_updated_at
19851
+ versionId: row2.versionId != null ? String(row2.versionId) : null,
19852
+ docId: String(row2.docId ?? row2.doc_id ?? ""),
19853
+ status: row2.status || "active",
19854
+ createdAt: _Granular.coerceIsoDate(row2.createdAt ?? row2.created_at),
19855
+ lastSeenAt: _Granular.coerceIsoDate(row2.lastSeenAt ?? row2.last_seen_at),
19856
+ summary: row2.summary != null ? String(row2.summary) : null,
19857
+ summaryUpdatedAt: row2.summaryUpdatedAt != null || row2.summary_updated_at != null ? _Granular.coerceIsoDate(
19858
+ row2.summaryUpdatedAt ?? row2.summary_updated_at
19360
19859
  ) : null,
19361
- subjectId: row.subjectId != null ? String(row.subjectId) : null,
19362
- sessionScope: row.sessionScope != null || row.session_scope != null ? String(row.sessionScope ?? row.session_scope) : null,
19363
- jobCount: typeof row.jobCount === "number" ? row.jobCount : void 0,
19364
- toolCallCount: typeof row.toolCallCount === "number" ? row.toolCallCount : void 0
19860
+ subjectId: row2.subjectId != null ? String(row2.subjectId) : null,
19861
+ sessionScope: row2.sessionScope != null || row2.session_scope != null ? String(row2.sessionScope ?? row2.session_scope) : null,
19862
+ jobCount: typeof row2.jobCount === "number" ? row2.jobCount : void 0,
19863
+ toolCallCount: typeof row2.toolCallCount === "number" ? row2.toolCallCount : void 0
19365
19864
  };
19366
19865
  }
19367
19866
  normalizeUserEnvironmentState(state) {
@@ -19540,7 +20039,7 @@ var Granular = class _Granular {
19540
20039
  if (!importer) {
19541
20040
  return null;
19542
20041
  }
19543
- const setupRun = await this.request(
20042
+ const setupRun = resolved.existingSetupRunId ? resolved.environment.setup : await this.request(
19544
20043
  `/control/environments/${environment.environmentId}/setup-runs`,
19545
20044
  {
19546
20045
  method: "POST",
@@ -19550,6 +20049,8 @@ var Granular = class _Granular {
19550
20049
  })
19551
20050
  }
19552
20051
  );
20052
+ if (!setupRun || resolved.existingSetupRunId && setupRun.setupRunId !== resolved.existingSetupRunId || setupRun.environmentId !== environment.environmentId || setupRun.sandboxId !== resolved.sandboxId || setupRun.subjectId !== resolved.subjectId)
20053
+ throw new Error("Importer setup does not match the canonical environment.");
19553
20054
  const setupRunId = setupRun.setupRunId;
19554
20055
  let claim = null;
19555
20056
  for (let attempt = 0; attempt < 3; attempt += 1) {
@@ -19592,6 +20093,8 @@ var Granular = class _Granular {
19592
20093
  sandboxId: environment.sandboxId,
19593
20094
  subjectId: environment.subjectId,
19594
20095
  externalUserId: resolved.externalUserId,
20096
+ setupRunId,
20097
+ setupOperationKey: setupRun.operationKey ?? null,
19595
20098
  reason: resolved.setupTriggerReason,
19596
20099
  incrementTotalObjectsToImportCount: async (n) => {
19597
20100
  const safeIncrement = Math.max(0, Math.trunc(n));
@@ -19881,6 +20384,56 @@ var Granular = class _Granular {
19881
20384
  host.heartbeatTimer = null;
19882
20385
  host.heartbeatInFlight = false;
19883
20386
  }
20387
+ async registerUsers(ontologyNameOrId, handler, options) {
20388
+ const provider = new UsersProvider(handler, options);
20389
+ const sandboxId = await this._resolveSandboxId(ontologyNameOrId);
20390
+ const previous = this.usersProviders.get(sandboxId);
20391
+ this.usersProviders.set(sandboxId, provider);
20392
+ try {
20393
+ const host = await this.ensureSandboxEffectHost(sandboxId);
20394
+ if (provider.registration?.providerId !== host.effectClientId) await this.registerUsersOnHost(host, provider);
20395
+ if (!provider.registration) throw new Error("User directory registration is no longer live.");
20396
+ return provider.registration;
20397
+ } catch (error) {
20398
+ if (this.usersProviders.get(sandboxId) === provider) {
20399
+ if (previous) this.usersProviders.set(sandboxId, previous);
20400
+ else this.usersProviders.delete(sandboxId);
20401
+ }
20402
+ throw error;
20403
+ }
20404
+ }
20405
+ async registerUsersOnHost(host, provider) {
20406
+ const registration = await host.wsClient.call("users.register", {});
20407
+ if (this.usersProviders.get(host.sandboxId) !== provider) throw new Error("User directory registration was replaced.");
20408
+ provider.bind(registration, host.sandboxId, host.effectClientId);
20409
+ }
20410
+ /** Register product-owned dev operator callbacks on the existing provider socket. */
20411
+ async registerDevelopmentProvider(ontologyNameOrId, options) {
20412
+ const provider = new DevelopmentProvider(options);
20413
+ const sandboxId = await this._resolveSandboxId(ontologyNameOrId);
20414
+ const previous = this.developmentProviders.get(sandboxId);
20415
+ this.developmentProviders.set(sandboxId, provider);
20416
+ try {
20417
+ const host = await this.ensureSandboxEffectHost(sandboxId);
20418
+ if (this.developmentProviders.get(sandboxId) !== provider) throw new Error("Development registration was replaced.");
20419
+ if (provider.registration?.providerId !== host.effectClientId) {
20420
+ await this.registerDevelopmentOnHost(host, provider);
20421
+ }
20422
+ if (!provider.registration) throw new Error("Development provider registration is no longer live.");
20423
+ return provider.registration;
20424
+ } catch (error) {
20425
+ if (this.developmentProviders.get(sandboxId) === provider) {
20426
+ if (previous) this.developmentProviders.set(sandboxId, previous);
20427
+ else this.developmentProviders.delete(sandboxId);
20428
+ }
20429
+ throw error;
20430
+ }
20431
+ }
20432
+ async registerDevelopmentOnHost(host, provider) {
20433
+ const registration = await host.wsClient.call("onboarding.register", provider.registrationParams());
20434
+ if (this.developmentProviders.get(host.sandboxId) !== provider) throw new Error("Development registration was replaced.");
20435
+ provider.bind(registration, host.sandboxId, host.effectClientId);
20436
+ }
19884
20437
  async synchronizeEffectHost(host) {
19885
20438
  if (host.syncPromise) {
19886
20439
  return host.syncPromise;
@@ -19891,6 +20444,12 @@ var Granular = class _Granular {
19891
20444
  protocolVersion: "2.0"
19892
20445
  });
19893
20446
  await this.publishSandboxEffectCatalog(host);
20447
+ if (this.resolveEnvironmentImporter(host.sandboxId, host.sandboxId))
20448
+ await host.wsClient.call("environment.importer.register", {});
20449
+ const users2 = this.usersProviders.get(host.sandboxId);
20450
+ if (users2) await this.registerUsersOnHost(host, users2);
20451
+ const development = this.developmentProviders.get(host.sandboxId);
20452
+ if (development) await this.registerDevelopmentOnHost(host, development);
19894
20453
  this.startEffectHostHeartbeat(host);
19895
20454
  })();
19896
20455
  try {
@@ -19938,6 +20497,29 @@ var Granular = class _Granular {
19938
20497
  recovering: false,
19939
20498
  syncPromise: null
19940
20499
  };
20500
+ wsClient.registerRpcHandler("environment.import", async (params) => {
20501
+ const p = params;
20502
+ if (!p || p.sandboxId !== sandboxId || !p.environmentId || !p.setupRunId || !p.subjectId || !p.identityId || !p.externalUserId) throw new Error("Invalid importer scope.");
20503
+ const current = await this.environments.get(p.environmentId);
20504
+ if (current.sandboxId !== sandboxId || current.buildId !== p.buildId || (current.envName || current.environment) !== p.environment || current.subjectId !== p.subjectId) throw new Error("Importer environment changed.");
20505
+ return this.runBoundEnvironmentImporter(p.environmentId, { ontology: sandboxId, setupRunId: p.setupRunId, expectedSubjectId: p.subjectId, expectedExternalUserId: p.externalUserId }, { identityId: p.identityId, externalUserId: p.externalUserId });
20506
+ });
20507
+ wsClient.registerRpcHandler("users.invoke", async (params) => {
20508
+ const provider = this.usersProviders.get(sandboxId);
20509
+ if (!provider) throw new Error("No user directory is registered for this ontology.");
20510
+ const input = params;
20511
+ return input?.page ? provider.invoke(input.page) : provider.invoke();
20512
+ });
20513
+ wsClient.registerRpcHandler("users.resolveMembership", async (params) => {
20514
+ const provider = this.usersProviders.get(sandboxId);
20515
+ if (!provider) throw new Error("No user directory is registered for this ontology.");
20516
+ return provider.resolveMembership(params);
20517
+ });
20518
+ wsClient.registerRpcHandler("onboarding.invoke", async (params) => {
20519
+ const provider = this.developmentProviders.get(sandboxId);
20520
+ if (!provider) throw new Error("No development handlers are registered for this sandbox.");
20521
+ return provider.invoke(params);
20522
+ });
19941
20523
  wsClient.registerRpcHandler("effect.invoke", async (params) => {
19942
20524
  const request = params;
19943
20525
  let commitReceipt;
@@ -20005,6 +20587,10 @@ var Granular = class _Granular {
20005
20587
  });
20006
20588
  wsClient.on("disconnect", () => {
20007
20589
  this.stopEffectHostHeartbeat(host);
20590
+ const users2 = this.usersProviders.get(sandboxId);
20591
+ if (users2?.registration?.providerId === host.effectClientId) users2.unbind();
20592
+ const provider = this.developmentProviders.get(sandboxId);
20593
+ if (provider?.registration?.providerId === host.effectClientId) provider.unbind();
20008
20594
  });
20009
20595
  try {
20010
20596
  await withTimeout(
@@ -20219,8 +20805,8 @@ var Granular = class _Granular {
20219
20805
  list: async () => {
20220
20806
  return this.request("/control/sandboxes");
20221
20807
  },
20222
- get: async (id) => {
20223
- return this.request(`/control/sandboxes/${id}`);
20808
+ get: async (id3) => {
20809
+ return this.request(`/control/sandboxes/${id3}`);
20224
20810
  },
20225
20811
  create: async (data) => {
20226
20812
  return this.request("/control/sandboxes", {
@@ -20228,14 +20814,14 @@ var Granular = class _Granular {
20228
20814
  body: JSON.stringify(data)
20229
20815
  });
20230
20816
  },
20231
- update: async (id, data) => {
20232
- return this.request(`/control/sandboxes/${id}`, {
20817
+ update: async (id3, data) => {
20818
+ return this.request(`/control/sandboxes/${id3}`, {
20233
20819
  method: "PATCH",
20234
20820
  body: JSON.stringify(data)
20235
20821
  });
20236
20822
  },
20237
- delete: async (id) => {
20238
- return this.request(`/control/sandboxes/${id}`, {
20823
+ delete: async (id3) => {
20824
+ return this.request(`/control/sandboxes/${id3}`, {
20239
20825
  method: "DELETE"
20240
20826
  });
20241
20827
  }
@@ -20385,17 +20971,17 @@ var Granular = class _Granular {
20385
20971
  const result = await this.request(
20386
20972
  `/control/stream-events?${query.toString()}`
20387
20973
  );
20388
- return (result.items || []).map((row) => ({
20389
- eventId: row.event_id,
20390
- streamName: row.stream_name,
20391
- eventType: row.event_type,
20392
- payload: typeof row.payload === "string" ? JSON.parse(row.payload) : row.payload,
20393
- environmentId: row.environment_id,
20394
- sessionId: row.session_id,
20395
- subjectId: row.subject_id,
20396
- source: row.source,
20397
- isAcked: Boolean(row.is_acked),
20398
- createdAt: row.created_at
20974
+ return (result.items || []).map((row2) => ({
20975
+ eventId: row2.event_id,
20976
+ streamName: row2.stream_name,
20977
+ eventType: row2.event_type,
20978
+ payload: typeof row2.payload === "string" ? JSON.parse(row2.payload) : row2.payload,
20979
+ environmentId: row2.environment_id,
20980
+ sessionId: row2.session_id,
20981
+ subjectId: row2.subject_id,
20982
+ source: row2.source,
20983
+ isAcked: Boolean(row2.is_acked),
20984
+ createdAt: row2.created_at
20399
20985
  }));
20400
20986
  },
20401
20987
  subscribe: (params) => {
@@ -20463,13 +21049,13 @@ var Granular = class _Granular {
20463
21049
  const result = await this.request(
20464
21050
  `/control/stream-events/stats?${query.toString()}`
20465
21051
  );
20466
- return (result.items || []).map((row) => ({
20467
- streamName: row.stream_name,
20468
- eventType: row.event_type,
20469
- total: Number(row.total),
20470
- last1h: Number(row.last_1h),
20471
- last24h: Number(row.last_24h),
20472
- unacked: Number(row.unacked)
21052
+ return (result.items || []).map((row2) => ({
21053
+ streamName: row2.stream_name,
21054
+ eventType: row2.event_type,
21055
+ total: Number(row2.total),
21056
+ last1h: Number(row2.last_1h),
21057
+ last24h: Number(row2.last_24h),
21058
+ unacked: Number(row2.unacked)
20473
21059
  }));
20474
21060
  }
20475
21061
  };
@@ -20508,9 +21094,9 @@ var Granular = class _Granular {
20508
21094
  })
20509
21095
  );
20510
21096
  },
20511
- get: async (id) => {
21097
+ get: async (id3) => {
20512
21098
  return normalizeSubject(
20513
- await this.request(`/control/subjects/${id}`)
21099
+ await this.request(`/control/subjects/${id3}`)
20514
21100
  );
20515
21101
  }
20516
21102
  };
@@ -22134,7 +22720,7 @@ function buildGranularAgentManualActionMemorySummary(input) {
22134
22720
  failureCount: typeof suggestion.failureCount === "number" && Number.isFinite(suggestion.failureCount) ? suggestion.failureCount : null,
22135
22721
  lastOccurredAt: typeof suggestion.lastOccurredAt === "number" && Number.isFinite(suggestion.lastOccurredAt) ? suggestion.lastOccurredAt : null,
22136
22722
  sampleTargetIds: Array.isArray(suggestion.sampleTargetIds) ? suggestion.sampleTargetIds.filter(
22137
- (id) => typeof id === "string" && id.trim().length > 0
22723
+ (id3) => typeof id3 === "string" && id3.trim().length > 0
22138
22724
  ).slice(0, 6) : []
22139
22725
  }));
22140
22726
  return [
@@ -23230,8 +23816,8 @@ function collectReferencesFromRecord(record, refs) {
23230
23816
  for (const key of VARIABLE_ARRAY_KEY_CANDIDATES)
23231
23817
  pushStringArray(refs.variableNames, record[key]);
23232
23818
  }
23233
- function stringValue(record, keys) {
23234
- for (const key of keys) {
23819
+ function stringValue(record, keys2) {
23820
+ for (const key of keys2) {
23235
23821
  const value = record[key];
23236
23822
  if (typeof value === "string" && value.trim()) {
23237
23823
  return value.trim();
@@ -23244,8 +23830,8 @@ function findEntryPathForRecord(record, heap) {
23244
23830
  if (directPath && heap.entriesByPath?.[directPath]) {
23245
23831
  return directPath;
23246
23832
  }
23247
- const id = stringValue(record, ["id", "_id", "recordId", "objectId"]);
23248
- if (!id) {
23833
+ const id3 = stringValue(record, ["id", "_id", "recordId", "objectId"]);
23834
+ if (!id3) {
23249
23835
  return null;
23250
23836
  }
23251
23837
  const className = stringValue(record, [
@@ -23257,12 +23843,12 @@ function findEntryPathForRecord(record, heap) {
23257
23843
  ]);
23258
23844
  const entries = Object.values(heap.entriesByPath || {});
23259
23845
  const exact = entries.find(
23260
- (entry) => entry.id === id && (!className || entry.className === className || entry.prototypes?.includes(className))
23846
+ (entry) => entry.id === id3 && (!className || entry.className === className || entry.prototypes?.includes(className))
23261
23847
  );
23262
23848
  if (exact?.path) {
23263
23849
  return exact.path;
23264
23850
  }
23265
- const idOnlyMatches = entries.filter((entry) => entry.id === id);
23851
+ const idOnlyMatches = entries.filter((entry) => entry.id === id3);
23266
23852
  return idOnlyMatches.length === 1 ? idOnlyMatches[0].path : null;
23267
23853
  }
23268
23854
  function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__ */ new Set()) {
@@ -23827,8 +24413,8 @@ function aggregateConversationTokenUsage(conversation) {
23827
24413
  )
23828
24414
  );
23829
24415
  }
23830
- function tokenUsageForGenerationOutput(generation) {
23831
- const attempts = generation.generationAttempts?.length ? generation.generationAttempts : [{ raw: generation.raw }];
24416
+ function tokenUsageForGenerationOutput(generation2) {
24417
+ const attempts = generation2.generationAttempts?.length ? generation2.generationAttempts : [{ raw: generation2.raw }];
23832
24418
  return aggregateTokenUsage(
23833
24419
  attempts.map((attempt) => extractTokenUsageFromRaw(attempt.raw))
23834
24420
  );
@@ -24316,11 +24902,11 @@ function normalizeHeapSnapshot2(heap) {
24316
24902
  function targetFromUiContext(context) {
24317
24903
  const target = asRecord7(context?.target) || asRecord7(context?.currentPageObject) || asRecord7(context?.commentaryTarget);
24318
24904
  const className = typeof target?.className === "string" ? target.className : "";
24319
- const id = typeof target?.id === "string" ? target.id : "";
24320
- if (!className || !id) return null;
24905
+ const id3 = typeof target?.id === "string" ? target.id : "";
24906
+ if (!className || !id3) return null;
24321
24907
  return {
24322
24908
  className,
24323
- id,
24909
+ id: id3,
24324
24910
  label: typeof target?.label === "string" ? target.label : void 0
24325
24911
  };
24326
24912
  }
@@ -25136,14 +25722,14 @@ function isTransientEvalError(error) {
25136
25722
  const message = error instanceof Error ? error.message : String(error);
25137
25723
  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);
25138
25724
  }
25139
- function assertionPassed(id, run) {
25725
+ function assertionPassed(id3, run) {
25140
25726
  try {
25141
- run(id);
25142
- return { id, label: id, status: "passed" };
25727
+ run(id3);
25728
+ return { id: id3, label: id3, status: "passed" };
25143
25729
  } catch (error) {
25144
25730
  return {
25145
- id,
25146
- label: id,
25731
+ id: id3,
25732
+ label: id3,
25147
25733
  status: "failed",
25148
25734
  message: error instanceof Error ? error.message : String(error)
25149
25735
  };
@@ -26069,7 +26655,7 @@ function createAgentEvalHarness(options) {
26069
26655
  });
26070
26656
  };
26071
26657
  const generationStartedAt = Date.now();
26072
- const generation = await withTimeout2(
26658
+ const generation2 = await withTimeout2(
26073
26659
  generateTurnWithRepair(options.generator, {
26074
26660
  systemPrompt,
26075
26661
  history: buildHistory(conversation.history),
@@ -26120,16 +26706,16 @@ function createAgentEvalHarness(options) {
26120
26706
  iteration: iteration + 1,
26121
26707
  templateId: renderedPrompt.templateId,
26122
26708
  templateVersion: renderedPrompt.templateVersion,
26123
- title: generation.code ? "Generated job code" : "Generated text reply",
26124
- message: generation.code || generation.reply || "",
26709
+ title: generation2.code ? "Generated job code" : "Generated text reply",
26710
+ message: generation2.code || generation2.reply || "",
26125
26711
  data: {
26126
- reply: generation.reply,
26127
- code: generation.code,
26128
- attempts: generation.generationAttempts,
26129
- usage: tokenUsageForGenerationOutput(generation)
26712
+ reply: generation2.reply,
26713
+ code: generation2.code,
26714
+ attempts: generation2.generationAttempts,
26715
+ usage: tokenUsageForGenerationOutput(generation2)
26130
26716
  }
26131
26717
  });
26132
- const generatedReasoningLines = generation.code ? consumeGranularReasoningOnlyChunk("", generation.code, {
26718
+ const generatedReasoningLines = generation2.code ? consumeGranularReasoningOnlyChunk("", generation2.code, {
26133
26719
  final: true
26134
26720
  }).reasoningLines : [];
26135
26721
  for (const line of generatedReasoningLines) {
@@ -26144,18 +26730,18 @@ function createAgentEvalHarness(options) {
26144
26730
  templateVersion: renderedPrompt.templateVersion,
26145
26731
  templateHash: renderedPrompt.templateHash,
26146
26732
  promptInstanceHash: renderedPrompt.promptInstanceHash,
26147
- generationReply: generation.reply,
26148
- generatedCode: generation.code,
26149
- rawGeneration: generation.raw,
26150
- generationAttempts: generation.generationAttempts,
26151
- tokenUsage: tokenUsageForGenerationOutput(generation)
26733
+ generationReply: generation2.reply,
26734
+ generatedCode: generation2.code,
26735
+ rawGeneration: generation2.raw,
26736
+ generationAttempts: generation2.generationAttempts,
26737
+ tokenUsage: tokenUsageForGenerationOutput(generation2)
26152
26738
  };
26153
26739
  turnLog.iterations.push(iterationLog);
26154
26740
  await writeJson(
26155
26741
  path.join(turnDir, `iteration-${iteration + 1}-generation.json`),
26156
- generation
26742
+ generation2
26157
26743
  );
26158
- if (!generation.code) {
26744
+ if (!generation2.code) {
26159
26745
  const responseText2 = "";
26160
26746
  const completed = {
26161
26747
  conversation,
@@ -26205,7 +26791,7 @@ function createAgentEvalHarness(options) {
26205
26791
  return completed;
26206
26792
  }
26207
26793
  const session = conversation.environment;
26208
- const job = await session.submitJob(generation.code, {
26794
+ const job = await session.submitJob(generation2.code, {
26209
26795
  agent: {
26210
26796
  userRequest: input.request,
26211
26797
  generationRequest: request,
@@ -26215,9 +26801,9 @@ function createAgentEvalHarness(options) {
26215
26801
  turnId,
26216
26802
  iteration: iteration + 1,
26217
26803
  tools,
26218
- generationReply: generation.reply,
26219
- rawGeneration: generation.raw,
26220
- repairIssues: generation.generationAttempts?.flatMap(
26804
+ generationReply: generation2.reply,
26805
+ rawGeneration: generation2.raw,
26806
+ repairIssues: generation2.generationAttempts?.flatMap(
26221
26807
  (attempt) => attempt.repairIssues || []
26222
26808
  )
26223
26809
  }
@@ -26233,7 +26819,7 @@ function createAgentEvalHarness(options) {
26233
26819
  templateVersion: renderedPrompt.templateVersion,
26234
26820
  title: "Submitted Granular job",
26235
26821
  message: job.id,
26236
- data: { code: generation.code }
26822
+ data: { code: generation2.code }
26237
26823
  });
26238
26824
  const outcome = await waitForJobOutcome({
26239
26825
  environment: conversation.environment,
@@ -26257,7 +26843,7 @@ function createAgentEvalHarness(options) {
26257
26843
  request: input.request,
26258
26844
  turnDir,
26259
26845
  boundaryTimestamp,
26260
- finalCode: generation.code,
26846
+ finalCode: generation2.code,
26261
26847
  stdout: outcome.stdout,
26262
26848
  stderr: outcome.stderr,
26263
26849
  prompts: outcome.prompts,
@@ -26277,7 +26863,7 @@ function createAgentEvalHarness(options) {
26277
26863
  request: input.request,
26278
26864
  turnDir,
26279
26865
  boundaryTimestamp,
26280
- finalCode: generation.code,
26866
+ finalCode: generation2.code,
26281
26867
  stdout: outcome.stdout,
26282
26868
  stderr: outcome.stderr,
26283
26869
  prompts: outcome.prompts,
@@ -26332,7 +26918,7 @@ function createAgentEvalHarness(options) {
26332
26918
  });
26333
26919
  const responseText = presentation.responseText ?? "";
26334
26920
  const verifierSnapshot = createHarnessVerifierSnapshot({
26335
- finalCode: generation.code,
26921
+ finalCode: generation2.code,
26336
26922
  resultPreview: JSON.stringify(outcome.result, null, 2),
26337
26923
  liveDoc: settledLiveDoc,
26338
26924
  projectionOptions: { boundaryTimestamp }
@@ -26385,7 +26971,7 @@ function createAgentEvalHarness(options) {
26385
26971
  conversation.history.push({
26386
26972
  role: "assistant",
26387
26973
  content: responseText,
26388
- code: generation.code,
26974
+ code: generation2.code,
26389
26975
  jobStatus: "succeeded",
26390
26976
  jobResultPreview: JSON.stringify(outcome.result, null, 2)
26391
26977
  });
@@ -26411,7 +26997,7 @@ function createAgentEvalHarness(options) {
26411
26997
  turnDir,
26412
26998
  responseText,
26413
26999
  terminalKind: getCurrentClosureId(settledLiveDoc) ? "closure" : "reply",
26414
- finalCode: generation.code,
27000
+ finalCode: generation2.code,
26415
27001
  actionSummary: latestCheckpoint.latestActionSummary || [],
26416
27002
  promptInteractions: [],
26417
27003
  verification: null,