@granular-software/sdk 0.4.36 → 0.4.37

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.
@@ -3956,11 +3956,22 @@ var TOKEN_REFRESH_LEEWAY_MS = 2 * 60 * 1e3;
3956
3956
  var TOKEN_REFRESH_RETRY_MS = 30 * 1e3;
3957
3957
  var MAX_TIMER_DELAY_MS = 2147483647;
3958
3958
  var DEBUG_WS = process.env.GRANULAR_DEBUG_WS === "1";
3959
+ var DEFAULT_RPC_TIMEOUT_MS = 3e4;
3960
+ var DOMAIN_PACKAGE_RPC_TIMEOUT_MS = 12e4;
3959
3961
  function debugWs(...args) {
3960
3962
  if (DEBUG_WS) {
3961
3963
  console.log(...args);
3962
3964
  }
3963
3965
  }
3966
+ function rpcTimeoutMsForMethod(method) {
3967
+ switch (method) {
3968
+ case "domain.fetchPackagePart":
3969
+ case "domain.getSummary":
3970
+ return DOMAIN_PACKAGE_RPC_TIMEOUT_MS;
3971
+ default:
3972
+ return DEFAULT_RPC_TIMEOUT_MS;
3973
+ }
3974
+ }
3964
3975
  var WSClient = class {
3965
3976
  ws = null;
3966
3977
  url;
@@ -4385,13 +4396,14 @@ var WSClient = class {
4385
4396
  return new Promise((resolve, reject) => {
4386
4397
  this.messageQueue.push({ resolve, reject, id });
4387
4398
  this.ws.send(JSON.stringify(request));
4399
+ const timeoutMs = rpcTimeoutMsForMethod(method);
4388
4400
  setTimeout(() => {
4389
4401
  const pending = this.messageQueue.find((q) => q.id === id);
4390
4402
  if (pending) {
4391
4403
  this.messageQueue = this.messageQueue.filter((q) => q.id !== id);
4392
4404
  reject(new Error(`RPC timeout: ${method}`));
4393
4405
  }
4394
- }, 3e4);
4406
+ }, timeoutMs);
4395
4407
  });
4396
4408
  }
