@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.
package/dist/index.mjs CHANGED
@@ -3929,11 +3929,22 @@ var TOKEN_REFRESH_LEEWAY_MS = 2 * 60 * 1e3;
3929
3929
  var TOKEN_REFRESH_RETRY_MS = 30 * 1e3;
3930
3930
  var MAX_TIMER_DELAY_MS = 2147483647;
3931
3931
  var DEBUG_WS = process.env.GRANULAR_DEBUG_WS === "1";
3932
+ var DEFAULT_RPC_TIMEOUT_MS = 3e4;
3933
+ var DOMAIN_PACKAGE_RPC_TIMEOUT_MS = 12e4;
3932
3934
  function debugWs(...args) {
3933
3935
  if (DEBUG_WS) {
3934
3936
  console.log(...args);
3935
3937
  }
3936
3938
  }
3939
+ function rpcTimeoutMsForMethod(method) {
3940
+ switch (method) {
3941
+ case "domain.fetchPackagePart":
3942
+ case "domain.getSummary":
3943
+ return DOMAIN_PACKAGE_RPC_TIMEOUT_MS;
3944
+ default:
3945
+ return DEFAULT_RPC_TIMEOUT_MS;
3946
+ }
3947
+ }
3937
3948
  var WSClient = class {
3938
3949
  ws = null;
3939
3950
  url;
@@ -4358,13 +4369,14 @@ var WSClient = class {
4358
4369
  return new Promise((resolve, reject) => {
4359
4370
  this.messageQueue.push({ resolve, reject, id });
4360
4371
  this.ws.send(JSON.stringify(request));
4372
+ const timeoutMs = rpcTimeoutMsForMethod(method);
4361
4373
  setTimeout(() => {
4362
4374
  const pending = this.messageQueue.find((q) => q.id === id);
4363
4375
  if (pending) {
4364
4376
  this.messageQueue = this.messageQueue.filter((q) => q.id !== id);
4365
4377
  reject(new Error(`RPC timeout: ${method}`));
4366
4378
  }
4367
- }, 3e4);
4379
+ }, timeoutMs);
4368
4380
  });
4369
4381
  }
