@granular-software/sdk 0.4.36 → 0.4.38

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,9 +4597,26 @@ 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;
4619
+ initialQuota;
4551
4620
  jobsMap = /* @__PURE__ */ new Map();
4552
4621
  pendingAgentMessagesByJobId = /* @__PURE__ */ new Map();
4553
4622
  eventListeners = /* @__PURE__ */ new Map();
@@ -4561,9 +4630,12 @@ var Session = class {
4561
4630
  lastKnownTools = /* @__PURE__ */ new Map();
4562
4631
  /** Last seen live prompts, keyed by prompt id, for answer normalization */
4563
4632
  promptCache = /* @__PURE__ */ new Map();
4564
- constructor(client, clientId) {
4633
+ /** Prompt ids locally answered before the document sync catches up. */
4634
+ hiddenPromptIds = /* @__PURE__ */ new Set();
4635
+ constructor(client, clientId, options = {}) {
4565
4636
  this.client = client;
4566
4637
  this.clientId = clientId || `client_${Date.now()}`;
4638
+ this.initialQuota = options.initialQuota || null;
4567
4639
  this.setupEventHandlers();
4568
4640
  this.setupToolInvokeHandler();
4569
4641
  }
@@ -4612,6 +4684,16 @@ var Session = class {
4612
4684
  get document() {
4613
4685
  return this.client.doc;
4614
4686
  }
4687
+ get quota() {
4688
+ return this.getQuota();
4689
+ }
4690
+ getQuota() {
4691
+ const quota = this.client.doc.billing?.quota;
4692
+ if (quota && typeof quota === "object") {
4693
+ return quota;
4694
+ }
4695
+ return this.initialQuota;
4696
+ }
4615
4697
  get sessionId() {
4616
4698
  return this.client.currentSessionId;
4617
4699
  }
@@ -4696,8 +4778,9 @@ var Session = class {
4696
4778
  * `effect.invoke` RPC back to the sandbox effect host, where the registered handlers
4697
4779
  * execute locally and return the result to the sandbox.
4698
4780
  */
4699
- async submitJob(code, domainRevision) {
4700
- let revision = domainRevision || this.currentDomainRevision || this.extractDomainRevisionFromDoc(this.client.doc) || void 0;
4781
+ async submitJob(code, domainRevisionOrOptions) {
4782
+ const options = typeof domainRevisionOrOptions === "string" ? { domainRevision: domainRevisionOrOptions } : domainRevisionOrOptions || {};
4783
+ let revision = options.domainRevision || this.currentDomainRevision || this.extractDomainRevisionFromDoc(this.client.doc) || void 0;
4701
4784
  if (!revision) {
4702
4785
  try {
4703
4786
  const summary = await this.getDomain();
@@ -4712,7 +4795,9 @@ var Session = class {
4712
4795
  }
4713
4796
  const result = await this.client.call("job.submit", {
4714
4797
  domainRevision: revision,
4715
- code
4798
+ code,
4799
+ metadata: options.metadata,
4800
+ agent: options.agent
4716
4801
  });
4717
4802
  if (!result.jobId) {
4718
4803
  throw new Error("Failed to submit job: no jobId returned");
@@ -4753,25 +4838,39 @@ var Session = class {
4753
4838
  const prompt = this.promptCache.get(promptId);
4754
4839
  const resolvedAnswer = resolvePromptAnswer(prompt, answer);
4755
4840
  this.promptCache.delete(promptId);
4756
- await this.client.call("prompt.answer", {
4757
- promptId,
4758
- answer: resolvedAnswer,
4759
- value: resolvedAnswer
4760
- });
4841
+ this.hiddenPromptIds.add(promptId);
4842
+ try {
4843
+ await this.client.call("prompt.answer", {
4844
+ promptId,
4845
+ answer: resolvedAnswer,
4846
+ value: resolvedAnswer
4847
+ });
4848
+ } catch (error) {
4849
+ this.hiddenPromptIds.delete(promptId);
4850
+ if (prompt) {
4851
+ this.promptCache.set(promptId, prompt);
4852
+ }
4853
+ throw error;
4854
+ }
4761
4855
  try {
4762
4856
  const content = this.stringifyConversationValue(resolvedAnswer);
4763
4857
  if (content.trim()) {
4764
- await this.appendConversationMessage({
4765
- role: "user",
4766
- content,
4767
- promptId
4768
- });
4858
+ await withPromptTranscriptTimeout(
4859
+ this.appendConversationMessage({
4860
+ role: "user",
4861
+ content,
4862
+ promptId
4863
+ })
4864
+ );
4769
4865
  }
4770
4866
  } catch {
4771
4867
  }
4772
4868
  }
4773
4869
  async appendConversationMessage(input) {
4774
- return this.client.call("conversation.append", input);
4870
+ return this.client.call(
4871
+ "conversation.append",
4872
+ input
4873
+ );
4775
4874
  }
4776
4875
  /**
4777
4876
  * Get the current list of available effects.
@@ -4780,9 +4879,53 @@ var Session = class {
4780
4879
  getEffects() {
4781
4880
  const doc = this.client.doc;
4782
4881
  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) {
4882
+ const domainPackages = doc.domain?.packages;
4883
+ const packageCandidates = domainPackages && typeof domainPackages === "object" ? [
4884
+ domainPackages.domain,
4885
+ domainPackages["@sandbox/domain"],
4886
+ ...Object.values(domainPackages)
4887
+ ].filter(Boolean) : [];
4888
+ for (const domainPkg of packageCandidates) {
4889
+ if (domainPkg?.tools && Array.isArray(domainPkg.tools)) {
4890
+ for (const tool of domainPkg.tools) {
4891
+ if (!tool?.name || toolMap.has(tool.name)) continue;
4892
+ toolMap.set(tool.name, {
4893
+ name: tool.name,
4894
+ description: tool.description,
4895
+ inputSchema: tool.inputSchema,
4896
+ outputSchema: tool.outputSchema,
4897
+ className: tool.className || void 0,
4898
+ static: tool.static || false,
4899
+ ready: false,
4900
+ publishedAt: void 0
4901
+ });
4902
+ }
4903
+ }
4904
+ if (!domainPkg?.classes || typeof domainPkg.classes !== "object") {
4905
+ continue;
4906
+ }
4907
+ for (const [className, classDef] of Object.entries(
4908
+ domainPkg.classes
4909
+ )) {
4910
+ const methods = Array.isArray(classDef?.methods) ? classDef.methods : [];
4911
+ for (const method of methods) {
4912
+ if (!method?.name || toolMap.has(method.name)) continue;
4913
+ toolMap.set(method.name, {
4914
+ name: method.name,
4915
+ description: method.description,
4916
+ inputSchema: method.inputSchema,
4917
+ outputSchema: method.outputSchema,
4918
+ className: method.className || classDef?.name || className,
4919
+ static: method.static || false,
4920
+ ready: false,
4921
+ publishedAt: void 0
4922
+ });
4923
+ }
4924
+ }
4925
+ }
4926
+ const legacyDomainPkg = doc.domain?.packages?.domain;
4927
+ if (legacyDomainPkg?.tools && Array.isArray(legacyDomainPkg.tools)) {
4928
+ for (const tool of legacyDomainPkg.tools) {
4786
4929
  if (!tool?.name) continue;
4787
4930
  toolMap.set(tool.name, {
4788
4931
  name: tool.name,
@@ -4796,6 +4939,27 @@ var Session = class {
4796
4939
  });
4797
4940
  }
4798
4941
  }
4942
+ if (legacyDomainPkg?.classes && typeof legacyDomainPkg.classes === "object") {
4943
+ for (const [className, classDef] of Object.entries(
4944
+ legacyDomainPkg.classes
4945
+ )) {
4946
+ const methods = Array.isArray(classDef?.methods) ? classDef.methods : [];
4947
+ for (const method of methods) {
4948
+ if (!method?.name || toolMap.has(method.name)) continue;
4949
+ toolMap.set(method.name, {
4950
+ name: method.name,
4951
+ description: method.description,
4952
+ inputSchema: method.inputSchema,
4953
+ outputSchema: method.outputSchema,
4954
+ className: method.className || classDef?.name || className,
4955
+ static: method.static || false,
4956
+ ready: false,
4957
+ publishedAt: void 0
4958
+ });
4959
+ }
4960
+ }
4961
+ }
4962
+ const hasPolicyFilteredDomainTools = toolMap.size > 0;
4799
4963
  const catalogs = doc.catalog?.rawToolCatalogs || {};
4800
4964
  for (const [clientId, catalog] of Object.entries(catalogs)) {
4801
4965
  const cat = catalog;
@@ -4803,6 +4967,7 @@ var Session = class {
4803
4967
  for (const tool of cat.tools) {
4804
4968
  if (!tool?.name) continue;
4805
4969
  const existing = toolMap.get(tool.name);
4970
+ if (hasPolicyFilteredDomainTools && !existing) continue;
4806
4971
  if (existing?.publishedAt && cat.publishedAt && existing.publishedAt > cat.publishedAt)
4807
4972
  continue;
4808
4973
  const isLocal = clientId === this.clientId;
@@ -4822,6 +4987,24 @@ var Session = class {
4822
4987
  }
4823
4988
  return Array.from(toolMap.values());
4824
4989
  }
4990
+ /**
4991
+ * Return the currently open prompt payloads known to this session.
4992
+ *
4993
+ * These come from live `prompt` / `prompt.request` websocket events and
4994
+ * preserve the exact shape used by `answerPrompt(...)`.
4995
+ */
4996
+ getPrompts() {
4997
+ return Array.from(this.promptCache.values()).map((prompt) => ({
4998
+ ...prompt,
4999
+ options: Array.isArray(prompt.options) ? prompt.options.map(
5000
+ (option) => typeof option === "string" ? option : { ...option }
5001
+ ) : void 0,
5002
+ metadata: prompt.metadata ? { ...prompt.metadata } : void 0
5003
+ }));
5004
+ }
5005
+ getHiddenPromptIds() {
5006
+ return Array.from(this.hiddenPromptIds);
5007
+ }
4825
5008
  /**
4826
5009
  * Backwards-compatible alias for `getEffects()`.
4827
5010
  */
@@ -4921,11 +5104,7 @@ var Session = class {
4921
5104
  if (!normalizedDocs) {
4922
5105
  return normalizedTypes;
4923
5106
  }
4924
- return [
4925
- normalizedTypes,
4926
- "Generated usage notes from ./sandbox-tools docs:",
4927
- normalizedDocs
4928
- ].join("\n\n");
5107
+ return [normalizedTypes, "[Docs]", normalizedDocs].join("\n\n");
4929
5108
  }
4930
5109
  if (normalizedDocs) {
4931
5110
  return normalizedDocs;
@@ -5147,6 +5326,7 @@ import { ${allImports} } from "./sandbox-tools";
5147
5326
  const emitPrompt = (payload) => {
5148
5327
  const prompt = normalizePrompt(payload);
5149
5328
  if (!prompt) return;
5329
+ this.hiddenPromptIds.delete(prompt.id);
5150
5330
  this.promptCache.set(prompt.id, prompt);
5151
5331
  this.emit("prompt", prompt);
5152
5332
  };
@@ -5329,6 +5509,7 @@ var JobImplementation = class {
5329
5509
  eventListeners = /* @__PURE__ */ new Map();
5330
5510
  bufferedAgentMessages = [];
5331
5511
  bufferedAgentMessageIds = /* @__PURE__ */ new Set();
5512
+ resultSettled = false;
5332
5513
  metadata;
5333
5514
  constructor(id, client, initialState) {
5334
5515
  this.id = id;
@@ -5353,7 +5534,9 @@ var JobImplementation = class {
5353
5534
  if (execData.error) {
5354
5535
  this.finalize("failed", void 0, execData.error);
5355
5536
  } else {
5356
- this.finalize("succeeded", execData.result);
5537
+ this.finalize("succeeded", execData.result, void 0, {
5538
+ hasResult: Object.prototype.hasOwnProperty.call(execData, "result")
5539
+ });
5357
5540
  }
5358
5541
  this.emit("status", this.status);
5359
5542
  }
@@ -5389,9 +5572,6 @@ var JobImplementation = class {
5389
5572
  if (normalizedStatus === "failed" || normalizedStatus === "timeout" || normalizedStatus === "canceled") {
5390
5573
  this.finalize(normalizedStatus);
5391
5574
  }
5392
- if (normalizedStatus === "succeeded") {
5393
- this.finalize("succeeded");
5394
- }
5395
5575
  this.emit("status", normalizedStatus);
5396
5576
  });
5397
5577
  this.client.on(`job.${id}.stdout`, (line) => {
@@ -5411,7 +5591,7 @@ var JobImplementation = class {
5411
5591
  this.emit("stderr", line);
5412
5592
  });
5413
5593
  this.client.on(`job.${id}.result`, (result) => {
5414
- this.finalize("succeeded", result);
5594
+ this.finalize("succeeded", result, void 0, { hasResult: true });
5415
5595
  });
5416
5596
  this.client.on(`job.${id}.error`, (error) => {
5417
5597
  this.finalize("failed", void 0, error);
@@ -5432,7 +5612,9 @@ var JobImplementation = class {
5432
5612
  this.client.on("job.completed", (data) => {
5433
5613
  const jobData = data;
5434
5614
  if (jobData.jobId === id) {
5435
- this.finalize("succeeded", jobData.result);
5615
+ this.finalize("succeeded", jobData.result, void 0, {
5616
+ hasResult: true
5617
+ });
5436
5618
  this.emit("status", this.status);
5437
5619
  }
5438
5620
  });
@@ -5557,7 +5739,7 @@ var JobImplementation = class {
5557
5739
  this.metadata.status = "running";
5558
5740
  }
5559
5741
  }
5560
- finalize(status, result, error) {
5742
+ finalize(status, result, error, options = {}) {
5561
5743
  if (!this.metadata.startedAt) {
5562
5744
  this.metadata.startedAt = Date.now();
5563
5745
  }
@@ -5565,14 +5747,18 @@ var JobImplementation = class {
5565
5747
  this.metadata.status = status;
5566
5748
  this.metadata.completedAt = this.metadata.completedAt || Date.now();
5567
5749
  this.metadata.durationMs = this.metadata.completedAt - this.metadata.startedAt;
5568
- if (result !== void 0) {
5750
+ if (!this.resultSettled && (options.hasResult || result !== void 0)) {
5569
5751
  this.metadata.result = sanitizeFeedbackValue(result);
5752
+ this.resultSettled = true;
5570
5753
  this._resolveResult(result);
5571
5754
  }
5572
- if (error !== void 0) {
5573
- const message = error instanceof Error ? error.message : String(error);
5755
+ if (!this.resultSettled && (error !== void 0 || status === "failed" || status === "timeout" || status === "canceled")) {
5756
+ const fallbackError = new Error(`Job ${this.id} ${status}.`);
5757
+ const cause = error ?? fallbackError;
5758
+ const message = cause instanceof Error ? cause.message : String(cause);
5574
5759
  this.metadata.error = truncateFeedbackString(message);
5575
- this._rejectResult(error);
5760
+ this.resultSettled = true;
5761
+ this._rejectResult(cause);
5576
5762
  }
5577
5763
  }
5578
5764
  upsertToolCall(next) {
@@ -5655,6 +5841,17 @@ function humanTextFromStdout(stdout) {
5655
5841
  }
5656
5842
  return null;
5657
5843
  }
5844
+ function responseTextFromAgentMessages(agentMessages) {
5845
+ for (const message of [...agentMessages].reverse()) {
5846
+ const record = asRecord2(message);
5847
+ if (!record) continue;
5848
+ for (const key of RESPONSE_KEYS) {
5849
+ const normalized = normalizeText(record[key]);
5850
+ if (normalized) return normalized;
5851
+ }
5852
+ }
5853
+ return null;
5854
+ }
5658
5855
  function pushString(target, value) {
5659
5856
  if (typeof value === "string" && value.trim()) {
5660
5857
  target.add(value.trim());
@@ -5680,6 +5877,41 @@ function collectReferencesFromRecord(record, refs) {
5680
5877
  for (const key of VARIABLE_ARRAY_KEY_CANDIDATES)
5681
5878
  pushStringArray(refs.variableNames, record[key]);
5682
5879
  }
5880
+ function stringValue(record, keys) {
5881
+ for (const key of keys) {
5882
+ const value = record[key];
5883
+ if (typeof value === "string" && value.trim()) {
5884
+ return value.trim();
5885
+ }
5886
+ }
5887
+ return null;
5888
+ }
5889
+ function findEntryPathForRecord(record, heap) {
5890
+ const directPath = stringValue(record, ["entryPath", "path"]);
5891
+ if (directPath && heap.entriesByPath?.[directPath]) {
5892
+ return directPath;
5893
+ }
5894
+ const id = stringValue(record, ["id", "_id", "recordId", "objectId"]);
5895
+ if (!id) {
5896
+ return null;
5897
+ }
5898
+ const className = stringValue(record, [
5899
+ "className",
5900
+ "_className",
5901
+ "__className",
5902
+ "prototype",
5903
+ "type"
5904
+ ]);
5905
+ const entries = Object.values(heap.entriesByPath || {});
5906
+ const exact = entries.find(
5907
+ (entry) => entry.id === id && (!className || entry.className === className || entry.prototypes?.includes(className))
5908
+ );
5909
+ if (exact?.path) {
5910
+ return exact.path;
5911
+ }
5912
+ const idOnlyMatches = entries.filter((entry) => entry.id === id);
5913
+ return idOnlyMatches.length === 1 ? idOnlyMatches[0].path : null;
5914
+ }
5683
5915
  function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__ */ new Set()) {
5684
5916
  if (value === null || value === void 0 || depth > 4 || seen.has(value))
5685
5917
  return;
@@ -5700,6 +5932,8 @@ function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__
5700
5932
  const record = asRecord2(value);
5701
5933
  if (!record) return;
5702
5934
  seen.add(value);
5935
+ const entryPath = findEntryPathForRecord(record, heap);
5936
+ if (entryPath) refs.entryPaths.add(entryPath);
5703
5937
  collectReferencesFromRecord(record, refs);
5704
5938
  for (const key of UI_CONTAINER_KEYS) {
5705
5939
  const nested = asRecord2(record[key]);
@@ -5808,6 +6042,7 @@ function resolveJobPresentation({
5808
6042
  jobId,
5809
6043
  result,
5810
6044
  stdout = [],
6045
+ agentMessages = [],
5811
6046
  sessionHeap,
5812
6047
  allowExplicitArtifacts = true
5813
6048
  }) {
@@ -5840,7 +6075,7 @@ function resolveJobPresentation({
5840
6075
  const hasExplicitArtifacts = allowExplicitArtifacts && (explicitEntries.length > 0 || explicitLists.length > 0);
5841
6076
  const lists = hasExplicitArtifacts ? explicitLists : jobLists;
5842
6077
  const entries = hasExplicitArtifacts ? explicitEntries : changedEntries;
5843
- const responseText = extractResponseText(result, stdout) || fallbackResponseText(entries, lists);
6078
+ const responseText = extractResponseText(result, stdout) || responseTextFromAgentMessages(agentMessages) || fallbackResponseText(entries, lists);
5844
6079
  return {
5845
6080
  responseText,
5846
6081
  entries,
@@ -10316,6 +10551,67 @@ external_exports.object({
10316
10551
  transitions: external_exports.array(StateMachineTransitionSchema),
10317
10552
  finalStates: external_exports.array(external_exports.string()).optional()
10318
10553
  }).strict();
10554
+ var POLICY_OPERATORS = [
10555
+ "eq",
10556
+ "neq",
10557
+ "gt",
10558
+ "gte",
10559
+ "lt",
10560
+ "lte",
10561
+ "contains",
10562
+ "not_contains",
10563
+ "starts_with",
10564
+ "ends_with",
10565
+ "exists"
10566
+ ];
10567
+ var PolicyPredicateSchema = external_exports.object({
10568
+ path: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional(),
10569
+ field: external_exports.string().optional(),
10570
+ input: external_exports.string().optional(),
10571
+ operator: external_exports.enum([...POLICY_OPERATORS]),
10572
+ stringValue: external_exports.string().optional(),
10573
+ numberValue: external_exports.number().optional(),
10574
+ booleanValue: external_exports.boolean().optional(),
10575
+ value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()]).optional()
10576
+ }).strict();
10577
+ var PolicyStateMachinePredicateSchema = external_exports.object({
10578
+ machine: external_exports.string().min(1),
10579
+ operator: external_exports.enum([...POLICY_OPERATORS]),
10580
+ state: external_exports.string().optional(),
10581
+ stringValue: external_exports.string().optional()
10582
+ }).strict();
10583
+ var PolicyConditionSchema = external_exports.lazy(
10584
+ () => external_exports.object({
10585
+ all: external_exports.array(PolicyConditionSchema).optional(),
10586
+ any: external_exports.array(PolicyConditionSchema).optional(),
10587
+ not: PolicyConditionSchema.optional(),
10588
+ input: PolicyPredicateSchema.optional(),
10589
+ object: PolicyPredicateSchema.optional(),
10590
+ stateMachine: PolicyStateMachinePredicateSchema.optional()
10591
+ }).strict().refine(
10592
+ (data) => [
10593
+ data.all,
10594
+ data.any,
10595
+ data.not,
10596
+ data.input,
10597
+ data.object,
10598
+ data.stateMachine
10599
+ ].filter((value) => value !== void 0).length === 1,
10600
+ {
10601
+ message: "Policy condition must define exactly one of all, any, not, input, object, or stateMachine"
10602
+ }
10603
+ )
10604
+ );
10605
+ var PolicyRuleSchema = external_exports.object({
10606
+ id: external_exports.string().min(1).optional(),
10607
+ reason: external_exports.string().optional(),
10608
+ when: PolicyConditionSchema
10609
+ }).strict();
10610
+ var PoliciesSchema = external_exports.object({
10611
+ allowWhen: external_exports.array(PolicyRuleSchema).optional(),
10612
+ confirmWhen: external_exports.array(PolicyRuleSchema).optional(),
10613
+ denyWhen: external_exports.array(PolicyRuleSchema).optional()
10614
+ }).strict();
10319
10615
  external_exports.object({
10320
10616
  postCondition: external_exports.union([
10321
10617
  external_exports.string(),
@@ -10345,7 +10641,8 @@ external_exports.object({
10345
10641
  reason: external_exports.string().optional(),
10346
10642
  mode: external_exports.string().optional()
10347
10643
  }).strict()
10348
- ]).optional()
10644
+ ]).optional(),
10645
+ policies: PoliciesSchema.optional()
10349
10646
  }).strict();
10350
10647
 
10351
10648
  // ../metamodel-core/src/index.ts
@@ -11019,6 +11316,110 @@ async function invokeRegisteredEffect(effectMap, request) {
11019
11316
  return resolved.handler(request.input, context);
11020
11317
  }
11021
11318
 
11319
+ // src/spend.ts
11320
+ function toGranularHttpBase(apiUrl) {
11321
+ const url = new URL(apiUrl);
11322
+ if (url.protocol === "ws:") {
11323
+ url.protocol = "http:";
11324
+ } else if (url.protocol === "wss:") {
11325
+ url.protocol = "https:";
11326
+ }
11327
+ url.pathname = url.pathname.replace(/\/ws\/connect$/, "").replace(/\/ws$/, "");
11328
+ if (!url.pathname || url.pathname === "/") {
11329
+ url.pathname = "/granular";
11330
+ }
11331
+ url.search = "";
11332
+ url.hash = "";
11333
+ return url.toString().replace(/\/$/, "");
11334
+ }
11335
+ function cleanIdPart(value) {
11336
+ return value.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "");
11337
+ }
11338
+ function buildOpenAISpendEventId(usage, context = {}) {
11339
+ const requestId = usage.requestId?.trim();
11340
+ if (!requestId) return void 0;
11341
+ const scope = context.sessionId || context.environmentId || context.subjectId || context.sandboxId || "global";
11342
+ return ["spend", "openai", scope, requestId].map(cleanIdPart).join("_");
11343
+ }
11344
+ function pricingEffectiveAtSeconds(value) {
11345
+ if (!value) return null;
11346
+ const parsed = Date.parse(value);
11347
+ return Number.isFinite(parsed) ? Math.floor(parsed / 1e3) : null;
11348
+ }
11349
+ function compactContext(context) {
11350
+ return Object.fromEntries(
11351
+ Object.entries(context).filter(
11352
+ ([, value]) => value != null && value !== ""
11353
+ )
11354
+ );
11355
+ }
11356
+ function omitTenantId(context) {
11357
+ const scopedContext = { ...context };
11358
+ delete scopedContext.tenantId;
11359
+ return scopedContext;
11360
+ }
11361
+ async function recordOpenAIUsageSpend(options) {
11362
+ const usageContext = compactContext({
11363
+ ...options.usage.usageContext || {},
11364
+ ...options.context || {}
11365
+ });
11366
+ const context = omitTenantId(usageContext);
11367
+ const spendEventId = options.usage.spendEventId || buildOpenAISpendEventId(options.usage, context);
11368
+ const metadata = {
11369
+ ...options.metadata || {},
11370
+ ...options.usage.rawUsage !== void 0 ? { openaiUsage: options.usage.rawUsage } : {},
11371
+ usageContext: context
11372
+ };
11373
+ const response = await fetch(
11374
+ `${toGranularHttpBase(options.apiUrl)}/control/spend/events`,
11375
+ {
11376
+ method: "POST",
11377
+ cache: "no-store",
11378
+ headers: {
11379
+ Authorization: `Bearer ${options.token}`,
11380
+ "Content-Type": "application/json"
11381
+ },
11382
+ body: JSON.stringify({
11383
+ ...spendEventId ? { spendEventId } : {},
11384
+ sandboxId: context.sandboxId || null,
11385
+ environmentId: context.environmentId || null,
11386
+ sessionId: context.sessionId || null,
11387
+ subjectId: context.subjectId || null,
11388
+ permissionProfileId: context.permissionProfileId || null,
11389
+ source: "openai",
11390
+ lineItemType: "llm_tokens",
11391
+ provider: options.usage.provider,
11392
+ model: options.usage.model,
11393
+ operation: options.usage.operation || "chat.completions",
11394
+ requestId: options.usage.requestId || null,
11395
+ inputTokens: options.usage.inputTokens,
11396
+ outputTokens: options.usage.outputTokens,
11397
+ cachedInputTokens: options.usage.cachedInputTokens,
11398
+ reasoningTokens: options.usage.reasoningTokens,
11399
+ quantity: options.usage.totalTokens,
11400
+ quantityUnit: "tokens",
11401
+ inputPricePerMillionMicros: options.usage.inputPricePerMillionMicros,
11402
+ cachedInputPricePerMillionMicros: options.usage.cachedInputPricePerMillionMicros,
11403
+ outputPricePerMillionMicros: options.usage.outputPricePerMillionMicros,
11404
+ amountMicros: options.usage.amountMicros,
11405
+ currency: options.usage.currency,
11406
+ pricingSource: options.usage.pricingSource,
11407
+ pricingEffectiveAt: pricingEffectiveAtSeconds(
11408
+ options.usage.pricingEffectiveAt
11409
+ ),
11410
+ estimated: false,
11411
+ metadata
11412
+ })
11413
+ }
11414
+ );
11415
+ if (!response.ok) {
11416
+ throw new Error(
11417
+ `Granular spend event failed (${response.status}): ${await response.text()}`
11418
+ );
11419
+ }
11420
+ return response.json();
11421
+ }
11422
+
11022
11423
  // ../metamodel-enum/src/index.ts
11023
11424
  function renderInlineStringUnion(values) {
11024
11425
  return values.map((value) => JSON.stringify(value)).join(" | ");
@@ -11377,6 +11778,148 @@ var noteMetamodelPackage = defineMetamodelPackage({
11377
11778
  }
11378
11779
  });
11379
11780
 
11781
+ // ../policy-engine/src/index.ts
11782
+ function isRecord(value) {
11783
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
11784
+ }
11785
+ function normalizePath(value) {
11786
+ if (Array.isArray(value)) {
11787
+ return value.map((part) => String(part)).filter(Boolean);
11788
+ }
11789
+ if (typeof value === "string") {
11790
+ return value.includes(".") ? value.split(".").filter(Boolean) : [value];
11791
+ }
11792
+ return [];
11793
+ }
11794
+ function firstDefinedValue(spec) {
11795
+ if ("value" in spec) return spec.value;
11796
+ if ("stringValue" in spec) return spec.stringValue;
11797
+ if ("numberValue" in spec) return spec.numberValue;
11798
+ if ("booleanValue" in spec) return spec.booleanValue;
11799
+ if ("state" in spec) return spec.state;
11800
+ return void 0;
11801
+ }
11802
+ function normalizeCondition(input) {
11803
+ if (input === void 0 || input === null) return { kind: "always" };
11804
+ if (!isRecord(input)) {
11805
+ throw new Error("Policy condition must be an object");
11806
+ }
11807
+ if (Array.isArray(input.all)) {
11808
+ return {
11809
+ kind: "all",
11810
+ conditions: input.all.map((item) => normalizeCondition(item))
11811
+ };
11812
+ }
11813
+ if (Array.isArray(input.any)) {
11814
+ return {
11815
+ kind: "any",
11816
+ conditions: input.any.map((item) => normalizeCondition(item))
11817
+ };
11818
+ }
11819
+ if (input.not !== void 0) {
11820
+ return { kind: "not", condition: normalizeCondition(input.not) };
11821
+ }
11822
+ for (const source of ["input", "object", "stateMachine"]) {
11823
+ const raw = input[source];
11824
+ if (!isRecord(raw)) continue;
11825
+ const operator = raw.operator;
11826
+ 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") {
11827
+ throw new Error(`Unsupported policy operator: ${String(operator)}`);
11828
+ }
11829
+ if (source === "stateMachine") {
11830
+ const machine = typeof raw.machine === "string" ? raw.machine : "";
11831
+ if (!machine) throw new Error("stateMachine condition requires machine");
11832
+ return {
11833
+ kind: "predicate",
11834
+ source,
11835
+ path: [machine],
11836
+ machine,
11837
+ operator,
11838
+ value: firstDefinedValue(raw)
11839
+ };
11840
+ }
11841
+ const path = normalizePath(raw.path ?? raw.field ?? raw.input);
11842
+ if (path.length === 0) {
11843
+ throw new Error(`${source} condition requires a path`);
11844
+ }
11845
+ return {
11846
+ kind: "predicate",
11847
+ source,
11848
+ path,
11849
+ operator,
11850
+ value: firstDefinedValue(raw)
11851
+ };
11852
+ }
11853
+ throw new Error(
11854
+ "Policy condition must contain all, any, not, input, object, or stateMachine"
11855
+ );
11856
+ }
11857
+ function summarizeCondition(condition) {
11858
+ switch (condition.kind) {
11859
+ case "always":
11860
+ return "always";
11861
+ case "all":
11862
+ return condition.conditions.map(summarizeCondition).join(" and ");
11863
+ case "any":
11864
+ return condition.conditions.map(summarizeCondition).join(" or ");
11865
+ case "not":
11866
+ return `not (${summarizeCondition(condition.condition)})`;
11867
+ case "predicate": {
11868
+ const path = condition.source === "stateMachine" ? `stateMachine.${condition.machine || condition.path.join(".")}` : `${condition.source}.${condition.path.join(".")}`;
11869
+ if (condition.operator === "exists") return `${path} exists`;
11870
+ return `${path} ${condition.operator} ${String(condition.value)}`;
11871
+ }
11872
+ }
11873
+ }
11874
+
11875
+ // ../metamodel-policy/src/index.ts
11876
+ function escapeGraphqlString(value) {
11877
+ return JSON.stringify(value);
11878
+ }
11879
+ function buildPolicyMutations(effectKey, spec) {
11880
+ const policies = spec.policies;
11881
+ if (!policies) return [];
11882
+ const mutations = [];
11883
+ const addRules = (key, outcome) => {
11884
+ const rules = policies[key] || [];
11885
+ rules.forEach((rule, index) => {
11886
+ const condition = normalizeCondition(rule.when);
11887
+ const summary = rule.reason || summarizeCondition(condition);
11888
+ const id = rule.id || `${effectKey}:${outcome}:${index + 1}`;
11889
+ mutations.push({
11890
+ label: `set policy ${outcome} on ${effectKey}`,
11891
+ 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))}) }`
11892
+ });
11893
+ });
11894
+ };
11895
+ addRules("allowWhen", "allow");
11896
+ addRules("confirmWhen", "confirm");
11897
+ addRules("denyWhen", "deny");
11898
+ return mutations;
11899
+ }
11900
+ var policyMetamodelPackage = defineMetamodelPackage({
11901
+ id: "policy",
11902
+ manifest: {
11903
+ buildEffectMutations: buildPolicyMutations
11904
+ },
11905
+ summary: {
11906
+ selections: {
11907
+ methodFields: ["policies"]
11908
+ },
11909
+ readMethodSummary(rawMethod) {
11910
+ return rawMethod.policies ? { metamodels: { policies: rawMethod.policies } } : {};
11911
+ }
11912
+ },
11913
+ docs: {
11914
+ effectRows: [
11915
+ {
11916
+ key: "policies",
11917
+ description: "Universal effect policies with allowWhen, confirmWhen, and denyWhen structural conditions."
11918
+ }
11919
+ ]
11920
+ }
11921
+ });
11922
+
11380
11923
  // ../metamodel-required/src/index.ts
11381
11924
  function buildRequiredFieldMutations(fieldPath, required) {
11382
11925
  if (!required) return [];
@@ -12151,7 +12694,8 @@ var DEFAULT_METAMODEL_PACKAGES = [
12151
12694
  searchableMetamodelPackage,
12152
12695
  validationRuleMetamodelPackage,
12153
12696
  stateMachineMetamodelPackage,
12154
- effectBehaviorsMetamodelPackage
12697
+ effectBehaviorsMetamodelPackage,
12698
+ policyMetamodelPackage
12155
12699
  ];
12156
12700
  createMetamodelRegistry(
12157
12701
  DEFAULT_METAMODEL_PACKAGES
@@ -12218,6 +12762,12 @@ var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_COUNT = 3;
12218
12762
  var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_DELAY_MS = 1e3;
12219
12763
  var LOCAL_CONTROL_REQUEST_RETRY_COUNT = 4;
12220
12764
  var LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS = 500;
12765
+ var SESSION_DATA_REQUEST_RETRY_COUNT = 4;
12766
+ var SESSION_DATA_REQUEST_RETRY_DELAY_MS = 500;
12767
+ var EFFECT_HOST_CONNECT_TIMEOUT_MS = 15e3;
12768
+ var EFFECT_CATALOG_SYNC_TIMEOUT_MS = 3e4;
12769
+ var EFFECT_CATALOG_SYNC_RETRY_COUNT = 3;
12770
+ var EFFECT_CATALOG_SYNC_RETRY_DELAY_MS = 1e3;
12221
12771
  function planRecordObjectsChunks(records, batchSize) {
12222
12772
  const total = records.length;
12223
12773
  const size = Math.max(1, Math.min(batchSize, total));
@@ -12232,6 +12782,19 @@ function planRecordObjectsChunks(records, batchSize) {
12232
12782
  function sleep(ms) {
12233
12783
  return new Promise((resolve) => setTimeout(resolve, ms));
12234
12784
  }
12785
+ function withTimeout(promise, timeoutMs, label) {
12786
+ let timer = null;
12787
+ const timeout = new Promise((_, reject) => {
12788
+ timer = setTimeout(() => {
12789
+ reject(new Error(`${label} timed out after ${timeoutMs}ms`));
12790
+ }, timeoutMs);
12791
+ });
12792
+ return Promise.race([promise, timeout]).finally(() => {
12793
+ if (timer) {
12794
+ clearTimeout(timer);
12795
+ }
12796
+ });
12797
+ }
12235
12798
  function isLocalControlUrl(url) {
12236
12799
  try {
12237
12800
  const parsed = new URL(url);
@@ -12245,7 +12808,19 @@ function isRetryableLocalWorkerRestart(status, body, url) {
12245
12808
  }
12246
12809
  function isRetryableRecordObjectsError(error) {
12247
12810
  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(
12811
+ 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(
12812
+ message
12813
+ );
12814
+ }
12815
+ function isRetryableEffectRegistrationError(error) {
12816
+ const message = error instanceof Error ? error.message : String(error);
12817
+ 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(
12818
+ message
12819
+ );
12820
+ }
12821
+ function isRetryableSessionDataError(error) {
12822
+ const message = error instanceof Error ? error.message : String(error);
12823
+ 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
12824
  message
12250
12825
  );
12251
12826
  }
@@ -12267,16 +12842,28 @@ function computeEffectRegistrationKey(effect) {
12267
12842
  effect.versionSelector
12268
12843
  )}`;
12269
12844
  }
12270
- function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId) {
12271
- const url = new URL(apiUrl);
12272
- if (url.pathname.endsWith("/granular/ws/connect")) {
12845
+ function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId, effectHostUrl) {
12846
+ const overrideUrl = effectHostUrl || process.env.GRANULAR_EFFECT_HOST_URL || process.env.EFFECT_HOST_URL;
12847
+ const api = new URL(apiUrl);
12848
+ const localRuntimeBase = process.env.RUNTIME_ORCHESTRATOR_URL || (isLocalControlUrl(apiUrl) ? `${api.protocol}//${api.hostname}:8791` : "");
12849
+ const url = new URL(overrideUrl || localRuntimeBase || apiUrl);
12850
+ if (url.protocol === "https:") {
12851
+ url.protocol = "wss:";
12852
+ } else if (url.protocol === "http:") {
12853
+ url.protocol = "ws:";
12854
+ }
12855
+ if (!overrideUrl && isLocalControlUrl(apiUrl) && api.pathname.endsWith("/granular")) {
12856
+ url.pathname = "/granular/orchestrator/effects/connect";
12857
+ } else if (url.pathname.endsWith("/granular/ws/connect")) {
12273
12858
  url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
12274
12859
  } else if (url.pathname.endsWith("/granular")) {
12275
- url.pathname = `${url.pathname.replace(/\/$/, "")}/effects/connect`;
12860
+ url.pathname = isLocalControlUrl(url.toString()) ? "/granular/orchestrator/effects/connect" : `${url.pathname.replace(/\/$/, "")}/effects/connect`;
12276
12861
  } else if (url.pathname.endsWith("/v2/ws/connect")) {
12277
12862
  url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
12278
12863
  } else if (url.pathname.endsWith("/v2/ws")) {
12279
12864
  url.pathname = url.pathname.replace(/\/ws$/, "/effects/connect");
12865
+ } else if (url.pathname === "/" && isLocalControlUrl(url.toString()) && (url.port === "8791" || !overrideUrl && Boolean(localRuntimeBase))) {
12866
+ url.pathname = "/granular/orchestrator/effects/connect";
12280
12867
  } else if (url.pathname.endsWith("/ws/connect")) {
12281
12868
  url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
12282
12869
  } else if (url.pathname.endsWith("/ws")) {
@@ -12311,6 +12898,79 @@ function normalizeHeapSnapshot(raw) {
12311
12898
  updatedAt: typeof heap.updatedAt === "number" ? heap.updatedAt : Date.now()
12312
12899
  };
12313
12900
  }
12901
+ function normalizeGraphPathSegment(value) {
12902
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
12903
+ }
12904
+ function extractRecordIdFromGraphPath(path, className) {
12905
+ const normalizedPrefix = `${normalizeGraphPathSegment(className)}_`;
12906
+ if (path.startsWith(normalizedPrefix)) {
12907
+ return path.slice(normalizedPrefix.length);
12908
+ }
12909
+ const legacyPrefix = `${className}_`;
12910
+ if (path.startsWith(legacyPrefix)) {
12911
+ return path.slice(legacyPrefix.length);
12912
+ }
12913
+ return path;
12914
+ }
12915
+ function toRecordSearchResult(className, node) {
12916
+ const path = typeof node.path === "string" ? node.path : "";
12917
+ if (!path) return null;
12918
+ const fields = Array.isArray(node.submodels) ? node.submodels.flatMap(
12919
+ (submodel) => {
12920
+ const name = typeof submodel?.label === "string" && submodel.label.trim() ? submodel.label : typeof submodel?.path === "string" ? submodel.path.split(":").pop() || submodel.path : "";
12921
+ if (!name) return [];
12922
+ if (typeof submodel.string_value === "string") {
12923
+ return [{ name, type: "string", value: submodel.string_value }];
12924
+ }
12925
+ if (typeof submodel.number_value === "number") {
12926
+ return [{ name, type: "number", value: submodel.number_value }];
12927
+ }
12928
+ if (typeof submodel.boolean_value === "boolean") {
12929
+ return [
12930
+ {
12931
+ name,
12932
+ type: "boolean",
12933
+ value: submodel.boolean_value
12934
+ }
12935
+ ];
12936
+ }
12937
+ return [];
12938
+ }
12939
+ ) : [];
12940
+ return {
12941
+ path,
12942
+ className,
12943
+ id: extractRecordIdFromGraphPath(path, className),
12944
+ label: typeof node.label === "string" && node.label.trim() ? node.label : extractRecordIdFromGraphPath(path, className),
12945
+ description: typeof node.description === "string" && node.description.trim() ? node.description : null,
12946
+ fields
12947
+ };
12948
+ }
12949
+ function normalizeRecordSearchText(value) {
12950
+ return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, " ").replace(/\s+/g, " ").trim();
12951
+ }
12952
+ function rankRecordSearchResult(result, query, index) {
12953
+ const normalizedQuery = normalizeRecordSearchText(query);
12954
+ if (!normalizedQuery) {
12955
+ return index;
12956
+ }
12957
+ const label = normalizeRecordSearchText(result.label || "");
12958
+ const id = normalizeRecordSearchText(result.id || "");
12959
+ const path = normalizeRecordSearchText(result.path || "");
12960
+ const className = normalizeRecordSearchText(result.className || "");
12961
+ const searchable = [label, id, path, className].filter(Boolean);
12962
+ if (label === normalizedQuery) return index;
12963
+ if (id === normalizedQuery || path === normalizedQuery) return 100 + index;
12964
+ if (label.startsWith(normalizedQuery)) return 200 + index;
12965
+ if (searchable.some((value) => value.startsWith(normalizedQuery))) {
12966
+ return 300 + index;
12967
+ }
12968
+ if (label.includes(normalizedQuery)) return 400 + index;
12969
+ if (searchable.some((value) => value.includes(normalizedQuery))) {
12970
+ return 500 + index;
12971
+ }
12972
+ return 900 + index;
12973
+ }
12314
12974
  function deriveRuntimeBaseUrl(apiEndpoint) {
12315
12975
  try {
12316
12976
  const endpoint = new URL(apiEndpoint);
@@ -12399,7 +13059,7 @@ function normalizeEnvironmentData(environment) {
12399
13059
  setup: normalizeEnvironmentSetupSummary(environment.setup)
12400
13060
  };
12401
13061
  }
12402
- var Environment = class {
13062
+ var Environment = class _Environment {
12403
13063
  granular;
12404
13064
  envData;
12405
13065
  _apiKey;
@@ -12594,28 +13254,30 @@ var Environment = class {
12594
13254
  return response.json();
12595
13255
  }
12596
13256
  // ==================== ID ↔ GRAPH PATH MAPPING ====================
13257
+ static normalizeGraphPathSegment(value) {
13258
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
13259
+ }
12597
13260
  /**
12598
- * Convert a class name + real-world ID into a unique graph path.
13261
+ * Convert a class name + application record ID into Granular's graph path.
12599
13262
  *
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.
12604
- *
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`.
13263
+ * This mirrors the record-write path normalization used by the control plane.
13264
+ * Keep the original customer/system ID in `real_id`; graph paths are stable
13265
+ * internal addresses, not the source of truth for business identity.
12608
13266
  */
12609
13267
  static toGraphPath(className, id) {
12610
- return `${className}_${id}`;
13268
+ return `${_Environment.normalizeGraphPathSegment(className)}_${_Environment.normalizeGraphPathSegment(id)}`;
12611
13269
  }
12612
13270
  /**
12613
- * Extract the real-world ID from a graph path, given the class name.
13271
+ * Best-effort extraction of an ID-like suffix from a graph path.
12614
13272
  *
12615
- * Strips the `{className}_` prefix. Returns the raw path if the
12616
- * expected prefix is not found.
13273
+ * Prefer the record's `real_id` field whenever exact customer/system IDs
13274
+ * matter, because graph path normalization is intentionally lossy.
12617
13275
  */
12618
13276
  static extractIdFromGraphPath(graphPath, className) {
13277
+ const normalizedPrefix = `${_Environment.normalizeGraphPathSegment(className)}_`;
13278
+ if (graphPath.startsWith(normalizedPrefix)) {
13279
+ return graphPath.substring(normalizedPrefix.length);
13280
+ }
12619
13281
  const prefix = `${className}_`;
12620
13282
  return graphPath.startsWith(prefix) ? graphPath.substring(prefix.length) : graphPath;
12621
13283
  }
@@ -12662,6 +13324,62 @@ var Environment = class {
12662
13324
  }
12663
13325
  return response.json();
12664
13326
  }
13327
+ async searchRecords(query, options = {}) {
13328
+ const normalizedQuery = query.replace(/\s+/g, " ").trim();
13329
+ const limit = Math.max(1, Math.min(50, Math.floor(options.limit ?? 12)));
13330
+ const offset = Math.max(0, Math.floor(options.offset ?? 0));
13331
+ const response = await this.graphql(
13332
+ `
13333
+ query RecordMentionSearch(
13334
+ $query: String
13335
+ $limit: Int
13336
+ $offset: Int
13337
+ $classNames: [String!]
13338
+ ) {
13339
+ record_search(
13340
+ query: $query
13341
+ limit: $limit
13342
+ offset: $offset
13343
+ class_names: $classNames
13344
+ ) {
13345
+ className
13346
+ model {
13347
+ path
13348
+ label
13349
+ description
13350
+ submodels {
13351
+ path
13352
+ label
13353
+ string_value
13354
+ number_value
13355
+ boolean_value
13356
+ }
13357
+ }
13358
+ }
13359
+ }
13360
+ `,
13361
+ {
13362
+ query: normalizedQuery,
13363
+ limit,
13364
+ offset,
13365
+ classNames: options.classNames?.length ? options.classNames : []
13366
+ }
13367
+ );
13368
+ const seen = /* @__PURE__ */ new Set();
13369
+ const results = (response.data?.record_search || []).flatMap((entry) => {
13370
+ const className = entry.className?.trim();
13371
+ const item = className && entry.model ? toRecordSearchResult(className, entry.model) : null;
13372
+ if (!item || seen.has(item.path)) {
13373
+ return [];
13374
+ }
13375
+ seen.add(item.path);
13376
+ return [item];
13377
+ });
13378
+ return results.map((result, index) => ({
13379
+ result,
13380
+ rank: rankRecordSearchResult(result, normalizedQuery, index)
13381
+ })).sort((left, right) => left.rank - right.rank).map((item) => item.result).slice(0, limit);
13382
+ }
12665
13383
  // ==================== RELATIONSHIP METHODS ====================
12666
13384
  /**
12667
13385
  * Define a relationship between two model types.
@@ -13427,7 +14145,8 @@ var Environment = class {
13427
14145
  body: JSON.stringify({
13428
14146
  records,
13429
14147
  batchSize: options.batchSize,
13430
- setupRunId: options.setupRunId
14148
+ setupRunId: options.setupRunId,
14149
+ writeMode: options.writeMode
13431
14150
  })
13432
14151
  }
13433
14152
  );
@@ -13479,11 +14198,13 @@ var Environment = class {
13479
14198
  };
13480
14199
  var EnvironmentSession = class extends Session {
13481
14200
  environment;
14201
+ sessionDataRoutePrefix;
13482
14202
  /** The last known graph container status, updated by checkReadiness() or on heartbeat */
13483
14203
  graphContainerStatus = null;
13484
- constructor(client, environment, clientId) {
13485
- super(client, clientId);
14204
+ constructor(client, environment, clientId, options = {}) {
14205
+ super(client, clientId, { initialQuota: options.initialQuota });
13486
14206
  this.environment = environment;
14207
+ this.sessionDataRoutePrefix = options.sessionDataRoutePrefix || "/orchestrator/ws/sessions";
13487
14208
  }
13488
14209
  get environmentId() {
13489
14210
  return this.environment.environmentId;
@@ -13528,7 +14249,7 @@ var EnvironmentSession = class extends Session {
13528
14249
  const doc = this.document;
13529
14250
  return normalizeHeapSnapshot(doc?.heap);
13530
14251
  }
13531
- async sessionDataRequest(path, query) {
14252
+ async sessionDataRequest(path, query, init2 = {}) {
13532
14253
  const searchParams = new URLSearchParams();
13533
14254
  for (const [key, value] of Object.entries(query || {})) {
13534
14255
  if (value !== null && typeof value !== "undefined" && value !== "") {
@@ -13536,23 +14257,39 @@ var EnvironmentSession = class extends Session {
13536
14257
  }
13537
14258
  }
13538
14259
  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"
14260
+ const url = `${this.environment.runtimeBaseUrl}${this.sessionDataRoutePrefix}/${encodeURIComponent(this.sessionId)}${path}${queryString ? `?${queryString}` : ""}`;
14261
+ const body = typeof init2.body === "undefined" ? void 0 : JSON.stringify(init2.body);
14262
+ for (let attempt = 1; attempt <= SESSION_DATA_REQUEST_RETRY_COUNT; attempt += 1) {
14263
+ try {
14264
+ const response = await fetch(url, {
14265
+ method: init2.method || "GET",
14266
+ headers: {
14267
+ Authorization: `Bearer ${this.environment.authToken}`,
14268
+ "Content-Type": "application/json"
14269
+ },
14270
+ ...typeof body === "undefined" ? {} : { body }
14271
+ });
14272
+ if (response.ok) {
14273
+ return response.json();
14274
+ }
14275
+ const errorText = await response.text();
14276
+ const error = new Error(
14277
+ `Session data API Error (${response.status}): ${errorText}`
14278
+ );
14279
+ if (isLocalControlUrl(url) && isRetryableSessionDataError(error) && attempt < SESSION_DATA_REQUEST_RETRY_COUNT) {
14280
+ await sleep(SESSION_DATA_REQUEST_RETRY_DELAY_MS * attempt);
14281
+ continue;
13546
14282
  }
14283
+ throw error;
14284
+ } catch (error) {
14285
+ if (isLocalControlUrl(url) && isRetryableSessionDataError(error) && attempt < SESSION_DATA_REQUEST_RETRY_COUNT) {
14286
+ await sleep(SESSION_DATA_REQUEST_RETRY_DELAY_MS * attempt);
14287
+ continue;
14288
+ }
14289
+ throw error;
13547
14290
  }
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
14291
  }
13555
- return response.json();
14292
+ throw new Error(`Session data API Error: exhausted retries for ${url}`);
13556
14293
  }
13557
14294
  async collectAllSessionItems(listPage) {
13558
14295
  const items = [];
@@ -13610,6 +14347,17 @@ var EnvironmentSession = class extends Session {
13610
14347
  get: (name) => this.sessionDataRequest(
13611
14348
  `/heap/lists/${encodeURIComponent(name)}`
13612
14349
  )
14350
+ },
14351
+ variables: {
14352
+ list: (options = {}) => this.sessionDataRequest("/heap/variables", options),
14353
+ get: (name) => this.sessionDataRequest(
14354
+ `/heap/variables/${encodeURIComponent(name)}`
14355
+ ),
14356
+ delete: (name) => this.sessionDataRequest(
14357
+ `/heap/variables/${encodeURIComponent(name)}`,
14358
+ void 0,
14359
+ { method: "DELETE" }
14360
+ )
13613
14361
  }
13614
14362
  };
13615
14363
  }
@@ -13678,8 +14426,21 @@ var EnvironmentSession = class extends Session {
13678
14426
  async graphql(query, variables) {
13679
14427
  return this.environment.graphql(query, variables);
13680
14428
  }
13681
- async defineRelationship(options) {
13682
- return this.environment.defineRelationship(options);
14429
+ async searchRecords(query, options = {}) {
14430
+ return this.environment.searchRecords(query, options);
14431
+ }
14432
+ async mentionRecord(input) {
14433
+ return this.sessionDataRequest(
14434
+ "/records/mention",
14435
+ void 0,
14436
+ {
14437
+ method: "POST",
14438
+ body: input
14439
+ }
14440
+ );
14441
+ }
14442
+ async defineRelationship(options) {
14443
+ return this.environment.defineRelationship(options);
13683
14444
  }
13684
14445
  async getRelationships(modelPath) {
13685
14446
  return this.environment.getRelationships(modelPath);
@@ -13825,6 +14586,7 @@ var Granular = class _Granular {
13825
14586
  WebSocketCtor;
13826
14587
  onUnexpectedClose;
13827
14588
  onReconnectError;
14589
+ effectHostUrl;
13828
14590
  debugHttp = process.env.GRANULAR_DEBUG_HTTP === "1";
13829
14591
  /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
13830
14592
  sandboxEffects = /* @__PURE__ */ new Map();
@@ -13853,6 +14615,7 @@ var Granular = class _Granular {
13853
14615
  this.WebSocketCtor = options.WebSocketCtor;
13854
14616
  this.onUnexpectedClose = options.onUnexpectedClose;
13855
14617
  this.onReconnectError = options.onReconnectError;
14618
+ this.effectHostUrl = options.effectHostUrl;
13856
14619
  this.httpUrl = this.apiUrl.replace(/^wss:\/\//, "https://").replace(/^ws:\/\//, "http://").replace(/\/ws$/, "");
13857
14620
  }
13858
14621
  /**
@@ -14023,6 +14786,30 @@ var Granular = class _Granular {
14023
14786
  permissions: options.permissions || options.user?.permissions || []
14024
14787
  });
14025
14788
  }
14789
+ /**
14790
+ * Run a registered environment importer against an environment that was
14791
+ * opened outside this SDK instance, for example by a delegated browser flow.
14792
+ *
14793
+ * This uses the same setup-run and queued record-import plumbing as
14794
+ * `openEnvironment()`: importer stages, expected object counts, and queued
14795
+ * import counters remain visible through `environment.setup` and
14796
+ * `getRecordImportSummary()`.
14797
+ */
14798
+ async runEnvironmentImporterForEnvironment(environmentId, options = {}) {
14799
+ const environmentData = await this.environments.get(environmentId);
14800
+ const environment = this.bindEnvironmentHandle(environmentData);
14801
+ const requestedOntology = options.ontology || environmentData.ontologyId || environmentData.sandboxId;
14802
+ return this.runEnvironmentImporter(
14803
+ {
14804
+ environment: environmentData,
14805
+ requestedOntology,
14806
+ sandboxId: environmentData.sandboxId,
14807
+ subjectId: environmentData.subjectId,
14808
+ setupTriggerReason: options.reason || "new_environment"
14809
+ },
14810
+ environment
14811
+ );
14812
+ }
14026
14813
  resolveRequestedTag(options, methodName) {
14027
14814
  const tag = options.tag?.trim() || options.tagName?.trim() || options.environment?.trim();
14028
14815
  if (!tag) {
@@ -14214,6 +15001,15 @@ var Granular = class _Granular {
14214
15001
  const environment = this.bindEnvironmentHandle(envData);
14215
15002
  return this.bindWebSocketEnvironmentSession(environment, clientId, minted);
14216
15003
  }
15004
+ async recordOpenAIUsageSpend(usage, context, options) {
15005
+ return recordOpenAIUsageSpend({
15006
+ apiUrl: this.apiUrl,
15007
+ token: this.apiKey,
15008
+ usage,
15009
+ context,
15010
+ metadata: options?.metadata
15011
+ });
15012
+ }
14217
15013
  /**
14218
15014
  * Mark a session closed in the control plane. If `environment` is the connected handle for that
14219
15015
  * `sessionId`, disconnects the WebSocket so the runtime tears down cleanly.
@@ -14266,15 +15062,25 @@ var Granular = class _Granular {
14266
15062
  return ontologyImporter;
14267
15063
  }
14268
15064
  async maybeRunEnvironmentImporter(resolved, environment) {
14269
- if (!resolved.setupTriggerReason) {
14270
- return;
15065
+ const setupTriggerReason = resolved.setupTriggerReason;
15066
+ if (!setupTriggerReason) {
15067
+ return null;
14271
15068
  }
15069
+ return this.runEnvironmentImporter(
15070
+ {
15071
+ ...resolved,
15072
+ setupTriggerReason
15073
+ },
15074
+ environment
15075
+ );
15076
+ }
15077
+ async runEnvironmentImporter(resolved, environment) {
14272
15078
  const importer = this.resolveEnvironmentImporter(
14273
15079
  resolved.requestedOntology,
14274
15080
  resolved.sandboxId
14275
15081
  );
14276
15082
  if (!importer) {
14277
- return;
15083
+ return null;
14278
15084
  }
14279
15085
  const setupRun = await this.request(
14280
15086
  `/control/environments/${environment.environmentId}/setup-runs`,
@@ -14314,16 +15120,24 @@ var Granular = class _Granular {
14314
15120
  },
14315
15121
  importRecords: async (records, options) => environment.enqueueRecordImport(records, {
14316
15122
  batchSize: options?.batchSize,
15123
+ writeMode: options?.writeMode,
14317
15124
  setupRunId
14318
15125
  })
14319
15126
  };
14320
15127
  try {
14321
15128
  await importer(importerContext);
14322
- await updateSetupRun({ markHookCompleted: true });
15129
+ const completedSetupRun = await this.request(
15130
+ `/control/environment-setup-runs/${setupRunId}`,
15131
+ {
15132
+ method: "PATCH",
15133
+ body: JSON.stringify({ markHookCompleted: true })
15134
+ }
15135
+ );
14323
15136
  const refreshedEnvironment = await this.environments.get(
14324
15137
  environment.environmentId
14325
15138
  );
14326
15139
  environment.syncEnvironmentData(refreshedEnvironment);
15140
+ return completedSetupRun;
14327
15141
  } catch (error) {
14328
15142
  await updateSetupRun({
14329
15143
  status: "failed",
@@ -14350,7 +15164,8 @@ var Granular = class _Granular {
14350
15164
  const environmentSession = new EnvironmentSession(
14351
15165
  client,
14352
15166
  environment,
14353
- clientId
15167
+ clientId,
15168
+ { initialQuota: session.quota || null }
14354
15169
  );
14355
15170
  await environmentSession.hello();
14356
15171
  return environmentSession;
@@ -14371,27 +15186,45 @@ var Granular = class _Granular {
14371
15186
  return effects;
14372
15187
  }
14373
15188
  serializeEffect(effect) {
14374
- return {
15189
+ const serialized = {
14375
15190
  effectKey: computeEffectKey2(effect),
14376
15191
  name: effect.name,
14377
15192
  description: effect.description,
14378
15193
  inputSchema: effect.inputSchema,
14379
- outputSchema: effect.outputSchema,
14380
15194
  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
15195
+ provenance: effect.provenance || { source: "custom" }
14386
15196
  };
15197
+ if (effect.outputSchema !== void 0) {
15198
+ serialized.outputSchema = effect.outputSchema;
15199
+ }
15200
+ if (effect.tags !== void 0) {
15201
+ serialized.tags = effect.tags;
15202
+ }
15203
+ if (effect.className !== void 0) {
15204
+ serialized.className = effect.className;
15205
+ }
15206
+ if (effect.static !== void 0) {
15207
+ serialized.static = effect.static;
15208
+ }
15209
+ if (effect.versionSelector !== void 0) {
15210
+ serialized.versionSelector = effect.versionSelector;
15211
+ }
15212
+ if (effect.metamodels !== void 0) {
15213
+ serialized.metamodels = effect.metamodels;
15214
+ }
15215
+ return serialized;
14387
15216
  }
14388
15217
  async publishSandboxEffectCatalog(host) {
14389
15218
  const effects = Array.from(
14390
15219
  this.getSandboxEffectMap(host.sandboxId).values()
14391
15220
  ).map((effect) => this.serializeEffect(effect));
14392
- const result = await host.wsClient.call("effects.publishCatalog", {
14393
- effects
14394
- });
15221
+ const result = await withTimeout(
15222
+ host.wsClient.call("effects.publishCatalog", {
15223
+ effects
15224
+ }),
15225
+ EFFECT_CATALOG_SYNC_TIMEOUT_MS,
15226
+ `effects.publishCatalog for sandbox ${host.sandboxId}`
15227
+ );
14395
15228
  const acceptedCount = typeof result?.acceptedCount === "number" ? result.acceptedCount : 0;
14396
15229
  const rejected = Array.isArray(result?.rejected) ? result.rejected : [];
14397
15230
  if (acceptedCount === 0 && rejected.length > 0) {
@@ -14410,8 +15243,26 @@ var Granular = class _Granular {
14410
15243
  }
14411
15244
  }
14412
15245
  async syncSandboxEffectCatalog(sandboxId) {
14413
- const host = await this.ensureSandboxEffectHost(sandboxId);
14414
- await this.publishSandboxEffectCatalog(host);
15246
+ let lastError;
15247
+ for (let attempt = 1; attempt <= EFFECT_CATALOG_SYNC_RETRY_COUNT; attempt += 1) {
15248
+ try {
15249
+ const host = await this.ensureSandboxEffectHost(sandboxId);
15250
+ await this.publishSandboxEffectCatalog(host);
15251
+ return;
15252
+ } catch (error) {
15253
+ lastError = error;
15254
+ this.disconnectSandboxEffectHost(sandboxId);
15255
+ if (attempt === EFFECT_CATALOG_SYNC_RETRY_COUNT || !isRetryableEffectRegistrationError(error)) {
15256
+ throw error;
15257
+ }
15258
+ console.warn(
15259
+ `[Granular] Retrying effect registration for sandbox ${sandboxId} after transient failure (${attempt}/${EFFECT_CATALOG_SYNC_RETRY_COUNT - 1} retries used):`,
15260
+ error
15261
+ );
15262
+ await sleep(EFFECT_CATALOG_SYNC_RETRY_DELAY_MS * attempt);
15263
+ }
15264
+ }
15265
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
14415
15266
  }
14416
15267
  recoverEffectHost(host, error) {
14417
15268
  if (host.recovering) {
@@ -14504,7 +15355,8 @@ var Granular = class _Granular {
14504
15355
  this.apiUrl,
14505
15356
  sandboxId,
14506
15357
  effectClientId,
14507
- clientId
15358
+ clientId,
15359
+ this.effectHostUrl
14508
15360
  ),
14509
15361
  sessionId: `effect-host:${effectClientId}`,
14510
15362
  token: this.apiKey,
@@ -14540,7 +15392,11 @@ var Granular = class _Granular {
14540
15392
  wsClient.on("disconnect", () => {
14541
15393
  this.stopEffectHostHeartbeat(host);
14542
15394
  });
14543
- await wsClient.connect();
15395
+ await withTimeout(
15396
+ wsClient.connect(),
15397
+ EFFECT_HOST_CONNECT_TIMEOUT_MS,
15398
+ `effect host WebSocket connect for sandbox ${sandboxId}`
15399
+ );
14544
15400
  await this.synchronizeEffectHost(host);
14545
15401
  this.sandboxEffectHosts.set(sandboxId, host);
14546
15402
  return host;
@@ -14663,7 +15519,7 @@ var Granular = class _Granular {
14663
15519
  /**
14664
15520
  * Ensure a permission profile exists for a sandbox, creating it if needed.
14665
15521
  * If profileName matches an existing profile name, returns its ID.
14666
- * Otherwise, creates a new profile with default allow-all rules.
15522
+ * Otherwise, creates a v1 source-profile file shape with an allow default.
14667
15523
  */
14668
15524
  async ensurePermissionProfile(sandboxId, profileName) {
14669
15525
  try {
@@ -14677,8 +15533,11 @@ var Granular = class _Granular {
14677
15533
  const created = await this.permissionProfiles.create(sandboxId, {
14678
15534
  name: profileName,
14679
15535
  rules: {
14680
- effects: { allow: ["*"] },
14681
- resources: { allow: ["*"] }
15536
+ schemaVersion: 1,
15537
+ name: profileName,
15538
+ description: profileName === "allow-all" ? "Every declared action is visible unless a manifest policy denies it." : `Generated permission profile ${profileName}`,
15539
+ defaults: { actionPolicy: "allow" },
15540
+ actions: []
14682
15541
  }
14683
15542
  });
14684
15543
  return created.permissionProfileId;
@@ -14751,33 +15610,63 @@ var Granular = class _Granular {
14751
15610
  * Permission Profile management for sandboxes
14752
15611
  */
14753
15612
  get permissionProfiles() {
15613
+ const profileSourceFromRecord = (record) => {
15614
+ const profile = record.profile || record.rules || {};
15615
+ return {
15616
+ ...profile,
15617
+ schemaVersion: profile.schemaVersion || 1,
15618
+ name: profile.name || record.name,
15619
+ description: profile.description || record.description
15620
+ };
15621
+ };
14754
15622
  return {
14755
15623
  list: async (sandboxId) => {
14756
15624
  const result = await this.request(
14757
- `/control/sandboxes/${sandboxId}/permission-profiles`
15625
+ `/control/sandboxes/${sandboxId}/permission-profile-sources`
14758
15626
  );
14759
15627
  return result.items;
14760
15628
  },
14761
15629
  get: async (sandboxId, profileId) => {
14762
- return this.request(
14763
- `/control/sandboxes/${sandboxId}/permission-profiles/${profileId}`
15630
+ const result = await this.request(
15631
+ `/control/sandboxes/${sandboxId}/permission-profile-sources`
15632
+ );
15633
+ const profile = result.items.find(
15634
+ (item) => item.permissionProfileId === profileId || item.name === profileId
14764
15635
  );
15636
+ if (!profile) {
15637
+ throw new Error(`Permission profile source not found: ${profileId}`);
15638
+ }
15639
+ return profile;
14765
15640
  },
14766
15641
  create: async (sandboxId, data) => {
14767
- return this.request(
14768
- `/control/sandboxes/${sandboxId}/permission-profiles`,
15642
+ const profile = {
15643
+ ...data.rules,
15644
+ schemaVersion: 1,
15645
+ name: data.name
15646
+ };
15647
+ const existingProfiles = await this.permissionProfiles.list(sandboxId);
15648
+ const profiles = [
15649
+ ...existingProfiles.filter((existing) => existing.name !== data.name).map((existing) => profileSourceFromRecord(existing)),
15650
+ profile
15651
+ ];
15652
+ const result = await this.request(
15653
+ `/control/sandboxes/${sandboxId}/permission-profile-sources`,
14769
15654
  {
14770
- method: "POST",
14771
- body: JSON.stringify(data)
15655
+ method: "PUT",
15656
+ body: JSON.stringify({ profiles })
14772
15657
  }
14773
15658
  );
15659
+ const synced = result.items.find((item) => item.name === data.name) || result.items[0];
15660
+ if (!synced) {
15661
+ throw new Error(
15662
+ `Permission profile source sync did not return ${data.name}`
15663
+ );
15664
+ }
15665
+ return synced;
14774
15666
  },
14775
- delete: async (sandboxId, profileId) => {
14776
- return this.request(
14777
- `/control/sandboxes/${sandboxId}/permission-profiles/${profileId}`,
14778
- {
14779
- method: "DELETE"
14780
- }
15667
+ delete: async (_sandboxId, _profileId) => {
15668
+ throw new Error(
15669
+ "Permission profile sources are updated by syncing the desired source set."
14781
15670
  );
14782
15671
  }
14783
15672
  };
@@ -15033,6 +15922,85 @@ var Granular = class _Granular {
15033
15922
  };
15034
15923
 
15035
15924
  // src/agent-harness.ts
15925
+ var DEFAULT_IGNORED_REASONING_COMMENT_DIRECTIVES = [
15926
+ /^@ts-ignore\b/i,
15927
+ /^@ts-expect-error\b/i,
15928
+ /^eslint-[\w-]+\b/i,
15929
+ /^biome-ignore\b/i,
15930
+ /^prettier-ignore\b/i,
15931
+ /^istanbul ignore\b/i
15932
+ ];
15933
+ var DEFAULT_LOW_SIGNAL_REASONING_LINES = [
15934
+ /^running\.?$/i,
15935
+ /^working\.?$/i,
15936
+ /^thinking\.?$/i,
15937
+ /^generating(?: code)?\.?$/i,
15938
+ /^starting(?: execution)?\.?$/i
15939
+ ];
15940
+ function parseReasoningCommentLine(line, options = {}) {
15941
+ const trimmed = line.trimStart();
15942
+ if (!trimmed.startsWith("//")) return null;
15943
+ const text = trimmed.replace(/^\/\/\s?/, "").trim();
15944
+ if (!text) return { kind: "ignored" };
15945
+ const ignoredDirectives = options.ignoredCommentDirectives || DEFAULT_IGNORED_REASONING_COMMENT_DIRECTIVES;
15946
+ if (ignoredDirectives.some((pattern) => pattern.test(text))) {
15947
+ return { kind: "ignored" };
15948
+ }
15949
+ const lowSignalLines = options.lowSignalReasoningLines || DEFAULT_LOW_SIGNAL_REASONING_LINES;
15950
+ if (lowSignalLines.some((pattern) => pattern.test(text))) {
15951
+ return { kind: "ignored" };
15952
+ }
15953
+ return { kind: "reasoning", text };
15954
+ }
15955
+ function consumeGranularReasoningTraceChunk(buffer, chunk, options = {}) {
15956
+ let text = buffer + chunk;
15957
+ let visibleText = "";
15958
+ const reasoningLines = [];
15959
+ while (true) {
15960
+ const newlineIndex = text.indexOf("\n");
15961
+ if (newlineIndex === -1) break;
15962
+ const rawLine = text.slice(0, newlineIndex);
15963
+ text = text.slice(newlineIndex + 1);
15964
+ const comment = parseReasoningCommentLine(
15965
+ rawLine.replace(/\r$/, ""),
15966
+ options
15967
+ );
15968
+ if (comment?.kind === "reasoning") {
15969
+ reasoningLines.push(comment.text);
15970
+ } else if (comment?.kind === "ignored") {
15971
+ continue;
15972
+ } else {
15973
+ visibleText += `${rawLine}
15974
+ `;
15975
+ }
15976
+ }
15977
+ if (options.final && text.length > 0) {
15978
+ const comment = parseReasoningCommentLine(text.replace(/\r$/, ""), options);
15979
+ if (comment?.kind === "reasoning") {
15980
+ reasoningLines.push(comment.text);
15981
+ text = "";
15982
+ } else if (comment?.kind === "ignored") {
15983
+ text = "";
15984
+ } else {
15985
+ visibleText += text;
15986
+ text = "";
15987
+ }
15988
+ }
15989
+ return { buffer: text, visibleText, reasoningLines };
15990
+ }
15991
+ function consumeGranularReasoningOnlyChunk(buffer, chunk, options = {}) {
15992
+ const result = consumeGranularReasoningTraceChunk(buffer, chunk, options);
15993
+ return {
15994
+ buffer: result.buffer,
15995
+ reasoningLines: result.reasoningLines
15996
+ };
15997
+ }
15998
+ function stripGranularReasoningTrace(text, options = {}) {
15999
+ return consumeGranularReasoningTraceChunk("", text, {
16000
+ ...options,
16001
+ final: true
16002
+ }).visibleText.trim();
16003
+ }
15036
16004
  function asRecord4(value) {
15037
16005
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
15038
16006
  return value;
@@ -15056,21 +16024,8 @@ function uniqueStrings(values, maxCount) {
15056
16024
  }
15057
16025
  return output;
15058
16026
  }
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}]`;
16027
+ function renderConstBlock(name, value) {
16028
+ return `const ${name} = ${JSON.stringify(value, null, 2)} as const;`;
15074
16029
  }
15075
16030
  function hashString(value) {
15076
16031
  if (!value) return null;
@@ -15081,97 +16036,248 @@ function hashString(value) {
15081
16036
  }
15082
16037
  return (hash >>> 0).toString(16).padStart(8, "0");
15083
16038
  }
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
16039
+ function findUndefinedSimpleTemplateIdentifier(source) {
16040
+ const declared = /* @__PURE__ */ new Set();
16041
+ const globals = /* @__PURE__ */ new Set([
16042
+ "Array",
16043
+ "Boolean",
16044
+ "Date",
16045
+ "JSON",
16046
+ "Math",
16047
+ "Number",
16048
+ "Object",
16049
+ "Promise",
16050
+ "String",
16051
+ "undefined",
16052
+ "null",
16053
+ "true",
16054
+ "false"
16055
+ ]);
16056
+ for (const match of source.matchAll(/import\s*\{([^}]+)\}\s*from/g)) {
16057
+ for (const part of match[1].split(",")) {
16058
+ const aliasMatch = part.trim().match(/\bas\s+([A-Za-z_$][\w$]*)$/);
16059
+ const nameMatch = part.trim().match(/^([A-Za-z_$][\w$]*)/);
16060
+ const name = aliasMatch?.[1] || nameMatch?.[1];
16061
+ if (name) declared.add(name);
16062
+ }
16063
+ }
16064
+ for (const match of source.matchAll(
16065
+ /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b/g
16066
+ )) {
16067
+ declared.add(match[1]);
16068
+ }
16069
+ for (const match of source.matchAll(
16070
+ /\bfor\s*(?:await\s*)?\(\s*(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s+of\b/g
16071
+ )) {
16072
+ declared.add(match[1]);
16073
+ }
16074
+ for (const match of source.matchAll(
16075
+ /\bcatch\s*\(\s*([A-Za-z_$][\w$]*)\s*\)/g
16076
+ )) {
16077
+ declared.add(match[1]);
16078
+ }
16079
+ for (const match of source.matchAll(
16080
+ /\(\s*([A-Za-z_$][\w$]*)\s*(?:,\s*[A-Za-z_$][\w$]*)*\s*\)\s*=>/g
16081
+ )) {
16082
+ declared.add(match[1]);
16083
+ }
16084
+ for (const match of source.matchAll(/\b([A-Za-z_$][\w$]*)\s*=>/g)) {
16085
+ declared.add(match[1]);
16086
+ }
16087
+ for (const match of source.matchAll(/\$\{\s*([A-Za-z_$][\w$]*)\s*\}/g)) {
16088
+ const identifier = match[1];
16089
+ if (!declared.has(identifier) && !globals.has(identifier)) {
16090
+ return identifier;
16091
+ }
16092
+ }
16093
+ return null;
16094
+ }
16095
+ function getGeneratedJobSyntaxError(source) {
16096
+ const withoutImports = source.replace(
16097
+ /^\s*import\s+[\s\S]*?\s+from\s+["'][^"']+["']\s*;?\s*$/gm,
16098
+ ""
15090
16099
  );
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;
16100
+ try {
16101
+ new Function(`return (async () => {
16102
+ ${withoutImports}
16103
+ });`);
16104
+ return null;
16105
+ } catch (error) {
16106
+ return error instanceof Error ? error.message : String(error);
16107
+ }
16108
+ }
16109
+ function hasNestedTemplateLiteralExpression(source) {
16110
+ let inString = null;
16111
+ let escaped = false;
16112
+ const templateStack = [];
16113
+ for (let index = 0; index < source.length; index += 1) {
16114
+ const char = source[index];
16115
+ const next = source[index + 1] || "";
16116
+ if (escaped) {
16117
+ escaped = false;
16118
+ continue;
16119
+ }
16120
+ if (char === "\\") {
16121
+ escaped = true;
16122
+ continue;
16123
+ }
16124
+ if (inString === "'" || inString === '"') {
16125
+ if (char === inString) inString = null;
16126
+ continue;
16127
+ }
16128
+ if (inString === "`") {
16129
+ const current = templateStack[templateStack.length - 1];
16130
+ if (char === "`") {
16131
+ if (current?.expressionDepth && current.expressionDepth > 0) {
16132
+ return true;
16133
+ }
16134
+ templateStack.pop();
16135
+ if (templateStack.length === 0) inString = null;
16136
+ continue;
16137
+ }
16138
+ if (char === "$" && next === "{") {
16139
+ if (current) current.expressionDepth += 1;
16140
+ index += 1;
16141
+ continue;
16142
+ }
16143
+ if (char === "}" && current?.expressionDepth) {
16144
+ current.expressionDepth -= 1;
16145
+ }
16146
+ continue;
16147
+ }
16148
+ if (char === "'" || char === '"') {
16149
+ inString = char;
16150
+ continue;
16151
+ }
16152
+ if (char === "`") {
16153
+ inString = "`";
16154
+ templateStack.push({ expressionDepth: 0 });
16155
+ }
15097
16156
  }
15098
16157
  return false;
15099
16158
  }
15100
- function reviewGeneratedJobCode(code) {
16159
+ function reviewGeneratedJobCode(code, _options = {}) {
15101
16160
  const normalized = typeof code === "string" ? code : "";
15102
- if (!normalized.trim()) return [];
15103
16161
  const issues = [];
16162
+ if (!normalized.trim()) {
16163
+ return issues;
16164
+ }
15104
16165
  if (/require\s*\(\s*['"]\.\/sandbox-tools['"]\s*\)/.test(normalized)) {
15105
16166
  issues.push({
15106
16167
  code: "commonjs_require",
15107
16168
  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
- }
16169
+ message: "Use ESM imports from './sandbox-tools' instead of require('./sandbox-tools')."
16170
+ });
15139
16171
  }
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
- }
16172
+ if (/\bprocess\.exit\s*\(/.test(normalized)) {
16173
+ issues.push({
16174
+ code: "process_exit",
16175
+ severity: "error",
16176
+ message: "Generated jobs must not call process.exit(...). Return from the job or emit a runtime message instead."
16177
+ });
16178
+ }
16179
+ if (/\bawait\s+import\s*\(\s*['"]\.\/sandbox-tools['"]\s*\)/.test(normalized)) {
16180
+ issues.push({
16181
+ code: "dynamic_import_in_job",
16182
+ severity: "error",
16183
+ message: "Import sandbox tools with a static top-level import from './sandbox-tools'; do not use dynamic import for runtime tools."
16184
+ });
16185
+ }
16186
+ if (hasNestedTemplateLiteralExpression(normalized)) {
16187
+ issues.push({
16188
+ code: "nested_template_literal_in_job",
16189
+ severity: "error",
16190
+ message: "Avoid nested template literals inside template expressions. Precompute conditional text in variables or use simpler string construction."
16191
+ });
15158
16192
  }
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) {
16193
+ const syntaxError = getGeneratedJobSyntaxError(normalized);
16194
+ if (syntaxError) {
15164
16195
  issues.push({
15165
- code: "missing_user_reply",
16196
+ code: "syntax_error_in_job",
15166
16197
  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."
16198
+ message: `The generated job has a JavaScript syntax error before runtime execution: ${syntaxError}.`
15168
16199
  });
15169
16200
  }
15170
- if (returnsShowPayload) {
16201
+ if (/[\u2018-\u201F]/.test(normalized)) {
15171
16202
  issues.push({
15172
- code: "return_show_not_for_ui",
16203
+ code: "syntax_error_in_job",
15173
16204
  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."
16205
+ message: "Use plain ASCII quotes and apostrophes in generated job strings."
16206
+ });
16207
+ }
16208
+ const undefinedTemplateIdentifier = findUndefinedSimpleTemplateIdentifier(normalized);
16209
+ if (undefinedTemplateIdentifier) {
16210
+ issues.push({
16211
+ code: "undefined_template_identifier",
16212
+ severity: "error",
16213
+ message: `The template literal references \`${undefinedTemplateIdentifier}\`, but that identifier is not declared in the generated job.`
16214
+ });
16215
+ }
16216
+ if (/\{\s*\.\.\.[A-Za-z_$][\w$]*/.test(normalized)) {
16217
+ issues.push({
16218
+ code: "object_spread_in_job",
16219
+ severity: "error",
16220
+ message: "Avoid object spread in generated jobs until the backend runtime transform can validate it structurally."
16221
+ });
16222
+ }
16223
+ if (/\bloop\./.test(normalized) && !/import\s*\{[^}]*\bloop\b[^}]*\}\s*from\s*['"]\.\/sandbox-tools['"]/.test(
16224
+ normalized
16225
+ )) {
16226
+ issues.push({
16227
+ code: "missing_loop_import",
16228
+ severity: "error",
16229
+ message: "The job calls loop.* but does not import loop from './sandbox-tools'."
16230
+ });
16231
+ }
16232
+ const bareLoopHelperImport = normalized.match(
16233
+ /import\s*\{[^}]*\b(ask_user|confirm|open_decision|close_decision|create_task|update_task|complete_task|close_loop)\b[^}]*\}\s*from\s*['"]\.\/sandbox-tools['"]/
16234
+ );
16235
+ if (bareLoopHelperImport) {
16236
+ issues.push({
16237
+ code: "bare_loop_helper_import",
16238
+ severity: "error",
16239
+ 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."
16240
+ });
16241
+ }
16242
+ if (/\bloop\.open_decision\s*\(\s*\{[\s\S]*?\boptions\s*:/.test(normalized)) {
16243
+ issues.push({
16244
+ code: "loop_helper_contract",
16245
+ severity: "error",
16246
+ message: "loop.open_decision(...) must use `candidates: [...]`, not `options: [...]`. Every candidate must include a string `id`."
16247
+ });
16248
+ }
16249
+ if (/\bloop\.close_decision\s*\(\s*\{[\s\S]*?\bselected\s*:/.test(normalized)) {
16250
+ issues.push({
16251
+ code: "loop_helper_contract",
16252
+ severity: "error",
16253
+ message: "loop.close_decision(...) must use `selectedId`, not `selected`."
16254
+ });
16255
+ }
16256
+ if (/\bloop\.(?:create_task|update_task|complete_task)\s*\(\s*\{[\s\S]*?\bid\s*:/.test(
16257
+ normalized
16258
+ )) {
16259
+ issues.push({
16260
+ code: "loop_helper_contract",
16261
+ severity: "error",
16262
+ message: "Loop task helpers must use `taskId`, not `id`, for explicit task identifiers."
16263
+ });
16264
+ }
16265
+ if (/\bconsole\.log\s*\(\s*JSON\.stringify\s*\(\s*\{[\s\S]*?\b(?:action|reply|code)\s*:/.test(
16266
+ normalized
16267
+ )) {
16268
+ issues.push({
16269
+ code: "stdout_json_reply",
16270
+ severity: "error",
16271
+ message: "Do not print JSON chat envelopes from generated jobs; use runtime messaging or return a plain result."
16272
+ });
16273
+ }
16274
+ if (/\breturn\s+\{[\s\S]*?\baction\s*:\s*['"]reply['"][\s\S]*?\breply\s*:/.test(
16275
+ normalized
16276
+ )) {
16277
+ issues.push({
16278
+ code: "return_chat_payload",
16279
+ severity: "error",
16280
+ message: "Do not return chat envelopes like { action, reply, code } from generated jobs; return a plain value or use runtime messaging."
15175
16281
  });
15176
16282
  }
15177
16283
  return issues;
@@ -15230,15 +16336,40 @@ function collectConversationReferents(liveDoc) {
15230
16336
  const ts = Number(message.ts) || 0;
15231
16337
  const messageId = typeof message.id === "string" ? message.id : void 0;
15232
16338
  const jobId = typeof message.jobId === "string" ? message.jobId : void 0;
15233
- for (const entryPath of uniqueStrings(asArray2(show.entryPaths))) {
16339
+ const entryPaths = uniqueStrings(asArray2(show.entryPaths));
16340
+ const entryClassCounts = /* @__PURE__ */ new Map();
16341
+ const entryMetadata = entryPaths.map((entryPath) => {
15234
16342
  const entry = asRecord4(entriesByPath[entryPath]);
16343
+ const className = typeof entry?.className === "string" ? entry.className : void 0;
16344
+ if (className) {
16345
+ entryClassCounts.set(
16346
+ className,
16347
+ (entryClassCounts.get(className) || 0) + 1
16348
+ );
16349
+ }
16350
+ return { entryPath, entry, className };
16351
+ });
16352
+ const displayGroupId = entryMetadata.length > 1 ? `message:${messageId || jobId || ts}:entries` : void 0;
16353
+ for (const [
16354
+ index,
16355
+ { entryPath, entry, className }
16356
+ ] of entryMetadata.entries()) {
15235
16357
  pushReferent({
15236
16358
  id: `entry:${entryPath}`,
15237
16359
  kind: "entry",
15238
16360
  ref: entryPath,
16361
+ role: "assistant",
16362
+ source: "heap_objects",
15239
16363
  entryPath,
15240
- className: typeof entry?.className === "string" ? entry.className : void 0,
16364
+ recordId: typeof entry?.id === "string" ? entry.id : void 0,
16365
+ className,
15241
16366
  label: typeof entry?.label === "string" && entry.label.trim() ? entry.label.trim() : typeof entry?.id === "string" && entry.id.trim() ? entry.id.trim() : entryPath,
16367
+ ...displayGroupId ? {
16368
+ displayGroupId,
16369
+ displayGroupIndex: index,
16370
+ displayGroupSize: entryMetadata.length,
16371
+ ...className && (entryClassCounts.get(className) || 0) > 1 ? { displayGroupSameTypeSize: entryClassCounts.get(className) } : {}
16372
+ } : {},
15242
16373
  messageId,
15243
16374
  jobId,
15244
16375
  ts
@@ -15250,6 +16381,8 @@ function collectConversationReferents(liveDoc) {
15250
16381
  id: `list:${listName}`,
15251
16382
  kind: "list",
15252
16383
  ref: listName,
16384
+ role: "assistant",
16385
+ source: "heap_objects",
15253
16386
  listName,
15254
16387
  className: typeof list?.className === "string" ? list.className : void 0,
15255
16388
  count: Array.isArray(list?.paths) ? list.paths.length : null,
@@ -15270,9 +16403,12 @@ function collectConversationReferents(liveDoc) {
15270
16403
  id: `variable:${variableName}`,
15271
16404
  kind: "variable",
15272
16405
  ref: variableName,
16406
+ role: "assistant",
16407
+ source: "heap_objects",
15273
16408
  variableName,
15274
16409
  variableKind: typeof variable?.kind === "string" ? variable.kind : void 0,
15275
16410
  entryPath,
16411
+ recordId: typeof entry?.id === "string" ? entry.id : void 0,
15276
16412
  listName,
15277
16413
  className: typeof variable?.className === "string" ? variable.className : typeof entry?.className === "string" ? entry.className : typeof list?.className === "string" ? list.className : void 0,
15278
16414
  label: typeof entry?.label === "string" && entry.label.trim() ? entry.label.trim() : typeof entry?.id === "string" && entry.id.trim() ? entry.id.trim() : null,
@@ -15293,18 +16429,24 @@ function projectConversationReferentFocus(liveDoc) {
15293
16429
  const entryPaths = [];
15294
16430
  const listNames = [];
15295
16431
  const variableNames = [];
15296
- for (const referent of referents.slice(0, 8)) {
15297
- if (referent.kind === "entry" && typeof referent.entryPath === "string") {
16432
+ let entryCount = 0;
16433
+ let listCount = 0;
16434
+ let variableCount = 0;
16435
+ for (const referent of referents) {
16436
+ if (referent.kind === "entry" && typeof referent.entryPath === "string" && entryCount < 8) {
16437
+ entryCount += 1;
15298
16438
  entryPaths.push(referent.entryPath);
15299
16439
  continue;
15300
16440
  }
15301
- if (referent.kind === "list" && typeof referent.listName === "string") {
16441
+ if (referent.kind === "list" && typeof referent.listName === "string" && listCount < 4) {
16442
+ listCount += 1;
15302
16443
  listNames.push(referent.listName);
15303
16444
  const list = asRecord4(listsByName[referent.listName]);
15304
16445
  entryPaths.push(...asArray2(list?.paths).slice(0, 4));
15305
16446
  continue;
15306
16447
  }
15307
- if (referent.kind === "variable" && typeof referent.variableName === "string") {
16448
+ if (referent.kind === "variable" && typeof referent.variableName === "string" && variableCount < 4) {
16449
+ variableCount += 1;
15308
16450
  variableNames.push(referent.variableName);
15309
16451
  if (typeof referent.entryPath === "string") {
15310
16452
  entryPaths.push(referent.entryPath);
@@ -15322,61 +16464,91 @@ function projectConversationReferentFocus(liveDoc) {
15322
16464
  variableNames: uniqueStrings(variableNames, 4)
15323
16465
  };
15324
16466
  }
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 = [];
16467
+ function selectConversationReferentsForPrompt(referents) {
16468
+ const selected = [];
16469
+ const seen = /* @__PURE__ */ new Set();
16470
+ let entryCount = 0;
16471
+ let listCount = 0;
16472
+ let variableCount = 0;
15333
16473
  for (const referent of referents) {
16474
+ if (!referent.kind || !referent.ref) continue;
16475
+ const key = `${referent.kind}:${referent.ref}`;
16476
+ if (seen.has(key)) continue;
16477
+ if (referent.kind === "entry") {
16478
+ if (entryCount >= 8) continue;
16479
+ entryCount += 1;
16480
+ } else if (referent.kind === "list") {
16481
+ if (listCount >= 4) continue;
16482
+ listCount += 1;
16483
+ } else if (referent.kind === "variable") {
16484
+ if (variableCount >= 4) continue;
16485
+ variableCount += 1;
16486
+ }
16487
+ seen.add(key);
16488
+ selected.push(referent);
16489
+ }
16490
+ return selected;
16491
+ }
16492
+ function projectConversationReferentSummary(liveDoc) {
16493
+ const referents = selectConversationReferentsForPrompt(
16494
+ collectConversationReferents(liveDoc)
16495
+ );
16496
+ const compact = referents.map((referent) => {
15334
16497
  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;
16498
+ return {
16499
+ kind: "entry",
16500
+ role: referent.role || null,
16501
+ source: referent.source || null,
16502
+ path: referent.entryPath,
16503
+ id: referent.recordId || null,
16504
+ type: referent.className || "unknown",
16505
+ label: referent.label || referent.entryPath,
16506
+ group: referent.displayGroupId ? {
16507
+ id: referent.displayGroupId,
16508
+ index: typeof referent.displayGroupIndex === "number" ? referent.displayGroupIndex : null,
16509
+ size: typeof referent.displayGroupSize === "number" ? referent.displayGroupSize : null,
16510
+ sameTypeSize: typeof referent.displayGroupSameTypeSize === "number" ? referent.displayGroupSameTypeSize : null
16511
+ } : void 0
16512
+ };
16513
+ }
16514
+ if (referent.kind === "entry" && referent.recordId) {
16515
+ return {
16516
+ kind: "entry",
16517
+ role: referent.role || null,
16518
+ source: referent.source || null,
16519
+ id: referent.recordId,
16520
+ type: referent.className || "unknown",
16521
+ label: referent.label || referent.recordId
16522
+ };
15339
16523
  }
15340
16524
  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;
16525
+ return {
16526
+ kind: "list",
16527
+ role: referent.role || null,
16528
+ source: referent.source || null,
16529
+ name: referent.listName,
16530
+ type: referent.className || "unknown",
16531
+ count: typeof referent.count === "number" ? referent.count : null
16532
+ };
15347
16533
  }
15348
16534
  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}`);
16535
+ return {
16536
+ kind: "variable",
16537
+ role: referent.role || null,
16538
+ source: referent.source || null,
16539
+ name: referent.variableName,
16540
+ valueKind: referent.variableKind || null,
16541
+ type: referent.className || null,
16542
+ path: referent.entryPath || null,
16543
+ list: referent.listName || null,
16544
+ label: referent.label || null,
16545
+ count: typeof referent.count === "number" ? referent.count : null,
16546
+ value: referent.variableKind === "scalar" ? referent.scalarValue ?? null : void 0
16547
+ };
15370
16548
  }
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");
16549
+ return null;
16550
+ }).filter(Boolean);
16551
+ return renderConstBlock("recentReferences", compact);
15380
16552
  }
15381
16553
  function getCurrentClosureId(liveDoc) {
15382
16554
  const loop = asRecord4(liveDoc?.loop);
@@ -15597,56 +16769,24 @@ function projectWorkflowFocus(liveDoc, pendingPrompts = [], options) {
15597
16769
  }
15598
16770
  function projectWorkflowSummary(liveDoc, pendingPrompts = [], options) {
15599
16771
  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(", ")}`);
16772
+ return renderConstBlock("workflowContext", {
16773
+ boundary: {
16774
+ timestamp: focus.boundaryTimestamp,
16775
+ reason: focus.boundaryReason,
16776
+ latestClosureId: focus.latestClosureId || null
16777
+ },
16778
+ recentActions: focus.recentActionSummary,
16779
+ workingSet: {
16780
+ variables: focus.variableNames,
16781
+ lists: focus.listNames,
16782
+ entries: focus.entryPaths
16783
+ },
16784
+ openHandles: {
16785
+ tasks: focus.activeTaskIds,
16786
+ decisions: focus.openDecisionIds,
16787
+ prompts: focus.openPromptIds
15647
16788
  }
15648
- }
15649
- return lines.join("\n");
16789
+ });
15650
16790
  }
15651
16791
  function hasOpenPrompt(liveDoc, pendingPrompts) {
15652
16792
  if (pendingPrompts.length > 0) return true;
@@ -15667,7 +16807,6 @@ function getExclusivePromptTarget(pendingPrompts) {
15667
16807
  return prompt?.type === "input" ? prompt : null;
15668
16808
  }
15669
16809
  function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15670
- const lines = [];
15671
16810
  const loop = asRecord4(liveDoc?.loop);
15672
16811
  const boundary = getWorkflowBoundary(liveDoc, options);
15673
16812
  const tasks = toSortedRecords(loop?.tasksById).filter((task) => {
@@ -15689,22 +16828,12 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15689
16828
  5
15690
16829
  );
15691
16830
  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
- }
16831
+ const compactTasks = visibleTasks.map((task) => ({
16832
+ id: typeof task.taskId === "string" ? task.taskId : "unknown",
16833
+ title: typeof task.title === "string" ? task.title : "Untitled task",
16834
+ status: typeof task.status === "string" ? task.status : "pending",
16835
+ summary: typeof task.summary === "string" && task.summary.trim() ? task.summary.trim() : null
16836
+ }));
15708
16837
  const decisions = toSortedRecords(loop?.decisionsById).filter((decision) => {
15709
16838
  const updatedAt = Number(decision.updatedAt) || Number(decision.createdAt) || 0;
15710
16839
  if (boundary.reason === "request_start") {
@@ -15718,33 +16847,29 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15718
16847
  (decision) => decision.status === "open"
15719
16848
  );
15720
16849
  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}`);
16850
+ const compactDecisions = visibleDecisions.map((decision) => {
16851
+ const status = typeof decision.status === "string" ? decision.status : "resolved";
16852
+ const selected = asRecord4(decision.selected);
16853
+ return {
16854
+ id: typeof decision.decisionId === "string" ? decision.decisionId : "unknown",
16855
+ title: typeof decision.title === "string" && decision.title.trim() ? decision.title.trim() : "Decision",
16856
+ status,
16857
+ candidates: status === "open" ? asArray2(decision.candidates).slice(0, 5).map((candidate) => {
16858
+ const record = asRecord4(candidate);
16859
+ if (!record) return null;
16860
+ return {
16861
+ id: typeof record.id === "string" ? record.id : "unknown",
16862
+ label: typeof record.label === "string" && record.label.trim() ? record.label.trim() : null,
16863
+ description: typeof record.description === "string" && record.description.trim() ? record.description.trim() : null,
16864
+ metadata: asRecord4(record.metadata)
16865
+ };
16866
+ }).filter(Boolean) : [],
16867
+ selected: status === "open" ? null : {
16868
+ id: typeof selected?.id === "string" ? selected.id : null,
16869
+ label: typeof selected?.label === "string" ? selected.label : null
15745
16870
  }
15746
- }
15747
- }
16871
+ };
16872
+ });
15748
16873
  const openPrompts = [
15749
16874
  ...pendingPrompts.map((prompt) => ({
15750
16875
  id: prompt.id,
@@ -15764,29 +16889,29 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
15764
16889
  (pendingPrompt) => pendingPrompt.id === promptId
15765
16890
  ) : false);
15766
16891
  }) : 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
- }
16892
+ const compactPrompts = visiblePrompts.slice(0, 3).map((prompt) => {
16893
+ const promptRecord = asRecord4(prompt) || {};
16894
+ return {
16895
+ id: typeof promptRecord.id === "string" ? promptRecord.id : typeof promptRecord.promptId === "string" ? promptRecord.promptId : null,
16896
+ type: typeof promptRecord.type === "string" ? promptRecord.type : "input",
16897
+ title: typeof promptRecord.title === "string" && promptRecord.title.trim() ? promptRecord.title.trim() : "Input required",
16898
+ message: typeof promptRecord.message === "string" && promptRecord.message.trim() ? promptRecord.message.trim() : null
16899
+ };
16900
+ });
15778
16901
  const currentClosureId = getCurrentClosureId(liveDoc);
15779
16902
  const closureRecord = currentClosureId ? asRecord4(asRecord4(loop?.closuresById)?.[currentClosureId]) : null;
15780
16903
  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");
16904
+ return renderConstBlock("workflowState", {
16905
+ tasks: compactTasks,
16906
+ hiddenActiveTaskCount: hiddenTaskCount,
16907
+ decisions: compactDecisions,
16908
+ openPrompts: compactPrompts,
16909
+ closure: visibleClosure ? {
16910
+ id: currentClosureId,
16911
+ status: typeof visibleClosure.status === "string" ? visibleClosure.status : "completed",
16912
+ summary: typeof visibleClosure.summary === "string" ? visibleClosure.summary : null
16913
+ } : null
16914
+ });
15790
16915
  }
15791
16916
  function projectHeapSummary(heap, options) {
15792
16917
  const heapRecord = asRecord4(heap) || {};
@@ -15831,55 +16956,72 @@ function projectHeapSummary(heap, options) {
15831
16956
  referencedPaths.add(path);
15832
16957
  }
15833
16958
  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))
16959
+ (list) => variables.some(
16960
+ (variable) => Boolean(variable?.listName === list.name)
16961
+ ) || Boolean(list.name && focusedListNames.has(list.name))
15835
16962
  ).sort((left, right) => (right.updatedAt || 0) - (left.updatedAt || 0)).slice(0, maxLists);
15836
16963
  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");
16964
+ return renderConstBlock("savedData", {
16965
+ variables: Object.fromEntries(
16966
+ variables.filter((variable) => typeof variable.name === "string").map((variable) => {
16967
+ if (variable.kind === "scalar") {
16968
+ return [
16969
+ variable.name,
16970
+ { kind: "scalar", value: variable.value ?? null }
16971
+ ];
16972
+ }
16973
+ if (variable.kind === "entry") {
16974
+ const entry = variable.entryPath ? asRecord4(
16975
+ entriesByPath[variable.entryPath]
16976
+ ) : null;
16977
+ return [
16978
+ variable.name,
16979
+ {
16980
+ kind: "entry",
16981
+ type: variable.className || entry?.className || "unknown",
16982
+ path: variable.entryPath || null,
16983
+ label: entry?.label || entry?.id || null
16984
+ }
16985
+ ];
16986
+ }
16987
+ const list = variable.listName ? asRecord4(listsByName[variable.listName]) : null;
16988
+ return [
16989
+ variable.name,
16990
+ {
16991
+ kind: "list",
16992
+ type: variable.className || list?.className || "unknown",
16993
+ list: variable.listName || null,
16994
+ count: (list?.paths || []).length
16995
+ }
16996
+ ];
16997
+ })
16998
+ ),
16999
+ lists: Object.fromEntries(
17000
+ visibleLists.filter((list) => typeof list.name === "string").map((list) => [
17001
+ list.name,
17002
+ {
17003
+ type: list.className || "unknown",
17004
+ count: (list.paths || []).length
17005
+ }
17006
+ ])
17007
+ ),
17008
+ entries: Object.fromEntries(
17009
+ visibleEntries.filter((entry) => typeof entry.path === "string").map((entry) => [
17010
+ entry.path,
17011
+ {
17012
+ type: entry.className || "unknown",
17013
+ id: entry.id || null,
17014
+ label: entry.label || entry.id || null,
17015
+ fields: asArray2(entry.fields).filter(
17016
+ (field) => field?.name && field.name !== "_realId" && field.name !== "real_id"
17017
+ ).slice(0, 3).map((field) => ({
17018
+ name: field.name,
17019
+ value: field.value ?? null
17020
+ }))
17021
+ }
17022
+ ])
17023
+ )
17024
+ });
15883
17025
  }
15884
17026
  function createHarnessVerifierSnapshot(input) {
15885
17027
  const workflowFocus = projectWorkflowFocus(
@@ -15976,8 +17118,8 @@ function buildContinuationInstruction(resultPreview) {
15976
17118
  "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
17119
  "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
17120
  "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.",
17121
+ "Reuse any existing taskId and decisionId values exactly as they appear in [State].",
17122
+ "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
17123
  "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
17124
  "If you ask the user a new question in this job, do not also close the loop in the same job.",
15983
17125
  "Write the smallest straightforward code for the current step. Avoid defensive fallback branches for hypothetical states that are not currently true.",
@@ -15988,39 +17130,101 @@ ${resultPreview}` : null
15988
17130
  ].filter(Boolean).join("\n\n");
15989
17131
  }
15990
17132
  function buildGranularAgentDomainBlock(domainDocumentation) {
15991
- return domainDocumentation?.trim() || "No domain reference available. The graph may not be ready yet.";
17133
+ return domainDocumentation?.trim() || "No domain contract available. The graph may not be ready yet.";
15992
17134
  }
15993
17135
  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");
17136
+ return renderConstBlock("session", {
17137
+ runtimeId: sessionContext?.sandboxId || null,
17138
+ environmentId: sessionContext?.environmentId || null,
17139
+ userName: sessionContext?.userName || null,
17140
+ domainRevision: sessionContext?.domainRevision || null
17141
+ });
16003
17142
  }
16004
17143
  function buildGranularAgentHeapBlock(heapSummary) {
16005
- return heapSummary?.trim() || "Heap is empty for this session.";
17144
+ return heapSummary?.trim() || renderConstBlock("savedData", {
17145
+ variables: {},
17146
+ lists: {},
17147
+ entries: {}
17148
+ });
16006
17149
  }
16007
17150
  function buildGranularAgentReferentBlock(referentSummary) {
16008
- return referentSummary?.trim() || "No recent referents recorded from prior assistant replies.";
17151
+ return referentSummary?.trim() || renderConstBlock("recentReferences", []);
16009
17152
  }
16010
17153
  function buildGranularAgentLoopBlock(loopSummary) {
16011
- return loopSummary?.trim() || "No active loop state recorded for this session.";
17154
+ return loopSummary?.trim() || renderConstBlock("workflowState", {
17155
+ tasks: [],
17156
+ decisions: [],
17157
+ openPrompts: [],
17158
+ closure: null
17159
+ });
16012
17160
  }
16013
17161
  function buildGranularAgentWorkflowBlock(workflowSummary) {
16014
- return workflowSummary?.trim() || "No current workflow snapshot recorded for this request yet.";
17162
+ return workflowSummary?.trim() || renderConstBlock("workflowContext", {
17163
+ boundary: null,
17164
+ recentActions: [],
17165
+ workingSet: {
17166
+ variables: [],
17167
+ lists: [],
17168
+ entries: []
17169
+ },
17170
+ openHandles: {
17171
+ tasks: [],
17172
+ decisions: [],
17173
+ prompts: []
17174
+ }
17175
+ });
16015
17176
  }
16016
- function buildGranularAgentToolBlock(tools) {
17177
+ function resolvePromptCapabilities(capabilities) {
17178
+ return {
17179
+ executeCode: capabilities?.executeCode !== false,
17180
+ readEntities: capabilities?.readEntities !== false,
17181
+ workflowHelpers: Array.isArray(capabilities?.workflowHelpers) ? capabilities.workflowHelpers : [
17182
+ "ask_user",
17183
+ "confirm",
17184
+ "open_decision",
17185
+ "close_decision",
17186
+ "create_task",
17187
+ "update_task",
17188
+ "complete_task",
17189
+ "close_loop"
17190
+ ],
17191
+ savedData: capabilities?.savedData !== false,
17192
+ showRecords: capabilities?.showRecords !== false
17193
+ };
17194
+ }
17195
+ function buildGranularAgentToolBlock(tools, capabilityOverrides) {
17196
+ const resolvedCapabilities = resolvePromptCapabilities(capabilityOverrides);
17197
+ const normalizedTools = (tools || []).filter((tool) => tool?.name).slice().sort((left, right) => {
17198
+ const leftScope = `${left.className || "global"}:${left.static ? "static" : "instance"}`;
17199
+ const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
17200
+ return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
17201
+ });
17202
+ const writeActions = normalizedTools.filter((tool) => tool.ready !== false).map((tool) => {
17203
+ const scope = tool.className ? `${tool.static ? "class" : "record"}:${tool.className}` : "global";
17204
+ return {
17205
+ name: tool.name,
17206
+ scope,
17207
+ description: tool.description?.trim() || null
17208
+ };
17209
+ });
17210
+ const capabilities = {
17211
+ executeCode: resolvedCapabilities.executeCode,
17212
+ readEntities: resolvedCapabilities.readEntities,
17213
+ writeActions,
17214
+ workflowHelpers: resolvedCapabilities.workflowHelpers,
17215
+ savedData: resolvedCapabilities.savedData,
17216
+ showRecords: resolvedCapabilities.showRecords
17217
+ };
17218
+ return renderConstBlock("capabilities", capabilities);
17219
+ }
17220
+ function buildGranularAgentActionIndex(tools) {
16017
17221
  const normalizedTools = (tools || []).filter((tool) => tool?.name).slice().sort((left, right) => {
16018
17222
  const leftScope = `${left.className || "global"}:${left.static ? "static" : "instance"}`;
16019
17223
  const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
16020
17224
  return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
16021
17225
  });
16022
17226
  if (normalizedTools.length === 0) {
16023
- return "No live effects are available in this session yet.";
17227
+ return "No domain write actions are available.";
16024
17228
  }
16025
17229
  const globalTools = normalizedTools.filter((tool) => !tool.className);
16026
17230
  const staticTools = normalizedTools.filter(
@@ -16029,9 +17233,7 @@ function buildGranularAgentToolBlock(tools) {
16029
17233
  const instanceTools = normalizedTools.filter(
16030
17234
  (tool) => Boolean(tool.className && !tool.static)
16031
17235
  );
16032
- const lines = [
16033
- "Treat this block as the planning map. Use DOMAIN REFERENCE below for exact signatures and query examples."
16034
- ];
17236
+ const lines = ["Available actions by scope:"];
16035
17237
  const appendGroup = (title, group) => {
16036
17238
  lines.push(`- ${title}:`);
16037
17239
  if (group.length === 0) {
@@ -16040,189 +17242,563 @@ function buildGranularAgentToolBlock(tools) {
16040
17242
  }
16041
17243
  for (const tool of group.slice(0, 10)) {
16042
17244
  const availability = tool.ready === false ? " [not ready]" : "";
17245
+ const schema = formatActionSchemaSummary(tool);
16043
17246
  const description = tool.description?.trim() ? ` - ${tool.description.trim()}` : "";
16044
- lines.push(` ${tool.name}${availability}${description}`);
17247
+ lines.push(` ${tool.name}${availability}${schema}${description}`);
16045
17248
  }
16046
17249
  if (group.length > 10) {
16047
17250
  lines.push(` +${group.length - 10} more`);
16048
17251
  }
16049
17252
  };
16050
- appendGroup("Global effects", globalTools);
16051
- appendGroup("Class-level effects", staticTools);
16052
- appendGroup("Record-level effects", instanceTools);
17253
+ appendGroup("Global", globalTools);
17254
+ appendGroup("Class-level", staticTools);
17255
+ appendGroup("Record-level", instanceTools);
16053
17256
  return lines.join("\n");
16054
17257
  }
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}`);
17258
+ function normalizeJsonSchema(value) {
17259
+ if (typeof value === "string") {
17260
+ try {
17261
+ return asRecord4(JSON.parse(value));
17262
+ } catch {
17263
+ return null;
17264
+ }
16068
17265
  }
16069
- if (checkpoint.controllerReason) {
16070
- lines.push(`controllerReason: ${checkpoint.controllerReason}`);
17266
+ return asRecord4(value);
17267
+ }
17268
+ function jsonSchemaTypeName(schema) {
17269
+ const record = normalizeJsonSchema(schema);
17270
+ if (!record) return "unknown";
17271
+ const type = record.type;
17272
+ if (typeof type === "string") {
17273
+ if (type === "array") return "array";
17274
+ if (type === "object") return "object";
17275
+ return type;
16071
17276
  }
16072
- if (typeof checkpoint.noProgressCount === "number") {
16073
- lines.push(`noProgressCount: ${checkpoint.noProgressCount}`);
17277
+ return "unknown";
17278
+ }
17279
+ function summarizeObjectSchema(schema) {
17280
+ const record = normalizeJsonSchema(schema);
17281
+ const properties = asRecord4(record?.properties);
17282
+ if (!properties || Object.keys(properties).length === 0) {
17283
+ return record ? "{}" : null;
17284
+ }
17285
+ const required = new Set(asArray2(record?.required));
17286
+ const fields = Object.entries(properties).slice(0, 8).map(([name, property]) => {
17287
+ const marker = required.has(name) ? "*" : "?";
17288
+ return `${name}${marker}: ${jsonSchemaTypeName(property)}`;
17289
+ });
17290
+ const remaining = Object.keys(properties).length - fields.length;
17291
+ return remaining > 0 ? `${fields.join(", ")}, +${remaining}` : fields.join(", ");
17292
+ }
17293
+ function formatActionSchemaSummary(tool) {
17294
+ const input = summarizeObjectSchema(tool.inputSchema);
17295
+ const output = summarizeObjectSchema(tool.outputSchema);
17296
+ const parts = [];
17297
+ if (input) parts.push(`input { ${input} }`);
17298
+ if (output) parts.push(`output { ${output} }`);
17299
+ return parts.length ? ` (${parts.join("; ")})` : "";
17300
+ }
17301
+ function splitDomainDocumentation(domainDocumentation) {
17302
+ const normalized = domainDocumentation?.trim() || "";
17303
+ if (!normalized) return { types: "", docs: "" };
17304
+ const docsSectionMatch = normalized.match(/\n\s*\[Docs\]\s*\n/i);
17305
+ if (docsSectionMatch?.index !== void 0) {
17306
+ return {
17307
+ types: normalized.slice(0, docsSectionMatch.index).trim(),
17308
+ docs: normalized.slice(docsSectionMatch.index + docsSectionMatch[0].length).trim()
17309
+ };
16074
17310
  }
16075
- if (checkpoint.latestJobError?.trim()) {
16076
- lines.push(`latestJobError: ${checkpoint.latestJobError.trim()}`);
17311
+ const legacyMarker = "Generated usage notes from ./sandbox-tools docs:";
17312
+ const legacyIndex = normalized.indexOf(legacyMarker);
17313
+ if (legacyIndex !== -1) {
17314
+ return {
17315
+ types: normalized.slice(0, legacyIndex).trim(),
17316
+ docs: normalized.slice(legacyIndex + legacyMarker.length).trim()
17317
+ };
16077
17318
  }
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
- );
17319
+ return { types: normalized, docs: "" };
17320
+ }
17321
+ function buildGranularAgentCheckpointBlock(checkpoint) {
17322
+ if (!checkpoint) {
17323
+ return renderConstBlock("previousCodeResult", null);
17324
+ }
17325
+ return renderConstBlock("previousCodeResult", {
17326
+ iteration: typeof checkpoint.iteration === "number" ? checkpoint.iteration : null,
17327
+ latestJobStatus: checkpoint.latestJobStatus || null,
17328
+ controllerOutcome: checkpoint.controllerOutcome || null,
17329
+ controllerReason: checkpoint.controllerReason || null,
17330
+ noProgressCount: typeof checkpoint.noProgressCount === "number" ? checkpoint.noProgressCount : null,
17331
+ latestJobError: checkpoint.latestJobError?.trim() || null,
17332
+ latestActionSummary: Array.isArray(checkpoint.latestActionSummary) ? checkpoint.latestActionSummary.slice(0, 8).map(normalizeActionSummaryForPrompt) : [],
17333
+ latestJobResult: checkpoint.latestJobResult?.trim() || null
17334
+ });
17335
+ }
17336
+ function parseSummaryOutcome(summary) {
17337
+ const outcome = {};
17338
+ for (const part of summary.split(",")) {
17339
+ const trimmed = part.trim();
17340
+ const match = /^([A-Za-z0-9_]+)=(.+)$/.exec(trimmed);
17341
+ if (!match) continue;
17342
+ const [, key, rawValue] = match;
17343
+ const unquoted = rawValue.replace(/^"|"$/g, "");
17344
+ if (/^-?\d+(?:\.\d+)?$/.test(unquoted)) {
17345
+ outcome[key] = Number(unquoted);
17346
+ } else if (unquoted === "true" || unquoted === "false") {
17347
+ outcome[key] = unquoted === "true";
17348
+ } else {
17349
+ outcome[key] = unquoted;
16085
17350
  }
16086
17351
  }
16087
- if (checkpoint.latestJobResult?.trim()) {
16088
- lines.push(`latestJobResult:
16089
- ${checkpoint.latestJobResult.trim()}`);
17352
+ return outcome;
17353
+ }
17354
+ function buildKnownFactsFromCheckpoint(checkpoint) {
17355
+ const summaries = Array.isArray(checkpoint?.latestActionSummary) ? checkpoint.latestActionSummary.map(normalizeActionSummaryForPrompt) : [];
17356
+ const facts = [];
17357
+ for (const summary of summaries) {
17358
+ const countedMatch = /^-\s*Counted\s+([A-Za-z0-9_]+).*?->\s*value=(\d+)/.exec(summary);
17359
+ if (countedMatch) {
17360
+ facts.push({
17361
+ entity: countedMatch[1],
17362
+ query: {},
17363
+ totalCount: Number(countedMatch[2])
17364
+ });
17365
+ continue;
17366
+ }
17367
+ const listedMatch = /^-\s*Listed\s+([A-Za-z0-9_]+).*?->\s*(.+)$/.exec(
17368
+ summary
17369
+ );
17370
+ if (!listedMatch) continue;
17371
+ const outcome = parseSummaryOutcome(listedMatch[2]);
17372
+ const count = typeof outcome.totalCount === "number" ? outcome.totalCount : typeof outcome.count === "number" ? outcome.count : void 0;
17373
+ if (typeof count !== "number") continue;
17374
+ const fact = {
17375
+ entity: listedMatch[1],
17376
+ query: {},
17377
+ totalCount: count
17378
+ };
17379
+ if (typeof outcome.hasMore === "boolean") {
17380
+ fact.lastPageHasMore = outcome.hasMore;
17381
+ fact.loadedAllItems = !outcome.hasMore;
17382
+ } else if (typeof outcome.count === "number" && outcome.count === count) {
17383
+ fact.loadedAllItems = true;
17384
+ }
17385
+ facts.push(fact);
16090
17386
  }
16091
- return lines.length > 0 ? lines.join("\n") : "No previous execution checkpoint recorded for this request yet.";
17387
+ return facts.slice(0, 8);
16092
17388
  }
16093
17389
  function buildGranularAgentSystemPrompt(input) {
17390
+ const outputMode = input.outputMode || "agentMessages";
17391
+ const promptCapabilities = resolvePromptCapabilities(input.capabilities);
17392
+ const domainSections = splitDomainDocumentation(input.domainDocumentation);
16094
17393
  const sessionBlock = buildGranularAgentSessionBlock(input.sessionContext);
16095
- const toolBlock = buildGranularAgentToolBlock(input.tools);
16096
- const domainBlock = buildGranularAgentDomainBlock(input.domainDocumentation);
17394
+ const toolBlock = buildGranularAgentToolBlock(
17395
+ input.tools,
17396
+ input.capabilities
17397
+ );
17398
+ const actionIndex = buildGranularAgentActionIndex(input.tools);
17399
+ const domainBlock = buildGranularAgentDomainBlock(domainSections.types);
16097
17400
  const workflowBlock = buildGranularAgentWorkflowBlock(input.workflowSummary);
16098
17401
  const checkpointBlock = buildGranularAgentCheckpointBlock(input.checkpoint);
16099
17402
  const heapBlock = buildGranularAgentHeapBlock(input.heapSummary);
16100
17403
  const referentBlock = buildGranularAgentReferentBlock(input.referentSummary);
16101
17404
  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.
17405
+ const knownFactsBlock = renderConstBlock(
17406
+ "knownFacts",
17407
+ buildKnownFactsFromCheckpoint(input.checkpoint)
17408
+ );
17409
+ 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 }\`.
17410
+ - Use \`{ reply, show }\` when the host UI should render records, heap variables, or lists from session state.
17411
+ - For multi-record display, prefer a saved list/listName so the UI can render a table; use entryPaths for a few individual records.
17412
+ - 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.
17413
+ - 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.
17414
+ - 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(...)\`.
17415
+ - \`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.
17416
+ - 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.
17417
+ - 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.
17418
+ - 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.
17419
+ - 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.
17420
+ - 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"] })\`.
17421
+ - \`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.
17422
+ - 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.
17423
+ - 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.
17424
+ - 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.
17425
+ - 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.
17426
+ - 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.
17427
+ - 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.
17428
+ - 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(...)\`.
17429
+ - \`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.
17430
+ - 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.
17431
+ - 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.
17432
+ - 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.`;
17433
+ const codeRules = promptCapabilities.executeCode ? `Code:
17434
+ - Use when the request needs session data, saved data, workflow state, record display, or available actions.
17435
+ - When using code, assistant text must be empty or one brief summary.
17436
+ - Code must be plain runnable JavaScript with top-level await.
17437
+ - Import needed classes and helpers from "./sandbox-tools".
17438
+ - Use static top-level imports such as \`import { Foo, agent_text_message } from "./sandbox-tools";\`. Do not use dynamic \`await import("./sandbox-tools")\`.
17439
+ - 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.
17440
+ - 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")\`.
17441
+ - 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.
17442
+ - User-visible output must use the provided message or record-display helpers.
17443
+ - After calling an action or effect, inspect the returned object and base the user-facing answer on its actual fields.
17444
+ - When calling an action, use the exact input property names from the action schema. Do not invent synonym keys for required inputs.
17445
+ - 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".
17446
+ - Never call \`process.exit(...)\`; emit a message and use \`return;\` to stop early.
17447
+ - 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.
17448
+ - 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.
17449
+ - Write \`//\` planning comments for the user, not for engineers: make them friendly, plain-language, and easy to understand.
17450
+ - 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.
17451
+ - 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.
17452
+ - Avoid technical terms, implementation names, code concepts, hidden helper names, and complex domain jargon in \`//\` planning comments unless the user already used that wording.
17453
+ - Each \`//\` planning comment should provide valuable feedback about the plan or next visible step. Do not add filler such as "Starting", "Running", or "Processing".
17454
+ ${outputRules}` : `Code:
17455
+ - Code execution is unavailable. Use text only, or ask the user for missing information.`;
17456
+ const workflowRules = promptCapabilities.workflowHelpers.length > 0 ? `Workflow:
17457
+ - Use workflow helpers when missing input should pause and resume the workflow.
17458
+ - If code discovers missing required input after a read, use \`await loop.ask_user(...)\`; do not just tell the user to provide it.
17459
+ - 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.
17460
+ - 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.
17461
+ - 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.
17462
+ - 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.
17463
+ - Use choice only for 2 to 5 short grounded options.
17464
+ - For record choices, set each option value to a stable scalar such as the record \`_graphPath\` or \`id\`, not a label-only value.
17465
+ - 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.
17466
+ - 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.
17467
+ - 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.
17468
+ - 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.
17469
+ - 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.
17470
+ - 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.
17471
+ - Reuse existing task, decision, and closure ids from [State].
17472
+ - If a user request matches both a domain record/action and a workflow helper, prefer the domain capability.` : "";
17473
+ return `[Harness]
17474
+ You are an assistant for a live user session. Use plain, natural language.
16105
17475
 
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.
17476
+ Mode selection:
17477
+ Text only:
17478
+ - Use for general explanations, unsupported requests, or requests that do not need session data.
17479
+ - 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.
17480
+ - 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.
17481
+ - Do not expose internal names, helper names, file paths, parameter names, or code.
17482
+ - 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
17483
 
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.
17484
+ ${codeRules}
16124
17485
 
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.
17486
+ ${workflowRules}
16136
17487
 
16137
- \u2500\u2500\u2500 SESSION CONTEXT \u2500\u2500\u2500
16138
- ${sessionBlock}
17488
+ High-priority execution rules:
17489
+ - 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.
17490
+ - 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.
17491
+ - 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.
17492
+ - 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.
17493
+ - 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.
17494
+ - 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.
17495
+ - 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.
17496
+ - 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.
17497
+ - 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.
17498
+ - 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.
17499
+ - 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.
17500
+ - 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.
17501
+ - 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.
17502
+ - 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.
17503
+ - 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.
17504
+ - 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.
17505
+ - 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.
17506
+ - 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.
17507
+ - 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.
17508
+ - 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.
17509
+ - 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
17510
 
16140
- \u2500\u2500\u2500 CAPABILITY SNAPSHOT \u2500\u2500\u2500
16141
- ${toolBlock}
17511
+ Intent resolution:
17512
+ - If intent is explicit, act directly.
17513
+ - 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.
17514
+ - 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.
17515
+ - 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.
17516
+ - 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.
17517
+ - 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.
17518
+ - 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.
17519
+ - 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.
17520
+ - 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.
17521
+ - 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.
17522
+ - 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.
17523
+ - 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.
17524
+ - 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.
17525
+ - 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.
17526
+ - 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.
17527
+ - 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.
17528
+ - 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.
17529
+ - Never call \`.get({ path: "" })\`; an empty path is not a saved reference.
17530
+ - 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.
17531
+ - \`.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.
17532
+ - 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.
17533
+ - If the entity, field, target, scope, ranking, or action is ambiguous, create 2 to 5 plausible interpretations.
17534
+ - Probe plausible interpretations with cheap read-only queries before deciding.
17535
+ - 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.
17536
+ - 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.
17537
+ - One strong match means proceed.
17538
+ - Several plausible matches means call \`loop.ask_user({ type: "choice", ... })\` with grounded choices.
17539
+ - No grounded match means ask for missing information.
17540
+ - For consequential changes, resolve first, confirm when needed, then act.
17541
+ - 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.
17542
+ - 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\`.
17543
+ - 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.
17544
+ - 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.
17545
+
17546
+ Use exploratory probing when:
17547
+ - the user gives a human reference instead of an exact id or path
17548
+ - a noun could refer to multiple entity types
17549
+ - a name, number, label, date, or amount is given without a clear field
17550
+ - ranking words are used without a clear metric
17551
+ - a requested change has an unclear target
17552
+ - the first reasonable lookup returns zero results
17553
+ - the first reasonable lookup returns several plausible results
17554
+
17555
+ Do not explore when:
17556
+ - the entity, field, filter, and action are explicit
17557
+ - the request is a general explanation
17558
+ - the request is unsupported by available capabilities
17559
+ - the next step is already a required workflow answer or confirmation
16142
17560
 
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.
17561
+ [Types]
17562
+ Import classes, helpers, and available actions from "./sandbox-tools".
17563
+ 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
17564
 
16147
17565
  ${domainBlock}
16148
17566
 
16149
- \u2500\u2500\u2500 EXECUTION CHECKPOINT \u2500\u2500\u2500
17567
+ [Docs]
17568
+ Query policy:
17569
+ - Use filter, search, sort, count, page, list, and iterate on entity classes.
17570
+ - Push filtering and sorting into entity queries. Do not fetch a page only to filter or sort locally.
17571
+ - Valid filter fields are defined by each entity filter type.
17572
+ - Valid sort fields are defined by each entity sort field type.
17573
+ - Search is class-wide text retrieval, not a field-scoped operator.
17574
+ - Entity classes do not have a \`.search(...)\` method. Use \`.find({ search })\`, \`.page({ search, ... })\`, or \`.list({ search, ... })\`.
17575
+ - 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\`.
17576
+ - 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.
17577
+ - 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.
17578
+ - Combine search and filter when both free-text matching and exact constraints are needed.
17579
+ - 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.
17580
+ - 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.
17581
+ - Boolean filters use \`equal_to: true\` or \`equal_to: false\`.
17582
+ - 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.
17583
+ - 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.
17584
+ - 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.
17585
+ - 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.
17586
+ - 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.
17587
+ - 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.
17588
+ - 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.
17589
+ - 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.
17590
+ - 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.
17591
+ - Prefer generated instance relationship getters from a grounded record over hand-written deep nested relationship filters.
17592
+ - 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.
17593
+ - 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.
17594
+ - 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.
17595
+ - 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.
17596
+ - 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.
17597
+ - 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.
17598
+ - 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.
17599
+ - 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.
17600
+ - 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.
17601
+ - 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.
17602
+ - 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.
17603
+ - 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 }\`.
17604
+ - 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.
17605
+ - 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.
17606
+ - 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.
17607
+ - 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.
17608
+ - 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.
17609
+ - 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.
17610
+ - 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.
17611
+ - 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.
17612
+ - 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.
17613
+ - For scheduling actions, convert relative wording into concrete ISO timestamps before mutating records.
17614
+ - 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.
17615
+ - 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.
17616
+ - 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.
17617
+ - 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.
17618
+ - For exploratory work, use count for totals and page with small perPage for samples; use iteration only after the interpretation is chosen.
17619
+
17620
+ Lookup ladder:
17621
+ 1. Check recent references and saved session data.
17622
+ 2. Try exact id or path when the user gave an id-like value.
17623
+ 3. If the request names a parent/container plus a target, ground the parent/container and traverse declared relationships to target candidates.
17624
+ 4. Try exact filters on fields whose names or aliases match the user words.
17625
+ 5. Try class-wide search with short target-local terms, not the whole user phrase.
17626
+ 6. Try relationship filters when the user mentions connected concepts and the filter shape is documented.
17627
+ 7. If the user names a parent/container and says the label may be approximate, inspect related target records before reporting no match.
17628
+ 8. If still empty, try one small set of normalized, prefix, or fuzzy variants when search supports it.
17629
+ 9. If still empty or ambiguous, ask the user for steering.
17630
+
17631
+ Exploration budget:
17632
+ - For a simple ambiguous reference, try up to 3 strategies.
17633
+ - For a broad ambiguous task, try up to 5 strategies.
17634
+ - Probe with small pages.
17635
+ - Do not run exhaustive scans during probing unless the user explicitly asks for all records or the selected task requires aggregation.
17636
+ - Stop early when a strong unique match is found.
17637
+
17638
+ Strong unique match:
17639
+ - exactly one record matches an exact id or path
17640
+ - exactly one record matches an exact filter on a likely identifier field
17641
+ - exactly one recent reference or saved value fits the request
17642
+ - one interpretation has results and all other reasonable interpretations have none
17643
+
17644
+ Ask the user when:
17645
+ - multiple exact matches exist
17646
+ - several entity types match the same phrase
17647
+ - the best match comes only from broad search and other plausible matches exist
17648
+ - the ranking or metric is unclear
17649
+ - the target is unique but the requested action is unclear
17650
+
17651
+ Relationship filters:
17652
+ - One-record relationships use \`is\`.
17653
+ - Multi-record relationships use \`some\`.
17654
+ - 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.
17655
+ - 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.
17656
+ - 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.
17657
+ - 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.
17658
+ - Use \`some\` only when the generated TypeScript type says \`ManyRelationFilter\`.
17659
+ - 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.
17660
+ - Use \`{ relationship: { id: "record_id" } }\` or \`{ relationship: { path: "class_record_id" } }\` when matching a known related record.
17661
+ - 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\`.
17662
+ - 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.
17663
+ - Use \`{ relationship: { is: { field: { equal_to: value } } } }\` only for nested field filters. Never put \`id\` or \`path\` inside \`is\`.
17664
+ - 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.
17665
+ - Do not pass a full record instance into a filter; if you already fetched a record, filter by its id or path instead.
17666
+ ${domainSections.docs ? `
17667
+ Domain notes:
17668
+ ${domainSections.docs}
17669
+ ` : ""}
17670
+
17671
+ Actions:
17672
+ ${actionIndex}
17673
+ - 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(...)\`.
17674
+ - Actions listed under "Class-level" are class/static methods. Call them on the imported class, e.g. \`await Item.action_name(...)\`.
17675
+ - 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.
17676
+ - Never call a record-level action as \`Class.action_name(...)\`; that method will not exist.
17677
+ - 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.
17678
+ - 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.
17679
+ - 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.
17680
+ - 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.
17681
+ - 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.
17682
+ - 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.
17683
+ - 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.
17684
+ - 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.
17685
+
17686
+ [State]
17687
+ ${toolBlock}
17688
+
17689
+ ${sessionBlock}
17690
+
16150
17691
  ${checkpointBlock}
16151
17692
 
16152
- \u2500\u2500\u2500 WORKFLOW SNAPSHOT \u2500\u2500\u2500
16153
17693
  ${workflowBlock}
16154
17694
 
16155
- \u2500\u2500\u2500 RECENT REFERENTS \u2500\u2500\u2500
16156
17695
  ${referentBlock}
16157
17696
 
16158
- \u2500\u2500\u2500 SESSION HEAP \u2500\u2500\u2500
16159
17697
  ${heapBlock}
16160
17698
 
16161
- \u2500\u2500\u2500 AGENT LOOP STATE \u2500\u2500\u2500
16162
17699
  ${loopBlock}
16163
17700
 
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.
17701
+ ${knownFactsBlock}
16184
17702
 
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.
17703
+ [Request]
17704
+ ${input.request?.trim() || "Use the latest user message in the conversation."}`;
17705
+ }
16192
17706
 
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.`;
17707
+ // src/openai-usage.ts
17708
+ var OPENAI_PRICING_SOURCE_URL = "https://developers.openai.com/api/docs/models/gpt-5.4/";
17709
+ var OPENAI_PRICING_EFFECTIVE_DATE = "2026-05-19";
17710
+ var OPENAI_MODEL_PRICING_USD_PER_MILLION = {
17711
+ "gpt-5.4": {
17712
+ provider: "openai",
17713
+ model: "gpt-5.4",
17714
+ currency: "USD",
17715
+ inputUsdPerMillion: 2.5,
17716
+ cachedInputUsdPerMillion: 0.25,
17717
+ outputUsdPerMillion: 15,
17718
+ sourceUrl: OPENAI_PRICING_SOURCE_URL,
17719
+ effectiveDate: OPENAI_PRICING_EFFECTIVE_DATE
17720
+ }
17721
+ };
17722
+ function asRecord5(value) {
17723
+ return value && typeof value === "object" ? value : null;
17724
+ }
17725
+ function numberField(record, key) {
17726
+ const value = record?.[key];
17727
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
17728
+ }
17729
+ function microsPerMillion(usdPerMillion) {
17730
+ return Math.round(usdPerMillion * 1e6);
17731
+ }
17732
+ function getOpenAIModelPricing(model) {
17733
+ return OPENAI_MODEL_PRICING_USD_PER_MILLION[model] || null;
17734
+ }
17735
+ function normalizeOpenAIUsage(rawUsage) {
17736
+ const usage = asRecord5(rawUsage);
17737
+ if (!usage) {
17738
+ return {
17739
+ inputTokens: 0,
17740
+ cachedInputTokens: 0,
17741
+ uncachedInputTokens: 0,
17742
+ outputTokens: 0,
17743
+ reasoningTokens: 0,
17744
+ totalTokens: 0
17745
+ };
17746
+ }
17747
+ const inputTokens = numberField(usage, "prompt_tokens") || numberField(usage, "input_tokens");
17748
+ const outputTokens = numberField(usage, "completion_tokens") || numberField(usage, "output_tokens");
17749
+ const totalTokens = numberField(usage, "total_tokens") || inputTokens + outputTokens;
17750
+ const inputDetails = asRecord5(usage.prompt_tokens_details) || asRecord5(usage.input_tokens_details);
17751
+ const outputDetails = asRecord5(usage.completion_tokens_details) || asRecord5(usage.output_tokens_details);
17752
+ const cachedInputTokens = Math.min(
17753
+ inputTokens,
17754
+ numberField(inputDetails, "cached_tokens") || numberField(inputDetails, "cached_input_tokens")
17755
+ );
17756
+ const reasoningTokens = numberField(outputDetails, "reasoning_tokens") || numberField(outputDetails, "reasoning_output_tokens");
17757
+ return {
17758
+ inputTokens,
17759
+ cachedInputTokens,
17760
+ uncachedInputTokens: Math.max(inputTokens - cachedInputTokens, 0),
17761
+ outputTokens,
17762
+ reasoningTokens,
17763
+ totalTokens
17764
+ };
17765
+ }
17766
+ function calculateOpenAITokenSpend(model, rawUsage) {
17767
+ const pricing = getOpenAIModelPricing(model);
17768
+ if (!pricing) return null;
17769
+ const usage = normalizeOpenAIUsage(rawUsage);
17770
+ const inputPricePerMillionMicros = microsPerMillion(
17771
+ pricing.inputUsdPerMillion
17772
+ );
17773
+ const cachedInputPricePerMillionMicros = microsPerMillion(
17774
+ pricing.cachedInputUsdPerMillion
17775
+ );
17776
+ const outputPricePerMillionMicros = microsPerMillion(
17777
+ pricing.outputUsdPerMillion
17778
+ );
17779
+ const amountMicros = Math.round(
17780
+ (usage.uncachedInputTokens * inputPricePerMillionMicros + usage.cachedInputTokens * cachedInputPricePerMillionMicros + usage.outputTokens * outputPricePerMillionMicros) / 1e6
17781
+ );
17782
+ return {
17783
+ provider: "openai",
17784
+ model,
17785
+ inputTokens: usage.inputTokens,
17786
+ cachedInputTokens: usage.cachedInputTokens,
17787
+ uncachedInputTokens: usage.uncachedInputTokens,
17788
+ outputTokens: usage.outputTokens,
17789
+ reasoningTokens: usage.reasoningTokens,
17790
+ totalTokens: usage.totalTokens,
17791
+ amountMicros,
17792
+ currency: "USD",
17793
+ inputPricePerMillionMicros,
17794
+ cachedInputPricePerMillionMicros,
17795
+ outputPricePerMillionMicros,
17796
+ pricingSource: pricing.sourceUrl,
17797
+ pricingEffectiveAt: pricing.effectiveDate,
17798
+ usage
17799
+ };
16224
17800
  }
16225
17801
 
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 };
17802
+ export { Environment, EnvironmentSession, Granular, OPENAI_MODEL_PRICING_USD_PER_MILLION, OntologyHandle, Session, WSClient, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentReferentBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, buildOpenAISpendEventId, buildSessionTranscript, calculateOpenAITokenSpend, consumeGranularReasoningOnlyChunk, consumeGranularReasoningTraceChunk, createHarnessVerifierSnapshot, evaluateContinuation, extractPromptTokens, getCurrentClosureId, getExclusivePromptTarget, getOpenAIModelPricing, hasOpenPrompt, invokeRegisteredEffect, isLocalApiUrl, normalizeEffectBehaviors, normalizeOpenAIUsage, normalizePrompt, normalizePromptChoiceOption, normalizePromptText, normalizePromptType, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, recordOpenAIUsageSpend, resolveApiUrl, resolveAuthTokenForApiUrl, resolveJobPresentation, resolvePromptAnswer, reviewGeneratedJobCode, scorePromptChoiceMatch, stripGranularReasoningTrace, toGranularHttpBase };
16227
17803
  //# sourceMappingURL=index.mjs.map
16228
17804
  //# sourceMappingURL=index.mjs.map