@granular-software/sdk 0.4.44 → 0.4.46

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.
@@ -4003,6 +4003,9 @@ var MAX_TIMER_DELAY_MS = 2147483647;
4003
4003
  var DEBUG_WS = process.env.GRANULAR_DEBUG_WS === "1";
4004
4004
  var DEFAULT_RPC_TIMEOUT_MS = 3e4;
4005
4005
  var DOMAIN_PACKAGE_RPC_TIMEOUT_MS = 12e4;
4006
+ var EFFECT_CONTROL_RPC_TIMEOUT_MS = 12e4;
4007
+ var DEFAULT_RECONNECT_DELAY_MS = 3e3;
4008
+ var DEFAULT_MAX_RECONNECT_ATTEMPTS = 5;
4006
4009
  function debugWs(...args) {
4007
4010
  if (DEBUG_WS) {
4008
4011
  console.log(...args);
@@ -4013,6 +4016,10 @@ function rpcTimeoutMsForMethod(method) {
4013
4016
  case "domain.fetchPackagePart":
4014
4017
  case "domain.getSummary":
4015
4018
  return DOMAIN_PACKAGE_RPC_TIMEOUT_MS;
4019
+ case "client.heartbeat":
4020
+ case "effects.publishCatalog":
4021
+ case "effects.refresh":
4022
+ return EFFECT_CONTROL_RPC_TIMEOUT_MS;
4016
4023
  default:
4017
4024
  return DEFAULT_RPC_TIMEOUT_MS;
4018
4025
  }
@@ -4032,6 +4039,7 @@ var WSClient = class {
4032
4039
  reconnectTimer = null;
4033
4040
  tokenRefreshTimer = null;
4034
4041
  isExplicitlyDisconnected = false;
4042
+ reconnectAttempts = 0;
4035
4043
  options;
4036
4044
  constructor(options) {
4037
4045
  this.options = options;
@@ -4186,6 +4194,7 @@ var WSClient = class {
4186
4194
  clearTimeout(this.reconnectTimer);
4187
4195
  this.reconnectTimer = null;
4188
4196
  }
4197
+ this.reconnectAttempts = 0;
4189
4198
  this.emit("open", {});
4190
4199
  resolve();
4191
4200
  });
@@ -4217,6 +4226,7 @@ var WSClient = class {
4217
4226
  clearTimeout(this.reconnectTimer);
4218
4227
  this.reconnectTimer = null;
4219
4228
  }
4229
+ this.reconnectAttempts = 0;
4220
4230
  this.emit("open", {});
4221
4231
  resolve();
4222
4232
  };
@@ -4276,7 +4286,8 @@ var WSClient = class {
4276
4286
  return new Error(`WebSocket disconnected${suffix}`);
4277
4287
  }
4278
4288
  handleDisconnect(close = {}) {
4279
- const reconnectDelayMs = 3e3;
4289
+ const baseReconnectDelayMs = typeof this.options.reconnectDelayMs === "number" && Number.isFinite(this.options.reconnectDelayMs) && this.options.reconnectDelayMs > 0 ? this.options.reconnectDelayMs : DEFAULT_RECONNECT_DELAY_MS;
4290
+ const maxReconnectAttempts = typeof this.options.maxReconnectAttempts === "number" && Number.isFinite(this.options.maxReconnectAttempts) && this.options.maxReconnectAttempts >= 0 ? Math.floor(this.options.maxReconnectAttempts) : DEFAULT_MAX_RECONNECT_ATTEMPTS;
4280
4291
  const unexpected = !this.isExplicitlyDisconnected;
4281
4292
  const info = {
4282
4293
  code: close.code,
@@ -4296,6 +4307,30 @@ var WSClient = class {
4296
4307
  const disconnectError = this.buildDisconnectError(info);
4297
4308
  this.rejectPending(disconnectError);
4298
4309
  this.emit("disconnect", info);
4310
+ if (this.reconnectAttempts >= maxReconnectAttempts) {
4311
+ const reconnectInfo = {
4312
+ error: `WebSocket reconnect attempts exhausted after ${maxReconnectAttempts} attempt(s).`,
4313
+ sessionId: this.sessionId,
4314
+ timestamp: Date.now()
4315
+ };
4316
+ this.emit("reconnect_error", reconnectInfo);
4317
+ if (this.options.onReconnectError) {
4318
+ try {
4319
+ this.options.onReconnectError(reconnectInfo);
4320
+ } catch (callbackError) {
4321
+ console.error(
4322
+ "[Granular] onReconnectError callback failed:",
4323
+ callbackError
4324
+ );
4325
+ }
4326
+ }
4327
+ return;
4328
+ }
4329
+ this.reconnectAttempts += 1;
4330
+ const reconnectDelayMs = Math.min(
4331
+ 3e4,
4332
+ baseReconnectDelayMs * 2 ** Math.max(0, this.reconnectAttempts - 1)
4333
+ );
4299
4334
  info.reconnectScheduled = true;
4300
4335
  info.reconnectDelayMs = reconnectDelayMs;
4301
4336
  if (this.options.onUnexpectedClose) {
@@ -4750,6 +4785,9 @@ var Session = class {
4750
4785
  promptCache = /* @__PURE__ */ new Map();
4751
4786
  /** Prompt ids locally answered before the document sync catches up. */
4752
4787
  hiddenPromptIds = /* @__PURE__ */ new Set();
4788
+ domainPackagePartCache = /* @__PURE__ */ new Map();
4789
+ domainPackagePartPromises = /* @__PURE__ */ new Map();
4790
+ domainPackageFetchQueue = Promise.resolve();
4753
4791
  constructor(client, clientId, options = {}) {
4754
4792
  this.client = client;
4755
4793
  this.clientId = clientId || `client_${Date.now()}`;
@@ -4957,12 +4995,18 @@ var Session = class {
4957
4995
  const resolvedAnswer = resolvePromptAnswer(prompt, answer);
4958
4996
  this.promptCache.delete(promptId);
4959
4997
  this.hiddenPromptIds.add(promptId);
4998
+ this.emit("prompt", { id: promptId, status: "answered" });
4960
4999
  try {
4961
- await this.client.call("prompt.answer", {
5000
+ const response = await this.client.call("prompt.answer", {
4962
5001
  promptId,
4963
5002
  answer: resolvedAnswer,
4964
5003
  value: resolvedAnswer
4965
5004
  });
5005
+ if (response && typeof response === "object" && "ok" in response && response.ok === false) {
5006
+ const rejected = response;
5007
+ const errorMessage = typeof rejected.error === "string" ? rejected.error : "Prompt answer was rejected.";
5008
+ throw new Error(errorMessage);
5009
+ }
4966
5010
  } catch (error) {
4967
5011
  this.hiddenPromptIds.delete(promptId);
4968
5012
  if (prompt) {
@@ -5190,11 +5234,33 @@ var Session = class {
5190
5234
  * Fetch a domain package part from the backend (no fallback).
5191
5235
  */
5192
5236
  async fetchDomainPart(part) {
5193
- const result = await this.client.call("domain.fetchPackagePart", {
5194
- moduleSpecifier: "@sandbox/domain",
5195
- part
5237
+ const cached = this.domainPackagePartCache.get(part);
5238
+ if (cached !== void 0) {
5239
+ return cached;
5240
+ }
5241
+ const inFlight = this.domainPackagePartPromises.get(part);
5242
+ if (inFlight) {
5243
+ return inFlight;
5244
+ }
5245
+ const fetchPromise = this.domainPackageFetchQueue.then(async () => {
5246
+ const result = await this.client.call("domain.fetchPackagePart", {
5247
+ moduleSpecifier: "@sandbox/domain",
5248
+ part
5249
+ });
5250
+ const content = result?.content ?? "";
5251
+ this.domainPackagePartCache.set(part, content);
5252
+ return content;
5196
5253
  });
5197
- return result?.content ?? "";
5254
+ this.domainPackagePartPromises.set(part, fetchPromise);
5255
+ this.domainPackageFetchQueue = fetchPromise.then(
5256
+ () => void 0,
5257
+ () => void 0
5258
+ );
5259
+ try {
5260
+ return await fetchPromise;
5261
+ } finally {
5262
+ this.domainPackagePartPromises.delete(part);
5263
+ }
5198
5264
  }
5199
5265
  /**
5200
5266
  * Get TypeScript class declarations for the current domain (for LLM/code gen).
@@ -5444,7 +5510,10 @@ import { ${allImports} } from "./sandbox-tools";
5444
5510
  const emitPrompt = (payload) => {
5445
5511
  const prompt = normalizePrompt(payload);
5446
5512
  if (!prompt) return;
5447
- this.hiddenPromptIds.delete(prompt.id);
5513
+ if (this.hiddenPromptIds.has(prompt.id)) {
5514
+ this.emit("prompt", { ...prompt, status: "answered" });
5515
+ return;
5516
+ }
5448
5517
  this.promptCache.set(prompt.id, prompt);
5449
5518
  this.emit("prompt", prompt);
5450
5519
  };
@@ -13055,6 +13124,7 @@ var LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS = 500;
13055
13124
  var SESSION_DATA_REQUEST_RETRY_COUNT = 4;
13056
13125
  var SESSION_DATA_REQUEST_RETRY_DELAY_MS = 500;
13057
13126
  var EFFECT_HOST_CONNECT_TIMEOUT_MS = 15e3;
13127
+ var SESSION_CONNECT_TIMEOUT_MS = 15e3;
13058
13128
  function filenameFromUploadBody(body) {
13059
13129
  const maybe = body;
13060
13130
  return typeof maybe.name === "string" && maybe.name.trim() ? maybe.name.trim() : null;
@@ -13074,7 +13144,7 @@ function bodyInitFromSessionFileUpload(body) {
13074
13144
  }
13075
13145
  return body;
13076
13146
  }
13077
- var EFFECT_CATALOG_SYNC_TIMEOUT_MS = 3e4;
13147
+ var EFFECT_CATALOG_SYNC_TIMEOUT_MS = 12e4;
13078
13148
  var EFFECT_CATALOG_SYNC_RETRY_COUNT = 3;
13079
13149
  var EFFECT_CATALOG_SYNC_RETRY_DELAY_MS = 1e3;
13080
13150
  function planRecordObjectsChunks(records, batchSize) {
@@ -15030,7 +15100,14 @@ var Granular = class _Granular {
15030
15100
  return tag;
15031
15101
  }
15032
15102
  buildManagedEnvironmentName(tag, versionId) {
15033
- return `__sdk__${tag}__${versionId}`;
15103
+ return `__sdk__${tag}__${versionId}__pinned`;
15104
+ }
15105
+ isManagedEnvironmentName(environment, tagName) {
15106
+ const name = environment.environment || environment.envName || "";
15107
+ return name.startsWith(`__sdk__${tagName}__`);
15108
+ }
15109
+ isPinnedToVersion(environment, versionId) {
15110
+ return environment.buildPolicy.mode === "pinned" && (environment.versionId === versionId || environment.buildPolicy.versionId === versionId || environment.buildPolicy.buildId === versionId);
15034
15111
  }
15035
15112
  matchesTagTrackedEnvironment(environment, tagName, tagId) {
15036
15113
  const environmentTagName = environment.tag?.name || environment.buildPolicy.tagName || null;
@@ -15091,7 +15168,7 @@ var Granular = class _Granular {
15091
15168
  );
15092
15169
  const currentMatches = this.sortEnvironmentsByRecency(
15093
15170
  userEnvironments.filter(
15094
- (environment) => this.matchesTagTrackedEnvironment(environment, tagName, tag.tagId) && environment.versionId === targetVersionId
15171
+ (environment) => this.matchesTagTrackedEnvironment(environment, tagName, tag.tagId) && environment.versionId === targetVersionId && (!this.isManagedEnvironmentName(environment, tagName) || this.isPinnedToVersion(environment, targetVersionId))
15095
15172
  )
15096
15173
  );
15097
15174
  if (currentMatches.length > 0) {
@@ -15120,6 +15197,7 @@ var Granular = class _Granular {
15120
15197
  subjectId: user.granularId,
15121
15198
  environment: this.buildManagedEnvironmentName(tagName, targetVersionId),
15122
15199
  tagId: tag.tagId,
15200
+ versionId: targetVersionId,
15123
15201
  permissionProfileId: null
15124
15202
  }),
15125
15203
  requestedOntology: ontology,
@@ -15165,6 +15243,7 @@ var Granular = class _Granular {
15165
15243
  row.summaryUpdatedAt ?? row.summary_updated_at
15166
15244
  ) : null,
15167
15245
  subjectId: row.subjectId != null ? String(row.subjectId) : null,
15246
+ sessionScope: row.sessionScope != null || row.session_scope != null ? String(row.sessionScope ?? row.session_scope) : null,
15168
15247
  jobCount: typeof row.jobCount === "number" ? row.jobCount : void 0,
15169
15248
  toolCallCount: typeof row.toolCallCount === "number" ? row.toolCallCount : void 0
15170
15249
  };
@@ -15372,7 +15451,11 @@ var Granular = class _Granular {
15372
15451
  onUnexpectedClose: this.onUnexpectedClose,
15373
15452
  onReconnectError: this.onReconnectError
15374
15453
  });
15375
- await client.connect();
15454
+ await withTimeout(
15455
+ client.connect(),
15456
+ SESSION_CONNECT_TIMEOUT_MS,
15457
+ `session WebSocket connect for ${session.sessionId}`
15458
+ );
15376
15459
  const environmentSession = new EnvironmentSession(
15377
15460
  client,
15378
15461
  environment,
@@ -15543,12 +15626,24 @@ var Granular = class _Granular {
15543
15626
  host.heartbeatInFlight = false;
15544
15627
  }
15545
15628
  async synchronizeEffectHost(host) {
15546
- await host.wsClient.call("client.hello", {
15547
- clientId: host.clientId,
15548
- protocolVersion: "2.0"
15549
- });
15550
- this.startEffectHostHeartbeat(host);
15551
- await this.publishSandboxEffectCatalog(host);
15629
+ if (host.syncPromise) {
15630
+ return host.syncPromise;
15631
+ }
15632
+ host.syncPromise = (async () => {
15633
+ await host.wsClient.call("client.hello", {
15634
+ clientId: host.clientId,
15635
+ protocolVersion: "2.0"
15636
+ });
15637
+ await this.publishSandboxEffectCatalog(host);
15638
+ this.startEffectHostHeartbeat(host);
15639
+ })();
15640
+ try {
15641
+ await host.syncPromise;
15642
+ } finally {
15643
+ if (host.syncPromise) {
15644
+ host.syncPromise = null;
15645
+ }
15646
+ }
15552
15647
  }
15553
15648
  async ensureSandboxEffectHost(sandboxId) {
15554
15649
  const existing = this.sandboxEffectHosts.get(sandboxId);
@@ -15584,7 +15679,8 @@ var Granular = class _Granular {
15584
15679
  wsClient,
15585
15680
  heartbeatTimer: null,
15586
15681
  heartbeatInFlight: false,
15587
- recovering: false
15682
+ recovering: false,
15683
+ syncPromise: null
15588
15684
  };
15589
15685
  wsClient.registerRpcHandler("effect.invoke", async (params) => {
15590
15686
  const request = params;
@@ -16402,6 +16498,79 @@ function validateHarnessTemplateManifest(value, context = "HarnessTemplateManife
16402
16498
  function defineHarnessTemplateManifest(value, context) {
16403
16499
  return validateHarnessTemplateManifest(value, context);
16404
16500
  }
16501
+ var DEFAULT_IGNORED_REASONING_COMMENT_DIRECTIVES = [
16502
+ /^@ts-ignore\b/i,
16503
+ /^@ts-expect-error\b/i,
16504
+ /^eslint-[\w-]+\b/i,
16505
+ /^biome-ignore\b/i,
16506
+ /^prettier-ignore\b/i,
16507
+ /^istanbul ignore\b/i
16508
+ ];
16509
+ var DEFAULT_LOW_SIGNAL_REASONING_LINES = [
16510
+ /^running\.?$/i,
16511
+ /^working\.?$/i,
16512
+ /^thinking\.?$/i,
16513
+ /^generating(?: code)?\.?$/i,
16514
+ /^starting(?: execution)?\.?$/i
16515
+ ];
16516
+ function parseReasoningCommentLine(line, options = {}) {
16517
+ const trimmed = line.trimStart();
16518
+ if (!trimmed.startsWith("//")) return null;
16519
+ const text = trimmed.replace(/^\/\/\s?/, "").trim();
16520
+ if (!text) return { kind: "ignored" };
16521
+ const ignoredDirectives = options.ignoredCommentDirectives || DEFAULT_IGNORED_REASONING_COMMENT_DIRECTIVES;
16522
+ if (ignoredDirectives.some((pattern) => pattern.test(text))) {
16523
+ return { kind: "ignored" };
16524
+ }
16525
+ const lowSignalLines = options.lowSignalReasoningLines || DEFAULT_LOW_SIGNAL_REASONING_LINES;
16526
+ if (lowSignalLines.some((pattern) => pattern.test(text))) {
16527
+ return { kind: "ignored" };
16528
+ }
16529
+ return { kind: "reasoning", text };
16530
+ }
16531
+ function consumeGranularReasoningTraceChunk(buffer, chunk, options = {}) {
16532
+ let text = buffer + chunk;
16533
+ let visibleText = "";
16534
+ const reasoningLines = [];
16535
+ while (true) {
16536
+ const newlineIndex = text.indexOf("\n");
16537
+ if (newlineIndex === -1) break;
16538
+ const rawLine = text.slice(0, newlineIndex);
16539
+ text = text.slice(newlineIndex + 1);
16540
+ const comment = parseReasoningCommentLine(
16541
+ rawLine.replace(/\r$/, ""),
16542
+ options
16543
+ );
16544
+ if (comment?.kind === "reasoning") {
16545
+ reasoningLines.push(comment.text);
16546
+ } else if (comment?.kind === "ignored") {
16547
+ continue;
16548
+ } else {
16549
+ visibleText += `${rawLine}
16550
+ `;
16551
+ }
16552
+ }
16553
+ if (options.final && text.length > 0) {
16554
+ const comment = parseReasoningCommentLine(text.replace(/\r$/, ""), options);
16555
+ if (comment?.kind === "reasoning") {
16556
+ reasoningLines.push(comment.text);
16557
+ text = "";
16558
+ } else if (comment?.kind === "ignored") {
16559
+ text = "";
16560
+ } else {
16561
+ visibleText += text;
16562
+ text = "";
16563
+ }
16564
+ }
16565
+ return { buffer: text, visibleText, reasoningLines };
16566
+ }
16567
+ function consumeGranularReasoningOnlyChunk(buffer, chunk, options = {}) {
16568
+ const result = consumeGranularReasoningTraceChunk(buffer, chunk, options);
16569
+ return {
16570
+ buffer: result.buffer,
16571
+ reasoningLines: result.reasoningLines
16572
+ };
16573
+ }
16405
16574
  function asRecord4(value) {
16406
16575
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
16407
16576
  return value;
@@ -17607,7 +17776,8 @@ function buildGranularAgentSessionBlock(sessionContext) {
17607
17776
  runtimeId: sessionContext?.sandboxId || null,
17608
17777
  environmentId: sessionContext?.environmentId || null,
17609
17778
  userName: sessionContext?.userName || null,
17610
- domainRevision: sessionContext?.domainRevision || null
17779
+ domainRevision: sessionContext?.domainRevision || null,
17780
+ uiContext: sessionContext?.uiContext || null
17611
17781
  });
17612
17782
  }
17613
17783
  function buildGranularAgentHeapBlock(heapSummary) {
@@ -17854,7 +18024,7 @@ function buildGranularAgentToolBlock(tools, capabilityOverrides) {
17854
18024
  const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
17855
18025
  return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
17856
18026
  });
17857
- const writeActions = normalizedTools.filter((tool) => tool.ready !== false).map((tool) => {
18027
+ const availableActions = normalizedTools.filter((tool) => tool.ready !== false).map((tool) => {
17858
18028
  const scope = tool.className ? `${tool.static ? "class" : "record"}:${tool.className}` : "global";
17859
18029
  return {
17860
18030
  name: tool.name,
@@ -17865,7 +18035,8 @@ function buildGranularAgentToolBlock(tools, capabilityOverrides) {
17865
18035
  const capabilities = {
17866
18036
  executeCode: resolvedCapabilities.executeCode,
17867
18037
  readEntities: resolvedCapabilities.readEntities,
17868
- writeActions,
18038
+ availableActions,
18039
+ writeActions: availableActions,
17869
18040
  workflowHelpers: resolvedCapabilities.workflowHelpers,
17870
18041
  savedData: resolvedCapabilities.savedData,
17871
18042
  showRecords: resolvedCapabilities.showRecords
@@ -17879,7 +18050,7 @@ function buildGranularAgentActionIndex(tools) {
17879
18050
  return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
17880
18051
  });
17881
18052
  if (normalizedTools.length === 0) {
17882
- return "No domain write actions are available.";
18053
+ return "No executable actions are available.";
17883
18054
  }
17884
18055
  const globalTools = normalizedTools.filter((tool) => !tool.className);
17885
18056
  const staticTools = normalizedTools.filter(
@@ -17973,6 +18144,76 @@ function splitDomainDocumentation(domainDocumentation) {
17973
18144
  }
17974
18145
  return { types: normalized, docs: "" };
17975
18146
  }
18147
+ var DOMAIN_HELPER_FUNCTION_NAMES = /* @__PURE__ */ new Set([
18148
+ "agent_heap_objects",
18149
+ "agent_message",
18150
+ "agent_text_message"
18151
+ ]);
18152
+ function inferGlobalActionToolsFromDomainTypes(domainTypes) {
18153
+ const inferred = [];
18154
+ const seen = /* @__PURE__ */ new Set();
18155
+ const declarationPattern = /(?:export\s+)?declare\s+function\s+([A-Za-z_$][\w$]*)\s*\(/g;
18156
+ let match;
18157
+ while (match = declarationPattern.exec(domainTypes)) {
18158
+ const name = match[1];
18159
+ if (!name || DOMAIN_HELPER_FUNCTION_NAMES.has(name) || seen.has(name)) {
18160
+ continue;
18161
+ }
18162
+ seen.add(name);
18163
+ inferred.push({
18164
+ name,
18165
+ description: "Executable global action declared by the domain runtime."
18166
+ });
18167
+ }
18168
+ const actionLinePattern = /^-\s*([A-Za-z_$][\w$]*)\s+\(global\):\s*(.+)$/gm;
18169
+ while (match = actionLinePattern.exec(domainTypes)) {
18170
+ const name = match[1];
18171
+ if (!name || DOMAIN_HELPER_FUNCTION_NAMES.has(name) || seen.has(name)) {
18172
+ continue;
18173
+ }
18174
+ seen.add(name);
18175
+ inferred.push({
18176
+ name,
18177
+ description: match[2]?.trim() || "Executable global action declared by the domain runtime."
18178
+ });
18179
+ }
18180
+ const scopedActionLinePattern = /^-\s*([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)\s+\((record|class)\):\s*(.+)$/gm;
18181
+ while (match = scopedActionLinePattern.exec(domainTypes)) {
18182
+ const className = match[1]?.toLowerCase();
18183
+ const name = match[2];
18184
+ const scope = match[3];
18185
+ if (!className || !name || DOMAIN_HELPER_FUNCTION_NAMES.has(name)) {
18186
+ continue;
18187
+ }
18188
+ const key = `${className}:${scope}:${name}`;
18189
+ if (seen.has(key)) {
18190
+ continue;
18191
+ }
18192
+ seen.add(key);
18193
+ inferred.push({
18194
+ name,
18195
+ className,
18196
+ static: scope === "class",
18197
+ description: match[4]?.trim() || "Executable action declared by the domain runtime."
18198
+ });
18199
+ }
18200
+ return inferred;
18201
+ }
18202
+ function resolvePromptTools(tools, domainTypes) {
18203
+ const byKey = /* @__PURE__ */ new Map();
18204
+ for (const tool of tools || []) {
18205
+ if (!tool?.name) continue;
18206
+ const key = `${tool.className || "global"}:${tool.static ? "static" : "instance"}:${tool.name}`;
18207
+ byKey.set(key, tool);
18208
+ }
18209
+ for (const tool of inferGlobalActionToolsFromDomainTypes(domainTypes)) {
18210
+ const key = `global:instance:${tool.name}`;
18211
+ if (!byKey.has(key)) {
18212
+ byKey.set(key, tool);
18213
+ }
18214
+ }
18215
+ return [...byKey.values()];
18216
+ }
17976
18217
  function buildGranularAgentCheckpointBlock(checkpoint) {
17977
18218
  if (!checkpoint) {
17978
18219
  return renderConstBlock("previousCodeResult", null);
@@ -18045,12 +18286,13 @@ function buildGranularAgentSystemPrompt(input) {
18045
18286
  const outputMode = input.outputMode || "agentMessages";
18046
18287
  const promptCapabilities = resolvePromptCapabilities(input.capabilities);
18047
18288
  const domainSections = splitDomainDocumentation(input.domainDocumentation);
18289
+ const promptTools = resolvePromptTools(input.tools, domainSections.types);
18048
18290
  const sessionBlock = buildGranularAgentSessionBlock(input.sessionContext);
18049
18291
  const toolBlock = buildGranularAgentToolBlock(
18050
- input.tools,
18292
+ promptTools,
18051
18293
  input.capabilities
18052
18294
  );
18053
- const actionIndex = buildGranularAgentActionIndex(input.tools);
18295
+ const actionIndex = buildGranularAgentActionIndex(promptTools);
18054
18296
  const domainBlock = buildGranularAgentDomainBlock(domainSections.types);
18055
18297
  const workflowBlock = buildGranularAgentWorkflowBlock(input.workflowSummary);
18056
18298
  const checkpointBlock = buildGranularAgentCheckpointBlock(input.checkpoint);
@@ -18078,7 +18320,7 @@ function buildGranularAgentSystemPrompt(input) {
18078
18320
  - When \`agent_text_message(...)\` mentions a grounded record that should remain clickable/referable, wrap only the visible record label in a self-closing inline reference tag: \`<granular-object class="class_name" id="stable_id_or_path" label="Visible label" />\`. Use the actual class name and stable id/path from the runtime record or effect result; do not invent ids, field names, or snake/camel-case aliases that are not present in the type declarations or returned object.
18079
18321
  - Treat \`agent_heap_objects(...)\` as the UI display call for user-visible records, not as a general storage helper. Do not wrap records under an \`items\` key.
18080
18322
  - When records should remain reusable for follow-ups, first save the runtime record or ordered record array with \`await heap.setVar("stable_selection_name", value)\`, then display that saved selection exactly once with \`await agent_heap_objects({ variableNames: ["stable_selection_name"] })\`.
18081
- - \`heap.setVar(...)\` only accepts scalar values, runtime records/sandbox instances, or arrays of runtime records/sandbox instances. Do not save plain action/effect result objects. If an action returns an id/path for a created record that should remain referable, fetch the created record first, then save/display that fetched record.
18323
+ - \`heap.setVar(...)\` only accepts scalar values, runtime records/sandbox instances, or arrays of runtime records/sandbox instances from one class. Do not save plain action/effect result objects or arrays of JSON summaries returned by actions. If an action returns ids/paths for records that should remain referable or displayed as records, fetch the matching runtime records first with the generated class \`.get(...)\`/query API, then save/display those fetched records. If the action returned only structured summaries, answer from those summaries with \`agent_text_message(...)\`.
18082
18324
  - Do not use \`agent_heap_objects({ entries: [...] })\` or \`agent_heap_objects({ saveAs, entries })\` as a shortcut for ordered pages, queues, search results, or ranked lists; those forms can create duplicate or poorly labelled displays. Save the selection with \`heap.setVar(...)\` and display it via \`variableNames\` instead.
18083
18325
  - Use \`entryPaths\` only for a few already-known individual records and \`listNames\` only for a host-created list that you intentionally want to show. Do not display both an entry/list selection and a heap variable for the same records.
18084
18326
  - When the user asks to show, list, display, open, or "show them" for records you found, call \`agent_heap_objects(...)\`; do not answer only with a count or text summary.
@@ -18128,10 +18370,11 @@ ${outputRules}` : `Code:
18128
18370
  - Use choice only for 2 to 5 short grounded options.
18129
18371
  - For record choices, set each option value to a stable scalar such as the record \`_graphPath\` or \`id\`, not a label-only value.
18130
18372
  - After \`await loop.ask_user(...)\` returns from a choice prompt, tolerate either the option value, the option object, or a human-readable label by matching against value, id/path, label, and description before failing. If a returned label is a prefix or substring of exactly one option label, treat it as that option.
18131
- - Use \`loop.confirm(...)\` for yes/no confirmation only when the user explicitly asks for confirmation, action or permission metadata requires it, policy requires it, or material uncertainty remains after grounding.
18373
+ - Use \`loop.confirm(...)\` for yes/no confirmation only when the user explicitly asks for a separate confirmation step, policy requires confirmation outside the action runtime, or material uncertainty remains after grounding.
18374
+ - If action, effect, tool, or permission metadata already marks the invoked action as confirmation-gated, do not call \`loop.confirm(...)\` before invoking it. Ground the target and input, then call the action once; the runtime action policy will surface the confirmation prompt and resume the same invocation after approval.
18132
18375
  - Do not add a generic yes/no confirmation after the user has already made a grounded choice, unless one of those confirmation conditions still applies.
18133
- - Do not add confirmation only because an allowed mutation is visible to other people, customer-facing, or consequential. If the user clearly requested the mutation and the grounded target, action, and condition are unique, perform the mutation unless confirmation is required by the user, policy, action metadata, or remaining material uncertainty.
18134
- - A conditional request such as "if this is true, do that" is authorization to perform the requested action after you verify the condition. Once the condition, target, and action are grounded uniquely, call the action directly; do not ask "should I perform/post/send this?" unless the user, policy, action metadata, or unresolved material uncertainty requires confirmation. The visibility or impact of an allowed action is not by itself unresolved uncertainty.
18376
+ - Do not add confirmation only because an allowed mutation is visible to other people, customer-facing, or consequential. If the user clearly requested the mutation and the grounded target, action, and condition are unique, perform the mutation unless confirmation is required outside the action runtime or remaining material uncertainty exists.
18377
+ - A conditional request such as "if this is true, do that" is authorization to perform the requested action after you verify the condition. Once the condition, target, and action are grounded uniquely, call the action directly; do not ask "should I perform/post/send this?" unless the user, policy outside the action runtime, or unresolved material uncertainty requires confirmation. The visibility or impact of an allowed action is not by itself unresolved uncertainty.
18135
18378
  - If the user explicitly asks you to stop for confirmation, natural-language text such as "please confirm" is not enough: call \`await loop.confirm(...)\` before the mutation, then perform the approved mutation in the same resumed job when it returns true.
18136
18379
  - Reuse existing task, decision, and closure ids from [State].
18137
18380
  - If a user request matches both a domain record/action and a workflow helper, prefer the domain capability.` : "";
@@ -18277,7 +18520,8 @@ Query policy:
18277
18520
  - For operational blocker, risk, status, or "what is happening" questions, inspect the relevant record's scalar fields such as status, priority, blocker, summary, latest update/message, due date, amount, and other domain-specific descriptive fields before answering.
18278
18521
  - For read-only readiness, risk, health, or status summaries, call any visible read-only assessment/status action on the grounded primary record before ad-hoc aggregation when such an action semantically matches the request. Use the returned fields in the reply and supplement with counts or record reads only when useful.
18279
18522
  - Do not hide required visible read-only assessment/status actions inside broad try/catch blocks. The runtime action surface should show that the assessment action ran.
18280
- - Treat action/effect results as structured values, not necessarily arrays. Before indexing, iterating, checking \`.length\`, or calling array methods, normalize the result first: use the result itself only when \`Array.isArray(result)\`; otherwise read the exact array field shown in the output schema, or a documented array field such as \`items\`, \`matches\`, \`results\`, \`records\`, \`entries\`, \`candidates\`, \`options\`, or a domain-specific array field. Never convert a non-array object result to \`[]\` before checking its documented fields.
18523
+ - Treat action/effect results as structured values, not necessarily arrays. Before indexing, iterating, checking \`.length\`, or calling array methods, normalize the result first: use the result itself only when \`Array.isArray(result)\`; otherwise read the exact array field shown in the output schema, or a documented array field such as \`items\`, \`matches\`, \`results\`, \`records\`, \`entries\`, \`candidates\`, \`options\`, \`requests\`, \`vendors\`, \`transactions\`, \`approvals\`, \`receipts\`, or another domain-specific array field. If a structured result has \`count > 0\`, never conclude there are no matches until you inspect every array-valued field on that result object, especially fields named by the output schema. Never convert a non-array object result to \`[]\` before checking its documented fields.
18524
+ - Plain JSON objects returned by actions are not sandbox record instances, even when they contain ids, titles, labels, or status fields. Use them for reasoning and text responses. Do not pass action-returned JSON objects or arrays directly to \`heap.setVar(...)\` or \`agent_heap_objects(...)\`; fetch corresponding runtime records first when the user needs record display or follow-up references.
18281
18525
  - When a visible search, lookup, availability, or assessment action returns candidates or matches, treat those returned records as already scoped by the action inputs unless the output schema gives reliable fields for further narrowing. When matching returned candidates to grounded records, use the output schema's actual identifier fields, including \`id\`, \`path\`, or fields ending in \`Id\`; do not assume candidates have \`_graphPath\`. Do not discard all returned candidates by re-filtering on guessed property names.
18282
18526
  - For scheduling actions, convert relative wording into concrete ISO timestamps before mutating records.
18283
18527
  - When a decision depends on fresh external state and a visible read-only status/lookup action exists on the grounded record, call it before deciding, mutating, or refusing based on stale stored fields.
@@ -18339,6 +18583,7 @@ ${domainSections.docs}
18339
18583
 
18340
18584
  Actions:
18341
18585
  ${actionIndex}
18586
+ - Global actions are executable functions exported by "./sandbox-tools"; import each global action you call, e.g. \`import { some_action } from "./sandbox-tools"; await some_action(...)\`. This includes frontend actions such as opening, focusing, or navigating the host UI.
18342
18587
  - Actions listed under "Record-level" are instance methods. First fetch or find the specific record, then call the action on that instance, e.g. \`const item = await Item.get({ path }); await item.action_name(...)\`.
18343
18588
  - Actions listed under "Class-level" are class/static methods. Call them on the imported class, e.g. \`await Item.action_name(...)\`.
18344
18589
  - The action index is the visibility contract. If an action is listed for a class, call it directly on fetched/listed instances of that class; do not use \`typeof record.action_name === "function"\` as a discovery gate. If an action is not listed, do not call it.
@@ -19114,7 +19359,7 @@ function extractJsonStringField(source, fieldName) {
19114
19359
  function modelOutputInstruction() {
19115
19360
  return [
19116
19361
  "Return only a JSON object with this shape:",
19117
- '{ "action": "reply" | "job", "reply": string, "code": string }',
19362
+ '{ "action": "reply" | "job", "code": string, "reply": string }',
19118
19363
  'Use "action":"reply" only when a plain conversational answer is enough and no live session state should change.',
19119
19364
  'Do not use "action":"reply" to promise future tool work; if the user asks to check, find, look up, inspect, read, reopen, summarize, transform, update, post, send, approve, schedule, reschedule, calculate, or confirm around session state, session files, generated files, tools, or a domain action, use "action":"job".',
19120
19365
  'If the user asks to use an attached file, uploaded file, generated file, previous output file, or "the summary/workbook/file you just created", choose "action":"job" and read it through [Runtime Imports] instead of answering from memory.',
@@ -19122,7 +19367,8 @@ function modelOutputInstruction() {
19122
19367
  'Before claiming you lack access, inspect the visible action list. If a visible read-only search, lookup, list, guidance, note, policy, or knowledge action can satisfy a "check", "find", "look up", or "whether we have guidance" request, choose "action":"job" and call it.',
19123
19368
  "Generated code must not report no matches for the primary human-described anchor after a single zero-result list/find/page call. Before that primary no-match return, retry the primary anchor with fewer text constraints or a distinct fallback such as owner/container grounding, relationship traversal, exact-id/path lookup, or shorter target-local search.",
19124
19369
  'Use "action":"job" when the next step should run code or mutate workflow state.',
19125
- 'When action is "job", include runnable code in "code".',
19370
+ 'When action is "job", include runnable code in "code" and emit the "code" field before any non-empty "reply" field so generated code comments can stream as progress.',
19371
+ "Generated job code must use plain ASCII punctuation in string literals and comments. Do not use curly quotes, smart apostrophes, en dashes, em dashes, or other typographic punctuation in code.",
19126
19372
  "Generated code must not reference prompt-only symbols such as runtimeImports, savedData, sessionFileManifest, recentReferences, workflowContext, workflowState, or capabilities. Copy concrete paths/ids from the prompt into strings, fetch records with documented imports, or use documented runtime globals.",
19127
19373
  "Generated code must follow [Runtime Imports]: import module exports from their listed module, use listed globals directly without importing them, and do not leave undeclared identifiers in the job.",
19128
19374
  "Generated action calls must use the exact input property names from the visible action schema. Do not invent synonym keys for required inputs.",
@@ -19207,13 +19453,36 @@ ${modelOutputInstruction()}`
19207
19453
  let text = "";
19208
19454
  let usage = null;
19209
19455
  let requestId = null;
19210
- if (input.onTextDelta) {
19211
- const onTextDelta = input.onTextDelta;
19456
+ if (input.onTextDelta || input.onReplyDelta || input.onCodeDelta) {
19212
19457
  const stream = await client.chat.completions.create({
19213
19458
  ...payload,
19214
19459
  stream: true,
19215
19460
  stream_options: { include_usage: true }
19216
19461
  });
19462
+ let streamedReply = "";
19463
+ let streamedCode = "";
19464
+ const emitReplyDelta = async () => {
19465
+ if (!input.onReplyDelta) return;
19466
+ const replyField = extractJsonStringField(text, "reply");
19467
+ if (!replyField) return;
19468
+ const nextReply = replyField.value;
19469
+ if (!nextReply.startsWith(streamedReply)) return;
19470
+ const delta = nextReply.slice(streamedReply.length);
19471
+ if (!delta) return;
19472
+ streamedReply = nextReply;
19473
+ await input.onReplyDelta(delta);
19474
+ };
19475
+ const emitCodeDelta = async () => {
19476
+ if (!input.onCodeDelta) return;
19477
+ const codeField = extractJsonStringField(text, "code");
19478
+ if (!codeField) return;
19479
+ const nextCode = codeField.value;
19480
+ if (!nextCode.startsWith(streamedCode)) return;
19481
+ const delta = nextCode.slice(streamedCode.length);
19482
+ if (!delta) return;
19483
+ streamedCode = nextCode;
19484
+ await input.onCodeDelta(delta);
19485
+ };
19217
19486
  for await (const event of stream) {
19218
19487
  requestId = requestId || event.id || event._request_id || null;
19219
19488
  usage = event.usage || usage;
@@ -19221,8 +19490,12 @@ ${modelOutputInstruction()}`
19221
19490
  const deltaText = typeof delta === "string" ? delta : Array.isArray(delta) ? delta.map((part) => asRecord6(part)?.text || "").join("") : "";
19222
19491
  if (!deltaText) continue;
19223
19492
  text += deltaText;
19224
- await onTextDelta(deltaText);
19493
+ await input.onTextDelta?.(deltaText);
19494
+ await emitReplyDelta();
19495
+ await emitCodeDelta();
19225
19496
  }
19497
+ await emitReplyDelta();
19498
+ await emitCodeDelta();
19226
19499
  raw = { streamed: true, model, usage, request_id: requestId };
19227
19500
  } else {
19228
19501
  const completion = await client.chat.completions.create(
@@ -19324,6 +19597,64 @@ function normalizeHeapSnapshot2(heap) {
19324
19597
  updatedAt: typeof heap?.updatedAt === "number" ? heap.updatedAt : Date.now()
19325
19598
  };
19326
19599
  }
19600
+ function targetFromUiContext(context) {
19601
+ const target = asRecord6(context?.target) || asRecord6(context?.currentPageObject) || asRecord6(context?.commentaryTarget);
19602
+ const className = typeof target?.className === "string" ? target.className : "";
19603
+ const id = typeof target?.id === "string" ? target.id : "";
19604
+ if (!className || !id) return null;
19605
+ return {
19606
+ className,
19607
+ id,
19608
+ label: typeof target?.label === "string" ? target.label : void 0
19609
+ };
19610
+ }
19611
+ function heapEntryMatchesTarget(entry, target) {
19612
+ if (entry.className !== target.className) return false;
19613
+ if (entry.id === target.id) return true;
19614
+ const fields = asRecord6(entry.fields);
19615
+ return fields?.real_id === target.id || fields?._realId === target.id;
19616
+ }
19617
+ function focusedHeapEntryPathsFromUiContext(heap, context) {
19618
+ const target = targetFromUiContext(context);
19619
+ if (!target) return [];
19620
+ return Object.entries(heap.entriesByPath).filter(([, entry]) => heapEntryMatchesTarget(entry, target)).map(([path2]) => path2);
19621
+ }
19622
+ function hasSessionDocumentContext(document) {
19623
+ const doc = asRecord6(document);
19624
+ if (!doc) return false;
19625
+ const heap = normalizeHeapSnapshot2(asRecord6(doc.heap));
19626
+ if (Object.keys(heap.entriesByPath).length > 0 || Object.keys(heap.listsByName).length > 0 || Object.keys(heap.variablesByName).length > 0) {
19627
+ return true;
19628
+ }
19629
+ const domain = asRecord6(doc.domain);
19630
+ const packages = asRecord6(domain?.packages);
19631
+ if (packages && Object.keys(packages).length > 0) return true;
19632
+ const prompts = asRecord6(doc.prompts);
19633
+ if (prompts && Object.keys(prompts).length > 0) return true;
19634
+ const workflows = asRecord6(doc.workflows);
19635
+ if (workflows && Object.keys(workflows).length > 0) return true;
19636
+ return false;
19637
+ }
19638
+ async function waitForSessionDocumentContext(environment, timeoutMs = 3e3) {
19639
+ if (hasSessionDocumentContext(environment.document)) return;
19640
+ await new Promise((resolve) => {
19641
+ let settled = false;
19642
+ let unsubscribe = null;
19643
+ const settle = () => {
19644
+ if (settled) return;
19645
+ settled = true;
19646
+ if (unsubscribe) unsubscribe();
19647
+ clearTimeout(timer);
19648
+ resolve();
19649
+ };
19650
+ const timer = setTimeout(settle, timeoutMs);
19651
+ unsubscribe = environment.on("sync", (document) => {
19652
+ if (hasSessionDocumentContext(document)) {
19653
+ settle();
19654
+ }
19655
+ });
19656
+ });
19657
+ }
19327
19658
  function buildContinuationPreview(checkpoint, noProgressCount) {
19328
19659
  const lines = [
19329
19660
  `Controller no-progress count: ${noProgressCount}`,
@@ -19345,7 +19676,7 @@ function readableAgentMessage(message) {
19345
19676
  const show = asRecord6(record.show);
19346
19677
  const variableNames = asArray3(show?.variableNames).map((value) => String(value)).filter(Boolean);
19347
19678
  if (variableNames.length) {
19348
- return `Displayed ${variableNames.join(", ")}`;
19679
+ return variableNames.length === 1 ? "Displayed the selected record" : "Displayed the selected records";
19349
19680
  }
19350
19681
  if (typeof record.kind === "string") {
19351
19682
  return `Agent ${record.kind} message`;
@@ -20338,6 +20669,7 @@ function createAgentEvalHarness(options) {
20338
20669
  if (environment.getEffects().length > 0) break;
20339
20670
  await sleep2(250);
20340
20671
  }
20672
+ await waitForSessionDocumentContext(environment);
20341
20673
  await ensureDir(path.join(artifactDir, slugify(label)));
20342
20674
  return {
20343
20675
  label,
@@ -20619,6 +20951,7 @@ function createAgentEvalHarness(options) {
20619
20951
  );
20620
20952
  while (iteration < maxIterations) {
20621
20953
  const liveDoc = cloneJson(conversation.environment.document);
20954
+ const promptHeap = normalizeHeapSnapshot2(asRecord6(liveDoc?.heap));
20622
20955
  const pendingPrompts = filterPromptsByBoundary(
20623
20956
  liveDoc,
20624
20957
  getOpenPromptsFromDoc(liveDoc),
@@ -20634,7 +20967,11 @@ function createAgentEvalHarness(options) {
20634
20967
  ...referentFocus.variableNames
20635
20968
  ],
20636
20969
  listNames: [...workflowFocus.listNames, ...referentFocus.listNames],
20637
- entryPaths: [...workflowFocus.entryPaths, ...referentFocus.entryPaths]
20970
+ entryPaths: [
20971
+ ...workflowFocus.entryPaths,
20972
+ ...referentFocus.entryPaths,
20973
+ ...focusedHeapEntryPathsFromUiContext(promptHeap, input.uiContext)
20974
+ ]
20638
20975
  };
20639
20976
  const tools = conversation.environment.getEffects().map((tool) => ({
20640
20977
  name: tool.name,
@@ -20650,7 +20987,8 @@ function createAgentEvalHarness(options) {
20650
20987
  sessionContext: {
20651
20988
  sandboxId: conversation.environment.sandboxId,
20652
20989
  environmentId: conversation.environment.environmentId,
20653
- domainRevision: conversation.environment.domainRevision
20990
+ domainRevision: conversation.environment.domainRevision,
20991
+ uiContext: input.uiContext || null
20654
20992
  },
20655
20993
  heapSummary: projectHeapSummary(asRecord6(liveDoc?.heap), {
20656
20994
  focus: heapFocus
@@ -20699,6 +21037,24 @@ function createAgentEvalHarness(options) {
20699
21037
  title: iteration === 0 ? "Generating agent response" : "Generating continuation",
20700
21038
  message: request
20701
21039
  });
21040
+ const emittedGeneratedReasoningLines = /* @__PURE__ */ new Set();
21041
+ let generatedReasoningBuffer = "";
21042
+ const emitGeneratedReasoningLine = async (line) => {
21043
+ if (emittedGeneratedReasoningLines.has(line)) return;
21044
+ emittedGeneratedReasoningLines.add(line);
21045
+ await emitProgress(onProgress, {
21046
+ phase: "generation",
21047
+ status: "running",
21048
+ scenarioId: conversation.label,
21049
+ stepId: turnId,
21050
+ iteration: iteration + 1,
21051
+ templateId: renderedPrompt.templateId,
21052
+ templateVersion: renderedPrompt.templateVersion,
21053
+ title: "Generated reasoning comment",
21054
+ message: line,
21055
+ data: { source: "generated_code_comment" }
21056
+ });
21057
+ };
20702
21058
  const generation = await withTimeout2(
20703
21059
  generateTurnWithRepair(options.generator, {
20704
21060
  systemPrompt,
@@ -20706,6 +21062,30 @@ function createAgentEvalHarness(options) {
20706
21062
  request,
20707
21063
  attempt: 1,
20708
21064
  tools,
21065
+ onReplyDelta: async (delta) => {
21066
+ await emitProgress(onProgress, {
21067
+ phase: "generation",
21068
+ status: "running",
21069
+ scenarioId: conversation.label,
21070
+ stepId: turnId,
21071
+ iteration: iteration + 1,
21072
+ templateId: renderedPrompt.templateId,
21073
+ templateVersion: renderedPrompt.templateVersion,
21074
+ title: "Generated text reply delta",
21075
+ message: delta,
21076
+ data: { delta }
21077
+ });
21078
+ },
21079
+ onCodeDelta: async (delta) => {
21080
+ const parsed = consumeGranularReasoningOnlyChunk(
21081
+ generatedReasoningBuffer,
21082
+ delta
21083
+ );
21084
+ generatedReasoningBuffer = parsed.buffer;
21085
+ for (const line of parsed.reasoningLines) {
21086
+ await emitGeneratedReasoningLine(line);
21087
+ }
21088
+ },
20709
21089
  usageContext: {
20710
21090
  sandboxId: conversation.environment.sandboxId,
20711
21091
  environmentId: conversation.environment.environmentId,
@@ -20734,6 +21114,12 @@ function createAgentEvalHarness(options) {
20734
21114
  usage: tokenUsageForGenerationOutput(generation)
20735
21115
  }
20736
21116
  });
21117
+ const generatedReasoningLines = generation.code ? consumeGranularReasoningOnlyChunk("", generation.code, {
21118
+ final: true
21119
+ }).reasoningLines : [];
21120
+ for (const line of generatedReasoningLines) {
21121
+ await emitGeneratedReasoningLine(line);
21122
+ }
20737
21123
  const iterationLog = {
20738
21124
  iteration: iteration + 1,
20739
21125
  request,