4370
4382
  async handleIncomingRpc(request) {
@@ -4478,10 +4490,48 @@ function normalizePromptText(value) {
4478
4490
  function extractPromptTokens(value) {
4479
4491
  return normalizePromptText(value).split(/\s+/).map((token) => token.trim()).filter((token) => token.length > 0);
4480
4492
  }
4493
+ function parseJsonPromptChoiceOption(option) {
4494
+ const trimmed = option.trim();
4495
+ if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return null;
4496
+ try {
4497
+ const parsed = JSON.parse(trimmed);
4498
+ return asRecord(parsed);
4499
+ } catch {
4500
+ return null;
4501
+ }
4502
+ }
4503
+ function normalizePromptChoiceOption(option) {
4504
+ if (typeof option === "string") {
4505
+ const record2 = parseJsonPromptChoiceOption(option);
4506
+ if (!record2) {
4507
+ return { value: option, label: option };
4508
+ }
4509
+ const value2 = typeof record2.value === "string" ? record2.value : typeof record2.id === "string" ? record2.id : typeof record2.label === "string" ? record2.label : JSON.stringify(record2);
4510
+ return {
4511
+ value: value2,
4512
+ label: typeof record2.label === "string" ? record2.label : value2,
4513
+ description: typeof record2.description === "string" ? record2.description : void 0
4514
+ };
4515
+ }
4516
+ const record = option;
4517
+ if (!record) {
4518
+ return { value: "", label: "" };
4519
+ }
4520
+ const nestedJson = (typeof record.value === "string" ? parseJsonPromptChoiceOption(record.value) : null) || (typeof record.label === "string" ? parseJsonPromptChoiceOption(record.label) : null);
4521
+ if (nestedJson) {
4522
+ return normalizePromptChoiceOption(nestedJson);
4523
+ }
4524
+ const value = typeof record.value === "string" ? record.value : typeof record.label === "string" ? record.label : JSON.stringify(record);
4525
+ return {
4526
+ value,
4527
+ label: typeof record.label === "string" ? record.label : value,
4528
+ description: typeof record.description === "string" ? record.description : void 0
4529
+ };
4530
+ }
4481
4531
  function scorePromptChoiceMatch(answer, answerTokens, option) {
4482
- const value = typeof option === "string" ? option : typeof option?.value === "string" ? option.value : "";
4483
- const label = typeof option === "string" ? option : typeof option?.label === "string" ? option.label : "";
4484
- const description = typeof option === "string" ? "" : typeof option?.description === "string" ? option.description : "";
4532
+ const choice = normalizePromptChoiceOption(option);
4533
+ const { value, label } = choice;
4534
+ const description = choice.description || "";
4485
4535
  const haystack = normalizePromptText([value, label, description].filter(Boolean).join(" "));
4486
4536
  if (!haystack) return { score: 0, resolvedValue: value || label || null };
4487
4537
  let score = 0;
@@ -4517,7 +4567,9 @@ function normalizePrompt(rawValue) {
4517
4567
  type: normalizePromptType(source === raw ? raw : { ...raw, ...source }),
4518
4568
  title: typeof source.title === "string" ? source.title : "Input required",
4519
4569
  message: typeof source.message === "string" ? source.message : "",
4520
- options: Array.isArray(source.options) ? source.options : void 0,
4570
+ options: Array.isArray(source.options) ? source.options.map(
4571
+ (option) => typeof option === "string" || asRecord(option) ? normalizePromptChoiceOption(option) : option
4572
+ ) : void 0,
4521
4573
  defaultValue: source.defaultValue,
4522
4574
  placeholder: typeof source.placeholder === "string" ? source.placeholder : void 0,
4523
4575
  allowEmpty: typeof source.allowEmpty === "boolean" ? source.allowEmpty : void 0,
@@ -4545,6 +4597,22 @@ function resolvePromptAnswer(prompt, answer) {
4545
4597
  }
4546
4598
 
4547
4599
  // src/session.ts
4600
+ var PROMPT_TRANSCRIPT_APPEND_TIMEOUT_MS = 5e3;
4601
+ function withPromptTranscriptTimeout(promise) {
4602
+ let timeout = null;
4603
+ return Promise.race([
4604
+ promise,
4605
+ new Promise((_, reject) => {
4606
+ timeout = setTimeout(() => {
4607
+ reject(new Error("Timed out appending prompt answer transcript."));
4608
+ }, PROMPT_TRANSCRIPT_APPEND_TIMEOUT_MS);
4609
+ })
4610
+ ]).finally(() => {
4611
+ if (timeout) {
4612
+ clearTimeout(timeout);
4613
+ }
4614
+ });
4615
+ }
4548
4616
  var Session = class {
4549
4617
  client;
4550
4618
  clientId;
@@ -4561,6 +4629,8 @@ var Session = class {
4561
4629
  lastKnownTools = /* @__PURE__ */ new Map();
4562
4630
  /** Last seen live prompts, keyed by prompt id, for answer normalization */
4563
4631
  promptCache = /* @__PURE__ */ new Map();
4632
+ /** Prompt ids locally answered before the document sync catches up. */
4633
+ hiddenPromptIds = /* @__PURE__ */ new Set();
4564
4634
  constructor(client, clientId) {
4565
4635
  this.client = client;
4566
4636
  this.clientId = clientId || `client_${Date.now()}`;
@@ -4696,8 +4766,9 @@ var Session = class {
4696
4766
  * `effect.invoke` RPC back to the sandbox effect host, where the registered handlers
4697
4767
  * execute locally and return the result to the sandbox.
4698
4768
  */
4699
- async submitJob(code, domainRevision) {
4700
- let revision = domainRevision || this.currentDomainRevision || this.extractDomainRevisionFromDoc(this.client.doc) || void 0;
4769
+ async submitJob(code, domainRevisionOrOptions) {
4770
+ const options = typeof domainRevisionOrOptions === "string" ? { domainRevision: domainRevisionOrOptions } : domainRevisionOrOptions || {};
4771
+ let revision = options.domainRevision || this.currentDomainRevision || this.extractDomainRevisionFromDoc(this.client.doc) || void 0;
4701
4772
  if (!revision) {
4702
4773
  try {
4703
4774
  const summary = await this.getDomain();
@@ -4712,7 +4783,9 @@ var Session = class {
4712
4783
  }
4713
4784
  const result = await this.client.call("job.submit", {
4714
4785
  domainRevision: revision,
4715
- code
4786
+ code,
4787
+ metadata: options.metadata,
4788
+ agent: options.agent
4716
4789
  });
4717
4790
  if (!result.jobId) {
4718
4791
  throw new Error("Failed to submit job: no jobId returned");
@@ -4753,25 +4826,39 @@ var Session = class {
4753
4826
  const prompt = this.promptCache.get(promptId);
4754
4827
  const resolvedAnswer = resolvePromptAnswer(prompt, answer);
4755
4828
  this.promptCache.delete(promptId);
4756
- await this.client.call("prompt.answer", {
4757
- promptId,
4758
- answer: resolvedAnswer,
4759
- value: resolvedAnswer
4760
- });
4829
+ this.hiddenPromptIds.add(promptId);
4830
+ try {
4831
+ await this.client.call("prompt.answer", {
4832
+ promptId,
4833
+ answer: resolvedAnswer,
4834
+ value: resolvedAnswer
4835
+ });
4836
+ } catch (error) {
4837
+ this.hiddenPromptIds.delete(promptId);
4838
+ if (prompt) {
4839
+ this.promptCache.set(promptId, prompt);
4840
+ }
4841
+ throw error;
4842
+ }
4761
4843
  try {
4762
4844
  const content = this.stringifyConversationValue(resolvedAnswer);
4763
4845
  if (content.trim()) {
4764
- await this.appendConversationMessage({
4765
- role: "user",
4766
- content,
4767
- promptId
4768
- });
4846
+ await withPromptTranscriptTimeout(
4847
+ this.appendConversationMessage({
4848
+ role: "user",
4849
+ content,
4850
+ promptId
4851
+ })
4852
+ );
4769
4853
  }
4770
4854
  } catch {
4771
4855
  }
4772
4856
  }
4773
4857
  async appendConversationMessage(input) {
4774
- return this.client.call("conversation.append", input);
4858
+ return this.client.call(
4859
+ "conversation.append",
4860
+ input
4861
+ );
4775
4862
  }
4776
4863
  /**
4777
4864
  * Get the current list of available effects.
@@ -4780,9 +4867,53 @@ var Session = class {
4780
4867
  getEffects() {
4781
4868
  const doc = this.client.doc;
4782
4869
  const toolMap = /* @__PURE__ */ new Map();
4783
- const domainPkg = doc.domain?.packages?.domain;
4784
- if (domainPkg?.tools && Array.isArray(domainPkg.tools)) {
4785
- for (const tool of domainPkg.tools) {
4870
+ const domainPackages = doc.domain?.packages;
4871
+ const packageCandidates = domainPackages && typeof domainPackages === "object" ? [
4872
+ domainPackages.domain,
4873
+ domainPackages["@sandbox/domain"],
4874
+ ...Object.values(domainPackages)
4875
+ ].filter(Boolean) : [];
4876
+ for (const domainPkg of packageCandidates) {
4877
+ if (domainPkg?.tools && Array.isArray(domainPkg.tools)) {
4878
+ for (const tool of domainPkg.tools) {
4879
+ if (!tool?.name || toolMap.has(tool.name)) continue;
4880
+ toolMap.set(tool.name, {
4881
+ name: tool.name,
4882
+ description: tool.description,
4883
+ inputSchema: tool.inputSchema,
4884
+ outputSchema: tool.outputSchema,
4885
+ className: tool.className || void 0,
4886
+ static: tool.static || false,
4887
+ ready: false,
4888
+ publishedAt: void 0
4889
+ });
4890
+ }
4891
+ }
4892
+ if (!domainPkg?.classes || typeof domainPkg.classes !== "object") {
4893
+ continue;
4894
+ }
4895
+ for (const [className, classDef] of Object.entries(
4896
+ domainPkg.classes
4897
+ )) {
4898
+ const methods = Array.isArray(classDef?.methods) ? classDef.methods : [];
4899
+ for (const method of methods) {
4900
+ if (!method?.name || toolMap.has(method.name)) continue;
4901
+ toolMap.set(method.name, {
4902
+ name: method.name,
4903
+ description: method.description,
4904
+ inputSchema: method.inputSchema,
4905
+ outputSchema: method.outputSchema,
4906
+ className: method.className || classDef?.name || className,
4907
+ static: method.static || false,
4908
+ ready: false,
4909
+ publishedAt: void 0
4910
+ });
4911
+ }
4912
+ }
4913
+ }
4914
+ const legacyDomainPkg = doc.domain?.packages?.domain;
4915
+ if (legacyDomainPkg?.tools && Array.isArray(legacyDomainPkg.tools)) {
4916
+ for (const tool of legacyDomainPkg.tools) {
4786
4917
  if (!tool?.name) continue;
4787
4918
  toolMap.set(tool.name, {
4788
4919
  name: tool.name,
@@ -4796,6 +4927,27 @@ var Session = class {
4796
4927
  });
4797
4928
  }
4798
4929
  }
4930
+ if (legacyDomainPkg?.classes && typeof legacyDomainPkg.classes === "object") {
4931
+ for (const [className, classDef] of Object.entries(
4932
+ legacyDomainPkg.classes
4933
+ )) {
4934
+ const methods = Array.isArray(classDef?.methods) ? classDef.methods : [];
4935
+ for (const method of methods) {
4936
+ if (!method?.name || toolMap.has(method.name)) continue;
4937
+ toolMap.set(method.name, {
4938
+ name: method.name,
4939
+ description: method.description,
4940
+ inputSchema: method.inputSchema,
4941
+ outputSchema: method.outputSchema,
4942
+ className: method.className || classDef?.name || className,
4943
+ static: method.static || false,
4944
+ ready: false,
4945
+ publishedAt: void 0
4946
+ });
4947
+ }
4948
+ }
4949
+ }
4950
+ const hasPolicyFilteredDomainTools = toolMap.size > 0;
4799
4951
  const catalogs = doc.catalog?.rawToolCatalogs || {};
4800
4952
  for (const [clientId, catalog] of Object.entries(catalogs)) {
4801
4953
  const cat = catalog;
@@ -4803,6 +4955,7 @@ var Session = class {
4803
4955
  for (const tool of cat.tools) {
4804
4956
  if (!tool?.name) continue;
4805
4957
  const existing = toolMap.get(tool.name);
4958
+ if (hasPolicyFilteredDomainTools && !existing) continue;
4806
4959
  if (existing?.publishedAt && cat.publishedAt && existing.publishedAt > cat.publishedAt)
4807
4960
  continue;
4808
4961
  const isLocal = clientId === this.clientId;
@@ -4822,6 +4975,24 @@ var Session = class {
4822
4975
  }
4823
4976
  return Array.from(toolMap.values());
4824
4977
  }
4978
+ /**
4979
+ * Return the currently open prompt payloads known to this session.
4980
+ *
4981
+ * These come from live `prompt` / `prompt.request` websocket events and
4982
+ * preserve the exact shape used by `answerPrompt(...)`.
4983
+ */
4984
+ getPrompts() {
4985
+ return Array.from(this.promptCache.values()).map((prompt) => ({
4986
+ ...prompt,
4987
+ options: Array.isArray(prompt.options) ? prompt.options.map(
4988
+ (option) => typeof option === "string" ? option : { ...option }
4989
+ ) : void 0,
4990
+ metadata: prompt.metadata ? { ...prompt.metadata } : void 0
4991
+ }));
4992
+ }
4993
+ getHiddenPromptIds() {
4994
+ return Array.from(this.hiddenPromptIds);
4995
+ }
4825
4996
  /**
4826
4997
  * Backwards-compatible alias for `getEffects()`.
4827
4998
  */
@@ -4921,11 +5092,7 @@ var Session = class {
4921
5092
  if (!normalizedDocs) {
4922
5093
  return normalizedTypes;
4923
5094
  }
4924
- return [
4925
- normalizedTypes,
4926
- "Generated usage notes from ./sandbox-tools docs:",
4927
- normalizedDocs
4928
- ].join("\n\n");
5095
+ return [normalizedTypes, "[Docs]", normalizedDocs].join("\n\n");
4929
5096
  }
4930
5097
  if (normalizedDocs) {
4931
5098
  return normalizedDocs;
@@ -5147,6 +5314,7 @@ import { ${allImports} } from "./sandbox-tools";
5147
5314
  const emitPrompt = (payload) => {
5148
5315
  const prompt = normalizePrompt(payload);
5149
5316
  if (!prompt) return;
5317
+ this.hiddenPromptIds.delete(prompt.id);
5150
5318
  this.promptCache.set(prompt.id, prompt);
5151
5319
  this.emit("prompt", prompt);
5152
5320
  };
@@ -5329,6 +5497,7 @@ var JobImplementation = class {
5329
5497
  eventListeners = /* @__PURE__ */ new Map();
5330
5498
  bufferedAgentMessages = [];
5331
5499
  bufferedAgentMessageIds = /* @__PURE__ */ new Set();
5500
+ resultSettled = false;
5332
5501
  metadata;
5333
5502
  constructor(id, client, initialState) {
5334
5503
  this.id = id;
@@ -5353,7 +5522,9 @@ var JobImplementation = class {
5353
5522
  if (execData.error) {
5354
5523
  this.finalize("failed", void 0, execData.error);
5355
5524
  } else {
5356
- this.finalize("succeeded", execData.result);
5525
+ this.finalize("succeeded", execData.result, void 0, {
5526
+ hasResult: Object.prototype.hasOwnProperty.call(execData, "result")
5527
+ });
5357
5528
  }
5358
5529
  this.emit("status", this.status);
5359
5530
  }
@@ -5389,9 +5560,6 @@ var JobImplementation = class {
5389
5560
  if (normalizedStatus === "failed" || normalizedStatus === "timeout" || normalizedStatus === "canceled") {
5390
5561
  this.finalize(normalizedStatus);
5391
5562
  }
5392
- if (normalizedStatus === "succeeded") {
5393
- this.finalize("succeeded");
5394
- }
5395
5563
  this.emit("status", normalizedStatus);
5396
5564
  });
5397
5565
  this.client.on(`job.${id}.stdout`, (line) => {
@@ -5411,7 +5579,7 @@ var JobImplementation = class {
5411
5579
  this.emit("stderr", line);
5412
5580
  });
5413
5581
  this.client.on(`job.${id}.result`, (result) => {
5414
- this.finalize("succeeded", result);
5582
+ this.finalize("succeeded", result, void 0, { hasResult: true });
5415
5583
  });
5416
5584
  this.client.on(`job.${id}.error`, (error) => {
5417
5585
  this.finalize("failed", void 0, error);
@@ -5432,7 +5600,9 @@ var JobImplementation = class {
5432
5600
  this.client.on("job.completed", (data) => {
5433
5601
  const jobData = data;
5434
5602
  if (jobData.jobId === id) {
5435
- this.finalize("succeeded", jobData.result);
5603
+ this.finalize("succeeded", jobData.result, void 0, {
5604
+ hasResult: true
5605
+ });
5436
5606
  this.emit("status", this.status);
5437
5607
  }
5438
5608
  });
@@ -5557,7 +5727,7 @@ var JobImplementation = class {
5557
5727
  this.metadata.status = "running";
5558
5728
  }
5559
5729
  }
5560
- finalize(status, result, error) {
5730
+ finalize(status, result, error, options = {}) {
5561
5731
  if (!this.metadata.startedAt) {
5562
5732
  this.metadata.startedAt = Date.now();
5563
5733
  }
@@ -5565,14 +5735,18 @@ var JobImplementation = class {
5565
5735
  this.metadata.status = status;
5566
5736
  this.metadata.completedAt = this.metadata.completedAt || Date.now();
5567
5737
  this.metadata.durationMs = this.metadata.completedAt - this.metadata.startedAt;
5568
- if (result !== void 0) {
5738
+ if (!this.resultSettled && (options.hasResult || result !== void 0)) {
5569
5739
  this.metadata.result = sanitizeFeedbackValue(result);
5740
+ this.resultSettled = true;
5570
5741
  this._resolveResult(result);
5571
5742
  }
5572
- if (error !== void 0) {
5573
- const message = error instanceof Error ? error.message : String(error);
5743
+ if (!this.resultSettled && (error !== void 0 || status === "failed" || status === "timeout" || status === "canceled")) {
5744
+ const fallbackError = new Error(`Job ${this.id} ${status}.`);
5745
+ const cause = error ?? fallbackError;
5746
+ const message = cause instanceof Error ? cause.message : String(cause);
5574
5747
  this.metadata.error = truncateFeedbackString(message);
5575
- this._rejectResult(error);
5748
+ this.resultSettled = true;
5749
+ this._rejectResult(cause);
5576
5750
  }
5577
5751
  }
5578
5752
  upsertToolCall(next) {
@@ -5655,6 +5829,17 @@ function humanTextFromStdout(stdout) {
5655
5829
  }
5656
5830
  return null;
5657
5831
  }
5832
+ function responseTextFromAgentMessages(agentMessages) {
5833
+ for (const message of [...agentMessages].reverse()) {
5834
+ const record = asRecord2(message);
5835
+ if (!record) continue;
5836
+ for (const key of RESPONSE_KEYS) {
5837
+ const normalized = normalizeText(record[key]);
5838
+ if (normalized) return normalized;
5839
+ }
5840
+ }
5841
+ return null;
5842
+ }
5658
5843
  function pushString(target, value) {
5659
5844
  if (typeof value === "string" && value.trim()) {
5660
5845
  target.add(value.trim());
@@ -5680,6 +5865,41 @@ function collectReferencesFromRecord(record, refs) {
5680
5865
  for (const key of VARIABLE_ARRAY_KEY_CANDIDATES)
5681
5866
  pushStringArray(refs.variableNames, record[key]);
5682
5867
  }
5868
+ function stringValue(record, keys) {
5869
+ for (const key of keys) {
5870
+ const value = record[key];
5871
+ if (typeof value === "string" && value.trim()) {
5872
+ return value.trim();
5873
+ }
5874
+ }
5875
+ return null;
5876
+ }
5877
+ function findEntryPathForRecord(record, heap) {
5878
+ const directPath = stringValue(record, ["entryPath", "path"]);
5879
+ if (directPath && heap.entriesByPath?.[directPath]) {
5880
+ return directPath;
5881
+ }
5882
+ const id = stringValue(record, ["id", "_id", "recordId", "objectId"]);
5883
+ if (!id) {
5884
+ return null;
5885
+ }
5886
+ const className = stringValue(record, [
5887
+ "className",
5888
+ "_className",
5889
+ "__className",
5890
+ "prototype",
5891
+ "type"
5892
+ ]);
5893
+ const entries = Object.values(heap.entriesByPath || {});
5894
+ const exact = entries.find(
5895
+ (entry) => entry.id === id && (!className || entry.className === className || entry.prototypes?.includes(className))
5896
+ );
5897
+ if (exact?.path) {
5898
+ return exact.path;
5899
+ }
5900
+ const idOnlyMatches = entries.filter((entry) => entry.id === id);
5901
+ return idOnlyMatches.length === 1 ? idOnlyMatches[0].path : null;
5902
+ }
5683
5903
  function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__ */ new Set()) {
5684
5904
  if (value === null || value === void 0 || depth > 4 || seen.has(value))
5685
5905
  return;
@@ -5700,6 +5920,8 @@ function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__
5700
5920
  const record = asRecord2(value);
5701
5921
  if (!record) return;
5702
5922
  seen.add(value);
5923
+ const entryPath = findEntryPathForRecord(record, heap);
5924
+ if (entryPath) refs.entryPaths.add(entryPath);
5703
5925
  collectReferencesFromRecord(record, refs);
5704
5926
  for (const key of UI_CONTAINER_KEYS) {
5705
5927
  const nested = asRecord2(record[key]);
@@ -5808,6 +6030,7 @@ function resolveJobPresentation({
5808
6030
  jobId,
5809
6031
  result,
5810
6032
  stdout = [],
6033
+ agentMessages = [],
5811
6034
  sessionHeap,
5812
6035
  allowExplicitArtifacts = true
5813
6036
  }) {
@@ -5840,7 +6063,7 @@ function resolveJobPresentation({
5840
6063
  const hasExplicitArtifacts = allowExplicitArtifacts && (explicitEntries.length > 0 || explicitLists.length > 0);
5841
6064
  const lists = hasExplicitArtifacts ? explicitLists : jobLists;
5842
6065
  const entries = hasExplicitArtifacts ? explicitEntries : changedEntries;
5843
- const responseText = extractResponseText(result, stdout) || fallbackResponseText(entries, lists);
6066
+ const responseText = extractResponseText(result, stdout) || responseTextFromAgentMessages(agentMessages) || fallbackResponseText(entries, lists);
5844
6067
  return {
5845
6068
  responseText,
5846
6069
  entries,
@@ -10316,6 +10539,67 @@ external_exports.object({
10316
10539
  transitions: external_exports.array(StateMachineTransitionSchema),
10317
10540
  finalStates: external_exports.array(external_exports.string()).optional()
10318
10541
  }).strict();
10542
+ var POLICY_OPERATORS = [
10543
+ "eq",
10544
+ "neq",
10545
+ "gt",
10546
+ "gte",
10547
+ "lt",
10548
+ "lte",
10549
+ "contains",
10550
+ "not_contains",
10551
+ "starts_with",
10552
+ "ends_with",
10553
+ "exists"
10554
+ ];
10555
+ var PolicyPredicateSchema = external_exports.object({
10556
+ path: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional(),
10557
+ field: external_exports.string().optional(),
10558
+ input: external_exports.string().optional(),
10559
+ operator: external_exports.enum([...POLICY_OPERATORS]),
10560
+ stringValue: external_exports.string().optional(),
10561
+ numberValue: external_exports.number().optional(),
10562
+ booleanValue: external_exports.boolean().optional(),
10563
+ value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()]).optional()
10564
+ }).strict();
10565
+ var PolicyStateMachinePredicateSchema = external_exports.object({
10566
+ machine: external_exports.string().min(1),
10567
+ operator: external_exports.enum([...POLICY_OPERATORS]),
10568
+ state: external_exports.string().optional(),
10569
+ stringValue: external_exports.string().optional()
10570
+ }).strict();
10571
+ var PolicyConditionSchema = external_exports.lazy(
10572
+ () => external_exports.object({
10573
+ all: external_exports.array(PolicyConditionSchema).optional(),
10574
+ any: external_exports.array(PolicyConditionSchema).optional(),
10575
+ not: PolicyConditionSchema.optional(),
10576
+ input: PolicyPredicateSchema.optional(),
10577
+ object: PolicyPredicateSchema.optional(),
10578
+ stateMachine: PolicyStateMachinePredicateSchema.optional()
10579
+ }).strict().refine(
10580
+ (data) => [
10581
+ data.all,
10582
+ data.any,
10583
+ data.not,
10584
+ data.input,
10585
+ data.object,
10586
+ data.stateMachine
10587
+ ].filter((value) => value !== void 0).length === 1,
10588
+ {
10589
+ message: "Policy condition must define exactly one of all, any, not, input, object, or stateMachine"
10590
+ }
10591
+ )
10592
+ );
10593
+ var PolicyRuleSchema = external_exports.object({
10594
+ id: external_exports.string().min(1).optional(),
10595
+ reason: external_exports.string().optional(),
10596
+ when: PolicyConditionSchema
10597
+ }).strict();
10598
+ var PoliciesSchema = external_exports.object({
10599
+ allowWhen: external_exports.array(PolicyRuleSchema).optional(),
10600
+ confirmWhen: external_exports.array(PolicyRuleSchema).optional(),
10601
+ denyWhen: external_exports.array(PolicyRuleSchema).optional()
10602
+ }).strict();
10319
10603
  external_exports.object({
10320
10604
  postCondition: external_exports.union([
10321
10605
  external_exports.string(),
@@ -10345,7 +10629,8 @@ external_exports.object({
10345
10629
  reason: external_exports.string().optional(),
10346
10630
  mode: external_exports.string().optional()
10347
10631
  }).strict()
10348
- ]).optional()
10632
+ ]).optional(),
10633
+ policies: PoliciesSchema.optional()
10349
10634
  }).strict();
10350
10635
 
10351
10636
  // ../metamodel-core/src/index.ts
@@ -11377,6 +11662,148 @@ var noteMetamodelPackage = defineMetamodelPackage({
11377
11662
  }
11378
11663
  });
11379
11664
 
11665
+ // ../policy-engine/src/index.ts
11666
+ function isRecord(value) {
11667
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
11668
+ }
11669
+ function normalizePath(value) {
11670
+ if (Array.isArray(value)) {
11671
+ return value.map((part) => String(part)).filter(Boolean);
11672
+ }
11673
+ if (typeof value === "string") {
11674
+ return value.includes(".") ? value.split(".").filter(Boolean) : [value];
11675
+ }
11676
+ return [];
11677
+ }
11678
+ function firstDefinedValue(spec) {
11679
+ if ("value" in spec) return spec.value;
11680
+ if ("stringValue" in spec) return spec.stringValue;
11681
+ if ("numberValue" in spec) return spec.numberValue;
11682
+ if ("booleanValue" in spec) return spec.booleanValue;
11683
+ if ("state" in spec) return spec.state;
11684
+ return void 0;
11685
+ }
11686
+ function normalizeCondition(input) {
11687
+ if (input === void 0 || input === null) return { kind: "always" };
11688
+ if (!isRecord(input)) {
11689
+ throw new Error("Policy condition must be an object");
11690
+ }
11691
+ if (Array.isArray(input.all)) {
11692
+ return {
11693
+ kind: "all",
11694
+ conditions: input.all.map((item) => normalizeCondition(item))
11695
+ };
11696
+ }
11697
+ if (Array.isArray(input.any)) {
11698
+ return {
11699
+ kind: "any",
11700
+ conditions: input.any.map((item) => normalizeCondition(item))
11701
+ };
11702
+ }
11703
+ if (input.not !== void 0) {
11704
+ return { kind: "not", condition: normalizeCondition(input.not) };
11705
+ }
11706
+ for (const source of ["input", "object", "stateMachine"]) {
11707
+ const raw = input[source];
11708
+ if (!isRecord(raw)) continue;
11709
+ const operator = raw.operator;
11710
+ 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") {
11711
+ throw new Error(`Unsupported policy operator: ${String(operator)}`);
11712
+ }
11713
+ if (source === "stateMachine") {
11714
+ const machine = typeof raw.machine === "string" ? raw.machine : "";
11715
+ if (!machine) throw new Error("stateMachine condition requires machine");
11716
+ return {
11717
+ kind: "predicate",
11718
+ source,
11719
+ path: [machine],
11720
+ machine,
11721
+ operator,
11722
+ value: firstDefinedValue(raw)
11723
+ };
11724
+ }
11725
+ const path = normalizePath(raw.path ?? raw.field ?? raw.input);
11726
+ if (path.length === 0) {
11727
+ throw new Error(`${source} condition requires a path`);
11728
+ }
11729
+ return {
11730
+ kind: "predicate",
11731
+ source,
11732
+ path,
11733
+ operator,
11734
+ value: firstDefinedValue(raw)
11735
+ };
11736
+ }
11737
+ throw new Error(
11738
+ "Policy condition must contain all, any, not, input, object, or stateMachine"
11739
+ );
11740
+ }
11741
+ function summarizeCondition(condition) {
11742
+ switch (condition.kind) {
11743
+ case "always":
11744
+ return "always";
11745
+ case "all":
11746
+ return condition.conditions.map(summarizeCondition).join(" and ");
11747
+ case "any":
11748
+ return condition.conditions.map(summarizeCondition).join(" or ");
11749
+ case "not":
11750
+ return `not (${summarizeCondition(condition.condition)})`;
11751
+ case "predicate": {
11752
+ const path = condition.source === "stateMachine" ? `stateMachine.${condition.machine || condition.path.join(".")}` : `${condition.source}.${condition.path.join(".")}`;
11753
+ if (condition.operator === "exists") return `${path} exists`;
11754
+ return `${path} ${condition.operator} ${String(condition.value)}`;
11755
+ }
11756
+ }
11757
+ }
11758
+
11759
+ // ../metamodel-policy/src/index.ts
11760
+ function escapeGraphqlString(value) {
11761
+ return JSON.stringify(value);
11762
+ }
11763
+ function buildPolicyMutations(effectKey, spec) {
11764
+ const policies = spec.policies;
11765
+ if (!policies) return [];
11766
+ const mutations = [];
11767
+ const addRules = (key, outcome) => {
11768
+ const rules = policies[key] || [];
11769
+ rules.forEach((rule, index) => {
11770
+ const condition = normalizeCondition(rule.when);
11771
+ const summary = rule.reason || summarizeCondition(condition);
11772
+ const id = rule.id || `${effectKey}:${outcome}:${index + 1}`;
11773
+ mutations.push({
11774
+ label: `set policy ${outcome} on ${effectKey}`,
11775
+ 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))}) }`
11776
+ });
11777
+ });
11778
+ };
11779
+ addRules("allowWhen", "allow");
11780
+ addRules("confirmWhen", "confirm");
11781
+ addRules("denyWhen", "deny");
11782
+ return mutations;
11783
+ }
11784
+ var policyMetamodelPackage = defineMetamodelPackage({
11785
+ id: "policy",
11786
+ manifest: {
11787
+ buildEffectMutations: buildPolicyMutations
11788
+ },
11789
+ summary: {
11790
+ selections: {
11791
+ methodFields: ["policies"]
11792
+ },
11793
+ readMethodSummary(rawMethod) {
11794
+ return rawMethod.policies ? { metamodels: { policies: rawMethod.policies } } : {};
11795
+ }
11796
+ },
11797
+ docs: {
11798
+ effectRows: [
11799
+ {
11800
+ key: "policies",
11801
+ description: "Universal effect policies with allowWhen, confirmWhen, and denyWhen structural conditions."
11802
+ }
11803
+ ]
11804
+ }
11805
+ });
11806
+
11380
11807
  // ../metamodel-required/src/index.ts
11381
11808
  function buildRequiredFieldMutations(fieldPath, required) {
11382
11809
  if (!required) return [];
@@ -12151,7 +12578,8 @@ var DEFAULT_METAMODEL_PACKAGES = [
12151
12578
  searchableMetamodelPackage,
12152
12579
  validationRuleMetamodelPackage,
12153
12580
  stateMachineMetamodelPackage,
12154
- effectBehaviorsMetamodelPackage
12581
+ effectBehaviorsMetamodelPackage,
12582
+ policyMetamodelPackage
12155
12583
  ];
12156
12584
  createMetamodelRegistry(
12157
12585
  DEFAULT_METAMODEL_PACKAGES
@@ -12218,6 +12646,12 @@ var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_COUNT = 3;
12218
12646
  var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_DELAY_MS = 1e3;
12219
12647
  var LOCAL_CONTROL_REQUEST_RETRY_COUNT = 4;
12220
12648
  var LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS = 500;
12649
+ var SESSION_DATA_REQUEST_RETRY_COUNT = 4;
12650
+ var SESSION_DATA_REQUEST_RETRY_DELAY_MS = 500;
12651
+ var EFFECT_HOST_CONNECT_TIMEOUT_MS = 15e3;
12652
+ var EFFECT_CATALOG_SYNC_TIMEOUT_MS = 3e4;
12653
+ var EFFECT_CATALOG_SYNC_RETRY_COUNT = 3;
12654
+ var EFFECT_CATALOG_SYNC_RETRY_DELAY_MS = 1e3;
12221
12655
  function planRecordObjectsChunks(records, batchSize) {
12222
12656
  const total = records.length;
12223
12657
  const size = Math.max(1, Math.min(batchSize, total));
@@ -12232,6 +12666,19 @@ function planRecordObjectsChunks(records, batchSize) {
12232
12666
  function sleep(ms) {
12233
12667
  return new Promise((resolve) => setTimeout(resolve, ms));
12234
12668
  }
12669
+ function withTimeout(promise, timeoutMs, label) {
12670
+ let timer = null;
12671
+ const timeout = new Promise((_, reject) => {
12672
+ timer = setTimeout(() => {
12673
+ reject(new Error(`${label} timed out after ${timeoutMs}ms`));
12674
+ }, timeoutMs);
12675
+ });
12676
+ return Promise.race([promise, timeout]).finally(() => {
12677
+ if (timer) {
12678
+ clearTimeout(timer);
12679
+ }
12680
+ });
12681
+ }
12235
12682
  function isLocalControlUrl(url) {
12236
12683
  try {
12237
12684
  const parsed = new URL(url);
@@ -12245,7 +12692,19 @@ function isRetryableLocalWorkerRestart(status, body, url) {
12245
12692
  }
12246
12693
  function isRetryableRecordObjectsError(error) {
12247
12694
  const message = error instanceof Error ? error.message : String(error);
12248
- return /worker restarted mid-request|econnreset|network|socket connection was closed unexpectedly|timed out/i.test(
12695
+ 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(
12696
+ message
12697
+ );
12698
+ }
12699
+ function isRetryableEffectRegistrationError(error) {
12700
+ const message = error instanceof Error ? error.message : String(error);
12701
+ 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(
12702
+ message
12703
+ );
12704
+ }
12705
+ function isRetryableSessionDataError(error) {
12706
+ const message = error instanceof Error ? error.message : String(error);
12707
+ 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(
12249
12708
  message
12250
12709
  );
12251
12710
  }
@@ -12267,16 +12726,28 @@ function computeEffectRegistrationKey(effect) {
12267
12726
  effect.versionSelector
12268
12727
  )}`;
12269
12728
  }
12270
- function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId) {
12271
- const url = new URL(apiUrl);
12272
- if (url.pathname.endsWith("/granular/ws/connect")) {
12729
+ function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId, effectHostUrl) {
12730
+ const overrideUrl = effectHostUrl || process.env.GRANULAR_EFFECT_HOST_URL || process.env.EFFECT_HOST_URL;
12731
+ const api = new URL(apiUrl);
12732
+ const localRuntimeBase = process.env.RUNTIME_ORCHESTRATOR_URL || (isLocalControlUrl(apiUrl) ? `${api.protocol}//${api.hostname}:8791` : "");
12733
+ const url = new URL(overrideUrl || localRuntimeBase || apiUrl);
12734
+ if (url.protocol === "https:") {
12735
+ url.protocol = "wss:";
12736
+ } else if (url.protocol === "http:") {
12737
+ url.protocol = "ws:";
12738
+ }
12739
+ if (!overrideUrl && isLocalControlUrl(apiUrl) && api.pathname.endsWith("/granular")) {
12740
+ url.pathname = "/granular/orchestrator/effects/connect";
12741
+ } else if (url.pathname.endsWith("/granular/ws/connect")) {
12273
12742
  url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
12274
12743
  } else if (url.pathname.endsWith("/granular")) {
12275
- url.pathname = `${url.pathname.replace(/\/$/, "")}/effects/connect`;
12744
+ url.pathname = isLocalControlUrl(url.toString()) ? "/granular/orchestrator/effects/connect" : `${url.pathname.replace(/\/$/, "")}/effects/connect`;
12276
12745
  } else if (url.pathname.endsWith("/v2/ws/connect")) {
12277
12746
  url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
12278
12747
  } else if (url.pathname.endsWith("/v2/ws")) {
12279
12748
  url.pathname = url.pathname.replace(/\/ws$/, "/effects/connect");
12749
+ } else if (url.pathname === "/" && isLocalControlUrl(url.toString()) && (url.port === "8791" || !overrideUrl && Boolean(localRuntimeBase))) {
12750
+ url.pathname = "/granular/orchestrator/effects/connect";
12280
12751
  } else if (url.pathname.endsWith("/ws/connect")) {
12281
12752
  url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
12282
12753
  } else if (url.pathname.endsWith("/ws")) {
@@ -12311,6 +12782,79 @@ function normalizeHeapSnapshot(raw) {
12311
12782
  updatedAt: typeof heap.updatedAt === "number" ? heap.updatedAt : Date.now()
12312
12783
  };
12313
12784
  }
12785
+ function normalizeGraphPathSegment(value) {
12786
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
12787
+ }
12788
+ function extractRecordIdFromGraphPath(path, className) {
12789
+ const normalizedPrefix = `${normalizeGraphPathSegment(className)}_`;
12790
+ if (path.startsWith(normalizedPrefix)) {
12791
+ return path.slice(normalizedPrefix.length);
12792
+ }
12793
+ const legacyPrefix = `${className}_`;
12794
+ if (path.startsWith(legacyPrefix)) {
12795
+ return path.slice(legacyPrefix.length);
12796
+ }
12797
+ return path;
12798
+ }
12799
+ function toRecordSearchResult(className, node) {
12800
+ const path = typeof node.path === "string" ? node.path : "";
12801
+ if (!path) return null;
12802
+ const fields = Array.isArray(node.submodels) ? node.submodels.flatMap(
12803
+ (submodel) => {
12804
+ const name = typeof submodel?.label === "string" && submodel.label.trim() ? submodel.label : typeof submodel?.path === "string" ? submodel.path.split(":").pop() || submodel.path : "";
12805
+ if (!name) return [];
12806
+ if (typeof submodel.string_value === "string") {
12807
+ return [{ name, type: "string", value: submodel.string_value }];
12808
+ }
12809
+ if (typeof submodel.number_value === "number") {
12810
+ return [{ name, type: "number", value: submodel.number_value }];
12811
+ }
12812
+ if (typeof submodel.boolean_value === "boolean") {
12813
+ return [
12814
+ {
12815
+ name,
12816
+ type: "boolean",
12817
+ value: submodel.boolean_value
12818
+ }
12819
+ ];
12820
+ }
12821
+ return [];
12822
+ }
12823
+ ) : [];
12824
+ return {
12825
+ path,
12826
+ className,
12827
+ id: extractRecordIdFromGraphPath(path, className),
12828
+ label: typeof node.label === "string" && node.label.trim() ? node.label : extractRecordIdFromGraphPath(path, className),
12829
+ description: typeof node.description === "string" && node.description.trim() ? node.description : null,
12830
+ fields
12831
+ };
12832
+ }
12833
+ function normalizeRecordSearchText(value) {
12834
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, " ").replace(/\s+/g, " ").trim();
12835
+ }
12836
+ function rankRecordSearchResult(result, query, index) {
12837
+ const normalizedQuery = normalizeRecordSearchText(query);
12838
+ if (!normalizedQuery) {
12839
+ return index;
12840
+ }
12841
+ const label = normalizeRecordSearchText(result.label || "");
12842
+ const id = normalizeRecordSearchText(result.id || "");
12843
+ const path = normalizeRecordSearchText(result.path || "");
12844
+ const className = normalizeRecordSearchText(result.className || "");
12845
+ const searchable = [label, id, path, className].filter(Boolean);
12846
+ if (label === normalizedQuery) return index;
12847
+ if (id === normalizedQuery || path === normalizedQuery) return 100 + index;
12848
+ if (label.startsWith(normalizedQuery)) return 200 + index;
12849
+ if (searchable.some((value) => value.startsWith(normalizedQuery))) {
12850
+ return 300 + index;
12851
+ }
12852
+ if (label.includes(normalizedQuery)) return 400 + index;
12853
+ if (searchable.some((value) => value.includes(normalizedQuery))) {
12854
+ return 500 + index;
12855
+ }
12856
+ return 900 + index;
12857
+ }
12314
12858
  function deriveRuntimeBaseUrl(apiEndpoint) {
12315
12859
  try {
12316
12860
  const endpoint = new URL(apiEndpoint);
@@ -12399,7 +12943,7 @@ function normalizeEnvironmentData(environment) {
12399
12943
  setup: normalizeEnvironmentSetupSummary(environment.setup)
12400
12944
  };
12401
12945
  }
12402
- var Environment = class {
12946
+ var Environment = class _Environment {
12403
12947
  granular;
12404
12948
  envData;
12405
12949
  _apiKey;
@@ -12594,28 +13138,30 @@ var Environment = class {
12594
13138
  return response.json();
12595
13139
  }
12596
13140
  // ==================== ID ↔ GRAPH PATH MAPPING ====================
13141
+ static normalizeGraphPathSegment(value) {
13142
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
13143
+ }
12597
13144
  /**
12598
- * Convert a class name + real-world ID into a unique graph path.
12599
- *
12600
- * Two objects of *different* classes may share the same real-world ID,
12601
- * so the graph path must incorporate the class to guarantee uniqueness.
12602
- *
12603
- * Format: `{className}_{id}` — deterministic, human-readable.
13145
+ * Convert a class name + application record ID into Granular's graph path.
12604
13146
  *
12605
- * **Convention**: class names should be simple identifiers without
12606
- * underscores (e.g. `author`, `book`). This ensures the prefix is
12607
- * unambiguously parseable by `extractIdFromGraphPath`.
13147
+ * This mirrors the record-write path normalization used by the control plane.
13148
+ * Keep the original customer/system ID in `real_id`; graph paths are stable
13149
+ * internal addresses, not the source of truth for business identity.
12608
13150
  */
12609
13151
  static toGraphPath(className, id) {
12610
- return `${className}_${id}`;
13152
+ return `${_Environment.normalizeGraphPathSegment(className)}_${_Environment.normalizeGraphPathSegment(id)}`;
12611
13153
  }
12612
13154
  /**
12613
- * Extract the real-world ID from a graph path, given the class name.
13155
+ * Best-effort extraction of an ID-like suffix from a graph path.
12614
13156
  *
12615
- * Strips the `{className}_` prefix. Returns the raw path if the
12616
- * expected prefix is not found.
13157
+ * Prefer the record's `real_id` field whenever exact customer/system IDs
13158
+ * matter, because graph path normalization is intentionally lossy.
12617
13159
  */
12618
13160
  static extractIdFromGraphPath(graphPath, className) {
13161
+ const normalizedPrefix = `${_Environment.normalizeGraphPathSegment(className)}_`;
13162
+ if (graphPath.startsWith(normalizedPrefix)) {
13163
+ return graphPath.substring(normalizedPrefix.length);
13164
+ }
12619
13165
  const prefix = `${className}_`;
12620
13166
  return graphPath.startsWith(prefix) ? graphPath.substring(prefix.length) : graphPath;
12621
13167
  }
@@ -12662,6 +13208,62 @@ var Environment = class {
12662
13208
  }
12663
13209
  return response.json();
12664
13210
  }
13211
+ async searchRecords(query, options = {}) {
13212
+ const normalizedQuery = query.replace(/\s+/g, " ").trim();
13213
+ const limit = Math.max(1, Math.min(50, Math.floor(options.limit ?? 12)));
13214
+ const offset = Math.max(0, Math.floor(options.offset ?? 0));
13215
+ const response = await this.graphql(
13216
+ `
13217
+ query RecordMentionSearch(
13218
+ $query: String
13219
+ $limit: Int
13220
+ $offset: Int
13221
+ $classNames: [String!]
13222
+ ) {
13223
+ record_search(
13224
+ query: $query
13225
+ limit: $limit
13226
+ offset: $offset
13227
+ class_names: $classNames
13228
+ ) {
13229
+ className
13230
+ model {
13231
+ path
13232
+ label
13233
+ description
13234
+ submodels {
13235
+ path
13236
+ label
13237
+ string_value
13238
+ number_value
13239
+ boolean_value
13240
+ }
13241
+ }
13242
+ }
13243
+ }
13244
+ `,
13245
+ {
13246
+ query: normalizedQuery,
13247
+ limit,
13248
+ offset,
13249
+ classNames: options.classNames?.length ? options.classNames : []
13250
+ }
13251
+ );
13252
+ const seen = /* @__PURE__ */ new Set();
13253
+ const results = (response.data?.record_search || []).flatMap((entry) => {
13254
+ const className = entry.className?.trim();
13255
+ const item = className && entry.model ? toRecordSearchResult(className, entry.model) : null;
13256
+ if (!item || seen.has(item.path)) {
13257
+ return [];
13258
+ }
13259
+ seen.add(item.path);
13260
+ return [item];
13261
+ });
13262
+ return results.map((result, index) => ({
13263
+ result,
13264
+ rank: rankRecordSearchResult(result, normalizedQuery, index)
13265
+ })).sort((left, right) => left.rank - right.rank).map((item) => item.result).slice(0, limit);
13266
+ }
12665
13267
  // ==================== RELATIONSHIP METHODS ====================
12666
13268
  /**
12667
13269
  * Define a relationship between two model types.
@@ -13427,7 +14029,8 @@ var Environment = class {
13427
14029
  body: JSON.stringify({
13428
14030
  records,
13429
14031
  batchSize: options.batchSize,
13430
- setupRunId: options.setupRunId
14032
+ setupRunId: options.setupRunId,
14033
+ writeMode: options.writeMode
13431
14034
  })
13432
14035
  }
13433
14036
  );
@@ -13479,11 +14082,13 @@ var Environment = class {
13479
14082
  };
13480
14083
  var EnvironmentSession = class extends Session {
13481
14084
  environment;
14085
+ sessionDataRoutePrefix;
13482
14086
  /** The last known graph container status, updated by checkReadiness() or on heartbeat */
13483
14087
  graphContainerStatus = null;
13484
- constructor(client, environment, clientId) {
14088
+ constructor(client, environment, clientId, options = {}) {
13485
14089
  super(client, clientId);
13486
14090
  this.environment = environment;
14091
+ this.sessionDataRoutePrefix = options.sessionDataRoutePrefix || "/orchestrator/ws/sessions";
13487
14092
  }
13488
14093
  get environmentId() {
13489
14094
  return this.environment.environmentId;
@@ -13528,7 +14133,7 @@ var EnvironmentSession = class extends Session {
13528
14133
  const doc = this.document;
13529
14134
  return normalizeHeapSnapshot(doc?.heap);
13530
14135
  }
13531
- async sessionDataRequest(path, query) {
14136
+ async sessionDataRequest(path, query, init2 = {}) {
13532
14137
  const searchParams = new URLSearchParams();
13533
14138
  for (const [key, value] of Object.entries(query || {})) {
13534
14139
  if (value !== null && typeof value !== "undefined" && value !== "") {
@@ -13536,23 +14141,39 @@ var EnvironmentSession = class extends Session {
13536
14141
  }
13537
14142
  }
13538
14143
  const queryString = searchParams.toString();
13539
- const response = await fetch(
13540
- `${this.environment.runtimeBaseUrl}/orchestrator/ws/sessions/${encodeURIComponent(this.sessionId)}${path}${queryString ? `?${queryString}` : ""}`,
13541
- {
13542
- method: "GET",
13543
- headers: {
13544
- Authorization: `Bearer ${this.environment.authToken}`,
13545
- "Content-Type": "application/json"
14144
+ const url = `${this.environment.runtimeBaseUrl}${this.sessionDataRoutePrefix}/${encodeURIComponent(this.sessionId)}${path}${queryString ? `?${queryString}` : ""}`;
14145
+ const body = typeof init2.body === "undefined" ? void 0 : JSON.stringify(init2.body);
14146
+ for (let attempt = 1; attempt <= SESSION_DATA_REQUEST_RETRY_COUNT; attempt += 1) {
14147
+ try {
14148
+ const response = await fetch(url, {
14149
+ method: init2.method || "GET",
14150
+ headers: {
14151
+ Authorization: `Bearer ${this.environment.authToken}`,
14152
+ "Content-Type": "application/json"
14153
+ },
14154
+ ...typeof body === "undefined" ? {} : { body }
14155
+ });
14156
+ if (response.ok) {
14157
+ return response.json();
14158
+ }
14159
+ const errorText = await response.text();
14160
+ const error = new Error(
14161
+ `Session data API Error (${response.status}): ${errorText}`
14162
+ );
14163
+ if (isLocalControlUrl(url) && isRetryableSessionDataError(error) && attempt < SESSION_DATA_REQUEST_RETRY_COUNT) {
14164
+ await sleep(SESSION_DATA_REQUEST_RETRY_DELAY_MS * attempt);
14165
+ continue;
14166
+ }
14167
+ throw error;
14168
+ } catch (error) {
14169
+ if (isLocalControlUrl(url) && isRetryableSessionDataError(error) && attempt < SESSION_DATA_REQUEST_RETRY_COUNT) {
14170
+ await sleep(SESSION_DATA_REQUEST_RETRY_DELAY_MS * attempt);
14171
+ continue;
13546
14172
  }
14173
+ throw error;
13547
14174
  }
13548
- );
13549
- if (!response.ok) {
13550
- const errorText = await response.text();
13551
- throw new Error(
13552
- `Session data API Error (${response.status}): ${errorText}`
13553
- );
13554
14175
  }
13555
- return response.json();
14176
+ throw new Error(`Session data API Error: exhausted retries for ${url}`);
13556
14177
  }
13557
14178
  async collectAllSessionItems(listPage) {
13558
14179
  const items = [];
@@ -13610,6 +14231,17 @@ var EnvironmentSession = class extends Session {
13610
14231
  get: (name) => this.sessionDataRequest(
13611
14232
  `/heap/lists/${encodeURIComponent(name)}`
13612
14233
  )
14234
+ },
14235
+ variables: {
14236
+ list: (options = {}) => this.sessionDataRequest("/heap/variables", options),
14237
+ get: (name) => this.sessionDataRequest(
14238
+ `/heap/variables/${encodeURIComponent(name)}`
14239
+ ),
14240
+ delete: (name) => this.sessionDataRequest(
14241
+ `/heap/variables/${encodeURIComponent(name)}`,
14242
+ void 0,
14243
+ { method: "DELETE" }
14244
+ )
13613
14245
  }
13614
14246
  };
13615
14247
  }
@@ -13678,6 +14310,19 @@ var EnvironmentSession = class extends Session {
13678
14310
  async graphql(query, variables) {
13679
14311
  return this.environment.graphql(query, variables);
13680
14312
  }
14313
+ async searchRecords(query, options = {}) {
14314
+ return this.environment.searchRecords(query, options);
14315
+ }
14316
+ async mentionRecord(input) {
14317
+ return this.sessionDataRequest(
14318
+ "/records/mention",
14319
+ void 0,
14320
+ {
14321
+ method: "POST",
14322
+ body: input
14323
+ }
14324
+ );
14325
+ }
13681
14326
  async defineRelationship(options) {
13682
14327
  return this.environment.defineRelationship(options);
13683
14328
  }
@@ -13825,6 +14470,7 @@ var Granular = class _Granular {
13825
14470
  WebSocketCtor;
13826
14471
  onUnexpectedClose;
13827
14472
  onReconnectError;
14473
+ effectHostUrl;
13828
14474
  debugHttp = process.env.GRANULAR_DEBUG_HTTP === "1";
13829
14475
  /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
13830
14476
  sandboxEffects = /* @__PURE__ */ new Map();
@@ -13853,6 +14499,7 @@ var Granular = class _Granular {
13853
14499
  this.WebSocketCtor = options.WebSocketCtor;
13854
14500
  this.onUnexpectedClose = options.onUnexpectedClose;
13855
14501
  this.onReconnectError = options.onReconnectError;
14502
+ this.effectHostUrl = options.effectHostUrl;
13856
14503
  this.httpUrl = this.apiUrl.replace(/^wss:\/\//, "https://").replace(/^ws:\/\//, "http://").replace(/\/ws$/, "");
13857
14504
  }
13858
14505
  /**
@@ -14023,6 +14670,30 @@ var Granular = class _Granular {
14023
14670
  permissions: options.permissions || options.user?.permissions || []
14024
14671
  });
14025
14672
  }
14673
+ /**
14674
+ * Run a registered environment importer against an environment that was
14675
+ * opened outside this SDK instance, for example by a delegated browser flow.
14676
+ *
14677
+ * This uses the same setup-run and queued record-import plumbing as
14678
+ * `openEnvironment()`: importer stages, expected object counts, and queued
14679
+ * import counters remain visible through `environment.setup` and
14680
+ * `getRecordImportSummary()`.
14681
+ */
14682
+ async runEnvironmentImporterForEnvironment(environmentId, options = {}) {
14683
+ const environmentData = await this.environments.get(environmentId);
14684
+ const environment = this.bindEnvironmentHandle(environmentData);
14685
+ const requestedOntology = options.ontology || environmentData.ontologyId || environmentData.sandboxId;
14686
+ return this.runEnvironmentImporter(
14687
+ {
14688
+ environment: environmentData,
14689
+ requestedOntology,
14690
+ sandboxId: environmentData.sandboxId,
14691
+ subjectId: environmentData.subjectId,
14692
+ setupTriggerReason: options.reason || "new_environment"
14693
+ },
14694
+ environment
14695
+ );
14696
+ }
14026
14697
  resolveRequestedTag(options, methodName) {
14027
14698
  const tag = options.tag?.trim() || options.tagName?.trim() || options.environment?.trim();
14028
14699
  if (!tag) {
@@ -14266,15 +14937,25 @@ var Granular = class _Granular {
14266
14937
  return ontologyImporter;
14267
14938
  }
14268
14939
  async maybeRunEnvironmentImporter(resolved, environment) {
14269
- if (!resolved.setupTriggerReason) {
14270
- return;
14940
+ const setupTriggerReason = resolved.setupTriggerReason;
14941
+ if (!setupTriggerReason) {
14942
+ return null;
14271
14943
  }
14944
+ return this.runEnvironmentImporter(
14945
+ {
14946
+ ...resolved,
14947
+ setupTriggerReason
14948
+ },
14949
+ environment
14950
+ );
14951
+ }
14952
+ async runEnvironmentImporter(resolved, environment) {
14272
14953
  const importer = this.resolveEnvironmentImporter(
14273
14954
  resolved.requestedOntology,
14274
14955
  resolved.sandboxId
14275
14956
  );
14276
14957
  if (!importer) {
14277
- return;
14958
+ return null;
14278
14959
  }
14279
14960
  const setupRun = await this.request(
14280
14961
  `/control/environments/${environment.environmentId}/setup-runs`,
@@ -14314,16 +14995,24 @@ var Granular = class _Granular {
14314
14995
  },
14315
14996
  importRecords: async (records, options) => environment.enqueueRecordImport(records, {
14316
14997
  batchSize: options?.batchSize,
14998
+ writeMode: options?.writeMode,
14317
14999
  setupRunId
14318
15000
  })
14319
15001
  };
14320
15002
  try {
14321
15003
  await importer(importerContext);
14322
- await updateSetupRun({ markHookCompleted: true });
15004
+ const completedSetupRun = await this.request(
15005
+ `/control/environment-setup-runs/${setupRunId}`,
15006
+ {
15007
+ method: "PATCH",
15008
+ body: JSON.stringify({ markHookCompleted: true })
15009
+ }
15010
+ );
14323
15011
  const refreshedEnvironment = await this.environments.get(
14324
15012
  environment.environmentId
14325
15013
  );
14326
15014
  environment.syncEnvironmentData(refreshedEnvironment);
15015
+ return completedSetupRun;
14327
15016
  } catch (error) {
14328
15017
  await updateSetupRun({
14329
15018
  status: "failed",
@@ -14371,27 +15060,45 @@ var Granular = class _Granular {
14371
15060
  return effects;
14372
15061
  }
14373
15062
  serializeEffect(effect) {
14374
- return {
15063
+ const serialized = {
14375
15064
  effectKey: computeEffectKey2(effect),
14376
15065
  name: effect.name,
14377
15066
  description: effect.description,
14378
15067
  inputSchema: effect.inputSchema,
14379
- outputSchema: effect.outputSchema,
14380
15068
  stability: effect.stability || "stable",
14381
- provenance: effect.provenance || { source: "custom" },
14382
- tags: effect.tags,
14383
- className: effect.className,
14384
- static: effect.static,
14385
- versionSelector: effect.versionSelector
15069
+ provenance: effect.provenance || { source: "custom" }
14386
15070
  };
15071
+ if (effect.outputSchema !== void 0) {
15072
+ serialized.outputSchema = effect.outputSchema;
15073
+ }
15074
+ if (effect.tags !== void 0) {
15075
+ serialized.tags = effect.tags;
15076
+ }
15077
+ if (effect.className !== void 0) {
15078
+ serialized.className = effect.className;
15079
+ }
15080
+ if (effect.static !== void 0) {
15081
+ serialized.static = effect.static;
15082
+ }
15083
+ if (effect.versionSelector !== void 0) {
15084
+ serialized.versionSelector = effect.versionSelector;
15085
+ }
15086
+ if (effect.metamodels !== void 0) {
15087
+ serialized.metamodels = effect.metamodels;
15088
+ }
15089
+ return serialized;
14387
15090
  }
14388
15091
  async publishSandboxEffectCatalog(host) {
14389
15092
  const effects = Array.from(
14390
15093
  this.getSandboxEffectMap(host.sandboxId).values()
14391
15094
  ).map((effect) => this.serializeEffect(effect));
14392
- const result = await host.wsClient.call("effects.publishCatalog", {
14393
- effects
14394
- });
15095
+ const result = await withTimeout(
15096
+ host.wsClient.call("effects.publishCatalog", {
15097
+ effects
15098
+ }),
15099
+ EFFECT_CATALOG_SYNC_TIMEOUT_MS,
15100
+ `effects.publishCatalog for sandbox ${host.sandboxId}`
15101
+ );
14395
15102
  const acceptedCount = typeof result?.acceptedCount === "number" ? result.acceptedCount : 0;
14396
15103
  const rejected = Array.isArray(result?.rejected) ? result.rejected : [];
14397
15104
  if (acceptedCount === 0 && rejected.length > 0) {
@@ -14410,8 +15117,26 @@ var Granular = class _Granular {
14410
15117
  }
14411
15118
  }
14412
15119
  async syncSandboxEffectCatalog(sandboxId) {
14413
- const host = await this.ensureSandboxEffectHost(sandboxId);
14414
- await this.publishSandboxEffectCatalog(host);
15120
+ let lastError;
15121
+ for (let attempt = 1; attempt <= EFFECT_CATALOG_SYNC_RETRY_COUNT; attempt += 1) {
15122
+ try {
15123
+ const host = await this.ensureSandboxEffectHost(sandboxId);
15124
+ await this.publishSandboxEffectCatalog(host);
15125
+ return;
15126
+ } catch (error) {
15127
+ lastError = error;
15128
+ this.disconnectSandboxEffectHost(sandboxId);
15129
+ if (attempt === EFFECT_CATALOG_SYNC_RETRY_COUNT || !isRetryableEffectRegistrationError(error)) {
15130
+ throw error;
15131
+ }
15132
+ console.warn(
15133
+ `[Granular] Retrying effect registration for sandbox ${sandboxId} after transient failure (${attempt}/${EFFECT_CATALOG_SYNC_RETRY_COUNT - 1} retries used):`,
15134
+ error
15135
+ );
15136
+ await sleep(EFFECT_CATALOG_SYNC_RETRY_DELAY_MS * attempt);
15137
+ }
15138
+ }
15139
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
14415
15140
  }
14416
15141
  recoverEffectHost(host, error) {
14417
15142
  if (host.recovering) {
@@ -14504,7 +15229,8 @@ var Granular = class _Granular {
14504
15229
  this.apiUrl,
14505
15230
  sandboxId,
14506
15231
  effectClientId,
14507
- clientId
15232
+ clientId,
15233
+ this.effectHostUrl
14508
15234
  ),
14509
15235
  sessionId: `effect-host:${effectClientId}`,
14510
15236
  token: this.apiKey,
@@ -14540,7 +15266,11 @@ var Granular = class _Granular {
14540
15266
  wsClient.on("disconnect", () => {
14541
15267
  this.stopEffectHostHeartbeat(host);
14542
15268
  });
14543
- await wsClient.connect();
15269
+ await withTimeout(
15270
+ wsClient.connect(),
15271
+ EFFECT_HOST_CONNECT_TIMEOUT_MS,
15272
+ `effect host WebSocket connect for sandbox ${sandboxId}`
15273
+ );
14544
15274
  await this.synchronizeEffectHost(host);
14545
15275
  this.sandboxEffectHosts.set(sandboxId, host);
14546
15276
  return host;
@@ -14663,7 +15393,7 @@ var Granular = class _Granular {
14663
15393
  /**
14664
15394
  * Ensure a permission profile exists for a sandbox, creating it if needed.
14665
15395
  * If profileName matches an existing profile name, returns its ID.
14666
- * Otherwise, creates a new profile with default allow-all rules.
15396
+ * Otherwise, creates a v1 source-profile file shape with an allow default.
14667
15397
  */
14668
15398
  async ensurePermissionProfile(sandboxId, profileName) {
14669
15399
  try {
@@ -14677,8 +15407,11 @@ var Granular = class _Granular {
14677
15407
  const created = await this.permissionProfiles.create(sandboxId, {
14678
15408
  name: profileName,
14679
15409
  rules: {
14680
- effects: { allow: ["*"] },
14681
- resources: { allow: ["*"] }
15410
+ schemaVersion: 1,
15411
+ name: profileName,
15412
+ description: profileName === "allow-all" ? "Every declared action is visible unless a manifest policy denies it." : `Generated permission profile ${profileName}`,
15413
+ defaults: { actionPolicy: "allow" },
15414
+ actions: []
14682
15415
  }
14683
15416
  });
14684
15417
  return created.permissionProfileId;
@@ -14751,33 +15484,63 @@ var Granular = class _Granular {
14751
15484
  * Permission Profile management for sandboxes
14752
15485
  */
14753
15486
  get permissionProfiles() {
15487
+ const profileSourceFromRecord = (record) => {
15488
+ const profile = record.profile || record.rules || {};
15489
+ return {
15490
+ ...profile,
15491
+ schemaVersion: profile.schemaVersion || 1,
15492
+ name: profile.name || record.name,
15493
+ description: profile.description || record.description
15494
+ };
15495
+ };
14754
15496
  return {
14755
15497
  list: async (sandboxId) => {
14756
15498
  const result = await this.request(
14757
- `/control/sandboxes/${sandboxId}/permission-profiles`
15499
+ `/control/sandboxes/${sandboxId}/permission-profile-sources`
14758
15500
  );
14759
15501
  return result.items;
14760
15502
  },
14761
15503
  get: async (sandboxId, profileId) => {
14762
- return this.request(
14763
- `/control/sandboxes/${sandboxId}/permission-profiles/${profileId}`
15504
+ const result = await this.request(
15505
+ `/control/sandboxes/${sandboxId}/permission-profile-sources`
15506
+ );
15507
+ const profile = result.items.find(
15508
+ (item) => item.permissionProfileId === profileId || item.name === profileId
14764
15509
  );
15510
+ if (!profile) {
15511
+ throw new Error(`Permission profile source not found: ${profileId}`);
15512
+ }
15513
+ return profile;
14765
15514
  },
14766
15515
  create: async (sandboxId, data) => {
14767
- return this.request(
14768
- `/control/sandboxes/${sandboxId}/permission-profiles`,
15516
+ const profile = {
15517
+ ...data.rules,
15518
+ schemaVersion: 1,
15519
+ name: data.name
15520
+ };
15521
+ const existingProfiles = await this.permissionProfiles.list(sandboxId);
15522
+ const profiles = [
15523
+ ...existingProfiles.filter((existing) => existing.name !== data.name).map((existing) => profileSourceFromRecord(existing)),
15524
+ profile
15525
+ ];
15526
+ const result = await this.request(
15527
+ `/control/sandboxes/${sandboxId}/permission-profile-sources`,
14769
15528
  {
14770
- method: "POST",
14771
- body: JSON.stringify(data)
15529
+ method: "PUT",
15530
+ body: JSON.stringify({ profiles })
14772
15531
  }
14773
15532
  );
15533
+ const synced = result.items.find((item) => item.name === data.name) || result.items[0];
15534
+ if (!synced) {
15535
+ throw new Error(
15536
+ `Permission profile source sync did not return ${data.name}`
15537
+ );
15538
+ }
15539
+ return synced;
14774
15540
  },
14775
- delete: async (sandboxId, profileId) => {
14776
- return this.request(
14777
- `/control/sandboxes/${sandboxId}/permission-profiles/${profileId}`,
14778
- {
14779
- method: "DELETE"
14780
- }
15541
+ delete: async (_sandboxId, _profileId) => {
15542
+ throw new Error(
15543
+ "Permission profile sources are updated by syncing the desired source set."
14781
15544
  );
14782
15545
  }
14783
15546
  };
@@ -15033,6 +15796,85 @@ var Granular = class _Granular {
15033
15796
  };
15034
15797
 
15035
15798
  // src/agent-harness.ts
15799
+ var DEFAULT_IGNORED_REASONING_COMMENT_DIRECTIVES = [
15800
+ /^@ts-ignore\b/i,
15801
+ /^@ts-expect-error\b/i,
15802
+ /^eslint-[\w-]+\b/i,
15803
+ /^biome-ignore\b/i,
15804
+ /^prettier-ignore\b/i,
15805
+ /^istanbul ignore\b/i
15806
+ ];
15807
+ var DEFAULT_LOW_SIGNAL_REASONING_LINES = [
15808
+ /^running\.?$/i,
15809
+ /^working\.?$/i,
15810
+ /^thinking\.?$/i,
15811
+ /^generating(?: code)?\.?$/i,
15812
+ /^starting(?: execution)?\.?$/i
15813
+ ];
15814
+ function parseReasoningCommentLine(line, options = {}) {
15815
+ const trimmed = line.trimStart();
15816
+ if (!trimmed.startsWith("//")) return null;
15817
+ const text = trimmed.replace(/^\/\/\s?/, "").trim();
15818
+ if (!text) return { kind: "ignored" };
15819
+ const ignoredDirectives = options.ignoredCommentDirectives || DEFAULT_IGNORED_REASONING_COMMENT_DIRECTIVES;
15820
+ if (ignoredDirectives.some((pattern) => pattern.test(text))) {
15821
+ return { kind: "ignored" };
15822
+ }
15823
+ const lowSignalLines = options.lowSignalReasoningLines || DEFAULT_LOW_SIGNAL_REASONING_LINES;
15824
+ if (lowSignalLines.some((pattern) => pattern.test(text))) {
15825
+ return { kind: "ignored" };
15826
+ }
15827
+ return { kind: "reasoning", text };
15828
+ }
15829
+ function consumeGranularReasoningTraceChunk(buffer, chunk, options = {}) {
15830
+ let text = buffer + chunk;
15831
+ let visibleText = "";
15832
+ const reasoningLines = [];
15833
+ while (true) {
15834
+ const newlineIndex = text.indexOf("\n");
15835
+ if (newlineIndex === -1) break;
15836
+ const rawLine = text.slice(0, newlineIndex);
15837
+ text = text.slice(newlineIndex + 1);
15838
+ const comment = parseReasoningCommentLine(
15839
+ rawLine.replace(/\r$/, ""),
15840
+ options
15841
+ );
15842
+ if (comment?.kind === "reasoning") {
15843
+ reasoningLines.push(comment.text);
15844
+ } else if (comment?.kind === "ignored") {
15845
+ continue;
15846
+ } else {
15847
+ visibleText += `${rawLine}
15848
+ `;
15849
+ }
15850
+ }
15851
+ if (options.final && text.length > 0) {
15852
+ const comment = parseReasoningCommentLine(text.replace(/\r$/, ""), options);
15853
+ if (comment?.kind === "reasoning") {
15854
+ reasoningLines.push(comment.text);
15855
+ text = "";
15856
+ } else if (comment?.kind === "ignored") {
15857
+ text = "";
15858
+ } else {
15859
+ visibleText += text;
15860
+ text = "";
15861
+ }
15862
+ }
15863
+ return { buffer: text, visibleText, reasoningLines };
15864
+ }
15865
+ function consumeGranularReasoningOnlyChunk(buffer, chunk, options = {}) {
15866
+ const result = consumeGranularReasoningTraceChunk(buffer, chunk, options);
15867
+ return {
15868
+ buffer: result.buffer,
15869
+ reasoningLines: result.reasoningLines
15870
+ };
15871
+ }
15872
+ function stripGranularReasoningTrace(text, options = {}) {
15873
+ return consumeGranularReasoningTraceChunk("", text, {
15874
+ ...options,
15875
+ final: true
15876
+ }).visibleText.trim();
15877
+ }
15036
15878
  function asRecord4(value) {
15037
15879
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
15038
15880
  return value;
@@ -15056,21 +15898,8 @@ function uniqueStrings(values, maxCount) {
15056
15898
  }
15057
15899
  return output;
15058
15900
  }
15059
- function formatScalar(value) {
15060
- if (typeof value === "string") return JSON.stringify(value);
15061
- if (typeof value === "number" || typeof value === "boolean")
15062
- return String(value);
15063
- if (value === null) return "null";
15064
- return "unknown";
15065
- }
15066
- function describeHeapEntry(entry, previewFieldLimit = 3) {
15067
- const headline = entry.label || entry.id || entry.path || "Unknown";
15068
- const pathLabel = entry.path && entry.path !== headline ? ` <${entry.path}>` : "";
15069
- const classLabel = entry.className || "unknown";
15070
- const preview = asArray2(entry.fields).filter(
15071
- (field) => field?.name && field.name !== "_realId" && field.name !== "real_id"
15072
- ).slice(0, previewFieldLimit).map((field) => `${field.name}=${formatScalar(field.value)}`).join(", ");
15073
- return preview ? `${headline}${pathLabel} [${classLabel}] ${preview}` : `${headline}${pathLabel} [${classLabel}]`;
15901
+ function renderConstBlock(name, value) {
15902
+ return `const ${name} = ${JSON.stringify(value, null, 2)} as const;`;
15074
15903
  }
15075
15904
  function hashString(value) {
15076
15905
  if (!value) return null;
@@ -15081,97 +15910,248 @@ function hashString(value) {
15081
15910
  }
15082
15911
  return (hash >>> 0).toString(16).padStart(8, "0");
15083
15912
  }
15084
- function hasSubstantiveAwaitAfterPrompt(code, marker) {
15085
- const startIndex = code.indexOf(marker);
15086
- if (startIndex === -1) return true;
15087
- const segment = code.slice(startIndex + marker.length);
15088
- const callMatches = segment.matchAll(
15089
- /await\s+([A-Za-z0-9_$.]+)\.([A-Za-z0-9_]+)\s*\(/g
15913
+ function findUndefinedSimpleTemplateIdentifier(source) {
15914
+ const declared = /* @__PURE__ */ new Set();
15915
+ const globals = /* @__PURE__ */ new Set([
15916
+ "Array",
15917
+ "Boolean",
15918
+ "Date",
15919
+ "JSON",
15920
+ "Math",
15921
+ "Number",
15922
+ "Object",
15923
+ "Promise",
15924
+ "String",
15925
+ "undefined",
15926
+ "null",
15927
+ "true",
15928
+ "false"
15929
+ ]);
15930
+ for (const match of source.matchAll(/import\s*\{([^}]+)\}\s*from/g)) {
15931
+ for (const part of match[1].split(",")) {
15932
+ const aliasMatch = part.trim().match(/\bas\s+([A-Za-z_$][\w$]*)$/);
15933
+ const nameMatch = part.trim().match(/^([A-Za-z_$][\w$]*)/);
15934
+ const name = aliasMatch?.[1] || nameMatch?.[1];
15935
+ if (name) declared.add(name);
15936
+ }
15937
+ }
15938
+ for (const match of source.matchAll(
15939
+ /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b/g
15940
+ )) {
15941
+ declared.add(match[1]);
15942
+ }
15943
+ for (const match of source.matchAll(
15944
+ /\bfor\s*(?:await\s*)?\(\s*(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s+of\b/g
15945
+ )) {
15946
+ declared.add(match[1]);
15947
+ }
15948
+ for (const match of source.matchAll(
15949
+ /\bcatch\s*\(\s*([A-Za-z_$][\w$]*)\s*\)/g
15950
+ )) {
15951
+ declared.add(match[1]);
15952
+ }
15953
+ for (const match of source.matchAll(
15954
+ /\(\s*([A-Za-z_$][\w$]*)\s*(?:,\s*[A-Za-z_$][\w$]*)*\s*\)\s*=>/g
15955
+ )) {
15956
+ declared.add(match[1]);
15957
+ }
15958
+ for (const match of source.matchAll(/\b([A-Za-z_$][\w$]*)\s*=>/g)) {
15959
+ declared.add(match[1]);
15960
+ }
15961
+ for (const match of source.matchAll(/\$\{\s*([A-Za-z_$][\w$]*)\s*\}/g)) {
15962
+ const identifier = match[1];
15963
+ if (!declared.has(identifier) && !globals.has(identifier)) {
15964
+ return identifier;
15965
+ }
15966
+ }
15967
+ return null;
15968
+ }
15969
+ function getGeneratedJobSyntaxError(source) {
15970
+ const withoutImports = source.replace(
15971
+ /^\s*import\s+[\s\S]*?\s+from\s+["'][^"']+["']\s*;?\s*$/gm,
15972
+ ""
15090
15973
  );
15091
- for (const match of callMatches) {
15092
- const receiver = match[1] || "";
15093
- const method = match[2] || "";
15094
- if (receiver === "loop" || receiver === "heap") continue;
15095
- if (method.startsWith("get_") || method.startsWith("get")) continue;
15096
- return true;
15974
+ try {
15975
+ new Function(`return (async () => {
15976
+ ${withoutImports}
15977
+ });`);
15978
+ return null;
15979
+ } catch (error) {
15980
+ return error instanceof Error ? error.message : String(error);
15981
+ }
15982
+ }
15983
+ function hasNestedTemplateLiteralExpression(source) {
15984
+ let inString = null;
15985
+ let escaped = false;
15986
+ const templateStack = [];
15987
+ for (let index = 0; index < source.length; index += 1) {
15988
+ const char = source[index];
15989
+ const next = source[index + 1] || "";
15990
+ if (escaped) {
15991
+ escaped = false;
15992
+ continue;
15993
+ }
15994
+ if (char === "\\") {
15995
+ escaped = true;
15996
+ continue;
15997
+ }
15998
+ if (inString === "'" || inString === '"') {
15999
+ if (char === inString) inString = null;
16000
+ continue;
16001
+ }
16002
+ if (inString === "`") {
16003
+ const current = templateStack[templateStack.length - 1];
16004
+ if (char === "`") {
16005
+ if (current?.expressionDepth && current.expressionDepth > 0) {
16006
+ return true;
16007
+ }
16008
+ templateStack.pop();
16009
+ if (templateStack.length === 0) inString = null;
16010
+ continue;
16011
+ }
16012
+ if (char === "$" && next === "{") {
16013
+ if (current) current.expressionDepth += 1;
16014
+ index += 1;
16015
+ continue;
16016
+ }
16017
+ if (char === "}" && current?.expressionDepth) {
16018
+ current.expressionDepth -= 1;
16019
+ }
16020
+ continue;
16021
+ }
16022
+ if (char === "'" || char === '"') {
16023
+ inString = char;
16024
+ continue;
16025
+ }
16026
+ if (char === "`") {
16027
+ inString = "`";
16028
+ templateStack.push({ expressionDepth: 0 });
16029
+ }
15097
16030
  }
15098
16031
  return false;
15099
16032
  }
15100
- function reviewGeneratedJobCode(code) {
16033
+ function reviewGeneratedJobCode(code, _options = {}) {
15101
16034
  const normalized = typeof code === "string" ? code : "";
15102
- if (!normalized.trim()) return [];
15103
16035
  const issues = [];
16036
+ if (!normalized.trim()) {
16037
+ return issues;
16038
+ }
15104
16039
  if (/require\s*\(\s*['"]\.\/sandbox-tools['"]\s*\)/.test(normalized)) {
15105
16040
  issues.push({
15106
16041
  code: "commonjs_require",
15107
16042
  severity: "error",
15108
- 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."
15109
- });
15110
- }
15111
- const placeholderPatterns = [
15112
- /ready to make the change next/i,
15113
- /ready to .* next/i,
15114
- /ready to .* now/i,
15115
- /i can make the change now/i,
15116
- /i can do that next/i,
15117
- /i'?m ready to continue/i,
15118
- /have your approval .* ready to make/i,
15119
- /approved\./i
15120
- ];
15121
- if (normalized.includes("await loop.confirm(")) {
15122
- const postConfirm = normalized.slice(
15123
- normalized.indexOf("await loop.confirm(")
15124
- );
15125
- const hasPlaceholder = placeholderPatterns.some(
15126
- (pattern) => pattern.test(postConfirm)
15127
- );
15128
- const hasSubstantiveAwait = hasSubstantiveAwaitAfterPrompt(
15129
- normalized,
15130
- "await loop.confirm("
15131
- );
15132
- if (!hasSubstantiveAwait || hasPlaceholder) {
15133
- issues.push({
15134
- code: "placeholder_after_confirm",
15135
- severity: "error",
15136
- 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.'"
15137
- });
15138
- }
16043
+ message: "Use ESM imports from './sandbox-tools' instead of require('./sandbox-tools')."
16044
+ });
15139
16045
  }
15140
- if (normalized.includes("await loop.ask_user(")) {
15141
- const postPrompt = normalized.slice(
15142
- normalized.indexOf("await loop.ask_user(")
15143
- );
15144
- const hasPlaceholder = placeholderPatterns.some(
15145
- (pattern) => pattern.test(postPrompt)
15146
- );
15147
- const hasSubstantiveAwait = hasSubstantiveAwaitAfterPrompt(
15148
- normalized,
15149
- "await loop.ask_user("
15150
- );
15151
- if (hasPlaceholder && !hasSubstantiveAwait) {
15152
- issues.push({
15153
- code: "placeholder_after_ask_user",
15154
- severity: "error",
15155
- 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."
15156
- });
15157
- }
16046
+ if (/\bprocess\.exit\s*\(/.test(normalized)) {
16047
+ issues.push({
16048
+ code: "process_exit",
16049
+ severity: "error",
16050
+ message: "Generated jobs must not call process.exit(...). Return from the job or emit a runtime message instead."
16051
+ });
16052
+ }
16053
+ if (/\bawait\s+import\s*\(\s*['"]\.\/sandbox-tools['"]\s*\)/.test(normalized)) {
16054
+ issues.push({
16055
+ code: "dynamic_import_in_job",
16056
+ severity: "error",
16057
+ message: "Import sandbox tools with a static top-level import from './sandbox-tools'; do not use dynamic import for runtime tools."
16058
+ });
16059
+ }
16060
+ if (hasNestedTemplateLiteralExpression(normalized)) {
16061
+ issues.push({
16062
+ code: "nested_template_literal_in_job",
16063
+ severity: "error",
16064
+ message: "Avoid nested template literals inside template expressions. Precompute conditional text in variables or use simpler string construction."
16065
+ });
16066
+ }
16067
+ const syntaxError = getGeneratedJobSyntaxError(normalized);
16068
+ if (syntaxError) {
16069
+ issues.push({
16070
+ code: "syntax_error_in_job",
16071
+ severity: "error",
16072
+ message: `The generated job has a JavaScript syntax error before runtime execution: ${syntaxError}.`
16073
+ });
16074
+ }
16075
+ if (/[\u2018-\u201F]/.test(normalized)) {
16076
+ issues.push({
16077
+ code: "syntax_error_in_job",
16078
+ severity: "error",
16079
+ message: "Use plain ASCII quotes and apostrophes in generated job strings."
16080
+ });
16081
+ }
16082
+ const undefinedTemplateIdentifier = findUndefinedSimpleTemplateIdentifier(normalized);
16083
+ if (undefinedTemplateIdentifier) {
16084
+ issues.push({
16085
+ code: "undefined_template_identifier",
16086
+ severity: "error",
16087
+ message: `The template literal references \`${undefinedTemplateIdentifier}\`, but that identifier is not declared in the generated job.`
16088
+ });
16089
+ }
16090
+ if (/\{\s*\.\.\.[A-Za-z_$][\w$]*/.test(normalized)) {
16091
+ issues.push({
16092
+ code: "object_spread_in_job",
16093
+ severity: "error",
16094
+ message: "Avoid object spread in generated jobs until the backend runtime transform can validate it structurally."
16095
+ });
16096
+ }
16097
+ if (/\bloop\./.test(normalized) && !/import\s*\{[^}]*\bloop\b[^}]*\}\s*from\s*['"]\.\/sandbox-tools['"]/.test(
16098
+ normalized
16099
+ )) {
16100
+ issues.push({
16101
+ code: "missing_loop_import",
16102
+ severity: "error",
16103
+ message: "The job calls loop.* but does not import loop from './sandbox-tools'."
16104
+ });
16105
+ }
16106
+ const bareLoopHelperImport = normalized.match(
16107
+ /import\s*\{[^}]*\b(ask_user|confirm|open_decision|close_decision|create_task|update_task|complete_task|close_loop)\b[^}]*\}\s*from\s*['"]\.\/sandbox-tools['"]/
16108
+ );
16109
+ if (bareLoopHelperImport) {
16110
+ issues.push({
16111
+ code: "bare_loop_helper_import",
16112
+ severity: "error",
16113
+ message: "Workflow helpers are exposed on the imported `loop` object. Import `loop` from './sandbox-tools' and call helpers as `loop.create_task(...)`, `loop.open_decision(...)`, `loop.confirm(...)`, etc.; do not import them as bare functions."
16114
+ });
16115
+ }
16116
+ if (/\bloop\.open_decision\s*\(\s*\{[\s\S]*?\boptions\s*:/.test(normalized)) {
16117
+ issues.push({
16118
+ code: "loop_helper_contract",
16119
+ severity: "error",
16120
+ message: "loop.open_decision(...) must use `candidates: [...]`, not `options: [...]`. Every candidate must include a string `id`."
16121
+ });
15158
16122
  }
15159
- const hasConversationalReturn = /return\s+[`'"]/.test(normalized) || /\breply\s*:/.test(normalized) || /\bagent_message\s*\(/.test(normalized) || /\bagent_text_message\s*\(/.test(normalized);
15160
- const returnsObjectLiteral = /return\s+\{[\s\S]*?\}/.test(normalized);
15161
- const returnsShowPayload = /return\s+\{[\s\S]*?\bshow\s*:/.test(normalized);
15162
- const closesLoop = /loop\.close_loop\s*\(/.test(normalized);
15163
- if (!hasConversationalReturn && returnsObjectLiteral && !closesLoop) {
16123
+ if (/\bloop\.close_decision\s*\(\s*\{[\s\S]*?\bselected\s*:/.test(normalized)) {
15164
16124
  issues.push({
15165
- code: "missing_user_reply",
16125
+ code: "loop_helper_contract",
15166
16126
  severity: "error",
15167
- 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."
16127
+ message: "loop.close_decision(...) must use `selectedId`, not `selected`."
15168
16128
  });
15169
16129
  }
15170
- if (returnsShowPayload) {
16130
+ if (/\bloop\.(?:create_task|update_task|complete_task)\s*\(\s*\{[\s\S]*?\bid\s*:/.test(
16131
+ normalized
16132
+ )) {
15171
16133
  issues.push({
15172
- code: "return_show_not_for_ui",
16134
+ code: "loop_helper_contract",
15173
16135
  severity: "error",
15174
- 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."
16136
+ message: "Loop task helpers must use `taskId`, not `id`, for explicit task identifiers."
16137
+ });
16138
+ }
16139
+ if (/\bconsole\.log\s*\(\s*JSON\.stringify\s*\(\s*\{[\s\S]*?\b(?:action|reply|code)\s*:/.test(
16140
+ normalized
16141
+ )) {
16142
+ issues.push({
16143
+ code: "stdout_json_reply",
16144
+ severity: "error",
16145
+ message: "Do not print JSON chat envelopes from generated jobs; use runtime messaging or return a plain result."
16146
+ });
16147
+ }
16148
+ if (/\breturn\s+\{[\s\S]*?\baction\s*:\s*['"]reply['"][\s\S]*?\breply\s*:/.test(
16149
+ normalized
16150
+ )) {
16151
+ issues.push({
16152
+ code: "return_chat_payload",
16153
+ severity: "error",
16154
+ message: "Do not return chat envelopes like { action, reply, code } from generated jobs; return a plain value or use runtime messaging."
15175
16155
  });
15176
16156
  }
15177
16157
  return issues;
@@ -15230,15 +16210,40 @@ function collectConversationReferents(liveDoc) {
15230
16210
  const ts = Number(message.ts) || 0;
15231
16211
  const messageId = typeof message.id === "string" ? message.id : void 0;
15232
16212
  const jobId = typeof message.jobId === "string" ? message.jobId : void 0;
15233
- for (const entryPath of uniqueStrings(asArray2(show.entryPaths))) {
16213
+ const entryPaths = uniqueStrings(asArray2(show.entryPaths));
16214
+ const entryClassCounts = /* @__PURE__ */ new Map();
16215
+ const entryMetadata = entryPaths.map((entryPath) => {
15234
16216
  const entry = asRecord4(entriesByPath[entryPath]);
16217
+ const className = typeof entry?.className === "string" ? entry.className : void 0;
16218
+ if (className) {
16219
+ entryClassCounts.set(
16220
+ className,
16221
+ (entryClassCounts.get(className) || 0) + 1
16222
+ );
16223
+ }
16224
+ return { entryPath, entry, className };
16225
+ });
16226
+ const displayGroupId = entryMetadata.length > 1 ? `message:${messageId || jobId || ts}:entries` : void 0;
16227
+ for (const [
16228
+ index,
16229
+ { entryPath, entry, className }
16230
+ ] of entryMetadata.entries()) {
15235
16231
  pushReferent({
15236
16232
  id: `entry:${entryPath}`,
15237
16233
  kind: "entry",
15238
16234
  ref: entryPath,
16235
+ role: "assistant",
16236
+ source: "heap_objects",
15239
16237
  entryPath,
15240
- className: typeof entry?.className === "string" ? entry.className : void 0,
16238
+ recordId: typeof entry?.id === "string" ? entry.id : void 0,
16239
+ className,
15241
16240
  label: typeof entry?.label === "string" && entry.label.trim() ? entry.label.trim() : typeof entry?.id === "string" && entry.id.trim() ? entry.id.trim() : entryPath,
16241
+ ...displayGroupId ? {
16242
+ displayGroupId,
16243
+ displayGroupIndex: index,
16244
+ displayGroupSize: entryMetadata.length,
16245
+ ...className && (entryClassCounts.get(className) || 0) > 1 ? { displayGroupSameTypeSize: entryClassCounts.get(className) } : {}
16246
+ } : {},
15242
16247
  messageId,
15243
16248
  jobId,
15244
16249
  ts
@@ -15250,6 +16255,8 @@ function collectConversationReferents(liveDoc) {
15250
16255
  id: `list:${listName}`,
15251
16256
  kind: "list",
15252
16257
  ref: listName,
16258
+ role: "assistant",
16259
+ source: "heap_objects",
15253
16260
  listName,
15254
16261
  className: typeof list?.className === "string" ? list.className : void 0,
15255
16262
  count: Array.isArray(list?.paths) ? list.paths.length : null,
@@ -15270,9 +16277,12 @@ function collectConversationReferents(liveDoc) {
15270
16277
  id: `variable:${variableName}`,
15271
16278
  kind: "variable",
15272
16279
  ref: variableName,
16280
+ role: "assistant",
16281
+ source: "heap_objects",
15273
16282
  variableName,
15274
16283
  variableKind: typeof variable?.kind === "string" ? variable.kind : void 0,
15275
16284
  entryPath,
16285
+ recordId: typeof entry?.id === "string" ? entry.id : void 0,
15276
16286
  listName,
15277
16287
  className: typeof variable?.className === "string" ? variable.className : typeof entry?.className === "string" ? entry.className : typeof list?.className === "string" ? list.className : void 0,
15278
16288
  label: typeof entry?.label === "string" && entry.label.trim() ? entry.label.trim() : typeof entry?.id === "string" && entry.id.trim() ? entry.id.trim() : null,
@@ -15293,18 +16303,24 @@ function projectConversationReferentFocus(liveDoc) {
15293
16303
  const entryPaths = [];
15294
16304
  const listNames = [];
15295
16305
  const variableNames = [];
15296
- for (const referent of referents.slice(0, 8)) {
15297
- if (referent.kind === "entry" && typeof referent.entryPath === "string") {
16306
+ let entryCount = 0;
16307
+ let listCount = 0;
16308
+ let variableCount = 0;
16309
+ for (const referent of referents) {
16310
+ if (referent.kind === "entry" && typeof referent.entryPath === "string" && entryCount < 8) {
16311
+ entryCount += 1;
15298
16312
  entryPaths.push(referent.entryPath);
15299
16313
  continue;
15300
16314
  }
15301
- if (referent.kind === "list" && typeof referent.listName === "string") {
16315
+ if (referent.kind === "list" && typeof referent.listName === "string" && listCount < 4) {
16316
+ listCount += 1;
15302
16317
  listNames.push(referent.listName);
15303
16318
  const list = asRecord4(listsByName[referent.listName]);
15304
16319
  entryPaths.push(...asArray2(list?.paths).slice(0, 4));
15305
16320
  continue;
15306
16321
  }
15307
- if (referent.kind === "variable" && typeof referent.variableName === "string") {
16322
+ if (referent.kind === "variable" && typeof referent.variableName === "string" && variableCount < 4) {
16323
+ variableCount += 1;
15308
16324
  variableNames.push(referent.variableName);
15309
16325
  if (typeof referent.entryPath === "string") {
15310
16326
  entryPaths.push(referent.entryPath);
@@ -15322,61 +16338,91 @@ function projectConversationReferentFocus(liveDoc) {
15322
16338
  variableNames: uniqueStrings(variableNames, 4)
15323
16339
  };
15324
16340
  }
15325
- function projectConversationReferentSummary(liveDoc) {
15326
- const referents = collectConversationReferents(liveDoc).slice(0, 8);
15327
- if (referents.length === 0) {
15328
- return "No recent referents recorded from prior assistant replies.";
15329
- }
15330
- const entryLines = [];
15331
- const listLines = [];
15332
- const variableLines = [];
16341
+ function selectConversationReferentsForPrompt(referents) {
16342
+ const selected = [];
16343
+ const seen = /* @__PURE__ */ new Set();
16344
+ let entryCount = 0;
16345
+ let listCount = 0;
16346
+ let variableCount = 0;
15333
16347
  for (const referent of referents) {
16348
+ if (!referent.kind || !referent.ref) continue;
16349
+ const key = `${referent.kind}:${referent.ref}`;
16350
+ if (seen.has(key)) continue;
16351
+ if (referent.kind === "entry") {
16352
+ if (entryCount >= 8) continue;
16353
+ entryCount += 1;
16354
+ } else if (referent.kind === "list") {
16355
+ if (listCount >= 4) continue;
16356
+ listCount += 1;
16357
+ } else if (referent.kind === "variable") {
16358
+ if (variableCount >= 4) continue;
16359
+ variableCount += 1;
16360
+ }
16361
+ seen.add(key);
16362
+ selected.push(referent);
16363
+ }
16364
+ return selected;
16365
+ }
16366
+ function projectConversationReferentSummary(liveDoc) {
16367
+ const referents = selectConversationReferentsForPrompt(
16368
+ collectConversationReferents(liveDoc)
16369
+ );
16370
+ const compact = referents.map((referent) => {
15334
16371
  if (referent.kind === "entry" && referent.entryPath) {
15335
- const label = referent.label || referent.entryPath;
15336
- const classLabel = referent.className || "unknown";
15337
- entryLines.push(`- ${label} <${referent.entryPath}> [${classLabel}]`);
15338
- continue;
16372
+ return {
16373
+ kind: "entry",
16374
+ role: referent.role || null,
16375
+ source: referent.source || null,
16376
+ path: referent.entryPath,
16377
+ id: referent.recordId || null,
16378
+ type: referent.className || "unknown",
16379
+ label: referent.label || referent.entryPath,
16380
+ group: referent.displayGroupId ? {
16381
+ id: referent.displayGroupId,
16382
+ index: typeof referent.displayGroupIndex === "number" ? referent.displayGroupIndex : null,
16383
+ size: typeof referent.displayGroupSize === "number" ? referent.displayGroupSize : null,
16384
+ sameTypeSize: typeof referent.displayGroupSameTypeSize === "number" ? referent.displayGroupSameTypeSize : null
16385
+ } : void 0
16386
+ };
16387
+ }
16388
+ if (referent.kind === "entry" && referent.recordId) {
16389
+ return {
16390
+ kind: "entry",
16391
+ role: referent.role || null,
16392
+ source: referent.source || null,
16393
+ id: referent.recordId,
16394
+ type: referent.className || "unknown",
16395
+ label: referent.label || referent.recordId
16396
+ };
15339
16397
  }
15340
16398
  if (referent.kind === "list" && referent.listName) {
15341
- const classLabel = referent.className || "unknown";
15342
- const countLabel = typeof referent.count === "number" ? referent.count : "?";
15343
- listLines.push(
15344
- `- ${referent.listName}: list<${classLabel}> -> ${countLabel} item(s)`
15345
- );
15346
- continue;
16399
+ return {
16400
+ kind: "list",
16401
+ role: referent.role || null,
16402
+ source: referent.source || null,
16403
+ name: referent.listName,
16404
+ type: referent.className || "unknown",
16405
+ count: typeof referent.count === "number" ? referent.count : null
16406
+ };
15347
16407
  }
15348
16408
  if (referent.kind === "variable" && referent.variableName) {
15349
- if (referent.variableKind === "entry" && referent.entryPath && referent.className) {
15350
- const label = referent.label || referent.entryPath;
15351
- variableLines.push(
15352
- `- ${referent.variableName}: entry<${referent.className}> -> ${label} <${referent.entryPath}>`
15353
- );
15354
- continue;
15355
- }
15356
- if (referent.variableKind === "list" && referent.listName && referent.className) {
15357
- const countLabel = typeof referent.count === "number" ? referent.count : "?";
15358
- variableLines.push(
15359
- `- ${referent.variableName}: list<${referent.className}> -> ${countLabel} item(s) via ${referent.listName}`
15360
- );
15361
- continue;
15362
- }
15363
- if (referent.variableKind === "scalar") {
15364
- variableLines.push(
15365
- `- ${referent.variableName}: scalar = ${formatScalar(referent.scalarValue)}`
15366
- );
15367
- continue;
15368
- }
15369
- variableLines.push(`- ${referent.variableName}`);
16409
+ return {
16410
+ kind: "variable",
16411
+ role: referent.role || null,
16412
+ source: referent.source || null,
16413
+ name: referent.variableName,
16414
+ valueKind: referent.variableKind || null,
16415
+ type: referent.className || null,
16416
+ path: referent.entryPath || null,
16417
+ list: referent.listName || null,
16418
+ label: referent.label || null,
16419
+ count: typeof referent.count === "number" ? referent.count : null,
16420
+ value: referent.variableKind === "scalar" ? referent.scalarValue ?? null : void 0
16421
+ };
15370
16422
  }
15371
- }
15372
- const lines = [];
15373
- lines.push("Entries:");
15374
- lines.push(...entryLines.length > 0 ? entryLines : ["- none"]);
15375
- lines.push("", "Lists:");
15376
- lines.push(...listLines.length > 0 ? listLines : ["- none"]);
15377
- lines.push("", "Variables:");
15378
- lines.push(...variableLines.length > 0 ? variableLines : ["- none"]);
15379
- return lines.join("\n");
16423
+ return null;
16424
+ }).filter(Boolean);
16425
+ return renderConstBlock("recentReferences", compact);
15380
16426
  }
15381
16427
  function getCurrentClosureId(liveDoc) {
15382
16428
  const loop = asRecord4(liveDoc?.loop);
@@ -15597,56 +16643,24 @@ function projectWorkflowFocus(liveDoc, pendingPrompts = [], options) {
15597
16643
  }
15598
16644
  function projectWorkflowSummary(liveDoc, pendingPrompts = [], options) {
15599
16645
  const focus = projectWorkflowFocus(liveDoc, pendingPrompts, options);
15600
- const lines = [];
15601
- lines.push("Workflow Boundary:");
15602
- if (focus.boundaryReason === "request_start") {
15603
- lines.push(
15604
- "- Start from work recorded after the current user request began."
15605
- );
15606
- } else if (focus.boundaryReason === "last_closed_loop" && focus.latestClosureId) {
15607
- lines.push(`- Start from work recorded after ${focus.latestClosureId}.`);
15608
- } else {
15609
- lines.push(
15610
- "- No prior closed loop recorded; use the latest user request as the boundary."
15611
- );
15612
- }
15613
- lines.push("", "Recent Actions:");
15614
- if (focus.recentActionSummary.length === 0) {
15615
- lines.push("- none");
15616
- } else {
15617
- for (const line of focus.recentActionSummary) {
15618
- lines.push(line.startsWith("- ") ? line : `- ${line}`);
15619
- }
15620
- }
15621
- lines.push("", "Working Set Hints:");
15622
- if (focus.variableNames.length === 0 && focus.listNames.length === 0 && focus.entryPaths.length === 0) {
15623
- lines.push("- none");
15624
- } else {
15625
- if (focus.variableNames.length > 0) {
15626
- lines.push(`- variables: ${focus.variableNames.join(", ")}`);
15627
- }
15628
- if (focus.listNames.length > 0) {
15629
- lines.push(`- lists: ${focus.listNames.join(", ")}`);
15630
- }
15631
- if (focus.entryPaths.length > 0) {
15632
- lines.push(`- entries: ${focus.entryPaths.join(", ")}`);
15633
- }
15634
- }
15635
- lines.push("", "Open Workflow Handles:");
15636
- if (focus.activeTaskIds.length === 0 && focus.openDecisionIds.length === 0 && focus.openPromptIds.length === 0) {
15637
- lines.push("- none");
15638
- } else {
15639
- if (focus.activeTaskIds.length > 0) {
15640
- lines.push(`- tasks: ${focus.activeTaskIds.join(", ")}`);
15641
- }
15642
- if (focus.openDecisionIds.length > 0) {
15643
- lines.push(`- decisions: ${focus.openDecisionIds.join(", ")}`);
15644
- }
15645
- if (focus.openPromptIds.length > 0) {
15646
- lines.push(`- prompts: ${focus.openPromptIds.join(", ")}`);
16646
+ return renderConstBlock("workflowContext", {
16647
+ boundary: {
16648
+ timestamp: focus.boundaryTimestamp,
16649
+ reason: focus.boundaryReason,
16650
+ latestClosureId: focus.latestClosureId || null
16651
+ },
16652
+ recentActions: focus.recentActionSummary,
16653
+ workingSet: {
16654
+ variables: focus.variableNames,
16655
+ lists: focus.listNames,
16656
+ entries: focus.entryPaths
16657
+ },
16658
+ openHandles: {
16659
+ tasks: focus.activeTaskIds,
16660
+ decisions: focus.openDecisionIds,
16661
+ prompts: focus.openPromptIds
15647
16662
  }
15648
- }
15649
- return lines.join("\n");
16663
+ });
15650
16664
  }
15651
16665
  function hasOpenPrompt(liveDoc, pendingPrompts) {
15652
16666
  if (pendingPrompts.length > 0) return true;
@@ -15667,7 +16681,6 @@ function getExclusivePromptTarget(pendingPrompts) {
15667
16681
  return prompt?.type === "input" ? prompt : null;
15668
16682
  }
15669
16683
  function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15670
- const lines = [];
15671
16684
  const loop = asRecord4(liveDoc?.loop);
15672
16685
  const boundary = getWorkflowBoundary(liveDoc, options);
15673
16686
  const tasks = toSortedRecords(loop?.tasksById).filter((task) => {
@@ -15689,22 +16702,12 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15689
16702
  5
15690
16703
  );
15691
16704
  const hiddenTaskCount = Math.max(0, activeTasks.length - visibleTasks.length);
15692
- lines.push("Tasks:");
15693
- if (visibleTasks.length === 0) {
15694
- lines.push("- none");
15695
- } else {
15696
- lines.push("- Reuse existing taskId values exactly as written below.");
15697
- for (const task of visibleTasks) {
15698
- const title = typeof task.title === "string" ? task.title : "Untitled task";
15699
- const taskId = typeof task.taskId === "string" ? task.taskId : "unknown";
15700
- const status = typeof task.status === "string" ? task.status : "pending";
15701
- const summary = typeof task.summary === "string" && task.summary.trim() ? ` \u2014 ${task.summary.trim()}` : "";
15702
- lines.push(`- [${status}] ${title} (${taskId})${summary}`);
15703
- }
15704
- if (hiddenTaskCount > 0) {
15705
- lines.push(`- ${hiddenTaskCount} more active task(s) omitted`);
15706
- }
15707
- }
16705
+ const compactTasks = visibleTasks.map((task) => ({
16706
+ id: typeof task.taskId === "string" ? task.taskId : "unknown",
16707
+ title: typeof task.title === "string" ? task.title : "Untitled task",
16708
+ status: typeof task.status === "string" ? task.status : "pending",
16709
+ summary: typeof task.summary === "string" && task.summary.trim() ? task.summary.trim() : null
16710
+ }));
15708
16711
  const decisions = toSortedRecords(loop?.decisionsById).filter((decision) => {
15709
16712
  const updatedAt = Number(decision.updatedAt) || Number(decision.createdAt) || 0;
15710
16713
  if (boundary.reason === "request_start") {
@@ -15718,33 +16721,29 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15718
16721
  (decision) => decision.status === "open"
15719
16722
  );
15720
16723
  const visibleDecisions = (openDecisions.length > 0 ? openDecisions : decisions.slice(0, 1)).slice(0, 3);
15721
- lines.push("", "Recent Decisions:");
15722
- if (visibleDecisions.length === 0) {
15723
- lines.push("- none");
15724
- } else {
15725
- lines.push("- Reuse existing decisionId values exactly as written below.");
15726
- for (const decision of visibleDecisions) {
15727
- const status = typeof decision.status === "string" ? decision.status : "resolved";
15728
- const title = typeof decision.title === "string" && decision.title.trim() ? decision.title.trim() : "Decision";
15729
- const decisionId = typeof decision.decisionId === "string" ? decision.decisionId : "unknown";
15730
- if (status === "open") {
15731
- const candidatePreview = asArray2(decision.candidates).slice(0, 3).map((candidate) => {
15732
- const record = asRecord4(candidate);
15733
- if (!record) return null;
15734
- const candidateId = typeof record.id === "string" ? record.id : "unknown";
15735
- const candidateLabel = typeof record.label === "string" && record.label.trim() ? record.label.trim() : candidateId;
15736
- return candidateLabel === candidateId ? candidateId : `${candidateLabel} (${candidateId})`;
15737
- }).filter((value) => Boolean(value)).join(", ");
15738
- lines.push(
15739
- `- [open] ${title} (${decisionId})${candidatePreview ? ` \u2014 candidates: ${candidatePreview}` : ""}`
15740
- );
15741
- } else {
15742
- const selected = asRecord4(decision.selected);
15743
- const label = typeof selected?.label === "string" ? selected.label : typeof selected?.id === "string" ? selected.id : "unknown";
15744
- lines.push(`- [resolved] ${title} (${decisionId}) -> ${label}`);
16724
+ const compactDecisions = visibleDecisions.map((decision) => {
16725
+ const status = typeof decision.status === "string" ? decision.status : "resolved";
16726
+ const selected = asRecord4(decision.selected);
16727
+ return {
16728
+ id: typeof decision.decisionId === "string" ? decision.decisionId : "unknown",
16729
+ title: typeof decision.title === "string" && decision.title.trim() ? decision.title.trim() : "Decision",
16730
+ status,
16731
+ candidates: status === "open" ? asArray2(decision.candidates).slice(0, 5).map((candidate) => {
16732
+ const record = asRecord4(candidate);
16733
+ if (!record) return null;
16734
+ return {
16735
+ id: typeof record.id === "string" ? record.id : "unknown",
16736
+ label: typeof record.label === "string" && record.label.trim() ? record.label.trim() : null,
16737
+ description: typeof record.description === "string" && record.description.trim() ? record.description.trim() : null,
16738
+ metadata: asRecord4(record.metadata)
16739
+ };
16740
+ }).filter(Boolean) : [],
16741
+ selected: status === "open" ? null : {
16742
+ id: typeof selected?.id === "string" ? selected.id : null,
16743
+ label: typeof selected?.label === "string" ? selected.label : null
15745
16744
  }
15746
- }
15747
- }
16745
+ };
16746
+ });
15748
16747
  const openPrompts = [
15749
16748
  ...pendingPrompts.map((prompt) => ({
15750
16749
  id: prompt.id,
@@ -15764,29 +16763,29 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15764
16763
  (pendingPrompt) => pendingPrompt.id === promptId
15765
16764
  ) : false);
15766
16765
  }) : openPrompts;
15767
- lines.push("", "Open Prompts:");
15768
- if (visiblePrompts.length === 0) {
15769
- lines.push("- none");
15770
- } else {
15771
- for (const prompt of visiblePrompts.slice(0, 3)) {
15772
- const title = typeof prompt.title === "string" && prompt.title.trim() ? prompt.title.trim() : "Input required";
15773
- const type = typeof prompt.type === "string" ? prompt.type : "input";
15774
- const message = typeof prompt.message === "string" && prompt.message.trim() ? ` \u2014 ${prompt.message.trim()}` : "";
15775
- lines.push(`- [${type}] ${title}${message}`);
15776
- }
15777
- }
16766
+ const compactPrompts = visiblePrompts.slice(0, 3).map((prompt) => {
16767
+ const promptRecord = asRecord4(prompt) || {};
16768
+ return {
16769
+ id: typeof promptRecord.id === "string" ? promptRecord.id : typeof promptRecord.promptId === "string" ? promptRecord.promptId : null,
16770
+ type: typeof promptRecord.type === "string" ? promptRecord.type : "input",
16771
+ title: typeof promptRecord.title === "string" && promptRecord.title.trim() ? promptRecord.title.trim() : "Input required",
16772
+ message: typeof promptRecord.message === "string" && promptRecord.message.trim() ? promptRecord.message.trim() : null
16773
+ };
16774
+ });
15778
16775
  const currentClosureId = getCurrentClosureId(liveDoc);
15779
16776
  const closureRecord = currentClosureId ? asRecord4(asRecord4(loop?.closuresById)?.[currentClosureId]) : null;
15780
16777
  const visibleClosure = closureRecord && (boundary.reason !== "request_start" || (Number(closureRecord.createdAt) || 0) >= boundary.timestamp) ? closureRecord : null;
15781
- lines.push("", "Loop Closure:");
15782
- if (visibleClosure) {
15783
- const status = typeof visibleClosure.status === "string" ? visibleClosure.status : "completed";
15784
- const summary = typeof visibleClosure.summary === "string" ? visibleClosure.summary : "No summary";
15785
- lines.push(`- current: [${status}] ${summary} (${currentClosureId})`);
15786
- } else {
15787
- lines.push("- none");
15788
- }
15789
- return lines.join("\n");
16778
+ return renderConstBlock("workflowState", {
16779
+ tasks: compactTasks,
16780
+ hiddenActiveTaskCount: hiddenTaskCount,
16781
+ decisions: compactDecisions,
16782
+ openPrompts: compactPrompts,
16783
+ closure: visibleClosure ? {
16784
+ id: currentClosureId,
16785
+ status: typeof visibleClosure.status === "string" ? visibleClosure.status : "completed",
16786
+ summary: typeof visibleClosure.summary === "string" ? visibleClosure.summary : null
16787
+ } : null
16788
+ });
15790
16789
  }
15791
16790
  function projectHeapSummary(heap, options) {
15792
16791
  const heapRecord = asRecord4(heap) || {};
@@ -15831,55 +16830,72 @@ function projectHeapSummary(heap, options) {
15831
16830
  referencedPaths.add(path);
15832
16831
  }
15833
16832
  const visibleLists = Object.values(listsByName).map((value) => asRecord4(value)).filter((value) => Boolean(value)).filter(
15834
- (list) => variables.some((variable) => variable.listName === list.name) || Boolean(list.name && focusedListNames.has(list.name))
16833
+ (list) => variables.some(
16834
+ (variable) => Boolean(variable?.listName === list.name)
16835
+ ) || Boolean(list.name && focusedListNames.has(list.name))
15835
16836
  ).sort((left, right) => (right.updatedAt || 0) - (left.updatedAt || 0)).slice(0, maxLists);
15836
16837
  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);
15837
- const lines = [];
15838
- lines.push("Variables:");
15839
- if (variables.length === 0) {
15840
- lines.push("- none");
15841
- } else {
15842
- for (const variable of variables) {
15843
- if (variable.kind === "scalar") {
15844
- lines.push(
15845
- `- ${variable.name}: scalar = ${formatScalar(variable.value)}`
15846
- );
15847
- continue;
15848
- }
15849
- if (variable.kind === "entry") {
15850
- const entry = variable.entryPath ? asRecord4(
15851
- entriesByPath[variable.entryPath]
15852
- ) : null;
15853
- lines.push(
15854
- `- ${variable.name}: entry<${variable.className || entry?.className || "unknown"}> -> ${entry ? describeHeapEntry(entry) : variable.entryPath || "missing"}`
15855
- );
15856
- continue;
15857
- }
15858
- const list = variable.listName ? asRecord4(listsByName[variable.listName]) : null;
15859
- lines.push(
15860
- `- ${variable.name}: list<${variable.className || list?.className || "unknown"}> -> ${(list?.paths || []).length} item(s)`
15861
- );
15862
- }
15863
- }
15864
- lines.push("", "Named Lists:");
15865
- if (visibleLists.length === 0) {
15866
- lines.push("- none");
15867
- } else {
15868
- for (const list of visibleLists) {
15869
- lines.push(
15870
- `- ${list.name}: ${list.className || "unknown"}[${(list.paths || []).length}]`
15871
- );
15872
- }
15873
- }
15874
- lines.push("", "Active Entries:");
15875
- if (visibleEntries.length === 0) {
15876
- lines.push("- none");
15877
- } else {
15878
- for (const entry of visibleEntries) {
15879
- lines.push(`- ${describeHeapEntry(entry)}`);
15880
- }
15881
- }
15882
- return lines.join("\n");
16838
+ return renderConstBlock("savedData", {
16839
+ variables: Object.fromEntries(
16840
+ variables.filter((variable) => typeof variable.name === "string").map((variable) => {
16841
+ if (variable.kind === "scalar") {
16842
+ return [
16843
+ variable.name,
16844
+ { kind: "scalar", value: variable.value ?? null }
16845
+ ];
16846
+ }
16847
+ if (variable.kind === "entry") {
16848
+ const entry = variable.entryPath ? asRecord4(
16849
+ entriesByPath[variable.entryPath]
16850
+ ) : null;
16851
+ return [
16852
+ variable.name,
16853
+ {
16854
+ kind: "entry",
16855
+ type: variable.className || entry?.className || "unknown",
16856
+ path: variable.entryPath || null,
16857
+ label: entry?.label || entry?.id || null
16858
+ }
16859
+ ];
16860
+ }
16861
+ const list = variable.listName ? asRecord4(listsByName[variable.listName]) : null;
16862
+ return [
16863
+ variable.name,
16864
+ {
16865
+ kind: "list",
16866
+ type: variable.className || list?.className || "unknown",
16867
+ list: variable.listName || null,
16868
+ count: (list?.paths || []).length
16869
+ }
16870
+ ];
16871
+ })
16872
+ ),
16873
+ lists: Object.fromEntries(
16874
+ visibleLists.filter((list) => typeof list.name === "string").map((list) => [
16875
+ list.name,
16876
+ {
16877
+ type: list.className || "unknown",
16878
+ count: (list.paths || []).length
16879
+ }
16880
+ ])
16881
+ ),
16882
+ entries: Object.fromEntries(
16883
+ visibleEntries.filter((entry) => typeof entry.path === "string").map((entry) => [
16884
+ entry.path,
16885
+ {
16886
+ type: entry.className || "unknown",
16887
+ id: entry.id || null,
16888
+ label: entry.label || entry.id || null,
16889
+ fields: asArray2(entry.fields).filter(
16890
+ (field) => field?.name && field.name !== "_realId" && field.name !== "real_id"
16891
+ ).slice(0, 3).map((field) => ({
16892
+ name: field.name,
16893
+ value: field.value ?? null
16894
+ }))
16895
+ }
16896
+ ])
16897
+ )
16898
+ });
15883
16899
  }
15884
16900
  function createHarnessVerifierSnapshot(input) {
15885
16901
  const workflowFocus = projectWorkflowFocus(
@@ -15976,8 +16992,8 @@ function buildContinuationInstruction(resultPreview) {
15976
16992
  "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.",
15977
16993
  "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.",
15978
16994
  "If this request clearly spans multiple steps and there are no active tasks yet, create 2-4 short user-visible tasks now.",
15979
- "Reuse any existing taskId and decisionId values exactly as they appear in AGENT LOOP STATE.",
15980
- "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.",
16995
+ "Reuse any existing taskId and decisionId values exactly as they appear in [State].",
16996
+ "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.",
15981
16997
  "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.'",
15982
16998
  "If you ask the user a new question in this job, do not also close the loop in the same job.",
15983
16999
  "Write the smallest straightforward code for the current step. Avoid defensive fallback branches for hypothetical states that are not currently true.",
@@ -15988,39 +17004,101 @@ ${resultPreview}` : null
15988
17004
  ].filter(Boolean).join("\n\n");
15989
17005
  }
15990
17006
  function buildGranularAgentDomainBlock(domainDocumentation) {
15991
- return domainDocumentation?.trim() || "No domain reference available. The graph may not be ready yet.";
17007
+ return domainDocumentation?.trim() || "No domain contract available. The graph may not be ready yet.";
15992
17008
  }
15993
17009
  function buildGranularAgentSessionBlock(sessionContext) {
15994
- if (!sessionContext) return "No session metadata available.";
15995
- const rows = [
15996
- ["sandboxId", sessionContext.sandboxId],
15997
- ["environmentId", sessionContext.environmentId],
15998
- ["userName", sessionContext.userName]
15999
- ];
16000
- const activeRows = rows.filter(([, value]) => Boolean(value));
16001
- if (activeRows.length === 0) return "No session metadata available.";
16002
- return activeRows.map(([key, value]) => `${key}: ${value}`).join("\n");
17010
+ return renderConstBlock("session", {
17011
+ runtimeId: sessionContext?.sandboxId || null,
17012
+ environmentId: sessionContext?.environmentId || null,
17013
+ userName: sessionContext?.userName || null,
17014
+ domainRevision: sessionContext?.domainRevision || null
17015
+ });
16003
17016
  }
16004
17017
  function buildGranularAgentHeapBlock(heapSummary) {
16005
- return heapSummary?.trim() || "Heap is empty for this session.";
17018
+ return heapSummary?.trim() || renderConstBlock("savedData", {
17019
+ variables: {},
17020
+ lists: {},
17021
+ entries: {}
17022
+ });
16006
17023
  }
16007
17024
  function buildGranularAgentReferentBlock(referentSummary) {
16008
- return referentSummary?.trim() || "No recent referents recorded from prior assistant replies.";
17025
+ return referentSummary?.trim() || renderConstBlock("recentReferences", []);
16009
17026
  }
16010
17027
  function buildGranularAgentLoopBlock(loopSummary) {
16011
- return loopSummary?.trim() || "No active loop state recorded for this session.";
17028
+ return loopSummary?.trim() || renderConstBlock("workflowState", {
17029
+ tasks: [],
17030
+ decisions: [],
17031
+ openPrompts: [],
17032
+ closure: null
17033
+ });
16012
17034
  }
16013
17035
  function buildGranularAgentWorkflowBlock(workflowSummary) {
16014
- return workflowSummary?.trim() || "No current workflow snapshot recorded for this request yet.";
17036
+ return workflowSummary?.trim() || renderConstBlock("workflowContext", {
17037
+ boundary: null,
17038
+ recentActions: [],
17039
+ workingSet: {
17040
+ variables: [],
17041
+ lists: [],
17042
+ entries: []
17043
+ },
17044
+ openHandles: {
17045
+ tasks: [],
17046
+ decisions: [],
17047
+ prompts: []
17048
+ }
17049
+ });
16015
17050
  }
16016
- function buildGranularAgentToolBlock(tools) {
17051
+ function resolvePromptCapabilities(capabilities) {
17052
+ return {
17053
+ executeCode: capabilities?.executeCode !== false,
17054
+ readEntities: capabilities?.readEntities !== false,
17055
+ workflowHelpers: Array.isArray(capabilities?.workflowHelpers) ? capabilities.workflowHelpers : [
17056
+ "ask_user",
17057
+ "confirm",
17058
+ "open_decision",
17059
+ "close_decision",
17060
+ "create_task",
17061
+ "update_task",
17062
+ "complete_task",
17063
+ "close_loop"
17064
+ ],
17065
+ savedData: capabilities?.savedData !== false,
17066
+ showRecords: capabilities?.showRecords !== false
17067
+ };
17068
+ }
17069
+ function buildGranularAgentToolBlock(tools, capabilityOverrides) {
17070
+ const resolvedCapabilities = resolvePromptCapabilities(capabilityOverrides);
17071
+ const normalizedTools = (tools || []).filter((tool) => tool?.name).slice().sort((left, right) => {
17072
+ const leftScope = `${left.className || "global"}:${left.static ? "static" : "instance"}`;
17073
+ const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
17074
+ return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
17075
+ });
17076
+ const writeActions = normalizedTools.filter((tool) => tool.ready !== false).map((tool) => {
17077
+ const scope = tool.className ? `${tool.static ? "class" : "record"}:${tool.className}` : "global";
17078
+ return {
17079
+ name: tool.name,
17080
+ scope,
17081
+ description: tool.description?.trim() || null
17082
+ };
17083
+ });
17084
+ const capabilities = {
17085
+ executeCode: resolvedCapabilities.executeCode,
17086
+ readEntities: resolvedCapabilities.readEntities,
17087
+ writeActions,
17088
+ workflowHelpers: resolvedCapabilities.workflowHelpers,
17089
+ savedData: resolvedCapabilities.savedData,
17090
+ showRecords: resolvedCapabilities.showRecords
17091
+ };
17092
+ return renderConstBlock("capabilities", capabilities);
17093
+ }
17094
+ function buildGranularAgentActionIndex(tools) {
16017
17095
  const normalizedTools = (tools || []).filter((tool) => tool?.name).slice().sort((left, right) => {
16018
17096
  const leftScope = `${left.className || "global"}:${left.static ? "static" : "instance"}`;
16019
17097
  const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
16020
17098
  return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
16021
17099
  });
16022
17100
  if (normalizedTools.length === 0) {
16023
- return "No live effects are available in this session yet.";
17101
+ return "No domain write actions are available.";
16024
17102
  }
16025
17103
  const globalTools = normalizedTools.filter((tool) => !tool.className);
16026
17104
  const staticTools = normalizedTools.filter(
@@ -16029,9 +17107,7 @@ function buildGranularAgentToolBlock(tools) {
16029
17107
  const instanceTools = normalizedTools.filter(
16030
17108
  (tool) => Boolean(tool.className && !tool.static)
16031
17109
  );
16032
- const lines = [
16033
- "Treat this block as the planning map. Use DOMAIN REFERENCE below for exact signatures and query examples."
16034
- ];
17110
+ const lines = ["Available actions by scope:"];
16035
17111
  const appendGroup = (title, group) => {
16036
17112
  lines.push(`- ${title}:`);
16037
17113
  if (group.length === 0) {
@@ -16040,189 +17116,468 @@ function buildGranularAgentToolBlock(tools) {
16040
17116
  }
16041
17117
  for (const tool of group.slice(0, 10)) {
16042
17118
  const availability = tool.ready === false ? " [not ready]" : "";
17119
+ const schema = formatActionSchemaSummary(tool);
16043
17120
  const description = tool.description?.trim() ? ` - ${tool.description.trim()}` : "";
16044
- lines.push(` ${tool.name}${availability}${description}`);
17121
+ lines.push(` ${tool.name}${availability}${schema}${description}`);
16045
17122
  }
16046
17123
  if (group.length > 10) {
16047
17124
  lines.push(` +${group.length - 10} more`);
16048
17125
  }
16049
17126
  };
16050
- appendGroup("Global effects", globalTools);
16051
- appendGroup("Class-level effects", staticTools);
16052
- appendGroup("Record-level effects", instanceTools);
17127
+ appendGroup("Global", globalTools);
17128
+ appendGroup("Class-level", staticTools);
17129
+ appendGroup("Record-level", instanceTools);
16053
17130
  return lines.join("\n");
16054
17131
  }
16055
- function buildGranularAgentCheckpointBlock(checkpoint) {
16056
- if (!checkpoint) {
16057
- return "No previous execution checkpoint recorded for this request yet.";
16058
- }
16059
- const lines = [];
16060
- if (typeof checkpoint.iteration === "number") {
16061
- lines.push(`iteration: ${checkpoint.iteration}`);
16062
- }
16063
- if (checkpoint.latestJobStatus) {
16064
- lines.push(`latestJobStatus: ${checkpoint.latestJobStatus}`);
16065
- }
16066
- if (checkpoint.controllerOutcome) {
16067
- lines.push(`controllerOutcome: ${checkpoint.controllerOutcome}`);
17132
+ function normalizeJsonSchema(value) {
17133
+ if (typeof value === "string") {
17134
+ try {
17135
+ return asRecord4(JSON.parse(value));
17136
+ } catch {
17137
+ return null;
17138
+ }
16068
17139
  }
16069
- if (checkpoint.controllerReason) {
16070
- lines.push(`controllerReason: ${checkpoint.controllerReason}`);
17140
+ return asRecord4(value);
17141
+ }
17142
+ function jsonSchemaTypeName(schema) {
17143
+ const record = normalizeJsonSchema(schema);
17144
+ if (!record) return "unknown";
17145
+ const type = record.type;
17146
+ if (typeof type === "string") {
17147
+ if (type === "array") return "array";
17148
+ if (type === "object") return "object";
17149
+ return type;
16071
17150
  }
16072
- if (typeof checkpoint.noProgressCount === "number") {
16073
- lines.push(`noProgressCount: ${checkpoint.noProgressCount}`);
17151
+ return "unknown";
17152
+ }
17153
+ function summarizeObjectSchema(schema) {
17154
+ const record = normalizeJsonSchema(schema);
17155
+ const properties = asRecord4(record?.properties);
17156
+ if (!properties || Object.keys(properties).length === 0) {
17157
+ return record ? "{}" : null;
17158
+ }
17159
+ const required = new Set(asArray2(record?.required));
17160
+ const fields = Object.entries(properties).slice(0, 8).map(([name, property]) => {
17161
+ const marker = required.has(name) ? "*" : "?";
17162
+ return `${name}${marker}: ${jsonSchemaTypeName(property)}`;
17163
+ });
17164
+ const remaining = Object.keys(properties).length - fields.length;
17165
+ return remaining > 0 ? `${fields.join(", ")}, +${remaining}` : fields.join(", ");
17166
+ }
17167
+ function formatActionSchemaSummary(tool) {
17168
+ const input = summarizeObjectSchema(tool.inputSchema);
17169
+ const output = summarizeObjectSchema(tool.outputSchema);
17170
+ const parts = [];
17171
+ if (input) parts.push(`input { ${input} }`);
17172
+ if (output) parts.push(`output { ${output} }`);
17173
+ return parts.length ? ` (${parts.join("; ")})` : "";
17174
+ }
17175
+ function splitDomainDocumentation(domainDocumentation) {
17176
+ const normalized = domainDocumentation?.trim() || "";
17177
+ if (!normalized) return { types: "", docs: "" };
17178
+ const docsSectionMatch = normalized.match(/\n\s*\[Docs\]\s*\n/i);
17179
+ if (docsSectionMatch?.index !== void 0) {
17180
+ return {
17181
+ types: normalized.slice(0, docsSectionMatch.index).trim(),
17182
+ docs: normalized.slice(docsSectionMatch.index + docsSectionMatch[0].length).trim()
17183
+ };
16074
17184
  }
16075
- if (checkpoint.latestJobError?.trim()) {
16076
- lines.push(`latestJobError: ${checkpoint.latestJobError.trim()}`);
17185
+ const legacyMarker = "Generated usage notes from ./sandbox-tools docs:";
17186
+ const legacyIndex = normalized.indexOf(legacyMarker);
17187
+ if (legacyIndex !== -1) {
17188
+ return {
17189
+ types: normalized.slice(0, legacyIndex).trim(),
17190
+ docs: normalized.slice(legacyIndex + legacyMarker.length).trim()
17191
+ };
16077
17192
  }
16078
- if (Array.isArray(checkpoint.latestActionSummary) && checkpoint.latestActionSummary.length > 0) {
16079
- lines.push("latestActionSummary:");
16080
- for (const line of checkpoint.latestActionSummary.slice(0, 8)) {
16081
- const normalizedLine = normalizeActionSummaryForPrompt(line);
16082
- lines.push(
16083
- normalizedLine.startsWith("- ") ? normalizedLine : `- ${normalizedLine}`
16084
- );
17193
+ return { types: normalized, docs: "" };
17194
+ }
17195
+ function buildGranularAgentCheckpointBlock(checkpoint) {
17196
+ if (!checkpoint) {
17197
+ return renderConstBlock("previousCodeResult", null);
17198
+ }
17199
+ return renderConstBlock("previousCodeResult", {
17200
+ iteration: typeof checkpoint.iteration === "number" ? checkpoint.iteration : null,
17201
+ latestJobStatus: checkpoint.latestJobStatus || null,
17202
+ controllerOutcome: checkpoint.controllerOutcome || null,
17203
+ controllerReason: checkpoint.controllerReason || null,
17204
+ noProgressCount: typeof checkpoint.noProgressCount === "number" ? checkpoint.noProgressCount : null,
17205
+ latestJobError: checkpoint.latestJobError?.trim() || null,
17206
+ latestActionSummary: Array.isArray(checkpoint.latestActionSummary) ? checkpoint.latestActionSummary.slice(0, 8).map(normalizeActionSummaryForPrompt) : [],
17207
+ latestJobResult: checkpoint.latestJobResult?.trim() || null
17208
+ });
17209
+ }
17210
+ function parseSummaryOutcome(summary) {
17211
+ const outcome = {};
17212
+ for (const part of summary.split(",")) {
17213
+ const trimmed = part.trim();
17214
+ const match = /^([A-Za-z0-9_]+)=(.+)$/.exec(trimmed);
17215
+ if (!match) continue;
17216
+ const [, key, rawValue] = match;
17217
+ const unquoted = rawValue.replace(/^"|"$/g, "");
17218
+ if (/^-?\d+(?:\.\d+)?$/.test(unquoted)) {
17219
+ outcome[key] = Number(unquoted);
17220
+ } else if (unquoted === "true" || unquoted === "false") {
17221
+ outcome[key] = unquoted === "true";
17222
+ } else {
17223
+ outcome[key] = unquoted;
16085
17224
  }
16086
17225
  }
16087
- if (checkpoint.latestJobResult?.trim()) {
16088
- lines.push(`latestJobResult:
16089
- ${checkpoint.latestJobResult.trim()}`);
17226
+ return outcome;
17227
+ }
17228
+ function buildKnownFactsFromCheckpoint(checkpoint) {
17229
+ const summaries = Array.isArray(checkpoint?.latestActionSummary) ? checkpoint.latestActionSummary.map(normalizeActionSummaryForPrompt) : [];
17230
+ const facts = [];
17231
+ for (const summary of summaries) {
17232
+ const countedMatch = /^-\s*Counted\s+([A-Za-z0-9_]+).*?->\s*value=(\d+)/.exec(summary);
17233
+ if (countedMatch) {
17234
+ facts.push({
17235
+ entity: countedMatch[1],
17236
+ query: {},
17237
+ totalCount: Number(countedMatch[2])
17238
+ });
17239
+ continue;
17240
+ }
17241
+ const listedMatch = /^-\s*Listed\s+([A-Za-z0-9_]+).*?->\s*(.+)$/.exec(
17242
+ summary
17243
+ );
17244
+ if (!listedMatch) continue;
17245
+ const outcome = parseSummaryOutcome(listedMatch[2]);
17246
+ const count = typeof outcome.totalCount === "number" ? outcome.totalCount : typeof outcome.count === "number" ? outcome.count : void 0;
17247
+ if (typeof count !== "number") continue;
17248
+ const fact = {
17249
+ entity: listedMatch[1],
17250
+ query: {},
17251
+ totalCount: count
17252
+ };
17253
+ if (typeof outcome.hasMore === "boolean") {
17254
+ fact.lastPageHasMore = outcome.hasMore;
17255
+ fact.loadedAllItems = !outcome.hasMore;
17256
+ } else if (typeof outcome.count === "number" && outcome.count === count) {
17257
+ fact.loadedAllItems = true;
17258
+ }
17259
+ facts.push(fact);
16090
17260
  }
16091
- return lines.length > 0 ? lines.join("\n") : "No previous execution checkpoint recorded for this request yet.";
17261
+ return facts.slice(0, 8);
16092
17262
  }
16093
17263
  function buildGranularAgentSystemPrompt(input) {
17264
+ const outputMode = input.outputMode || "agentMessages";
17265
+ const promptCapabilities = resolvePromptCapabilities(input.capabilities);
17266
+ const domainSections = splitDomainDocumentation(input.domainDocumentation);
16094
17267
  const sessionBlock = buildGranularAgentSessionBlock(input.sessionContext);
16095
- const toolBlock = buildGranularAgentToolBlock(input.tools);
16096
- const domainBlock = buildGranularAgentDomainBlock(input.domainDocumentation);
17268
+ const toolBlock = buildGranularAgentToolBlock(
17269
+ input.tools,
17270
+ input.capabilities
17271
+ );
17272
+ const actionIndex = buildGranularAgentActionIndex(input.tools);
17273
+ const domainBlock = buildGranularAgentDomainBlock(domainSections.types);
16097
17274
  const workflowBlock = buildGranularAgentWorkflowBlock(input.workflowSummary);
16098
17275
  const checkpointBlock = buildGranularAgentCheckpointBlock(input.checkpoint);
16099
17276
  const heapBlock = buildGranularAgentHeapBlock(input.heapSummary);
16100
17277
  const referentBlock = buildGranularAgentReferentBlock(input.referentSummary);
16101
17278
  const loopBlock = buildGranularAgentLoopBlock(input.loopSummary);
16102
- return `You are an AI assistant for a live Granular session.
16103
- You can help the user understand the domain, answer questions, or generate and execute code against the live session.
16104
- Your tone must be natural and human-like.
17279
+ const knownFactsBlock = renderConstBlock(
17280
+ "knownFacts",
17281
+ buildKnownFactsFromCheckpoint(input.checkpoint)
17282
+ );
17283
+ 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 }\`.
17284
+ - Use \`{ reply, show }\` when the host UI should render records, heap variables, or lists from session state.
17285
+ - For multi-record display, prefer a saved list/listName so the UI can render a table; use entryPaths for a few individual records.
17286
+ - 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.
17287
+ - 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.
17288
+ - 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(...)\`.
17289
+ - \`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.
17290
+ - 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.
17291
+ - 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.
17292
+ - 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.
17293
+ - 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.
17294
+ - 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"] })\`.
17295
+ - \`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.
17296
+ - 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.
17297
+ - 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.
17298
+ - 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.
17299
+ - 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.
17300
+ - 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.
17301
+ - 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.
17302
+ - 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(...)\`.
17303
+ - \`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.
17304
+ - 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.
17305
+ - 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.
17306
+ - 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.`;
17307
+ const codeRules = promptCapabilities.executeCode ? `Code:
17308
+ - Use when the request needs session data, saved data, workflow state, record display, or available actions.
17309
+ - When using code, assistant text must be empty or one brief summary.
17310
+ - Code must be plain runnable JavaScript with top-level await.
17311
+ - Import needed classes and helpers from "./sandbox-tools".
17312
+ - Use static top-level imports such as \`import { Foo, agent_text_message } from "./sandbox-tools";\`. Do not use dynamic \`await import("./sandbox-tools")\`.
17313
+ - 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.
17314
+ - 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")\`.
17315
+ - 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.
17316
+ - User-visible output must use the provided message or record-display helpers.
17317
+ - After calling an action or effect, inspect the returned object and base the user-facing answer on its actual fields.
17318
+ - When calling an action, use the exact input property names from the action schema. Do not invent synonym keys for required inputs.
17319
+ - 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".
17320
+ - Never call \`process.exit(...)\`; emit a message and use \`return;\` to stop early.
17321
+ - 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.
17322
+ - 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.
17323
+ - Write \`//\` planning comments for the user, not for engineers: make them friendly, plain-language, and easy to understand.
17324
+ - 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.
17325
+ - 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.
17326
+ - Avoid technical terms, implementation names, code concepts, hidden helper names, and complex domain jargon in \`//\` planning comments unless the user already used that wording.
17327
+ - Each \`//\` planning comment should provide valuable feedback about the plan or next visible step. Do not add filler such as "Starting", "Running", or "Processing".
17328
+ ${outputRules}` : `Code:
17329
+ - Code execution is unavailable. Use text only, or ask the user for missing information.`;
17330
+ const workflowRules = promptCapabilities.workflowHelpers.length > 0 ? `Workflow:
17331
+ - Use workflow helpers when missing input should pause and resume the workflow.
17332
+ - If code discovers missing required input after a read, use \`await loop.ask_user(...)\`; do not just tell the user to provide it.
17333
+ - 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.
17334
+ - 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.
17335
+ - 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.
17336
+ - 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.
17337
+ - Use choice only for 2 to 5 short grounded options.
17338
+ - For record choices, set each option value to a stable scalar such as the record \`_graphPath\` or \`id\`, not a label-only value.
17339
+ - 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.
17340
+ - 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.
17341
+ - 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.
17342
+ - 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.
17343
+ - 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.
17344
+ - 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.
17345
+ - Reuse existing task, decision, and closure ids from [State].
17346
+ - If a user request matches both a domain record/action and a workflow helper, prefer the domain capability.` : "";
17347
+ return `[Harness]
17348
+ You are an assistant for a live user session. Use plain, natural language.
16105
17349
 
16106
- 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.
16107
- When you call \`execute_code\`, additional assistant text must be either:
16108
- - empty, or
16109
- - a brief summary of the actions the generated code will perform.
16110
- Do not include any other kind of commentary when calling \`execute_code\`.
16111
- - 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(...)\`.
16112
- - 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.
16113
- - 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.
16114
- - 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.
17350
+ Mode selection:
17351
+ Text only:
17352
+ - Use for general explanations, unsupported requests, or requests that do not need session data.
17353
+ - 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.
17354
+ - 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.
17355
+ - Do not expose internal names, helper names, file paths, parameter names, or code.
17356
+ - 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.
16115
17357
 
16116
- \u2500\u2500\u2500 STREAMING COMMENT RULES \u2500\u2500\u2500
16117
- - While you are writing code, add short single-line comments with the prefix \`// \` before meaningful blocks.
16118
- - These comments should explain the intent in friendly product language, not in implementation jargon.
16119
- - Comments are shown live as a reasoning trace, so keep them brief, concrete, and useful.
16120
- - Do not mention method names, file paths, or internal identifiers in those comments.
16121
- - Use only single-line \`//\` comments for this purpose. Do not use block comments.
16122
- - If you are replying with text only, you may also include a few leading \`// \` comment lines before the final answer.
16123
- - End text-only replies with the plain user-facing answer on normal lines, without a comment prefix.
17358
+ ${codeRules}
16124
17359
 
16125
- \u2500\u2500\u2500 RESPONSE STYLE RULES \u2500\u2500\u2500
16126
- - Use plain, friendly product language.
16127
- - Never mention internal implementation details in user-facing text:
16128
- class names, effect names, method names, function names, file paths, parameter names, or code snippets.
16129
- - Never expose dotted identifiers such as \`Class.method\` in user-facing text.
16130
- - Do not say "sandbox" in user-facing text unless the user is explicitly asking about the runtime environment itself.
16131
- - If you need clarification, ask in everyday language.
16132
- - 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.
16133
- - 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.
16134
- - Keep replies concise and clear.
16135
- - This is a conversation UI, not an API console. Favor human answers over machine-shaped payloads.
17360
+ ${workflowRules}
16136
17361
 
16137
- \u2500\u2500\u2500 SESSION CONTEXT \u2500\u2500\u2500
16138
- ${sessionBlock}
17362
+ High-priority execution rules:
17363
+ - 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.
17364
+ - 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.
17365
+ - 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.
17366
+ - 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.
17367
+ - 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.
17368
+ - 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.
17369
+ - 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.
17370
+ - 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.
17371
+ - 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.
17372
+ - 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.
17373
+ - 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.
17374
+ - 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.
17375
+ - 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.
17376
+ - 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.
17377
+ - 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.
17378
+ - 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.
17379
+ - 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.
17380
+ - 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.
17381
+ - 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.
17382
+ - 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.
17383
+ - 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.
16139
17384
 
16140
- \u2500\u2500\u2500 CAPABILITY SNAPSHOT \u2500\u2500\u2500
16141
- ${toolBlock}
17385
+ Intent resolution:
17386
+ - If intent is explicit, act directly.
17387
+ - 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.
17388
+ - 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.
17389
+ - 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.
17390
+ - 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.
17391
+ - 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.
17392
+ - 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.
17393
+ - 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.
17394
+ - 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.
17395
+ - 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.
17396
+ - 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.
17397
+ - 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.
17398
+ - 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.
17399
+ - 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.
17400
+ - 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.
17401
+ - 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.
17402
+ - 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.
17403
+ - Never call \`.get({ path: "" })\`; an empty path is not a saved reference.
17404
+ - 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.
17405
+ - \`.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.
17406
+ - 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.
17407
+ - If the entity, field, target, scope, ranking, or action is ambiguous, create 2 to 5 plausible interpretations.
17408
+ - Probe plausible interpretations with cheap read-only queries before deciding.
17409
+ - 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.
17410
+ - 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.
17411
+ - One strong match means proceed.
17412
+ - Several plausible matches means call \`loop.ask_user({ type: "choice", ... })\` with grounded choices.
17413
+ - No grounded match means ask for missing information.
17414
+ - For consequential changes, resolve first, confirm when needed, then act.
17415
+ - 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.
17416
+ - 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\`.
17417
+ - 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.
17418
+ - 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.
17419
+
17420
+ Use exploratory probing when:
17421
+ - the user gives a human reference instead of an exact id or path
17422
+ - a noun could refer to multiple entity types
17423
+ - a name, number, label, date, or amount is given without a clear field
17424
+ - ranking words are used without a clear metric
17425
+ - a requested change has an unclear target
17426
+ - the first reasonable lookup returns zero results
17427
+ - the first reasonable lookup returns several plausible results
17428
+
17429
+ Do not explore when:
17430
+ - the entity, field, filter, and action are explicit
17431
+ - the request is a general explanation
17432
+ - the request is unsupported by available capabilities
17433
+ - the next step is already a required workflow answer or confirmation
16142
17434
 
16143
- \u2500\u2500\u2500 DOMAIN REFERENCE (from ./sandbox-tools) \u2500\u2500\u2500
16144
- Import classes and effect functions from \`./sandbox-tools\` in generated code.
16145
- Use the TypeScript declarations for exact signatures. When present, the generated usage notes below them show query patterns and examples.
17435
+ [Types]
17436
+ Import classes, helpers, and available actions from "./sandbox-tools".
17437
+ 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.
16146
17438
 
16147
17439
  ${domainBlock}
16148
17440
 
16149
- \u2500\u2500\u2500 EXECUTION CHECKPOINT \u2500\u2500\u2500
17441
+ [Docs]
17442
+ Query policy:
17443
+ - Use filter, search, sort, count, page, list, and iterate on entity classes.
17444
+ - Push filtering and sorting into entity queries. Do not fetch a page only to filter or sort locally.
17445
+ - Valid filter fields are defined by each entity filter type.
17446
+ - Valid sort fields are defined by each entity sort field type.
17447
+ - Search is class-wide text retrieval, not a field-scoped operator.
17448
+ - Entity classes do not have a \`.search(...)\` method. Use \`.find({ search })\`, \`.page({ search, ... })\`, or \`.list({ search, ... })\`.
17449
+ - 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\`.
17450
+ - 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.
17451
+ - 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.
17452
+ - Combine search and filter when both free-text matching and exact constraints are needed.
17453
+ - 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.
17454
+ - 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.
17455
+ - Boolean filters use \`equal_to: true\` or \`equal_to: false\`.
17456
+ - 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.
17457
+ - 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.
17458
+ - 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.
17459
+ - 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.
17460
+ - 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.
17461
+ - 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.
17462
+ - 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.
17463
+ - 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.
17464
+ - 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.
17465
+ - Prefer generated instance relationship getters from a grounded record over hand-written deep nested relationship filters.
17466
+ - 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.
17467
+ - 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.
17468
+ - 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.
17469
+ - 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.
17470
+ - 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.
17471
+ - 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.
17472
+ - 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.
17473
+ - 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.
17474
+ - 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.
17475
+ - 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.
17476
+ - 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.
17477
+ - 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 }\`.
17478
+ - 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.
17479
+ - 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.
17480
+ - 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.
17481
+ - 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.
17482
+ - 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.
17483
+ - 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.
17484
+ - 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.
17485
+ - 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.
17486
+ - 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.
17487
+ - For scheduling actions, convert relative wording into concrete ISO timestamps before mutating records.
17488
+ - 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.
17489
+ - 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.
17490
+ - 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.
17491
+ - 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.
17492
+ - For exploratory work, use count for totals and page with small perPage for samples; use iteration only after the interpretation is chosen.
17493
+
17494
+ Lookup ladder:
17495
+ 1. Check recent references and saved session data.
17496
+ 2. Try exact id or path when the user gave an id-like value.
17497
+ 3. If the request names a parent/container plus a target, ground the parent/container and traverse declared relationships to target candidates.
17498
+ 4. Try exact filters on fields whose names or aliases match the user words.
17499
+ 5. Try class-wide search with short target-local terms, not the whole user phrase.
17500
+ 6. Try relationship filters when the user mentions connected concepts and the filter shape is documented.
17501
+ 7. If the user names a parent/container and says the label may be approximate, inspect related target records before reporting no match.
17502
+ 8. If still empty, try one small set of normalized, prefix, or fuzzy variants when search supports it.
17503
+ 9. If still empty or ambiguous, ask the user for steering.
17504
+
17505
+ Exploration budget:
17506
+ - For a simple ambiguous reference, try up to 3 strategies.
17507
+ - For a broad ambiguous task, try up to 5 strategies.
17508
+ - Probe with small pages.
17509
+ - Do not run exhaustive scans during probing unless the user explicitly asks for all records or the selected task requires aggregation.
17510
+ - Stop early when a strong unique match is found.
17511
+
17512
+ Strong unique match:
17513
+ - exactly one record matches an exact id or path
17514
+ - exactly one record matches an exact filter on a likely identifier field
17515
+ - exactly one recent reference or saved value fits the request
17516
+ - one interpretation has results and all other reasonable interpretations have none
17517
+
17518
+ Ask the user when:
17519
+ - multiple exact matches exist
17520
+ - several entity types match the same phrase
17521
+ - the best match comes only from broad search and other plausible matches exist
17522
+ - the ranking or metric is unclear
17523
+ - the target is unique but the requested action is unclear
17524
+
17525
+ Relationship filters:
17526
+ - One-record relationships use \`is\`.
17527
+ - Multi-record relationships use \`some\`.
17528
+ - 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.
17529
+ - 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.
17530
+ - 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.
17531
+ - 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.
17532
+ - Use \`some\` only when the generated TypeScript type says \`ManyRelationFilter\`.
17533
+ - 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.
17534
+ - Use \`{ relationship: { id: "record_id" } }\` or \`{ relationship: { path: "class_record_id" } }\` when matching a known related record.
17535
+ - 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\`.
17536
+ - 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.
17537
+ - Use \`{ relationship: { is: { field: { equal_to: value } } } }\` only for nested field filters. Never put \`id\` or \`path\` inside \`is\`.
17538
+ - 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.
17539
+ - Do not pass a full record instance into a filter; if you already fetched a record, filter by its id or path instead.
17540
+ ${domainSections.docs ? `
17541
+ Domain notes:
17542
+ ${domainSections.docs}
17543
+ ` : ""}
17544
+
17545
+ Actions:
17546
+ ${actionIndex}
17547
+ - 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(...)\`.
17548
+ - Actions listed under "Class-level" are class/static methods. Call them on the imported class, e.g. \`await Item.action_name(...)\`.
17549
+ - 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.
17550
+ - Never call a record-level action as \`Class.action_name(...)\`; that method will not exist.
17551
+ - 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.
17552
+ - 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.
17553
+ - 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.
17554
+ - 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.
17555
+ - 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.
17556
+ - 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.
17557
+ - 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.
17558
+ - 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.
17559
+
17560
+ [State]
17561
+ ${toolBlock}
17562
+
17563
+ ${sessionBlock}
17564
+
16150
17565
  ${checkpointBlock}
16151
17566
 
16152
- \u2500\u2500\u2500 WORKFLOW SNAPSHOT \u2500\u2500\u2500
16153
17567
  ${workflowBlock}
16154
17568
 
16155
- \u2500\u2500\u2500 RECENT REFERENTS \u2500\u2500\u2500
16156
17569
  ${referentBlock}
16157
17570
 
16158
- \u2500\u2500\u2500 SESSION HEAP \u2500\u2500\u2500
16159
17571
  ${heapBlock}
16160
17572
 
16161
- \u2500\u2500\u2500 AGENT LOOP STATE \u2500\u2500\u2500
16162
17573
  ${loopBlock}
16163
17574
 
16164
- \u2500\u2500\u2500 LOOP PLAYBOOK \u2500\u2500\u2500
16165
- - 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.
16166
- - Use CAPABILITY SNAPSHOT to choose the next step, then use DOMAIN REFERENCE for exact signatures and query shapes.
16167
- - Take the minimum next step that directly helps the user. Avoid duplicate work, speculative cleanup, or extra fetching that is not needed yet.
16168
- - Use RECENT REFERENTS to resolve follow-up references across turns, such as "that invoice", "that customer", "those products", or "the other one".
16169
- - 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.
16170
- - 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.
16171
- - If the request has more than one reasonable interpretation, ask the user to clarify instead of guessing.
16172
- - 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.
16173
- - 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.
16174
- - 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.
16175
- - Reuse exact \`taskId\`, \`decisionId\`, and \`closureId\` values from AGENT LOOP STATE. Never invent or rewrite them.
16176
- - If the request is ambiguous or clearly multi-step, create 2-4 short user-visible tasks and keep them updated as the workflow advances.
16177
- - Use \`loop.ask_user({ type: 'choice', options: [...] })\` when you have a short, grounded shortlist the user can choose from. Otherwise use \`type: 'input'\`.
16178
- - 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.
16179
- - When \`type: 'choice'\` fits, do not ask the same question as plain text with bullets such as "Common options:" or "Choose one of these:".
16180
- - Use \`loop.confirm(...)\` for consequential approval unless the user already clearly instructed you to perform that exact action now.
16181
- - Await \`loop.ask_user(...)\` and \`loop.confirm(...)\`. After the job resumes, continue in the same job whenever the answer is enough to act.
16182
- - 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.
16183
- - If you ask a new question in the current job, do not also close the loop in that same job.
16184
-
16185
- \u2500\u2500\u2500 LOOP HELPER REFERENCE \u2500\u2500\u2500
16186
- - \`loop.ask_user(...)\`: pause the current job for missing input; use \`type: 'choice'\` only for a short grounded shortlist.
16187
- - \`loop.confirm(...)\`: pause for yes/no approval before a consequential action, then branch on the returned boolean.
16188
- - \`loop.open_decision(...)\`: save explicit candidates that later jobs can revisit; each candidate needs an \`id\`.
16189
- - \`loop.close_decision(...)\`: resolve an open decision with a stored \`selectedId\` and optional rationale.
16190
- - \`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.
16191
- - \`loop.close_loop(...)\`: record the workflow outcome when it is completed, canceled, or blocked.
17575
+ ${knownFactsBlock}
16192
17576
 
16193
- \u2500\u2500\u2500 CODE RULES \u2500\u2500\u2500
16194
- - Import from \`./sandbox-tools\`.
16195
- - If you use \`heap\`, \`loop\`, \`agent_text_message\`, or \`agent_heap_objects\`, import them explicitly from \`./sandbox-tools\`.
16196
- - Write top-level executable code with \`await\` at top level.
16197
- - The generated job body must be plain runnable JavaScript. Do not use TypeScript-only syntax.
16198
- - Follow the exact classes, methods, and parameter shapes in DOMAIN REFERENCE. Do not invent helpers or unsupported arguments.
16199
- - Use \`ClassName.get({ path })\` only for known graph paths when you want a direct graph fetch.
16200
- - 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.
16201
- - \`perPage\` defaults to \`100\` and is capped at \`100\`.
16202
- - 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.
16203
- - Push \`filter\`, \`search\`, and \`sort\` into graph queries instead of fetching a page and processing it locally.
16204
- - 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.
16205
- - 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.
16206
- - If ordering alone answers the request, use \`sort\` without inventing a \`filter\`.
16207
- - 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(...)\`.
16208
- - 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.
16209
- - Call instance methods on instances, static methods on classes, and global effects by name.
16210
- - Use \`heap.getEntry(path)\` for remembered heap entries, \`heap.getList(name)\` for remembered lists, and \`heap.getVar(name)\` only for named variables.
16211
- - Use \`heap.setVar(...)\` and \`heap.deleteVar(...)\` only when they help the next step.
16212
- - Prefer \`heap.setVar(...)\` for scalars or one selected instance. Prefer \`ClassName.list({ saveAs })\` for reusable typed lists. Empty arrays are allowed.
16213
- - 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.
16214
- - Use the \`loop\` helpers to manage workflow state: \`ask_user\`, \`confirm\`, \`open_decision\`, \`close_decision\`, \`create_task\`, \`update_task\`, \`complete_task\`, and \`close_loop\`.
16215
- - Use \`type: 'choice'\` only for short grounded options. Use \`type: 'input'\` when the answer should stay open-ended.
16216
- - \`loop.confirm(...)\` is for consequential approval. Do not ask for approval in plain text.
16217
- - After \`await loop.ask_user(...)\` or \`await loop.confirm(...)\`, continue in the same resumed job when the answer is enough to act.
16218
- - Every job that answers the user must emit \`agent_text_message(...)\` and/or \`agent_heap_objects(...)\`.
16219
- - Use \`agent_text_message(...)\` for user-visible text.
16220
- - 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.
16221
- - 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.
16222
- - Keep the code small and direct. Avoid speculative branches, broad casts, and raw JSON dumps unless the user asked for them.
16223
- - Use \`console.log()\` only for intermediate diagnostics, not for the final user-facing answer.`;
17577
+ [Request]
17578
+ ${input.request?.trim() || "Use the latest user message in the conversation."}`;
16224
17579
  }
16225
17580
 
16226
- export { Environment, EnvironmentSession, Granular, OntologyHandle, Session, WSClient, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentReferentBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, buildSessionTranscript, createHarnessVerifierSnapshot, evaluateContinuation, extractPromptTokens, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, invokeRegisteredEffect, isLocalApiUrl, normalizeEffectBehaviors, normalizePrompt, normalizePromptText, normalizePromptType, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, resolveApiUrl, resolveAuthTokenForApiUrl, resolveJobPresentation, resolvePromptAnswer, reviewGeneratedJobCode, scorePromptChoiceMatch };
17581
+ export { Environment, EnvironmentSession, Granular, OntologyHandle, Session, WSClient, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentReferentBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, buildSessionTranscript, consumeGranularReasoningOnlyChunk, consumeGranularReasoningTraceChunk, createHarnessVerifierSnapshot, evaluateContinuation, extractPromptTokens, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, invokeRegisteredEffect, isLocalApiUrl, normalizeEffectBehaviors, normalizePrompt, normalizePromptChoiceOption, normalizePromptText, normalizePromptType, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, resolveApiUrl, resolveAuthTokenForApiUrl, resolveJobPresentation, resolvePromptAnswer, reviewGeneratedJobCode, scorePromptChoiceMatch, stripGranularReasoningTrace };
16227
17582
  //# sourceMappingURL=index.mjs.map
16228
17583
  //# sourceMappingURL=index.mjs.map