@granular-software/sdk 0.4.80 → 0.4.81

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -12,6 +12,7 @@ var module$1 = require('module');
12
12
  var url = require('url');
13
13
  var readline = require('readline');
14
14
  var http = require('http');
15
+ var NodeWebSocket = require('ws');
15
16
  var Automerge = require('@automerge/automerge');
16
17
 
17
18
  var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
@@ -42,6 +43,7 @@ var os__default = /*#__PURE__*/_interopDefault(os);
42
43
  var tty__default = /*#__PURE__*/_interopDefault(tty);
43
44
  var readline__namespace = /*#__PURE__*/_interopNamespace(readline);
44
45
  var http__namespace = /*#__PURE__*/_interopNamespace(http);
46
+ var NodeWebSocket__default = /*#__PURE__*/_interopDefault(NodeWebSocket);
45
47
  var Automerge__namespace = /*#__PURE__*/_interopNamespace(Automerge);
46
48
 
47
49
  var __create = Object.create;
@@ -141,16 +143,16 @@ async function digestJson(value) {
141
143
  const cryptoLike = globalThis.crypto;
142
144
  if (cryptoLike?.subtle) {
143
145
  const data = new TextEncoder().encode(payload);
144
- const hash2 = await cryptoLike.subtle.digest("SHA-256", data);
145
- const hex = Array.from(new Uint8Array(hash2)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
146
+ const hash3 = await cryptoLike.subtle.digest("SHA-256", data);
147
+ const hex = Array.from(new Uint8Array(hash3)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
146
148
  return `sha256:${hex}`;
147
149
  }
148
- let hash = 2166136261;
150
+ let hash2 = 2166136261;
149
151
  for (let index = 0; index < payload.length; index += 1) {
150
- hash ^= payload.charCodeAt(index);
151
- hash = Math.imul(hash, 16777619);
152
+ hash2 ^= payload.charCodeAt(index);
153
+ hash2 = Math.imul(hash2, 16777619);
152
154
  }
153
- return `fnv1a:${(hash >>> 0).toString(16).padStart(8, "0")}`;
155
+ return `fnv1a:${(hash2 >>> 0).toString(16).padStart(8, "0")}`;
154
156
  }
155
157
  function sortJson(value) {
156
158
  if (Array.isArray(value)) return value.map(sortJson);
@@ -1010,7 +1012,7 @@ var require_main = __commonJS({
1010
1012
  var os2 = __require("os");
1011
1013
  var crypto2 = __require("crypto");
1012
1014
  var packageJson = require_package();
1013
- var version2 = packageJson.version;
1015
+ var version3 = packageJson.version;
1014
1016
  var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
1015
1017
  function parse(src) {
1016
1018
  const obj = {};
@@ -1059,13 +1061,13 @@ var require_main = __commonJS({
1059
1061
  return DotenvModule.parse(decrypted);
1060
1062
  }
1061
1063
  function _warn(message) {
1062
- console.log(`[dotenv@${version2}][WARN] ${message}`);
1064
+ console.log(`[dotenv@${version3}][WARN] ${message}`);
1063
1065
  }
1064
1066
  function _debug(message) {
1065
- console.log(`[dotenv@${version2}][DEBUG] ${message}`);
1067
+ console.log(`[dotenv@${version3}][DEBUG] ${message}`);
1066
1068
  }
1067
1069
  function _log(message) {
1068
- console.log(`[dotenv@${version2}] ${message}`);
1070
+ console.log(`[dotenv@${version3}] ${message}`);
1069
1071
  }
1070
1072
  function _dotenvKey(options) {
1071
1073
  if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
@@ -10564,10 +10566,10 @@ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
10564
10566
  return 3;
10565
10567
  }
10566
10568
  if ("TERM_PROGRAM" in env) {
10567
- const version2 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
10569
+ const version3 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
10568
10570
  switch (env.TERM_PROGRAM) {
10569
10571
  case "iTerm.app": {
10570
- return version2 >= 3 ? 3 : 2;
10572
+ return version3 >= 3 ? 3 : 2;
10571
10573
  }
10572
10574
  case "Apple_Terminal": {
10573
10575
  return 2;
@@ -12847,9 +12849,9 @@ async function onboardWatchCommand(options) {
12847
12849
  });
12848
12850
  }
12849
12851
  for (const directive of snapshot.directives) {
12850
- const version2 = `${directive.revision}:${directive.status}:${directive.updatedAt}`;
12851
- if (directiveVersions.get(directive.directiveId) === version2) continue;
12852
- directiveVersions.set(directive.directiveId, version2);
12852
+ const version3 = `${directive.revision}:${directive.status}:${directive.updatedAt}`;
12853
+ if (directiveVersions.get(directive.directiveId) === version3) continue;
12854
+ directiveVersions.set(directive.directiveId, version3);
12853
12855
  if (directive.status === "applied") continue;
12854
12856
  emit2({
12855
12857
  type: "directive.changed",
@@ -13449,8 +13451,9 @@ var {
13449
13451
  } = import_index.default;
13450
13452
 
13451
13453
  // package.json
13454
+ var version = "0.4.81";
13452
13455
  var package_default = {
13453
- version: "0.4.80"};
13456
+ version};
13454
13457
 
13455
13458
  // src/cli/commands/onboarding-preflight.ts
13456
13459
  function assessOnboardingPreflight(report, dependencies) {
@@ -14388,8 +14391,8 @@ var ZodIssueCode = util.arrayToEnum([
14388
14391
  "not_finite"
14389
14392
  ]);
14390
14393
  var quotelessJson = (obj) => {
14391
- const json = JSON.stringify(obj, null, 2);
14392
- return json.replace(/"([^"]+)":/g, "$1:");
14394
+ const json2 = JSON.stringify(obj, null, 2);
14395
+ return json2.replace(/"([^"]+)":/g, "$1:");
14393
14396
  };
14394
14397
  var ZodError = class _ZodError extends Error {
14395
14398
  get errors() {
@@ -15100,11 +15103,11 @@ function datetimeRegex(args) {
15100
15103
  regex2 = `${regex2}(${opts.join("|")})`;
15101
15104
  return new RegExp(`^${regex2}$`);
15102
15105
  }
15103
- function isValidIP(ip, version2) {
15104
- if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
15106
+ function isValidIP(ip, version3) {
15107
+ if ((version3 === "v4" || !version3) && ipv4Regex.test(ip)) {
15105
15108
  return true;
15106
15109
  }
15107
- if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
15110
+ if ((version3 === "v6" || !version3) && ipv6Regex.test(ip)) {
15108
15111
  return true;
15109
15112
  }
15110
15113
  return false;
@@ -15131,11 +15134,11 @@ function isValidJWT(jwt, alg) {
15131
15134
  return false;
15132
15135
  }
15133
15136
  }
15134
- function isValidCidr(ip, version2) {
15135
- if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
15137
+ function isValidCidr(ip, version3) {
15138
+ if ((version3 === "v4" || !version3) && ipv4CidrRegex.test(ip)) {
15136
15139
  return true;
15137
15140
  }
15138
- if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
15141
+ if ((version3 === "v6" || !version3) && ipv6CidrRegex.test(ip)) {
15139
15142
  return true;
15140
15143
  }
15141
15144
  return false;
@@ -18434,6 +18437,27 @@ external_exports.object({
18434
18437
  }).strict()
18435
18438
  ]).optional(),
18436
18439
  creates: CreatesSchema.optional(),
18440
+ reconcileWith: external_exports.string().min(1).optional(),
18441
+ fenceWith: external_exports.string().min(1).optional(),
18442
+ versionPrecondition: external_exports.object({
18443
+ expected: external_exports.string().regex(/^input(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/)
18444
+ }).strict().optional(),
18445
+ concurrency: external_exports.union([
18446
+ external_exports.object({
18447
+ resource: external_exports.string().min(1).max(200),
18448
+ key: external_exports.string().regex(/^input(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/),
18449
+ scope: external_exports.enum(["environment", "sandbox"]).optional()
18450
+ }).strict(),
18451
+ external_exports.object({
18452
+ resources: external_exports.array(
18453
+ external_exports.object({
18454
+ resource: external_exports.string().min(1).max(200),
18455
+ key: external_exports.string().regex(/^input(?:\.[A-Za-z_][A-Za-z0-9_]*)+$/)
18456
+ }).strict()
18457
+ ).min(1).max(8),
18458
+ scope: external_exports.enum(["environment", "sandbox"]).optional()
18459
+ }).strict()
18460
+ ]).optional(),
18437
18461
  access: external_exports.enum(["read", "write", "ui"]).optional(),
18438
18462
  effectKind: external_exports.enum(["read", "write", "ui"]).optional(),
18439
18463
  sideEffect: external_exports.enum(["read", "write", "ui", "readonly", "read_only"]).optional(),
@@ -22320,9 +22344,9 @@ async function pullCommand(versionId) {
22320
22344
  const api = new ApiClient(config.apiKey, config.apiUrl);
22321
22345
  const spin = spinner(`Fetching version ${versionId}...`);
22322
22346
  try {
22323
- const version2 = await api.getVersion(versionId);
22324
- const targetManifestId = version2.manifestId;
22325
- const targetVersionLabel = version2.versionNumber != null ? `v${version2.versionNumber}` : versionId;
22347
+ const version3 = await api.getVersion(versionId);
22348
+ const targetManifestId = version3.manifestId;
22349
+ const targetVersionLabel = version3.versionNumber != null ? `v${version3.versionNumber}` : versionId;
22326
22350
  spin.text = " Downloading manifest content...";
22327
22351
  const full = await api.getManifest(targetManifestId);
22328
22352
  if (!full.content) {
@@ -22365,14 +22389,14 @@ function namesForMessage(names, fallback2) {
22365
22389
  return names.slice(0, 3).join(", ");
22366
22390
  }
22367
22391
  async function createVersionForUploadedManifest(api, sandboxId, uploadedManifest) {
22368
- const version2 = await api.createVersion(
22392
+ const version3 = await api.createVersion(
22369
22393
  sandboxId,
22370
22394
  uploadedManifest.manifestId
22371
22395
  );
22372
- if (!version2.manifestId)
22396
+ if (!version3.manifestId)
22373
22397
  throw new Error("Build version did not provide its authoritative manifest");
22374
- uploadedManifest.manifestId = version2.manifestId;
22375
- return version2;
22398
+ uploadedManifest.manifestId = version3.manifestId;
22399
+ return version3;
22376
22400
  }
22377
22401
  async function createBuildOnboardingReporter(api, runId, sandboxId, connect2) {
22378
22402
  const isTerminal = async () => {
@@ -22621,7 +22645,7 @@ async function buildCommand() {
22621
22645
  "Creating or reusing ontology version from manifest..."
22622
22646
  );
22623
22647
  try {
22624
- const version2 = await createVersionForUploadedManifest(
22648
+ const version3 = await createVersionForUploadedManifest(
22625
22649
  api,
22626
22650
  config.sandboxId,
22627
22651
  uploadedManifest
@@ -22630,8 +22654,8 @@ async function buildCommand() {
22630
22654
  phase: "build",
22631
22655
  sandboxId: config.sandboxId,
22632
22656
  manifestId: uploadedManifest.manifestId,
22633
- buildId: version2.buildId,
22634
- buildStatus: version2.status || "building",
22657
+ buildId: version3.buildId,
22658
+ buildStatus: version3.status || "building",
22635
22659
  presence: "working",
22636
22660
  currentActivity: `Compiling ${manifest2.name}`
22637
22661
  });
@@ -22642,15 +22666,15 @@ async function buildCommand() {
22642
22666
  {
22643
22667
  step: "compile",
22644
22668
  ontologyName: manifest2.name,
22645
- buildId: version2.buildId,
22669
+ buildId: version3.buildId,
22646
22670
  stateMachineNames: stateMachineNames.slice(0, 25),
22647
22671
  effectNames: effectNames.slice(0, 25)
22648
22672
  }
22649
22673
  );
22650
- building.text = ` Running build for version... ${brand.muted(version2.buildId)}`;
22674
+ building.text = ` Running build for version... ${brand.muted(version3.buildId)}`;
22651
22675
  const startTime = Date.now();
22652
22676
  const completed = await api.waitForVersionBuild(
22653
- version2.buildId,
22677
+ version3.buildId,
22654
22678
  (status) => {
22655
22679
  const elapsed = Math.round((Date.now() - startTime) / 1e3);
22656
22680
  building.text = ` Running build for version... ${brand.muted(`${status} (${elapsed}s)`)}`;
@@ -22845,7 +22869,7 @@ async function deployCommand(options = {}) {
22845
22869
  const devTag = tags.find((tag2) => tag2.name === "dev");
22846
22870
  const prodTag = tags.find((tag2) => tag2.name === "prod");
22847
22871
  const existingVersion = options.releaseKey ? null : versions.find(
22848
- (version2) => version2.manifestDigest === uploadedManifest.digest
22872
+ (version3) => version3.manifestDigest === uploadedManifest.digest
22849
22873
  ) || null;
22850
22874
  const existingVersionId = existingVersion?.buildId || null;
22851
22875
  const devVersionId = devTag?.targetVersionId || devTag?.targetBuildId || null;
@@ -22860,20 +22884,20 @@ async function deployCommand(options = {}) {
22860
22884
  ` Current manifest already matches ${brand.secondary(existingVersionId)} on dev.`
22861
22885
  );
22862
22886
  } else {
22863
- const version2 = await api.createVersion(
22887
+ const version3 = await api.createVersion(
22864
22888
  config.sandboxId,
22865
22889
  uploadedManifest.manifestId,
22866
22890
  options.releaseKey
22867
22891
  );
22868
- if (version2.createdNewVersion === false && version2.status === "completed") {
22869
- completed = version2;
22892
+ if (version3.createdNewVersion === false && version3.status === "completed") {
22893
+ completed = version3;
22870
22894
  building.succeed(
22871
- ` Reused ${brand.secondary(version2.buildId)}; the release key is unchanged.`
22895
+ ` Reused ${brand.secondary(version3.buildId)}; the release key is unchanged.`
22872
22896
  );
22873
22897
  } else {
22874
22898
  const startTime = Date.now();
22875
- building.text = ` Running build for version... ${brand.muted(version2.buildId)}`;
22876
- completed = await api.waitForVersionBuild(version2.buildId, (status) => {
22899
+ building.text = ` Running build for version... ${brand.muted(version3.buildId)}`;
22900
+ completed = await api.waitForVersionBuild(version3.buildId, (status) => {
22877
22901
  const elapsed = Math.round((Date.now() - startTime) / 1e3);
22878
22902
  building.text = ` Running build for version... ${brand.muted(`${status} (${elapsed}s)`)}`;
22879
22903
  });
@@ -23464,6 +23488,163 @@ function eventsFeedSearch(filter) {
23464
23488
  return search.size ? `?${search.toString()}` : "";
23465
23489
  }
23466
23490
 
23491
+ // src/customer-skill-authorization.ts
23492
+ var secret = () => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replaceAll("+", "-").replaceAll("/", "_").replaceAll("=", "");
23493
+ var hash = async (s) => Array.from(
23494
+ new Uint8Array(
23495
+ await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s))
23496
+ ),
23497
+ (x) => x.toString(16).padStart(2, "0")
23498
+ ).join("");
23499
+ var equal = (a, b) => {
23500
+ let v = a.length ^ b.length;
23501
+ for (let i = 0; i < Math.max(a.length, b.length); i++)
23502
+ v |= (a.charCodeAt(i) || 0) ^ (b.charCodeAt(i) || 0);
23503
+ return v === 0;
23504
+ };
23505
+ var json = (body, status = 200) => Response.json(body, {
23506
+ status,
23507
+ headers: { "Cache-Control": "no-store", "Referrer-Policy": "no-referrer" }
23508
+ });
23509
+ var escape = (s) => s.replace(
23510
+ /[&<>"']/g,
23511
+ (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]
23512
+ );
23513
+ function customerSkillAuthorization(model, o) {
23514
+ const origin = new URL(model.setupUrl).origin, path10 = new URL(model.setupUrl).pathname;
23515
+ if (o.serviceToken.length < 32 || new URL(o.loginUrl).origin !== origin || !model.runtimeOrigin.startsWith("https://"))
23516
+ throw Error("Invalid customer setup authorization");
23517
+ const launches = /* @__PURE__ */ new Map();
23518
+ const bindings = /* @__PURE__ */ new Map();
23519
+ const forms = /* @__PURE__ */ new Map();
23520
+ const call = async (suffix, body) => {
23521
+ const r = await (o.fetch || fetch)(model.runtimeOrigin + suffix, {
23522
+ method: "POST",
23523
+ redirect: "error",
23524
+ headers: {
23525
+ "content-type": "application/json",
23526
+ authorization: "Bearer " + o.serviceToken
23527
+ },
23528
+ body: JSON.stringify(body),
23529
+ signal: AbortSignal.timeout(15e3)
23530
+ });
23531
+ if (!r.ok) throw Error("Customer runtime unavailable");
23532
+ return r.json();
23533
+ };
23534
+ const prune = () => {
23535
+ for (const table2 of [launches, bindings, forms])
23536
+ for (const [key, row3] of table2)
23537
+ if (row3.expiresAt <= Date.now()) table2.delete(key);
23538
+ };
23539
+ return {
23540
+ async resolveLaunch(request) {
23541
+ prune();
23542
+ if (!await o.authenticate(request))
23543
+ return Response.redirect(o.loginUrl, 303);
23544
+ if (launches.size >= 1e3) return json({ error: "setup_busy" }, 429);
23545
+ const launch = secret(), binding = secret(), expiresAt = Date.now() + 5 * 6e4;
23546
+ launches.set(await hash(launch), { request, binding, expiresAt });
23547
+ bindings.set(binding, { request, expiresAt: Date.now() + 15 * 6e4 });
23548
+ return { launch, productModelId: model.productModelId };
23549
+ },
23550
+ async fetch(request) {
23551
+ prune();
23552
+ const url = new URL(request.url);
23553
+ if (url.origin !== origin) return json({ error: "not_found" }, 404);
23554
+ if (url.pathname === path10 + "/redeem" || url.pathname === path10 + "/check") {
23555
+ if (request.method !== "POST" || !equal(
23556
+ request.headers.get("authorization") || "",
23557
+ "Bearer " + o.serviceToken
23558
+ ))
23559
+ return json({ error: "not_authorized" }, 401);
23560
+ const body = await request.json();
23561
+ let binding;
23562
+ if (url.pathname.endsWith("redeem")) {
23563
+ if (typeof body?.launch !== "string" || !/^[a-f0-9]{64}$/.test(body.proofHash))
23564
+ return json({ error: "invalid_request" }, 400);
23565
+ const row4 = launches.get(await hash(body.launch));
23566
+ if (!row4 || row4.proofHash && row4.proofHash !== body.proofHash)
23567
+ return json({ error: "launch_unavailable" }, 403);
23568
+ row4.proofHash = body.proofHash;
23569
+ binding = row4.binding;
23570
+ } else binding = body?.binding;
23571
+ const row3 = bindings.get(binding), actor2 = row3 ? await o.authenticate(row3.request) : null;
23572
+ if (!actor2) return json({ error: "customer_session_ended" }, 401);
23573
+ return json({
23574
+ binding,
23575
+ productModelId: model.productModelId,
23576
+ identityId: actor2.identityId,
23577
+ providerSubject: actor2.providerSubject,
23578
+ displayName: actor2.displayName,
23579
+ authorizedUntil: row3.expiresAt
23580
+ });
23581
+ }
23582
+ if (url.pathname !== path10 + "/approve") return null;
23583
+ const actor = await o.authenticate(request);
23584
+ if (!actor) return Response.redirect(o.loginUrl, 303);
23585
+ if (request.method === "GET") {
23586
+ const attemptId = url.searchParams.get("attempt");
23587
+ if (!attemptId || !/^[A-Za-z0-9_-]{16,100}$/.test(attemptId))
23588
+ return json({ error: "invalid_attempt" }, 400);
23589
+ const pending = await call("/subject/customer-request", {
23590
+ attemptId,
23591
+ identityId: actor.identityId,
23592
+ providerSubject: actor.providerSubject
23593
+ });
23594
+ const binding = secret();
23595
+ bindings.set(binding, { request, expiresAt: Date.now() + 15 * 6e4 });
23596
+ const csrf = secret();
23597
+ forms.set(await hash(csrf), {
23598
+ sessionHash: await hash(request.headers.get("cookie") || ""),
23599
+ identityId: actor.identityId,
23600
+ binding,
23601
+ attemptId,
23602
+ expiresAt: Date.now() + 5 * 6e4
23603
+ });
23604
+ return new Response(
23605
+ `<!doctype html><meta charset="utf-8"><title>Connect ${escape(model.productName)}</title><main><h1>Connect ${escape(model.productName)} to your coding agent</h1><p>Signed in as ${escape(actor.displayName)}.</p><p>Access: ${escape(pending.scopeLabel)}. Device code: <strong>${escape(pending.pairingCode)}</strong>.</p><p>The agent can run jobs within this account's existing product permissions. Choices requested by a job stay in your companion.</p><form method="post"><input type="hidden" name="csrf" value="${csrf}"><button type="submit">Allow this coding agent</button></form></main>`,
23606
+ {
23607
+ headers: {
23608
+ "Content-Type": "text/html; charset=utf-8",
23609
+ "Cache-Control": "no-store",
23610
+ "Content-Security-Policy": `default-src 'none'; form-action 'self' ${model.runtimeOrigin}; frame-ancestors 'none'; base-uri 'none'`
23611
+ }
23612
+ }
23613
+ );
23614
+ }
23615
+ if (request.method !== "POST" || request.headers.get("origin") !== origin)
23616
+ return json({ error: "not_authorized" }, 403);
23617
+ const form = await request.formData(), key = await hash(String(form.get("csrf") || "")), state = forms.get(key);
23618
+ if (!state || state.identityId !== actor.identityId || state.sessionHash !== await hash(request.headers.get("cookie") || ""))
23619
+ return json({ error: "not_authorized" }, 403);
23620
+ if (!state.approval || Date.now() - state.approval.issuedAt > 45e3) {
23621
+ state.inFlight ||= call("/subject/customer-approve", {
23622
+ attemptId: state.attemptId,
23623
+ identityId: actor.identityId,
23624
+ providerSubject: actor.providerSubject,
23625
+ binding: state.binding
23626
+ });
23627
+ try {
23628
+ const result = await state.inFlight;
23629
+ state.approval = {
23630
+ enterPath: result.enterPath,
23631
+ issuedAt: Date.now()
23632
+ };
23633
+ } finally {
23634
+ state.inFlight = void 0;
23635
+ }
23636
+ }
23637
+ const destination = new URL(
23638
+ state.approval.enterPath,
23639
+ model.runtimeOrigin
23640
+ );
23641
+ if (destination.origin !== model.runtimeOrigin || !/^\/views\/[a-f0-9]{40}\/enter$/.test(destination.pathname))
23642
+ throw Error("Invalid customer handoff");
23643
+ return Response.redirect(destination.href, 303);
23644
+ }
23645
+ };
23646
+ }
23647
+
23467
23648
  // src/customer-skill.ts
23468
23649
  function customerSkillSlug(name) {
23469
23650
  const value = name.normalize("NFKD").toLowerCase().replace(/[\u0300-\u036f]/g, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-|-$/g, "");
@@ -23494,7 +23675,7 @@ First inspect an existing .agents/skills/${slug}/subject-package.json. After dow
23494
23675
  2. Open ${model.setupUrl}/launch in the browser signed into ${model.productName}. Complete normal product sign-in if requested. Read its product-authorized one-use launch. Verify productModelId is ${JSON.stringify(model.productModelId)} and server is ${JSON.stringify(model.runtimeOrigin)}. Keep the launch private. Never request or export account cookies, OAuth tokens or a developer API key.
23495
23676
  3. Set GRANULAR_SUBJECT_PROFILE to product:${model.productModelId}. With the downloaded helper, run start --server ${JSON.stringify(model.runtimeOrigin)} --launch <returned-launch>. Open its returned companion URL. Preserve normal sign-in and explicit approval for the matching device.
23496
23677
  4. Using that same helper and profile, run activate --wait, then connect. If approval is still pending at timeout, resume the same attempt; do not issue another launch. For a matching current-session installation use skill --resume with the same output; otherwise install with skill --output .agents/skills/${slug} --product-name ${quote(model.productName)} --model ${quote(model.productModelId)}. The helper verifies the authenticated product model.
23497
- 5. Read the installed SKILL.md and REFERENCE.md. Run its subject-cli.sh context before every job; it refreshes the generated domain from the current authenticated session. Do not use stale types, substitute a model/account or fabricate setup success.
23678
+ 5. Read the installed SKILL.md. Run its subject-cli.sh context before every job, then read the returned domain or the refreshed REFERENCE.md; they contain the same current types and documentation. Do not use stale types, substitute a model/account or fabricate setup success.
23498
23679
 
23499
23680
  If the product connection is unavailable, report that exact blocker. Do not use an onboarding development-test handoff as customer installation.
23500
23681
  `;
@@ -23503,11 +23684,12 @@ function createCustomerSkillSetup(model, options) {
23503
23684
  customerSkillOrigin(options.publicOrigin);
23504
23685
  customerSkillOrigin(options.runtimeOrigin);
23505
23686
  customerSkillSlug(model.productName);
23506
- if (typeof options.resolveLaunch !== "function")
23687
+ if (typeof options.resolveLaunch !== "function" && !options.customerSession)
23507
23688
  throw Error("A product-authorized customer launch callback is required");
23508
23689
  if (model.runtimeOrigin !== options.runtimeOrigin || model.setupUrl !== `${options.publicOrigin}/agent-skills/${encodeURIComponent(model.productModelId)}/setup`)
23509
23690
  throw Error("Customer setup origin mismatch");
23510
23691
  const path10 = new URL(model.setupUrl).pathname;
23692
+ const authorization = options.customerSession ? customerSkillAuthorization(model, options.customerSession) : void 0;
23511
23693
  const headers = {
23512
23694
  "Cache-Control": "private, no-store",
23513
23695
  "X-Content-Type-Options": "nosniff",
@@ -23517,14 +23699,18 @@ function createCustomerSkillSetup(model, options) {
23517
23699
  registration: model,
23518
23700
  async fetch(request) {
23519
23701
  const url = new URL(request.url);
23520
- if (url.origin !== options.publicOrigin || request.method !== "GET")
23702
+ if (url.origin !== options.publicOrigin)
23703
+ return new Response(null, { status: 404, headers });
23704
+ const authorizedRoute = await authorization?.fetch(request);
23705
+ if (authorizedRoute) return authorizedRoute;
23706
+ if (request.method !== "GET")
23521
23707
  return new Response(null, { status: 404, headers });
23522
23708
  if (url.pathname === path10 + "/instructions")
23523
23709
  return new Response(customerSkillInstructions(model), {
23524
23710
  headers: { ...headers, "Content-Type": "text/plain; charset=utf-8" }
23525
23711
  });
23526
23712
  if (url.pathname === path10 + "/launch") {
23527
- const launch = await options.resolveLaunch(request);
23713
+ const launch = await (authorization?.resolveLaunch || options.resolveLaunch)(request);
23528
23714
  if (launch instanceof Response) {
23529
23715
  const responseHeaders = new Headers(launch.headers);
23530
23716
  for (const [key, value] of Object.entries(headers))
@@ -24176,7 +24362,7 @@ function isRetryableRecordObjectsError(error2) {
24176
24362
  }
24177
24363
  function isRetryableEffectRegistrationError(error2) {
24178
24364
  const message = error2 instanceof Error ? error2.message : String(error2);
24179
- return /timed out|websocket disconnected|websocket not connected|rpc timeout|rpc error: internal error; reference|worker restarted mid-request|network connection lost|bad gateway|gateway timeout|too many requests|(?:control plane|granular|graphql) api error \((?:429|500|502|503|504)\)/i.test(
24365
+ return /timed out|websocket error|websocket disconnected|websocket not connected|econnrefused|econnreset|socket connection was closed unexpectedly|rpc timeout|rpc error: internal error; reference|worker restarted mid-request|network connection lost|bad gateway|gateway timeout|too many requests|(?:control plane|granular|graphql) api error \((?:429|500|502|503|504)\)/i.test(
24180
24366
  message
24181
24367
  );
24182
24368
  }
@@ -26026,92 +26212,99 @@ async function invokeRegisteredEffect(effectMap, request, options = {}) {
26026
26212
  const idempotencyKey = commitRequired ? await resolveInvocationIdempotencyKey(request) : request.context?.idempotencyKey;
26027
26213
  let commitStarted = false;
26028
26214
  let commitPromise = null;
26215
+ const prepareCommit = (requestedKind, productResult) => {
26216
+ if (!declaration || !commitRequired)
26217
+ throw Error("No active commit declaration");
26218
+ let projection;
26219
+ try {
26220
+ projection = declaration.project(productResult, {
26221
+ input: request.input
26222
+ });
26223
+ validateProjectionResult(declaration, projection);
26224
+ } catch (error2) {
26225
+ const message = error2 instanceof Error ? error2.message : String(error2);
26226
+ throw new Error(
26227
+ `Product mutation may have succeeded, but its commit projection is invalid: ${message}`
26228
+ );
26229
+ }
26230
+ if (requestedKind === "transition") {
26231
+ const transition = request.context?.invocation?.transition;
26232
+ const outcome2 = projection.outcome;
26233
+ if (!transition || !outcome2?.key) {
26234
+ throw new Error(
26235
+ `Transition effect ${request.effectKey} did not resolve an authored outcome`
26236
+ );
26237
+ }
26238
+ if (!Object.prototype.hasOwnProperty.call(transition.outcomes, outcome2.key)) {
26239
+ throw new Error(
26240
+ `Transition ${transition.machine}.${transition.transition} does not declare outcome ${outcome2.key}`
26241
+ );
26242
+ }
26243
+ }
26244
+ const invocationId = request.context?.invocationId || "";
26245
+ const environmentId = request.context?.environmentId || "";
26246
+ const sandboxId = request.context?.sandboxId || "";
26247
+ if (!invocationId || !environmentId || !sandboxId || !idempotencyKey) {
26248
+ throw new Error(
26249
+ `Committed effect ${request.effectKey} is missing its trusted invocation scope`
26250
+ );
26251
+ }
26252
+ const commitRequest = {
26253
+ kind: requestedKind,
26254
+ effectKey: request.effectKey,
26255
+ effectName: request.effectName,
26256
+ operationLabel: resolved.effect.label || resolved.effect.name,
26257
+ invocationId,
26258
+ idempotencyKey,
26259
+ sandboxId,
26260
+ environmentId,
26261
+ ...request.context?.sessionId ? { sessionId: request.context.sessionId } : {},
26262
+ ...request.context?.jobId ? { jobId: request.context.jobId } : {},
26263
+ ...request.context?.buildId ? { buildId: request.context.buildId } : {},
26264
+ ...request.context?.invocation?.artifactId ? { artifactId: request.context.invocation.artifactId } : {},
26265
+ projection,
26266
+ ...requestedKind === "transition" && request.context?.invocation?.transition ? { transition: request.context.invocation.transition } : {}
26267
+ };
26268
+ return commitRequest;
26269
+ };
26029
26270
  const beginCommit = (requestedKind, productResult) => {
26030
- if (!declaration || !commitRequired || !commitTransport) {
26271
+ if (declaration?.storage)
26272
+ throw Error(
26273
+ "A storage-backed handler returns its result; the SDK acknowledges it after the source transaction"
26274
+ );
26275
+ if (!declaration || !commitRequired || !commitTransport)
26031
26276
  return Promise.reject(
26032
26277
  new Error(
26033
26278
  `Effect ${request.effectKey} does not declare an active ${requestedKind} commit`
26034
26279
  )
26035
26280
  );
26036
- }
26037
- if (declaration.kind !== requestedKind) {
26281
+ if (declaration.kind !== requestedKind)
26038
26282
  return Promise.reject(
26039
26283
  new Error(
26040
26284
  `Effect ${request.effectKey} declares ${declaration.kind} commit, not ${requestedKind}`
26041
26285
  )
26042
26286
  );
26043
- }
26044
- if (commitStarted) {
26287
+ if (commitStarted)
26045
26288
  return Promise.reject(
26046
- new Error(
26047
- `Effect invocation ${request.context?.invocationId || request.effectKey} already emitted its commit`
26048
- )
26289
+ Error("Effect invocation already emitted its commit")
26049
26290
  );
26050
- }
26051
26291
  commitStarted = true;
26052
26292
  commitPromise = (async () => {
26053
- let projection;
26293
+ let prepared;
26054
26294
  try {
26055
- projection = declaration.project(productResult);
26056
- validateProjectionResult(declaration, projection);
26295
+ prepared = prepareCommit(requestedKind, productResult);
26057
26296
  } catch (error2) {
26058
- const message = error2 instanceof Error ? error2.message : String(error2);
26059
- if (commitTransport.mappingFailed) {
26060
- await commitTransport.mappingFailed({
26061
- effectKey: request.effectKey,
26062
- effectName: request.effectName,
26063
- invocationId: request.context?.invocationId || "",
26064
- idempotencyKey: idempotencyKey || "",
26065
- environmentId: request.context?.environmentId || "",
26066
- message
26067
- });
26068
- }
26069
- throw new Error(
26070
- `Product mutation may have succeeded, but its commit projection is invalid: ${message}`
26071
- );
26072
- }
26073
- if (requestedKind === "transition") {
26074
- const transition = request.context?.invocation?.transition;
26075
- const outcome2 = projection.outcome;
26076
- if (!transition || !outcome2?.key) {
26077
- throw new Error(
26078
- `Transition effect ${request.effectKey} did not resolve an authored outcome`
26079
- );
26080
- }
26081
- if (!Object.prototype.hasOwnProperty.call(
26082
- transition.outcomes,
26083
- outcome2.key
26084
- )) {
26085
- throw new Error(
26086
- `Transition ${transition.machine}.${transition.transition} does not declare outcome ${outcome2.key}`
26087
- );
26088
- }
26089
- }
26090
- const invocationId = request.context?.invocationId || "";
26091
- const environmentId = request.context?.environmentId || "";
26092
- const sandboxId = request.context?.sandboxId || "";
26093
- if (!invocationId || !environmentId || !sandboxId || !idempotencyKey) {
26094
- throw new Error(
26095
- `Committed effect ${request.effectKey} is missing its trusted invocation scope`
26096
- );
26297
+ await commitTransport.mappingFailed?.({
26298
+ effectKey: request.effectKey,
26299
+ effectName: request.effectName,
26300
+ invocationId: context.invocationId || "",
26301
+ idempotencyKey: idempotencyKey || "",
26302
+ environmentId: context.environmentId,
26303
+ message: String(error2)
26304
+ });
26305
+ throw error2;
26097
26306
  }
26098
- const commitRequest = {
26099
- kind: requestedKind,
26100
- effectKey: request.effectKey,
26101
- effectName: request.effectName,
26102
- operationLabel: resolved.effect.label || resolved.effect.name,
26103
- invocationId,
26104
- idempotencyKey,
26105
- sandboxId,
26106
- environmentId,
26107
- ...request.context?.sessionId ? { sessionId: request.context.sessionId } : {},
26108
- ...request.context?.jobId ? { jobId: request.context.jobId } : {},
26109
- ...request.context?.buildId ? { buildId: request.context.buildId } : {},
26110
- ...request.context?.invocation?.artifactId ? { artifactId: request.context.invocation.artifactId } : {},
26111
- projection,
26112
- ...requestedKind === "transition" && request.context?.invocation?.transition ? { transition: request.context.invocation.transition } : {}
26113
- };
26114
- const receipt = await commitTransport.persist(commitRequest);
26307
+ const receipt = await commitTransport.persist(prepared);
26115
26308
  await options.commitAcknowledged?.(receipt);
26116
26309
  return receipt;
26117
26310
  })();
@@ -26149,15 +26342,44 @@ async function invokeRegisteredEffect(effectMap, request, options = {}) {
26149
26342
  let handlerResult;
26150
26343
  let handlerError;
26151
26344
  let handlerFailed = false;
26152
- try {
26345
+ const callHandler = () => {
26153
26346
  if (resolved.mode === "artifactOptions") {
26154
- handlerResult = await resolved.handler(request.input, context);
26347
+ return resolved.handler(request.input, context);
26155
26348
  } else if (resolved.effect.className && !resolved.effect.static && request.input && typeof request.input === "object" && "_objectId" in request.input) {
26156
26349
  const { _objectId, ...rest } = request.input;
26157
- handlerResult = await resolved.handler(_objectId, rest, context);
26350
+ return resolved.handler(_objectId, rest, context);
26158
26351
  } else {
26159
- handlerResult = await resolved.handler(request.input, context);
26352
+ return resolved.handler(request.input, context);
26160
26353
  }
26354
+ };
26355
+ try {
26356
+ if (commitRequired && declaration?.storage) {
26357
+ if (resolved.handler.constructor?.name === "AsyncFunction")
26358
+ throw Error(
26359
+ "SQLite commit handlers must be synchronous; no handler was executed"
26360
+ );
26361
+ const stored = declaration.storage.execute(
26362
+ {
26363
+ context,
26364
+ operationId: idempotencyKey,
26365
+ effectKey: request.effectKey,
26366
+ input: request.input
26367
+ },
26368
+ () => {
26369
+ const result = callHandler();
26370
+ if (result && typeof result.then === "function")
26371
+ throw Error("SQLite commit handlers must be synchronous");
26372
+ return { result, request: prepareCommit(declaration.kind, result) };
26373
+ }
26374
+ );
26375
+ handlerResult = stored.result;
26376
+ commitStarted = true;
26377
+ commitPromise = (async () => {
26378
+ const receipt = await commitTransport.persist(stored.request);
26379
+ await options.commitAcknowledged?.(receipt);
26380
+ return receipt;
26381
+ })();
26382
+ } else handlerResult = await callHandler();
26161
26383
  } catch (error2) {
26162
26384
  handlerFailed = true;
26163
26385
  handlerError = error2;
@@ -26217,6 +26439,152 @@ function buildEffectMetamodelMutations(toolPath, spec) {
26217
26439
  );
26218
26440
  }
26219
26441
 
26442
+ // ../job-protocol/src/provider-failure.ts
26443
+ function parseProviderFailure(value) {
26444
+ if (!value || typeof value !== "object") return;
26445
+ const r = value;
26446
+ if (r.protocol !== "granular.mutation.v1" || r.outcome !== "not_committed" || r.terminal !== true || r.fenced !== true || typeof r.operationId !== "string" || r.operationId.length > 1e3 || typeof r.fenceToken !== "string" || r.fenceToken.length > 1e3 || !["string", "number"].includes(typeof r.precondition))
26447
+ return;
26448
+ if (r.reason === "VersionConflict" || r.reason === "FencedOperation")
26449
+ return {
26450
+ protocol: r.protocol,
26451
+ outcome: r.outcome,
26452
+ terminal: true,
26453
+ fenced: true,
26454
+ operationId: r.operationId,
26455
+ precondition: r.precondition,
26456
+ fenceToken: r.fenceToken,
26457
+ reason: r.reason
26458
+ };
26459
+ if (r.reason !== "Rejected" || !r.failure || !["PolicyDenied", "InvalidInput", "ProviderFailure"].includes(
26460
+ r.failure.code
26461
+ ) || typeof r.failure.message !== "string" || r.failure.message.length > 2e3)
26462
+ return;
26463
+ const ruleIds = Array.isArray(r.failure.ruleIds) ? r.failure.ruleIds.filter((x) => typeof x === "string" && x.length <= 300).slice(0, 20) : void 0;
26464
+ return {
26465
+ protocol: r.protocol,
26466
+ outcome: r.outcome,
26467
+ terminal: true,
26468
+ fenced: true,
26469
+ operationId: r.operationId,
26470
+ precondition: r.precondition,
26471
+ fenceToken: r.fenceToken,
26472
+ reason: "Rejected",
26473
+ failure: {
26474
+ code: r.failure.code,
26475
+ message: r.failure.message,
26476
+ ...ruleIds ? { ruleIds } : {}
26477
+ }
26478
+ };
26479
+ }
26480
+
26481
+ // ../job-protocol/src/native-effect-guide.ts
26482
+ function nativeEffectReference(declarations) {
26483
+ const nativeGuide = `
26484
+
26485
+ [Native Effect jobs: Effect 4.1.2]
26486
+ A job file is a function body, not an ES-module entry point. Put documented imports first, then explicitly return the root Effect. Do not use export default, an exported main/run function, or a bare final Effect expression. Constructing an Effect does not execute it. The worker supplies the generated Invocation, Graph and Session dependencies; do not run Effect.runPromise yourself or construct replacement live services.
26487
+
26488
+ Minimal valid job file (substitute a grounded ID):
26489
+ import { Effect } from "effect";
26490
+ import { Order } from "@granular/domain";
26491
+ return Effect.gen(function* () {
26492
+ const order = yield* Order.get({ id: "grounded-order-id" });
26493
+ if (!order) return { found: false };
26494
+ const current = yield* order.read_current();
26495
+ return { id: current.id, quantity: current.quantity, version: current.version };
26496
+ });
26497
+
26498
+ Streams, filtering and bounded concurrency:
26499
+ import { Stream } from "effect";
26500
+ import { Order } from "@granular/domain";
26501
+ return Order.iterate({ perPage: 50, filter: { status: { equal_to: "ready" }, quantity: { greater_than_or_equal_to: 2 } } }).pipe(
26502
+ Stream.take(3),
26503
+ Stream.mapEffect(order => order.read_current(), { concurrency: 2 }),
26504
+ Stream.runCollect
26505
+ );
26506
+ In this Effect version, Stream.runCollect returns an array. Do not use Stream.mapEffectPar or Chunk.toReadonlyArray. Use Stream.mapEffect with its concurrency option. Use Effect.catch for typed errors and Effect.result for independent per-item success/failure; do not assume Effect.catchAll is available. Prefer inferred types over casts or suppression of compiler errors.
26507
+
26508
+ Canonical writes reserve invocation identity in the trusted runtime. Do not supply caller keys or invent a low-level action name. Use the declared record action, an expectedVersion from its authoritative read_current(), and only the fields intended to change. A new job is a separate action; rerunning an entire workflow can repeat earlier successful writes.
26509
+ After VersionConflict, read the current source, preserve concurrent changes, recompute and invoke the intended remaining action once. After PolicyDenied, respect the named rule; do not retry another key, operation or actor to bypass it.
26510
+ A timeout, disconnect or local catch does not prove that a write did not commit. Use granular job reconcile <operation-id> --session <session-id> before another write. When the ontology declares fencing, --fence can obtain terminal non-commit evidence and reject delayed delivery. If committed, use the original result rather than repeating the mutation. If not_committed is verified and fenced, read the current source before a fresh action. If evidence remains inconclusive, stay blocked.
26511
+ Use granular job inspect <job-id> --session <session-id> --json for the original error chain, handling, receipts and steering. Use granular job commit <commit-id> --session <session-id> to inspect synchronization; --retry requeues only projection work. User prompts and approvals must use the declared interaction flow, not a fabricated answer.
26512
+ `;
26513
+ const orderStart = declarations.indexOf("export type Order = EntityBase &");
26514
+ const orderEnd = declarations.indexOf(
26515
+ "export declare const Order:",
26516
+ orderStart
26517
+ );
26518
+ const orderBlock = orderStart >= 0 && orderEnd > orderStart ? declarations.slice(orderStart, orderEnd) : "";
26519
+ const filter = declarations.match(/export interface OrderFilter \{([\s\S]*?)\n\}/)?.[1] || "";
26520
+ if (orderBlock.includes("read_current(") && /\bquantity\?/.test(filter) && /\bstatus\?/.test(filter))
26521
+ return declarations + nativeGuide;
26522
+ const exampleStart = nativeGuide.indexOf("Minimal valid job file");
26523
+ const exampleEnd = nativeGuide.indexOf("In this Effect version,");
26524
+ const genericExample = `Minimal valid job file:
26525
+ import { Effect } from "effect";
26526
+ return Effect.succeed({ ok: true });
26527
+
26528
+ Use the actual generated entity's get/iterate methods for records and streams. Supply only declared search/filter fields and operators. Compose Stream.filter, Stream.take and Stream.mapEffect with bounded concurrency. Do not invent entity or action names from an example.
26529
+ `;
26530
+ const guide = nativeGuide.slice(0, exampleStart) + genericExample + nativeGuide.slice(exampleEnd);
26531
+ return declarations + guide.replace(
26532
+ "an expectedVersion from its authoritative read_current()",
26533
+ "the action's declared version precondition from its declared authoritative reader"
26534
+ );
26535
+ }
26536
+
26537
+ // ../job-protocol/src/index.ts
26538
+ function isJobDiagnostics(value) {
26539
+ if (!value || typeof value !== "object") return false;
26540
+ const v = value;
26541
+ const codes = [
26542
+ "VersionConflict",
26543
+ "FencedOperation",
26544
+ "ConcurrentMutation",
26545
+ "RetryBlocked",
26546
+ "OperationKeyMismatch",
26547
+ "PolicyDenied",
26548
+ "ApprovalRequired",
26549
+ "InvalidInput",
26550
+ "ProviderFailure",
26551
+ "TransportFailure",
26552
+ "PostconditionFailed",
26553
+ "JobLogicFailure",
26554
+ "RuntimeDefect",
26555
+ "BudgetExceeded",
26556
+ "JobTypeError",
26557
+ "JobDefect",
26558
+ "Interrupted"
26559
+ ];
26560
+ const strings3 = (x) => Array.isArray(x) && x.every((i) => typeof i === "string" && i.length <= 1e3);
26561
+ return v.version === 1 && (v.resolutions === void 0 || Array.isArray(v.resolutions) && v.resolutions.length <= 128 && v.resolutions.every(
26562
+ (r) => r && typeof r.operationId === "string" && ["committed", "not_committed"].includes(r.outcome) && ["provider_ack", "reconciliation"].includes(r.source) && Number.isFinite(r.at)
26563
+ )) && Array.isArray(v.failures) && v.failures.length <= 128 && v.failures.every(
26564
+ (f) => f && typeof f.id === "string" && typeof f.message === "string" && codes.includes(f.code) && f._tag === f.code && [
26565
+ "safety",
26566
+ "policy",
26567
+ "validation",
26568
+ "provider",
26569
+ "transport",
26570
+ "verification",
26571
+ "runtime",
26572
+ "job"
26573
+ ].includes(f.origin) && ["expected", "defect", "interruption"].includes(f.kind) && ["host", "guest"].includes(f.authority) && ["not_started", "unknown", "committed"].includes(f.commit) && (!f.causedBy || strings3(f.causedBy)) && (!f.ruleIds || strings3(f.ruleIds))
26574
+ ) && Array.isArray(v.handling) && v.handling.length <= 512 && v.handling.every(
26575
+ (h) => h && typeof h.failureId === "string" && ["caught", "retry", "propagated"].includes(h.action) && (!h.outcome || ["recovered", "failed"].includes(h.outcome)) && (!h.causedFailureIds || strings3(h.causedFailureIds))
26576
+ ) && strings3(v.unresolved) && Array.isArray(v.steering) && v.steering.every(
26577
+ (s) => s && typeof s.failureId === "string" && typeof s.action === "string" && typeof s.message === "string"
26578
+ );
26579
+ }
26580
+ var JobExecutionError = class extends Error {
26581
+ constructor(message, diagnostics) {
26582
+ super(message);
26583
+ this.diagnostics = diagnostics;
26584
+ this.name = "JobExecutionError";
26585
+ }
26586
+ };
26587
+
26220
26588
  // src/prompt-utils.ts
26221
26589
  function asRecord2(value) {
26222
26590
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
@@ -26337,17 +26705,25 @@ function resolvePromptAnswer(prompt3, answer) {
26337
26705
  return Boolean(answer);
26338
26706
  }
26339
26707
  if (prompt3.type === "choice" && Array.isArray(prompt3.options) && typeof answer === "string") {
26708
+ const exact = prompt3.options.map(normalizePromptChoiceOption).filter((option) => option.value === answer || option.label === answer);
26709
+ if (exact.length === 1) return exact[0].value;
26710
+ if (prompt3.metadata?.relationshipResolution) return answer;
26340
26711
  const normalized = normalizePromptText(answer);
26341
26712
  const tokens = extractPromptTokens(answer);
26342
26713
  let best = {
26343
26714
  score: -1,
26344
26715
  resolvedValue: null
26345
26716
  };
26717
+ let tied = false;
26346
26718
  for (const option of prompt3.options) {
26347
26719
  const scored = scorePromptChoiceMatch(normalized, tokens, option);
26348
- if (scored.score > best.score) best = scored;
26720
+ if (scored.score > best.score) {
26721
+ best = scored;
26722
+ tied = false;
26723
+ } else if (scored.score === best.score) tied = true;
26349
26724
  }
26350
- if (best.resolvedValue) return best.resolvedValue;
26725
+ if (best.score > 0 && !tied && best.resolvedValue)
26726
+ return best.resolvedValue;
26351
26727
  }
26352
26728
  return answer;
26353
26729
  }
@@ -26452,9 +26828,24 @@ var Session = class {
26452
26828
  const jobsById = recordFromUnknown(recordFromUnknown(doc)?.jobs)?.byId;
26453
26829
  const jobs = recordFromUnknown(jobsById) || {};
26454
26830
  const openPromptIds = /* @__PURE__ */ new Set();
26831
+ const terminalPromptIds = /* @__PURE__ */ new Set();
26455
26832
  for (const [jobId, jobValue] of Object.entries(jobs)) {
26456
26833
  const prompts = recordFromUnknown(recordFromUnknown(jobValue)?.prompts);
26457
26834
  if (!prompts) continue;
26835
+ const status = String(
26836
+ recordFromUnknown(jobValue)?.status || ""
26837
+ ).toLowerCase();
26838
+ if ([
26839
+ "failed",
26840
+ "succeeded",
26841
+ "completed",
26842
+ "canceled",
26843
+ "cancelled",
26844
+ "interrupted"
26845
+ ].includes(status)) {
26846
+ for (const id3 of Object.keys(prompts)) terminalPromptIds.add(id3);
26847
+ continue;
26848
+ }
26458
26849
  for (const [promptId, promptValue] of Object.entries(prompts)) {
26459
26850
  const persisted = recordFromUnknown(promptValue);
26460
26851
  if (!persisted || persisted.status !== "open") continue;
@@ -26483,7 +26874,10 @@ var Session = class {
26483
26874
  }
26484
26875
  for (const promptId of this.promptCache.keys()) {
26485
26876
  if (!openPromptIds.has(promptId)) {
26877
+ const previous = this.promptCache.get(promptId);
26486
26878
  this.promptCache.delete(promptId);
26879
+ if (previous && terminalPromptIds.has(promptId))
26880
+ this.emit("prompt:answered", { ...previous, status: "canceled" });
26487
26881
  }
26488
26882
  }
26489
26883
  }
@@ -26705,6 +27099,26 @@ var Session = class {
26705
27099
  * `effect.invoke` RPC back to the sandbox effect host, where the registered handlers
26706
27100
  * execute locally and return the result to the sandbox.
26707
27101
  */
27102
+ /** Ask the ontology-declared provider to reconcile an uncertain invocation. */
27103
+ async reconcileInvocation(operationId2, options) {
27104
+ return await this.client.call("job.reconcile", {
27105
+ operationId: operationId2,
27106
+ ...options?.fence === true ? { fence: true } : {}
27107
+ });
27108
+ }
27109
+ /** Inspect a canonical commit already recorded by this session. */
27110
+ async getCommitReceipt(commitId) {
27111
+ return await this.client.call("job.commit", {
27112
+ commitId
27113
+ });
27114
+ }
27115
+ /** Retry only graph synchronization of this session's existing product commit. */
27116
+ async retryCommitProjection(commitId) {
27117
+ return await this.client.call("job.commit", {
27118
+ commitId,
27119
+ retryProjection: true
27120
+ });
27121
+ }
26708
27122
  async submitJob(code, domainRevisionOrOptions) {
26709
27123
  const options = typeof domainRevisionOrOptions === "string" ? { domainRevision: domainRevisionOrOptions } : domainRevisionOrOptions || {};
26710
27124
  let revision2 = options.domainRevision || this.currentDomainRevision || this.extractDomainRevisionFromDoc(this.client.doc) || void 0;
@@ -26724,6 +27138,7 @@ var Session = class {
26724
27138
  domainRevision: revision2,
26725
27139
  code,
26726
27140
  metadata: options.metadata,
27141
+ runtime: options.runtime,
26727
27142
  agent: options.agent
26728
27143
  });
26729
27144
  if (!result.jobId) {
@@ -27062,7 +27477,15 @@ var Session = class {
27062
27477
  /**
27063
27478
  * Get TypeScript class declarations for the current domain (for LLM/code gen).
27064
27479
  */
27065
- async getDomainTypes() {
27480
+ async getDomainTypes(options) {
27481
+ if (options?.runtime === "effect") {
27482
+ const result = await this.client.call("domain.fetchPackagePart", {
27483
+ moduleSpecifier: "@sandbox/domain",
27484
+ part: "types",
27485
+ runtime: "effect"
27486
+ });
27487
+ return result.content;
27488
+ }
27066
27489
  return this.fetchDomainPart("types");
27067
27490
  }
27068
27491
  /**
@@ -27074,7 +27497,11 @@ var Session = class {
27074
27497
  /**
27075
27498
  * Get domain documentation for LLMs. Returns types (preferred) or fallback.
27076
27499
  */
27077
- async getDomainDocumentation() {
27500
+ async getDomainDocumentation(options) {
27501
+ if (options?.runtime === "effect") {
27502
+ const declarations = await this.getDomainTypes(options);
27503
+ return nativeEffectReference(declarations);
27504
+ }
27078
27505
  const [types, docs] = await Promise.all([
27079
27506
  this.getDomainTypes(),
27080
27507
  this.getDomainDocs()
@@ -27386,6 +27813,7 @@ import { ${tools[0]?.name || "example"} } from "@granular/actions/backend";
27386
27813
  this.client.on("harness.text_response.delta", (data) => {
27387
27814
  this.emit("harness:text_response_delta", data);
27388
27815
  });
27816
+ this.client.on("job.telemetry", (data) => this.emit("job:telemetry", data));
27389
27817
  this.client.on("exec.completed", (data) => {
27390
27818
  this.emit("exec:completed", data);
27391
27819
  });
@@ -27514,6 +27942,7 @@ var JobImplementation = class {
27514
27942
  id;
27515
27943
  client;
27516
27944
  status = "queued";
27945
+ diagnostics;
27517
27946
  _resultPromise;
27518
27947
  _resolveResult;
27519
27948
  _rejectResult;
@@ -27537,6 +27966,34 @@ var JobImplementation = class {
27537
27966
  this._resolveResult = resolve8;
27538
27967
  this._rejectResult = reject2;
27539
27968
  });
27969
+ const capture = (value) => {
27970
+ if ((value?.jobId === id3 || value?.execId === id3) && isJobDiagnostics(value.diagnostics))
27971
+ this.diagnostics = value.diagnostics;
27972
+ };
27973
+ for (const event of [
27974
+ "exec.completed",
27975
+ "job.completed",
27976
+ "job.failed",
27977
+ "exec.failed"
27978
+ ])
27979
+ this.client.on(event, capture);
27980
+ const sync = () => {
27981
+ const record3 = this.client.doc?.jobs?.byId?.[id3];
27982
+ if (!record3) return;
27983
+ if (isJobDiagnostics(record3.metadata?.diagnostics))
27984
+ this.diagnostics = JSON.parse(
27985
+ JSON.stringify(record3.metadata.diagnostics)
27986
+ );
27987
+ if (["succeeded", "failed", "timeout", "canceled"].includes(record3.status))
27988
+ this.finalize(record3.status, record3.result, record3.error, {
27989
+ hasResult: record3.status === "succeeded"
27990
+ });
27991
+ };
27992
+ this.client.on("sync", sync);
27993
+ queueMicrotask(sync);
27994
+ this.client.on("job.telemetry", (data) => {
27995
+ if (data?.jobId === id3) this.emit("telemetry", data);
27996
+ });
27540
27997
  this.client.on("exec.completed", (data) => {
27541
27998
  const execData = data;
27542
27999
  if (execData.execId === id3 || execData.jobId === id3) {
@@ -27770,7 +28227,7 @@ var JobImplementation = class {
27770
28227
  const message = cause instanceof Error ? cause.message : String(cause);
27771
28228
  this.metadata.error = truncateFeedbackString(message);
27772
28229
  this.resultSettled = true;
27773
- this._rejectResult(cause);
28230
+ this._rejectResult(new JobExecutionError(message, this.diagnostics));
27774
28231
  }
27775
28232
  }
27776
28233
  upsertToolCall(next) {
@@ -27816,9 +28273,9 @@ function trimString(value) {
27816
28273
  function compactJson(value, maxLength = 320) {
27817
28274
  if (value === void 0 || value === null) return void 0;
27818
28275
  try {
27819
- const json = JSON.stringify(value);
27820
- if (!json || json === "undefined") return void 0;
27821
- return json.length > maxLength ? `${json.slice(0, maxLength)}...` : json;
28276
+ const json2 = JSON.stringify(value);
28277
+ if (!json2 || json2 === "undefined") return void 0;
28278
+ return json2.length > maxLength ? `${json2.slice(0, maxLength)}...` : json2;
27822
28279
  } catch {
27823
28280
  return String(value);
27824
28281
  }
@@ -27838,9 +28295,9 @@ function stringifyTranscriptValue(value, fallback2 = "") {
27838
28295
  if (typeof value === "boolean") return value ? "Confirmed" : "Canceled";
27839
28296
  if (value === void 0) return fallback2;
27840
28297
  try {
27841
- const json = JSON.stringify(value, null, 2);
27842
- if (!json || json === "undefined") return fallback2;
27843
- return json.length > 2e3 ? `${json.slice(0, 2e3)}...` : json;
28298
+ const json2 = JSON.stringify(value, null, 2);
28299
+ if (!json2 || json2 === "undefined") return fallback2;
28300
+ return json2.length > 2e3 ? `${json2.slice(0, 2e3)}...` : json2;
27844
28301
  } catch {
27845
28302
  return String(value);
27846
28303
  }
@@ -28292,6 +28749,7 @@ function rpcTimeoutMsForMethod(method) {
28292
28749
  switch (method) {
28293
28750
  case "domain.fetchPackagePart":
28294
28751
  case "domain.getSummary":
28752
+ case "domain.getHarnessContext":
28295
28753
  return DOMAIN_PACKAGE_RPC_TIMEOUT_MS;
28296
28754
  case "effects.publishCatalog":
28297
28755
  case "effects.resetCatalog":
@@ -28299,6 +28757,7 @@ function rpcTimeoutMsForMethod(method) {
28299
28757
  case "effects.removeCatalog":
28300
28758
  case "effects.refresh":
28301
28759
  case "harness.prepare":
28760
+ case "job.submitSubject":
28302
28761
  return EFFECT_CONTROL_RPC_TIMEOUT_MS;
28303
28762
  case "harness.run":
28304
28763
  return HARNESS_RUN_RPC_TIMEOUT_MS;
@@ -28720,8 +29179,9 @@ var WSClient = class {
28720
29179
  );
28721
29180
  this.reconnectTimer = setTimeout(() => {
28722
29181
  this.reconnectTimer = null;
28723
- console.log("[Granular] Attempting reconnect...");
29182
+ console.error("[Granular] Attempting reconnect...");
28724
29183
  this.connect().catch((error2) => {
29184
+ if (this.isExplicitlyDisconnected) return;
28725
29185
  console.error("[Granular] Reconnect failed:", error2);
28726
29186
  this.emitReconnectErrorMessage(
28727
29187
  error2 instanceof Error ? error2.message : String(error2)
@@ -28821,11 +29281,11 @@ var WSClient = class {
28821
29281
  return true;
28822
29282
  }
28823
29283
  exposeCanonicalQuarantine(replacement, currentCanonical, error2) {
28824
- const version2 = documentVersion(replacement);
29284
+ const version3 = documentVersion(replacement);
28825
29285
  if (currentCanonical) {
28826
29286
  const quarantine2 = Object.freeze({
28827
- documentEpoch: version2.epoch,
28828
- documentRevision: version2.revision,
29287
+ documentEpoch: version3.epoch,
29288
+ documentRevision: version3.revision,
28829
29289
  error: new Error(error2.message)
28830
29290
  });
28831
29291
  for (const handler of this.canonicalDocumentQuarantineHandlers) {
@@ -28836,8 +29296,8 @@ var WSClient = class {
28836
29296
  const accepted = Automerge__namespace.toJS(this.doc);
28837
29297
  const quarantine = Automerge__namespace.from({
28838
29298
  ...accepted,
28839
- documentEpoch: version2.epoch,
28840
- documentRevision: version2.revision,
29299
+ documentEpoch: version3.epoch,
29300
+ documentRevision: version3.revision,
28841
29301
  feed: {
28842
29302
  activation: { mode: "canonical" }
28843
29303
  }
@@ -29255,7 +29715,12 @@ var WSClient = class {
29255
29715
  id: request.id,
29256
29716
  error: {
29257
29717
  code: -32e3,
29258
- message: error2 instanceof Error ? error2.message : "Unknown error"
29718
+ message: error2 instanceof Error ? error2.message : "Unknown error",
29719
+ ...parseProviderFailure(error2?.providerFailure) ? {
29720
+ providerFailure: parseProviderFailure(
29721
+ error2.providerFailure
29722
+ )
29723
+ } : {}
29259
29724
  }
29260
29725
  };
29261
29726
  this.ws?.send(JSON.stringify(errorResponse));
@@ -29539,7 +30004,7 @@ function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId, effectH
29539
30004
  } else if (url.protocol === "http:") {
29540
30005
  url.protocol = "ws:";
29541
30006
  }
29542
- if (!overrideUrl && isLocalControlUrl(apiUrl) && !localRuntimeBase && api.pathname.endsWith("/granular")) {
30007
+ if (url.pathname.endsWith("/effects/connect")) ; else if (!overrideUrl && isLocalControlUrl(apiUrl) && !localRuntimeBase && api.pathname.endsWith("/granular")) {
29543
30008
  url.pathname = "/granular/effects/connect";
29544
30009
  } else if (url.pathname.endsWith("/granular/ws/connect")) {
29545
30010
  url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
@@ -31041,6 +31506,7 @@ var Environment = class _Environment {
31041
31506
  * synchronous commit of every row is not required.
31042
31507
  */
31043
31508
  async recordObjects(records, options) {
31509
+ options?.signal?.throwIfAborted();
31044
31510
  if (!Array.isArray(records) || records.length === 0) {
31045
31511
  return [];
31046
31512
  }
@@ -31062,10 +31528,12 @@ var Environment = class _Environment {
31062
31528
  const onChunk = options?.onChunkComplete;
31063
31529
  for (let waveStart = 0; waveStart < plans.length; waveStart += concurrency) {
31064
31530
  const wave = plans.slice(waveStart, waveStart + concurrency);
31531
+ options?.signal?.throwIfAborted();
31065
31532
  await Promise.all(
31066
31533
  wave.map(async (plan) => {
31067
31534
  const { items, durationMs } = await this.executeRecordObjectsChunk(
31068
- plan.slice
31535
+ plan.slice,
31536
+ options?.signal
31069
31537
  );
31070
31538
  if (items.length !== plan.slice.length) {
31071
31539
  throw new Error(
@@ -31097,19 +31565,22 @@ var Environment = class _Environment {
31097
31565
  }
31098
31566
  return results;
31099
31567
  }
31100
- async executeRecordObjectsChunk(chunk) {
31568
+ async executeRecordObjectsChunk(chunk, signal) {
31101
31569
  const wallStart = Date.now();
31102
31570
  let lastError;
31103
31571
  for (let attempt = 1; attempt <= DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_COUNT; attempt += 1) {
31572
+ signal?.throwIfAborted();
31104
31573
  try {
31105
31574
  const response = await this.controlPlaneRequest(`/control/environments/${this.environmentId}/records/batch`, {
31106
31575
  method: "POST",
31107
- body: JSON.stringify({ records: chunk })
31576
+ body: JSON.stringify({ records: chunk }),
31577
+ signal
31108
31578
  });
31109
31579
  const items = Array.isArray(response.items) ? response.items : [];
31110
31580
  return { items, durationMs: Date.now() - wallStart };
31111
31581
  } catch (error2) {
31112
31582
  lastError = error2;
31583
+ if (signal?.aborted) throw error2;
31113
31584
  if (!isRetryableRecordObjectsError(error2) || attempt === DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_COUNT) {
31114
31585
  throw error2;
31115
31586
  }
@@ -31426,6 +31897,7 @@ var EnvironmentSession = class extends Session {
31426
31897
  }
31427
31898
  get jobs() {
31428
31899
  return {
31900
+ events: (jobId, options = {}) => this.sessionDataRequest(`/jobs/${encodeURIComponent(jobId)}/events`, options),
31429
31901
  list: (options = {}) => this.sessionDataRequest(
31430
31902
  "/jobs",
31431
31903
  options
@@ -31869,18 +32341,26 @@ var OntologyHandle = class {
31869
32341
  return this.granular.registerUsers(this.ontologyNameOrId, handler, options);
31870
32342
  }
31871
32343
  get customerSkill() {
31872
- return { register: (options) => this.granular.registerCustomerSkill(this.ontologyNameOrId, options) };
32344
+ return {
32345
+ register: (options) => this.granular.registerCustomerSkill(this.ontologyNameOrId, options)
32346
+ };
31873
32347
  }
31874
32348
  get development() {
31875
32349
  return {
31876
- register: (options) => this.granular.registerDevelopmentProvider(this.ontologyNameOrId, options)
32350
+ register: (options) => this.granular.registerDevelopmentProvider(
32351
+ this.ontologyNameOrId,
32352
+ options
32353
+ )
31877
32354
  };
31878
32355
  }
31879
32356
  get importer() {
31880
32357
  return {
31881
32358
  /** Register and publish on the existing backend provider connection. */
31882
32359
  register: async (handler) => {
31883
- this.granular.registerEnvironmentImporter(this.ontologyNameOrId, handler);
32360
+ this.granular.registerEnvironmentImporter(
32361
+ this.ontologyNameOrId,
32362
+ handler
32363
+ );
31884
32364
  await this.granular.connectEnvironmentImporter(this.ontologyNameOrId);
31885
32365
  },
31886
32366
  onEnvironmentCreate: (handler) => this.granular.registerEnvironmentImporter(
@@ -31914,6 +32394,8 @@ var Granular = class _Granular {
31914
32394
  usersProviders = /* @__PURE__ */ new Map();
31915
32395
  /** In-flight host connection promises to avoid duplicate concurrent connects */
31916
32396
  sandboxEffectHostPromises = /* @__PURE__ */ new Map();
32397
+ effectHostGenerations = /* @__PURE__ */ new Map();
32398
+ effectHostRecovery = /* @__PURE__ */ new Map();
31917
32399
  /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
31918
32400
  ontologyImporters = /* @__PURE__ */ new Map();
31919
32401
  /** Resolved importer hooks keyed by sandboxId for fast lookups during openEnvironment(). */
@@ -31965,7 +32447,10 @@ var Granular = class _Granular {
31965
32447
  }
31966
32448
  async connectEnvironmentImporter(ontologyNameOrId) {
31967
32449
  const sandboxId = await this._resolveSandboxId(ontologyNameOrId);
31968
- const importer = this.resolveEnvironmentImporter(ontologyNameOrId, sandboxId);
32450
+ const importer = this.resolveEnvironmentImporter(
32451
+ ontologyNameOrId,
32452
+ sandboxId
32453
+ );
31969
32454
  if (!importer) throw new Error("No environment importer registered.");
31970
32455
  const host = await this.ensureSandboxEffectHost(sandboxId);
31971
32456
  await host.wsClient.call("environment.importer.register", {});
@@ -32281,7 +32766,9 @@ var Granular = class _Granular {
32281
32766
  async runBoundEnvironmentImporter(environmentId, options, verifiedIdentity) {
32282
32767
  const environmentData = await this.environments.get(environmentId);
32283
32768
  if (options.expectedSubjectId && environmentData.subjectId !== options.expectedSubjectId) {
32284
- throw new Error("Importer environment does not match the authenticated subject.");
32769
+ throw new Error(
32770
+ "Importer environment does not match the authenticated subject."
32771
+ );
32285
32772
  }
32286
32773
  const subject = await this.request(
32287
32774
  `/control/subjects/${encodeURIComponent(environmentData.subjectId)}`
@@ -32290,7 +32777,9 @@ var Granular = class _Granular {
32290
32777
  throw new Error("Importer canonical identity changed.");
32291
32778
  const externalUserId = verifiedIdentity?.externalUserId || subject.userId || subject.identityId;
32292
32779
  if ((subject.subjectId || subject.granularId) !== environmentData.subjectId || !externalUserId || options.expectedExternalUserId && options.expectedExternalUserId !== externalUserId) {
32293
- throw new Error("Importer subject has no matching canonical product identity.");
32780
+ throw new Error(
32781
+ "Importer subject has no matching canonical product identity."
32782
+ );
32294
32783
  }
32295
32784
  const environment = this.bindEnvironmentHandle(environmentData);
32296
32785
  const requestedOntology = options.ontology || environmentData.ontologyId || environmentData.sandboxId;
@@ -32885,7 +33374,9 @@ var Granular = class _Granular {
32885
33374
  }
32886
33375
  );
32887
33376
  if (!setupRun || resolved.existingSetupRunId && setupRun.setupRunId !== resolved.existingSetupRunId || setupRun.environmentId !== environment.environmentId || setupRun.sandboxId !== resolved.sandboxId || setupRun.subjectId !== resolved.subjectId)
32888
- throw new Error("Importer setup does not match the canonical environment.");
33377
+ throw new Error(
33378
+ "Importer setup does not match the canonical environment."
33379
+ );
32889
33380
  const setupRunId = setupRun.setupRunId;
32890
33381
  let claim = null;
32891
33382
  for (let attempt = 0; attempt < 3; attempt += 1) {
@@ -33139,47 +33630,99 @@ var Granular = class _Granular {
33139
33630
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
33140
33631
  }
33141
33632
  recoverEffectHost(host, error2) {
33142
- if (host.recovering) {
33143
- return;
33144
- }
33145
- if (this.sandboxEffectHosts.get(host.sandboxId) !== host) {
33633
+ const sandboxId = host.sandboxId;
33634
+ if (host.recovering || this.sandboxEffectHosts.get(sandboxId) !== host)
33146
33635
  return;
33147
- }
33148
33636
  host.recovering = true;
33149
- this.stopEffectHostHeartbeat(host);
33150
- this.sandboxEffectHosts.delete(host.sandboxId);
33151
- try {
33152
- host.wsClient.disconnect();
33153
- } catch (disconnectError) {
33154
- console.warn(
33155
- `[Granular] Failed to disconnect stale effect host for sandbox ${host.sandboxId}:`,
33156
- disconnectError
33157
- );
33158
- }
33159
- void this.ensureSandboxEffectHost(host.sandboxId).catch(
33160
- (reconnectError) => {
33161
- console.error(
33162
- `[Granular] Failed to recover effect host for sandbox ${host.sandboxId} after heartbeat failure:`,
33637
+ this.disconnectSandboxEffectHost(sandboxId);
33638
+ const state = {
33639
+ attempt: 0,
33640
+ generation: this.effectHostGenerations.get(sandboxId) || 0,
33641
+ timer: void 0
33642
+ };
33643
+ this.effectHostRecovery.set(sandboxId, state);
33644
+ const active = () => this.effectHostRecovery.get(sandboxId) === state && this.effectHostGenerations.get(sandboxId) === state.generation && (!!this.sandboxEffects.get(sandboxId)?.size || this.usersProviders.has(sandboxId) || this.developmentProviders.has(sandboxId) || !!this.resolveEnvironmentImporter(sandboxId, sandboxId));
33645
+ const reconnect = async () => {
33646
+ if (!active()) return;
33647
+ try {
33648
+ await this.ensureSandboxEffectHost(sandboxId);
33649
+ if (active()) this.effectHostRecovery.delete(sandboxId);
33650
+ } catch (reconnectError) {
33651
+ if (!active()) return;
33652
+ const retryable = isRetryableEffectRegistrationError(reconnectError);
33653
+ console.warn(
33654
+ `[Granular] Effect host ${sandboxId} connection failed; registered handlers are retained.`,
33163
33655
  reconnectError
33164
33656
  );
33165
- console.error("[Granular] Original heartbeat failure:", error2);
33166
- if (this.onReconnectError) {
33167
- try {
33168
- this.onReconnectError({
33169
- sessionId: `effect-host:${host.effectClientId}`,
33170
- error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError),
33171
- timestamp: Date.now(),
33172
- terminal: false
33173
- });
33174
- } catch (callbackError) {
33175
- console.error(
33176
- "[Granular] onReconnectError callback failed after effect-host recovery failure:",
33177
- callbackError
33178
- );
33179
- }
33657
+ try {
33658
+ this.onReconnectError?.({
33659
+ sessionId: `effect-host:${host.effectClientId}`,
33660
+ error: reconnectError instanceof Error ? reconnectError.message : String(reconnectError),
33661
+ timestamp: Date.now(),
33662
+ terminal: !retryable
33663
+ });
33664
+ } catch (callbackError) {
33665
+ console.error(
33666
+ "[Granular] onReconnectError callback failed:",
33667
+ callbackError
33668
+ );
33669
+ }
33670
+ if (!retryable) {
33671
+ this.effectHostRecovery.delete(sandboxId);
33672
+ return;
33180
33673
  }
33674
+ const delay = Math.min(3e4, 1e3 * 2 ** Math.min(state.attempt++, 5));
33675
+ state.timer = setTimeout(() => void reconnect(), delay);
33676
+ state.timer.unref?.();
33181
33677
  }
33678
+ };
33679
+ void reconnect();
33680
+ }
33681
+ effectCommitTransport() {
33682
+ return {
33683
+ persist: (request) => this.request(
33684
+ `/control/environments/${encodeURIComponent(request.environmentId)}/commits`,
33685
+ {
33686
+ method: "POST",
33687
+ body: JSON.stringify({
33688
+ kind: request.kind,
33689
+ invocationId: request.invocationId,
33690
+ idempotencyKey: request.idempotencyKey,
33691
+ effectKey: request.effectKey,
33692
+ projection: request.projection
33693
+ })
33694
+ }
33695
+ ),
33696
+ mappingFailed: (failure) => this.request(
33697
+ `/control/environments/${encodeURIComponent(failure.environmentId)}/commit-invocations/${encodeURIComponent(failure.invocationId)}`,
33698
+ {
33699
+ method: "PATCH",
33700
+ body: JSON.stringify({
33701
+ status: "mapping_failed",
33702
+ error: {
33703
+ code: "commit_projection_mapping_failed",
33704
+ message: failure.message,
33705
+ retryable: false
33706
+ }
33707
+ })
33708
+ }
33709
+ )
33710
+ };
33711
+ }
33712
+ async recoverSourceCommits(host) {
33713
+ const stores = new Set(
33714
+ Array.from(this.getSandboxEffectMap(host.sandboxId).values()).map((effect) => effect.commit?.storage).filter(Boolean)
33182
33715
  );
33716
+ for (const store of stores) {
33717
+ try {
33718
+ await store.recover(this.effectCommitTransport(), host.sandboxId);
33719
+ } catch (error2) {
33720
+ console.warn(
33721
+ "[Granular] Source commit delivery remains pending:",
33722
+ String(error2)
33723
+ );
33724
+ }
33725
+ }
33183
33726
  }
33184
33727
  startEffectHostHeartbeat(host) {
33185
33728
  if (host.heartbeatTimer) {
@@ -33191,7 +33734,7 @@ var Granular = class _Granular {
33191
33734
  return;
33192
33735
  }
33193
33736
  host.heartbeatInFlight = true;
33194
- host.wsClient.call("client.heartbeat", {}).catch((error2) => {
33737
+ host.wsClient.call("client.heartbeat", {}).then(() => this.recoverSourceCommits(host)).catch((error2) => {
33195
33738
  console.warn(`${failureLabel} ${host.sandboxId}:`, error2);
33196
33739
  if (recoverOnFailure) {
33197
33740
  this.recoverEffectHost(host, error2);
@@ -33245,18 +33788,45 @@ var Granular = class _Granular {
33245
33788
  /** Publish only public setup metadata; product session authority stays in resolveLaunch. */
33246
33789
  async registerCustomerSkill(ontologyNameOrId, options) {
33247
33790
  const productModelId = await this._resolveSandboxId(ontologyNameOrId);
33248
- const model = await this.request(`/control/sandboxes/${encodeURIComponent(productModelId)}`);
33249
- const registration = { productModelId, productName: model.name, setupUrl: `${options.publicOrigin}/agent-skills/${encodeURIComponent(productModelId)}/setup`, runtimeOrigin: options.runtimeOrigin };
33791
+ const model = await this.request(
33792
+ `/control/sandboxes/${encodeURIComponent(productModelId)}`
33793
+ );
33794
+ const registration = {
33795
+ productModelId,
33796
+ productName: model.name,
33797
+ setupUrl: `${options.publicOrigin}/agent-skills/${encodeURIComponent(productModelId)}/setup`,
33798
+ runtimeOrigin: options.runtimeOrigin
33799
+ };
33250
33800
  const handler = createCustomerSkillSetup(registration, options);
33251
- await this.request(`/control/sandboxes/${encodeURIComponent(productModelId)}/customer-skill`, { method: "PUT", body: JSON.stringify({ setupUrl: registration.setupUrl, runtimeOrigin: registration.runtimeOrigin }) });
33252
- return { registration: handler.registration, fetch: async (request) => {
33253
- try {
33254
- const current = await this.request(`/control/sandboxes/${encodeURIComponent(productModelId)}`);
33255
- return createCustomerSkillSetup({ ...registration, productName: current.name }, options).fetch(request);
33256
- } catch {
33257
- return Response.json({ error: "product_setup_unavailable" }, { status: 503, headers: { "Cache-Control": "no-store" } });
33801
+ await this.request(
33802
+ `/control/sandboxes/${encodeURIComponent(productModelId)}/customer-skill`,
33803
+ {
33804
+ method: "PUT",
33805
+ body: JSON.stringify({
33806
+ setupUrl: registration.setupUrl,
33807
+ runtimeOrigin: registration.runtimeOrigin
33808
+ })
33258
33809
  }
33259
- } };
33810
+ );
33811
+ return {
33812
+ registration: handler.registration,
33813
+ fetch: async (request) => {
33814
+ try {
33815
+ const current = await this.request(
33816
+ `/control/sandboxes/${encodeURIComponent(productModelId)}`
33817
+ );
33818
+ return createCustomerSkillSetup(
33819
+ { ...registration, productName: current.name },
33820
+ options
33821
+ ).fetch(request);
33822
+ } catch {
33823
+ return Response.json(
33824
+ { error: "product_setup_unavailable" },
33825
+ { status: 503, headers: { "Cache-Control": "no-store" } }
33826
+ );
33827
+ }
33828
+ }
33829
+ };
33260
33830
  }
33261
33831
  /** Register product-owned dev operator callbacks on the existing provider socket. */
33262
33832
  async registerDevelopmentProvider(ontologyNameOrId, options) {
@@ -33281,8 +33851,12 @@ var Granular = class _Granular {
33281
33851
  }
33282
33852
  }
33283
33853
  async registerDevelopmentOnHost(host, provider) {
33284
- const registration = await host.wsClient.call("onboarding.register", provider.registrationParams());
33285
- if (this.developmentProviders.get(host.sandboxId) !== provider) throw new Error("Development registration was replaced.");
33854
+ const registration = await host.wsClient.call(
33855
+ "onboarding.register",
33856
+ provider.registrationParams()
33857
+ );
33858
+ if (this.developmentProviders.get(host.sandboxId) !== provider)
33859
+ throw new Error("Development registration was replaced.");
33286
33860
  provider.bind(registration, host.sandboxId, host.effectClientId);
33287
33861
  }
33288
33862
  async synchronizeEffectHost(host) {
@@ -33316,10 +33890,9 @@ var Granular = class _Granular {
33316
33890
  if (existing) {
33317
33891
  return existing;
33318
33892
  }
33893
+ const generation2 = this.effectHostGenerations.get(sandboxId) || 0;
33319
33894
  const inflight = this.sandboxEffectHostPromises.get(sandboxId);
33320
- if (inflight) {
33321
- return inflight;
33322
- }
33895
+ if (inflight?.generation === generation2) return inflight.promise;
33323
33896
  const connectPromise = (async () => {
33324
33897
  const effectClientId = crypto.randomUUID();
33325
33898
  const clientId = `effect-host:${sandboxId}:${effectClientId}`;
@@ -33339,6 +33912,7 @@ var Granular = class _Granular {
33339
33912
  onReconnectError: this.onReconnectError
33340
33913
  });
33341
33914
  const host = {
33915
+ generation: generation2,
33342
33916
  sandboxId,
33343
33917
  effectClientId,
33344
33918
  clientId,
@@ -33348,29 +33922,58 @@ var Granular = class _Granular {
33348
33922
  recovering: false,
33349
33923
  syncPromise: null
33350
33924
  };
33351
- wsClient.registerRpcHandler("environment.import", async (params) => {
33352
- const p = params;
33353
- if (!p || p.sandboxId !== sandboxId || !p.environmentId || !p.setupRunId || !p.subjectId || !p.identityId || !p.externalUserId) throw new Error("Invalid importer scope.");
33354
- const current = await this.environments.get(p.environmentId);
33355
- if (current.sandboxId !== sandboxId || current.buildId !== p.buildId || (current.envName || current.environment) !== p.environment || current.subjectId !== p.subjectId) throw new Error("Importer environment changed.");
33356
- return this.runBoundEnvironmentImporter(p.environmentId, { ontology: sandboxId, setupRunId: p.setupRunId, expectedSubjectId: p.subjectId, expectedExternalUserId: p.externalUserId }, { identityId: p.identityId, externalUserId: p.externalUserId });
33357
- });
33925
+ wsClient.registerRpcHandler(
33926
+ "environment.import",
33927
+ async (params) => {
33928
+ const p = params;
33929
+ if (!p || p.sandboxId !== sandboxId || !p.environmentId || !p.setupRunId || !p.subjectId || !p.identityId || !p.externalUserId)
33930
+ throw new Error("Invalid importer scope.");
33931
+ const current = await this.environments.get(p.environmentId);
33932
+ if (current.sandboxId !== sandboxId || current.buildId !== p.buildId || (current.envName || current.environment) !== p.environment || current.subjectId !== p.subjectId)
33933
+ throw new Error("Importer environment changed.");
33934
+ return this.runBoundEnvironmentImporter(
33935
+ p.environmentId,
33936
+ {
33937
+ ontology: sandboxId,
33938
+ setupRunId: p.setupRunId,
33939
+ expectedSubjectId: p.subjectId,
33940
+ expectedExternalUserId: p.externalUserId
33941
+ },
33942
+ { identityId: p.identityId, externalUserId: p.externalUserId }
33943
+ );
33944
+ }
33945
+ );
33358
33946
  wsClient.registerRpcHandler("users.invoke", async (params) => {
33359
33947
  const provider = this.usersProviders.get(sandboxId);
33360
- if (!provider) throw new Error("No user directory is registered for this ontology.");
33948
+ if (!provider)
33949
+ throw new Error("No user directory is registered for this ontology.");
33361
33950
  const input = params;
33362
33951
  return input?.page ? provider.invoke(input.page) : provider.invoke();
33363
33952
  });
33364
- wsClient.registerRpcHandler("users.resolveMembership", async (params) => {
33365
- const provider = this.usersProviders.get(sandboxId);
33366
- if (!provider) throw new Error("No user directory is registered for this ontology.");
33367
- return provider.resolveMembership(params);
33368
- });
33369
- wsClient.registerRpcHandler("onboarding.invoke", async (params) => {
33370
- const provider = this.developmentProviders.get(sandboxId);
33371
- if (!provider) throw new Error("No development handlers are registered for this sandbox.");
33372
- return provider.invoke(params);
33373
- });
33953
+ wsClient.registerRpcHandler(
33954
+ "users.resolveMembership",
33955
+ async (params) => {
33956
+ const provider = this.usersProviders.get(sandboxId);
33957
+ if (!provider)
33958
+ throw new Error(
33959
+ "No user directory is registered for this ontology."
33960
+ );
33961
+ return provider.resolveMembership(
33962
+ params
33963
+ );
33964
+ }
33965
+ );
33966
+ wsClient.registerRpcHandler(
33967
+ "onboarding.invoke",
33968
+ async (params) => {
33969
+ const provider = this.developmentProviders.get(sandboxId);
33970
+ if (!provider)
33971
+ throw new Error(
33972
+ "No development handlers are registered for this sandbox."
33973
+ );
33974
+ return provider.invoke(params);
33975
+ }
33976
+ );
33374
33977
  wsClient.registerRpcHandler("effect.invoke", async (params) => {
33375
33978
  const request = params;
33376
33979
  let commitReceipt;
@@ -33381,41 +33984,7 @@ var Granular = class _Granular {
33381
33984
  commitAcknowledged: (receipt) => {
33382
33985
  commitReceipt = receipt;
33383
33986
  },
33384
- commit: {
33385
- persist: (commitRequest) => this.request(
33386
- `/control/environments/${encodeURIComponent(
33387
- commitRequest.environmentId
33388
- )}/commits`,
33389
- {
33390
- method: "POST",
33391
- body: JSON.stringify({
33392
- kind: commitRequest.kind,
33393
- invocationId: commitRequest.invocationId,
33394
- idempotencyKey: commitRequest.idempotencyKey,
33395
- effectKey: commitRequest.effectKey,
33396
- projection: commitRequest.projection
33397
- })
33398
- }
33399
- ),
33400
- mappingFailed: (failure) => this.request(
33401
- `/control/environments/${encodeURIComponent(
33402
- failure.environmentId
33403
- )}/commit-invocations/${encodeURIComponent(
33404
- failure.invocationId
33405
- )}`,
33406
- {
33407
- method: "PATCH",
33408
- body: JSON.stringify({
33409
- status: "mapping_failed",
33410
- error: {
33411
- code: "commit_projection_mapping_failed",
33412
- message: failure.message,
33413
- retryable: false
33414
- }
33415
- })
33416
- }
33417
- )
33418
- },
33987
+ commit: this.effectCommitTransport(),
33419
33988
  feedback: {
33420
33989
  invocationId: request.callId,
33421
33990
  publish: (method, publishParams) => wsClient.call(method, publishParams)
@@ -33434,6 +34003,7 @@ var Granular = class _Granular {
33434
34003
  `[Granular] Failed to re-sync effect host for sandbox ${sandboxId}:`,
33435
34004
  error2
33436
34005
  );
34006
+ this.recoverEffectHost(host, error2);
33437
34007
  });
33438
34008
  });
33439
34009
  wsClient.on("disconnect", () => {
@@ -33450,6 +34020,8 @@ var Granular = class _Granular {
33450
34020
  `effect host WebSocket connect for sandbox ${sandboxId}`
33451
34021
  );
33452
34022
  await this.synchronizeEffectHost(host);
34023
+ if ((this.effectHostGenerations.get(sandboxId) || 0) !== generation2)
34024
+ throw new Error("Effect host connection was canceled");
33453
34025
  this.sandboxEffectHosts.set(sandboxId, host);
33454
34026
  return host;
33455
34027
  } catch (error2) {
@@ -33458,21 +34030,32 @@ var Granular = class _Granular {
33458
34030
  throw error2;
33459
34031
  }
33460
34032
  })();
33461
- this.sandboxEffectHostPromises.set(sandboxId, connectPromise);
34033
+ this.sandboxEffectHostPromises.set(sandboxId, {
34034
+ generation: generation2,
34035
+ promise: connectPromise
34036
+ });
33462
34037
  try {
33463
34038
  return await connectPromise;
33464
34039
  } finally {
33465
- this.sandboxEffectHostPromises.delete(sandboxId);
34040
+ if (this.sandboxEffectHostPromises.get(sandboxId)?.promise === connectPromise)
34041
+ this.sandboxEffectHostPromises.delete(sandboxId);
33466
34042
  }
33467
34043
  }
33468
34044
  disconnectSandboxEffectHost(sandboxId) {
34045
+ this.effectHostGenerations.set(
34046
+ sandboxId,
34047
+ (this.effectHostGenerations.get(sandboxId) || 0) + 1
34048
+ );
34049
+ const recovering = this.effectHostRecovery.get(sandboxId);
34050
+ if (recovering?.timer) clearTimeout(recovering.timer);
34051
+ this.effectHostRecovery.delete(sandboxId);
33469
34052
  const host = this.sandboxEffectHosts.get(sandboxId);
33470
34053
  if (!host) {
33471
34054
  return;
33472
34055
  }
34056
+ this.sandboxEffectHosts.delete(sandboxId);
33473
34057
  this.stopEffectHostHeartbeat(host);
33474
34058
  host.wsClient.disconnect();
33475
- this.sandboxEffectHosts.delete(sandboxId);
33476
34059
  }
33477
34060
  /**
33478
34061
  * Register an effect (tool) for a specific sandbox.
@@ -34479,7 +35062,8 @@ function createGranularClient() {
34479
35062
  config,
34480
35063
  granular: new Granular({
34481
35064
  apiKey: config.apiKey,
34482
- apiUrl: config.apiUrl
35065
+ apiUrl: config.apiUrl,
35066
+ WebSocketCtor: NodeWebSocket__default.default
34483
35067
  })
34484
35068
  };
34485
35069
  }
@@ -34592,7 +35176,8 @@ async function withRuntimeConnection(options, callback) {
34592
35176
  return await callback(connection);
34593
35177
  } finally {
34594
35178
  try {
34595
- await connection.environment.disconnect();
35179
+ if (options.sessionId) connection.session.disconnectTransport();
35180
+ else await connection.environment.disconnect();
34596
35181
  } catch {
34597
35182
  connection.environment?.client?.disconnect?.();
34598
35183
  }
@@ -34677,11 +35262,11 @@ function parseSessionListInteger(value, name) {
34677
35262
  return parsed;
34678
35263
  }
34679
35264
  function printValue(value, emitJson) {
34680
- const json = JSON.stringify(value, null, 2);
35265
+ const json2 = JSON.stringify(value, null, 2);
34681
35266
  if (emitJson) {
34682
- console.log(json);
35267
+ console.log(json2);
34683
35268
  } else {
34684
- console.log(json);
35269
+ console.log(json2);
34685
35270
  console.log();
34686
35271
  }
34687
35272
  }
@@ -35054,7 +35639,48 @@ async function effectsDiffCommand(options) {
35054
35639
  }
35055
35640
 
35056
35641
  // src/cli/commands/job.ts
35642
+ async function waitForStoredJobResult(liveResult, inspect, options = {}) {
35643
+ let busy = false, failures = 0, finished = false;
35644
+ let resolveStored, rejectStored;
35645
+ const storedResult = new Promise((resolve8, reject2) => {
35646
+ resolveStored = resolve8;
35647
+ rejectStored = reject2;
35648
+ });
35649
+ const tick = async () => {
35650
+ if (busy || finished) return;
35651
+ busy = true;
35652
+ try {
35653
+ const record3 = await inspect();
35654
+ failures = 0;
35655
+ if (record3.status === "succeeded" || record3.status === "completed")
35656
+ resolveStored(record3.result);
35657
+ else if (["failed", "timeout", "canceled"].includes(record3.status))
35658
+ rejectStored(new Error(record3.error || "Job " + record3.status));
35659
+ } catch {
35660
+ if (++failures >= (options.maxInspectionFailures ?? 6))
35661
+ rejectStored(
35662
+ new Error(
35663
+ "Job status could not be verified after repeated inspection failures. Inspect the original job before retrying; its source outcome is unknown."
35664
+ )
35665
+ );
35666
+ } finally {
35667
+ busy = false;
35668
+ }
35669
+ };
35670
+ const cancel = options.schedule ? options.schedule(tick, options.pollMs ?? 5e3) : (() => {
35671
+ const timer = setInterval(tick, options.pollMs ?? 5e3);
35672
+ return () => clearInterval(timer);
35673
+ })();
35674
+ try {
35675
+ return await Promise.race([liveResult, storedResult]);
35676
+ } finally {
35677
+ finished = true;
35678
+ cancel();
35679
+ }
35680
+ }
35057
35681
  async function jobRunCommand(options) {
35682
+ if (options.runtime && !["promise", "effect"].includes(options.runtime))
35683
+ throw new Error("--runtime must be promise or effect");
35058
35684
  const emitJson = options.json === true;
35059
35685
  const code = readJobCodeFromOptions({
35060
35686
  file: options.file,
@@ -35072,7 +35698,11 @@ async function jobRunCommand(options) {
35072
35698
  sessionId: options.session
35073
35699
  },
35074
35700
  async ({ environment, session: session2, ontologyId }) => {
35075
- const job2 = await session2.submitJob(code);
35701
+ const job2 = await session2.submitJob(code, {
35702
+ runtime: options.runtime
35703
+ });
35704
+ process.stderr.write(`jobId=${job2.id} sessionId=${session2.sessionId}
35705
+ `);
35076
35706
  const stdout = [];
35077
35707
  const stderr = [];
35078
35708
  job2.on("stdout", (line) => {
@@ -35091,14 +35721,37 @@ async function jobRunCommand(options) {
35091
35721
  `);
35092
35722
  }
35093
35723
  });
35094
- const result = await job2.result;
35724
+ let result;
35725
+ let error2;
35726
+ try {
35727
+ result = await waitForStoredJobResult(
35728
+ job2.result,
35729
+ () => session2.jobs.get(job2.id)
35730
+ );
35731
+ } catch (failure) {
35732
+ error2 = failure instanceof Error ? failure.message : String(failure);
35733
+ }
35734
+ let inspectionError;
35735
+ const stored = await session2.jobs.get(job2.id).catch((failure) => {
35736
+ inspectionError = failure instanceof Error ? failure.message : String(failure);
35737
+ return null;
35738
+ });
35739
+ const diagnostics = stored?.executionReport?.diagnostics || job2.diagnostics;
35740
+ const ok = !error2 && !inspectionError && !diagnostics?.unresolved.length && !diagnostics?.truncated && !stored?.executionReport?.findings.some(
35741
+ (f) => f.authority === "host" && f.severity === "blocked"
35742
+ );
35743
+ if (!ok) process.exitCode = 1;
35095
35744
  const payload = {
35096
- ok: true,
35745
+ ok,
35746
+ ...error2 ? { error: error2 } : {},
35747
+ ...inspectionError ? { inspectionError } : {},
35748
+ ...diagnostics ? { diagnostics } : {},
35097
35749
  ontologyId,
35098
35750
  environmentId: environment.environmentId,
35099
35751
  sessionId: session2.sessionId,
35100
35752
  jobId: job2.id,
35101
- status: job2.status,
35753
+ status: stored?.status || job2.status,
35754
+ executionReport: stored?.executionReport,
35102
35755
  stdout,
35103
35756
  stderr,
35104
35757
  result
@@ -35107,7 +35760,22 @@ async function jobRunCommand(options) {
35107
35760
  console.log(JSON.stringify(payload, null, 2));
35108
35761
  return;
35109
35762
  }
35110
- success(`Job ${job2.id} succeeded.`);
35763
+ if (ok) success(`Job ${job2.id} succeeded.`);
35764
+ else
35765
+ error(
35766
+ `Job ${job2.id}: ${error2 || "execution finished with unresolved consequences"}`
35767
+ );
35768
+ for (const steer of diagnostics?.steering || [])
35769
+ console.error(`[${steer.failureId}] ${steer.message}`);
35770
+ for (const finding of stored?.executionReport?.findings || [])
35771
+ console.error(
35772
+ `[${finding.authority}/${finding.code}] ${finding.message} Next: ${finding.action}`
35773
+ );
35774
+ if (inspectionError)
35775
+ console.error(
35776
+ `Stored report unavailable: ${inspectionError}. Inspect job ${job2.id} in session ${session2.sessionId}; its result and source outcome must not be guessed from this inspection failure.`
35777
+ );
35778
+ recoveryCommands(stored?.executionReport, session2.sessionId);
35111
35779
  console.log();
35112
35780
  keyValue({
35113
35781
  "Ontology ID": payload.ontologyId,
@@ -35122,6 +35790,232 @@ async function jobRunCommand(options) {
35122
35790
  }
35123
35791
  );
35124
35792
  }
35793
+ async function jobReconcileCommand(operationId2, options) {
35794
+ await withRuntimeConnection(
35795
+ { sessionId: options.session },
35796
+ async ({ session: session2 }) => {
35797
+ const result = await session2.reconcileInvocation(operationId2, {
35798
+ fence: options.fence
35799
+ });
35800
+ if (!result.ok) process.exitCode = 1;
35801
+ if (options.json) console.log(JSON.stringify(result, null, 2));
35802
+ else if (result.ok)
35803
+ success(`Invocation ${result.operationId}: ${result.outcome}.`);
35804
+ else {
35805
+ error(result.error || "The invocation remains unresolved");
35806
+ for (const steer of result.diagnostics?.steering || [])
35807
+ console.error(steer.message);
35808
+ }
35809
+ }
35810
+ );
35811
+ }
35812
+ async function jobTypesCommand(options) {
35813
+ if (!["promise", "effect"].includes(options.runtime || "promise"))
35814
+ throw new Error("--runtime must be promise or effect");
35815
+ await withRuntimeConnection(
35816
+ { sessionId: options.session },
35817
+ async ({ session: session2 }) => console.log(
35818
+ await session2.getDomainTypes({
35819
+ runtime: options.runtime
35820
+ })
35821
+ )
35822
+ );
35823
+ }
35824
+ async function jobInspectCommand(jobId, options) {
35825
+ await withRuntimeConnection(
35826
+ { sessionId: options.session },
35827
+ async ({ session: session2 }) => {
35828
+ const job2 = await session2.jobs.get(jobId);
35829
+ if (options.json) {
35830
+ console.log(JSON.stringify(job2, null, 2));
35831
+ return;
35832
+ }
35833
+ console.log(`Job ${job2.jobId}: ${job2.status}`);
35834
+ if (job2.error) console.log(job2.error);
35835
+ const report = job2.executionReport;
35836
+ if (!report) {
35837
+ console.log("Execution report unavailable for this job.");
35838
+ return;
35839
+ }
35840
+ for (const steer of report.diagnostics?.steering || [])
35841
+ console.log(`Next: ${steer.message}`);
35842
+ for (const failure of report.diagnostics?.failures || []) {
35843
+ console.log(
35844
+ `[${failure.origin}/${failure.code}] ${failure.message} (at failure: ${failure.commit})`
35845
+ );
35846
+ for (const resolution of report.diagnostics?.resolutions?.filter(
35847
+ (r) => r.operationId === failure.operationId
35848
+ ) || [])
35849
+ console.log(" Current verified outcome: " + resolution.outcome);
35850
+ if (failure.ruleIds?.length)
35851
+ console.log(" Rules: " + failure.ruleIds.join(", "));
35852
+ if (failure.causedBy?.length)
35853
+ console.log(" Caused by: " + failure.causedBy.join(", "));
35854
+ for (const handling of report.diagnostics?.handling.filter(
35855
+ (h) => h.failureId === failure.id
35856
+ ) || [])
35857
+ console.log(
35858
+ ` ${handling.action}${handling.outcome ? " / " + handling.outcome : ""}`
35859
+ );
35860
+ }
35861
+ recoveryCommands(report, session2.sessionId);
35862
+ if (report.host)
35863
+ console.log(
35864
+ `Host: ${report.host.calls} calls, ${report.host.writes} write attempts, peak ${report.host.peakInFlight} concurrent`
35865
+ );
35866
+ console.log(
35867
+ `Capture: ${report.capture.state}, ${report.capture.events} events (guest diagnostics)`
35868
+ );
35869
+ if (report.liveTelemetry) {
35870
+ const live = report.liveTelemetry;
35871
+ console.log(
35872
+ `Live diagnostics: saved through #${live.persistedThrough}; ${live.complete ? "complete" : "partial"}; ${live.dropped} dropped${live.logsTruncated ? "; logs truncated" : ""}`
35873
+ );
35874
+ if (!live.complete)
35875
+ console.log(
35876
+ "Coverage: unacknowledged logs and handling may still be missing."
35877
+ );
35878
+ for (const [level, lines] of [
35879
+ ["stdout", job2.stdout || []],
35880
+ ["stderr", job2.stderr || []]
35881
+ ]) {
35882
+ if (lines.length > 5)
35883
+ console.log(
35884
+ `${level}: showing last 5 of ${lines.length} lines (use --json for all captured lines)`
35885
+ );
35886
+ for (const line of lines.slice(-5)) console.log(`[${level}] ${line}`);
35887
+ }
35888
+ }
35889
+ for (const node of report.nodes) {
35890
+ let depth = 0, parent = node.parentId;
35891
+ const seen = /* @__PURE__ */ new Set();
35892
+ while (parent && depth < 12 && !seen.has(parent)) {
35893
+ seen.add(parent);
35894
+ parent = report.nodes.find((n) => n.id === parent)?.parentId || null;
35895
+ depth++;
35896
+ }
35897
+ console.log(
35898
+ " ".repeat(depth) + `${node.label}: ${node.status}${node.durationMs === void 0 ? "" : ` (${Math.round(node.durationMs)} ms)`}${node.iterations === void 0 ? "" : `, ${node.iterations} iterations`}`
35899
+ );
35900
+ }
35901
+ for (const resolution of report.resolutions?.items || []) {
35902
+ const m = resolution.result.metadata;
35903
+ console.log(
35904
+ `Resolution: ${m.source === "agent_context" ? "coding agent" : m.model || "Jev unavailable"} \u2014 ${m.outcome === "candidate" ? "suggests " + m.recommendedId : m.outcome || m.reason}; ${Math.round(resolution.durationMs)} ms; ${m.steering ? "route " + m.steering.action + " (" + m.steering.reason + ")" : "routing unavailable"}; evidence ${resolution.id}`
35905
+ );
35906
+ }
35907
+ if (report.resolutions?.skippedCount)
35908
+ console.log(
35909
+ `Resolution capture limit: ${report.resolutions.skippedCount} assessments skipped`
35910
+ );
35911
+ for (const query of report.queries || []) {
35912
+ console.log(
35913
+ `Query ${query.id}: ${query.className}.${query.operation} \u2014 ${query.status}${query.search ? ", search (value redacted)" : ""}`
35914
+ );
35915
+ for (const predicate of query.predicates)
35916
+ console.log(
35917
+ ` ${predicate.location}: ${predicate.field} ${predicate.operator} (value redacted)`
35918
+ );
35919
+ for (const stage of query.stages)
35920
+ console.log(
35921
+ ` ${stage.stage} [${stage.location}]: ${stage.before ?? "?"} \u2192 ${stage.after}${stage.rejected === void 0 ? "" : `, ${stage.measurement === "separate_counts" ? "observed reduction" : "removed"} ${stage.rejected}`}${stage.field ? `, ${stage.field} ${stage.operator}` : ""} (${stage.measurement}${stage.complete ? "" : ", bounded/partial"})`
35922
+ );
35923
+ }
35924
+ for (const node of report.nodes)
35925
+ if (node.metrics?.evaluated !== void 0)
35926
+ console.log(
35927
+ `Filter ${node.label}: evaluated ${node.metrics.evaluated}, accepted ${node.metrics.accepted}, rejected ${node.metrics.rejected}, failed ${node.metrics.predicateFailed}, pending ${node.metrics.pending} \u2014 ${node.status}`
35928
+ );
35929
+ for (const finding of report.findings)
35930
+ console.log(
35931
+ `[${finding.authority}/${finding.severity}] ${finding.message} ${finding.action}`
35932
+ );
35933
+ for (const gap of report.capture.blindSpots)
35934
+ console.log(`Coverage: ${gap}`);
35935
+ }
35936
+ );
35937
+ }
35938
+ async function jobCommitCommand(commitId, options) {
35939
+ await withRuntimeConnection(
35940
+ { sessionId: options.session },
35941
+ async ({ environment }) => {
35942
+ const receipt = options.retry ? await environment.environment.commit.retry(commitId) : await environment.environment.commit.get(commitId);
35943
+ if (options.json) console.log(JSON.stringify(receipt, null, 2));
35944
+ else {
35945
+ console.log(
35946
+ `Commit ${receipt.commitId}: product ${receipt.product.status}; agent ${receipt.agent.status}.`
35947
+ );
35948
+ if (!["synced", "not_requested"].includes(receipt.agent.status))
35949
+ console.log(
35950
+ "Inspect the projection failure; retry synchronization when appropriate. Do not repeat the product operation."
35951
+ );
35952
+ }
35953
+ }
35954
+ );
35955
+ }
35956
+ function recoveryCommands(report, sessionId) {
35957
+ const seen = /* @__PURE__ */ new Set();
35958
+ for (const steer of report?.diagnostics?.steering || []) {
35959
+ const failure = report.diagnostics.failures.find(
35960
+ (f) => f.id === steer.failureId
35961
+ );
35962
+ const id3 = failure?.relatedOperationId || failure?.operationId;
35963
+ if (steer.action === "reconcile" && id3) {
35964
+ const command = `granular job reconcile ${id3} --session ${sessionId}`;
35965
+ if (!seen.has(command)) {
35966
+ seen.add(command);
35967
+ console.error("Recovery: " + command);
35968
+ }
35969
+ }
35970
+ }
35971
+ for (const receipt of report?.commits || [])
35972
+ if (!["synced", "not_requested"].includes(receipt.agent.status))
35973
+ console.error(
35974
+ `Recovery: granular job commit ${receipt.commitId} --session ${sessionId}`
35975
+ );
35976
+ }
35977
+ function formatJobEvent(event) {
35978
+ const decision = event.kind === "decision" ? ` \u2192 ${event.data.disposition}/${event.data.action} [${event.data.scope}]` : "";
35979
+ const operation = event.refs.operationId ? `; operation ${event.refs.operationId}` : "";
35980
+ const cause = event.refs.causedBy?.length ? `; caused by ${event.refs.causedBy.join(", ")}` : "";
35981
+ return `#${event.sequence} [${event.authority}/${event.kind}] ${event.summary}${decision}${operation}${cause}`;
35982
+ }
35983
+ async function jobEventsCommand(jobId, options) {
35984
+ let cursor = Number(options.after ?? 0);
35985
+ if (!Number.isSafeInteger(cursor) || cursor < 0)
35986
+ throw Error("--after must be a non-negative integer");
35987
+ await withRuntimeConnection(
35988
+ { sessionId: options.session },
35989
+ async ({ session: session2 }) => {
35990
+ do {
35991
+ const page = await session2.jobs.events(jobId, { after: cursor });
35992
+ if (options.json) {
35993
+ if (!options.follow || page.items.length || page.gap)
35994
+ console.log(JSON.stringify(page));
35995
+ } else {
35996
+ if (!page.available)
35997
+ console.log("Shared events unavailable for this historical job.");
35998
+ if (page.gap)
35999
+ console.log(
36000
+ `Event coverage gap: ${page.dropped} earlier events are outside the retained window. Inspect the complete failure and operation evidence with job inspect --json.`
36001
+ );
36002
+ for (const event of page.items) console.log(formatJobEvent(event));
36003
+ }
36004
+ cursor = Math.max(cursor, page.lastSequence);
36005
+ if (!options.follow || [
36006
+ "succeeded",
36007
+ "completed",
36008
+ "failed",
36009
+ "canceled",
36010
+ "cancelled",
36011
+ "timeout"
36012
+ ].includes(page.status))
36013
+ break;
36014
+ await new Promise((resolve8) => setTimeout(resolve8, 1e3));
36015
+ } while (true);
36016
+ }
36017
+ );
36018
+ }
35125
36019
 
35126
36020
  // src/cli/commands/permissions.ts
35127
36021
  init_src();
@@ -35312,15 +36206,15 @@ async function versionDiffCommand(versionId, againstVersionId, options) {
35312
36206
  againstVersionId ? `Computing diff ${versionId} \u2190 ${againstVersionId}...` : `Computing diff for ${versionId}...`
35313
36207
  );
35314
36208
  try {
35315
- const [version2, diffResult] = await Promise.all([
36209
+ const [version3, diffResult] = await Promise.all([
35316
36210
  api.getVersion(versionId),
35317
36211
  api.getVersionDiff(versionId, againstVersionId)
35318
36212
  ]);
35319
36213
  const baseVersion = diffResult.againstVersionId ? await api.getVersion(diffResult.againstVersionId).catch(() => null) : null;
35320
36214
  const summary = diffResult.diff.summary;
35321
36215
  const payload = {
35322
- versionId: version2.buildId,
35323
- versionNumber: version2.versionNumber ?? null,
36216
+ versionId: version3.buildId,
36217
+ versionNumber: version3.versionNumber ?? null,
35324
36218
  againstVersionId: diffResult.againstVersionId,
35325
36219
  againstVersionNumber: baseVersion?.versionNumber ?? null,
35326
36220
  summary,
@@ -35333,7 +36227,7 @@ async function versionDiffCommand(versionId, againstVersionId, options) {
35333
36227
  spin?.succeed(" Version diff ready.");
35334
36228
  console.log();
35335
36229
  keyValue({
35336
- Version: formatVersionLabel(version2.buildId, version2.versionNumber),
36230
+ Version: formatVersionLabel(version3.buildId, version3.versionNumber),
35337
36231
  "Compared against": baseVersion ? formatVersionLabel(baseVersion.buildId, baseVersion.versionNumber) : diffResult.againstVersionId || "previous version",
35338
36232
  "Added operations": summary.added,
35339
36233
  "Changed operations": summary.changed,
@@ -36160,9 +37054,8 @@ async function onboardGitReportCommand(options) {
36160
37054
  }
36161
37055
 
36162
37056
  // src/cli/index.ts
36163
- var VERSION = "0.2.0";
36164
37057
  var program2 = new Command();
36165
- program2.name("granular").description("Version and run Granular ontologies from code").version(VERSION, "-v, --version");
37058
+ program2.name("granular").description("Version and run Granular ontologies from code").version(version, "-v, --version");
36166
37059
  program2.option("--local", "Use local endpoints (localhost)").option("--env <target>", "Endpoint target: local|production");
36167
37060
  program2.hook("preAction", () => {
36168
37061
  const opts = program2.opts();
@@ -36352,14 +37245,30 @@ onboard.command("resume [run-id]").description("Resume the same durable run and
36352
37245
  }
36353
37246
  }
36354
37247
  );
36355
- onboard.command("browser-code").description("Explicitly authorize a developer browser for this API-key-owned run").option("--no-expiry", "Local test only: browser grant lasts until explicitly revoked").option("--revoke", "Revoke every pending code and browser authorization for this run").option("--json", "Print the sensitive one-use handoff code; never persist or share it").action(async (options) => {
36356
- try {
36357
- await onboardBrowserCodeCommand({ ...options, noExpiry: options.expiry === false });
36358
- } catch (error2) {
36359
- error(error2.message);
36360
- process.exitCode = 1;
37248
+ onboard.command("browser-code").description(
37249
+ "Explicitly authorize a developer browser for this API-key-owned run"
37250
+ ).option(
37251
+ "--no-expiry",
37252
+ "Local test only: browser grant lasts until explicitly revoked"
37253
+ ).option(
37254
+ "--revoke",
37255
+ "Revoke every pending code and browser authorization for this run"
37256
+ ).option(
37257
+ "--json",
37258
+ "Print the sensitive one-use handoff code; never persist or share it"
37259
+ ).action(
37260
+ async (options) => {
37261
+ try {
37262
+ await onboardBrowserCodeCommand({
37263
+ ...options,
37264
+ noExpiry: options.expiry === false
37265
+ });
37266
+ } catch (error2) {
37267
+ error(error2.message);
37268
+ process.exitCode = 1;
37269
+ }
36361
37270
  }
36362
- });
37271
+ );
36363
37272
  var externalAuth = onboard.command("external-auth").description("Inspect and plan disabled external-agent authorization");
36364
37273
  var externalAuthAction = (action) => async (options) => {
36365
37274
  try {
@@ -36448,7 +37357,12 @@ onboard.command("token-renew").description("Renew the scoped token for the same
36448
37357
  process.exit(1);
36449
37358
  }
36450
37359
  });
36451
- onboard.command("roles-apply").description("Write explicitly approved structured role action-policy sources").requiredOption("--file <path>", "Exact blueprint/review revision and selected roleIds JSON").action(async (options) => {
37360
+ onboard.command("roles-apply").description(
37361
+ "Write explicitly approved structured role action-policy sources"
37362
+ ).requiredOption(
37363
+ "--file <path>",
37364
+ "Exact blueprint/review revision and selected roleIds JSON"
37365
+ ).action(async (options) => {
36452
37366
  try {
36453
37367
  await onboardRolesApplyCommand(options);
36454
37368
  } catch (error2) {
@@ -36456,7 +37370,12 @@ onboard.command("roles-apply").description("Write explicitly approved structured
36456
37370
  process.exitCode = 1;
36457
37371
  }
36458
37372
  });
36459
- onboard.command("roles-verify").description("Check approved role policies in the current completed build; runtime verification is separate").requiredOption("--file <path>", "Exact blueprint/review revision, roleIds and buildId JSON").action(async (options) => {
37373
+ onboard.command("roles-verify").description(
37374
+ "Check approved role policies in the current completed build; runtime verification is separate"
37375
+ ).requiredOption(
37376
+ "--file <path>",
37377
+ "Exact blueprint/review revision, roleIds and buildId JSON"
37378
+ ).action(async (options) => {
36460
37379
  try {
36461
37380
  await onboardRolesVerifyCommand(options);
36462
37381
  } catch (error2) {
@@ -36464,7 +37383,16 @@ onboard.command("roles-verify").description("Check approved role policies in the
36464
37383
  process.exitCode = 1;
36465
37384
  }
36466
37385
  });
36467
- onboard.command("integration-report").description("Report approved per-item integration and its focused commit").requiredOption("--file <path>", "Exact revision/build/environment report JSON").option("--blueprint <path>", "Blueprint JSON for offline mapping validation").option("--commit <sha>", "Full commit ID for the integration change").option("--step <step>", "effect-handler, initial-import, incremental-import or state").option("--target <id>", "Exact model item implemented by this change").option("--repo <path>", "Product repository (defaults to current directory)").option("--validate-only", "Validate mappings offline; do not authenticate or publish").action(async (options) => {
37386
+ onboard.command("integration-report").description("Report approved per-item integration and its focused commit").requiredOption(
37387
+ "--file <path>",
37388
+ "Exact revision/build/environment report JSON"
37389
+ ).option("--blueprint <path>", "Blueprint JSON for offline mapping validation").option("--commit <sha>", "Full commit ID for the integration change").option(
37390
+ "--step <step>",
37391
+ "effect-handler, initial-import, incremental-import or state"
37392
+ ).option("--target <id>", "Exact model item implemented by this change").option("--repo <path>", "Product repository (defaults to current directory)").option(
37393
+ "--validate-only",
37394
+ "Validate mappings offline; do not authenticate or publish"
37395
+ ).action(async (options) => {
36468
37396
  try {
36469
37397
  await onboardIntegrationReportCommand(options);
36470
37398
  } catch (error2) {
@@ -36472,7 +37400,9 @@ onboard.command("integration-report").description("Report approved per-item inte
36472
37400
  process.exitCode = 1;
36473
37401
  }
36474
37402
  });
36475
- onboard.command("integration-verify-imports").description("Check actual queued import completion and record shape for the reported implementation").requiredOption("--file <path>", "Bound import verification request JSON").action(async (options) => {
37403
+ onboard.command("integration-verify-imports").description(
37404
+ "Check actual queued import completion and record shape for the reported implementation"
37405
+ ).requiredOption("--file <path>", "Bound import verification request JSON").action(async (options) => {
36476
37406
  try {
36477
37407
  await onboardIntegrationVerifyImportsCommand(options);
36478
37408
  } catch (error2) {
@@ -36574,7 +37504,12 @@ onboard.command("bind").description("Bind build or environment evidence to the c
36574
37504
  }
36575
37505
  }
36576
37506
  );
36577
- onboard.command("git-plan").description("Plan scoped Git operations offline without changing the repository").requiredOption("--file <path>", "JSON with explicit files, targetBranch, operations, commitMessage and optional pullRequest").action((options) => {
37507
+ onboard.command("git-plan").description(
37508
+ "Plan scoped Git operations offline without changing the repository"
37509
+ ).requiredOption(
37510
+ "--file <path>",
37511
+ "JSON with explicit files, targetBranch, operations, commitMessage and optional pullRequest"
37512
+ ).action((options) => {
36578
37513
  try {
36579
37514
  onboardGitPlanCommand(options);
36580
37515
  } catch (error2) {
@@ -36582,7 +37517,9 @@ onboard.command("git-plan").description("Plan scoped Git operations offline with
36582
37517
  process.exitCode = 1;
36583
37518
  }
36584
37519
  });
36585
- onboard.command("git-status").description("Read the saved Git proposal and its separate developer approval").action(async () => {
37520
+ onboard.command("git-status").description(
37521
+ "Read the saved Git proposal and its separate developer approval"
37522
+ ).action(async () => {
36586
37523
  try {
36587
37524
  await onboardGitStatusCommand();
36588
37525
  } catch (error2) {
@@ -36590,7 +37527,12 @@ onboard.command("git-status").description("Read the saved Git proposal and its s
36590
37527
  process.exitCode = 1;
36591
37528
  }
36592
37529
  });
36593
- onboard.command("git-propose").description("Publish an exact local Git plan for developer approval; never execute").requiredOption("--file <path>", "Plan JSON from git-plan").requiredOption("--base-revision <number>", "Displayed Git proposal revision, or 0 when absent").action(async (options) => {
37530
+ onboard.command("git-propose").description(
37531
+ "Publish an exact local Git plan for developer approval; never execute"
37532
+ ).requiredOption("--file <path>", "Plan JSON from git-plan").requiredOption(
37533
+ "--base-revision <number>",
37534
+ "Displayed Git proposal revision, or 0 when absent"
37535
+ ).action(async (options) => {
36594
37536
  try {
36595
37537
  await onboardGitProposeCommand(options);
36596
37538
  } catch (error2) {
@@ -36598,7 +37540,9 @@ onboard.command("git-propose").description("Publish an exact local Git plan for
36598
37540
  process.exitCode = 1;
36599
37541
  }
36600
37542
  });
36601
- onboard.command("git-consume").description("Validate local scope and consume exact developer approval once; output a plan without executing").requiredOption("--proposal-id <id>", "Exact approved proposal id").requiredOption("--revision <number>", "Exact approved proposal revision").action(async (options) => {
37543
+ onboard.command("git-consume").description(
37544
+ "Validate local scope and consume exact developer approval once; output a plan without executing"
37545
+ ).requiredOption("--proposal-id <id>", "Exact approved proposal id").requiredOption("--revision <number>", "Exact approved proposal revision").action(async (options) => {
36602
37546
  try {
36603
37547
  await onboardGitConsumeCommand(options);
36604
37548
  } catch (error2) {
@@ -36606,7 +37550,12 @@ onboard.command("git-consume").description("Validate local scope and consume exa
36606
37550
  process.exitCode = 1;
36607
37551
  }
36608
37552
  });
36609
- onboard.command("git-report").description("Report a locally checked commit using exact consumed approval, without rebinding the source run or claiming remote execution").requiredOption("--file <path>", "Saved git-consume output containing its receipt").action(async (options) => {
37553
+ onboard.command("git-report").description(
37554
+ "Report a locally checked commit using exact consumed approval, without rebinding the source run or claiming remote execution"
37555
+ ).requiredOption(
37556
+ "--file <path>",
37557
+ "Saved git-consume output containing its receipt"
37558
+ ).action(async (options) => {
36610
37559
  try {
36611
37560
  await onboardGitReportCommand(options);
36612
37561
  } catch (error2) {
@@ -36614,8 +37563,8 @@ onboard.command("git-report").description("Report a locally checked commit using
36614
37563
  process.exitCode = 1;
36615
37564
  }
36616
37565
  });
36617
- var version = program2.command("version").description("Inspect ontology versions");
36618
- version.command("current").description("Show the latest/current ontology version for this repo").option("--json", "Print machine-readable JSON").action(async (options) => {
37566
+ var version2 = program2.command("version").description("Inspect ontology versions");
37567
+ version2.command("current").description("Show the latest/current ontology version for this repo").option("--json", "Print machine-readable JSON").action(async (options) => {
36619
37568
  try {
36620
37569
  await versionCurrentCommand(options);
36621
37570
  } catch (err) {
@@ -36623,7 +37572,7 @@ version.command("current").description("Show the latest/current ontology version
36623
37572
  process.exit(1);
36624
37573
  }
36625
37574
  });
36626
- version.command("diff <version-id> [against-version-id]").description("Show the semantic diff between one version and another").option("--json", "Print machine-readable JSON").action(
37575
+ version2.command("diff <version-id> [against-version-id]").description("Show the semantic diff between one version and another").option("--json", "Print machine-readable JSON").action(
36627
37576
  async (versionId, againstVersionId, options) => {
36628
37577
  try {
36629
37578
  await versionDiffCommand(versionId, againstVersionId, options);
@@ -36861,16 +37810,88 @@ job.command("run").description(
36861
37810
  ).option(
36862
37811
  "--session <sessionId>",
36863
37812
  "Connect to an existing session instead of creating a fresh one"
37813
+ ).option(
37814
+ "--runtime <runtime>",
37815
+ "Job runtime: promise or experimental effect",
37816
+ "promise"
36864
37817
  ).option("--file <path>", "Read the job source from a file").option("--inline <code>", "Provide the job source inline").option("--json", "Print machine-readable JSON").action(
36865
37818
  async (options) => {
36866
37819
  try {
36867
37820
  await jobRunCommand(options);
36868
37821
  } catch (err) {
36869
- error(err.message);
36870
- process.exit(1);
37822
+ if (options.json)
37823
+ console.log(JSON.stringify({ ok: false, error: err.message }));
37824
+ else error(err.message);
37825
+ process.exitCode = 1;
36871
37826
  }
36872
37827
  }
36873
37828
  );
37829
+ job.command("inspect <jobId>").description(
37830
+ "Inspect a job's outcome, execution structure, findings and recovery guidance"
37831
+ ).requiredOption("--session <sessionId>", "Session owning the job").option("--json", "Print the complete stored job and execution report").action(async (jobId, options) => {
37832
+ try {
37833
+ await jobInspectCommand(jobId, options);
37834
+ } catch (error2) {
37835
+ if (options.json)
37836
+ console.log(JSON.stringify({ ok: false, error: error2.message }));
37837
+ else error(error2.message);
37838
+ process.exitCode = 1;
37839
+ }
37840
+ });
37841
+ job.command("events <jobId>").description(
37842
+ "Read shared job events, decisions and causes; follow prints new events as they persist"
37843
+ ).requiredOption("--session <sessionId>", "Session owning the job").option("--after <sequence>", "Read events after this sequence", "0").option("--follow", "Wait for new events until the job ends").option("--json", "Print JSON; one JSON object per batch when following").action(async (jobId, options) => {
37844
+ try {
37845
+ await jobEventsCommand(jobId, options);
37846
+ } catch (error2) {
37847
+ if (options.json)
37848
+ console.log(JSON.stringify({ ok: false, error: error2.message }));
37849
+ else error(error2.message);
37850
+ process.exitCode = 1;
37851
+ }
37852
+ });
37853
+ job.command("types").description("Print the generated TypeScript interface for a job runtime").requiredOption("--session <sessionId>", "Session providing the ontology").option("--runtime <runtime>", "Job runtime: promise or effect", "promise").action(async (options) => {
37854
+ try {
37855
+ await jobTypesCommand(options);
37856
+ } catch (error2) {
37857
+ error(error2.message);
37858
+ process.exitCode = 1;
37859
+ }
37860
+ });
37861
+ job.command("reconcile <operationId>").description(
37862
+ "Verify an invocation's original outcome without replaying the product operation"
37863
+ ).requiredOption(
37864
+ "--session <sessionId>",
37865
+ "Session in the invocation's environment"
37866
+ ).option(
37867
+ "--fence",
37868
+ "Permanently block the original provider operation if it has not committed"
37869
+ ).option("--json", "Print machine-readable JSON").action(async (operationId2, options) => {
37870
+ try {
37871
+ await jobReconcileCommand(operationId2, options);
37872
+ } catch (error2) {
37873
+ if (options.json)
37874
+ console.log(JSON.stringify({ ok: false, error: error2.message }));
37875
+ else error(error2.message);
37876
+ process.exitCode = 1;
37877
+ }
37878
+ });
37879
+ job.command("commit <commitId>").description("Inspect a canonical commit or retry only its agent projection").requiredOption(
37880
+ "--session <sessionId>",
37881
+ "Session in the commit's environment"
37882
+ ).option(
37883
+ "--retry",
37884
+ "Requeue projection synchronization; never invokes the product handler"
37885
+ ).option("--json", "Print the canonical receipt").action(async (commitId, options) => {
37886
+ try {
37887
+ await jobCommitCommand(commitId, options);
37888
+ } catch (error2) {
37889
+ if (options.json)
37890
+ console.log(JSON.stringify({ ok: false, error: error2.message }));
37891
+ else error(error2.message);
37892
+ process.exitCode = 1;
37893
+ }
37894
+ });
36874
37895
  program2.command("graphql").description(
36875
37896
  "Execute a real GraphQL query against the current Granular environment"
36876
37897
  ).requiredOption("--query <query>", "GraphQL query or mutation string").option("--variables <json>", "JSON object of GraphQL variables").option(