4397
4409
  async handleIncomingRpc(request) {
@@ -4505,10 +4517,48 @@ function normalizePromptText(value) {
4505
4517
  function extractPromptTokens(value) {
4506
4518
  return normalizePromptText(value).split(/\s+/).map((token) => token.trim()).filter((token) => token.length > 0);
4507
4519
  }
4520
+ function parseJsonPromptChoiceOption(option) {
4521
+ const trimmed = option.trim();
4522
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return null;
4523
+ try {
4524
+ const parsed = JSON.parse(trimmed);
4525
+ return asRecord(parsed);
4526
+ } catch {
4527
+ return null;
4528
+ }
4529
+ }
4530
+ function normalizePromptChoiceOption(option) {
4531
+ if (typeof option === "string") {
4532
+ const record2 = parseJsonPromptChoiceOption(option);
4533
+ if (!record2) {
4534
+ return { value: option, label: option };
4535
+ }
4536
+ const value2 = typeof record2.value === "string" ? record2.value : typeof record2.id === "string" ? record2.id : typeof record2.label === "string" ? record2.label : JSON.stringify(record2);
4537
+ return {
4538
+ value: value2,
4539
+ label: typeof record2.label === "string" ? record2.label : value2,
4540
+ description: typeof record2.description === "string" ? record2.description : void 0
4541
+ };
4542
+ }
4543
+ const record = option;
4544
+ if (!record) {
4545
+ return { value: "", label: "" };
4546
+ }
4547
+ const nestedJson = (typeof record.value === "string" ? parseJsonPromptChoiceOption(record.value) : null) || (typeof record.label === "string" ? parseJsonPromptChoiceOption(record.label) : null);
4548
+ if (nestedJson) {
4549
+ return normalizePromptChoiceOption(nestedJson);
4550
+ }
4551
+ const value = typeof record.value === "string" ? record.value : typeof record.label === "string" ? record.label : JSON.stringify(record);
4552
+ return {
4553
+ value,
4554
+ label: typeof record.label === "string" ? record.label : value,
4555
+ description: typeof record.description === "string" ? record.description : void 0
4556
+ };
4557
+ }
4508
4558
  function scorePromptChoiceMatch(answer, answerTokens, option) {
4509
- const value = typeof option === "string" ? option : typeof option?.value === "string" ? option.value : "";
4510
- const label = typeof option === "string" ? option : typeof option?.label === "string" ? option.label : "";
4511
- const description = typeof option === "string" ? "" : typeof option?.description === "string" ? option.description : "";
4559
+ const choice = normalizePromptChoiceOption(option);
4560
+ const { value, label } = choice;
4561
+ const description = choice.description || "";
4512
4562
  const haystack = normalizePromptText([value, label, description].filter(Boolean).join(" "));
4513
4563
  if (!haystack) return { score: 0, resolvedValue: value || label || null };
4514
4564
  let score = 0;
@@ -4544,7 +4594,9 @@ function normalizePrompt(rawValue) {
4544
4594
  type: normalizePromptType(source === raw ? raw : { ...raw, ...source }),
4545
4595
  title: typeof source.title === "string" ? source.title : "Input required",
4546
4596
  message: typeof source.message === "string" ? source.message : "",
4547
- options: Array.isArray(source.options) ? source.options : void 0,
4597
+ options: Array.isArray(source.options) ? source.options.map(
4598
+ (option) => typeof option === "string" || asRecord(option) ? normalizePromptChoiceOption(option) : option
4599
+ ) : void 0,
4548
4600
  defaultValue: source.defaultValue,
4549
4601
  placeholder: typeof source.placeholder === "string" ? source.placeholder : void 0,
4550
4602
  allowEmpty: typeof source.allowEmpty === "boolean" ? source.allowEmpty : void 0,
@@ -4572,6 +4624,22 @@ function resolvePromptAnswer(prompt, answer) {
4572
4624
  }
4573
4625
 
4574
4626
  // src/session.ts
4627
+ var PROMPT_TRANSCRIPT_APPEND_TIMEOUT_MS = 5e3;
4628
+ function withPromptTranscriptTimeout(promise) {
4629
+ let timeout = null;
4630
+ return Promise.race([
4631
+ promise,
4632
+ new Promise((_, reject) => {
4633
+ timeout = setTimeout(() => {
4634
+ reject(new Error("Timed out appending prompt answer transcript."));
4635
+ }, PROMPT_TRANSCRIPT_APPEND_TIMEOUT_MS);
4636
+ })
4637
+ ]).finally(() => {
4638
+ if (timeout) {
4639
+ clearTimeout(timeout);
4640
+ }
4641
+ });
4642
+ }
4575
4643
  var Session = class {
4576
4644
  client;
4577
4645
  clientId;
@@ -4588,6 +4656,8 @@ var Session = class {
4588
4656
  lastKnownTools = /* @__PURE__ */ new Map();
4589
4657
  /** Last seen live prompts, keyed by prompt id, for answer normalization */
4590
4658
  promptCache = /* @__PURE__ */ new Map();
4659
+ /** Prompt ids locally answered before the document sync catches up. */
4660
+ hiddenPromptIds = /* @__PURE__ */ new Set();
4591
4661
  constructor(client, clientId) {
4592
4662
  this.client = client;
4593
4663
  this.clientId = clientId || `client_${Date.now()}`;
@@ -4723,8 +4793,9 @@ var Session = class {
4723
4793
  * `effect.invoke` RPC back to the sandbox effect host, where the registered handlers
4724
4794
  * execute locally and return the result to the sandbox.
4725
4795
  */
4726
- async submitJob(code, domainRevision) {
4727
- let revision = domainRevision || this.currentDomainRevision || this.extractDomainRevisionFromDoc(this.client.doc) || void 0;
4796
+ async submitJob(code, domainRevisionOrOptions) {
4797
+ const options = typeof domainRevisionOrOptions === "string" ? { domainRevision: domainRevisionOrOptions } : domainRevisionOrOptions || {};
4798
+ let revision = options.domainRevision || this.currentDomainRevision || this.extractDomainRevisionFromDoc(this.client.doc) || void 0;
4728
4799
  if (!revision) {
4729
4800
  try {
4730
4801
  const summary = await this.getDomain();
@@ -4739,7 +4810,9 @@ var Session = class {
4739
4810
  }
4740
4811
  const result = await this.client.call("job.submit", {
4741
4812
  domainRevision: revision,
4742
- code
4813
+ code,
4814
+ metadata: options.metadata,
4815
+ agent: options.agent
4743
4816
  });
4744
4817
  if (!result.jobId) {
4745
4818
  throw new Error("Failed to submit job: no jobId returned");
@@ -4780,25 +4853,39 @@ var Session = class {
4780
4853
  const prompt = this.promptCache.get(promptId);
4781
4854
  const resolvedAnswer = resolvePromptAnswer(prompt, answer);
4782
4855
  this.promptCache.delete(promptId);
4783
- await this.client.call("prompt.answer", {
4784
- promptId,
4785
- answer: resolvedAnswer,
4786
- value: resolvedAnswer
4787
- });
4856
+ this.hiddenPromptIds.add(promptId);
4857
+ try {
4858
+ await this.client.call("prompt.answer", {
4859
+ promptId,
4860
+ answer: resolvedAnswer,
4861
+ value: resolvedAnswer
4862
+ });
4863
+ } catch (error) {
4864
+ this.hiddenPromptIds.delete(promptId);
4865
+ if (prompt) {
4866
+ this.promptCache.set(promptId, prompt);
4867
+ }
4868
+ throw error;
4869
+ }
4788
4870
  try {
4789
4871
  const content = this.stringifyConversationValue(resolvedAnswer);
4790
4872
  if (content.trim()) {
4791
- await this.appendConversationMessage({
4792
- role: "user",
4793
- content,
4794
- promptId
4795
- });
4873
+ await withPromptTranscriptTimeout(
4874
+ this.appendConversationMessage({
4875
+ role: "user",
4876
+ content,
4877
+ promptId
4878
+ })
4879
+ );
4796
4880
  }
4797
4881
  } catch {
4798
4882
  }
4799
4883
  }
4800
4884
  async appendConversationMessage(input) {
4801
- return this.client.call("conversation.append", input);
4885
+ return this.client.call(
4886
+ "conversation.append",
4887
+ input
4888
+ );
4802
4889
  }
4803
4890
  /**
4804
4891
  * Get the current list of available effects.
@@ -4807,9 +4894,53 @@ var Session = class {
4807
4894
  getEffects() {
4808
4895
  const doc = this.client.doc;
4809
4896
  const toolMap = /* @__PURE__ */ new Map();
4810
- const domainPkg = doc.domain?.packages?.domain;
4811
- if (domainPkg?.tools && Array.isArray(domainPkg.tools)) {
4812
- for (const tool of domainPkg.tools) {
4897
+ const domainPackages = doc.domain?.packages;
4898
+ const packageCandidates = domainPackages && typeof domainPackages === "object" ? [
4899
+ domainPackages.domain,
4900
+ domainPackages["@sandbox/domain"],
4901
+ ...Object.values(domainPackages)
4902
+ ].filter(Boolean) : [];
4903
+ for (const domainPkg of packageCandidates) {
4904
+ if (domainPkg?.tools && Array.isArray(domainPkg.tools)) {
4905
+ for (const tool of domainPkg.tools) {
4906
+ if (!tool?.name || toolMap.has(tool.name)) continue;
4907
+ toolMap.set(tool.name, {
4908
+ name: tool.name,
4909
+ description: tool.description,
4910
+ inputSchema: tool.inputSchema,
4911
+ outputSchema: tool.outputSchema,
4912
+ className: tool.className || void 0,
4913
+ static: tool.static || false,
4914
+ ready: false,
4915
+ publishedAt: void 0
4916
+ });
4917
+ }
4918
+ }
4919
+ if (!domainPkg?.classes || typeof domainPkg.classes !== "object") {
4920
+ continue;
4921
+ }
4922
+ for (const [className, classDef] of Object.entries(
4923
+ domainPkg.classes
4924
+ )) {
4925
+ const methods = Array.isArray(classDef?.methods) ? classDef.methods : [];
4926
+ for (const method of methods) {
4927
+ if (!method?.name || toolMap.has(method.name)) continue;
4928
+ toolMap.set(method.name, {
4929
+ name: method.name,
4930
+ description: method.description,
4931
+ inputSchema: method.inputSchema,
4932
+ outputSchema: method.outputSchema,
4933
+ className: method.className || classDef?.name || className,
4934
+ static: method.static || false,
4935
+ ready: false,
4936
+ publishedAt: void 0
4937
+ });
4938
+ }
4939
+ }
4940
+ }
4941
+ const legacyDomainPkg = doc.domain?.packages?.domain;
4942
+ if (legacyDomainPkg?.tools && Array.isArray(legacyDomainPkg.tools)) {
4943
+ for (const tool of legacyDomainPkg.tools) {
4813
4944
  if (!tool?.name) continue;
4814
4945
  toolMap.set(tool.name, {
4815
4946
  name: tool.name,
@@ -4823,6 +4954,27 @@ var Session = class {
4823
4954
  });
4824
4955
  }
4825
4956
  }
4957
+ if (legacyDomainPkg?.classes && typeof legacyDomainPkg.classes === "object") {
4958
+ for (const [className, classDef] of Object.entries(
4959
+ legacyDomainPkg.classes
4960
+ )) {
4961
+ const methods = Array.isArray(classDef?.methods) ? classDef.methods : [];
4962
+ for (const method of methods) {
4963
+ if (!method?.name || toolMap.has(method.name)) continue;
4964
+ toolMap.set(method.name, {
4965
+ name: method.name,
4966
+ description: method.description,
4967
+ inputSchema: method.inputSchema,
4968
+ outputSchema: method.outputSchema,
4969
+ className: method.className || classDef?.name || className,
4970
+ static: method.static || false,
4971
+ ready: false,
4972
+ publishedAt: void 0
4973
+ });
4974
+ }
4975
+ }
4976
+ }
4977
+ const hasPolicyFilteredDomainTools = toolMap.size > 0;
4826
4978
  const catalogs = doc.catalog?.rawToolCatalogs || {};
4827
4979
  for (const [clientId, catalog] of Object.entries(catalogs)) {
4828
4980
  const cat = catalog;
@@ -4830,6 +4982,7 @@ var Session = class {
4830
4982
  for (const tool of cat.tools) {
4831
4983
  if (!tool?.name) continue;
4832
4984
  const existing = toolMap.get(tool.name);
4985
+ if (hasPolicyFilteredDomainTools && !existing) continue;
4833
4986
  if (existing?.publishedAt && cat.publishedAt && existing.publishedAt > cat.publishedAt)
4834
4987
  continue;
4835
4988
  const isLocal = clientId === this.clientId;
@@ -4849,6 +5002,24 @@ var Session = class {
4849
5002
  }
4850
5003
  return Array.from(toolMap.values());
4851
5004
  }
5005
+ /**
5006
+ * Return the currently open prompt payloads known to this session.
5007
+ *
5008
+ * These come from live `prompt` / `prompt.request` websocket events and
5009
+ * preserve the exact shape used by `answerPrompt(...)`.
5010
+ */
5011
+ getPrompts() {
5012
+ return Array.from(this.promptCache.values()).map((prompt) => ({
5013
+ ...prompt,
5014
+ options: Array.isArray(prompt.options) ? prompt.options.map(
5015
+ (option) => typeof option === "string" ? option : { ...option }
5016
+ ) : void 0,
5017
+ metadata: prompt.metadata ? { ...prompt.metadata } : void 0
5018
+ }));
5019
+ }
5020
+ getHiddenPromptIds() {
5021
+ return Array.from(this.hiddenPromptIds);
5022
+ }
4852
5023
  /**
4853
5024
  * Backwards-compatible alias for `getEffects()`.
4854
5025
  */
@@ -4948,11 +5119,7 @@ var Session = class {
4948
5119
  if (!normalizedDocs) {
4949
5120
  return normalizedTypes;
4950
5121
  }
4951
- return [
4952
- normalizedTypes,
4953
- "Generated usage notes from ./sandbox-tools docs:",
4954
- normalizedDocs
4955
- ].join("\n\n");
5122
+ return [normalizedTypes, "[Docs]", normalizedDocs].join("\n\n");
4956
5123
  }
4957
5124
  if (normalizedDocs) {
4958
5125
  return normalizedDocs;
@@ -5174,6 +5341,7 @@ import { ${allImports} } from "./sandbox-tools";
5174
5341
  const emitPrompt = (payload) => {
5175
5342
  const prompt = normalizePrompt(payload);
5176
5343
  if (!prompt) return;
5344
+ this.hiddenPromptIds.delete(prompt.id);
5177
5345
  this.promptCache.set(prompt.id, prompt);
5178
5346
  this.emit("prompt", prompt);
5179
5347
  };
@@ -5356,6 +5524,7 @@ var JobImplementation = class {
5356
5524
  eventListeners = /* @__PURE__ */ new Map();
5357
5525
  bufferedAgentMessages = [];
5358
5526
  bufferedAgentMessageIds = /* @__PURE__ */ new Set();
5527
+ resultSettled = false;
5359
5528
  metadata;
5360
5529
  constructor(id, client, initialState) {
5361
5530
  this.id = id;
@@ -5380,7 +5549,9 @@ var JobImplementation = class {
5380
5549
  if (execData.error) {
5381
5550
  this.finalize("failed", void 0, execData.error);
5382
5551
  } else {
5383
- this.finalize("succeeded", execData.result);
5552
+ this.finalize("succeeded", execData.result, void 0, {
5553
+ hasResult: Object.prototype.hasOwnProperty.call(execData, "result")
5554
+ });
5384
5555
  }
5385
5556
  this.emit("status", this.status);
5386
5557
  }
@@ -5416,9 +5587,6 @@ var JobImplementation = class {
5416
5587
  if (normalizedStatus === "failed" || normalizedStatus === "timeout" || normalizedStatus === "canceled") {
5417
5588
  this.finalize(normalizedStatus);
5418
5589
  }
5419
- if (normalizedStatus === "succeeded") {
5420
- this.finalize("succeeded");
5421
- }
5422
5590
  this.emit("status", normalizedStatus);
5423
5591
  });
5424
5592
  this.client.on(`job.${id}.stdout`, (line) => {
@@ -5438,7 +5606,7 @@ var JobImplementation = class {
5438
5606
  this.emit("stderr", line);
5439
5607
  });
5440
5608
  this.client.on(`job.${id}.result`, (result) => {
5441
- this.finalize("succeeded", result);
5609
+ this.finalize("succeeded", result, void 0, { hasResult: true });
5442
5610
  });
5443
5611
  this.client.on(`job.${id}.error`, (error) => {
5444
5612
  this.finalize("failed", void 0, error);
@@ -5459,7 +5627,9 @@ var JobImplementation = class {
5459
5627
  this.client.on("job.completed", (data) => {
5460
5628
  const jobData = data;
5461
5629
  if (jobData.jobId === id) {
5462
- this.finalize("succeeded", jobData.result);
5630
+ this.finalize("succeeded", jobData.result, void 0, {
5631
+ hasResult: true
5632
+ });
5463
5633
  this.emit("status", this.status);
5464
5634
  }
5465
5635
  });
@@ -5584,7 +5754,7 @@ var JobImplementation = class {
5584
5754
  this.metadata.status = "running";
5585
5755
  }
5586
5756
  }
5587
- finalize(status, result, error) {
5757
+ finalize(status, result, error, options = {}) {
5588
5758
  if (!this.metadata.startedAt) {
5589
5759
  this.metadata.startedAt = Date.now();
5590
5760
  }
@@ -5592,14 +5762,18 @@ var JobImplementation = class {
5592
5762
  this.metadata.status = status;
5593
5763
  this.metadata.completedAt = this.metadata.completedAt || Date.now();
5594
5764
  this.metadata.durationMs = this.metadata.completedAt - this.metadata.startedAt;
5595
- if (result !== void 0) {
5765
+ if (!this.resultSettled && (options.hasResult || result !== void 0)) {
5596
5766
  this.metadata.result = sanitizeFeedbackValue(result);
5767
+ this.resultSettled = true;
5597
5768
  this._resolveResult(result);
5598
5769
  }
5599
- if (error !== void 0) {
5600
- const message = error instanceof Error ? error.message : String(error);
5770
+ if (!this.resultSettled && (error !== void 0 || status === "failed" || status === "timeout" || status === "canceled")) {
5771
+ const fallbackError = new Error(`Job ${this.id} ${status}.`);
5772
+ const cause = error ?? fallbackError;
5773
+ const message = cause instanceof Error ? cause.message : String(cause);
5601
5774
  this.metadata.error = truncateFeedbackString(message);
5602
- this._rejectResult(error);
5775
+ this.resultSettled = true;
5776
+ this._rejectResult(cause);
5603
5777
  }
5604
5778
  }
5605
5779
  upsertToolCall(next) {
@@ -5682,6 +5856,17 @@ function humanTextFromStdout(stdout) {
5682
5856
  }
5683
5857
  return null;
5684
5858
  }
5859
+ function responseTextFromAgentMessages(agentMessages) {
5860
+ for (const message of [...agentMessages].reverse()) {
5861
+ const record = asRecord2(message);
5862
+ if (!record) continue;
5863
+ for (const key of RESPONSE_KEYS) {
5864
+ const normalized = normalizeText(record[key]);
5865
+ if (normalized) return normalized;
5866
+ }
5867
+ }
5868
+ return null;
5869
+ }
5685
5870
  function pushString(target, value) {
5686
5871
  if (typeof value === "string" && value.trim()) {
5687
5872
  target.add(value.trim());
@@ -5707,6 +5892,41 @@ function collectReferencesFromRecord(record, refs) {
5707
5892
  for (const key of VARIABLE_ARRAY_KEY_CANDIDATES)
5708
5893
  pushStringArray(refs.variableNames, record[key]);
5709
5894
  }
5895
+ function stringValue(record, keys) {
5896
+ for (const key of keys) {
5897
+ const value = record[key];
5898
+ if (typeof value === "string" && value.trim()) {
5899
+ return value.trim();
5900
+ }
5901
+ }
5902
+ return null;
5903
+ }
5904
+ function findEntryPathForRecord(record, heap) {
5905
+ const directPath = stringValue(record, ["entryPath", "path"]);
5906
+ if (directPath && heap.entriesByPath?.[directPath]) {
5907
+ return directPath;
5908
+ }
5909
+ const id = stringValue(record, ["id", "_id", "recordId", "objectId"]);
5910
+ if (!id) {
5911
+ return null;
5912
+ }
5913
+ const className = stringValue(record, [
5914
+ "className",
5915
+ "_className",
5916
+ "__className",
5917
+ "prototype",
5918
+ "type"
5919
+ ]);
5920
+ const entries = Object.values(heap.entriesByPath || {});
5921
+ const exact = entries.find(
5922
+ (entry) => entry.id === id && (!className || entry.className === className || entry.prototypes?.includes(className))
5923
+ );
5924
+ if (exact?.path) {
5925
+ return exact.path;
5926
+ }
5927
+ const idOnlyMatches = entries.filter((entry) => entry.id === id);
5928
+ return idOnlyMatches.length === 1 ? idOnlyMatches[0].path : null;
5929
+ }
5710
5930
  function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__ */ new Set()) {
5711
5931
  if (value === null || value === void 0 || depth > 4 || seen.has(value))
5712
5932
  return;
@@ -5727,6 +5947,8 @@ function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__
5727
5947
  const record = asRecord2(value);
5728
5948
  if (!record) return;
5729
5949
  seen.add(value);
5950
+ const entryPath = findEntryPathForRecord(record, heap);
5951
+ if (entryPath) refs.entryPaths.add(entryPath);
5730
5952
  collectReferencesFromRecord(record, refs);
5731
5953
  for (const key of UI_CONTAINER_KEYS) {
5732
5954
  const nested = asRecord2(record[key]);
@@ -5835,6 +6057,7 @@ function resolveJobPresentation({
5835
6057
  jobId,
5836
6058
  result,
5837
6059
  stdout = [],
6060
+ agentMessages = [],
5838
6061
  sessionHeap,
5839
6062
  allowExplicitArtifacts = true
5840
6063
  }) {
@@ -5867,7 +6090,7 @@ function resolveJobPresentation({
5867
6090
  const hasExplicitArtifacts = allowExplicitArtifacts && (explicitEntries.length > 0 || explicitLists.length > 0);
5868
6091
  const lists = hasExplicitArtifacts ? explicitLists : jobLists;
5869
6092
  const entries = hasExplicitArtifacts ? explicitEntries : changedEntries;
5870
- const responseText = extractResponseText(result, stdout) || fallbackResponseText(entries, lists);
6093
+ const responseText = extractResponseText(result, stdout) || responseTextFromAgentMessages(agentMessages) || fallbackResponseText(entries, lists);
5871
6094
  return {
5872
6095
  responseText,
5873
6096
  entries,
@@ -10343,6 +10566,67 @@ external_exports.object({
10343
10566
  transitions: external_exports.array(StateMachineTransitionSchema),
10344
10567
  finalStates: external_exports.array(external_exports.string()).optional()
10345
10568
  }).strict();
10569
+ var POLICY_OPERATORS = [
10570
+ "eq",
10571
+ "neq",
10572
+ "gt",
10573
+ "gte",
10574
+ "lt",
10575
+ "lte",
10576
+ "contains",
10577
+ "not_contains",
10578
+ "starts_with",
10579
+ "ends_with",
10580
+ "exists"
10581
+ ];
10582
+ var PolicyPredicateSchema = external_exports.object({
10583
+ path: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional(),
10584
+ field: external_exports.string().optional(),
10585
+ input: external_exports.string().optional(),
10586
+ operator: external_exports.enum([...POLICY_OPERATORS]),
10587
+ stringValue: external_exports.string().optional(),
10588
+ numberValue: external_exports.number().optional(),
10589
+ booleanValue: external_exports.boolean().optional(),
10590
+ value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()]).optional()
10591
+ }).strict();
10592
+ var PolicyStateMachinePredicateSchema = external_exports.object({
10593
+ machine: external_exports.string().min(1),
10594
+ operator: external_exports.enum([...POLICY_OPERATORS]),
10595
+ state: external_exports.string().optional(),
10596
+ stringValue: external_exports.string().optional()
10597
+ }).strict();
10598
+ var PolicyConditionSchema = external_exports.lazy(
10599
+ () => external_exports.object({
10600
+ all: external_exports.array(PolicyConditionSchema).optional(),
10601
+ any: external_exports.array(PolicyConditionSchema).optional(),
10602
+ not: PolicyConditionSchema.optional(),
10603
+ input: PolicyPredicateSchema.optional(),
10604
+ object: PolicyPredicateSchema.optional(),
10605
+ stateMachine: PolicyStateMachinePredicateSchema.optional()
10606
+ }).strict().refine(
10607
+ (data) => [
10608
+ data.all,
10609
+ data.any,
10610
+ data.not,
10611
+ data.input,
10612
+ data.object,
10613
+ data.stateMachine
10614
+ ].filter((value) => value !== void 0).length === 1,
10615
+ {
10616
+ message: "Policy condition must define exactly one of all, any, not, input, object, or stateMachine"
10617
+ }
10618
+ )
10619
+ );
10620
+ var PolicyRuleSchema = external_exports.object({
10621
+ id: external_exports.string().min(1).optional(),
10622
+ reason: external_exports.string().optional(),
10623
+ when: PolicyConditionSchema
10624
+ }).strict();
10625
+ var PoliciesSchema = external_exports.object({
10626
+ allowWhen: external_exports.array(PolicyRuleSchema).optional(),
10627
+ confirmWhen: external_exports.array(PolicyRuleSchema).optional(),
10628
+ denyWhen: external_exports.array(PolicyRuleSchema).optional()
10629
+ }).strict();
10346
10630
  external_exports.object({
10347
10631
  postCondition: external_exports.union([
10348
10632
  external_exports.string(),
@@ -10372,7 +10656,8 @@ external_exports.object({
10372
10656
  reason: external_exports.string().optional(),
10373
10657
  mode: external_exports.string().optional()
10374
10658
  }).strict()
10375
- ]).optional()
10659
+ ]).optional(),
10660
+ policies: PoliciesSchema.optional()
10376
10661
  }).strict();
10377
10662
 
10378
10663
  // ../metamodel-core/src/index.ts
@@ -11404,6 +11689,148 @@ var noteMetamodelPackage = defineMetamodelPackage({
11404
11689
  }
11405
11690
  });
11406
11691
 
11692
+ // ../policy-engine/src/index.ts
11693
+ function isRecord(value) {
11694
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
11695
+ }
11696
+ function normalizePath(value) {
11697
+ if (Array.isArray(value)) {
11698
+ return value.map((part) => String(part)).filter(Boolean);
11699
+ }
11700
+ if (typeof value === "string") {
11701
+ return value.includes(".") ? value.split(".").filter(Boolean) : [value];
11702
+ }
11703
+ return [];
11704
+ }
11705
+ function firstDefinedValue(spec) {
11706
+ if ("value" in spec) return spec.value;
11707
+ if ("stringValue" in spec) return spec.stringValue;
11708
+ if ("numberValue" in spec) return spec.numberValue;
11709
+ if ("booleanValue" in spec) return spec.booleanValue;
11710
+ if ("state" in spec) return spec.state;
11711
+ return void 0;
11712
+ }
11713
+ function normalizeCondition(input) {
11714
+ if (input === void 0 || input === null) return { kind: "always" };
11715
+ if (!isRecord(input)) {
11716
+ throw new Error("Policy condition must be an object");
11717
+ }
11718
+ if (Array.isArray(input.all)) {
11719
+ return {
11720
+ kind: "all",
11721
+ conditions: input.all.map((item) => normalizeCondition(item))
11722
+ };
11723
+ }
11724
+ if (Array.isArray(input.any)) {
11725
+ return {
11726
+ kind: "any",
11727
+ conditions: input.any.map((item) => normalizeCondition(item))
11728
+ };
11729
+ }
11730
+ if (input.not !== void 0) {
11731
+ return { kind: "not", condition: normalizeCondition(input.not) };
11732
+ }
11733
+ for (const source of ["input", "object", "stateMachine"]) {
11734
+ const raw = input[source];
11735
+ if (!isRecord(raw)) continue;
11736
+ const operator = raw.operator;
11737
+ if (operator !== "eq" && operator !== "neq" && operator !== "gt" && operator !== "gte" && operator !== "lt" && operator !== "lte" && operator !== "contains" && operator !== "not_contains" && operator !== "starts_with" && operator !== "ends_with" && operator !== "exists") {
11738
+ throw new Error(`Unsupported policy operator: ${String(operator)}`);
11739
+ }
11740
+ if (source === "stateMachine") {
11741
+ const machine = typeof raw.machine === "string" ? raw.machine : "";
11742
+ if (!machine) throw new Error("stateMachine condition requires machine");
11743
+ return {
11744
+ kind: "predicate",
11745
+ source,
11746
+ path: [machine],
11747
+ machine,
11748
+ operator,
11749
+ value: firstDefinedValue(raw)
11750
+ };
11751
+ }
11752
+ const path2 = normalizePath(raw.path ?? raw.field ?? raw.input);
11753
+ if (path2.length === 0) {
11754
+ throw new Error(`${source} condition requires a path`);
11755
+ }
11756
+ return {
11757
+ kind: "predicate",
11758
+ source,
11759
+ path: path2,
11760
+ operator,
11761
+ value: firstDefinedValue(raw)
11762
+ };
11763
+ }
11764
+ throw new Error(
11765
+ "Policy condition must contain all, any, not, input, object, or stateMachine"
11766
+ );
11767
+ }
11768
+ function summarizeCondition(condition) {
11769
+ switch (condition.kind) {
11770
+ case "always":
11771
+ return "always";
11772
+ case "all":
11773
+ return condition.conditions.map(summarizeCondition).join(" and ");
11774
+ case "any":
11775
+ return condition.conditions.map(summarizeCondition).join(" or ");
11776
+ case "not":
11777
+ return `not (${summarizeCondition(condition.condition)})`;
11778
+ case "predicate": {
11779
+ const path2 = condition.source === "stateMachine" ? `stateMachine.${condition.machine || condition.path.join(".")}` : `${condition.source}.${condition.path.join(".")}`;
11780
+ if (condition.operator === "exists") return `${path2} exists`;
11781
+ return `${path2} ${condition.operator} ${String(condition.value)}`;
11782
+ }
11783
+ }
11784
+ }
11785
+
11786
+ // ../metamodel-policy/src/index.ts
11787
+ function escapeGraphqlString(value) {
11788
+ return JSON.stringify(value);
11789
+ }
11790
+ function buildPolicyMutations(effectKey, spec) {
11791
+ const policies = spec.policies;
11792
+ if (!policies) return [];
11793
+ const mutations = [];
11794
+ const addRules = (key, outcome) => {
11795
+ const rules = policies[key] || [];
11796
+ rules.forEach((rule, index) => {
11797
+ const condition = normalizeCondition(rule.when);
11798
+ const summary = rule.reason || summarizeCondition(condition);
11799
+ const id = rule.id || `${effectKey}:${outcome}:${index + 1}`;
11800
+ mutations.push({
11801
+ label: `set policy ${outcome} on ${effectKey}`,
11802
+ query: `mutation { set_policy_rule(effect_key: ${escapeGraphqlString(effectKey)}, policy_id: ${escapeGraphqlString(id)}, outcome: ${escapeGraphqlString(outcome)}, reason: ${escapeGraphqlString(summary)}, condition_json: ${escapeGraphqlString(JSON.stringify(condition))}) }`
11803
+ });
11804
+ });
11805
+ };
11806
+ addRules("allowWhen", "allow");
11807
+ addRules("confirmWhen", "confirm");
11808
+ addRules("denyWhen", "deny");
11809
+ return mutations;
11810
+ }
11811
+ var policyMetamodelPackage = defineMetamodelPackage({
11812
+ id: "policy",
11813
+ manifest: {
11814
+ buildEffectMutations: buildPolicyMutations
11815
+ },
11816
+ summary: {
11817
+ selections: {
11818
+ methodFields: ["policies"]
11819
+ },
11820
+ readMethodSummary(rawMethod) {
11821
+ return rawMethod.policies ? { metamodels: { policies: rawMethod.policies } } : {};
11822
+ }
11823
+ },
11824
+ docs: {
11825
+ effectRows: [
11826
+ {
11827
+ key: "policies",
11828
+ description: "Universal effect policies with allowWhen, confirmWhen, and denyWhen structural conditions."
11829
+ }
11830
+ ]
11831
+ }
11832
+ });
11833
+
11407
11834
  // ../metamodel-required/src/index.ts
11408
11835
  function buildRequiredFieldMutations(fieldPath, required) {
11409
11836
  if (!required) return [];
@@ -12178,7 +12605,8 @@ var DEFAULT_METAMODEL_PACKAGES = [
12178
12605
  searchableMetamodelPackage,
12179
12606
  validationRuleMetamodelPackage,
12180
12607
  stateMachineMetamodelPackage,
12181
- effectBehaviorsMetamodelPackage
12608
+ effectBehaviorsMetamodelPackage,
12609
+ policyMetamodelPackage
12182
12610
  ];
12183
12611
  createMetamodelRegistry(
12184
12612
  DEFAULT_METAMODEL_PACKAGES
@@ -12245,6 +12673,12 @@ var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_COUNT = 3;
12245
12673
  var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_DELAY_MS = 1e3;
12246
12674
  var LOCAL_CONTROL_REQUEST_RETRY_COUNT = 4;
12247
12675
  var LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS = 500;
12676
+ var SESSION_DATA_REQUEST_RETRY_COUNT = 4;
12677
+ var SESSION_DATA_REQUEST_RETRY_DELAY_MS = 500;
12678
+ var EFFECT_HOST_CONNECT_TIMEOUT_MS = 15e3;
12679
+ var EFFECT_CATALOG_SYNC_TIMEOUT_MS = 3e4;
12680
+ var EFFECT_CATALOG_SYNC_RETRY_COUNT = 3;
12681
+ var EFFECT_CATALOG_SYNC_RETRY_DELAY_MS = 1e3;
12248
12682
  function planRecordObjectsChunks(records, batchSize) {
12249
12683
  const total = records.length;
12250
12684
  const size = Math.max(1, Math.min(batchSize, total));
@@ -12259,6 +12693,19 @@ function planRecordObjectsChunks(records, batchSize) {
12259
12693
  function sleep(ms) {
12260
12694
  return new Promise((resolve) => setTimeout(resolve, ms));
12261
12695
  }
12696
+ function withTimeout(promise, timeoutMs, label) {
12697
+ let timer = null;
12698
+ const timeout = new Promise((_, reject) => {
12699
+ timer = setTimeout(() => {
12700
+ reject(new Error(`${label} timed out after ${timeoutMs}ms`));
12701
+ }, timeoutMs);
12702
+ });
12703
+ return Promise.race([promise, timeout]).finally(() => {
12704
+ if (timer) {
12705
+ clearTimeout(timer);
12706
+ }
12707
+ });
12708
+ }
12262
12709
  function isLocalControlUrl(url) {
12263
12710
  try {
12264
12711
  const parsed = new URL(url);
@@ -12272,7 +12719,19 @@ function isRetryableLocalWorkerRestart(status, body, url) {
12272
12719
  }
12273
12720
  function isRetryableRecordObjectsError(error) {
12274
12721
  const message = error instanceof Error ? error.message : String(error);
12275
- return /worker restarted mid-request|econnreset|network|socket connection was closed unexpectedly|timed out/i.test(
12722
+ return /worker restarted mid-request|econnreset|network|socket connection was closed unexpectedly|timed out|bad gateway|too many requests|gateway timeout|control plane api error \((?:429|500|502|503|504)\)|graphql api error \((?:429|500|502|503|504)\)|failed to record batch/i.test(
12723
+ message
12724
+ );
12725
+ }
12726
+ function isRetryableEffectRegistrationError(error) {
12727
+ const message = error instanceof Error ? error.message : String(error);
12728
+ return /timed out|websocket disconnected|websocket not connected|rpc timeout|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(
12729
+ message
12730
+ );
12731
+ }
12732
+ function isRetryableSessionDataError(error) {
12733
+ const message = error instanceof Error ? error.message : String(error);
12734
+ return /network connection lost|worker restarted mid-request|econnreset|socket connection was closed unexpectedly|bad gateway|gateway timeout|service unavailable|session data api error \((?:429|500|502|503|504)\)/i.test(
12276
12735
  message
12277
12736
  );
12278
12737
  }
@@ -12294,16 +12753,28 @@ function computeEffectRegistrationKey(effect) {
12294
12753
  effect.versionSelector
12295
12754
  )}`;
12296
12755
  }
12297
- function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId) {
12298
- const url = new URL(apiUrl);
12299
- if (url.pathname.endsWith("/granular/ws/connect")) {
12756
+ function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId, effectHostUrl) {
12757
+ const overrideUrl = effectHostUrl || process.env.GRANULAR_EFFECT_HOST_URL || process.env.EFFECT_HOST_URL;
12758
+ const api = new URL(apiUrl);
12759
+ const localRuntimeBase = process.env.RUNTIME_ORCHESTRATOR_URL || (isLocalControlUrl(apiUrl) ? `${api.protocol}//${api.hostname}:8791` : "");
12760
+ const url = new URL(overrideUrl || localRuntimeBase || apiUrl);
12761
+ if (url.protocol === "https:") {
12762
+ url.protocol = "wss:";
12763
+ } else if (url.protocol === "http:") {
12764
+ url.protocol = "ws:";
12765
+ }
12766
+ if (!overrideUrl && isLocalControlUrl(apiUrl) && api.pathname.endsWith("/granular")) {
12767
+ url.pathname = "/granular/orchestrator/effects/connect";
12768
+ } else if (url.pathname.endsWith("/granular/ws/connect")) {
12300
12769
  url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
12301
12770
  } else if (url.pathname.endsWith("/granular")) {
12302
- url.pathname = `${url.pathname.replace(/\/$/, "")}/effects/connect`;
12771
+ url.pathname = isLocalControlUrl(url.toString()) ? "/granular/orchestrator/effects/connect" : `${url.pathname.replace(/\/$/, "")}/effects/connect`;
12303
12772
  } else if (url.pathname.endsWith("/v2/ws/connect")) {
12304
12773
  url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
12305
12774
  } else if (url.pathname.endsWith("/v2/ws")) {
12306
12775
  url.pathname = url.pathname.replace(/\/ws$/, "/effects/connect");
12776
+ } else if (url.pathname === "/" && isLocalControlUrl(url.toString()) && (url.port === "8791" || !overrideUrl && Boolean(localRuntimeBase))) {
12777
+ url.pathname = "/granular/orchestrator/effects/connect";
12307
12778
  } else if (url.pathname.endsWith("/ws/connect")) {
12308
12779
  url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
12309
12780
  } else if (url.pathname.endsWith("/ws")) {
@@ -12338,6 +12809,79 @@ function normalizeHeapSnapshot(raw) {
12338
12809
  updatedAt: typeof heap.updatedAt === "number" ? heap.updatedAt : Date.now()
12339
12810
  };
12340
12811
  }
12812
+ function normalizeGraphPathSegment(value) {
12813
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
12814
+ }
12815
+ function extractRecordIdFromGraphPath(path2, className) {
12816
+ const normalizedPrefix = `${normalizeGraphPathSegment(className)}_`;
12817
+ if (path2.startsWith(normalizedPrefix)) {
12818
+ return path2.slice(normalizedPrefix.length);
12819
+ }
12820
+ const legacyPrefix = `${className}_`;
12821
+ if (path2.startsWith(legacyPrefix)) {
12822
+ return path2.slice(legacyPrefix.length);
12823
+ }
12824
+ return path2;
12825
+ }
12826
+ function toRecordSearchResult(className, node) {
12827
+ const path2 = typeof node.path === "string" ? node.path : "";
12828
+ if (!path2) return null;
12829
+ const fields = Array.isArray(node.submodels) ? node.submodels.flatMap(
12830
+ (submodel) => {
12831
+ const name = typeof submodel?.label === "string" && submodel.label.trim() ? submodel.label : typeof submodel?.path === "string" ? submodel.path.split(":").pop() || submodel.path : "";
12832
+ if (!name) return [];
12833
+ if (typeof submodel.string_value === "string") {
12834
+ return [{ name, type: "string", value: submodel.string_value }];
12835
+ }
12836
+ if (typeof submodel.number_value === "number") {
12837
+ return [{ name, type: "number", value: submodel.number_value }];
12838
+ }
12839
+ if (typeof submodel.boolean_value === "boolean") {
12840
+ return [
12841
+ {
12842
+ name,
12843
+ type: "boolean",
12844
+ value: submodel.boolean_value
12845
+ }
12846
+ ];
12847
+ }
12848
+ return [];
12849
+ }
12850
+ ) : [];
12851
+ return {
12852
+ path: path2,
12853
+ className,
12854
+ id: extractRecordIdFromGraphPath(path2, className),
12855
+ label: typeof node.label === "string" && node.label.trim() ? node.label : extractRecordIdFromGraphPath(path2, className),
12856
+ description: typeof node.description === "string" && node.description.trim() ? node.description : null,
12857
+ fields
12858
+ };
12859
+ }
12860
+ function normalizeRecordSearchText(value) {
12861
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, " ").replace(/\s+/g, " ").trim();
12862
+ }
12863
+ function rankRecordSearchResult(result, query, index) {
12864
+ const normalizedQuery = normalizeRecordSearchText(query);
12865
+ if (!normalizedQuery) {
12866
+ return index;
12867
+ }
12868
+ const label = normalizeRecordSearchText(result.label || "");
12869
+ const id = normalizeRecordSearchText(result.id || "");
12870
+ const path2 = normalizeRecordSearchText(result.path || "");
12871
+ const className = normalizeRecordSearchText(result.className || "");
12872
+ const searchable = [label, id, path2, className].filter(Boolean);
12873
+ if (label === normalizedQuery) return index;
12874
+ if (id === normalizedQuery || path2 === normalizedQuery) return 100 + index;
12875
+ if (label.startsWith(normalizedQuery)) return 200 + index;
12876
+ if (searchable.some((value) => value.startsWith(normalizedQuery))) {
12877
+ return 300 + index;
12878
+ }
12879
+ if (label.includes(normalizedQuery)) return 400 + index;
12880
+ if (searchable.some((value) => value.includes(normalizedQuery))) {
12881
+ return 500 + index;
12882
+ }
12883
+ return 900 + index;
12884
+ }
12341
12885
  function deriveRuntimeBaseUrl(apiEndpoint) {
12342
12886
  try {
12343
12887
  const endpoint = new URL(apiEndpoint);
@@ -12426,7 +12970,7 @@ function normalizeEnvironmentData(environment) {
12426
12970
  setup: normalizeEnvironmentSetupSummary(environment.setup)
12427
12971
  };
12428
12972
  }
12429
- var Environment = class {
12973
+ var Environment = class _Environment {
12430
12974
  granular;
12431
12975
  envData;
12432
12976
  _apiKey;
@@ -12621,28 +13165,30 @@ var Environment = class {
12621
13165
  return response.json();
12622
13166
  }
12623
13167
  // ==================== ID ↔ GRAPH PATH MAPPING ====================
13168
+ static normalizeGraphPathSegment(value) {
13169
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
13170
+ }
12624
13171
  /**
12625
- * Convert a class name + real-world ID into a unique graph path.
13172
+ * Convert a class name + application record ID into Granular's graph path.
12626
13173
  *
12627
- * Two objects of *different* classes may share the same real-world ID,
12628
- * so the graph path must incorporate the class to guarantee uniqueness.
12629
- *
12630
- * Format: `{className}_{id}` — deterministic, human-readable.
12631
- *
12632
- * **Convention**: class names should be simple identifiers without
12633
- * underscores (e.g. `author`, `book`). This ensures the prefix is
12634
- * unambiguously parseable by `extractIdFromGraphPath`.
13174
+ * This mirrors the record-write path normalization used by the control plane.
13175
+ * Keep the original customer/system ID in `real_id`; graph paths are stable
13176
+ * internal addresses, not the source of truth for business identity.
12635
13177
  */
12636
13178
  static toGraphPath(className, id) {
12637
- return `${className}_${id}`;
13179
+ return `${_Environment.normalizeGraphPathSegment(className)}_${_Environment.normalizeGraphPathSegment(id)}`;
12638
13180
  }
12639
13181
  /**
12640
- * Extract the real-world ID from a graph path, given the class name.
13182
+ * Best-effort extraction of an ID-like suffix from a graph path.
12641
13183
  *
12642
- * Strips the `{className}_` prefix. Returns the raw path if the
12643
- * expected prefix is not found.
13184
+ * Prefer the record's `real_id` field whenever exact customer/system IDs
13185
+ * matter, because graph path normalization is intentionally lossy.
12644
13186
  */
12645
13187
  static extractIdFromGraphPath(graphPath, className) {
13188
+ const normalizedPrefix = `${_Environment.normalizeGraphPathSegment(className)}_`;
13189
+ if (graphPath.startsWith(normalizedPrefix)) {
13190
+ return graphPath.substring(normalizedPrefix.length);
13191
+ }
12646
13192
  const prefix = `${className}_`;
12647
13193
  return graphPath.startsWith(prefix) ? graphPath.substring(prefix.length) : graphPath;
12648
13194
  }
@@ -12689,6 +13235,62 @@ var Environment = class {
12689
13235
  }
12690
13236
  return response.json();
12691
13237
  }
13238
+ async searchRecords(query, options = {}) {
13239
+ const normalizedQuery = query.replace(/\s+/g, " ").trim();
13240
+ const limit = Math.max(1, Math.min(50, Math.floor(options.limit ?? 12)));
13241
+ const offset = Math.max(0, Math.floor(options.offset ?? 0));
13242
+ const response = await this.graphql(
13243
+ `
13244
+ query RecordMentionSearch(
13245
+ $query: String
13246
+ $limit: Int
13247
+ $offset: Int
13248
+ $classNames: [String!]
13249
+ ) {
13250
+ record_search(
13251
+ query: $query
13252
+ limit: $limit
13253
+ offset: $offset
13254
+ class_names: $classNames
13255
+ ) {
13256
+ className
13257
+ model {
13258
+ path
13259
+ label
13260
+ description
13261
+ submodels {
13262
+ path
13263
+ label
13264
+ string_value
13265
+ number_value
13266
+ boolean_value
13267
+ }
13268
+ }
13269
+ }
13270
+ }
13271
+ `,
13272
+ {
13273
+ query: normalizedQuery,
13274
+ limit,
13275
+ offset,
13276
+ classNames: options.classNames?.length ? options.classNames : []
13277
+ }
13278
+ );
13279
+ const seen = /* @__PURE__ */ new Set();
13280
+ const results = (response.data?.record_search || []).flatMap((entry) => {
13281
+ const className = entry.className?.trim();
13282
+ const item = className && entry.model ? toRecordSearchResult(className, entry.model) : null;
13283
+ if (!item || seen.has(item.path)) {
13284
+ return [];
13285
+ }
13286
+ seen.add(item.path);
13287
+ return [item];
13288
+ });
13289
+ return results.map((result, index) => ({
13290
+ result,
13291
+ rank: rankRecordSearchResult(result, normalizedQuery, index)
13292
+ })).sort((left, right) => left.rank - right.rank).map((item) => item.result).slice(0, limit);
13293
+ }
12692
13294
  // ==================== RELATIONSHIP METHODS ====================
12693
13295
  /**
12694
13296
  * Define a relationship between two model types.
@@ -13454,7 +14056,8 @@ var Environment = class {
13454
14056
  body: JSON.stringify({
13455
14057
  records,
13456
14058
  batchSize: options.batchSize,
13457
- setupRunId: options.setupRunId
14059
+ setupRunId: options.setupRunId,
14060
+ writeMode: options.writeMode
13458
14061
  })
13459
14062
  }
13460
14063
  );
@@ -13506,11 +14109,13 @@ var Environment = class {
13506
14109
  };
13507
14110
  var EnvironmentSession = class extends Session {
13508
14111
  environment;
14112
+ sessionDataRoutePrefix;
13509
14113
  /** The last known graph container status, updated by checkReadiness() or on heartbeat */
13510
14114
  graphContainerStatus = null;
13511
- constructor(client, environment, clientId) {
14115
+ constructor(client, environment, clientId, options = {}) {
13512
14116
  super(client, clientId);
13513
14117
  this.environment = environment;
14118
+ this.sessionDataRoutePrefix = options.sessionDataRoutePrefix || "/orchestrator/ws/sessions";
13514
14119
  }
13515
14120
  get environmentId() {
13516
14121
  return this.environment.environmentId;
@@ -13555,7 +14160,7 @@ var EnvironmentSession = class extends Session {
13555
14160
  const doc = this.document;
13556
14161
  return normalizeHeapSnapshot(doc?.heap);
13557
14162
  }
13558
- async sessionDataRequest(path2, query) {
14163
+ async sessionDataRequest(path2, query, init2 = {}) {
13559
14164
  const searchParams = new URLSearchParams();
13560
14165
  for (const [key, value] of Object.entries(query || {})) {
13561
14166
  if (value !== null && typeof value !== "undefined" && value !== "") {
@@ -13563,23 +14168,39 @@ var EnvironmentSession = class extends Session {
13563
14168
  }
13564
14169
  }
13565
14170
  const queryString = searchParams.toString();
13566
- const response = await fetch(
13567
- `${this.environment.runtimeBaseUrl}/orchestrator/ws/sessions/${encodeURIComponent(this.sessionId)}${path2}${queryString ? `?${queryString}` : ""}`,
13568
- {
13569
- method: "GET",
13570
- headers: {
13571
- Authorization: `Bearer ${this.environment.authToken}`,
13572
- "Content-Type": "application/json"
14171
+ const url = `${this.environment.runtimeBaseUrl}${this.sessionDataRoutePrefix}/${encodeURIComponent(this.sessionId)}${path2}${queryString ? `?${queryString}` : ""}`;
14172
+ const body = typeof init2.body === "undefined" ? void 0 : JSON.stringify(init2.body);
14173
+ for (let attempt = 1; attempt <= SESSION_DATA_REQUEST_RETRY_COUNT; attempt += 1) {
14174
+ try {
14175
+ const response = await fetch(url, {
14176
+ method: init2.method || "GET",
14177
+ headers: {
14178
+ Authorization: `Bearer ${this.environment.authToken}`,
14179
+ "Content-Type": "application/json"
14180
+ },
14181
+ ...typeof body === "undefined" ? {} : { body }
14182
+ });
14183
+ if (response.ok) {
14184
+ return response.json();
14185
+ }
14186
+ const errorText = await response.text();
14187
+ const error = new Error(
14188
+ `Session data API Error (${response.status}): ${errorText}`
14189
+ );
14190
+ if (isLocalControlUrl(url) && isRetryableSessionDataError(error) && attempt < SESSION_DATA_REQUEST_RETRY_COUNT) {
14191
+ await sleep(SESSION_DATA_REQUEST_RETRY_DELAY_MS * attempt);
14192
+ continue;
14193
+ }
14194
+ throw error;
14195
+ } catch (error) {
14196
+ if (isLocalControlUrl(url) && isRetryableSessionDataError(error) && attempt < SESSION_DATA_REQUEST_RETRY_COUNT) {
14197
+ await sleep(SESSION_DATA_REQUEST_RETRY_DELAY_MS * attempt);
14198
+ continue;
13573
14199
  }
14200
+ throw error;
13574
14201
  }
13575
- );
13576
- if (!response.ok) {
13577
- const errorText = await response.text();
13578
- throw new Error(
13579
- `Session data API Error (${response.status}): ${errorText}`
13580
- );
13581
14202
  }
13582
- return response.json();
14203
+ throw new Error(`Session data API Error: exhausted retries for ${url}`);
13583
14204
  }
13584
14205
  async collectAllSessionItems(listPage) {
13585
14206
  const items = [];
@@ -13637,6 +14258,17 @@ var EnvironmentSession = class extends Session {
13637
14258
  get: (name) => this.sessionDataRequest(
13638
14259
  `/heap/lists/${encodeURIComponent(name)}`
13639
14260
  )
14261
+ },
14262
+ variables: {
14263
+ list: (options = {}) => this.sessionDataRequest("/heap/variables", options),
14264
+ get: (name) => this.sessionDataRequest(
14265
+ `/heap/variables/${encodeURIComponent(name)}`
14266
+ ),
14267
+ delete: (name) => this.sessionDataRequest(
14268
+ `/heap/variables/${encodeURIComponent(name)}`,
14269
+ void 0,
14270
+ { method: "DELETE" }
14271
+ )
13640
14272
  }
13641
14273
  };
13642
14274
  }
@@ -13705,6 +14337,19 @@ var EnvironmentSession = class extends Session {
13705
14337
  async graphql(query, variables) {
13706
14338
  return this.environment.graphql(query, variables);
13707
14339
  }
14340
+ async searchRecords(query, options = {}) {
14341
+ return this.environment.searchRecords(query, options);
14342
+ }
14343
+ async mentionRecord(input) {
14344
+ return this.sessionDataRequest(
14345
+ "/records/mention",
14346
+ void 0,
14347
+ {
14348
+ method: "POST",
14349
+ body: input
14350
+ }
14351
+ );
14352
+ }
13708
14353
  async defineRelationship(options) {
13709
14354
  return this.environment.defineRelationship(options);
13710
14355
  }
@@ -13852,6 +14497,7 @@ var Granular = class _Granular {
13852
14497
  WebSocketCtor;
13853
14498
  onUnexpectedClose;
13854
14499
  onReconnectError;
14500
+ effectHostUrl;
13855
14501
  debugHttp = process.env.GRANULAR_DEBUG_HTTP === "1";
13856
14502
  /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
13857
14503
  sandboxEffects = /* @__PURE__ */ new Map();
@@ -13880,6 +14526,7 @@ var Granular = class _Granular {
13880
14526
  this.WebSocketCtor = options.WebSocketCtor;
13881
14527
  this.onUnexpectedClose = options.onUnexpectedClose;
13882
14528
  this.onReconnectError = options.onReconnectError;
14529
+ this.effectHostUrl = options.effectHostUrl;
13883
14530
  this.httpUrl = this.apiUrl.replace(/^wss:\/\//, "https://").replace(/^ws:\/\//, "http://").replace(/\/ws$/, "");
13884
14531
  }
13885
14532
  /**
@@ -14050,6 +14697,30 @@ var Granular = class _Granular {
14050
14697
  permissions: options.permissions || options.user?.permissions || []
14051
14698
  });
14052
14699
  }
14700
+ /**
14701
+ * Run a registered environment importer against an environment that was
14702
+ * opened outside this SDK instance, for example by a delegated browser flow.
14703
+ *
14704
+ * This uses the same setup-run and queued record-import plumbing as
14705
+ * `openEnvironment()`: importer stages, expected object counts, and queued
14706
+ * import counters remain visible through `environment.setup` and
14707
+ * `getRecordImportSummary()`.
14708
+ */
14709
+ async runEnvironmentImporterForEnvironment(environmentId, options = {}) {
14710
+ const environmentData = await this.environments.get(environmentId);
14711
+ const environment = this.bindEnvironmentHandle(environmentData);
14712
+ const requestedOntology = options.ontology || environmentData.ontologyId || environmentData.sandboxId;
14713
+ return this.runEnvironmentImporter(
14714
+ {
14715
+ environment: environmentData,
14716
+ requestedOntology,
14717
+ sandboxId: environmentData.sandboxId,
14718
+ subjectId: environmentData.subjectId,
14719
+ setupTriggerReason: options.reason || "new_environment"
14720
+ },
14721
+ environment
14722
+ );
14723
+ }
14053
14724
  resolveRequestedTag(options, methodName) {
14054
14725
  const tag = options.tag?.trim() || options.tagName?.trim() || options.environment?.trim();
14055
14726
  if (!tag) {
@@ -14293,15 +14964,25 @@ var Granular = class _Granular {
14293
14964
  return ontologyImporter;
14294
14965
  }
14295
14966
  async maybeRunEnvironmentImporter(resolved, environment) {
14296
- if (!resolved.setupTriggerReason) {
14297
- return;
14967
+ const setupTriggerReason = resolved.setupTriggerReason;
14968
+ if (!setupTriggerReason) {
14969
+ return null;
14298
14970
  }
14971
+ return this.runEnvironmentImporter(
14972
+ {
14973
+ ...resolved,
14974
+ setupTriggerReason
14975
+ },
14976
+ environment
14977
+ );
14978
+ }
14979
+ async runEnvironmentImporter(resolved, environment) {
14299
14980
  const importer = this.resolveEnvironmentImporter(
14300
14981
  resolved.requestedOntology,
14301
14982
  resolved.sandboxId
14302
14983
  );
14303
14984
  if (!importer) {
14304
- return;
14985
+ return null;
14305
14986
  }
14306
14987
  const setupRun = await this.request(
14307
14988
  `/control/environments/${environment.environmentId}/setup-runs`,
@@ -14341,16 +15022,24 @@ var Granular = class _Granular {
14341
15022
  },
14342
15023
  importRecords: async (records, options) => environment.enqueueRecordImport(records, {
14343
15024
  batchSize: options?.batchSize,
15025
+ writeMode: options?.writeMode,
14344
15026
  setupRunId
14345
15027
  })
14346
15028
  };
14347
15029
  try {
14348
15030
  await importer(importerContext);
14349
- await updateSetupRun({ markHookCompleted: true });
15031
+ const completedSetupRun = await this.request(
15032
+ `/control/environment-setup-runs/${setupRunId}`,
15033
+ {
15034
+ method: "PATCH",
15035
+ body: JSON.stringify({ markHookCompleted: true })
15036
+ }
15037
+ );
14350
15038
  const refreshedEnvironment = await this.environments.get(
14351
15039
  environment.environmentId
14352
15040
  );
14353
15041
  environment.syncEnvironmentData(refreshedEnvironment);
15042
+ return completedSetupRun;
14354
15043
  } catch (error) {
14355
15044
  await updateSetupRun({
14356
15045
  status: "failed",
@@ -14398,27 +15087,45 @@ var Granular = class _Granular {
14398
15087
  return effects;
14399
15088
  }
14400
15089
  serializeEffect(effect) {
14401
- return {
15090
+ const serialized = {
14402
15091
  effectKey: computeEffectKey2(effect),
14403
15092
  name: effect.name,
14404
15093
  description: effect.description,
14405
15094
  inputSchema: effect.inputSchema,
14406
- outputSchema: effect.outputSchema,
14407
15095
  stability: effect.stability || "stable",
14408
- provenance: effect.provenance || { source: "custom" },
14409
- tags: effect.tags,
14410
- className: effect.className,
14411
- static: effect.static,
14412
- versionSelector: effect.versionSelector
15096
+ provenance: effect.provenance || { source: "custom" }
14413
15097
  };
15098
+ if (effect.outputSchema !== void 0) {
15099
+ serialized.outputSchema = effect.outputSchema;
15100
+ }
15101
+ if (effect.tags !== void 0) {
15102
+ serialized.tags = effect.tags;
15103
+ }
15104
+ if (effect.className !== void 0) {
15105
+ serialized.className = effect.className;
15106
+ }
15107
+ if (effect.static !== void 0) {
15108
+ serialized.static = effect.static;
15109
+ }
15110
+ if (effect.versionSelector !== void 0) {
15111
+ serialized.versionSelector = effect.versionSelector;
15112
+ }
15113
+ if (effect.metamodels !== void 0) {
15114
+ serialized.metamodels = effect.metamodels;
15115
+ }
15116
+ return serialized;
14414
15117
  }
14415
15118
  async publishSandboxEffectCatalog(host) {
14416
15119
  const effects = Array.from(
14417
15120
  this.getSandboxEffectMap(host.sandboxId).values()
14418
15121
  ).map((effect) => this.serializeEffect(effect));
14419
- const result = await host.wsClient.call("effects.publishCatalog", {
14420
- effects
14421
- });
15122
+ const result = await withTimeout(
15123
+ host.wsClient.call("effects.publishCatalog", {
15124
+ effects
15125
+ }),
15126
+ EFFECT_CATALOG_SYNC_TIMEOUT_MS,
15127
+ `effects.publishCatalog for sandbox ${host.sandboxId}`
15128
+ );
14422
15129
  const acceptedCount = typeof result?.acceptedCount === "number" ? result.acceptedCount : 0;
14423
15130
  const rejected = Array.isArray(result?.rejected) ? result.rejected : [];
14424
15131
  if (acceptedCount === 0 && rejected.length > 0) {
@@ -14437,8 +15144,26 @@ var Granular = class _Granular {
14437
15144
  }
14438
15145
  }
14439
15146
  async syncSandboxEffectCatalog(sandboxId) {
14440
- const host = await this.ensureSandboxEffectHost(sandboxId);
14441
- await this.publishSandboxEffectCatalog(host);
15147
+ let lastError;
15148
+ for (let attempt = 1; attempt <= EFFECT_CATALOG_SYNC_RETRY_COUNT; attempt += 1) {
15149
+ try {
15150
+ const host = await this.ensureSandboxEffectHost(sandboxId);
15151
+ await this.publishSandboxEffectCatalog(host);
15152
+ return;
15153
+ } catch (error) {
15154
+ lastError = error;
15155
+ this.disconnectSandboxEffectHost(sandboxId);
15156
+ if (attempt === EFFECT_CATALOG_SYNC_RETRY_COUNT || !isRetryableEffectRegistrationError(error)) {
15157
+ throw error;
15158
+ }
15159
+ console.warn(
15160
+ `[Granular] Retrying effect registration for sandbox ${sandboxId} after transient failure (${attempt}/${EFFECT_CATALOG_SYNC_RETRY_COUNT - 1} retries used):`,
15161
+ error
15162
+ );
15163
+ await sleep(EFFECT_CATALOG_SYNC_RETRY_DELAY_MS * attempt);
15164
+ }
15165
+ }
15166
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
14442
15167
  }
14443
15168
  recoverEffectHost(host, error) {
14444
15169
  if (host.recovering) {
@@ -14531,7 +15256,8 @@ var Granular = class _Granular {
14531
15256
  this.apiUrl,
14532
15257
  sandboxId,
14533
15258
  effectClientId,
14534
- clientId
15259
+ clientId,
15260
+ this.effectHostUrl
14535
15261
  ),
14536
15262
  sessionId: `effect-host:${effectClientId}`,
14537
15263
  token: this.apiKey,
@@ -14567,7 +15293,11 @@ var Granular = class _Granular {
14567
15293
  wsClient.on("disconnect", () => {
14568
15294
  this.stopEffectHostHeartbeat(host);
14569
15295
  });
14570
- await wsClient.connect();
15296
+ await withTimeout(
15297
+ wsClient.connect(),
15298
+ EFFECT_HOST_CONNECT_TIMEOUT_MS,
15299
+ `effect host WebSocket connect for sandbox ${sandboxId}`
15300
+ );
14571
15301
  await this.synchronizeEffectHost(host);
14572
15302
  this.sandboxEffectHosts.set(sandboxId, host);
14573
15303
  return host;
@@ -14690,7 +15420,7 @@ var Granular = class _Granular {
14690
15420
  /**
14691
15421
  * Ensure a permission profile exists for a sandbox, creating it if needed.
14692
15422
  * If profileName matches an existing profile name, returns its ID.
14693
- * Otherwise, creates a new profile with default allow-all rules.
15423
+ * Otherwise, creates a v1 source-profile file shape with an allow default.
14694
15424
  */
14695
15425
  async ensurePermissionProfile(sandboxId, profileName) {
14696
15426
  try {
@@ -14704,8 +15434,11 @@ var Granular = class _Granular {
14704
15434
  const created = await this.permissionProfiles.create(sandboxId, {
14705
15435
  name: profileName,
14706
15436
  rules: {
14707
- effects: { allow: ["*"] },
14708
- resources: { allow: ["*"] }
15437
+ schemaVersion: 1,
15438
+ name: profileName,
15439
+ description: profileName === "allow-all" ? "Every declared action is visible unless a manifest policy denies it." : `Generated permission profile ${profileName}`,
15440
+ defaults: { actionPolicy: "allow" },
15441
+ actions: []
14709
15442
  }
14710
15443
  });
14711
15444
  return created.permissionProfileId;
@@ -14778,33 +15511,63 @@ var Granular = class _Granular {
14778
15511
  * Permission Profile management for sandboxes
14779
15512
  */
14780
15513
  get permissionProfiles() {
15514
+ const profileSourceFromRecord = (record) => {
15515
+ const profile = record.profile || record.rules || {};
15516
+ return {
15517
+ ...profile,
15518
+ schemaVersion: profile.schemaVersion || 1,
15519
+ name: profile.name || record.name,
15520
+ description: profile.description || record.description
15521
+ };
15522
+ };
14781
15523
  return {
14782
15524
  list: async (sandboxId) => {
14783
15525
  const result = await this.request(
14784
- `/control/sandboxes/${sandboxId}/permission-profiles`
15526
+ `/control/sandboxes/${sandboxId}/permission-profile-sources`
14785
15527
  );
14786
15528
  return result.items;
14787
15529
  },
14788
15530
  get: async (sandboxId, profileId) => {
14789
- return this.request(
14790
- `/control/sandboxes/${sandboxId}/permission-profiles/${profileId}`
15531
+ const result = await this.request(
15532
+ `/control/sandboxes/${sandboxId}/permission-profile-sources`
14791
15533
  );
15534
+ const profile = result.items.find(
15535
+ (item) => item.permissionProfileId === profileId || item.name === profileId
15536
+ );
15537
+ if (!profile) {
15538
+ throw new Error(`Permission profile source not found: ${profileId}`);
15539
+ }
15540
+ return profile;
14792
15541
  },
14793
15542
  create: async (sandboxId, data) => {
14794
- return this.request(
14795
- `/control/sandboxes/${sandboxId}/permission-profiles`,
15543
+ const profile = {
15544
+ ...data.rules,
15545
+ schemaVersion: 1,
15546
+ name: data.name
15547
+ };
15548
+ const existingProfiles = await this.permissionProfiles.list(sandboxId);
15549
+ const profiles = [
15550
+ ...existingProfiles.filter((existing) => existing.name !== data.name).map((existing) => profileSourceFromRecord(existing)),
15551
+ profile
15552
+ ];
15553
+ const result = await this.request(
15554
+ `/control/sandboxes/${sandboxId}/permission-profile-sources`,
14796
15555
  {
14797
- method: "POST",
14798
- body: JSON.stringify(data)
15556
+ method: "PUT",
15557
+ body: JSON.stringify({ profiles })
14799
15558
  }
14800
15559
  );
15560
+ const synced = result.items.find((item) => item.name === data.name) || result.items[0];
15561
+ if (!synced) {
15562
+ throw new Error(
15563
+ `Permission profile source sync did not return ${data.name}`
15564
+ );
15565
+ }
15566
+ return synced;
14801
15567
  },
14802
- delete: async (sandboxId, profileId) => {
14803
- return this.request(
14804
- `/control/sandboxes/${sandboxId}/permission-profiles/${profileId}`,
14805
- {
14806
- method: "DELETE"
14807
- }
15568
+ delete: async (_sandboxId, _profileId) => {
15569
+ throw new Error(
15570
+ "Permission profile sources are updated by syncing the desired source set."
14808
15571
  );
14809
15572
  }
14810
15573
  };
@@ -15083,21 +15846,8 @@ function uniqueStrings(values, maxCount) {
15083
15846
  }
15084
15847
  return output;
15085
15848
  }
15086
- function formatScalar(value) {
15087
- if (typeof value === "string") return JSON.stringify(value);
15088
- if (typeof value === "number" || typeof value === "boolean")
15089
- return String(value);
15090
- if (value === null) return "null";
15091
- return "unknown";
15092
- }
15093
- function describeHeapEntry(entry, previewFieldLimit = 3) {
15094
- const headline = entry.label || entry.id || entry.path || "Unknown";
15095
- const pathLabel = entry.path && entry.path !== headline ? ` <${entry.path}>` : "";
15096
- const classLabel = entry.className || "unknown";
15097
- const preview = asArray2(entry.fields).filter(
15098
- (field) => field?.name && field.name !== "_realId" && field.name !== "real_id"
15099
- ).slice(0, previewFieldLimit).map((field) => `${field.name}=${formatScalar(field.value)}`).join(", ");
15100
- return preview ? `${headline}${pathLabel} [${classLabel}] ${preview}` : `${headline}${pathLabel} [${classLabel}]`;
15849
+ function renderConstBlock(name, value) {
15850
+ return `const ${name} = ${JSON.stringify(value, null, 2)} as const;`;
15101
15851
  }
15102
15852
  function hashString(value) {
15103
15853
  if (!value) return null;
@@ -15108,101 +15858,6 @@ function hashString(value) {
15108
15858
  }
15109
15859
  return (hash >>> 0).toString(16).padStart(8, "0");
15110
15860
  }
15111
- function hasSubstantiveAwaitAfterPrompt(code, marker) {
15112
- const startIndex = code.indexOf(marker);
15113
- if (startIndex === -1) return true;
15114
- const segment = code.slice(startIndex + marker.length);
15115
- const callMatches = segment.matchAll(
15116
- /await\s+([A-Za-z0-9_$.]+)\.([A-Za-z0-9_]+)\s*\(/g
15117
- );
15118
- for (const match of callMatches) {
15119
- const receiver = match[1] || "";
15120
- const method = match[2] || "";
15121
- if (receiver === "loop" || receiver === "heap") continue;
15122
- if (method.startsWith("get_") || method.startsWith("get")) continue;
15123
- return true;
15124
- }
15125
- return false;
15126
- }
15127
- function reviewGeneratedJobCode(code) {
15128
- const normalized = typeof code === "string" ? code : "";
15129
- if (!normalized.trim()) return [];
15130
- const issues = [];
15131
- if (/require\s*\(\s*['"]\.\/sandbox-tools['"]\s*\)/.test(normalized)) {
15132
- issues.push({
15133
- code: "commonjs_require",
15134
- severity: "error",
15135
- message: "Use ESM imports like `import { Customer, loop } from './sandbox-tools';` instead of require('./sandbox-tools'). Generated jobs must be plain runnable JavaScript for the sandbox runtime."
15136
- });
15137
- }
15138
- const placeholderPatterns = [
15139
- /ready to make the change next/i,
15140
- /ready to .* next/i,
15141
- /ready to .* now/i,
15142
- /i can make the change now/i,
15143
- /i can do that next/i,
15144
- /i'?m ready to continue/i,
15145
- /have your approval .* ready to make/i,
15146
- /approved\./i
15147
- ];
15148
- if (normalized.includes("await loop.confirm(")) {
15149
- const postConfirm = normalized.slice(
15150
- normalized.indexOf("await loop.confirm(")
15151
- );
15152
- const hasPlaceholder = placeholderPatterns.some(
15153
- (pattern) => pattern.test(postConfirm)
15154
- );
15155
- const hasSubstantiveAwait = hasSubstantiveAwaitAfterPrompt(
15156
- normalized,
15157
- "await loop.confirm("
15158
- );
15159
- if (!hasSubstantiveAwait || hasPlaceholder) {
15160
- issues.push({
15161
- code: "placeholder_after_confirm",
15162
- severity: "error",
15163
- message: "After await loop.confirm(...) returns true, the job must perform the approved mutation in the same resumed run. Do not stop with placeholder text like 'Approved, I can make the change now.'"
15164
- });
15165
- }
15166
- }
15167
- if (normalized.includes("await loop.ask_user(")) {
15168
- const postPrompt = normalized.slice(
15169
- normalized.indexOf("await loop.ask_user(")
15170
- );
15171
- const hasPlaceholder = placeholderPatterns.some(
15172
- (pattern) => pattern.test(postPrompt)
15173
- );
15174
- const hasSubstantiveAwait = hasSubstantiveAwaitAfterPrompt(
15175
- normalized,
15176
- "await loop.ask_user("
15177
- );
15178
- if (hasPlaceholder && !hasSubstantiveAwait) {
15179
- issues.push({
15180
- code: "placeholder_after_ask_user",
15181
- severity: "error",
15182
- message: "After await loop.ask_user(...) returns a usable answer, continue the workflow in the same resumed run instead of stopping with placeholder text about doing the work later."
15183
- });
15184
- }
15185
- }
15186
- const hasConversationalReturn = /return\s+[`'"]/.test(normalized) || /\breply\s*:/.test(normalized) || /\bagent_message\s*\(/.test(normalized) || /\bagent_text_message\s*\(/.test(normalized);
15187
- const returnsObjectLiteral = /return\s+\{[\s\S]*?\}/.test(normalized);
15188
- const returnsShowPayload = /return\s+\{[\s\S]*?\bshow\s*:/.test(normalized);
15189
- const closesLoop = /loop\.close_loop\s*\(/.test(normalized);
15190
- if (!hasConversationalReturn && returnsObjectLiteral && !closesLoop) {
15191
- issues.push({
15192
- code: "missing_user_reply",
15193
- severity: "error",
15194
- message: "User-facing jobs must end with a natural-language answer. Return a short string, an object with a top-level `reply` string, or post text with agent_text_message(...). Do not end with bare structured JSON."
15195
- });
15196
- }
15197
- if (returnsShowPayload) {
15198
- issues.push({
15199
- code: "return_show_not_for_ui",
15200
- severity: "error",
15201
- message: "Do not use the final return value to send UI record refs through `show`. Use agent_heap_objects(...) for heap-backed UI, then return plain text if you still want a final textual answer."
15202
- });
15203
- }
15204
- return issues;
15205
- }
15206
15861
  function extractFocusHintsFromActionSummary(actionSummaryLines) {
15207
15862
  const variableNames = [];
15208
15863
  const listNames = [];
@@ -15230,6 +15885,247 @@ function extractFocusHintsFromActionSummary(actionSummaryLines) {
15230
15885
  function normalizeActionSummaryForPrompt(line) {
15231
15886
  return line.replace(/\blimit=/g, "perPage=").replace(/\blimit:/g, "perPage:");
15232
15887
  }
15888
+ function collectConversationReferents(liveDoc) {
15889
+ const conversation = asRecord4(liveDoc?.conversation);
15890
+ const persistedReferents = asArray2(conversation?.referents).map((value) => asRecord4(value)).filter((value) => Boolean(value));
15891
+ if (persistedReferents.length > 0) {
15892
+ return persistedReferents.slice().sort((left, right) => (right.ts || 0) - (left.ts || 0));
15893
+ }
15894
+ const heap = asRecord4(liveDoc?.heap);
15895
+ const entriesByPath = asRecord4(heap?.entriesByPath) || {};
15896
+ const listsByName = asRecord4(heap?.listsByName) || {};
15897
+ const variablesByName = asRecord4(heap?.variablesByName) || {};
15898
+ const messages = asArray2(conversation?.messages).map((value) => asRecord4(value)).filter((value) => Boolean(value)).slice().sort((left, right) => (Number(right.ts) || 0) - (Number(left.ts) || 0));
15899
+ const referents = [];
15900
+ const seen = /* @__PURE__ */ new Set();
15901
+ const pushReferent = (referent) => {
15902
+ if (!referent?.kind || !referent.ref) return;
15903
+ const key = `${referent.kind}:${referent.ref}`;
15904
+ if (seen.has(key)) return;
15905
+ seen.add(key);
15906
+ referents.push(referent);
15907
+ };
15908
+ for (const message of messages) {
15909
+ if (message.role !== "assistant") continue;
15910
+ const show = asRecord4(message.show);
15911
+ if (!show) continue;
15912
+ const ts = Number(message.ts) || 0;
15913
+ const messageId = typeof message.id === "string" ? message.id : void 0;
15914
+ const jobId = typeof message.jobId === "string" ? message.jobId : void 0;
15915
+ const entryPaths = uniqueStrings(asArray2(show.entryPaths));
15916
+ const entryClassCounts = /* @__PURE__ */ new Map();
15917
+ const entryMetadata = entryPaths.map((entryPath) => {
15918
+ const entry = asRecord4(entriesByPath[entryPath]);
15919
+ const className = typeof entry?.className === "string" ? entry.className : void 0;
15920
+ if (className) {
15921
+ entryClassCounts.set(
15922
+ className,
15923
+ (entryClassCounts.get(className) || 0) + 1
15924
+ );
15925
+ }
15926
+ return { entryPath, entry, className };
15927
+ });
15928
+ const displayGroupId = entryMetadata.length > 1 ? `message:${messageId || jobId || ts}:entries` : void 0;
15929
+ for (const [
15930
+ index,
15931
+ { entryPath, entry, className }
15932
+ ] of entryMetadata.entries()) {
15933
+ pushReferent({
15934
+ id: `entry:${entryPath}`,
15935
+ kind: "entry",
15936
+ ref: entryPath,
15937
+ role: "assistant",
15938
+ source: "heap_objects",
15939
+ entryPath,
15940
+ recordId: typeof entry?.id === "string" ? entry.id : void 0,
15941
+ className,
15942
+ label: typeof entry?.label === "string" && entry.label.trim() ? entry.label.trim() : typeof entry?.id === "string" && entry.id.trim() ? entry.id.trim() : entryPath,
15943
+ ...displayGroupId ? {
15944
+ displayGroupId,
15945
+ displayGroupIndex: index,
15946
+ displayGroupSize: entryMetadata.length,
15947
+ ...className && (entryClassCounts.get(className) || 0) > 1 ? { displayGroupSameTypeSize: entryClassCounts.get(className) } : {}
15948
+ } : {},
15949
+ messageId,
15950
+ jobId,
15951
+ ts
15952
+ });
15953
+ }
15954
+ for (const listName of uniqueStrings(asArray2(show.listNames))) {
15955
+ const list = asRecord4(listsByName[listName]);
15956
+ pushReferent({
15957
+ id: `list:${listName}`,
15958
+ kind: "list",
15959
+ ref: listName,
15960
+ role: "assistant",
15961
+ source: "heap_objects",
15962
+ listName,
15963
+ className: typeof list?.className === "string" ? list.className : void 0,
15964
+ count: Array.isArray(list?.paths) ? list.paths.length : null,
15965
+ messageId,
15966
+ jobId,
15967
+ ts
15968
+ });
15969
+ }
15970
+ for (const variableName of uniqueStrings(
15971
+ asArray2(show.variableNames)
15972
+ )) {
15973
+ const variable = asRecord4(variablesByName[variableName]);
15974
+ const entryPath = typeof variable?.entryPath === "string" ? variable.entryPath : void 0;
15975
+ const listName = typeof variable?.listName === "string" ? variable.listName : void 0;
15976
+ const entry = entryPath ? asRecord4(entriesByPath[entryPath]) : null;
15977
+ const list = listName ? asRecord4(listsByName[listName]) : null;
15978
+ pushReferent({
15979
+ id: `variable:${variableName}`,
15980
+ kind: "variable",
15981
+ ref: variableName,
15982
+ role: "assistant",
15983
+ source: "heap_objects",
15984
+ variableName,
15985
+ variableKind: typeof variable?.kind === "string" ? variable.kind : void 0,
15986
+ entryPath,
15987
+ recordId: typeof entry?.id === "string" ? entry.id : void 0,
15988
+ listName,
15989
+ className: typeof variable?.className === "string" ? variable.className : typeof entry?.className === "string" ? entry.className : typeof list?.className === "string" ? list.className : void 0,
15990
+ label: typeof entry?.label === "string" && entry.label.trim() ? entry.label.trim() : typeof entry?.id === "string" && entry.id.trim() ? entry.id.trim() : null,
15991
+ count: variable?.kind === "list" && Array.isArray(list?.paths) ? list.paths.length : null,
15992
+ scalarValue: variable?.kind === "scalar" && (typeof variable.value === "string" || typeof variable.value === "number" || typeof variable.value === "boolean" || variable.value === null) ? variable.value : void 0,
15993
+ messageId,
15994
+ jobId,
15995
+ ts
15996
+ });
15997
+ }
15998
+ }
15999
+ return referents;
16000
+ }
16001
+ function projectConversationReferentFocus(liveDoc) {
16002
+ const heap = asRecord4(liveDoc?.heap);
16003
+ const listsByName = asRecord4(heap?.listsByName) || {};
16004
+ const referents = collectConversationReferents(liveDoc);
16005
+ const entryPaths = [];
16006
+ const listNames = [];
16007
+ const variableNames = [];
16008
+ let entryCount = 0;
16009
+ let listCount = 0;
16010
+ let variableCount = 0;
16011
+ for (const referent of referents) {
16012
+ if (referent.kind === "entry" && typeof referent.entryPath === "string" && entryCount < 8) {
16013
+ entryCount += 1;
16014
+ entryPaths.push(referent.entryPath);
16015
+ continue;
16016
+ }
16017
+ if (referent.kind === "list" && typeof referent.listName === "string" && listCount < 4) {
16018
+ listCount += 1;
16019
+ listNames.push(referent.listName);
16020
+ const list = asRecord4(listsByName[referent.listName]);
16021
+ entryPaths.push(...asArray2(list?.paths).slice(0, 4));
16022
+ continue;
16023
+ }
16024
+ if (referent.kind === "variable" && typeof referent.variableName === "string" && variableCount < 4) {
16025
+ variableCount += 1;
16026
+ variableNames.push(referent.variableName);
16027
+ if (typeof referent.entryPath === "string") {
16028
+ entryPaths.push(referent.entryPath);
16029
+ }
16030
+ if (typeof referent.listName === "string") {
16031
+ listNames.push(referent.listName);
16032
+ const list = asRecord4(listsByName[referent.listName]);
16033
+ entryPaths.push(...asArray2(list?.paths).slice(0, 4));
16034
+ }
16035
+ }
16036
+ }
16037
+ return {
16038
+ entryPaths: uniqueStrings(entryPaths, 8),
16039
+ listNames: uniqueStrings(listNames, 4),
16040
+ variableNames: uniqueStrings(variableNames, 4)
16041
+ };
16042
+ }
16043
+ function selectConversationReferentsForPrompt(referents) {
16044
+ const selected = [];
16045
+ const seen = /* @__PURE__ */ new Set();
16046
+ let entryCount = 0;
16047
+ let listCount = 0;
16048
+ let variableCount = 0;
16049
+ for (const referent of referents) {
16050
+ if (!referent.kind || !referent.ref) continue;
16051
+ const key = `${referent.kind}:${referent.ref}`;
16052
+ if (seen.has(key)) continue;
16053
+ if (referent.kind === "entry") {
16054
+ if (entryCount >= 8) continue;
16055
+ entryCount += 1;
16056
+ } else if (referent.kind === "list") {
16057
+ if (listCount >= 4) continue;
16058
+ listCount += 1;
16059
+ } else if (referent.kind === "variable") {
16060
+ if (variableCount >= 4) continue;
16061
+ variableCount += 1;
16062
+ }
16063
+ seen.add(key);
16064
+ selected.push(referent);
16065
+ }
16066
+ return selected;
16067
+ }
16068
+ function projectConversationReferentSummary(liveDoc) {
16069
+ const referents = selectConversationReferentsForPrompt(
16070
+ collectConversationReferents(liveDoc)
16071
+ );
16072
+ const compact = referents.map((referent) => {
16073
+ if (referent.kind === "entry" && referent.entryPath) {
16074
+ return {
16075
+ kind: "entry",
16076
+ role: referent.role || null,
16077
+ source: referent.source || null,
16078
+ path: referent.entryPath,
16079
+ id: referent.recordId || null,
16080
+ type: referent.className || "unknown",
16081
+ label: referent.label || referent.entryPath,
16082
+ group: referent.displayGroupId ? {
16083
+ id: referent.displayGroupId,
16084
+ index: typeof referent.displayGroupIndex === "number" ? referent.displayGroupIndex : null,
16085
+ size: typeof referent.displayGroupSize === "number" ? referent.displayGroupSize : null,
16086
+ sameTypeSize: typeof referent.displayGroupSameTypeSize === "number" ? referent.displayGroupSameTypeSize : null
16087
+ } : void 0
16088
+ };
16089
+ }
16090
+ if (referent.kind === "entry" && referent.recordId) {
16091
+ return {
16092
+ kind: "entry",
16093
+ role: referent.role || null,
16094
+ source: referent.source || null,
16095
+ id: referent.recordId,
16096
+ type: referent.className || "unknown",
16097
+ label: referent.label || referent.recordId
16098
+ };
16099
+ }
16100
+ if (referent.kind === "list" && referent.listName) {
16101
+ return {
16102
+ kind: "list",
16103
+ role: referent.role || null,
16104
+ source: referent.source || null,
16105
+ name: referent.listName,
16106
+ type: referent.className || "unknown",
16107
+ count: typeof referent.count === "number" ? referent.count : null
16108
+ };
16109
+ }
16110
+ if (referent.kind === "variable" && referent.variableName) {
16111
+ return {
16112
+ kind: "variable",
16113
+ role: referent.role || null,
16114
+ source: referent.source || null,
16115
+ name: referent.variableName,
16116
+ valueKind: referent.variableKind || null,
16117
+ type: referent.className || null,
16118
+ path: referent.entryPath || null,
16119
+ list: referent.listName || null,
16120
+ label: referent.label || null,
16121
+ count: typeof referent.count === "number" ? referent.count : null,
16122
+ value: referent.variableKind === "scalar" ? referent.scalarValue ?? null : void 0
16123
+ };
16124
+ }
16125
+ return null;
16126
+ }).filter(Boolean);
16127
+ return renderConstBlock("recentReferences", compact);
16128
+ }
15233
16129
  function getCurrentClosureId(liveDoc) {
15234
16130
  const loop = asRecord4(liveDoc?.loop);
15235
16131
  return typeof loop?.currentClosureId === "string" ? loop.currentClosureId : null;
@@ -15449,56 +16345,24 @@ function projectWorkflowFocus(liveDoc, pendingPrompts = [], options) {
15449
16345
  }
15450
16346
  function projectWorkflowSummary(liveDoc, pendingPrompts = [], options) {
15451
16347
  const focus = projectWorkflowFocus(liveDoc, pendingPrompts, options);
15452
- const lines = [];
15453
- lines.push("Workflow Boundary:");
15454
- if (focus.boundaryReason === "request_start") {
15455
- lines.push(
15456
- "- Start from work recorded after the current user request began."
15457
- );
15458
- } else if (focus.boundaryReason === "last_closed_loop" && focus.latestClosureId) {
15459
- lines.push(`- Start from work recorded after ${focus.latestClosureId}.`);
15460
- } else {
15461
- lines.push(
15462
- "- No prior closed loop recorded; use the latest user request as the boundary."
15463
- );
15464
- }
15465
- lines.push("", "Recent Actions:");
15466
- if (focus.recentActionSummary.length === 0) {
15467
- lines.push("- none");
15468
- } else {
15469
- for (const line of focus.recentActionSummary) {
15470
- lines.push(line.startsWith("- ") ? line : `- ${line}`);
15471
- }
15472
- }
15473
- lines.push("", "Working Set Hints:");
15474
- if (focus.variableNames.length === 0 && focus.listNames.length === 0 && focus.entryPaths.length === 0) {
15475
- lines.push("- none");
15476
- } else {
15477
- if (focus.variableNames.length > 0) {
15478
- lines.push(`- variables: ${focus.variableNames.join(", ")}`);
15479
- }
15480
- if (focus.listNames.length > 0) {
15481
- lines.push(`- lists: ${focus.listNames.join(", ")}`);
15482
- }
15483
- if (focus.entryPaths.length > 0) {
15484
- lines.push(`- entries: ${focus.entryPaths.join(", ")}`);
15485
- }
15486
- }
15487
- lines.push("", "Open Workflow Handles:");
15488
- if (focus.activeTaskIds.length === 0 && focus.openDecisionIds.length === 0 && focus.openPromptIds.length === 0) {
15489
- lines.push("- none");
15490
- } else {
15491
- if (focus.activeTaskIds.length > 0) {
15492
- lines.push(`- tasks: ${focus.activeTaskIds.join(", ")}`);
15493
- }
15494
- if (focus.openDecisionIds.length > 0) {
15495
- lines.push(`- decisions: ${focus.openDecisionIds.join(", ")}`);
15496
- }
15497
- if (focus.openPromptIds.length > 0) {
15498
- lines.push(`- prompts: ${focus.openPromptIds.join(", ")}`);
16348
+ return renderConstBlock("workflowContext", {
16349
+ boundary: {
16350
+ timestamp: focus.boundaryTimestamp,
16351
+ reason: focus.boundaryReason,
16352
+ latestClosureId: focus.latestClosureId || null
16353
+ },
16354
+ recentActions: focus.recentActionSummary,
16355
+ workingSet: {
16356
+ variables: focus.variableNames,
16357
+ lists: focus.listNames,
16358
+ entries: focus.entryPaths
16359
+ },
16360
+ openHandles: {
16361
+ tasks: focus.activeTaskIds,
16362
+ decisions: focus.openDecisionIds,
16363
+ prompts: focus.openPromptIds
15499
16364
  }
15500
- }
15501
- return lines.join("\n");
16365
+ });
15502
16366
  }
15503
16367
  function hasOpenPrompt(liveDoc, pendingPrompts) {
15504
16368
  if (pendingPrompts.length > 0) return true;
@@ -15514,7 +16378,6 @@ function hasOpenPrompt(liveDoc, pendingPrompts) {
15514
16378
  return false;
15515
16379
  }
15516
16380
  function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15517
- const lines = [];
15518
16381
  const loop = asRecord4(liveDoc?.loop);
15519
16382
  const boundary = getWorkflowBoundary(liveDoc, options);
15520
16383
  const tasks = toSortedRecords(loop?.tasksById).filter((task) => {
@@ -15536,22 +16399,12 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15536
16399
  5
15537
16400
  );
15538
16401
  const hiddenTaskCount = Math.max(0, activeTasks.length - visibleTasks.length);
15539
- lines.push("Tasks:");
15540
- if (visibleTasks.length === 0) {
15541
- lines.push("- none");
15542
- } else {
15543
- lines.push("- Reuse existing taskId values exactly as written below.");
15544
- for (const task of visibleTasks) {
15545
- const title = typeof task.title === "string" ? task.title : "Untitled task";
15546
- const taskId = typeof task.taskId === "string" ? task.taskId : "unknown";
15547
- const status = typeof task.status === "string" ? task.status : "pending";
15548
- const summary = typeof task.summary === "string" && task.summary.trim() ? ` \u2014 ${task.summary.trim()}` : "";
15549
- lines.push(`- [${status}] ${title} (${taskId})${summary}`);
15550
- }
15551
- if (hiddenTaskCount > 0) {
15552
- lines.push(`- ${hiddenTaskCount} more active task(s) omitted`);
15553
- }
15554
- }
16402
+ const compactTasks = visibleTasks.map((task) => ({
16403
+ id: typeof task.taskId === "string" ? task.taskId : "unknown",
16404
+ title: typeof task.title === "string" ? task.title : "Untitled task",
16405
+ status: typeof task.status === "string" ? task.status : "pending",
16406
+ summary: typeof task.summary === "string" && task.summary.trim() ? task.summary.trim() : null
16407
+ }));
15555
16408
  const decisions = toSortedRecords(loop?.decisionsById).filter((decision) => {
15556
16409
  const updatedAt = Number(decision.updatedAt) || Number(decision.createdAt) || 0;
15557
16410
  if (boundary.reason === "request_start") {
@@ -15565,33 +16418,29 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15565
16418
  (decision) => decision.status === "open"
15566
16419
  );
15567
16420
  const visibleDecisions = (openDecisions.length > 0 ? openDecisions : decisions.slice(0, 1)).slice(0, 3);
15568
- lines.push("", "Recent Decisions:");
15569
- if (visibleDecisions.length === 0) {
15570
- lines.push("- none");
15571
- } else {
15572
- lines.push("- Reuse existing decisionId values exactly as written below.");
15573
- for (const decision of visibleDecisions) {
15574
- const status = typeof decision.status === "string" ? decision.status : "resolved";
15575
- const title = typeof decision.title === "string" && decision.title.trim() ? decision.title.trim() : "Decision";
15576
- const decisionId = typeof decision.decisionId === "string" ? decision.decisionId : "unknown";
15577
- if (status === "open") {
15578
- const candidatePreview = asArray2(decision.candidates).slice(0, 3).map((candidate) => {
15579
- const record = asRecord4(candidate);
15580
- if (!record) return null;
15581
- const candidateId = typeof record.id === "string" ? record.id : "unknown";
15582
- const candidateLabel = typeof record.label === "string" && record.label.trim() ? record.label.trim() : candidateId;
15583
- return candidateLabel === candidateId ? candidateId : `${candidateLabel} (${candidateId})`;
15584
- }).filter((value) => Boolean(value)).join(", ");
15585
- lines.push(
15586
- `- [open] ${title} (${decisionId})${candidatePreview ? ` \u2014 candidates: ${candidatePreview}` : ""}`
15587
- );
15588
- } else {
15589
- const selected = asRecord4(decision.selected);
15590
- const label = typeof selected?.label === "string" ? selected.label : typeof selected?.id === "string" ? selected.id : "unknown";
15591
- lines.push(`- [resolved] ${title} (${decisionId}) -> ${label}`);
16421
+ const compactDecisions = visibleDecisions.map((decision) => {
16422
+ const status = typeof decision.status === "string" ? decision.status : "resolved";
16423
+ const selected = asRecord4(decision.selected);
16424
+ return {
16425
+ id: typeof decision.decisionId === "string" ? decision.decisionId : "unknown",
16426
+ title: typeof decision.title === "string" && decision.title.trim() ? decision.title.trim() : "Decision",
16427
+ status,
16428
+ candidates: status === "open" ? asArray2(decision.candidates).slice(0, 5).map((candidate) => {
16429
+ const record = asRecord4(candidate);
16430
+ if (!record) return null;
16431
+ return {
16432
+ id: typeof record.id === "string" ? record.id : "unknown",
16433
+ label: typeof record.label === "string" && record.label.trim() ? record.label.trim() : null,
16434
+ description: typeof record.description === "string" && record.description.trim() ? record.description.trim() : null,
16435
+ metadata: asRecord4(record.metadata)
16436
+ };
16437
+ }).filter(Boolean) : [],
16438
+ selected: status === "open" ? null : {
16439
+ id: typeof selected?.id === "string" ? selected.id : null,
16440
+ label: typeof selected?.label === "string" ? selected.label : null
15592
16441
  }
15593
- }
15594
- }
16442
+ };
16443
+ });
15595
16444
  const openPrompts = [
15596
16445
  ...pendingPrompts.map((prompt) => ({
15597
16446
  id: prompt.id,
@@ -15611,29 +16460,29 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15611
16460
  (pendingPrompt) => pendingPrompt.id === promptId
15612
16461
  ) : false);
15613
16462
  }) : openPrompts;
15614
- lines.push("", "Open Prompts:");
15615
- if (visiblePrompts.length === 0) {
15616
- lines.push("- none");
15617
- } else {
15618
- for (const prompt of visiblePrompts.slice(0, 3)) {
15619
- const title = typeof prompt.title === "string" && prompt.title.trim() ? prompt.title.trim() : "Input required";
15620
- const type = typeof prompt.type === "string" ? prompt.type : "input";
15621
- const message = typeof prompt.message === "string" && prompt.message.trim() ? ` \u2014 ${prompt.message.trim()}` : "";
15622
- lines.push(`- [${type}] ${title}${message}`);
15623
- }
15624
- }
16463
+ const compactPrompts = visiblePrompts.slice(0, 3).map((prompt) => {
16464
+ const promptRecord = asRecord4(prompt) || {};
16465
+ return {
16466
+ id: typeof promptRecord.id === "string" ? promptRecord.id : typeof promptRecord.promptId === "string" ? promptRecord.promptId : null,
16467
+ type: typeof promptRecord.type === "string" ? promptRecord.type : "input",
16468
+ title: typeof promptRecord.title === "string" && promptRecord.title.trim() ? promptRecord.title.trim() : "Input required",
16469
+ message: typeof promptRecord.message === "string" && promptRecord.message.trim() ? promptRecord.message.trim() : null
16470
+ };
16471
+ });
15625
16472
  const currentClosureId = getCurrentClosureId(liveDoc);
15626
16473
  const closureRecord = currentClosureId ? asRecord4(asRecord4(loop?.closuresById)?.[currentClosureId]) : null;
15627
16474
  const visibleClosure = closureRecord && (boundary.reason !== "request_start" || (Number(closureRecord.createdAt) || 0) >= boundary.timestamp) ? closureRecord : null;
15628
- lines.push("", "Loop Closure:");
15629
- if (visibleClosure) {
15630
- const status = typeof visibleClosure.status === "string" ? visibleClosure.status : "completed";
15631
- const summary = typeof visibleClosure.summary === "string" ? visibleClosure.summary : "No summary";
15632
- lines.push(`- current: [${status}] ${summary} (${currentClosureId})`);
15633
- } else {
15634
- lines.push("- none");
15635
- }
15636
- return lines.join("\n");
16475
+ return renderConstBlock("workflowState", {
16476
+ tasks: compactTasks,
16477
+ hiddenActiveTaskCount: hiddenTaskCount,
16478
+ decisions: compactDecisions,
16479
+ openPrompts: compactPrompts,
16480
+ closure: visibleClosure ? {
16481
+ id: currentClosureId,
16482
+ status: typeof visibleClosure.status === "string" ? visibleClosure.status : "completed",
16483
+ summary: typeof visibleClosure.summary === "string" ? visibleClosure.summary : null
16484
+ } : null
16485
+ });
15637
16486
  }
15638
16487
  function projectHeapSummary(heap, options) {
15639
16488
  const heapRecord = asRecord4(heap) || {};
@@ -15678,55 +16527,72 @@ function projectHeapSummary(heap, options) {
15678
16527
  referencedPaths.add(path2);
15679
16528
  }
15680
16529
  const visibleLists = Object.values(listsByName).map((value) => asRecord4(value)).filter((value) => Boolean(value)).filter(
15681
- (list) => variables.some((variable) => variable.listName === list.name) || Boolean(list.name && focusedListNames.has(list.name))
16530
+ (list) => variables.some(
16531
+ (variable) => Boolean(variable?.listName === list.name)
16532
+ ) || Boolean(list.name && focusedListNames.has(list.name))
15682
16533
  ).sort((left, right) => (right.updatedAt || 0) - (left.updatedAt || 0)).slice(0, maxLists);
15683
16534
  const visibleEntries = Object.values(entriesByPath).map((value) => asRecord4(value)).filter((value) => Boolean(value)).filter((entry) => entry.path && referencedPaths.has(entry.path)).sort((left, right) => (right.updatedAt || 0) - (left.updatedAt || 0)).slice(0, maxEntries);
15684
- const lines = [];
15685
- lines.push("Variables:");
15686
- if (variables.length === 0) {
15687
- lines.push("- none");
15688
- } else {
15689
- for (const variable of variables) {
15690
- if (variable.kind === "scalar") {
15691
- lines.push(
15692
- `- ${variable.name}: scalar = ${formatScalar(variable.value)}`
15693
- );
15694
- continue;
15695
- }
15696
- if (variable.kind === "entry") {
15697
- const entry = variable.entryPath ? asRecord4(
15698
- entriesByPath[variable.entryPath]
15699
- ) : null;
15700
- lines.push(
15701
- `- ${variable.name}: entry<${variable.className || entry?.className || "unknown"}> -> ${entry ? describeHeapEntry(entry) : variable.entryPath || "missing"}`
15702
- );
15703
- continue;
15704
- }
15705
- const list = variable.listName ? asRecord4(listsByName[variable.listName]) : null;
15706
- lines.push(
15707
- `- ${variable.name}: list<${variable.className || list?.className || "unknown"}> -> ${(list?.paths || []).length} item(s)`
15708
- );
15709
- }
15710
- }
15711
- lines.push("", "Named Lists:");
15712
- if (visibleLists.length === 0) {
15713
- lines.push("- none");
15714
- } else {
15715
- for (const list of visibleLists) {
15716
- lines.push(
15717
- `- ${list.name}: ${list.className || "unknown"}[${(list.paths || []).length}]`
15718
- );
15719
- }
15720
- }
15721
- lines.push("", "Active Entries:");
15722
- if (visibleEntries.length === 0) {
15723
- lines.push("- none");
15724
- } else {
15725
- for (const entry of visibleEntries) {
15726
- lines.push(`- ${describeHeapEntry(entry)}`);
15727
- }
15728
- }
15729
- return lines.join("\n");
16535
+ return renderConstBlock("savedData", {
16536
+ variables: Object.fromEntries(
16537
+ variables.filter((variable) => typeof variable.name === "string").map((variable) => {
16538
+ if (variable.kind === "scalar") {
16539
+ return [
16540
+ variable.name,
16541
+ { kind: "scalar", value: variable.value ?? null }
16542
+ ];
16543
+ }
16544
+ if (variable.kind === "entry") {
16545
+ const entry = variable.entryPath ? asRecord4(
16546
+ entriesByPath[variable.entryPath]
16547
+ ) : null;
16548
+ return [
16549
+ variable.name,
16550
+ {
16551
+ kind: "entry",
16552
+ type: variable.className || entry?.className || "unknown",
16553
+ path: variable.entryPath || null,
16554
+ label: entry?.label || entry?.id || null
16555
+ }
16556
+ ];
16557
+ }
16558
+ const list = variable.listName ? asRecord4(listsByName[variable.listName]) : null;
16559
+ return [
16560
+ variable.name,
16561
+ {
16562
+ kind: "list",
16563
+ type: variable.className || list?.className || "unknown",
16564
+ list: variable.listName || null,
16565
+ count: (list?.paths || []).length
16566
+ }
16567
+ ];
16568
+ })
16569
+ ),
16570
+ lists: Object.fromEntries(
16571
+ visibleLists.filter((list) => typeof list.name === "string").map((list) => [
16572
+ list.name,
16573
+ {
16574
+ type: list.className || "unknown",
16575
+ count: (list.paths || []).length
16576
+ }
16577
+ ])
16578
+ ),
16579
+ entries: Object.fromEntries(
16580
+ visibleEntries.filter((entry) => typeof entry.path === "string").map((entry) => [
16581
+ entry.path,
16582
+ {
16583
+ type: entry.className || "unknown",
16584
+ id: entry.id || null,
16585
+ label: entry.label || entry.id || null,
16586
+ fields: asArray2(entry.fields).filter(
16587
+ (field) => field?.name && field.name !== "_realId" && field.name !== "real_id"
16588
+ ).slice(0, 3).map((field) => ({
16589
+ name: field.name,
16590
+ value: field.value ?? null
16591
+ }))
16592
+ }
16593
+ ])
16594
+ )
16595
+ });
15730
16596
  }
15731
16597
  function createHarnessVerifierSnapshot(input) {
15732
16598
  const workflowFocus = projectWorkflowFocus(
@@ -15823,8 +16689,8 @@ function buildContinuationInstruction(resultPreview) {
15823
16689
  "If the user names a concrete record that is not already in the heap, resolve it from the graph before saying it is missing: try a broad search, then a small set of normalized/fuzzy variants or a paged scan when the domain supports it.",
15824
16690
  "If the request needs all matching records, use iterate(...) or page until hasMore is false. A single list(...) or page(...) call is only one page.",
15825
16691
  "If this request clearly spans multiple steps and there are no active tasks yet, create 2-4 short user-visible tasks now.",
15826
- "Reuse any existing taskId and decisionId values exactly as they appear in AGENT LOOP STATE.",
15827
- "When progress depends on the user's choice, missing detail, or approval, use loop.ask_user(...) or loop.confirm(...) so the job pauses and resumes through the live workflow.",
16692
+ "Reuse any existing taskId and decisionId values exactly as they appear in [State].",
16693
+ "When progress depends on the user's choice, missing detail, or confirmation, use loop.ask_user(...) or loop.confirm(...) so the job pauses and resumes through the live workflow.",
15828
16694
  "After a resumed ask_user or confirm call, continue the same job and perform the newly authorized action when the answer is sufficient. Do not stop with placeholder text like 'I'm ready to do it next.'",
15829
16695
  "If you ask the user a new question in this job, do not also close the loop in the same job.",
15830
16696
  "Write the smallest straightforward code for the current step. Avoid defensive fallback branches for hypothetical states that are not currently true.",
@@ -15835,39 +16701,101 @@ ${resultPreview}` : null
15835
16701
  ].filter(Boolean).join("\n\n");
15836
16702
  }
15837
16703
  function buildGranularAgentDomainBlock(domainDocumentation) {
15838
- return domainDocumentation?.trim() || "No domain reference available. The graph may not be ready yet.";
16704
+ return domainDocumentation?.trim() || "No domain contract available. The graph may not be ready yet.";
15839
16705
  }
15840
16706
  function buildGranularAgentSessionBlock(sessionContext) {
15841
- if (!sessionContext) return "No session metadata available.";
15842
- const rows = [
15843
- ["sandboxId", sessionContext.sandboxId],
15844
- ["environmentId", sessionContext.environmentId],
15845
- ["userName", sessionContext.userName]
15846
- ];
15847
- const activeRows = rows.filter(([, value]) => Boolean(value));
15848
- if (activeRows.length === 0) return "No session metadata available.";
15849
- return activeRows.map(([key, value]) => `${key}: ${value}`).join("\n");
16707
+ return renderConstBlock("session", {
16708
+ runtimeId: sessionContext?.sandboxId || null,
16709
+ environmentId: sessionContext?.environmentId || null,
16710
+ userName: sessionContext?.userName || null,
16711
+ domainRevision: sessionContext?.domainRevision || null
16712
+ });
15850
16713
  }
15851
16714
  function buildGranularAgentHeapBlock(heapSummary) {
15852
- return heapSummary?.trim() || "Heap is empty for this session.";
16715
+ return heapSummary?.trim() || renderConstBlock("savedData", {
16716
+ variables: {},
16717
+ lists: {},
16718
+ entries: {}
16719
+ });
15853
16720
  }
15854
16721
  function buildGranularAgentReferentBlock(referentSummary) {
15855
- return referentSummary?.trim() || "No recent referents recorded from prior assistant replies.";
16722
+ return referentSummary?.trim() || renderConstBlock("recentReferences", []);
15856
16723
  }
15857
16724
  function buildGranularAgentLoopBlock(loopSummary) {
15858
- return loopSummary?.trim() || "No active loop state recorded for this session.";
16725
+ return loopSummary?.trim() || renderConstBlock("workflowState", {
16726
+ tasks: [],
16727
+ decisions: [],
16728
+ openPrompts: [],
16729
+ closure: null
16730
+ });
15859
16731
  }
15860
16732
  function buildGranularAgentWorkflowBlock(workflowSummary) {
15861
- return workflowSummary?.trim() || "No current workflow snapshot recorded for this request yet.";
16733
+ return workflowSummary?.trim() || renderConstBlock("workflowContext", {
16734
+ boundary: null,
16735
+ recentActions: [],
16736
+ workingSet: {
16737
+ variables: [],
16738
+ lists: [],
16739
+ entries: []
16740
+ },
16741
+ openHandles: {
16742
+ tasks: [],
16743
+ decisions: [],
16744
+ prompts: []
16745
+ }
16746
+ });
15862
16747
  }
15863
- function buildGranularAgentToolBlock(tools) {
16748
+ function resolvePromptCapabilities(capabilities) {
16749
+ return {
16750
+ executeCode: capabilities?.executeCode !== false,
16751
+ readEntities: capabilities?.readEntities !== false,
16752
+ workflowHelpers: Array.isArray(capabilities?.workflowHelpers) ? capabilities.workflowHelpers : [
16753
+ "ask_user",
16754
+ "confirm",
16755
+ "open_decision",
16756
+ "close_decision",
16757
+ "create_task",
16758
+ "update_task",
16759
+ "complete_task",
16760
+ "close_loop"
16761
+ ],
16762
+ savedData: capabilities?.savedData !== false,
16763
+ showRecords: capabilities?.showRecords !== false
16764
+ };
16765
+ }
16766
+ function buildGranularAgentToolBlock(tools, capabilityOverrides) {
16767
+ const resolvedCapabilities = resolvePromptCapabilities(capabilityOverrides);
16768
+ const normalizedTools = (tools || []).filter((tool) => tool?.name).slice().sort((left, right) => {
16769
+ const leftScope = `${left.className || "global"}:${left.static ? "static" : "instance"}`;
16770
+ const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
16771
+ return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
16772
+ });
16773
+ const writeActions = normalizedTools.filter((tool) => tool.ready !== false).map((tool) => {
16774
+ const scope = tool.className ? `${tool.static ? "class" : "record"}:${tool.className}` : "global";
16775
+ return {
16776
+ name: tool.name,
16777
+ scope,
16778
+ description: tool.description?.trim() || null
16779
+ };
16780
+ });
16781
+ const capabilities = {
16782
+ executeCode: resolvedCapabilities.executeCode,
16783
+ readEntities: resolvedCapabilities.readEntities,
16784
+ writeActions,
16785
+ workflowHelpers: resolvedCapabilities.workflowHelpers,
16786
+ savedData: resolvedCapabilities.savedData,
16787
+ showRecords: resolvedCapabilities.showRecords
16788
+ };
16789
+ return renderConstBlock("capabilities", capabilities);
16790
+ }
16791
+ function buildGranularAgentActionIndex(tools) {
15864
16792
  const normalizedTools = (tools || []).filter((tool) => tool?.name).slice().sort((left, right) => {
15865
16793
  const leftScope = `${left.className || "global"}:${left.static ? "static" : "instance"}`;
15866
16794
  const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
15867
16795
  return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
15868
16796
  });
15869
16797
  if (normalizedTools.length === 0) {
15870
- return "No live effects are available in this session yet.";
16798
+ return "No domain write actions are available.";
15871
16799
  }
15872
16800
  const globalTools = normalizedTools.filter((tool) => !tool.className);
15873
16801
  const staticTools = normalizedTools.filter(
@@ -15876,9 +16804,7 @@ function buildGranularAgentToolBlock(tools) {
15876
16804
  const instanceTools = normalizedTools.filter(
15877
16805
  (tool) => Boolean(tool.className && !tool.static)
15878
16806
  );
15879
- const lines = [
15880
- "Treat this block as the planning map. Use DOMAIN REFERENCE below for exact signatures and query examples."
15881
- ];
16807
+ const lines = ["Available actions by scope:"];
15882
16808
  const appendGroup = (title, group) => {
15883
16809
  lines.push(`- ${title}:`);
15884
16810
  if (group.length === 0) {
@@ -15887,187 +16813,466 @@ function buildGranularAgentToolBlock(tools) {
15887
16813
  }
15888
16814
  for (const tool of group.slice(0, 10)) {
15889
16815
  const availability = tool.ready === false ? " [not ready]" : "";
16816
+ const schema = formatActionSchemaSummary(tool);
15890
16817
  const description = tool.description?.trim() ? ` - ${tool.description.trim()}` : "";
15891
- lines.push(` ${tool.name}${availability}${description}`);
16818
+ lines.push(` ${tool.name}${availability}${schema}${description}`);
15892
16819
  }
15893
16820
  if (group.length > 10) {
15894
16821
  lines.push(` +${group.length - 10} more`);
15895
16822
  }
15896
16823
  };
15897
- appendGroup("Global effects", globalTools);
15898
- appendGroup("Class-level effects", staticTools);
15899
- appendGroup("Record-level effects", instanceTools);
16824
+ appendGroup("Global", globalTools);
16825
+ appendGroup("Class-level", staticTools);
16826
+ appendGroup("Record-level", instanceTools);
15900
16827
  return lines.join("\n");
15901
16828
  }
15902
- function buildGranularAgentCheckpointBlock(checkpoint) {
15903
- if (!checkpoint) {
15904
- return "No previous execution checkpoint recorded for this request yet.";
15905
- }
15906
- const lines = [];
15907
- if (typeof checkpoint.iteration === "number") {
15908
- lines.push(`iteration: ${checkpoint.iteration}`);
15909
- }
15910
- if (checkpoint.latestJobStatus) {
15911
- lines.push(`latestJobStatus: ${checkpoint.latestJobStatus}`);
15912
- }
15913
- if (checkpoint.controllerOutcome) {
15914
- lines.push(`controllerOutcome: ${checkpoint.controllerOutcome}`);
16829
+ function normalizeJsonSchema(value) {
16830
+ if (typeof value === "string") {
16831
+ try {
16832
+ return asRecord4(JSON.parse(value));
16833
+ } catch {
16834
+ return null;
16835
+ }
15915
16836
  }
15916
- if (checkpoint.controllerReason) {
15917
- lines.push(`controllerReason: ${checkpoint.controllerReason}`);
16837
+ return asRecord4(value);
16838
+ }
16839
+ function jsonSchemaTypeName(schema) {
16840
+ const record = normalizeJsonSchema(schema);
16841
+ if (!record) return "unknown";
16842
+ const type = record.type;
16843
+ if (typeof type === "string") {
16844
+ if (type === "array") return "array";
16845
+ if (type === "object") return "object";
16846
+ return type;
15918
16847
  }
15919
- if (typeof checkpoint.noProgressCount === "number") {
15920
- lines.push(`noProgressCount: ${checkpoint.noProgressCount}`);
16848
+ return "unknown";
16849
+ }
16850
+ function summarizeObjectSchema(schema) {
16851
+ const record = normalizeJsonSchema(schema);
16852
+ const properties = asRecord4(record?.properties);
16853
+ if (!properties || Object.keys(properties).length === 0) {
16854
+ return record ? "{}" : null;
16855
+ }
16856
+ const required = new Set(asArray2(record?.required));
16857
+ const fields = Object.entries(properties).slice(0, 8).map(([name, property]) => {
16858
+ const marker = required.has(name) ? "*" : "?";
16859
+ return `${name}${marker}: ${jsonSchemaTypeName(property)}`;
16860
+ });
16861
+ const remaining = Object.keys(properties).length - fields.length;
16862
+ return remaining > 0 ? `${fields.join(", ")}, +${remaining}` : fields.join(", ");
16863
+ }
16864
+ function formatActionSchemaSummary(tool) {
16865
+ const input = summarizeObjectSchema(tool.inputSchema);
16866
+ const output = summarizeObjectSchema(tool.outputSchema);
16867
+ const parts = [];
16868
+ if (input) parts.push(`input { ${input} }`);
16869
+ if (output) parts.push(`output { ${output} }`);
16870
+ return parts.length ? ` (${parts.join("; ")})` : "";
16871
+ }
16872
+ function splitDomainDocumentation(domainDocumentation) {
16873
+ const normalized = domainDocumentation?.trim() || "";
16874
+ if (!normalized) return { types: "", docs: "" };
16875
+ const docsSectionMatch = normalized.match(/\n\s*\[Docs\]\s*\n/i);
16876
+ if (docsSectionMatch?.index !== void 0) {
16877
+ return {
16878
+ types: normalized.slice(0, docsSectionMatch.index).trim(),
16879
+ docs: normalized.slice(docsSectionMatch.index + docsSectionMatch[0].length).trim()
16880
+ };
15921
16881
  }
15922
- if (checkpoint.latestJobError?.trim()) {
15923
- lines.push(`latestJobError: ${checkpoint.latestJobError.trim()}`);
16882
+ const legacyMarker = "Generated usage notes from ./sandbox-tools docs:";
16883
+ const legacyIndex = normalized.indexOf(legacyMarker);
16884
+ if (legacyIndex !== -1) {
16885
+ return {
16886
+ types: normalized.slice(0, legacyIndex).trim(),
16887
+ docs: normalized.slice(legacyIndex + legacyMarker.length).trim()
16888
+ };
15924
16889
  }
15925
- if (Array.isArray(checkpoint.latestActionSummary) && checkpoint.latestActionSummary.length > 0) {
15926
- lines.push("latestActionSummary:");
15927
- for (const line of checkpoint.latestActionSummary.slice(0, 8)) {
15928
- const normalizedLine = normalizeActionSummaryForPrompt(line);
15929
- lines.push(
15930
- normalizedLine.startsWith("- ") ? normalizedLine : `- ${normalizedLine}`
15931
- );
16890
+ return { types: normalized, docs: "" };
16891
+ }
16892
+ function buildGranularAgentCheckpointBlock(checkpoint) {
16893
+ if (!checkpoint) {
16894
+ return renderConstBlock("previousCodeResult", null);
16895
+ }
16896
+ return renderConstBlock("previousCodeResult", {
16897
+ iteration: typeof checkpoint.iteration === "number" ? checkpoint.iteration : null,
16898
+ latestJobStatus: checkpoint.latestJobStatus || null,
16899
+ controllerOutcome: checkpoint.controllerOutcome || null,
16900
+ controllerReason: checkpoint.controllerReason || null,
16901
+ noProgressCount: typeof checkpoint.noProgressCount === "number" ? checkpoint.noProgressCount : null,
16902
+ latestJobError: checkpoint.latestJobError?.trim() || null,
16903
+ latestActionSummary: Array.isArray(checkpoint.latestActionSummary) ? checkpoint.latestActionSummary.slice(0, 8).map(normalizeActionSummaryForPrompt) : [],
16904
+ latestJobResult: checkpoint.latestJobResult?.trim() || null
16905
+ });
16906
+ }
16907
+ function parseSummaryOutcome(summary) {
16908
+ const outcome = {};
16909
+ for (const part of summary.split(",")) {
16910
+ const trimmed = part.trim();
16911
+ const match = /^([A-Za-z0-9_]+)=(.+)$/.exec(trimmed);
16912
+ if (!match) continue;
16913
+ const [, key, rawValue] = match;
16914
+ const unquoted = rawValue.replace(/^"|"$/g, "");
16915
+ if (/^-?\d+(?:\.\d+)?$/.test(unquoted)) {
16916
+ outcome[key] = Number(unquoted);
16917
+ } else if (unquoted === "true" || unquoted === "false") {
16918
+ outcome[key] = unquoted === "true";
16919
+ } else {
16920
+ outcome[key] = unquoted;
15932
16921
  }
15933
16922
  }
15934
- if (checkpoint.latestJobResult?.trim()) {
15935
- lines.push(`latestJobResult:
15936
- ${checkpoint.latestJobResult.trim()}`);
16923
+ return outcome;
16924
+ }
16925
+ function buildKnownFactsFromCheckpoint(checkpoint) {
16926
+ const summaries = Array.isArray(checkpoint?.latestActionSummary) ? checkpoint.latestActionSummary.map(normalizeActionSummaryForPrompt) : [];
16927
+ const facts = [];
16928
+ for (const summary of summaries) {
16929
+ const countedMatch = /^-\s*Counted\s+([A-Za-z0-9_]+).*?->\s*value=(\d+)/.exec(summary);
16930
+ if (countedMatch) {
16931
+ facts.push({
16932
+ entity: countedMatch[1],
16933
+ query: {},
16934
+ totalCount: Number(countedMatch[2])
16935
+ });
16936
+ continue;
16937
+ }
16938
+ const listedMatch = /^-\s*Listed\s+([A-Za-z0-9_]+).*?->\s*(.+)$/.exec(
16939
+ summary
16940
+ );
16941
+ if (!listedMatch) continue;
16942
+ const outcome = parseSummaryOutcome(listedMatch[2]);
16943
+ const count = typeof outcome.totalCount === "number" ? outcome.totalCount : typeof outcome.count === "number" ? outcome.count : void 0;
16944
+ if (typeof count !== "number") continue;
16945
+ const fact = {
16946
+ entity: listedMatch[1],
16947
+ query: {},
16948
+ totalCount: count
16949
+ };
16950
+ if (typeof outcome.hasMore === "boolean") {
16951
+ fact.lastPageHasMore = outcome.hasMore;
16952
+ fact.loadedAllItems = !outcome.hasMore;
16953
+ } else if (typeof outcome.count === "number" && outcome.count === count) {
16954
+ fact.loadedAllItems = true;
16955
+ }
16956
+ facts.push(fact);
15937
16957
  }
15938
- return lines.length > 0 ? lines.join("\n") : "No previous execution checkpoint recorded for this request yet.";
16958
+ return facts.slice(0, 8);
15939
16959
  }
15940
16960
  function buildGranularAgentSystemPrompt(input) {
16961
+ const outputMode = input.outputMode || "agentMessages";
16962
+ const promptCapabilities = resolvePromptCapabilities(input.capabilities);
16963
+ const domainSections = splitDomainDocumentation(input.domainDocumentation);
15941
16964
  const sessionBlock = buildGranularAgentSessionBlock(input.sessionContext);
15942
- const toolBlock = buildGranularAgentToolBlock(input.tools);
15943
- const domainBlock = buildGranularAgentDomainBlock(input.domainDocumentation);
16965
+ const toolBlock = buildGranularAgentToolBlock(
16966
+ input.tools,
16967
+ input.capabilities
16968
+ );
16969
+ const actionIndex = buildGranularAgentActionIndex(input.tools);
16970
+ const domainBlock = buildGranularAgentDomainBlock(domainSections.types);
15944
16971
  const workflowBlock = buildGranularAgentWorkflowBlock(input.workflowSummary);
15945
16972
  const checkpointBlock = buildGranularAgentCheckpointBlock(input.checkpoint);
15946
16973
  const heapBlock = buildGranularAgentHeapBlock(input.heapSummary);
15947
16974
  const referentBlock = buildGranularAgentReferentBlock(input.referentSummary);
15948
16975
  const loopBlock = buildGranularAgentLoopBlock(input.loopSummary);
15949
- return `You are an AI assistant for a live Granular session.
15950
- You can help the user understand the domain, answer questions, or generate and execute code against the live session.
15951
- Your tone must be natural and human-like.
16976
+ const knownFactsBlock = renderConstBlock(
16977
+ "knownFacts",
16978
+ buildKnownFactsFromCheckpoint(input.checkpoint)
16979
+ );
16980
+ const outputRules = outputMode === "returnValue" ? promptCapabilities.showRecords ? `- End every user-facing job by returning either a short natural-language string or an object like \`{ reply, show }\`.
16981
+ - Use \`{ reply, show }\` when the host UI should render records, heap variables, or lists from session state.
16982
+ - For multi-record display, prefer a saved list/listName so the UI can render a table; use entryPaths for a few individual records.
16983
+ - When the user asks to show, list, display, open, or "show them" for records you found, include those heap-backed records in \`show\`; do not answer only with a count or text summary.
16984
+ - For count-only questions such as "how many", "how many X do I have", or "what is the total number of X", call the entity \`.count(...)\` or use page \`totalCount\` only when a page is already needed for other reasons. Answer with text only. Do not fetch, save, or display sample records just to ground a numeric count.
16985
+ - Do not call \`agent_text_message(...)\` or \`agent_heap_objects(...)\` unless the host explicitly opts into those side-channel message helpers.` : `- End every user-facing job by returning a short natural-language string.` : promptCapabilities.showRecords ? `- Every job that answers the user must emit \`agent_text_message(...)\` and/or \`agent_heap_objects(...)\`.
16986
+ - \`agent_text_message(...)\` displays text directly to the user in the host UI. Treat it as the user-facing progress and reply channel, not as a debug log.
16987
+ - For long-running or multi-step jobs, send several short \`agent_text_message(...)\` updates as useful milestones are reached so the user can see what is happening instead of waiting in silence.
16988
+ - Write \`agent_text_message(...)\` content in a friendly, readable product-assistant style: concrete, concise, and natural. Avoid robotic status dumps, raw implementation names, and unexplained IDs unless the ID helps the user.
16989
+ - 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.
16990
+ - 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.
16991
+ - 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"] })\`.
16992
+ - \`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.
16993
+ - 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.
16994
+ - 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.
16995
+ - 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.
16996
+ - For count-only questions such as "how many", "how many X do I have", or "what is the total number of X", call the entity \`.count(...)\` or use page \`totalCount\` only when a page is already needed for other reasons. Answer with \`agent_text_message(...)\` only. Do not call \`agent_heap_objects(...)\`, \`saveAs\`, or \`heap.setVar(...)\` unless the user also asked to see records or a later requested action needs a reusable record selection.
16997
+ - Any job that identifies a specific record in the visible answer must also display that grounded record with \`agent_heap_objects(...)\` when the user should see/open it, or save it with \`heap.setVar(...)\` when it is only needed for follow-up resolution.
16998
+ - For ordered record slices, pages, queues, search results, or ranked lists, save the slice with \`heap.setVar(...)\` and then call \`agent_heap_objects({ variableNames: [...] })\` once. Use a stable name that preserves the slice identity and ordering so later references such as "the second item" or "back on the first slice" resolve to the correct earlier slice, not merely the most recent record.
16999
+ - Do not rely on the final return value for UI output. Do not return ad-hoc \`reply\` / \`show\` payloads instead of explicit agent message calls.` : `- Every job that answers the user must emit \`agent_text_message(...)\`.
17000
+ - \`agent_text_message(...)\` displays text directly to the user in the host UI. Treat it as the user-facing progress and reply channel, not as a debug log.
17001
+ - For long-running or multi-step jobs, send several short \`agent_text_message(...)\` updates as useful milestones are reached so the user can see what is happening instead of waiting in silence.
17002
+ - Write \`agent_text_message(...)\` content in a friendly, readable product-assistant style: concrete, concise, and natural. Avoid robotic status dumps, raw implementation names, and unexplained IDs unless the ID helps the user.
17003
+ - 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.`;
17004
+ const codeRules = promptCapabilities.executeCode ? `Code:
17005
+ - Use when the request needs session data, saved data, workflow state, record display, or available actions.
17006
+ - When using code, assistant text must be empty or one brief summary.
17007
+ - Code must be plain runnable JavaScript with top-level await.
17008
+ - Import needed classes and helpers from "./sandbox-tools".
17009
+ - Use static top-level imports such as \`import { Foo, agent_text_message } from "./sandbox-tools";\`. Do not use dynamic \`await import("./sandbox-tools")\`.
17010
+ - Keep generated jobs as straightforward top-level scripts. Small local helper functions are allowed when they make the code clearer, but avoid hiding domain actions, prompts, or relationship traversal inside broad generic helpers.
17011
+ - Do not nest template literals: never put a backtick string inside another template string or inside a \`\${...}\` expression. Build conditional text in variables first, or use simple string concatenation. For multi-line replies, prefer a \`lines\` array and \`.join("\\n")\`.
17012
+ - Do not write an action branch that finds multiple candidates, emits a "please choose" message, and returns. When the current request asks for an action, the same branch must call \`await loop.ask_user(...)\`, resolve the answer, and continue to the requested action before the job finishes.
17013
+ - User-visible output must use the provided message or record-display helpers.
17014
+ - After calling an action or effect, inspect the returned object and base the user-facing answer on its actual fields.
17015
+ - When calling an action, use the exact input property names from the action schema. Do not invent synonym keys for required inputs.
17016
+ - After a mutation succeeds, ground the answer in the affected record by emitting or saving the record for UI display and naming a stable user-visible identifier when one exists. Do not answer only "done" or "sent".
17017
+ - Never call \`process.exit(...)\`; emit a message and use \`return;\` to stop early.
17018
+ - Add short \`//\` planning comments before meaningful blocks. The user will see these comments concatenated as a planning trace while the job is being drafted, so they should read together like a properly written plan.
17019
+ - In \`//\` planning comments, clearly explain the logic of what the job is about to do: the sequence of steps, why each step matters, and any important decision points or branches.
17020
+ - Write \`//\` planning comments for the user, not for engineers: make them friendly, plain-language, and easy to understand.
17021
+ - Keep \`//\` planning comments in future tense, but vary the phrasing so they do not become a repetitive list of sentences that all start the same way.
17022
+ - Make the \`//\` planning trace feel connected: use natural transitions for sequence, dependency, contrast, and branching when useful. If the next step depends on what the job finds, say that in plain language.
17023
+ - Avoid technical terms, implementation names, code concepts, hidden helper names, and complex domain jargon in \`//\` planning comments unless the user already used that wording.
17024
+ - Each \`//\` planning comment should provide valuable feedback about the plan or next visible step. Do not add filler such as "Starting", "Running", or "Processing".
17025
+ ${outputRules}` : `Code:
17026
+ - Code execution is unavailable. Use text only, or ask the user for missing information.`;
17027
+ const workflowRules = promptCapabilities.workflowHelpers.length > 0 ? `Workflow:
17028
+ - Use workflow helpers when missing input should pause and resume the workflow.
17029
+ - If code discovers missing required input after a read, use \`await loop.ask_user(...)\`; do not just tell the user to provide it.
17030
+ - Do not ask the user for data the job can discover from grounded records, relationships, saved session state, or visible read-only actions. Ask only when the missing value is truly unavailable, ambiguous, or requires a human decision.
17031
+ - When ambiguity blocks a requested action, import \`loop\` and use \`await loop.ask_user({ type: "choice", ... })\` with grounded options so the same job can resume and complete the action. A plain text request such as "please choose one" is not a workflow and leaves the action unhandled.
17032
+ - If a requested action has 2 to 5 plausible grounded targets, the job is not complete after showing them. Do not stop after \`agent_text_message(...)\` or \`agent_heap_objects(...)\`; import \`loop\`, ask for a grounded choice with \`await loop.ask_user(...)\`, then call the action on the selected record after the job resumes.
17033
+ - If a lookup before a mutation returns multiple plausible target records, do not mutate the first sorted or first returned record. Ask for a grounded choice unless the user supplied a unique identifier, ordinal, or selector that leaves exactly one target.
17034
+ - Use choice only for 2 to 5 short grounded options.
17035
+ - For record choices, set each option value to a stable scalar such as the record \`_graphPath\` or \`id\`, not a label-only value.
17036
+ - 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.
17037
+ - 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.
17038
+ - 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.
17039
+ - 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.
17040
+ - 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.
17041
+ - 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.
17042
+ - Reuse existing task, decision, and closure ids from [State].
17043
+ - If a user request matches both a domain record/action and a workflow helper, prefer the domain capability.` : "";
17044
+ return `[Harness]
17045
+ You are an assistant for a live user session. Use plain, natural language.
15952
17046
 
15953
- Call the \`execute_code\` effect ONLY when the user's intent matches the domain's capabilities and requires executing code against the live session. If the user is just asking a general question or if their request doesn't match the available effects or domain types, respond with text to explain.
15954
- When you call \`execute_code\`, additional assistant text must be either:
15955
- - empty, or
15956
- - a brief summary of the actions the generated code will perform.
15957
- Do not include any other kind of commentary when calling \`execute_code\`.
15958
- - If the next step needs to create or update workflow state in the live session, you must call \`execute_code\`. This includes \`loop.ask_user(...)\`, \`loop.confirm(...)\`, \`loop.open_decision(...)\`, \`loop.close_decision(...)\`, \`loop.create_task(...)\`, \`loop.update_task(...)\`, \`loop.complete_task(...)\`, and \`loop.close_loop(...)\`.
15959
- - If the next step is an interactive clarification that should be resumable in the live workflow, you must call \`execute_code\`. A missing preference, rule, metric, target, or option selection is not a plain-text reply when the answer should drive the next live step.
15960
- - If you can offer a short grounded shortlist, that clarification should usually be \`loop.ask_user({ type: 'choice', ... })\` instead of a plain-text question with bullet options.
15961
- - Never simulate a live prompt, confirmation, decision, task change, or loop closure in plain text. Plain-text replies are only for conversational answers that do not need to mutate session state.
17047
+ Mode selection:
17048
+ Text only:
17049
+ - Use for general explanations, unsupported requests, or requests that do not need session data.
17050
+ - Do not use text only when the user asks you to check, look up, search, inspect, update, schedule, or otherwise use session data or tools.
17051
+ - Do not answer with a promise like "I'll check" or "I'll do that next"; if the request needs tools, choose a job and run them now.
17052
+ - Do not expose internal names, helper names, file paths, parameter names, or code.
17053
+ - In code jobs, never use \`console.log(JSON.stringify({ action, reply, code }))\` as a user reply. Use the provided message helpers or final return contract.
15962
17054
 
15963
- \u2500\u2500\u2500 STREAMING COMMENT RULES \u2500\u2500\u2500
15964
- - While you are writing code, add short single-line comments with the prefix \`// \` before meaningful blocks.
15965
- - These comments should explain the intent in friendly product language, not in implementation jargon.
15966
- - Comments are shown live as a reasoning trace, so keep them brief, concrete, and useful.
15967
- - Do not mention method names, file paths, or internal identifiers in those comments.
15968
- - Use only single-line \`//\` comments for this purpose. Do not use block comments.
15969
- - If you are replying with text only, you may also include a few leading \`// \` comment lines before the final answer.
15970
- - End text-only replies with the plain user-facing answer on normal lines, without a comment prefix.
17055
+ ${codeRules}
15971
17056
 
15972
- \u2500\u2500\u2500 RESPONSE STYLE RULES \u2500\u2500\u2500
15973
- - Use plain, friendly product language.
15974
- - Never mention internal implementation details in user-facing text:
15975
- class names, effect names, method names, function names, file paths, parameter names, or code snippets.
15976
- - Never expose dotted identifiers such as \`Class.method\` in user-facing text.
15977
- - Do not say "sandbox" in user-facing text unless the user is explicitly asking about the runtime environment itself.
15978
- - If you need clarification, ask in everyday language.
15979
- - If the missing information should pause the live workflow for later continuation, ask through \`loop.ask_user(...)\` in generated code rather than with a plain-text question.
15980
- - If you are asking the user to pick from explicit options, prefer a live \`loop.ask_user({ type: 'choice', ... })\` prompt over a direct reply that lists those options in text.
15981
- - Keep replies concise and clear.
15982
- - This is a conversation UI, not an API console. Favor human answers over machine-shaped payloads.
17057
+ ${workflowRules}
15983
17058
 
15984
- \u2500\u2500\u2500 SESSION CONTEXT \u2500\u2500\u2500
15985
- ${sessionBlock}
17059
+ High-priority execution rules:
17060
+ - Treat a human reference as something to ground, not as missing data. When the user names or describes a record, group, queue, parent, relationship, or prior result and asks to inspect, decide, update, schedule, approve, send, or otherwise act on session data, run a code job to ground it before asking the user for more details.
17061
+ - For a human-described primary anchor, a no-match answer is only justified after more than one distinct grounding attempt, such as owner/container grounding, relationship traversal, exact id/path lookup, or shorter target-local search. Before the primary no-match return, retry that same anchor with fewer text constraints or a distinct grounding strategy; do not stop after one zero-result list/find/page call.
17062
+ - A confirmation requirement is not a reason to stay text-only. Do all safe read-only grounding and availability/status checks first, then call \`loop.confirm(...)\` or \`loop.ask_user(...)\` before the mutation.
17063
+ - In any code branch where a requested action or mutation has multiple possible targets, import \`loop\` statically and use \`await loop.ask_user(...)\` in that branch. This includes ambiguity discovered after a query returns several records. A branch that only shows candidates, asks in text, and returns leaves the requested action unfinished.
17064
+ - Before any mutation, know whether the target is one record or several. A singular phrase like "the item" is not proof of uniqueness after a query finds multiple matching records. If the user did not give an exact identifier or explicit selection criterion, call \`loop.ask_user({ type: "choice", ... })\` with grounded choices; do not choose by age, amount, priority, order, or convenience on your own. Resolve the target before any yes/no confirmation.
17065
+ - Treat partial names, first words, aliases, and shorthand labels as partial references. Use search/contains or grounded relationship traversal first; do not report no match after only an exact \`equal_to\` name filter.
17066
+ - When a partial name, alias, or shorthand resolves to a stored record, include that record's stored display value in the visible answer at least once. Prefer exact fields such as name, title, number, label, or other user-facing identifier over the user's shorthand.
17067
+ - If the user says the label/name may be wrong, or gives a nickname/quoted phrase, do not stop after one direct target search. Ground the stable anchor in the request first, such as the named owner, container, parent, account, project, location, or other higher-level record; then traverse its declared relationships, inspect related candidate records, and only then report no match or ask for help.
17068
+ - If the user says "still", "current", "latest", "where", "check", "if", or asks you to decide whether a condition is true, first identify the record that can prove the condition. When that condition names a related object, the code order must be: load the action target or anchor, traverse to the related evidence record, call its visible status/lookup action when available, then decide whether to mutate. Do not branch, return, or reject the condition from parent/action-target status before that evidence step.
17069
+ - When a condition names an anchored noun phrase whose final noun is an entity type, the final entity type is the evidence record to test. Use the earlier words only to ground or traverse to that record; do not test the anchor record as a substitute.
17070
+ - Do not treat prior read-only summaries, cached parent fields, action-target fields, or stored related-record fields as fresh evidence for a later conditional mutation when a related evidence object and visible lookup/status action can be reached.
17071
+ - When the user asks whether a suitable or available candidate exists for assignment, scheduling, routing, or ownership, call the visible availability/matching/search action on the candidate entity when one exists. Existing relationships or current assignments are context, not proof of current availability.
17072
+ - When a request names an owner, parent, account, project, location, or other container plus a target item, plan it as two steps: ground the owner/container, then discover the target through declared relationships, relationship filters, or short target-local search. Do not combine owner/container words with target words in one target-class search, and do not require owner/container words to appear in target-local fields such as title or summary.
17073
+ - When the target or evidence record is reached through relationships, use the declared relationship index/getter list as a graph and walk getters whose target types lead toward the needed entity. If a target has a one-record parent field and the user named the grandparent/owner, start from the grandparent/owner and traverse down through getters; do not put the grandparent condition inside the target's parent filter. If a relationship is documented as one-record or many-to-one, never use \`some\` on it.
17074
+ - After refusing a bypass, external-send, export, or restricted-data request, a follow-up that refers to the same item/case/record inherits that boundary even if no record was saved. Do not perform a different mutation, search for replacement candidates, or ask which restricted referent to use; refuse unless a visible allowed workflow explicitly authorizes the new request.
17075
+ - If the previous answer mentioned, displayed, or contrasted multiple plausible records and the next mutation uses only "it", "that", "that one", "the item", or similar, ask which grounded record to use. Even if one record seems more actionable, the pronoun alone is ambiguous, and a confirmation prompt is not a substitute for a grounded choice prompt.
17076
+ - A saved list, heap object collection, table, or record-display artifact with multiple possible mutation targets counts as multiple plausible records even when the visible text only gave counts. Do not pick the first, last, or most recent item from that collection for a pronoun like "that one"; ask for a grounded choice first.
17077
+ - For "first N", "next N", "top N", queue, slice, newest/oldest, or ranked-list requests, use the runtime paging surface on the target record type when it exists. Relationship getters can help discover context, but a local \`.slice(0, N)\` over a relationship array is not a paged queue result.
17078
+ - When selecting a single "top", "best", "urgent", or "most relevant" record from a broad set, do not rely on lexicographic sorting of label fields or the first page while more results exist. Narrow with grounded filters or gather enough candidates first, then rank from explicit record fields.
17079
+ - Do not remove candidates returned by an availability/search action solely because they are already assigned, current, or previously related, unless the user asked for a different candidate. If the action returned them as available or matching, they remain valid candidates.
17080
+ - In filters, use \`some\` only on relationship fields that are declared as many/collection fields. Singular relationship fields must use \`path\`, \`id\`, or \`is\`; if unsure, follow declared getters from an already grounded record instead.
15986
17081
 
15987
- \u2500\u2500\u2500 CAPABILITY SNAPSHOT \u2500\u2500\u2500
15988
- ${toolBlock}
17082
+ Intent resolution:
17083
+ - If intent is explicit, act directly.
17084
+ - For pronouns and discourse references like this, it, that, those, them, their, the previous one, or the selected ones, inspect recentReferences first. Do not use recentReferences array order as a selector when several same-type records could satisfy the phrase.
17085
+ - For follow-up phrases like same item, that record, the one you showed, or the previous result, read the single type-compatible recentReference before doing a fresh search. If the follow-up names a related target or evidence type, use the recent record only as the anchor and traverse declared relationships toward that type before searching the target class directly or deciding a condition.
17086
+ - If recentReferences contains an exact entry path for the follow-up target, call the matching class \`.get({ path })\` first only when that entry is the single plausible type-compatible referent or the user identified it with a unique identifier, ordinal, or descriptive selector. A phrase like "that one" is still a bare pronoun when multiple same-type records were displayed or saved together.
17087
+ - recentReferences includes user-mentioned records, assistant inline object references, and assistant heap object messages; prefer the latest type-compatible reference only when it is the single plausible referent for the phrase and not merely the last item from a multi-record display or saved list.
17088
+ - Record paths are opaque ids. Never synthesize a path from a label, name, title, or user phrase; copy an exact path from [State] or discover the record with a query.
17089
+ - If there is exactly one latest type-compatible reference for a phrase like "that same item", use it directly; do not ask the user to restate the item when you can already name or fetch it. This does not apply when the user refers to an earlier slice/list by ordinal wording, or when the prior answer intentionally contrasted several records.
17090
+ - For explicit continuity phrases like "that same item", "same record", or "the previous result", do not ask the user which record they mean. Use the recent reference first; if no saved reference exists, rerun the prior narrow grounding lookup from the conversation text instead of answering text-only that the record is not grounded.
17091
+ - If a follow-up mutation uses only a pronoun such as "it" or "that" after the prior turn mentioned multiple same-type records, ask the user to choose from grounded options before mutating.
17092
+ - If the prior turn displayed or summarized two or more plausible records and the next mutation says only "it", "that", or "on it", do not infer the target from your own ranking; call \`loop.ask_user({ type: "choice", ... })\` with the grounded records first, then mutate only the chosen record.
17093
+ - If the prior turn intentionally contrasted multiple records that could all receive the requested mutation, a lone pronoun is ambiguous even when one record was listed first or looked more urgent.
17094
+ - If a follow-up mutation uses a bare pronoun and recentReferences contains a matching \`group.id\` with \`group.sameTypeSize\` greater than 1, the target is unresolved. The next code must ask for a grounded choice with \`loop.ask_user(...)\`; never call a mutation on one grouped path first.
17095
+ - For follow-up words like "other", "another", or "remaining" after the user selected one candidate from a previous choice, resolve within the active contrast from that choice and the user's answer. Exclude the selected item, preserve descriptors such as larger, smaller, next, older, different, or same status, and do not take the first leftover from a wider saved list when the contrast narrows the intended set.
17096
+ - Before any mutation, prove the target resolves to exactly one grounded record. If the request describes a set, category, relationship, prior result group, or other non-unique scope, gather the candidate records first; when more than one candidate remains, ask the user to choose before calling the action.
17097
+ - For ambiguous choice prompts before a mutation, every option that describes a different candidate must carry a distinct grounded record value/path. After the answer, do not fall back to the first candidate if matching fails; ask again or stop without mutating.
17098
+ - The [State] constants are prompt context, not runtime variables. Never reference \`savedData\`, \`recentReferences\`, \`workflowContext\`, \`workflowState\`, or \`capabilities\` as variables in generated code. When using a recent reference, copy its path string into code and fetch it with \`Class.get({ path: "..." })\`, or call \`heap.getEntry("...")\` when the class is not obvious.
17099
+ - Never write placeholder grounding code such as \`const path = null\`, \`const groundedPath = ""\`, or \`const recordPath = ""\`. If no saved reference is available, delete that branch entirely and execute the fallback lookup directly.
17100
+ - Never call \`.get({ path: "" })\`; an empty path is not a saved reference.
17101
+ - For ordinal references to earlier pages, slices, lists, or ranked results, use the saved list/recent references first. If no saved list is available, rerun the exact same ordered query and select the ordinal index from its returned \`items\`; never invent a record path from a label or ordinal.
17102
+ - \`.get({ path })\` returns \`null\` when a path is not found; it does not throw for normal misses. Check for null before using a search fallback.
17103
+ - If multiple recent references could satisfy the phrase and the action or target would materially differ, ask for a grounded choice before any confirmation or mutation.
17104
+ - If the entity, field, target, scope, ranking, or action is ambiguous, create 2 to 5 plausible interpretations.
17105
+ - Probe plausible interpretations with cheap read-only queries before deciding.
17106
+ - A zero-result first query is not enough to report failure for a human reference; continue in the same job with another grounded strategy such as partial search, owner/container grounding, or relationship traversal before reporting no match.
17107
+ - If a direct target search returns zero and the request contains a stable anchor such as a named related record or higher-level container, ground that anchor and inspect related records before reporting no match.
17108
+ - One strong match means proceed.
17109
+ - Several plausible matches means call \`loop.ask_user({ type: "choice", ... })\` with grounded choices.
17110
+ - No grounded match means ask for missing information.
17111
+ - For consequential changes, resolve first, confirm when needed, then act.
17112
+ - Do not ask the user to resend a request because you need to verify data. If the request needs verification, run a job that verifies it now. If a follow-up reference is not available, rerun the prior narrow grounding lookup or ask a specific grounded question.
17113
+ - If the user asks a read-only advisory question such as "Should we message the team?" and also says not to update/send/act yet, provide the recommendation from grounded data. Do not pause with \`loop.ask_user\` or \`loop.confirm\`.
17114
+ - If the user asks for specific fields, read those fields from the grounded record and include every requested value in the visible answer. If saved state identifies the record but does not include the requested fields, fetch the record before answering. Only say a field is unavailable after checking the documented field/property on the fetched record.
17115
+ - If the user asks for blocked work and sensitive/restricted work as separate things, keep those candidate sets separate. Exclude sensitive or restricted-workflow records from the ordinary blocked operational candidate unless the user explicitly asks for blocked sensitive work.
17116
+
17117
+ Use exploratory probing when:
17118
+ - the user gives a human reference instead of an exact id or path
17119
+ - a noun could refer to multiple entity types
17120
+ - a name, number, label, date, or amount is given without a clear field
17121
+ - ranking words are used without a clear metric
17122
+ - a requested change has an unclear target
17123
+ - the first reasonable lookup returns zero results
17124
+ - the first reasonable lookup returns several plausible results
15989
17125
 
15990
- \u2500\u2500\u2500 DOMAIN REFERENCE (from ./sandbox-tools) \u2500\u2500\u2500
15991
- Import classes and effect functions from \`./sandbox-tools\` in generated code.
15992
- Use the TypeScript declarations for exact signatures. When present, the generated usage notes below them show query patterns and examples.
17126
+ Do not explore when:
17127
+ - the entity, field, filter, and action are explicit
17128
+ - the request is a general explanation
17129
+ - the request is unsupported by available capabilities
17130
+ - the next step is already a required workflow answer or confirmation
17131
+
17132
+ [Types]
17133
+ Import classes, helpers, and available actions from "./sandbox-tools".
17134
+ Use the domain contract below as the exact code-facing contract. Generated docs, relationship indexes, and action indexes are authoritative for valid fields, getters, actions, and filter shapes.
15993
17135
 
15994
17136
  ${domainBlock}
15995
17137
 
15996
- \u2500\u2500\u2500 EXECUTION CHECKPOINT \u2500\u2500\u2500
17138
+ [Docs]
17139
+ Query policy:
17140
+ - Use filter, search, sort, count, page, list, and iterate on entity classes.
17141
+ - Push filtering and sorting into entity queries. Do not fetch a page only to filter or sort locally.
17142
+ - Valid filter fields are defined by each entity filter type.
17143
+ - Valid sort fields are defined by each entity sort field type.
17144
+ - Search is class-wide text retrieval, not a field-scoped operator.
17145
+ - Entity classes do not have a \`.search(...)\` method. Use \`.find({ search })\`, \`.page({ search, ... })\`, or \`.list({ search, ... })\`.
17146
+ - Entity \`.list(...)\` returns an array of records; use \`matches[0]\`, \`matches.length\`, and direct iteration. Entity \`.page(...)\` returns \`{ items, page, perPage, totalCount, hasMore }\`; only page results have \`.items\`.
17147
+ - For natural queue slices, infer pagination even when the user does not say "page": "first five" means \`page: 1, perPage: 5\`; a follow-up "next five" for the same queue means \`page: 2, perPage: 5\` with the same sort and grounded filter.
17148
+ - For first/next/top queue slices, page the target item class directly with a structured relationship filter. Relationship getters and local \`.slice(0, 5)\` are useful for exploration but do not prove runtime pagination.
17149
+ - Combine search and filter when both free-text matching and exact constraints are needed.
17150
+ - For exact categorical states, prefer positive filters with \`equal_to\` or \`in\`. Do not express a requested state through substring negation of a different state with \`not_contains\`; categorical labels can contain other labels and disappear from the result.
17151
+ - Do not use \`not_in\`; the runtime filter surface does not support it. Use \`in\` with explicit allowed values, or fetch a bounded candidate page and filter excluded values locally before showing the final slice.
17152
+ - Boolean filters use \`equal_to: true\` or \`equal_to: false\`.
17153
+ - Use \`equal_to\` on names only when you know the full stored value. A shortened name, first word, fragment, alias, or nickname is not an exact name; use search/contains first and then ground the exact record. If an exact-name query returns zero for a human-supplied name, retry with search/contains in the same job before reporting that nothing exists.
17154
+ - Keep full-text search strings short and distinctive. Prefer one concrete name/id or 1 to 3 salient terms, then use filters, relationships, or local ranking for the rest.
17155
+ - Do not search a target entity for only a related-record name while also filtering by that relationship. First ground the related record, then use a relationship filter/getter, and use target-entity search only for the target's own identifier, title, label, description, or other target-local fields.
17156
+ - When the user combines a concrete entity name with generic task words like a priority, workflow state, risk, summary, or requested outcome, do not put the whole phrase into one full-text search. Search/filter the concrete name first, then apply status, priority, relationship, amount, date, or ranking constraints.
17157
+ - Treat urgency as priority unless the domain explicitly documents urgent as a status. For an urgent operational item, do not require \`status = "urgent"\`; inspect status/blocker after grounding likely priority matches.
17158
+ - Do not sort a free-text priority, severity, or rank-like label field and assume the first row is most important. Rank candidates locally from explicit field values and continue paging or narrow the query when the result says more records exist.
17159
+ - When looking for blocked or blocking work, treat phrases such as "no blocker", "not blocked", "without blocker", "none", and "clear" as negative evidence. Do not select a record only because its summary/title contains the substring "block"; prefer explicit blocker/status fields and keep scanning for a true blocker.
17160
+ - For broad "open", "active", or "top" operational records, avoid guessing a tiny fixed status list unless the domain documents one. Prefer relationship grounding plus a supported positive filter/list, or locally exclude clearly terminal states such as resolved, closed, complete, completed, paid, canceled, or archived after fetching a bounded sorted candidate page.
17161
+ - When a requested object is normally reached through relationships, follow the declared relationship chain from the grounded parent or related record before giving up on a direct search. If the target entity type is named, prefer chains whose declared return types lead to that target type.
17162
+ - Prefer generated instance relationship getters from a grounded record over hand-written deep nested relationship filters.
17163
+ - When you have grounded a parent record and need its related records, call the declared parent getter such as \`parent.get_related_records()\` instead of writing a nested relationship filter on the target class.
17164
+ - When deciding whether a related object is still in a current state, traverse to the related evidence record and call its visible lookup/status action when available. Do not decide, stop, post, or treat the condition as false from only stored fields, the parent record's status/title/summary, or prior displayed text.
17165
+ - For queues owned by a higher-level record, ground that record and keep the exact query plan: target class, direct relationship path or getter chain, filters, sort, page, and perPage. Save the displayed page and reuse the same plan for follow-up pages instead of inventing a new relationship filter.
17166
+ - Relationship getters return exactly their named entity type. If you call a getter for units/sites, those are not operational items; call the next declared item/work getter on each unit/site, or query the item class directly before reading item fields.
17167
+ - Relationship getters return only their declared related entity type. Do not treat one relationship result as another entity type because the request mentions it; walk the declared relationship chain exactly, or use a grounded direct query for the target entity.
17168
+ - Only call relationship getters that are declared for the class of the record you currently have. If the needed target is not a direct getter on that class, walk through the declared intermediate getter first; never skip a relationship hop by inventing a convenience getter.
17169
+ - Relationship getters are async. Always \`await record.get_related_records()\` before checking whether the result is an array, iterating it, or reading fields from its records.
17170
+ - Relationship filter fields are selectors, not hydrated nested objects. To read a field from a related record, call the declared relationship getter and use the returned record; do not read \`record.relationship.someField\` from the original record.
17171
+ - Do not filter relationship fields with scalar text operators. For example, do not write \`related: { contains: "Example" }\` or pass a parent path into a child filter; ground the related record first, then use the correctly typed relationship getter or \`id\`/\`path\` filter.
17172
+ - Relationship path filters must use a path for the relationship's target type. If a target item has a related parent/container field and the user named a higher-level parent, first follow the parent's declared getter to the correct related record, then use that related record's \`_graphPath\`; never put the wrong record type's path into a child relationship filter.
17173
+ - Do not use a target record's local text fields to prove ownership by a named parent/container. A filter such as \`title/summary contains parentName\` is not a relationship. Ground the parent/container and traverse getters or use the documented relationship field.
17174
+ - Do not write transitive relationship filters such as \`container: { is: { parent: ... } }\` for queue slices. Use a direct relationship path filter from the already grounded related record, such as \`container: { path: container._graphPath }\`.
17175
+ - Do not invent broad relationship filter fields on a target class unless that field is present in the generated filter type. For owned queues, ground the parent first, use declared relationship getters to reach the owned related records, or use the exact documented relationship field.
17176
+ - Do not optional-chain relationship getters to guess at hidden relationships. If a getter is not declared in the TypeScript contract, it does not exist.
17177
+ - Generated relationship getters return arrays of related records, not page objects. Iterate the returned array directly; do not read \`.items\` from a relationship getter result.
17178
+ - If an explicit target entity is not found through an expected relationship chain, try a grounded direct query/search for that target entity before reporting that no target exists.
17179
+ - 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.
17180
+ - 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.
17181
+ - 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.
17182
+ - 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.
17183
+ - 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.
17184
+ - For scheduling actions, convert relative wording into concrete ISO timestamps before mutating records.
17185
+ - 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.
17186
+ - When deciding whether something is blocked, held, delayed, or still active, combine the fresh lookup result with relevant status, blocker, summary, checkpoint, reason, and latest update fields. Do not use a tiny hand-written status allowlist as the only authority; words such as hold, held, pending, delayed, awaiting, blocked, customs, review, and exception are blocking evidence unless the domain explicitly says otherwise.
17187
+ - One page does not prove there are no more records. For all, every, export, or broad scans, use iteration or page until there are no more results.
17188
+ - When selecting a single "best", "urgent", "top", or "most relevant" record from a broad page, do not assume the first returned page is complete if \`hasMore\` is true. Continue paging, use iteration, or add a stronger grounded filter before selecting.
17189
+ - For exploratory work, use count for totals and page with small perPage for samples; use iteration only after the interpretation is chosen.
17190
+
17191
+ Lookup ladder:
17192
+ 1. Check recent references and saved session data.
17193
+ 2. Try exact id or path when the user gave an id-like value.
17194
+ 3. If the request names a parent/container plus a target, ground the parent/container and traverse declared relationships to target candidates.
17195
+ 4. Try exact filters on fields whose names or aliases match the user words.
17196
+ 5. Try class-wide search with short target-local terms, not the whole user phrase.
17197
+ 6. Try relationship filters when the user mentions connected concepts and the filter shape is documented.
17198
+ 7. If the user names a parent/container and says the label may be approximate, inspect related target records before reporting no match.
17199
+ 8. If still empty, try one small set of normalized, prefix, or fuzzy variants when search supports it.
17200
+ 9. If still empty or ambiguous, ask the user for steering.
17201
+
17202
+ Exploration budget:
17203
+ - For a simple ambiguous reference, try up to 3 strategies.
17204
+ - For a broad ambiguous task, try up to 5 strategies.
17205
+ - Probe with small pages.
17206
+ - Do not run exhaustive scans during probing unless the user explicitly asks for all records or the selected task requires aggregation.
17207
+ - Stop early when a strong unique match is found.
17208
+
17209
+ Strong unique match:
17210
+ - exactly one record matches an exact id or path
17211
+ - exactly one record matches an exact filter on a likely identifier field
17212
+ - exactly one recent reference or saved value fits the request
17213
+ - one interpretation has results and all other reasonable interpretations have none
17214
+
17215
+ Ask the user when:
17216
+ - multiple exact matches exist
17217
+ - several entity types match the same phrase
17218
+ - the best match comes only from broad search and other plausible matches exist
17219
+ - the ranking or metric is unclear
17220
+ - the target is unique but the requested action is unclear
17221
+
17222
+ Relationship filters:
17223
+ - One-record relationships use \`is\`.
17224
+ - Multi-record relationships use \`some\`.
17225
+ - Never guess relationship cardinality from wording. Check the generated TypeScript filter type for the field before writing a relationship filter; if you are not sure, use declared relationship getters from already grounded records instead of a relationship filter.
17226
+ - If a relationship filter type or field is one-record/singular, never use \`some\` on that field. Match by \`id\`, \`path\`, or \`is\`, or fetch the related record and continue through declared getters when you need to traverse farther.
17227
+ - Do not invent nested operators under relationship fields. A one-record relationship filter accepts only its documented operators such as \`id\`, \`path\`, \`is\`, \`null\`, and \`not_null\`; deeper conditions must go under \`is\` or be handled by fetching records and following getters.
17228
+ - Never use \`some\` on one-record fields. If the generated TypeScript type says \`OneRelationFilter\`, valid operators are \`id\`, \`path\`, \`is\`, \`null\`, and \`not_null\`; \`some\` is invalid.
17229
+ - Use \`some\` only when the generated TypeScript type says \`ManyRelationFilter\`.
17230
+ - For a singular relationship that points to an intermediate record, nested filters still use \`is\` at the singular hop. Do not use \`some\` because the nested condition names another related record.
17231
+ - Use \`{ relationship: { id: "record_id" } }\` or \`{ relationship: { path: "class_record_id" } }\` when matching a known related record.
17232
+ - When you already fetched the related record, use \`{ relationship: { path: record._graphPath } }\` or \`{ relationship: { id: record.id } }\`; do not wrap a known id/path under \`is\`.
17233
+ - The path used in a relationship filter must be the path of the relationship target. For same-queue follow-ups from an item/batch/ticket, fetch that item's related unit/site/depot first and use the related unit/site/depot path; do not use the item path as a unit/site/depot path.
17234
+ - Use \`{ relationship: { is: { field: { equal_to: value } } } }\` only for nested field filters. Never put \`id\` or \`path\` inside \`is\`.
17235
+ - Do not write \`{ relationship: { some: ... } }\` unless the generated filter type for that exact relationship says it is a many/collection relationship. For one-record, parent, owner, or many-to-one relationships, use \`path\`, \`id\`, \`is\`, or getter traversal.
17236
+ - Do not pass a full record instance into a filter; if you already fetched a record, filter by its id or path instead.
17237
+ ${domainSections.docs ? `
17238
+ Domain notes:
17239
+ ${domainSections.docs}
17240
+ ` : ""}
17241
+
17242
+ Actions:
17243
+ ${actionIndex}
17244
+ - 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(...)\`.
17245
+ - Actions listed under "Class-level" are class/static methods. Call them on the imported class, e.g. \`await Item.action_name(...)\`.
17246
+ - 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.
17247
+ - Never call a record-level action as \`Class.action_name(...)\`; that method will not exist.
17248
+ - For action inputs, use the exact property names from the generated TypeScript method signature or the input schema shown in the action list. Do not invent synonym fields for required inputs.
17249
+ - Match user verbs to visible action names semantically. If a visible action clearly satisfies the user's requested operation, ground the target record and call that action instead of refusing because the wording differs.
17250
+ - When several visible actions or targets plausibly match the request, search/list the plausible grounded candidates, ask for a grounded choice when more than one remains, confirm if needed, then call only the selected visible action.
17251
+ - If the user asks to find records in a workflow state first, do not pre-filter away plausible records with unrelated secondary flags unless the ontology explicitly documents that relationship; gather the grounded candidates, ask when more than one remains, then confirm/action the selected record when appropriate.
17252
+ - If the user asks for an action that is not visible in the action list, refuse explicitly. Do not answer with only a read-only summary, do not ask for confirmation, and do not attempt hidden, guessed, or similarly named methods.
17253
+ - If the user asks to bypass permissions, skip a normal workflow, use a raw HTTP side channel, or export/send restricted data externally, do not ask for confirmation or missing details. Refuse and explain the allowed workflow boundary.
17254
+ - A restricted or denied referent stays restricted in follow-up turns. If the user later says "that same item", "fine then", or similar after a sensitive/bypass request, do not perform a mutation on that referent unless a visible allowed workflow explicitly authorizes it.
17255
+ - When summarizing records found by a query, include or display stable user-visible identifiers such as number, name, title, label, date, amount, or status. Do not answer only with counts when the user asked what you found.
17256
+
17257
+ [State]
17258
+ ${toolBlock}
17259
+
17260
+ ${sessionBlock}
17261
+
15997
17262
  ${checkpointBlock}
15998
17263
 
15999
- \u2500\u2500\u2500 WORKFLOW SNAPSHOT \u2500\u2500\u2500
16000
17264
  ${workflowBlock}
16001
17265
 
16002
- \u2500\u2500\u2500 RECENT REFERENTS \u2500\u2500\u2500
16003
17266
  ${referentBlock}
16004
17267
 
16005
- \u2500\u2500\u2500 SESSION HEAP \u2500\u2500\u2500
16006
17268
  ${heapBlock}
16007
17269
 
16008
- \u2500\u2500\u2500 AGENT LOOP STATE \u2500\u2500\u2500
16009
17270
  ${loopBlock}
16010
17271
 
16011
- \u2500\u2500\u2500 LOOP PLAYBOOK \u2500\u2500\u2500
16012
- - Continue from the latest structured state. Treat WORKFLOW SNAPSHOT, EXECUTION CHECKPOINT, RECENT REFERENTS, SESSION HEAP, and AGENT LOOP STATE as the working memory for this request.
16013
- - Use CAPABILITY SNAPSHOT to choose the next step, then use DOMAIN REFERENCE for exact signatures and query shapes.
16014
- - Take the minimum next step that directly helps the user. Avoid duplicate work, speculative cleanup, or extra fetching that is not needed yet.
16015
- - Use RECENT REFERENTS to resolve follow-up references across turns, such as "that invoice", "that customer", "those products", or "the other one".
16016
- - Treat user-provided names, numbers, and labels as human references, not exact keys. Resolve them with code: check recent referents/heap first, then query the graph with the broadest supported \`search\` or \`filter\`, then retry with a few normalized/fuzzy/prefix variants when the first pass is empty or ambiguous. Only say a record does not exist after a reasonable lookup across the relevant class.
16017
- - If one strong match exists, use it. If several plausible matches remain, use \`loop.ask_user({ type: 'choice', ... })\` with the grounded candidates instead of guessing.
16018
- - If the request has more than one reasonable interpretation, ask the user to clarify instead of guessing.
16019
- - For comparisons, rankings, selections, or summaries, first identify the rule you are using. If that rule is not clear from the user request and DOMAIN REFERENCE, ask the user before choosing anything.
16020
- - When the ranking, comparison, or selection rule is unclear, the minimum next step is the clarification itself. Do not run a placeholder query for a provisional winner before asking.
16021
- - If a user request matches both a domain type/effect and a loop helper, prioritize the domain type/effect. For example, if DOMAIN REFERENCE contains a \`Task\` class and the user asks to create a task, create the domain task record; do not call \`loop.create_task(...)\` unless you are only tracking your own workflow.
16022
- - Reuse exact \`taskId\`, \`decisionId\`, and \`closureId\` values from AGENT LOOP STATE. Never invent or rewrite them.
16023
- - If the request is ambiguous or clearly multi-step, create 2-4 short user-visible tasks and keep them updated as the workflow advances.
16024
- - Use \`loop.ask_user({ type: 'choice', options: [...] })\` when you have a short, grounded shortlist the user can choose from. Otherwise use \`type: 'input'\`.
16025
- - For an unclear ranking, comparison, or selection rule, prefer \`type: 'choice'\` when you can offer a short grounded list of plausible interpretations from the domain or nearby context.
16026
- - When \`type: 'choice'\` fits, do not ask the same question as plain text with bullets such as "Common options:" or "Choose one of these:".
16027
- - Use \`loop.confirm(...)\` for consequential approval unless the user already clearly instructed you to perform that exact action now.
16028
- - Await \`loop.ask_user(...)\` and \`loop.confirm(...)\`. After the job resumes, continue in the same job whenever the answer is enough to act.
16029
- - Use \`loop.open_decision(...)\` to persist grounded candidates, \`loop.close_decision(...)\` to resolve one, and \`loop.close_loop(...)\` when the workflow is completed, canceled, or blocked.
16030
- - If you ask a new question in the current job, do not also close the loop in that same job.
16031
-
16032
- \u2500\u2500\u2500 LOOP HELPER REFERENCE \u2500\u2500\u2500
16033
- - \`loop.ask_user(...)\`: pause the current job for missing input; use \`type: 'choice'\` only for a short grounded shortlist.
16034
- - \`loop.confirm(...)\`: pause for yes/no approval before a consequential action, then branch on the returned boolean.
16035
- - \`loop.open_decision(...)\`: save explicit candidates that later jobs can revisit; each candidate needs an \`id\`.
16036
- - \`loop.close_decision(...)\`: resolve an open decision with a stored \`selectedId\` and optional rationale.
16037
- - \`loop.create_task(...)\`, \`loop.update_task(...)\`, \`loop.complete_task(...)\`: keep a short resumable task list for the agent's workflow; these are not domain \`Task\` records.
16038
- - \`loop.close_loop(...)\`: record the workflow outcome when it is completed, canceled, or blocked.
17272
+ ${knownFactsBlock}
16039
17273
 
16040
- \u2500\u2500\u2500 CODE RULES \u2500\u2500\u2500
16041
- - Import from \`./sandbox-tools\`.
16042
- - If you use \`heap\`, \`loop\`, \`agent_text_message\`, or \`agent_heap_objects\`, import them explicitly from \`./sandbox-tools\`.
16043
- - Write top-level executable code with \`await\` at top level.
16044
- - The generated job body must be plain runnable JavaScript. Do not use TypeScript-only syntax.
16045
- - Follow the exact classes, methods, and parameter shapes in DOMAIN REFERENCE. Do not invent helpers or unsupported arguments.
16046
- - Use \`ClassName.get({ path })\` only for known graph paths when you want a direct graph fetch.
16047
- - Use \`ClassName.count()\` for totals, \`ClassName.page({ page, perPage, saveAs })\` when you need \`items\` plus \`totalCount\` or \`hasMore\`, \`ClassName.list({ page, perPage, saveAs })\` for one page of records, and \`ClassName.iterate({ perPage, maxItems })\` for large scans.
16048
- - \`perPage\` defaults to \`100\` and is capped at \`100\`.
16049
- - A single \`list(...)\` or \`page(...)\` call never proves there are no more records. For "all", "every", exports, broad scans, or exhaustive searches, use \`iterate(...)\` when available or loop \`page(...)\` until \`hasMore\` is false.
16050
- - Push \`filter\`, \`search\`, and \`sort\` into graph queries instead of fetching a page and processing it locally.
16051
- - A property appearing on a record does not make it valid in \`filter\` or \`sort\`; only use fields and operators that are explicitly exposed in DOMAIN REFERENCE.
16052
- - Choose \`sort.field\` verbatim from the sortable fields listed in DOMAIN REFERENCE. Do not sort by relationship names, related-record collections, counts, totals, or other derived metrics unless they are explicitly listed as sortable.
16053
- - If ordering alone answers the request, use \`sort\` without inventing a \`filter\`.
16054
- - Do not invent proxy metrics, fallback heuristics, or made-up tie-breakers to resolve ambiguity. If the rule is unclear, ask the user with \`loop.ask_user(...)\`.
16055
- - Do not fetch, sort, or show a provisional record just to have something to display while the real ranking or selection rule is still ambiguous.
16056
- - Call instance methods on instances, static methods on classes, and global effects by name.
16057
- - Use \`heap.getEntry(path)\` for remembered heap entries, \`heap.getList(name)\` for remembered lists, and \`heap.getVar(name)\` only for named variables.
16058
- - Use \`heap.setVar(...)\` and \`heap.deleteVar(...)\` only when they help the next step.
16059
- - Prefer \`heap.setVar(...)\` for scalars or one selected instance. Prefer \`ClassName.list({ saveAs })\` for reusable typed lists. Empty arrays are allowed.
16060
- - Only store sandbox instances, typed lists, or scalars in the heap. If a helper returns plain JSON, keep it local or store only the chosen scalar.
16061
- - Use the \`loop\` helpers to manage workflow state: \`ask_user\`, \`confirm\`, \`open_decision\`, \`close_decision\`, \`create_task\`, \`update_task\`, \`complete_task\`, and \`close_loop\`.
16062
- - Use \`type: 'choice'\` only for short grounded options. Use \`type: 'input'\` when the answer should stay open-ended.
16063
- - \`loop.confirm(...)\` is for consequential approval. Do not ask for approval in plain text.
16064
- - After \`await loop.ask_user(...)\` or \`await loop.confirm(...)\`, continue in the same resumed job when the answer is enough to act.
16065
- - Every job that answers the user must emit \`agent_text_message(...)\` and/or \`agent_heap_objects(...)\`.
16066
- - Use \`agent_text_message(...)\` for user-visible text.
16067
- - Use \`agent_heap_objects(...)\` for user-visible records. You may pass sandbox instances directly, or heap-backed \`entryPaths\`, \`listNames\`, and \`variableNames\` when you already have them. Use \`saveAs\` or \`heap.setVar(...)\` when you need a reusable named selection.
16068
- - Do not rely on the final return value for UI output. Do not return ad-hoc \`reply\` / \`show\` payloads instead of explicit agent message calls.
16069
- - Keep the code small and direct. Avoid speculative branches, broad casts, and raw JSON dumps unless the user asked for them.
16070
- - Use \`console.log()\` only for intermediate diagnostics, not for the final user-facing answer.`;
17274
+ [Request]
17275
+ ${input.request?.trim() || "Use the latest user message in the conversation."}`;
16071
17276
  }
16072
17277
 
16073
17278
  // src/agent-evals.ts
@@ -16127,6 +17332,143 @@ function asArray3(value) {
16127
17332
  if (!value) return [];
16128
17333
  return Array.isArray(value) ? value : [value];
16129
17334
  }
17335
+ var GPT_54_TOKEN_PRICING_USD_PER_MILLION = {
17336
+ input: 0.75,
17337
+ cachedInput: 0.075,
17338
+ output: 4.5
17339
+ };
17340
+ function emptyTokenUsage() {
17341
+ return {
17342
+ calls: 0,
17343
+ inputTokens: 0,
17344
+ cachedInputTokens: 0,
17345
+ uncachedInputTokens: 0,
17346
+ outputTokens: 0,
17347
+ totalTokens: 0,
17348
+ inputCostUsd: 0,
17349
+ cachedInputCostUsd: 0,
17350
+ outputCostUsd: 0,
17351
+ totalCostUsd: 0,
17352
+ missingUsageCalls: 0
17353
+ };
17354
+ }
17355
+ function numberField(record, key) {
17356
+ const value = record?.[key];
17357
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
17358
+ }
17359
+ function calculateTokenCost(input) {
17360
+ const inputCostUsd = input.uncachedInputTokens * GPT_54_TOKEN_PRICING_USD_PER_MILLION.input / 1e6;
17361
+ const cachedInputCostUsd = input.cachedInputTokens * GPT_54_TOKEN_PRICING_USD_PER_MILLION.cachedInput / 1e6;
17362
+ const outputCostUsd = input.outputTokens * GPT_54_TOKEN_PRICING_USD_PER_MILLION.output / 1e6;
17363
+ return {
17364
+ inputCostUsd,
17365
+ cachedInputCostUsd,
17366
+ outputCostUsd,
17367
+ totalCostUsd: inputCostUsd + cachedInputCostUsd + outputCostUsd
17368
+ };
17369
+ }
17370
+ function extractTokenUsageFromRaw(raw) {
17371
+ const usage = asRecord5(asRecord5(raw)?.usage);
17372
+ if (!usage) return null;
17373
+ const inputTokens = numberField(usage, "prompt_tokens") || numberField(usage, "input_tokens");
17374
+ const outputTokens = numberField(usage, "completion_tokens") || numberField(usage, "output_tokens");
17375
+ const details = asRecord5(usage.prompt_tokens_details) || asRecord5(usage.input_tokens_details);
17376
+ const cachedInputTokens = Math.min(
17377
+ inputTokens,
17378
+ numberField(details, "cached_tokens") || numberField(details, "cached_input_tokens")
17379
+ );
17380
+ const uncachedInputTokens = Math.max(inputTokens - cachedInputTokens, 0);
17381
+ const totalTokens = numberField(usage, "total_tokens") || inputTokens + outputTokens;
17382
+ const costs = calculateTokenCost({
17383
+ uncachedInputTokens,
17384
+ cachedInputTokens,
17385
+ outputTokens
17386
+ });
17387
+ return {
17388
+ calls: 1,
17389
+ inputTokens,
17390
+ cachedInputTokens,
17391
+ uncachedInputTokens,
17392
+ outputTokens,
17393
+ totalTokens,
17394
+ ...costs,
17395
+ missingUsageCalls: 0
17396
+ };
17397
+ }
17398
+ function addTokenUsage(aggregate, usage) {
17399
+ if (!usage) {
17400
+ return {
17401
+ ...aggregate,
17402
+ missingUsageCalls: aggregate.missingUsageCalls + 1
17403
+ };
17404
+ }
17405
+ const inputTokens = aggregate.inputTokens + usage.inputTokens;
17406
+ const cachedInputTokens = aggregate.cachedInputTokens + usage.cachedInputTokens;
17407
+ const uncachedInputTokens = aggregate.uncachedInputTokens + usage.uncachedInputTokens;
17408
+ const outputTokens = aggregate.outputTokens + usage.outputTokens;
17409
+ const costs = calculateTokenCost({
17410
+ uncachedInputTokens,
17411
+ cachedInputTokens,
17412
+ outputTokens
17413
+ });
17414
+ return {
17415
+ calls: aggregate.calls + usage.calls,
17416
+ inputTokens,
17417
+ cachedInputTokens,
17418
+ uncachedInputTokens,
17419
+ outputTokens,
17420
+ totalTokens: aggregate.totalTokens + usage.totalTokens,
17421
+ ...costs,
17422
+ missingUsageCalls: aggregate.missingUsageCalls + usage.missingUsageCalls
17423
+ };
17424
+ }
17425
+ function aggregateTokenUsage(usages) {
17426
+ return usages.reduce(
17427
+ (aggregate, usage) => addTokenUsage(aggregate, usage),
17428
+ emptyTokenUsage()
17429
+ );
17430
+ }
17431
+ function aggregateConversationTokenUsage(conversation) {
17432
+ return aggregateTokenUsage(
17433
+ conversation.logTurns.flatMap(
17434
+ (turn) => turn.iterations.map((iteration) => iteration.tokenUsage)
17435
+ )
17436
+ );
17437
+ }
17438
+ function tokenUsageForGenerationOutput(generation) {
17439
+ const attempts = generation.generationAttempts?.length ? generation.generationAttempts : [{ raw: generation.raw }];
17440
+ return aggregateTokenUsage(
17441
+ attempts.map((attempt) => extractTokenUsageFromRaw(attempt.raw))
17442
+ );
17443
+ }
17444
+ function formatUsd(value) {
17445
+ return `$${value.toFixed(6)}`;
17446
+ }
17447
+ function formatTokenUsage(usage) {
17448
+ if (!usage || usage.calls === 0 && usage.missingUsageCalls === 0) {
17449
+ return ["- LLM calls with usage data: 0", "- Total cost: $0.000000"];
17450
+ }
17451
+ return [
17452
+ `- LLM calls with usage data: ${usage.calls}`,
17453
+ `- LLM calls missing usage data: ${usage.missingUsageCalls}`,
17454
+ `- Input tokens: ${usage.inputTokens}`,
17455
+ `- Cached input tokens: ${usage.cachedInputTokens}`,
17456
+ `- Uncached input tokens: ${usage.uncachedInputTokens}`,
17457
+ `- Output tokens: ${usage.outputTokens}`,
17458
+ `- Total tokens: ${usage.totalTokens}`,
17459
+ `- Input cost: ${formatUsd(usage.inputCostUsd)}`,
17460
+ `- Cached input cost: ${formatUsd(usage.cachedInputCostUsd)}`,
17461
+ `- Output cost: ${formatUsd(usage.outputCostUsd)}`,
17462
+ `- Total cost: ${formatUsd(usage.totalCostUsd)}`,
17463
+ `- Pricing basis: GPT-5.4 at $${GPT_54_TOKEN_PRICING_USD_PER_MILLION.input}/M input, $${GPT_54_TOKEN_PRICING_USD_PER_MILLION.cachedInput}/M cached input, $${GPT_54_TOKEN_PRICING_USD_PER_MILLION.output}/M output.`
17464
+ ];
17465
+ }
17466
+ function getJobAgentMessages(liveDoc, jobId) {
17467
+ const jobsById = asRecord5(asRecord5(liveDoc.jobs)?.byId);
17468
+ const job = asRecord5(jobsById?.[jobId]);
17469
+ const agentMessages = job?.agentMessages;
17470
+ return Array.isArray(agentMessages) ? agentMessages : [];
17471
+ }
16130
17472
  function buildScenarioSteps(scenario) {
16131
17473
  if (scenario.steps?.length) {
16132
17474
  return scenario.steps;
@@ -16242,19 +17584,99 @@ function extractJsonObject(text) {
16242
17584
  const start = text.indexOf("{");
16243
17585
  const end = text.lastIndexOf("}");
16244
17586
  if (start === -1 || end === -1 || end < start) return null;
17587
+ const candidate = text.slice(start, end + 1);
16245
17588
  try {
16246
- return JSON.parse(text.slice(start, end + 1));
17589
+ return JSON.parse(candidate);
16247
17590
  } catch {
16248
- return null;
17591
+ const fallback = {};
17592
+ for (const fieldName of ["action", "reply", "code"]) {
17593
+ const field = extractJsonStringField(candidate, fieldName);
17594
+ if (field?.complete) {
17595
+ fallback[fieldName] = field.value;
17596
+ }
17597
+ }
17598
+ return Object.keys(fallback).length > 0 ? fallback : null;
16249
17599
  }
16250
17600
  }
17601
+ function extractJsonStringField(source, fieldName) {
17602
+ const keyIndex = source.indexOf(JSON.stringify(fieldName));
17603
+ if (keyIndex === -1) return null;
17604
+ const colonIndex = source.indexOf(":", keyIndex + fieldName.length + 2);
17605
+ if (colonIndex === -1) return null;
17606
+ let cursor = colonIndex + 1;
17607
+ while (cursor < source.length && /\s/.test(source[cursor] || "")) cursor += 1;
17608
+ if (source[cursor] !== '"') return null;
17609
+ cursor += 1;
17610
+ let value = "";
17611
+ while (cursor < source.length) {
17612
+ const char = source[cursor];
17613
+ if (char === '"') return { value, complete: true };
17614
+ if (char !== "\\") {
17615
+ value += char;
17616
+ cursor += 1;
17617
+ continue;
17618
+ }
17619
+ if (cursor + 1 >= source.length) return { value, complete: false };
17620
+ const escaped = source[cursor + 1];
17621
+ if (escaped === "n") value += "\n";
17622
+ else if (escaped === "r") value += "\r";
17623
+ else if (escaped === "t") value += " ";
17624
+ else if (escaped === "b") value += "\b";
17625
+ else if (escaped === "f") value += "\f";
17626
+ else if (escaped === '"' || escaped === "\\" || escaped === "/") {
17627
+ value += escaped;
17628
+ } else if (escaped === "u") {
17629
+ const hex = source.slice(cursor + 2, cursor + 6);
17630
+ if (hex.length < 4 || !/^[0-9a-fA-F]{4}$/.test(hex)) {
17631
+ return { value, complete: false };
17632
+ }
17633
+ value += String.fromCharCode(Number.parseInt(hex, 16));
17634
+ cursor += 6;
17635
+ continue;
17636
+ } else {
17637
+ value += escaped;
17638
+ }
17639
+ cursor += 2;
17640
+ }
17641
+ return { value, complete: false };
17642
+ }
16251
17643
  function modelOutputInstruction() {
16252
17644
  return [
16253
17645
  "Return only a JSON object with this shape:",
16254
17646
  '{ "action": "reply" | "job", "reply": string, "code": string }',
16255
17647
  'Use "action":"reply" only when a plain conversational answer is enough and no live session state should change.',
17648
+ 'Do not use "action":"reply" to promise future tool work; if the user asks to check, find, look up, inspect, update, post, send, approve, schedule, reschedule, calculate, or confirm around a domain action, use "action":"job".',
17649
+ 'Do not use "action":"reply" to say a record is not grounded yet; if the request names or describes a domain record, use "action":"job" and ground it from session state, relationships, searches, or visible read-only actions first.',
17650
+ '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.',
17651
+ "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.",
16256
17652
  'Use "action":"job" when the next step should run code or mutate workflow state.',
16257
17653
  'When action is "job", include runnable code in "code".',
17654
+ "Generated code must not reference prompt-only symbols such as savedData, recentReferences, workflowContext, workflowState, or capabilities. Copy concrete paths/ids from the prompt into strings, fetch records with imports from ./sandbox-tools, or use documented runtime helpers.",
17655
+ "Generated code must import every class and helper it uses from ./sandbox-tools; do not leave undeclared identifiers in the job.",
17656
+ "Generated action calls must use the exact input property names from the visible action schema. Do not invent synonym keys for required inputs.",
17657
+ "If multiple possible targets or a needed human decision blocks a requested operation, put the pause inside code with loop.ask_user(...) or loop.confirm(...); listing candidates or asking only in reply text and returning is incomplete, including when ambiguity is discovered after a query returns several records.",
17658
+ "When a lookup before a mutation returns multiple plausible target records, generated code must ask for a grounded choice; do not mutate results[0], the earliest sorted record, or any other default pick unless the user supplied a unique identifier, ordinal, or selector.",
17659
+ "A bare pronoun such as it, that, or that one is not a unique mutation target when recentReferences, savedData, or the prior visible answer contains multiple compatible records. Do not let one exact recentReference path override that multi-record ambiguity; generated code must ask for a grounded choice before mutating.",
17660
+ "If a follow-up names the same/previous record and also names a related target or evidence type in a condition, use the same/previous record only as the anchor; traverse to the named related type before deciding or mutating.",
17661
+ "For owner/container plus target requests, generated code must ground the owner/container first, then discover the target through relationships, relationship filters, or short target-local search; do not combine owner/container words with target words in one target-class query or require owner/container words to appear in target-local title/summary fields.",
17662
+ "For requested categorical states, generated code should use positive exact filters or explicit local checks; do not use substring negation of another state as a proxy for the requested state.",
17663
+ "For conditional mutations based on a related evidence record, generated code order must be: load the action target or anchor, traverse to the related evidence record, call any visible status/lookup action, then decide whether to mutate. Do not decide, mutate, return, or reject the condition from parent/action-target fields before that evidence step.",
17664
+ "When a condition names an anchored noun phrase whose final noun is an entity type, the final entity type is the evidence record to test; use the earlier words only to ground or traverse to that record.",
17665
+ "Do not treat prior read-only summaries, cached parent fields, action-target fields, or stored related-record fields as fresh evidence for a later conditional mutation when a related evidence object and visible lookup/status action can be reached.",
17666
+ "Generated code must await declared relationship getters before checking arrays, iterating, or reading related-record fields.",
17667
+ "Generated code must call only relationship getters declared on the current record's class; if the target is not direct, walk the declared intermediate getter first instead of inventing a convenience getter.",
17668
+ "Generated code must use declared relationship getters before reading fields from related records; relationship filter fields are not guaranteed to be hydrated nested objects.",
17669
+ "For suitable/available candidate requests, generated code must call a visible availability, matching, or search action when one exists instead of relying only on current relationships or assignments.",
17670
+ "A follow-up to a refused bypass, export, external-send, or restricted-data request must keep the refusal boundary for the same referent; choose a reply refusal instead of running a mutation job.",
17671
+ "Visible answers for grounded named records should include the stored display name or identifier, not only the user's shorthand.",
17672
+ "When the user asks for specific fields, the reply must include every requested field or explicitly say which grounded field is unavailable after fetching the grounded record if saved state is partial.",
17673
+ "When matching action-returned candidates to grounded records, use the output schema's actual identifier fields, including id, path, or fields ending in Id; do not assume returned candidates have _graphPath.",
17674
+ "When resolving a choice answer, accept an unambiguous prefix or substring of an option label; do not fail just because the returned label is abbreviated.",
17675
+ "Do not discard availability/search results solely because a candidate is already assigned or related, unless the user asked for a different candidate.",
17676
+ "After verifying a user-authorized conditional mutation, call the action directly; do not add loop.confirm(...) solely because the mutation is visible to other people, customer-facing, or consequential. Confirm only when the user, policy, action metadata, or unresolved material uncertainty requires it.",
17677
+ "When a job identifies a specific record in its visible answer, display it with agent_heap_objects(...) when the user should see or open it; otherwise save it with await heap.setVar(...) only when it is needed for follow-up resolution.",
17678
+ "heap.setVar(...) accepts scalars, runtime records, sandbox instances, or arrays of those values; do not save plain action/effect result objects. Fetch a created record by its returned id/path before saving or displaying it.",
17679
+ "For requested record fields, read the documented properties from the fetched record before saying a value is unavailable.",
16258
17680
  'When action is "reply", include the user-facing answer in "reply".'
16259
17681
  ].join("\n");
16260
17682
  }
@@ -16263,7 +17685,7 @@ function createOpenAIChatTurnGenerator(options) {
16263
17685
  /\/$/,
16264
17686
  ""
16265
17687
  );
16266
- const model = options.model || "gpt-5-mini";
17688
+ const model = options.model || "gpt-5.4";
16267
17689
  return async (input) => {
16268
17690
  const messages = [
16269
17691
  {
@@ -16277,8 +17699,12 @@ ${modelOutputInstruction()}`
16277
17699
  ];
16278
17700
  const payload = {
16279
17701
  model,
16280
- messages
17702
+ messages,
17703
+ response_format: { type: "json_object" }
16281
17704
  };
17705
+ if (input.onTextDelta) {
17706
+ payload.stream = true;
17707
+ }
16282
17708
  if (typeof options.temperature === "number") {
16283
17709
  payload.temperature = options.temperature;
16284
17710
  }
@@ -16304,19 +17730,63 @@ ${modelOutputInstruction()}`
16304
17730
  `OpenAI chat generation failed: ${response.status} ${errorText}`
16305
17731
  );
16306
17732
  }
16307
- const raw = await response.json();
16308
- const content = asRecord5(
16309
- asRecord5(raw.choices?.[0])?.message
16310
- )?.content;
16311
- const text = typeof content === "string" ? content : Array.isArray(content) ? content.map((part) => asRecord5(part)?.text || "").join("") : "";
17733
+ let raw;
17734
+ let text = "";
17735
+ if (input.onTextDelta && response.body) {
17736
+ const onTextDelta = input.onTextDelta;
17737
+ const reader = response.body.getReader();
17738
+ const decoder = new TextDecoder();
17739
+ let buffer = "";
17740
+ const processStreamLine = async (line) => {
17741
+ const trimmedLine = line.trimEnd();
17742
+ if (!trimmedLine.startsWith("data:")) return;
17743
+ const data = trimmedLine.slice("data:".length).trim();
17744
+ if (!data || data === "[DONE]") return;
17745
+ const event = JSON.parse(data);
17746
+ const delta = asRecord5(
17747
+ asRecord5(event.choices?.[0])?.delta
17748
+ )?.content;
17749
+ const deltaText = typeof delta === "string" ? delta : Array.isArray(delta) ? delta.map((part) => asRecord5(part)?.text || "").join("") : "";
17750
+ if (!deltaText) return;
17751
+ text += deltaText;
17752
+ await onTextDelta(deltaText);
17753
+ };
17754
+ while (true) {
17755
+ const { value, done } = await reader.read();
17756
+ if (done) break;
17757
+ buffer += decoder.decode(value, { stream: true });
17758
+ while (true) {
17759
+ const lineEnd = buffer.indexOf("\n");
17760
+ if (lineEnd === -1) break;
17761
+ const line = buffer.slice(0, lineEnd);
17762
+ buffer = buffer.slice(lineEnd + 1);
17763
+ await processStreamLine(line);
17764
+ }
17765
+ }
17766
+ buffer += decoder.decode();
17767
+ if (buffer.trim()) {
17768
+ await processStreamLine(buffer);
17769
+ }
17770
+ raw = { streamed: true };
17771
+ } else {
17772
+ const json = await response.json();
17773
+ raw = json;
17774
+ const content = asRecord5(
17775
+ asRecord5(json.choices?.[0])?.message
17776
+ )?.content;
17777
+ text = typeof content === "string" ? content : Array.isArray(content) ? content.map((part) => asRecord5(part)?.text || "").join("") : "";
17778
+ }
16312
17779
  const parsed = extractJsonObject(text);
16313
17780
  if (!parsed) {
16314
17781
  if (attempt < 3) {
16315
17782
  await sleep2(300 * attempt);
16316
17783
  continue;
16317
17784
  }
16318
- throw new Error(`Model output was not valid JSON:
16319
- ${text}`);
17785
+ return {
17786
+ reply: text.trim(),
17787
+ code: void 0,
17788
+ raw
17789
+ };
16320
17790
  }
16321
17791
  return {
16322
17792
  reply: typeof parsed.reply === "string" ? parsed.reply : void 0,
@@ -16343,7 +17813,7 @@ async function ensureDir(dir) {
16343
17813
  async function sleep2(ms) {
16344
17814
  await new Promise((resolve) => setTimeout(resolve, ms));
16345
17815
  }
16346
- async function withTimeout(promise, ms, label) {
17816
+ async function withTimeout2(promise, ms, label) {
16347
17817
  let timeoutId;
16348
17818
  try {
16349
17819
  return await Promise.race([
@@ -16362,9 +17832,27 @@ async function withTimeout(promise, ms, label) {
16362
17832
  function getActionSummary(liveDoc, jobId) {
16363
17833
  const jobsById = asRecord5(asRecord5(liveDoc?.jobs)?.byId) || {};
16364
17834
  const job = asRecord5(jobsById[jobId]);
16365
- return Array.isArray(job?.actionSummary) ? job.actionSummary.filter(
17835
+ const summary = Array.isArray(job?.actionSummary) ? job.actionSummary.filter(
16366
17836
  (line) => typeof line === "string"
16367
17837
  ) : [];
17838
+ const trace = Array.isArray(job?.actionTrace) ? job.actionTrace.map((event) => asRecord5(event)).filter((event) => Boolean(event)) : [];
17839
+ const traceLines = trace.map((event) => {
17840
+ const kind = typeof event.kind === "string" ? event.kind : "";
17841
+ const action = typeof event.action === "string" ? event.action : "";
17842
+ const target = typeof event.target === "string" ? event.target : "";
17843
+ if (!action) return "";
17844
+ if (kind === "effect_call") {
17845
+ return `- Called ${target || action}`;
17846
+ }
17847
+ if (kind === "loop_op" && action === "ask_user") {
17848
+ return "- Asked the user for input";
17849
+ }
17850
+ if (kind === "loop_op" && action === "confirm") {
17851
+ return "- Requested confirmation";
17852
+ }
17853
+ return "";
17854
+ }).filter((line) => Boolean(line));
17855
+ return Array.from(/* @__PURE__ */ new Set([...summary, ...traceLines]));
16368
17856
  }
16369
17857
  function normalizeHeapSnapshot2(heap) {
16370
17858
  return {
@@ -16389,21 +17877,30 @@ ${checkpoint.latestJobResult}` : null
16389
17877
  async function waitForJobOutcome(input) {
16390
17878
  const stdout = [];
16391
17879
  const stderr = [];
17880
+ let lastLiveDoc = null;
17881
+ let lastPromptCount = 0;
17882
+ let lastMessageCount = 0;
17883
+ let lastJobSummary = null;
16392
17884
  input.job.on("stdout", (line) => stdout.push(String(line)));
16393
17885
  input.job.on("stderr", (line) => stderr.push(String(line)));
16394
17886
  const startedAt = Date.now();
16395
17887
  while (Date.now() - startedAt < input.timeoutMs) {
16396
17888
  const liveDoc = cloneJson(input.environment.document);
17889
+ lastLiveDoc = liveDoc;
16397
17890
  const prompts = filterPromptsByBoundary(
16398
17891
  liveDoc,
16399
17892
  getOpenPromptsFromDoc(liveDoc),
16400
17893
  input.boundaryTimestamp
16401
17894
  );
17895
+ lastPromptCount = prompts.length;
17896
+ const messages = asArray3(asRecord5(liveDoc.conversation)?.messages);
17897
+ lastMessageCount = messages.length;
17898
+ lastJobSummary = asRecord5(asRecord5(liveDoc.jobs)?.byId)?.[input.job.id] || null;
16402
17899
  if (prompts.length > 0) {
16403
17900
  return { kind: "prompt", prompts, liveDoc, stdout, stderr };
16404
17901
  }
16405
17902
  try {
16406
- const result = await withTimeout(
17903
+ const result = await withTimeout2(
16407
17904
  input.job.result,
16408
17905
  input.pollIntervalMs,
16409
17906
  `job ${input.job.id} tick`
@@ -16414,37 +17911,70 @@ async function waitForJobOutcome(input) {
16414
17911
  if (!/timed out after/.test(message)) throw error;
16415
17912
  }
16416
17913
  }
16417
- throw new Error(`Job ${input.job.id} timed out after ${input.timeoutMs}ms`);
17914
+ const diagnostics = {
17915
+ elapsedMs: Date.now() - startedAt,
17916
+ promptCount: lastPromptCount,
17917
+ messageCount: lastMessageCount,
17918
+ stdoutTail: stdout.slice(-5),
17919
+ stderrTail: stderr.slice(-5),
17920
+ job: lastJobSummary,
17921
+ hasLiveDoc: Boolean(lastLiveDoc)
17922
+ };
17923
+ throw new Error(
17924
+ `Job ${input.job.id} timed out after ${input.timeoutMs}ms. Diagnostics: ${JSON.stringify(diagnostics)}`
17925
+ );
16418
17926
  }
16419
17927
  async function generateTurnWithRepair(generator, input) {
16420
- let output = await generator(input);
16421
- let request = input.request;
16422
- let attempt = input.attempt;
16423
- for (let repairRound = 0; repairRound < 3; repairRound += 1) {
16424
- if (!output.code) return output;
16425
- const issues = reviewGeneratedJobCode(output.code);
16426
- if (issues.length === 0) return output;
16427
- request = [
16428
- request,
16429
- "",
16430
- "Regenerate the job code and fix these issues:",
16431
- ...issues.map((issue) => `- ${issue.message}`),
16432
- "Return the full corrected job code."
16433
- ].join("\n");
16434
- attempt += 1;
16435
- output = await generator({
16436
- ...input,
16437
- attempt,
16438
- request,
16439
- repairIssues: issues
16440
- });
16441
- }
16442
- return output;
17928
+ const output = await generator(input);
17929
+ const generationAttempts = [
17930
+ {
17931
+ attempt: input.attempt,
17932
+ request: input.request,
17933
+ repairIssues: input.repairIssues,
17934
+ reply: output.reply,
17935
+ code: output.code,
17936
+ raw: output.raw
17937
+ }
17938
+ ];
17939
+ return { ...output, generationAttempts };
16443
17940
  }
16444
17941
  async function writeJson(filePath, value) {
16445
17942
  await promises.writeFile(filePath, `${JSON.stringify(value, null, 2)}
16446
17943
  `);
16447
17944
  }
17945
+ function describeScenarioBehavior(result) {
17946
+ if (result.scenario.description?.trim()) {
17947
+ return result.scenario.description.trim();
17948
+ }
17949
+ const steps = result.steps?.length ? result.steps : buildScenarioSteps(result.scenario).map((step, index) => ({
17950
+ id: step.id || `step-${index + 1}`,
17951
+ request: step.request
17952
+ }));
17953
+ const stepSummary = steps.map((step, index) => {
17954
+ const request = step.request.replace(/\s+/g, " ").trim();
17955
+ return `${index + 1}. ${step.id}: ${request}`;
17956
+ }).join(" ");
17957
+ return [
17958
+ `This report tests scenario \`${result.scenario.id}\` across ${steps.length} user turn${steps.length === 1 ? "" : "s"}.`,
17959
+ "It verifies that the agent grounds the natural-language request in the current ontology/session context, generates the expected job or refusal, and that the runtime executes or blocks the resulting behavior correctly.",
17960
+ stepSummary
17961
+ ].filter(Boolean).join(" ");
17962
+ }
17963
+ function describeJobSource(result) {
17964
+ if (result.scenario.jobSource === "hardcoded") {
17965
+ return "Hardcoded deterministic job code supplied by the test.";
17966
+ }
17967
+ if (result.scenario.jobSource === "mixed") {
17968
+ return "Mixed: LLM-generated agent jobs plus hardcoded setup/inspection jobs supplied by the test.";
17969
+ }
17970
+ const hasGeneratedCode = Boolean(
17971
+ result.finalCode || result.steps?.some((step) => step.finalCode)
17972
+ );
17973
+ if (hasGeneratedCode) {
17974
+ return "LLM-generated agent job code. Setup, direct inspections, and assertions are hardcoded by the test harness.";
17975
+ }
17976
+ return "LLM-generated agent response. Setup, direct inspections, and assertions are hardcoded by the test harness.";
17977
+ }
16448
17978
  function buildResultReport(result) {
16449
17979
  const stepSection = result.steps?.length ? [
16450
17980
  "## Steps",
@@ -16461,6 +17991,15 @@ function buildResultReport(result) {
16461
17991
  const lines = [
16462
17992
  `# Scenario Report: ${result.scenario.id}`,
16463
17993
  "",
17994
+ "## Behavior Under Test",
17995
+ describeScenarioBehavior(result),
17996
+ "",
17997
+ "## Job Source",
17998
+ describeJobSource(result),
17999
+ "",
18000
+ "## Token Usage And Cost",
18001
+ ...formatTokenUsage(result.tokenUsage),
18002
+ "",
16464
18003
  "## Request",
16465
18004
  result.scenario.request || result.steps?.[0]?.request || "_No single request_",
16466
18005
  "",
@@ -16487,9 +18026,21 @@ function buildResultReport(result) {
16487
18026
  `;
16488
18027
  }
16489
18028
  function buildSuiteIndex(results) {
18029
+ const totalUsage = aggregateTokenUsage(
18030
+ results.map((result) => result.tokenUsage)
18031
+ );
16490
18032
  const lines = [
16491
18033
  "# Agent Eval Report Index",
16492
18034
  "",
18035
+ "## Token Usage And Cost",
18036
+ ...formatTokenUsage(totalUsage),
18037
+ "",
18038
+ "## Session Logs",
18039
+ "",
18040
+ "- [Readable chronological logs](./logs/README.md)",
18041
+ "",
18042
+ "## Scenario Reports",
18043
+ "",
16493
18044
  ...results.map(
16494
18045
  (result) => `- [${result.scenario.id}](./${result.scenario.id}/REPORT.md) - ${result.status}`
16495
18046
  )
@@ -16497,6 +18048,191 @@ function buildSuiteIndex(results) {
16497
18048
  return `${lines.join("\n")}
16498
18049
  `;
16499
18050
  }
18051
+ function buildLogsIndex(results) {
18052
+ const totalUsage = aggregateTokenUsage(
18053
+ results.map((result) => result.tokenUsage)
18054
+ );
18055
+ const lines = [
18056
+ "# Agent Eval Session Logs",
18057
+ "",
18058
+ "Each file is a chronological session report with user requests, agent responses, generated code, runtime actions/results, and system prompts at the end.",
18059
+ "",
18060
+ "## Token Usage And Cost",
18061
+ ...formatTokenUsage(totalUsage),
18062
+ "",
18063
+ ...results.map((result) => {
18064
+ const logName = `${slugify(result.scenario.id)}.md`;
18065
+ return `- [${result.scenario.id}](./${logName}) - ${result.status} - ${formatUsd(result.tokenUsage?.totalCostUsd || 0)}`;
18066
+ })
18067
+ ];
18068
+ return `${lines.join("\n")}
18069
+ `;
18070
+ }
18071
+ function fenced(value, language = "") {
18072
+ const fence = value.includes("```") ? "````" : "```";
18073
+ return `${fence}${language}
18074
+ ${value}
18075
+ ${fence}`;
18076
+ }
18077
+ function jsonBlock(value) {
18078
+ return fenced(JSON.stringify(value, null, 2), "json");
18079
+ }
18080
+ function buildSessionLogReport(input) {
18081
+ const { conversation, result, error } = input;
18082
+ const systemPrompts = conversation.logTurns.flatMap(
18083
+ (turn) => turn.iterations.map((iteration) => ({
18084
+ turn,
18085
+ iteration
18086
+ }))
18087
+ );
18088
+ const lines = [
18089
+ `# Session Log: ${conversation.label}`,
18090
+ "",
18091
+ "## Behavior Under Test",
18092
+ result ? describeScenarioBehavior(result) : "This session log captures the chronological agent/runtime behavior for a scenario that did not complete a structured result.",
18093
+ "",
18094
+ "## Job Source",
18095
+ result ? describeJobSource(result) : "LLM-generated agent jobs when generation completed; setup and harness assertions are hardcoded by the test harness.",
18096
+ "",
18097
+ "## Token Usage And Cost",
18098
+ ...formatTokenUsage(
18099
+ result?.tokenUsage || aggregateConversationTokenUsage(conversation)
18100
+ ),
18101
+ "",
18102
+ "## Metadata",
18103
+ `- Session id: \`${conversation.environment.sessionId}\``,
18104
+ `- Environment id: \`${conversation.environment.environmentId}\``,
18105
+ `- Sandbox id: \`${conversation.environment.sandboxId}\``,
18106
+ `- Status: ${result?.status || (error ? "failed" : "unknown")}`,
18107
+ ...result?.error || error ? [`- Error: ${result?.error || error}`] : [],
18108
+ "",
18109
+ "## Conversation"
18110
+ ];
18111
+ for (const turn of conversation.logTurns) {
18112
+ lines.push("", `### Turn ${turn.turnNumber}: ${turn.turnId}`, "");
18113
+ lines.push("**User**", "");
18114
+ lines.push(turn.request, "");
18115
+ for (const iteration of turn.iterations) {
18116
+ lines.push(`#### Agent Generation ${iteration.iteration}`, "");
18117
+ lines.push(
18118
+ "**Token Usage And Cost**",
18119
+ "",
18120
+ ...formatTokenUsage(iteration.tokenUsage),
18121
+ ""
18122
+ );
18123
+ if ((iteration.generationAttempts?.length || 0) > 1) {
18124
+ lines.push("**Generation Attempts**", "");
18125
+ for (const attempt of iteration.generationAttempts || []) {
18126
+ lines.push(`Attempt ${attempt.attempt}`, "");
18127
+ if (attempt.repairIssues?.length) {
18128
+ lines.push("Repair issues:", "");
18129
+ for (const issue of attempt.repairIssues) {
18130
+ lines.push(`- ${issue.code}: ${issue.message}`);
18131
+ }
18132
+ lines.push("");
18133
+ }
18134
+ lines.push("Request", "", fenced(attempt.request, "text"), "");
18135
+ if (attempt.reply?.trim()) {
18136
+ lines.push("Draft reply", "", attempt.reply.trim(), "");
18137
+ }
18138
+ if (attempt.code?.trim()) {
18139
+ lines.push("Code", "", fenced(attempt.code.trim(), "ts"), "");
18140
+ }
18141
+ }
18142
+ }
18143
+ if (iteration.generationReply?.trim()) {
18144
+ lines.push("**Draft Reply**", "", iteration.generationReply.trim(), "");
18145
+ }
18146
+ if (iteration.generatedCode?.trim()) {
18147
+ lines.push(
18148
+ "**Generated Code**",
18149
+ "",
18150
+ fenced(iteration.generatedCode.trim(), "ts"),
18151
+ ""
18152
+ );
18153
+ } else {
18154
+ lines.push("**Generated Code**", "", "_No code generated._", "");
18155
+ }
18156
+ if (iteration.promptInteractions?.length) {
18157
+ lines.push("**Structured User Input**", "");
18158
+ for (const interaction of iteration.promptInteractions) {
18159
+ lines.push(
18160
+ `- ${interaction.type}: ${interaction.message || interaction.title} -> \`${JSON.stringify(interaction.answer)}\``
18161
+ );
18162
+ }
18163
+ lines.push("");
18164
+ }
18165
+ if (iteration.actionSummary?.length) {
18166
+ lines.push("**Runtime Actions**", "");
18167
+ for (const action of iteration.actionSummary) lines.push(`- ${action}`);
18168
+ lines.push("");
18169
+ }
18170
+ if (iteration.responseText?.trim()) {
18171
+ lines.push("**Agent Response**", "", iteration.responseText.trim(), "");
18172
+ }
18173
+ if (iteration.continuation) {
18174
+ lines.push(
18175
+ "**Harness Continuation**",
18176
+ "",
18177
+ jsonBlock(iteration.continuation),
18178
+ ""
18179
+ );
18180
+ }
18181
+ if (iteration.result !== void 0) {
18182
+ lines.push("**Runtime Result**", "", jsonBlock(iteration.result), "");
18183
+ }
18184
+ if (iteration.error) {
18185
+ lines.push("**Error**", "", iteration.error, "");
18186
+ }
18187
+ }
18188
+ if (turn.completed) {
18189
+ lines.push(
18190
+ "**Turn Final Response**",
18191
+ "",
18192
+ turn.completed.responseText || "_No reply_",
18193
+ ""
18194
+ );
18195
+ if (turn.completed.actionSummary.length) {
18196
+ lines.push("**Turn Final Actions**", "");
18197
+ for (const action of turn.completed.actionSummary)
18198
+ lines.push(`- ${action}`);
18199
+ lines.push("");
18200
+ }
18201
+ }
18202
+ if (turn.error) {
18203
+ lines.push("**Turn Error**", "", turn.error, "");
18204
+ }
18205
+ }
18206
+ lines.push("", "## System Prompts", "");
18207
+ if (!systemPrompts.length) {
18208
+ lines.push("_No system prompts captured._", "");
18209
+ } else {
18210
+ for (const { turn, iteration } of systemPrompts) {
18211
+ lines.push(
18212
+ `### Turn ${turn.turnNumber}, Generation ${iteration.iteration}`,
18213
+ "",
18214
+ fenced(iteration.systemPrompt, "text"),
18215
+ ""
18216
+ );
18217
+ }
18218
+ }
18219
+ return `${lines.join("\n")}
18220
+ `;
18221
+ }
18222
+ async function writeSessionLogReport(input) {
18223
+ const logsDir = path__default.default.join(input.artifactDir, "logs");
18224
+ await ensureDir(logsDir);
18225
+ await promises.writeFile(
18226
+ path__default.default.join(logsDir, `${slugify(input.conversation.label)}.md`),
18227
+ buildSessionLogReport(input)
18228
+ );
18229
+ }
18230
+ function findTurnLog(conversation, turnDir) {
18231
+ return conversation.logTurns.find((turn) => turn.turnDir === turnDir);
18232
+ }
18233
+ function latestIterationLog(turn) {
18234
+ return turn?.iterations[turn.iterations.length - 1];
18235
+ }
16500
18236
  async function applySetup(setup, context) {
16501
18237
  if (!setup) return;
16502
18238
  if (setup.manifest) {
@@ -16581,7 +18317,7 @@ async function runAgentEvalSuite(options) {
16581
18317
  inspect: async (code) => {
16582
18318
  const session = conversation.environment;
16583
18319
  const job = await session.submitJob(code);
16584
- return withTimeout(
18320
+ return withTimeout2(
16585
18321
  job.result,
16586
18322
  9e4,
16587
18323
  `inspection job ${job.id}`
@@ -16656,6 +18392,7 @@ async function runAgentEvalSuite(options) {
16656
18392
  actionSummary: lastStep.actionSummary,
16657
18393
  promptInteractions: lastStep.promptInteractions,
16658
18394
  verification: lastStep.inspectionResults.length <= 1 ? lastStep.inspectionResults[0] ?? null : lastStep.inspectionResults,
18395
+ tokenUsage: aggregateConversationTokenUsage(conversation),
16659
18396
  steps: stepResults,
16660
18397
  turnDir: conversation.artifactDir
16661
18398
  };
@@ -16671,9 +18408,22 @@ async function runAgentEvalSuite(options) {
16671
18408
  path__default.default.join(conversation.artifactDir, "REPORT.md"),
16672
18409
  buildResultReport(result)
16673
18410
  );
18411
+ await writeSessionLogReport({
18412
+ artifactDir: options.harness.artifactDir,
18413
+ conversation,
18414
+ result
18415
+ });
16674
18416
  finalResult = result;
16675
18417
  } catch (error) {
16676
18418
  const failureMessage = error instanceof Error ? error.message : String(error);
18419
+ const failedTurn = conversation.logTurns[conversation.logTurns.length - 1];
18420
+ if (failedTurn && !failedTurn.completed) {
18421
+ failedTurn.error = failureMessage;
18422
+ const failedIteration = latestIterationLog(failedTurn);
18423
+ if (failedIteration && !failedIteration.responseText) {
18424
+ failedIteration.error = failureMessage;
18425
+ }
18426
+ }
16677
18427
  if (attempt < 2 && isTransientEvalError(error)) {
16678
18428
  await options.harness.closeConversation(conversation);
16679
18429
  continue;
@@ -16686,6 +18436,7 @@ async function runAgentEvalSuite(options) {
16686
18436
  actionSummary: [],
16687
18437
  promptInteractions: [],
16688
18438
  verification: null,
18439
+ tokenUsage: aggregateConversationTokenUsage(conversation),
16689
18440
  turnDir: path__default.default.join(options.harness.artifactDir, scenario.id),
16690
18441
  error: failureMessage
16691
18442
  };
@@ -16696,6 +18447,12 @@ async function runAgentEvalSuite(options) {
16696
18447
  path__default.default.join(failed.turnDir, "REPORT.md"),
16697
18448
  buildResultReport(failed)
16698
18449
  );
18450
+ await writeSessionLogReport({
18451
+ artifactDir: options.harness.artifactDir,
18452
+ conversation,
18453
+ result: failed,
18454
+ error: failureMessage
18455
+ });
16699
18456
  finalResult = failed;
16700
18457
  } finally {
16701
18458
  await options.harness.closeConversation(conversation);
@@ -16710,6 +18467,7 @@ async function runAgentEvalSuite(options) {
16710
18467
  actionSummary: [],
16711
18468
  promptInteractions: [],
16712
18469
  verification: null,
18470
+ tokenUsage: emptyTokenUsage(),
16713
18471
  turnDir: path__default.default.join(options.harness.artifactDir, scenario.id),
16714
18472
  error: "Scenario ended without a result."
16715
18473
  };
@@ -16724,6 +18482,11 @@ async function runAgentEvalSuite(options) {
16724
18482
  path__default.default.join(options.harness.artifactDir, "REPORT_INDEX.md"),
16725
18483
  buildSuiteIndex(results)
16726
18484
  );
18485
+ await ensureDir(path__default.default.join(options.harness.artifactDir, "logs"));
18486
+ await promises.writeFile(
18487
+ path__default.default.join(options.harness.artifactDir, "logs", "README.md"),
18488
+ buildLogsIndex(results)
18489
+ );
16727
18490
  return { artifactDir: options.harness.artifactDir, results };
16728
18491
  }
16729
18492
  function createAgentEvalHarness(options) {
@@ -16756,6 +18519,10 @@ function createAgentEvalHarness(options) {
16756
18519
  promptEvents.push({ prompt, receivedAt: Date.now() });
16757
18520
  };
16758
18521
  environment.on("prompt", promptHandler);
18522
+ for (let attempt = 0; attempt < 12; attempt += 1) {
18523
+ if (environment.getEffects().length > 0) break;
18524
+ await sleep2(250);
18525
+ }
16759
18526
  await ensureDir(path__default.default.join(artifactDir, slugify(label)));
16760
18527
  return {
16761
18528
  label,
@@ -16763,7 +18530,8 @@ function createAgentEvalHarness(options) {
16763
18530
  history: [],
16764
18531
  promptEvents,
16765
18532
  artifactDir: path__default.default.join(artifactDir, slugify(label)),
16766
- turnCount: 0
18533
+ turnCount: 0,
18534
+ logTurns: []
16767
18535
  };
16768
18536
  }
16769
18537
  async function closeConversation(conversation) {
@@ -16777,7 +18545,7 @@ function createAgentEvalHarness(options) {
16777
18545
  }
16778
18546
  async function runCheckJob(code, session) {
16779
18547
  const job = await session.submitJob(code);
16780
- return withTimeout(job.result, jobTimeoutMs, `check job ${job.id}`);
18548
+ return withTimeout2(job.result, jobTimeoutMs, `check job ${job.id}`);
16781
18549
  }
16782
18550
  function buildCheckContext(conversation, completed, turnDir) {
16783
18551
  const liveDoc = cloneJson(conversation.environment.document);
@@ -16801,14 +18569,26 @@ function createAgentEvalHarness(options) {
16801
18569
  };
16802
18570
  }
16803
18571
  async function runInspection(conversation, inspection, completed, turnDir) {
16804
- const result = await runCheckJob(inspection.code, conversation.environment);
16805
- const text = JSON.stringify(result, null, 2);
16806
- assertMatches(
16807
- `Verification for ${conversation.label}`,
16808
- text,
16809
- inspection.includes,
16810
- inspection.excludes
16811
- );
18572
+ let result = null;
18573
+ let lastError = null;
18574
+ for (let attempt = 0; attempt < 10; attempt += 1) {
18575
+ result = await runCheckJob(inspection.code, conversation.environment);
18576
+ const text = JSON.stringify(result, null, 2);
18577
+ try {
18578
+ assertMatches(
18579
+ `Verification for ${conversation.label}`,
18580
+ text,
18581
+ inspection.includes,
18582
+ inspection.excludes
18583
+ );
18584
+ lastError = null;
18585
+ break;
18586
+ } catch (error) {
18587
+ lastError = error;
18588
+ await sleep2(250);
18589
+ }
18590
+ }
18591
+ if (lastError) throw lastError;
16812
18592
  if (inspection.check) {
16813
18593
  await inspection.check({
16814
18594
  ...buildCheckContext(conversation, completed, turnDir),
@@ -16834,6 +18614,11 @@ function createAgentEvalHarness(options) {
16834
18614
  message: prompt.message,
16835
18615
  answer
16836
18616
  });
18617
+ const turnLog = findTurnLog(pending.conversation, pending.turnDir);
18618
+ const iterationLog = latestIterationLog(turnLog);
18619
+ if (iterationLog) {
18620
+ iterationLog.promptInteractions = pending.promptInteractions;
18621
+ }
16837
18622
  const resumed = await waitForJobOutcome({
16838
18623
  environment: pending.conversation.environment,
16839
18624
  job: pending.job,
@@ -16857,6 +18642,7 @@ function createAgentEvalHarness(options) {
16857
18642
  jobId: pending.job.id,
16858
18643
  result: resumed.result,
16859
18644
  stdout: [...pending.stdout, ...resumed.stdout],
18645
+ agentMessages: getJobAgentMessages(liveDoc, pending.job.id),
16860
18646
  sessionHeap: normalizeHeapSnapshot2(asRecord5(liveDoc?.heap))
16861
18647
  });
16862
18648
  const responseText = presentation.responseText || pending.finalReply || "Done.";
@@ -16874,6 +18660,23 @@ function createAgentEvalHarness(options) {
16874
18660
  promptInteractions: pending.promptInteractions,
16875
18661
  result: resumed.result
16876
18662
  });
18663
+ const actionSummary = getActionSummary(liveDoc, pending.job.id);
18664
+ if (iterationLog) {
18665
+ iterationLog.responseText = responseText;
18666
+ iterationLog.terminalKind = getCurrentClosureId(liveDoc) ? "closure" : "reply";
18667
+ iterationLog.actionSummary = actionSummary;
18668
+ iterationLog.promptInteractions = pending.promptInteractions;
18669
+ iterationLog.result = resumed.result;
18670
+ }
18671
+ if (turnLog) {
18672
+ turnLog.completed = {
18673
+ responseText,
18674
+ terminalKind: getCurrentClosureId(liveDoc) ? "closure" : "reply",
18675
+ actionSummary,
18676
+ promptInteractions: pending.promptInteractions,
18677
+ result: resumed.result
18678
+ };
18679
+ }
16877
18680
  return {
16878
18681
  conversation: pending.conversation,
16879
18682
  request: pending.request,
@@ -16881,7 +18684,7 @@ function createAgentEvalHarness(options) {
16881
18684
  responseText,
16882
18685
  terminalKind: getCurrentClosureId(liveDoc) ? "closure" : "reply",
16883
18686
  finalCode: pending.finalCode,
16884
- actionSummary: getActionSummary(liveDoc, pending.job.id),
18687
+ actionSummary,
16885
18688
  promptInteractions: pending.promptInteractions,
16886
18689
  verification: null,
16887
18690
  result: resumed.result
@@ -16893,6 +18696,14 @@ function createAgentEvalHarness(options) {
16893
18696
  const turnId = `turn-${String(turnNumber).padStart(2, "0")}-${slugify(input.request.slice(0, 48))}`;
16894
18697
  const turnDir = path__default.default.join(conversation.artifactDir, turnId);
16895
18698
  await ensureDir(turnDir);
18699
+ const turnLog = {
18700
+ turnNumber,
18701
+ turnId,
18702
+ request: input.request,
18703
+ turnDir,
18704
+ iterations: []
18705
+ };
18706
+ conversation.logTurns.push(turnLog);
16896
18707
  if (input.prepareRecords?.length) {
16897
18708
  await conversation.environment.recordObjects(input.prepareRecords);
16898
18709
  }
@@ -16931,6 +18742,24 @@ function createAgentEvalHarness(options) {
16931
18742
  const workflowFocus = projectWorkflowFocus(liveDoc, pendingPrompts, {
16932
18743
  boundaryTimestamp
16933
18744
  });
18745
+ const referentFocus = projectConversationReferentFocus(liveDoc);
18746
+ const heapFocus = {
18747
+ variableNames: [
18748
+ ...workflowFocus.variableNames,
18749
+ ...referentFocus.variableNames
18750
+ ],
18751
+ listNames: [...workflowFocus.listNames, ...referentFocus.listNames],
18752
+ entryPaths: [...workflowFocus.entryPaths, ...referentFocus.entryPaths]
18753
+ };
18754
+ const tools = conversation.environment.getEffects().map((tool) => ({
18755
+ name: tool.name,
18756
+ description: tool.description,
18757
+ className: tool.className,
18758
+ static: tool.static,
18759
+ ready: tool.ready,
18760
+ inputSchema: tool.inputSchema,
18761
+ outputSchema: tool.outputSchema
18762
+ }));
16934
18763
  const systemPrompt = buildGranularAgentSystemPrompt({
16935
18764
  domainDocumentation: await conversation.environment.getDomainDocumentation(),
16936
18765
  sessionContext: {
@@ -16938,37 +18767,44 @@ function createAgentEvalHarness(options) {
16938
18767
  environmentId: conversation.environment.environmentId,
16939
18768
  domainRevision: conversation.environment.domainRevision
16940
18769
  },
16941
- heapSummary: projectHeapSummary(liveDoc, {
16942
- focus: workflowFocus
18770
+ heapSummary: projectHeapSummary(asRecord5(liveDoc?.heap), {
18771
+ focus: heapFocus
16943
18772
  }),
18773
+ referentSummary: projectConversationReferentSummary(liveDoc),
16944
18774
  loopSummary: projectLoopSummary(liveDoc, pendingPrompts, {
16945
18775
  boundaryTimestamp
16946
18776
  }),
16947
18777
  workflowSummary: projectWorkflowSummary(liveDoc, pendingPrompts, {
16948
18778
  boundaryTimestamp
16949
18779
  }),
16950
- tools: conversation.environment.getEffects().map((tool) => ({
16951
- name: tool.name,
16952
- description: tool.description,
16953
- className: tool.className,
16954
- static: tool.static,
16955
- ready: tool.ready
16956
- })),
18780
+ tools,
16957
18781
  checkpoint: latestCheckpoint
16958
18782
  });
16959
18783
  const request = iteration === 0 ? input.request : buildContinuationInstruction(
16960
18784
  buildContinuationPreview(latestCheckpoint, noProgressCount)
16961
18785
  );
16962
- const generation = await withTimeout(
18786
+ const generation = await withTimeout2(
16963
18787
  generateTurnWithRepair(options.generator, {
16964
18788
  systemPrompt,
16965
18789
  history: buildHistory(conversation.history),
16966
18790
  request,
16967
- attempt: 1
18791
+ attempt: 1,
18792
+ tools
16968
18793
  }),
16969
18794
  chatTimeoutMs,
16970
18795
  `chat generation for ${conversation.label} iteration ${iteration + 1}`
16971
18796
  );
18797
+ const iterationLog = {
18798
+ iteration: iteration + 1,
18799
+ request,
18800
+ systemPrompt,
18801
+ generationReply: generation.reply,
18802
+ generatedCode: generation.code,
18803
+ rawGeneration: generation.raw,
18804
+ generationAttempts: generation.generationAttempts,
18805
+ tokenUsage: tokenUsageForGenerationOutput(generation)
18806
+ };
18807
+ turnLog.iterations.push(iterationLog);
16972
18808
  await writeJson(
16973
18809
  path__default.default.join(turnDir, `iteration-${iteration + 1}-generation.json`),
16974
18810
  generation
@@ -16995,11 +18831,39 @@ function createAgentEvalHarness(options) {
16995
18831
  turnDir
16996
18832
  );
16997
18833
  }
18834
+ iterationLog.responseText = responseText2;
18835
+ iterationLog.terminalKind = "reply";
18836
+ iterationLog.actionSummary = [];
18837
+ iterationLog.promptInteractions = [];
18838
+ iterationLog.result = completed.result;
18839
+ turnLog.completed = {
18840
+ responseText: responseText2,
18841
+ terminalKind: "reply",
18842
+ actionSummary: [],
18843
+ promptInteractions: [],
18844
+ result: completed.result
18845
+ };
16998
18846
  await writeJson(path__default.default.join(turnDir, "result.json"), completed);
16999
18847
  return completed;
17000
18848
  }
17001
18849
  const session = conversation.environment;
17002
- const job = await session.submitJob(generation.code);
18850
+ const job = await session.submitJob(generation.code, {
18851
+ agent: {
18852
+ userRequest: input.request,
18853
+ generationRequest: request,
18854
+ systemPrompt,
18855
+ history: buildHistory(conversation.history),
18856
+ scenarioLabel: conversation.label,
18857
+ turnId,
18858
+ iteration: iteration + 1,
18859
+ tools,
18860
+ generationReply: generation.reply,
18861
+ rawGeneration: generation.raw,
18862
+ repairIssues: generation.generationAttempts?.flatMap(
18863
+ (attempt) => attempt.repairIssues || []
18864
+ )
18865
+ }
18866
+ });
17003
18867
  const outcome = await waitForJobOutcome({
17004
18868
  environment: conversation.environment,
17005
18869
  job,
@@ -17055,6 +18919,13 @@ function createAgentEvalHarness(options) {
17055
18919
  turnDir
17056
18920
  );
17057
18921
  }
18922
+ turnLog.completed = {
18923
+ responseText: resumed.responseText,
18924
+ terminalKind: resumed.terminalKind,
18925
+ actionSummary: resumed.actionSummary,
18926
+ promptInteractions: resumed.promptInteractions,
18927
+ result: resumed.result
18928
+ };
17058
18929
  return resumed;
17059
18930
  }
17060
18931
  }
@@ -17072,6 +18943,7 @@ function createAgentEvalHarness(options) {
17072
18943
  jobId: job.id,
17073
18944
  result: outcome.result,
17074
18945
  stdout: outcome.stdout,
18946
+ agentMessages: getJobAgentMessages(settledLiveDoc, job.id),
17075
18947
  sessionHeap
17076
18948
  });
17077
18949
  const responseText = presentation.responseText || generation.reply?.trim() || "Done.";
@@ -17125,6 +18997,12 @@ function createAgentEvalHarness(options) {
17125
18997
  result: outcome.result
17126
18998
  }
17127
18999
  );
19000
+ iterationLog.responseText = responseText;
19001
+ iterationLog.terminalKind = getCurrentClosureId(settledLiveDoc) ? "closure" : "reply";
19002
+ iterationLog.actionSummary = latestCheckpoint.latestActionSummary || [];
19003
+ iterationLog.promptInteractions = [];
19004
+ iterationLog.continuation = continuation;
19005
+ iterationLog.result = outcome.result;
17128
19006
  if (!continuation.shouldContinue) {
17129
19007
  const completed = {
17130
19008
  conversation,
@@ -17146,6 +19024,13 @@ function createAgentEvalHarness(options) {
17146
19024
  turnDir
17147
19025
  );
17148
19026
  }
19027
+ turnLog.completed = {
19028
+ responseText,
19029
+ terminalKind: completed.terminalKind,
19030
+ actionSummary: completed.actionSummary,
19031
+ promptInteractions: [],
19032
+ result: outcome.result
19033
+ };
17149
19034
  await writeJson(path__default.default.join(turnDir, "result.json"), completed);
17150
19035
  return completed;
17151
19036
  }