@granular-software/sdk 0.4.36 → 0.4.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -2
- package/dist/agent-evals.d.mts +64 -3
- package/dist/agent-evals.d.ts +64 -3
- package/dist/agent-evals.js +2486 -601
- package/dist/agent-evals.js.map +1 -1
- package/dist/agent-evals.mjs +2486 -601
- package/dist/agent-evals.mjs.map +1 -1
- package/dist/agent-harness.d.mts +39 -4
- package/dist/agent-harness.d.ts +39 -4
- package/dist/agent-harness.js +1051 -456
- package/dist/agent-harness.js.map +1 -1
- package/dist/agent-harness.mjs +1049 -457
- package/dist/agent-harness.mjs.map +1 -1
- package/dist/cli/index.js +2335 -289
- package/dist/{client-Cq8onk2D.d.mts → client-eE9nTfvp.d.mts} +109 -28
- package/dist/{client-Cq8onk2D.d.ts → client-eE9nTfvp.d.ts} +109 -28
- package/dist/index.d.mts +17 -5
- package/dist/index.d.ts +17 -5
- package/dist/index.js +1930 -571
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1927 -572
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -3951,11 +3951,22 @@ var TOKEN_REFRESH_LEEWAY_MS = 2 * 60 * 1e3;
|
|
|
3951
3951
|
var TOKEN_REFRESH_RETRY_MS = 30 * 1e3;
|
|
3952
3952
|
var MAX_TIMER_DELAY_MS = 2147483647;
|
|
3953
3953
|
var DEBUG_WS = process.env.GRANULAR_DEBUG_WS === "1";
|
|
3954
|
+
var DEFAULT_RPC_TIMEOUT_MS = 3e4;
|
|
3955
|
+
var DOMAIN_PACKAGE_RPC_TIMEOUT_MS = 12e4;
|
|
3954
3956
|
function debugWs(...args) {
|
|
3955
3957
|
if (DEBUG_WS) {
|
|
3956
3958
|
console.log(...args);
|
|
3957
3959
|
}
|
|
3958
3960
|
}
|
|
3961
|
+
function rpcTimeoutMsForMethod(method) {
|
|
3962
|
+
switch (method) {
|
|
3963
|
+
case "domain.fetchPackagePart":
|
|
3964
|
+
case "domain.getSummary":
|
|
3965
|
+
return DOMAIN_PACKAGE_RPC_TIMEOUT_MS;
|
|
3966
|
+
default:
|
|
3967
|
+
return DEFAULT_RPC_TIMEOUT_MS;
|
|
3968
|
+
}
|
|
3969
|
+
}
|
|
3959
3970
|
var WSClient = class {
|
|
3960
3971
|
ws = null;
|
|
3961
3972
|
url;
|
|
@@ -4380,13 +4391,14 @@ var WSClient = class {
|
|
|
4380
4391
|
return new Promise((resolve, reject) => {
|
|
4381
4392
|
this.messageQueue.push({ resolve, reject, id });
|
|
4382
4393
|
this.ws.send(JSON.stringify(request));
|
|
4394
|
+
const timeoutMs = rpcTimeoutMsForMethod(method);
|
|
4383
4395
|
setTimeout(() => {
|
|
4384
4396
|
const pending = this.messageQueue.find((q) => q.id === id);
|
|
4385
4397
|
if (pending) {
|
|
4386
4398
|
this.messageQueue = this.messageQueue.filter((q) => q.id !== id);
|
|
4387
4399
|
reject(new Error(`RPC timeout: ${method}`));
|
|
4388
4400
|
}
|
|
4389
|
-
},
|
|
4401
|
+
}, timeoutMs);
|
|
4390
4402
|
});
|
|
4391
4403
|
}
|
|
4392
4404
|
async handleIncomingRpc(request) {
|
|
@@ -4500,10 +4512,48 @@ function normalizePromptText(value) {
|
|
|
4500
4512
|
function extractPromptTokens(value) {
|
|
4501
4513
|
return normalizePromptText(value).split(/\s+/).map((token) => token.trim()).filter((token) => token.length > 0);
|
|
4502
4514
|
}
|
|
4515
|
+
function parseJsonPromptChoiceOption(option) {
|
|
4516
|
+
const trimmed = option.trim();
|
|
4517
|
+
if (!trimmed.startsWith("{") || !trimmed.endsWith("}")) return null;
|
|
4518
|
+
try {
|
|
4519
|
+
const parsed = JSON.parse(trimmed);
|
|
4520
|
+
return asRecord(parsed);
|
|
4521
|
+
} catch {
|
|
4522
|
+
return null;
|
|
4523
|
+
}
|
|
4524
|
+
}
|
|
4525
|
+
function normalizePromptChoiceOption(option) {
|
|
4526
|
+
if (typeof option === "string") {
|
|
4527
|
+
const record2 = parseJsonPromptChoiceOption(option);
|
|
4528
|
+
if (!record2) {
|
|
4529
|
+
return { value: option, label: option };
|
|
4530
|
+
}
|
|
4531
|
+
const value2 = typeof record2.value === "string" ? record2.value : typeof record2.id === "string" ? record2.id : typeof record2.label === "string" ? record2.label : JSON.stringify(record2);
|
|
4532
|
+
return {
|
|
4533
|
+
value: value2,
|
|
4534
|
+
label: typeof record2.label === "string" ? record2.label : value2,
|
|
4535
|
+
description: typeof record2.description === "string" ? record2.description : void 0
|
|
4536
|
+
};
|
|
4537
|
+
}
|
|
4538
|
+
const record = option;
|
|
4539
|
+
if (!record) {
|
|
4540
|
+
return { value: "", label: "" };
|
|
4541
|
+
}
|
|
4542
|
+
const nestedJson = (typeof record.value === "string" ? parseJsonPromptChoiceOption(record.value) : null) || (typeof record.label === "string" ? parseJsonPromptChoiceOption(record.label) : null);
|
|
4543
|
+
if (nestedJson) {
|
|
4544
|
+
return normalizePromptChoiceOption(nestedJson);
|
|
4545
|
+
}
|
|
4546
|
+
const value = typeof record.value === "string" ? record.value : typeof record.label === "string" ? record.label : JSON.stringify(record);
|
|
4547
|
+
return {
|
|
4548
|
+
value,
|
|
4549
|
+
label: typeof record.label === "string" ? record.label : value,
|
|
4550
|
+
description: typeof record.description === "string" ? record.description : void 0
|
|
4551
|
+
};
|
|
4552
|
+
}
|
|
4503
4553
|
function scorePromptChoiceMatch(answer, answerTokens, option) {
|
|
4504
|
-
const
|
|
4505
|
-
const
|
|
4506
|
-
const description =
|
|
4554
|
+
const choice = normalizePromptChoiceOption(option);
|
|
4555
|
+
const { value, label } = choice;
|
|
4556
|
+
const description = choice.description || "";
|
|
4507
4557
|
const haystack = normalizePromptText([value, label, description].filter(Boolean).join(" "));
|
|
4508
4558
|
if (!haystack) return { score: 0, resolvedValue: value || label || null };
|
|
4509
4559
|
let score = 0;
|
|
@@ -4539,7 +4589,9 @@ function normalizePrompt(rawValue) {
|
|
|
4539
4589
|
type: normalizePromptType(source === raw ? raw : { ...raw, ...source }),
|
|
4540
4590
|
title: typeof source.title === "string" ? source.title : "Input required",
|
|
4541
4591
|
message: typeof source.message === "string" ? source.message : "",
|
|
4542
|
-
options: Array.isArray(source.options) ? source.options
|
|
4592
|
+
options: Array.isArray(source.options) ? source.options.map(
|
|
4593
|
+
(option) => typeof option === "string" || asRecord(option) ? normalizePromptChoiceOption(option) : option
|
|
4594
|
+
) : void 0,
|
|
4543
4595
|
defaultValue: source.defaultValue,
|
|
4544
4596
|
placeholder: typeof source.placeholder === "string" ? source.placeholder : void 0,
|
|
4545
4597
|
allowEmpty: typeof source.allowEmpty === "boolean" ? source.allowEmpty : void 0,
|
|
@@ -4567,6 +4619,22 @@ function resolvePromptAnswer(prompt, answer) {
|
|
|
4567
4619
|
}
|
|
4568
4620
|
|
|
4569
4621
|
// src/session.ts
|
|
4622
|
+
var PROMPT_TRANSCRIPT_APPEND_TIMEOUT_MS = 5e3;
|
|
4623
|
+
function withPromptTranscriptTimeout(promise) {
|
|
4624
|
+
let timeout = null;
|
|
4625
|
+
return Promise.race([
|
|
4626
|
+
promise,
|
|
4627
|
+
new Promise((_, reject) => {
|
|
4628
|
+
timeout = setTimeout(() => {
|
|
4629
|
+
reject(new Error("Timed out appending prompt answer transcript."));
|
|
4630
|
+
}, PROMPT_TRANSCRIPT_APPEND_TIMEOUT_MS);
|
|
4631
|
+
})
|
|
4632
|
+
]).finally(() => {
|
|
4633
|
+
if (timeout) {
|
|
4634
|
+
clearTimeout(timeout);
|
|
4635
|
+
}
|
|
4636
|
+
});
|
|
4637
|
+
}
|
|
4570
4638
|
var Session = class {
|
|
4571
4639
|
client;
|
|
4572
4640
|
clientId;
|
|
@@ -4583,6 +4651,8 @@ var Session = class {
|
|
|
4583
4651
|
lastKnownTools = /* @__PURE__ */ new Map();
|
|
4584
4652
|
/** Last seen live prompts, keyed by prompt id, for answer normalization */
|
|
4585
4653
|
promptCache = /* @__PURE__ */ new Map();
|
|
4654
|
+
/** Prompt ids locally answered before the document sync catches up. */
|
|
4655
|
+
hiddenPromptIds = /* @__PURE__ */ new Set();
|
|
4586
4656
|
constructor(client, clientId) {
|
|
4587
4657
|
this.client = client;
|
|
4588
4658
|
this.clientId = clientId || `client_${Date.now()}`;
|
|
@@ -4718,8 +4788,9 @@ var Session = class {
|
|
|
4718
4788
|
* `effect.invoke` RPC back to the sandbox effect host, where the registered handlers
|
|
4719
4789
|
* execute locally and return the result to the sandbox.
|
|
4720
4790
|
*/
|
|
4721
|
-
async submitJob(code,
|
|
4722
|
-
|
|
4791
|
+
async submitJob(code, domainRevisionOrOptions) {
|
|
4792
|
+
const options = typeof domainRevisionOrOptions === "string" ? { domainRevision: domainRevisionOrOptions } : domainRevisionOrOptions || {};
|
|
4793
|
+
let revision = options.domainRevision || this.currentDomainRevision || this.extractDomainRevisionFromDoc(this.client.doc) || void 0;
|
|
4723
4794
|
if (!revision) {
|
|
4724
4795
|
try {
|
|
4725
4796
|
const summary = await this.getDomain();
|
|
@@ -4734,7 +4805,9 @@ var Session = class {
|
|
|
4734
4805
|
}
|
|
4735
4806
|
const result = await this.client.call("job.submit", {
|
|
4736
4807
|
domainRevision: revision,
|
|
4737
|
-
code
|
|
4808
|
+
code,
|
|
4809
|
+
metadata: options.metadata,
|
|
4810
|
+
agent: options.agent
|
|
4738
4811
|
});
|
|
4739
4812
|
if (!result.jobId) {
|
|
4740
4813
|
throw new Error("Failed to submit job: no jobId returned");
|
|
@@ -4775,25 +4848,39 @@ var Session = class {
|
|
|
4775
4848
|
const prompt = this.promptCache.get(promptId);
|
|
4776
4849
|
const resolvedAnswer = resolvePromptAnswer(prompt, answer);
|
|
4777
4850
|
this.promptCache.delete(promptId);
|
|
4778
|
-
|
|
4779
|
-
|
|
4780
|
-
answer
|
|
4781
|
-
|
|
4782
|
-
|
|
4851
|
+
this.hiddenPromptIds.add(promptId);
|
|
4852
|
+
try {
|
|
4853
|
+
await this.client.call("prompt.answer", {
|
|
4854
|
+
promptId,
|
|
4855
|
+
answer: resolvedAnswer,
|
|
4856
|
+
value: resolvedAnswer
|
|
4857
|
+
});
|
|
4858
|
+
} catch (error) {
|
|
4859
|
+
this.hiddenPromptIds.delete(promptId);
|
|
4860
|
+
if (prompt) {
|
|
4861
|
+
this.promptCache.set(promptId, prompt);
|
|
4862
|
+
}
|
|
4863
|
+
throw error;
|
|
4864
|
+
}
|
|
4783
4865
|
try {
|
|
4784
4866
|
const content = this.stringifyConversationValue(resolvedAnswer);
|
|
4785
4867
|
if (content.trim()) {
|
|
4786
|
-
await
|
|
4787
|
-
|
|
4788
|
-
|
|
4789
|
-
|
|
4790
|
-
|
|
4868
|
+
await withPromptTranscriptTimeout(
|
|
4869
|
+
this.appendConversationMessage({
|
|
4870
|
+
role: "user",
|
|
4871
|
+
content,
|
|
4872
|
+
promptId
|
|
4873
|
+
})
|
|
4874
|
+
);
|
|
4791
4875
|
}
|
|
4792
4876
|
} catch {
|
|
4793
4877
|
}
|
|
4794
4878
|
}
|
|
4795
4879
|
async appendConversationMessage(input) {
|
|
4796
|
-
return this.client.call(
|
|
4880
|
+
return this.client.call(
|
|
4881
|
+
"conversation.append",
|
|
4882
|
+
input
|
|
4883
|
+
);
|
|
4797
4884
|
}
|
|
4798
4885
|
/**
|
|
4799
4886
|
* Get the current list of available effects.
|
|
@@ -4802,9 +4889,53 @@ var Session = class {
|
|
|
4802
4889
|
getEffects() {
|
|
4803
4890
|
const doc = this.client.doc;
|
|
4804
4891
|
const toolMap = /* @__PURE__ */ new Map();
|
|
4805
|
-
const
|
|
4806
|
-
|
|
4807
|
-
|
|
4892
|
+
const domainPackages = doc.domain?.packages;
|
|
4893
|
+
const packageCandidates = domainPackages && typeof domainPackages === "object" ? [
|
|
4894
|
+
domainPackages.domain,
|
|
4895
|
+
domainPackages["@sandbox/domain"],
|
|
4896
|
+
...Object.values(domainPackages)
|
|
4897
|
+
].filter(Boolean) : [];
|
|
4898
|
+
for (const domainPkg of packageCandidates) {
|
|
4899
|
+
if (domainPkg?.tools && Array.isArray(domainPkg.tools)) {
|
|
4900
|
+
for (const tool of domainPkg.tools) {
|
|
4901
|
+
if (!tool?.name || toolMap.has(tool.name)) continue;
|
|
4902
|
+
toolMap.set(tool.name, {
|
|
4903
|
+
name: tool.name,
|
|
4904
|
+
description: tool.description,
|
|
4905
|
+
inputSchema: tool.inputSchema,
|
|
4906
|
+
outputSchema: tool.outputSchema,
|
|
4907
|
+
className: tool.className || void 0,
|
|
4908
|
+
static: tool.static || false,
|
|
4909
|
+
ready: false,
|
|
4910
|
+
publishedAt: void 0
|
|
4911
|
+
});
|
|
4912
|
+
}
|
|
4913
|
+
}
|
|
4914
|
+
if (!domainPkg?.classes || typeof domainPkg.classes !== "object") {
|
|
4915
|
+
continue;
|
|
4916
|
+
}
|
|
4917
|
+
for (const [className, classDef] of Object.entries(
|
|
4918
|
+
domainPkg.classes
|
|
4919
|
+
)) {
|
|
4920
|
+
const methods = Array.isArray(classDef?.methods) ? classDef.methods : [];
|
|
4921
|
+
for (const method of methods) {
|
|
4922
|
+
if (!method?.name || toolMap.has(method.name)) continue;
|
|
4923
|
+
toolMap.set(method.name, {
|
|
4924
|
+
name: method.name,
|
|
4925
|
+
description: method.description,
|
|
4926
|
+
inputSchema: method.inputSchema,
|
|
4927
|
+
outputSchema: method.outputSchema,
|
|
4928
|
+
className: method.className || classDef?.name || className,
|
|
4929
|
+
static: method.static || false,
|
|
4930
|
+
ready: false,
|
|
4931
|
+
publishedAt: void 0
|
|
4932
|
+
});
|
|
4933
|
+
}
|
|
4934
|
+
}
|
|
4935
|
+
}
|
|
4936
|
+
const legacyDomainPkg = doc.domain?.packages?.domain;
|
|
4937
|
+
if (legacyDomainPkg?.tools && Array.isArray(legacyDomainPkg.tools)) {
|
|
4938
|
+
for (const tool of legacyDomainPkg.tools) {
|
|
4808
4939
|
if (!tool?.name) continue;
|
|
4809
4940
|
toolMap.set(tool.name, {
|
|
4810
4941
|
name: tool.name,
|
|
@@ -4818,6 +4949,27 @@ var Session = class {
|
|
|
4818
4949
|
});
|
|
4819
4950
|
}
|
|
4820
4951
|
}
|
|
4952
|
+
if (legacyDomainPkg?.classes && typeof legacyDomainPkg.classes === "object") {
|
|
4953
|
+
for (const [className, classDef] of Object.entries(
|
|
4954
|
+
legacyDomainPkg.classes
|
|
4955
|
+
)) {
|
|
4956
|
+
const methods = Array.isArray(classDef?.methods) ? classDef.methods : [];
|
|
4957
|
+
for (const method of methods) {
|
|
4958
|
+
if (!method?.name || toolMap.has(method.name)) continue;
|
|
4959
|
+
toolMap.set(method.name, {
|
|
4960
|
+
name: method.name,
|
|
4961
|
+
description: method.description,
|
|
4962
|
+
inputSchema: method.inputSchema,
|
|
4963
|
+
outputSchema: method.outputSchema,
|
|
4964
|
+
className: method.className || classDef?.name || className,
|
|
4965
|
+
static: method.static || false,
|
|
4966
|
+
ready: false,
|
|
4967
|
+
publishedAt: void 0
|
|
4968
|
+
});
|
|
4969
|
+
}
|
|
4970
|
+
}
|
|
4971
|
+
}
|
|
4972
|
+
const hasPolicyFilteredDomainTools = toolMap.size > 0;
|
|
4821
4973
|
const catalogs = doc.catalog?.rawToolCatalogs || {};
|
|
4822
4974
|
for (const [clientId, catalog] of Object.entries(catalogs)) {
|
|
4823
4975
|
const cat = catalog;
|
|
@@ -4825,6 +4977,7 @@ var Session = class {
|
|
|
4825
4977
|
for (const tool of cat.tools) {
|
|
4826
4978
|
if (!tool?.name) continue;
|
|
4827
4979
|
const existing = toolMap.get(tool.name);
|
|
4980
|
+
if (hasPolicyFilteredDomainTools && !existing) continue;
|
|
4828
4981
|
if (existing?.publishedAt && cat.publishedAt && existing.publishedAt > cat.publishedAt)
|
|
4829
4982
|
continue;
|
|
4830
4983
|
const isLocal = clientId === this.clientId;
|
|
@@ -4844,6 +4997,24 @@ var Session = class {
|
|
|
4844
4997
|
}
|
|
4845
4998
|
return Array.from(toolMap.values());
|
|
4846
4999
|
}
|
|
5000
|
+
/**
|
|
5001
|
+
* Return the currently open prompt payloads known to this session.
|
|
5002
|
+
*
|
|
5003
|
+
* These come from live `prompt` / `prompt.request` websocket events and
|
|
5004
|
+
* preserve the exact shape used by `answerPrompt(...)`.
|
|
5005
|
+
*/
|
|
5006
|
+
getPrompts() {
|
|
5007
|
+
return Array.from(this.promptCache.values()).map((prompt) => ({
|
|
5008
|
+
...prompt,
|
|
5009
|
+
options: Array.isArray(prompt.options) ? prompt.options.map(
|
|
5010
|
+
(option) => typeof option === "string" ? option : { ...option }
|
|
5011
|
+
) : void 0,
|
|
5012
|
+
metadata: prompt.metadata ? { ...prompt.metadata } : void 0
|
|
5013
|
+
}));
|
|
5014
|
+
}
|
|
5015
|
+
getHiddenPromptIds() {
|
|
5016
|
+
return Array.from(this.hiddenPromptIds);
|
|
5017
|
+
}
|
|
4847
5018
|
/**
|
|
4848
5019
|
* Backwards-compatible alias for `getEffects()`.
|
|
4849
5020
|
*/
|
|
@@ -4943,11 +5114,7 @@ var Session = class {
|
|
|
4943
5114
|
if (!normalizedDocs) {
|
|
4944
5115
|
return normalizedTypes;
|
|
4945
5116
|
}
|
|
4946
|
-
return [
|
|
4947
|
-
normalizedTypes,
|
|
4948
|
-
"Generated usage notes from ./sandbox-tools docs:",
|
|
4949
|
-
normalizedDocs
|
|
4950
|
-
].join("\n\n");
|
|
5117
|
+
return [normalizedTypes, "[Docs]", normalizedDocs].join("\n\n");
|
|
4951
5118
|
}
|
|
4952
5119
|
if (normalizedDocs) {
|
|
4953
5120
|
return normalizedDocs;
|
|
@@ -5169,6 +5336,7 @@ import { ${allImports} } from "./sandbox-tools";
|
|
|
5169
5336
|
const emitPrompt = (payload) => {
|
|
5170
5337
|
const prompt = normalizePrompt(payload);
|
|
5171
5338
|
if (!prompt) return;
|
|
5339
|
+
this.hiddenPromptIds.delete(prompt.id);
|
|
5172
5340
|
this.promptCache.set(prompt.id, prompt);
|
|
5173
5341
|
this.emit("prompt", prompt);
|
|
5174
5342
|
};
|
|
@@ -5351,6 +5519,7 @@ var JobImplementation = class {
|
|
|
5351
5519
|
eventListeners = /* @__PURE__ */ new Map();
|
|
5352
5520
|
bufferedAgentMessages = [];
|
|
5353
5521
|
bufferedAgentMessageIds = /* @__PURE__ */ new Set();
|
|
5522
|
+
resultSettled = false;
|
|
5354
5523
|
metadata;
|
|
5355
5524
|
constructor(id, client, initialState) {
|
|
5356
5525
|
this.id = id;
|
|
@@ -5375,7 +5544,9 @@ var JobImplementation = class {
|
|
|
5375
5544
|
if (execData.error) {
|
|
5376
5545
|
this.finalize("failed", void 0, execData.error);
|
|
5377
5546
|
} else {
|
|
5378
|
-
this.finalize("succeeded", execData.result
|
|
5547
|
+
this.finalize("succeeded", execData.result, void 0, {
|
|
5548
|
+
hasResult: Object.prototype.hasOwnProperty.call(execData, "result")
|
|
5549
|
+
});
|
|
5379
5550
|
}
|
|
5380
5551
|
this.emit("status", this.status);
|
|
5381
5552
|
}
|
|
@@ -5411,9 +5582,6 @@ var JobImplementation = class {
|
|
|
5411
5582
|
if (normalizedStatus === "failed" || normalizedStatus === "timeout" || normalizedStatus === "canceled") {
|
|
5412
5583
|
this.finalize(normalizedStatus);
|
|
5413
5584
|
}
|
|
5414
|
-
if (normalizedStatus === "succeeded") {
|
|
5415
|
-
this.finalize("succeeded");
|
|
5416
|
-
}
|
|
5417
5585
|
this.emit("status", normalizedStatus);
|
|
5418
5586
|
});
|
|
5419
5587
|
this.client.on(`job.${id}.stdout`, (line) => {
|
|
@@ -5433,7 +5601,7 @@ var JobImplementation = class {
|
|
|
5433
5601
|
this.emit("stderr", line);
|
|
5434
5602
|
});
|
|
5435
5603
|
this.client.on(`job.${id}.result`, (result) => {
|
|
5436
|
-
this.finalize("succeeded", result);
|
|
5604
|
+
this.finalize("succeeded", result, void 0, { hasResult: true });
|
|
5437
5605
|
});
|
|
5438
5606
|
this.client.on(`job.${id}.error`, (error) => {
|
|
5439
5607
|
this.finalize("failed", void 0, error);
|
|
@@ -5454,7 +5622,9 @@ var JobImplementation = class {
|
|
|
5454
5622
|
this.client.on("job.completed", (data) => {
|
|
5455
5623
|
const jobData = data;
|
|
5456
5624
|
if (jobData.jobId === id) {
|
|
5457
|
-
this.finalize("succeeded", jobData.result
|
|
5625
|
+
this.finalize("succeeded", jobData.result, void 0, {
|
|
5626
|
+
hasResult: true
|
|
5627
|
+
});
|
|
5458
5628
|
this.emit("status", this.status);
|
|
5459
5629
|
}
|
|
5460
5630
|
});
|
|
@@ -5579,7 +5749,7 @@ var JobImplementation = class {
|
|
|
5579
5749
|
this.metadata.status = "running";
|
|
5580
5750
|
}
|
|
5581
5751
|
}
|
|
5582
|
-
finalize(status, result, error) {
|
|
5752
|
+
finalize(status, result, error, options = {}) {
|
|
5583
5753
|
if (!this.metadata.startedAt) {
|
|
5584
5754
|
this.metadata.startedAt = Date.now();
|
|
5585
5755
|
}
|
|
@@ -5587,14 +5757,18 @@ var JobImplementation = class {
|
|
|
5587
5757
|
this.metadata.status = status;
|
|
5588
5758
|
this.metadata.completedAt = this.metadata.completedAt || Date.now();
|
|
5589
5759
|
this.metadata.durationMs = this.metadata.completedAt - this.metadata.startedAt;
|
|
5590
|
-
if (result !== void 0) {
|
|
5760
|
+
if (!this.resultSettled && (options.hasResult || result !== void 0)) {
|
|
5591
5761
|
this.metadata.result = sanitizeFeedbackValue(result);
|
|
5762
|
+
this.resultSettled = true;
|
|
5592
5763
|
this._resolveResult(result);
|
|
5593
5764
|
}
|
|
5594
|
-
if (error !== void 0) {
|
|
5595
|
-
const
|
|
5765
|
+
if (!this.resultSettled && (error !== void 0 || status === "failed" || status === "timeout" || status === "canceled")) {
|
|
5766
|
+
const fallbackError = new Error(`Job ${this.id} ${status}.`);
|
|
5767
|
+
const cause = error ?? fallbackError;
|
|
5768
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
5596
5769
|
this.metadata.error = truncateFeedbackString(message);
|
|
5597
|
-
this.
|
|
5770
|
+
this.resultSettled = true;
|
|
5771
|
+
this._rejectResult(cause);
|
|
5598
5772
|
}
|
|
5599
5773
|
}
|
|
5600
5774
|
upsertToolCall(next) {
|
|
@@ -5677,6 +5851,17 @@ function humanTextFromStdout(stdout) {
|
|
|
5677
5851
|
}
|
|
5678
5852
|
return null;
|
|
5679
5853
|
}
|
|
5854
|
+
function responseTextFromAgentMessages(agentMessages) {
|
|
5855
|
+
for (const message of [...agentMessages].reverse()) {
|
|
5856
|
+
const record = asRecord2(message);
|
|
5857
|
+
if (!record) continue;
|
|
5858
|
+
for (const key of RESPONSE_KEYS) {
|
|
5859
|
+
const normalized = normalizeText(record[key]);
|
|
5860
|
+
if (normalized) return normalized;
|
|
5861
|
+
}
|
|
5862
|
+
}
|
|
5863
|
+
return null;
|
|
5864
|
+
}
|
|
5680
5865
|
function pushString(target, value) {
|
|
5681
5866
|
if (typeof value === "string" && value.trim()) {
|
|
5682
5867
|
target.add(value.trim());
|
|
@@ -5702,6 +5887,41 @@ function collectReferencesFromRecord(record, refs) {
|
|
|
5702
5887
|
for (const key of VARIABLE_ARRAY_KEY_CANDIDATES)
|
|
5703
5888
|
pushStringArray(refs.variableNames, record[key]);
|
|
5704
5889
|
}
|
|
5890
|
+
function stringValue(record, keys) {
|
|
5891
|
+
for (const key of keys) {
|
|
5892
|
+
const value = record[key];
|
|
5893
|
+
if (typeof value === "string" && value.trim()) {
|
|
5894
|
+
return value.trim();
|
|
5895
|
+
}
|
|
5896
|
+
}
|
|
5897
|
+
return null;
|
|
5898
|
+
}
|
|
5899
|
+
function findEntryPathForRecord(record, heap) {
|
|
5900
|
+
const directPath = stringValue(record, ["entryPath", "path"]);
|
|
5901
|
+
if (directPath && heap.entriesByPath?.[directPath]) {
|
|
5902
|
+
return directPath;
|
|
5903
|
+
}
|
|
5904
|
+
const id = stringValue(record, ["id", "_id", "recordId", "objectId"]);
|
|
5905
|
+
if (!id) {
|
|
5906
|
+
return null;
|
|
5907
|
+
}
|
|
5908
|
+
const className = stringValue(record, [
|
|
5909
|
+
"className",
|
|
5910
|
+
"_className",
|
|
5911
|
+
"__className",
|
|
5912
|
+
"prototype",
|
|
5913
|
+
"type"
|
|
5914
|
+
]);
|
|
5915
|
+
const entries = Object.values(heap.entriesByPath || {});
|
|
5916
|
+
const exact = entries.find(
|
|
5917
|
+
(entry) => entry.id === id && (!className || entry.className === className || entry.prototypes?.includes(className))
|
|
5918
|
+
);
|
|
5919
|
+
if (exact?.path) {
|
|
5920
|
+
return exact.path;
|
|
5921
|
+
}
|
|
5922
|
+
const idOnlyMatches = entries.filter((entry) => entry.id === id);
|
|
5923
|
+
return idOnlyMatches.length === 1 ? idOnlyMatches[0].path : null;
|
|
5924
|
+
}
|
|
5705
5925
|
function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__ */ new Set()) {
|
|
5706
5926
|
if (value === null || value === void 0 || depth > 4 || seen.has(value))
|
|
5707
5927
|
return;
|
|
@@ -5722,6 +5942,8 @@ function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__
|
|
|
5722
5942
|
const record = asRecord2(value);
|
|
5723
5943
|
if (!record) return;
|
|
5724
5944
|
seen.add(value);
|
|
5945
|
+
const entryPath = findEntryPathForRecord(record, heap);
|
|
5946
|
+
if (entryPath) refs.entryPaths.add(entryPath);
|
|
5725
5947
|
collectReferencesFromRecord(record, refs);
|
|
5726
5948
|
for (const key of UI_CONTAINER_KEYS) {
|
|
5727
5949
|
const nested = asRecord2(record[key]);
|
|
@@ -5830,6 +6052,7 @@ function resolveJobPresentation({
|
|
|
5830
6052
|
jobId,
|
|
5831
6053
|
result,
|
|
5832
6054
|
stdout = [],
|
|
6055
|
+
agentMessages = [],
|
|
5833
6056
|
sessionHeap,
|
|
5834
6057
|
allowExplicitArtifacts = true
|
|
5835
6058
|
}) {
|
|
@@ -5862,7 +6085,7 @@ function resolveJobPresentation({
|
|
|
5862
6085
|
const hasExplicitArtifacts = allowExplicitArtifacts && (explicitEntries.length > 0 || explicitLists.length > 0);
|
|
5863
6086
|
const lists = hasExplicitArtifacts ? explicitLists : jobLists;
|
|
5864
6087
|
const entries = hasExplicitArtifacts ? explicitEntries : changedEntries;
|
|
5865
|
-
const responseText = extractResponseText(result, stdout) || fallbackResponseText(entries, lists);
|
|
6088
|
+
const responseText = extractResponseText(result, stdout) || responseTextFromAgentMessages(agentMessages) || fallbackResponseText(entries, lists);
|
|
5866
6089
|
return {
|
|
5867
6090
|
responseText,
|
|
5868
6091
|
entries,
|
|
@@ -10338,6 +10561,67 @@ external_exports.object({
|
|
|
10338
10561
|
transitions: external_exports.array(StateMachineTransitionSchema),
|
|
10339
10562
|
finalStates: external_exports.array(external_exports.string()).optional()
|
|
10340
10563
|
}).strict();
|
|
10564
|
+
var POLICY_OPERATORS = [
|
|
10565
|
+
"eq",
|
|
10566
|
+
"neq",
|
|
10567
|
+
"gt",
|
|
10568
|
+
"gte",
|
|
10569
|
+
"lt",
|
|
10570
|
+
"lte",
|
|
10571
|
+
"contains",
|
|
10572
|
+
"not_contains",
|
|
10573
|
+
"starts_with",
|
|
10574
|
+
"ends_with",
|
|
10575
|
+
"exists"
|
|
10576
|
+
];
|
|
10577
|
+
var PolicyPredicateSchema = external_exports.object({
|
|
10578
|
+
path: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional(),
|
|
10579
|
+
field: external_exports.string().optional(),
|
|
10580
|
+
input: external_exports.string().optional(),
|
|
10581
|
+
operator: external_exports.enum([...POLICY_OPERATORS]),
|
|
10582
|
+
stringValue: external_exports.string().optional(),
|
|
10583
|
+
numberValue: external_exports.number().optional(),
|
|
10584
|
+
booleanValue: external_exports.boolean().optional(),
|
|
10585
|
+
value: external_exports.union([external_exports.string(), external_exports.number(), external_exports.boolean(), external_exports.null()]).optional()
|
|
10586
|
+
}).strict();
|
|
10587
|
+
var PolicyStateMachinePredicateSchema = external_exports.object({
|
|
10588
|
+
machine: external_exports.string().min(1),
|
|
10589
|
+
operator: external_exports.enum([...POLICY_OPERATORS]),
|
|
10590
|
+
state: external_exports.string().optional(),
|
|
10591
|
+
stringValue: external_exports.string().optional()
|
|
10592
|
+
}).strict();
|
|
10593
|
+
var PolicyConditionSchema = external_exports.lazy(
|
|
10594
|
+
() => external_exports.object({
|
|
10595
|
+
all: external_exports.array(PolicyConditionSchema).optional(),
|
|
10596
|
+
any: external_exports.array(PolicyConditionSchema).optional(),
|
|
10597
|
+
not: PolicyConditionSchema.optional(),
|
|
10598
|
+
input: PolicyPredicateSchema.optional(),
|
|
10599
|
+
object: PolicyPredicateSchema.optional(),
|
|
10600
|
+
stateMachine: PolicyStateMachinePredicateSchema.optional()
|
|
10601
|
+
}).strict().refine(
|
|
10602
|
+
(data) => [
|
|
10603
|
+
data.all,
|
|
10604
|
+
data.any,
|
|
10605
|
+
data.not,
|
|
10606
|
+
data.input,
|
|
10607
|
+
data.object,
|
|
10608
|
+
data.stateMachine
|
|
10609
|
+
].filter((value) => value !== void 0).length === 1,
|
|
10610
|
+
{
|
|
10611
|
+
message: "Policy condition must define exactly one of all, any, not, input, object, or stateMachine"
|
|
10612
|
+
}
|
|
10613
|
+
)
|
|
10614
|
+
);
|
|
10615
|
+
var PolicyRuleSchema = external_exports.object({
|
|
10616
|
+
id: external_exports.string().min(1).optional(),
|
|
10617
|
+
reason: external_exports.string().optional(),
|
|
10618
|
+
when: PolicyConditionSchema
|
|
10619
|
+
}).strict();
|
|
10620
|
+
var PoliciesSchema = external_exports.object({
|
|
10621
|
+
allowWhen: external_exports.array(PolicyRuleSchema).optional(),
|
|
10622
|
+
confirmWhen: external_exports.array(PolicyRuleSchema).optional(),
|
|
10623
|
+
denyWhen: external_exports.array(PolicyRuleSchema).optional()
|
|
10624
|
+
}).strict();
|
|
10341
10625
|
external_exports.object({
|
|
10342
10626
|
postCondition: external_exports.union([
|
|
10343
10627
|
external_exports.string(),
|
|
@@ -10367,7 +10651,8 @@ external_exports.object({
|
|
|
10367
10651
|
reason: external_exports.string().optional(),
|
|
10368
10652
|
mode: external_exports.string().optional()
|
|
10369
10653
|
}).strict()
|
|
10370
|
-
]).optional()
|
|
10654
|
+
]).optional(),
|
|
10655
|
+
policies: PoliciesSchema.optional()
|
|
10371
10656
|
}).strict();
|
|
10372
10657
|
|
|
10373
10658
|
// ../metamodel-core/src/index.ts
|
|
@@ -11399,6 +11684,148 @@ var noteMetamodelPackage = defineMetamodelPackage({
|
|
|
11399
11684
|
}
|
|
11400
11685
|
});
|
|
11401
11686
|
|
|
11687
|
+
// ../policy-engine/src/index.ts
|
|
11688
|
+
function isRecord(value) {
|
|
11689
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
11690
|
+
}
|
|
11691
|
+
function normalizePath(value) {
|
|
11692
|
+
if (Array.isArray(value)) {
|
|
11693
|
+
return value.map((part) => String(part)).filter(Boolean);
|
|
11694
|
+
}
|
|
11695
|
+
if (typeof value === "string") {
|
|
11696
|
+
return value.includes(".") ? value.split(".").filter(Boolean) : [value];
|
|
11697
|
+
}
|
|
11698
|
+
return [];
|
|
11699
|
+
}
|
|
11700
|
+
function firstDefinedValue(spec) {
|
|
11701
|
+
if ("value" in spec) return spec.value;
|
|
11702
|
+
if ("stringValue" in spec) return spec.stringValue;
|
|
11703
|
+
if ("numberValue" in spec) return spec.numberValue;
|
|
11704
|
+
if ("booleanValue" in spec) return spec.booleanValue;
|
|
11705
|
+
if ("state" in spec) return spec.state;
|
|
11706
|
+
return void 0;
|
|
11707
|
+
}
|
|
11708
|
+
function normalizeCondition(input) {
|
|
11709
|
+
if (input === void 0 || input === null) return { kind: "always" };
|
|
11710
|
+
if (!isRecord(input)) {
|
|
11711
|
+
throw new Error("Policy condition must be an object");
|
|
11712
|
+
}
|
|
11713
|
+
if (Array.isArray(input.all)) {
|
|
11714
|
+
return {
|
|
11715
|
+
kind: "all",
|
|
11716
|
+
conditions: input.all.map((item) => normalizeCondition(item))
|
|
11717
|
+
};
|
|
11718
|
+
}
|
|
11719
|
+
if (Array.isArray(input.any)) {
|
|
11720
|
+
return {
|
|
11721
|
+
kind: "any",
|
|
11722
|
+
conditions: input.any.map((item) => normalizeCondition(item))
|
|
11723
|
+
};
|
|
11724
|
+
}
|
|
11725
|
+
if (input.not !== void 0) {
|
|
11726
|
+
return { kind: "not", condition: normalizeCondition(input.not) };
|
|
11727
|
+
}
|
|
11728
|
+
for (const source of ["input", "object", "stateMachine"]) {
|
|
11729
|
+
const raw = input[source];
|
|
11730
|
+
if (!isRecord(raw)) continue;
|
|
11731
|
+
const operator = raw.operator;
|
|
11732
|
+
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") {
|
|
11733
|
+
throw new Error(`Unsupported policy operator: ${String(operator)}`);
|
|
11734
|
+
}
|
|
11735
|
+
if (source === "stateMachine") {
|
|
11736
|
+
const machine = typeof raw.machine === "string" ? raw.machine : "";
|
|
11737
|
+
if (!machine) throw new Error("stateMachine condition requires machine");
|
|
11738
|
+
return {
|
|
11739
|
+
kind: "predicate",
|
|
11740
|
+
source,
|
|
11741
|
+
path: [machine],
|
|
11742
|
+
machine,
|
|
11743
|
+
operator,
|
|
11744
|
+
value: firstDefinedValue(raw)
|
|
11745
|
+
};
|
|
11746
|
+
}
|
|
11747
|
+
const path = normalizePath(raw.path ?? raw.field ?? raw.input);
|
|
11748
|
+
if (path.length === 0) {
|
|
11749
|
+
throw new Error(`${source} condition requires a path`);
|
|
11750
|
+
}
|
|
11751
|
+
return {
|
|
11752
|
+
kind: "predicate",
|
|
11753
|
+
source,
|
|
11754
|
+
path,
|
|
11755
|
+
operator,
|
|
11756
|
+
value: firstDefinedValue(raw)
|
|
11757
|
+
};
|
|
11758
|
+
}
|
|
11759
|
+
throw new Error(
|
|
11760
|
+
"Policy condition must contain all, any, not, input, object, or stateMachine"
|
|
11761
|
+
);
|
|
11762
|
+
}
|
|
11763
|
+
function summarizeCondition(condition) {
|
|
11764
|
+
switch (condition.kind) {
|
|
11765
|
+
case "always":
|
|
11766
|
+
return "always";
|
|
11767
|
+
case "all":
|
|
11768
|
+
return condition.conditions.map(summarizeCondition).join(" and ");
|
|
11769
|
+
case "any":
|
|
11770
|
+
return condition.conditions.map(summarizeCondition).join(" or ");
|
|
11771
|
+
case "not":
|
|
11772
|
+
return `not (${summarizeCondition(condition.condition)})`;
|
|
11773
|
+
case "predicate": {
|
|
11774
|
+
const path = condition.source === "stateMachine" ? `stateMachine.${condition.machine || condition.path.join(".")}` : `${condition.source}.${condition.path.join(".")}`;
|
|
11775
|
+
if (condition.operator === "exists") return `${path} exists`;
|
|
11776
|
+
return `${path} ${condition.operator} ${String(condition.value)}`;
|
|
11777
|
+
}
|
|
11778
|
+
}
|
|
11779
|
+
}
|
|
11780
|
+
|
|
11781
|
+
// ../metamodel-policy/src/index.ts
|
|
11782
|
+
function escapeGraphqlString(value) {
|
|
11783
|
+
return JSON.stringify(value);
|
|
11784
|
+
}
|
|
11785
|
+
function buildPolicyMutations(effectKey, spec) {
|
|
11786
|
+
const policies = spec.policies;
|
|
11787
|
+
if (!policies) return [];
|
|
11788
|
+
const mutations = [];
|
|
11789
|
+
const addRules = (key, outcome) => {
|
|
11790
|
+
const rules = policies[key] || [];
|
|
11791
|
+
rules.forEach((rule, index) => {
|
|
11792
|
+
const condition = normalizeCondition(rule.when);
|
|
11793
|
+
const summary = rule.reason || summarizeCondition(condition);
|
|
11794
|
+
const id = rule.id || `${effectKey}:${outcome}:${index + 1}`;
|
|
11795
|
+
mutations.push({
|
|
11796
|
+
label: `set policy ${outcome} on ${effectKey}`,
|
|
11797
|
+
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))}) }`
|
|
11798
|
+
});
|
|
11799
|
+
});
|
|
11800
|
+
};
|
|
11801
|
+
addRules("allowWhen", "allow");
|
|
11802
|
+
addRules("confirmWhen", "confirm");
|
|
11803
|
+
addRules("denyWhen", "deny");
|
|
11804
|
+
return mutations;
|
|
11805
|
+
}
|
|
11806
|
+
var policyMetamodelPackage = defineMetamodelPackage({
|
|
11807
|
+
id: "policy",
|
|
11808
|
+
manifest: {
|
|
11809
|
+
buildEffectMutations: buildPolicyMutations
|
|
11810
|
+
},
|
|
11811
|
+
summary: {
|
|
11812
|
+
selections: {
|
|
11813
|
+
methodFields: ["policies"]
|
|
11814
|
+
},
|
|
11815
|
+
readMethodSummary(rawMethod) {
|
|
11816
|
+
return rawMethod.policies ? { metamodels: { policies: rawMethod.policies } } : {};
|
|
11817
|
+
}
|
|
11818
|
+
},
|
|
11819
|
+
docs: {
|
|
11820
|
+
effectRows: [
|
|
11821
|
+
{
|
|
11822
|
+
key: "policies",
|
|
11823
|
+
description: "Universal effect policies with allowWhen, confirmWhen, and denyWhen structural conditions."
|
|
11824
|
+
}
|
|
11825
|
+
]
|
|
11826
|
+
}
|
|
11827
|
+
});
|
|
11828
|
+
|
|
11402
11829
|
// ../metamodel-required/src/index.ts
|
|
11403
11830
|
function buildRequiredFieldMutations(fieldPath, required) {
|
|
11404
11831
|
if (!required) return [];
|
|
@@ -12173,7 +12600,8 @@ var DEFAULT_METAMODEL_PACKAGES = [
|
|
|
12173
12600
|
searchableMetamodelPackage,
|
|
12174
12601
|
validationRuleMetamodelPackage,
|
|
12175
12602
|
stateMachineMetamodelPackage,
|
|
12176
|
-
effectBehaviorsMetamodelPackage
|
|
12603
|
+
effectBehaviorsMetamodelPackage,
|
|
12604
|
+
policyMetamodelPackage
|
|
12177
12605
|
];
|
|
12178
12606
|
createMetamodelRegistry(
|
|
12179
12607
|
DEFAULT_METAMODEL_PACKAGES
|
|
@@ -12240,6 +12668,12 @@ var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_COUNT = 3;
|
|
|
12240
12668
|
var DEFAULT_DIRECT_RECORD_OBJECTS_RETRY_DELAY_MS = 1e3;
|
|
12241
12669
|
var LOCAL_CONTROL_REQUEST_RETRY_COUNT = 4;
|
|
12242
12670
|
var LOCAL_CONTROL_REQUEST_RETRY_DELAY_MS = 500;
|
|
12671
|
+
var SESSION_DATA_REQUEST_RETRY_COUNT = 4;
|
|
12672
|
+
var SESSION_DATA_REQUEST_RETRY_DELAY_MS = 500;
|
|
12673
|
+
var EFFECT_HOST_CONNECT_TIMEOUT_MS = 15e3;
|
|
12674
|
+
var EFFECT_CATALOG_SYNC_TIMEOUT_MS = 3e4;
|
|
12675
|
+
var EFFECT_CATALOG_SYNC_RETRY_COUNT = 3;
|
|
12676
|
+
var EFFECT_CATALOG_SYNC_RETRY_DELAY_MS = 1e3;
|
|
12243
12677
|
function planRecordObjectsChunks(records, batchSize) {
|
|
12244
12678
|
const total = records.length;
|
|
12245
12679
|
const size = Math.max(1, Math.min(batchSize, total));
|
|
@@ -12254,6 +12688,19 @@ function planRecordObjectsChunks(records, batchSize) {
|
|
|
12254
12688
|
function sleep(ms) {
|
|
12255
12689
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
12256
12690
|
}
|
|
12691
|
+
function withTimeout(promise, timeoutMs, label) {
|
|
12692
|
+
let timer = null;
|
|
12693
|
+
const timeout = new Promise((_, reject) => {
|
|
12694
|
+
timer = setTimeout(() => {
|
|
12695
|
+
reject(new Error(`${label} timed out after ${timeoutMs}ms`));
|
|
12696
|
+
}, timeoutMs);
|
|
12697
|
+
});
|
|
12698
|
+
return Promise.race([promise, timeout]).finally(() => {
|
|
12699
|
+
if (timer) {
|
|
12700
|
+
clearTimeout(timer);
|
|
12701
|
+
}
|
|
12702
|
+
});
|
|
12703
|
+
}
|
|
12257
12704
|
function isLocalControlUrl(url) {
|
|
12258
12705
|
try {
|
|
12259
12706
|
const parsed = new URL(url);
|
|
@@ -12267,7 +12714,19 @@ function isRetryableLocalWorkerRestart(status, body, url) {
|
|
|
12267
12714
|
}
|
|
12268
12715
|
function isRetryableRecordObjectsError(error) {
|
|
12269
12716
|
const message = error instanceof Error ? error.message : String(error);
|
|
12270
|
-
return /worker restarted mid-request|econnreset|network|socket connection was closed unexpectedly|timed out/i.test(
|
|
12717
|
+
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(
|
|
12718
|
+
message
|
|
12719
|
+
);
|
|
12720
|
+
}
|
|
12721
|
+
function isRetryableEffectRegistrationError(error) {
|
|
12722
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
12723
|
+
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(
|
|
12724
|
+
message
|
|
12725
|
+
);
|
|
12726
|
+
}
|
|
12727
|
+
function isRetryableSessionDataError(error) {
|
|
12728
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
12729
|
+
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(
|
|
12271
12730
|
message
|
|
12272
12731
|
);
|
|
12273
12732
|
}
|
|
@@ -12289,16 +12748,28 @@ function computeEffectRegistrationKey(effect) {
|
|
|
12289
12748
|
effect.versionSelector
|
|
12290
12749
|
)}`;
|
|
12291
12750
|
}
|
|
12292
|
-
function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId) {
|
|
12293
|
-
const
|
|
12294
|
-
|
|
12751
|
+
function buildEffectHostUrl(apiUrl, sandboxId, effectClientId, clientId, effectHostUrl) {
|
|
12752
|
+
const overrideUrl = effectHostUrl || process.env.GRANULAR_EFFECT_HOST_URL || process.env.EFFECT_HOST_URL;
|
|
12753
|
+
const api = new URL(apiUrl);
|
|
12754
|
+
const localRuntimeBase = process.env.RUNTIME_ORCHESTRATOR_URL || (isLocalControlUrl(apiUrl) ? `${api.protocol}//${api.hostname}:8791` : "");
|
|
12755
|
+
const url = new URL(overrideUrl || localRuntimeBase || apiUrl);
|
|
12756
|
+
if (url.protocol === "https:") {
|
|
12757
|
+
url.protocol = "wss:";
|
|
12758
|
+
} else if (url.protocol === "http:") {
|
|
12759
|
+
url.protocol = "ws:";
|
|
12760
|
+
}
|
|
12761
|
+
if (!overrideUrl && isLocalControlUrl(apiUrl) && api.pathname.endsWith("/granular")) {
|
|
12762
|
+
url.pathname = "/granular/orchestrator/effects/connect";
|
|
12763
|
+
} else if (url.pathname.endsWith("/granular/ws/connect")) {
|
|
12295
12764
|
url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
|
|
12296
12765
|
} else if (url.pathname.endsWith("/granular")) {
|
|
12297
|
-
url.pathname = `${url.pathname.replace(/\/$/, "")}/effects/connect`;
|
|
12766
|
+
url.pathname = isLocalControlUrl(url.toString()) ? "/granular/orchestrator/effects/connect" : `${url.pathname.replace(/\/$/, "")}/effects/connect`;
|
|
12298
12767
|
} else if (url.pathname.endsWith("/v2/ws/connect")) {
|
|
12299
12768
|
url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
|
|
12300
12769
|
} else if (url.pathname.endsWith("/v2/ws")) {
|
|
12301
12770
|
url.pathname = url.pathname.replace(/\/ws$/, "/effects/connect");
|
|
12771
|
+
} else if (url.pathname === "/" && isLocalControlUrl(url.toString()) && (url.port === "8791" || !overrideUrl && Boolean(localRuntimeBase))) {
|
|
12772
|
+
url.pathname = "/granular/orchestrator/effects/connect";
|
|
12302
12773
|
} else if (url.pathname.endsWith("/ws/connect")) {
|
|
12303
12774
|
url.pathname = url.pathname.replace(/\/ws\/connect$/, "/effects/connect");
|
|
12304
12775
|
} else if (url.pathname.endsWith("/ws")) {
|
|
@@ -12333,6 +12804,79 @@ function normalizeHeapSnapshot(raw) {
|
|
|
12333
12804
|
updatedAt: typeof heap.updatedAt === "number" ? heap.updatedAt : Date.now()
|
|
12334
12805
|
};
|
|
12335
12806
|
}
|
|
12807
|
+
function normalizeGraphPathSegment(value) {
|
|
12808
|
+
return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "");
|
|
12809
|
+
}
|
|
12810
|
+
function extractRecordIdFromGraphPath(path, className) {
|
|
12811
|
+
const normalizedPrefix = `${normalizeGraphPathSegment(className)}_`;
|
|
12812
|
+
if (path.startsWith(normalizedPrefix)) {
|
|
12813
|
+
return path.slice(normalizedPrefix.length);
|
|
12814
|
+
}
|
|
12815
|
+
const legacyPrefix = `${className}_`;
|
|
12816
|
+
if (path.startsWith(legacyPrefix)) {
|
|
12817
|
+
return path.slice(legacyPrefix.length);
|
|
12818
|
+
}
|
|
12819
|
+
return path;
|
|
12820
|
+
}
|
|
12821
|
+
function toRecordSearchResult(className, node) {
|
|
12822
|
+
const path = typeof node.path === "string" ? node.path : "";
|
|
12823
|
+
if (!path) return null;
|
|
12824
|
+
const fields = Array.isArray(node.submodels) ? node.submodels.flatMap(
|
|
12825
|
+
(submodel) => {
|
|
12826
|
+
const name = typeof submodel?.label === "string" && submodel.label.trim() ? submodel.label : typeof submodel?.path === "string" ? submodel.path.split(":").pop() || submodel.path : "";
|
|
12827
|
+
if (!name) return [];
|
|
12828
|
+
if (typeof submodel.string_value === "string") {
|
|
12829
|
+
return [{ name, type: "string", value: submodel.string_value }];
|
|
12830
|
+
}
|
|
12831
|
+
if (typeof submodel.number_value === "number") {
|
|
12832
|
+
return [{ name, type: "number", value: submodel.number_value }];
|
|
12833
|
+
}
|
|
12834
|
+
if (typeof submodel.boolean_value === "boolean") {
|
|
12835
|
+
return [
|
|
12836
|
+
{
|
|
12837
|
+
name,
|
|
12838
|
+
type: "boolean",
|
|
12839
|
+
value: submodel.boolean_value
|
|
12840
|
+
}
|
|
12841
|
+
];
|
|
12842
|
+
}
|
|
12843
|
+
return [];
|
|
12844
|
+
}
|
|
12845
|
+
) : [];
|
|
12846
|
+
return {
|
|
12847
|
+
path,
|
|
12848
|
+
className,
|
|
12849
|
+
id: extractRecordIdFromGraphPath(path, className),
|
|
12850
|
+
label: typeof node.label === "string" && node.label.trim() ? node.label : extractRecordIdFromGraphPath(path, className),
|
|
12851
|
+
description: typeof node.description === "string" && node.description.trim() ? node.description : null,
|
|
12852
|
+
fields
|
|
12853
|
+
};
|
|
12854
|
+
}
|
|
12855
|
+
function normalizeRecordSearchText(value) {
|
|
12856
|
+
return value.trim().toLowerCase().replace(/[^a-z0-9]+/g, " ").replace(/\s+/g, " ").trim();
|
|
12857
|
+
}
|
|
12858
|
+
function rankRecordSearchResult(result, query, index) {
|
|
12859
|
+
const normalizedQuery = normalizeRecordSearchText(query);
|
|
12860
|
+
if (!normalizedQuery) {
|
|
12861
|
+
return index;
|
|
12862
|
+
}
|
|
12863
|
+
const label = normalizeRecordSearchText(result.label || "");
|
|
12864
|
+
const id = normalizeRecordSearchText(result.id || "");
|
|
12865
|
+
const path = normalizeRecordSearchText(result.path || "");
|
|
12866
|
+
const className = normalizeRecordSearchText(result.className || "");
|
|
12867
|
+
const searchable = [label, id, path, className].filter(Boolean);
|
|
12868
|
+
if (label === normalizedQuery) return index;
|
|
12869
|
+
if (id === normalizedQuery || path === normalizedQuery) return 100 + index;
|
|
12870
|
+
if (label.startsWith(normalizedQuery)) return 200 + index;
|
|
12871
|
+
if (searchable.some((value) => value.startsWith(normalizedQuery))) {
|
|
12872
|
+
return 300 + index;
|
|
12873
|
+
}
|
|
12874
|
+
if (label.includes(normalizedQuery)) return 400 + index;
|
|
12875
|
+
if (searchable.some((value) => value.includes(normalizedQuery))) {
|
|
12876
|
+
return 500 + index;
|
|
12877
|
+
}
|
|
12878
|
+
return 900 + index;
|
|
12879
|
+
}
|
|
12336
12880
|
function deriveRuntimeBaseUrl(apiEndpoint) {
|
|
12337
12881
|
try {
|
|
12338
12882
|
const endpoint = new URL(apiEndpoint);
|
|
@@ -12421,7 +12965,7 @@ function normalizeEnvironmentData(environment) {
|
|
|
12421
12965
|
setup: normalizeEnvironmentSetupSummary(environment.setup)
|
|
12422
12966
|
};
|
|
12423
12967
|
}
|
|
12424
|
-
var Environment = class {
|
|
12968
|
+
var Environment = class _Environment {
|
|
12425
12969
|
granular;
|
|
12426
12970
|
envData;
|
|
12427
12971
|
_apiKey;
|
|
@@ -12616,28 +13160,30 @@ var Environment = class {
|
|
|
12616
13160
|
return response.json();
|
|
12617
13161
|
}
|
|
12618
13162
|
// ==================== ID ↔ GRAPH PATH MAPPING ====================
|
|
13163
|
+
static normalizeGraphPathSegment(value) {
|
|
13164
|
+
return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").replace(/_+/g, "_").replace(/^_+|_+$/g, "").toLowerCase();
|
|
13165
|
+
}
|
|
12619
13166
|
/**
|
|
12620
|
-
* Convert a class name +
|
|
12621
|
-
*
|
|
12622
|
-
* Two objects of *different* classes may share the same real-world ID,
|
|
12623
|
-
* so the graph path must incorporate the class to guarantee uniqueness.
|
|
12624
|
-
*
|
|
12625
|
-
* Format: `{className}_{id}` — deterministic, human-readable.
|
|
13167
|
+
* Convert a class name + application record ID into Granular's graph path.
|
|
12626
13168
|
*
|
|
12627
|
-
*
|
|
12628
|
-
*
|
|
12629
|
-
*
|
|
13169
|
+
* This mirrors the record-write path normalization used by the control plane.
|
|
13170
|
+
* Keep the original customer/system ID in `real_id`; graph paths are stable
|
|
13171
|
+
* internal addresses, not the source of truth for business identity.
|
|
12630
13172
|
*/
|
|
12631
13173
|
static toGraphPath(className, id) {
|
|
12632
|
-
return `${className}_${id}`;
|
|
13174
|
+
return `${_Environment.normalizeGraphPathSegment(className)}_${_Environment.normalizeGraphPathSegment(id)}`;
|
|
12633
13175
|
}
|
|
12634
13176
|
/**
|
|
12635
|
-
*
|
|
13177
|
+
* Best-effort extraction of an ID-like suffix from a graph path.
|
|
12636
13178
|
*
|
|
12637
|
-
*
|
|
12638
|
-
*
|
|
13179
|
+
* Prefer the record's `real_id` field whenever exact customer/system IDs
|
|
13180
|
+
* matter, because graph path normalization is intentionally lossy.
|
|
12639
13181
|
*/
|
|
12640
13182
|
static extractIdFromGraphPath(graphPath, className) {
|
|
13183
|
+
const normalizedPrefix = `${_Environment.normalizeGraphPathSegment(className)}_`;
|
|
13184
|
+
if (graphPath.startsWith(normalizedPrefix)) {
|
|
13185
|
+
return graphPath.substring(normalizedPrefix.length);
|
|
13186
|
+
}
|
|
12641
13187
|
const prefix = `${className}_`;
|
|
12642
13188
|
return graphPath.startsWith(prefix) ? graphPath.substring(prefix.length) : graphPath;
|
|
12643
13189
|
}
|
|
@@ -12684,6 +13230,62 @@ var Environment = class {
|
|
|
12684
13230
|
}
|
|
12685
13231
|
return response.json();
|
|
12686
13232
|
}
|
|
13233
|
+
async searchRecords(query, options = {}) {
|
|
13234
|
+
const normalizedQuery = query.replace(/\s+/g, " ").trim();
|
|
13235
|
+
const limit = Math.max(1, Math.min(50, Math.floor(options.limit ?? 12)));
|
|
13236
|
+
const offset = Math.max(0, Math.floor(options.offset ?? 0));
|
|
13237
|
+
const response = await this.graphql(
|
|
13238
|
+
`
|
|
13239
|
+
query RecordMentionSearch(
|
|
13240
|
+
$query: String
|
|
13241
|
+
$limit: Int
|
|
13242
|
+
$offset: Int
|
|
13243
|
+
$classNames: [String!]
|
|
13244
|
+
) {
|
|
13245
|
+
record_search(
|
|
13246
|
+
query: $query
|
|
13247
|
+
limit: $limit
|
|
13248
|
+
offset: $offset
|
|
13249
|
+
class_names: $classNames
|
|
13250
|
+
) {
|
|
13251
|
+
className
|
|
13252
|
+
model {
|
|
13253
|
+
path
|
|
13254
|
+
label
|
|
13255
|
+
description
|
|
13256
|
+
submodels {
|
|
13257
|
+
path
|
|
13258
|
+
label
|
|
13259
|
+
string_value
|
|
13260
|
+
number_value
|
|
13261
|
+
boolean_value
|
|
13262
|
+
}
|
|
13263
|
+
}
|
|
13264
|
+
}
|
|
13265
|
+
}
|
|
13266
|
+
`,
|
|
13267
|
+
{
|
|
13268
|
+
query: normalizedQuery,
|
|
13269
|
+
limit,
|
|
13270
|
+
offset,
|
|
13271
|
+
classNames: options.classNames?.length ? options.classNames : []
|
|
13272
|
+
}
|
|
13273
|
+
);
|
|
13274
|
+
const seen = /* @__PURE__ */ new Set();
|
|
13275
|
+
const results = (response.data?.record_search || []).flatMap((entry) => {
|
|
13276
|
+
const className = entry.className?.trim();
|
|
13277
|
+
const item = className && entry.model ? toRecordSearchResult(className, entry.model) : null;
|
|
13278
|
+
if (!item || seen.has(item.path)) {
|
|
13279
|
+
return [];
|
|
13280
|
+
}
|
|
13281
|
+
seen.add(item.path);
|
|
13282
|
+
return [item];
|
|
13283
|
+
});
|
|
13284
|
+
return results.map((result, index) => ({
|
|
13285
|
+
result,
|
|
13286
|
+
rank: rankRecordSearchResult(result, normalizedQuery, index)
|
|
13287
|
+
})).sort((left, right) => left.rank - right.rank).map((item) => item.result).slice(0, limit);
|
|
13288
|
+
}
|
|
12687
13289
|
// ==================== RELATIONSHIP METHODS ====================
|
|
12688
13290
|
/**
|
|
12689
13291
|
* Define a relationship between two model types.
|
|
@@ -13449,7 +14051,8 @@ var Environment = class {
|
|
|
13449
14051
|
body: JSON.stringify({
|
|
13450
14052
|
records,
|
|
13451
14053
|
batchSize: options.batchSize,
|
|
13452
|
-
setupRunId: options.setupRunId
|
|
14054
|
+
setupRunId: options.setupRunId,
|
|
14055
|
+
writeMode: options.writeMode
|
|
13453
14056
|
})
|
|
13454
14057
|
}
|
|
13455
14058
|
);
|
|
@@ -13501,11 +14104,13 @@ var Environment = class {
|
|
|
13501
14104
|
};
|
|
13502
14105
|
var EnvironmentSession = class extends Session {
|
|
13503
14106
|
environment;
|
|
14107
|
+
sessionDataRoutePrefix;
|
|
13504
14108
|
/** The last known graph container status, updated by checkReadiness() or on heartbeat */
|
|
13505
14109
|
graphContainerStatus = null;
|
|
13506
|
-
constructor(client, environment, clientId) {
|
|
14110
|
+
constructor(client, environment, clientId, options = {}) {
|
|
13507
14111
|
super(client, clientId);
|
|
13508
14112
|
this.environment = environment;
|
|
14113
|
+
this.sessionDataRoutePrefix = options.sessionDataRoutePrefix || "/orchestrator/ws/sessions";
|
|
13509
14114
|
}
|
|
13510
14115
|
get environmentId() {
|
|
13511
14116
|
return this.environment.environmentId;
|
|
@@ -13550,7 +14155,7 @@ var EnvironmentSession = class extends Session {
|
|
|
13550
14155
|
const doc = this.document;
|
|
13551
14156
|
return normalizeHeapSnapshot(doc?.heap);
|
|
13552
14157
|
}
|
|
13553
|
-
async sessionDataRequest(path, query) {
|
|
14158
|
+
async sessionDataRequest(path, query, init2 = {}) {
|
|
13554
14159
|
const searchParams = new URLSearchParams();
|
|
13555
14160
|
for (const [key, value] of Object.entries(query || {})) {
|
|
13556
14161
|
if (value !== null && typeof value !== "undefined" && value !== "") {
|
|
@@ -13558,23 +14163,39 @@ var EnvironmentSession = class extends Session {
|
|
|
13558
14163
|
}
|
|
13559
14164
|
}
|
|
13560
14165
|
const queryString = searchParams.toString();
|
|
13561
|
-
const
|
|
13562
|
-
|
|
13563
|
-
|
|
13564
|
-
|
|
13565
|
-
|
|
13566
|
-
|
|
13567
|
-
|
|
14166
|
+
const url = `${this.environment.runtimeBaseUrl}${this.sessionDataRoutePrefix}/${encodeURIComponent(this.sessionId)}${path}${queryString ? `?${queryString}` : ""}`;
|
|
14167
|
+
const body = typeof init2.body === "undefined" ? void 0 : JSON.stringify(init2.body);
|
|
14168
|
+
for (let attempt = 1; attempt <= SESSION_DATA_REQUEST_RETRY_COUNT; attempt += 1) {
|
|
14169
|
+
try {
|
|
14170
|
+
const response = await fetch(url, {
|
|
14171
|
+
method: init2.method || "GET",
|
|
14172
|
+
headers: {
|
|
14173
|
+
Authorization: `Bearer ${this.environment.authToken}`,
|
|
14174
|
+
"Content-Type": "application/json"
|
|
14175
|
+
},
|
|
14176
|
+
...typeof body === "undefined" ? {} : { body }
|
|
14177
|
+
});
|
|
14178
|
+
if (response.ok) {
|
|
14179
|
+
return response.json();
|
|
14180
|
+
}
|
|
14181
|
+
const errorText = await response.text();
|
|
14182
|
+
const error = new Error(
|
|
14183
|
+
`Session data API Error (${response.status}): ${errorText}`
|
|
14184
|
+
);
|
|
14185
|
+
if (isLocalControlUrl(url) && isRetryableSessionDataError(error) && attempt < SESSION_DATA_REQUEST_RETRY_COUNT) {
|
|
14186
|
+
await sleep(SESSION_DATA_REQUEST_RETRY_DELAY_MS * attempt);
|
|
14187
|
+
continue;
|
|
14188
|
+
}
|
|
14189
|
+
throw error;
|
|
14190
|
+
} catch (error) {
|
|
14191
|
+
if (isLocalControlUrl(url) && isRetryableSessionDataError(error) && attempt < SESSION_DATA_REQUEST_RETRY_COUNT) {
|
|
14192
|
+
await sleep(SESSION_DATA_REQUEST_RETRY_DELAY_MS * attempt);
|
|
14193
|
+
continue;
|
|
13568
14194
|
}
|
|
14195
|
+
throw error;
|
|
13569
14196
|
}
|
|
13570
|
-
);
|
|
13571
|
-
if (!response.ok) {
|
|
13572
|
-
const errorText = await response.text();
|
|
13573
|
-
throw new Error(
|
|
13574
|
-
`Session data API Error (${response.status}): ${errorText}`
|
|
13575
|
-
);
|
|
13576
14197
|
}
|
|
13577
|
-
|
|
14198
|
+
throw new Error(`Session data API Error: exhausted retries for ${url}`);
|
|
13578
14199
|
}
|
|
13579
14200
|
async collectAllSessionItems(listPage) {
|
|
13580
14201
|
const items = [];
|
|
@@ -13632,6 +14253,17 @@ var EnvironmentSession = class extends Session {
|
|
|
13632
14253
|
get: (name) => this.sessionDataRequest(
|
|
13633
14254
|
`/heap/lists/${encodeURIComponent(name)}`
|
|
13634
14255
|
)
|
|
14256
|
+
},
|
|
14257
|
+
variables: {
|
|
14258
|
+
list: (options = {}) => this.sessionDataRequest("/heap/variables", options),
|
|
14259
|
+
get: (name) => this.sessionDataRequest(
|
|
14260
|
+
`/heap/variables/${encodeURIComponent(name)}`
|
|
14261
|
+
),
|
|
14262
|
+
delete: (name) => this.sessionDataRequest(
|
|
14263
|
+
`/heap/variables/${encodeURIComponent(name)}`,
|
|
14264
|
+
void 0,
|
|
14265
|
+
{ method: "DELETE" }
|
|
14266
|
+
)
|
|
13635
14267
|
}
|
|
13636
14268
|
};
|
|
13637
14269
|
}
|
|
@@ -13700,6 +14332,19 @@ var EnvironmentSession = class extends Session {
|
|
|
13700
14332
|
async graphql(query, variables) {
|
|
13701
14333
|
return this.environment.graphql(query, variables);
|
|
13702
14334
|
}
|
|
14335
|
+
async searchRecords(query, options = {}) {
|
|
14336
|
+
return this.environment.searchRecords(query, options);
|
|
14337
|
+
}
|
|
14338
|
+
async mentionRecord(input) {
|
|
14339
|
+
return this.sessionDataRequest(
|
|
14340
|
+
"/records/mention",
|
|
14341
|
+
void 0,
|
|
14342
|
+
{
|
|
14343
|
+
method: "POST",
|
|
14344
|
+
body: input
|
|
14345
|
+
}
|
|
14346
|
+
);
|
|
14347
|
+
}
|
|
13703
14348
|
async defineRelationship(options) {
|
|
13704
14349
|
return this.environment.defineRelationship(options);
|
|
13705
14350
|
}
|
|
@@ -13847,6 +14492,7 @@ var Granular = class _Granular {
|
|
|
13847
14492
|
WebSocketCtor;
|
|
13848
14493
|
onUnexpectedClose;
|
|
13849
14494
|
onReconnectError;
|
|
14495
|
+
effectHostUrl;
|
|
13850
14496
|
debugHttp = process.env.GRANULAR_DEBUG_HTTP === "1";
|
|
13851
14497
|
/** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
|
|
13852
14498
|
sandboxEffects = /* @__PURE__ */ new Map();
|
|
@@ -13875,6 +14521,7 @@ var Granular = class _Granular {
|
|
|
13875
14521
|
this.WebSocketCtor = options.WebSocketCtor;
|
|
13876
14522
|
this.onUnexpectedClose = options.onUnexpectedClose;
|
|
13877
14523
|
this.onReconnectError = options.onReconnectError;
|
|
14524
|
+
this.effectHostUrl = options.effectHostUrl;
|
|
13878
14525
|
this.httpUrl = this.apiUrl.replace(/^wss:\/\//, "https://").replace(/^ws:\/\//, "http://").replace(/\/ws$/, "");
|
|
13879
14526
|
}
|
|
13880
14527
|
/**
|
|
@@ -14045,6 +14692,30 @@ var Granular = class _Granular {
|
|
|
14045
14692
|
permissions: options.permissions || options.user?.permissions || []
|
|
14046
14693
|
});
|
|
14047
14694
|
}
|
|
14695
|
+
/**
|
|
14696
|
+
* Run a registered environment importer against an environment that was
|
|
14697
|
+
* opened outside this SDK instance, for example by a delegated browser flow.
|
|
14698
|
+
*
|
|
14699
|
+
* This uses the same setup-run and queued record-import plumbing as
|
|
14700
|
+
* `openEnvironment()`: importer stages, expected object counts, and queued
|
|
14701
|
+
* import counters remain visible through `environment.setup` and
|
|
14702
|
+
* `getRecordImportSummary()`.
|
|
14703
|
+
*/
|
|
14704
|
+
async runEnvironmentImporterForEnvironment(environmentId, options = {}) {
|
|
14705
|
+
const environmentData = await this.environments.get(environmentId);
|
|
14706
|
+
const environment = this.bindEnvironmentHandle(environmentData);
|
|
14707
|
+
const requestedOntology = options.ontology || environmentData.ontologyId || environmentData.sandboxId;
|
|
14708
|
+
return this.runEnvironmentImporter(
|
|
14709
|
+
{
|
|
14710
|
+
environment: environmentData,
|
|
14711
|
+
requestedOntology,
|
|
14712
|
+
sandboxId: environmentData.sandboxId,
|
|
14713
|
+
subjectId: environmentData.subjectId,
|
|
14714
|
+
setupTriggerReason: options.reason || "new_environment"
|
|
14715
|
+
},
|
|
14716
|
+
environment
|
|
14717
|
+
);
|
|
14718
|
+
}
|
|
14048
14719
|
resolveRequestedTag(options, methodName) {
|
|
14049
14720
|
const tag = options.tag?.trim() || options.tagName?.trim() || options.environment?.trim();
|
|
14050
14721
|
if (!tag) {
|
|
@@ -14288,15 +14959,25 @@ var Granular = class _Granular {
|
|
|
14288
14959
|
return ontologyImporter;
|
|
14289
14960
|
}
|
|
14290
14961
|
async maybeRunEnvironmentImporter(resolved, environment) {
|
|
14291
|
-
|
|
14292
|
-
|
|
14962
|
+
const setupTriggerReason = resolved.setupTriggerReason;
|
|
14963
|
+
if (!setupTriggerReason) {
|
|
14964
|
+
return null;
|
|
14293
14965
|
}
|
|
14966
|
+
return this.runEnvironmentImporter(
|
|
14967
|
+
{
|
|
14968
|
+
...resolved,
|
|
14969
|
+
setupTriggerReason
|
|
14970
|
+
},
|
|
14971
|
+
environment
|
|
14972
|
+
);
|
|
14973
|
+
}
|
|
14974
|
+
async runEnvironmentImporter(resolved, environment) {
|
|
14294
14975
|
const importer = this.resolveEnvironmentImporter(
|
|
14295
14976
|
resolved.requestedOntology,
|
|
14296
14977
|
resolved.sandboxId
|
|
14297
14978
|
);
|
|
14298
14979
|
if (!importer) {
|
|
14299
|
-
return;
|
|
14980
|
+
return null;
|
|
14300
14981
|
}
|
|
14301
14982
|
const setupRun = await this.request(
|
|
14302
14983
|
`/control/environments/${environment.environmentId}/setup-runs`,
|
|
@@ -14336,16 +15017,24 @@ var Granular = class _Granular {
|
|
|
14336
15017
|
},
|
|
14337
15018
|
importRecords: async (records, options) => environment.enqueueRecordImport(records, {
|
|
14338
15019
|
batchSize: options?.batchSize,
|
|
15020
|
+
writeMode: options?.writeMode,
|
|
14339
15021
|
setupRunId
|
|
14340
15022
|
})
|
|
14341
15023
|
};
|
|
14342
15024
|
try {
|
|
14343
15025
|
await importer(importerContext);
|
|
14344
|
-
|
|
15026
|
+
const completedSetupRun = await this.request(
|
|
15027
|
+
`/control/environment-setup-runs/${setupRunId}`,
|
|
15028
|
+
{
|
|
15029
|
+
method: "PATCH",
|
|
15030
|
+
body: JSON.stringify({ markHookCompleted: true })
|
|
15031
|
+
}
|
|
15032
|
+
);
|
|
14345
15033
|
const refreshedEnvironment = await this.environments.get(
|
|
14346
15034
|
environment.environmentId
|
|
14347
15035
|
);
|
|
14348
15036
|
environment.syncEnvironmentData(refreshedEnvironment);
|
|
15037
|
+
return completedSetupRun;
|
|
14349
15038
|
} catch (error) {
|
|
14350
15039
|
await updateSetupRun({
|
|
14351
15040
|
status: "failed",
|
|
@@ -14393,27 +15082,45 @@ var Granular = class _Granular {
|
|
|
14393
15082
|
return effects;
|
|
14394
15083
|
}
|
|
14395
15084
|
serializeEffect(effect) {
|
|
14396
|
-
|
|
15085
|
+
const serialized = {
|
|
14397
15086
|
effectKey: computeEffectKey2(effect),
|
|
14398
15087
|
name: effect.name,
|
|
14399
15088
|
description: effect.description,
|
|
14400
15089
|
inputSchema: effect.inputSchema,
|
|
14401
|
-
outputSchema: effect.outputSchema,
|
|
14402
15090
|
stability: effect.stability || "stable",
|
|
14403
|
-
provenance: effect.provenance || { source: "custom" }
|
|
14404
|
-
tags: effect.tags,
|
|
14405
|
-
className: effect.className,
|
|
14406
|
-
static: effect.static,
|
|
14407
|
-
versionSelector: effect.versionSelector
|
|
15091
|
+
provenance: effect.provenance || { source: "custom" }
|
|
14408
15092
|
};
|
|
15093
|
+
if (effect.outputSchema !== void 0) {
|
|
15094
|
+
serialized.outputSchema = effect.outputSchema;
|
|
15095
|
+
}
|
|
15096
|
+
if (effect.tags !== void 0) {
|
|
15097
|
+
serialized.tags = effect.tags;
|
|
15098
|
+
}
|
|
15099
|
+
if (effect.className !== void 0) {
|
|
15100
|
+
serialized.className = effect.className;
|
|
15101
|
+
}
|
|
15102
|
+
if (effect.static !== void 0) {
|
|
15103
|
+
serialized.static = effect.static;
|
|
15104
|
+
}
|
|
15105
|
+
if (effect.versionSelector !== void 0) {
|
|
15106
|
+
serialized.versionSelector = effect.versionSelector;
|
|
15107
|
+
}
|
|
15108
|
+
if (effect.metamodels !== void 0) {
|
|
15109
|
+
serialized.metamodels = effect.metamodels;
|
|
15110
|
+
}
|
|
15111
|
+
return serialized;
|
|
14409
15112
|
}
|
|
14410
15113
|
async publishSandboxEffectCatalog(host) {
|
|
14411
15114
|
const effects = Array.from(
|
|
14412
15115
|
this.getSandboxEffectMap(host.sandboxId).values()
|
|
14413
15116
|
).map((effect) => this.serializeEffect(effect));
|
|
14414
|
-
const result = await
|
|
14415
|
-
effects
|
|
14416
|
-
|
|
15117
|
+
const result = await withTimeout(
|
|
15118
|
+
host.wsClient.call("effects.publishCatalog", {
|
|
15119
|
+
effects
|
|
15120
|
+
}),
|
|
15121
|
+
EFFECT_CATALOG_SYNC_TIMEOUT_MS,
|
|
15122
|
+
`effects.publishCatalog for sandbox ${host.sandboxId}`
|
|
15123
|
+
);
|
|
14417
15124
|
const acceptedCount = typeof result?.acceptedCount === "number" ? result.acceptedCount : 0;
|
|
14418
15125
|
const rejected = Array.isArray(result?.rejected) ? result.rejected : [];
|
|
14419
15126
|
if (acceptedCount === 0 && rejected.length > 0) {
|
|
@@ -14432,8 +15139,26 @@ var Granular = class _Granular {
|
|
|
14432
15139
|
}
|
|
14433
15140
|
}
|
|
14434
15141
|
async syncSandboxEffectCatalog(sandboxId) {
|
|
14435
|
-
|
|
14436
|
-
|
|
15142
|
+
let lastError;
|
|
15143
|
+
for (let attempt = 1; attempt <= EFFECT_CATALOG_SYNC_RETRY_COUNT; attempt += 1) {
|
|
15144
|
+
try {
|
|
15145
|
+
const host = await this.ensureSandboxEffectHost(sandboxId);
|
|
15146
|
+
await this.publishSandboxEffectCatalog(host);
|
|
15147
|
+
return;
|
|
15148
|
+
} catch (error) {
|
|
15149
|
+
lastError = error;
|
|
15150
|
+
this.disconnectSandboxEffectHost(sandboxId);
|
|
15151
|
+
if (attempt === EFFECT_CATALOG_SYNC_RETRY_COUNT || !isRetryableEffectRegistrationError(error)) {
|
|
15152
|
+
throw error;
|
|
15153
|
+
}
|
|
15154
|
+
console.warn(
|
|
15155
|
+
`[Granular] Retrying effect registration for sandbox ${sandboxId} after transient failure (${attempt}/${EFFECT_CATALOG_SYNC_RETRY_COUNT - 1} retries used):`,
|
|
15156
|
+
error
|
|
15157
|
+
);
|
|
15158
|
+
await sleep(EFFECT_CATALOG_SYNC_RETRY_DELAY_MS * attempt);
|
|
15159
|
+
}
|
|
15160
|
+
}
|
|
15161
|
+
throw lastError instanceof Error ? lastError : new Error(String(lastError));
|
|
14437
15162
|
}
|
|
14438
15163
|
recoverEffectHost(host, error) {
|
|
14439
15164
|
if (host.recovering) {
|
|
@@ -14526,7 +15251,8 @@ var Granular = class _Granular {
|
|
|
14526
15251
|
this.apiUrl,
|
|
14527
15252
|
sandboxId,
|
|
14528
15253
|
effectClientId,
|
|
14529
|
-
clientId
|
|
15254
|
+
clientId,
|
|
15255
|
+
this.effectHostUrl
|
|
14530
15256
|
),
|
|
14531
15257
|
sessionId: `effect-host:${effectClientId}`,
|
|
14532
15258
|
token: this.apiKey,
|
|
@@ -14562,7 +15288,11 @@ var Granular = class _Granular {
|
|
|
14562
15288
|
wsClient.on("disconnect", () => {
|
|
14563
15289
|
this.stopEffectHostHeartbeat(host);
|
|
14564
15290
|
});
|
|
14565
|
-
await
|
|
15291
|
+
await withTimeout(
|
|
15292
|
+
wsClient.connect(),
|
|
15293
|
+
EFFECT_HOST_CONNECT_TIMEOUT_MS,
|
|
15294
|
+
`effect host WebSocket connect for sandbox ${sandboxId}`
|
|
15295
|
+
);
|
|
14566
15296
|
await this.synchronizeEffectHost(host);
|
|
14567
15297
|
this.sandboxEffectHosts.set(sandboxId, host);
|
|
14568
15298
|
return host;
|
|
@@ -14685,7 +15415,7 @@ var Granular = class _Granular {
|
|
|
14685
15415
|
/**
|
|
14686
15416
|
* Ensure a permission profile exists for a sandbox, creating it if needed.
|
|
14687
15417
|
* If profileName matches an existing profile name, returns its ID.
|
|
14688
|
-
* Otherwise, creates a
|
|
15418
|
+
* Otherwise, creates a v1 source-profile file shape with an allow default.
|
|
14689
15419
|
*/
|
|
14690
15420
|
async ensurePermissionProfile(sandboxId, profileName) {
|
|
14691
15421
|
try {
|
|
@@ -14699,8 +15429,11 @@ var Granular = class _Granular {
|
|
|
14699
15429
|
const created = await this.permissionProfiles.create(sandboxId, {
|
|
14700
15430
|
name: profileName,
|
|
14701
15431
|
rules: {
|
|
14702
|
-
|
|
14703
|
-
|
|
15432
|
+
schemaVersion: 1,
|
|
15433
|
+
name: profileName,
|
|
15434
|
+
description: profileName === "allow-all" ? "Every declared action is visible unless a manifest policy denies it." : `Generated permission profile ${profileName}`,
|
|
15435
|
+
defaults: { actionPolicy: "allow" },
|
|
15436
|
+
actions: []
|
|
14704
15437
|
}
|
|
14705
15438
|
});
|
|
14706
15439
|
return created.permissionProfileId;
|
|
@@ -14773,33 +15506,63 @@ var Granular = class _Granular {
|
|
|
14773
15506
|
* Permission Profile management for sandboxes
|
|
14774
15507
|
*/
|
|
14775
15508
|
get permissionProfiles() {
|
|
15509
|
+
const profileSourceFromRecord = (record) => {
|
|
15510
|
+
const profile = record.profile || record.rules || {};
|
|
15511
|
+
return {
|
|
15512
|
+
...profile,
|
|
15513
|
+
schemaVersion: profile.schemaVersion || 1,
|
|
15514
|
+
name: profile.name || record.name,
|
|
15515
|
+
description: profile.description || record.description
|
|
15516
|
+
};
|
|
15517
|
+
};
|
|
14776
15518
|
return {
|
|
14777
15519
|
list: async (sandboxId) => {
|
|
14778
15520
|
const result = await this.request(
|
|
14779
|
-
`/control/sandboxes/${sandboxId}/permission-
|
|
15521
|
+
`/control/sandboxes/${sandboxId}/permission-profile-sources`
|
|
14780
15522
|
);
|
|
14781
15523
|
return result.items;
|
|
14782
15524
|
},
|
|
14783
15525
|
get: async (sandboxId, profileId) => {
|
|
14784
|
-
|
|
14785
|
-
`/control/sandboxes/${sandboxId}/permission-
|
|
15526
|
+
const result = await this.request(
|
|
15527
|
+
`/control/sandboxes/${sandboxId}/permission-profile-sources`
|
|
15528
|
+
);
|
|
15529
|
+
const profile = result.items.find(
|
|
15530
|
+
(item) => item.permissionProfileId === profileId || item.name === profileId
|
|
14786
15531
|
);
|
|
15532
|
+
if (!profile) {
|
|
15533
|
+
throw new Error(`Permission profile source not found: ${profileId}`);
|
|
15534
|
+
}
|
|
15535
|
+
return profile;
|
|
14787
15536
|
},
|
|
14788
15537
|
create: async (sandboxId, data) => {
|
|
14789
|
-
|
|
14790
|
-
|
|
15538
|
+
const profile = {
|
|
15539
|
+
...data.rules,
|
|
15540
|
+
schemaVersion: 1,
|
|
15541
|
+
name: data.name
|
|
15542
|
+
};
|
|
15543
|
+
const existingProfiles = await this.permissionProfiles.list(sandboxId);
|
|
15544
|
+
const profiles = [
|
|
15545
|
+
...existingProfiles.filter((existing) => existing.name !== data.name).map((existing) => profileSourceFromRecord(existing)),
|
|
15546
|
+
profile
|
|
15547
|
+
];
|
|
15548
|
+
const result = await this.request(
|
|
15549
|
+
`/control/sandboxes/${sandboxId}/permission-profile-sources`,
|
|
14791
15550
|
{
|
|
14792
|
-
method: "
|
|
14793
|
-
body: JSON.stringify(
|
|
15551
|
+
method: "PUT",
|
|
15552
|
+
body: JSON.stringify({ profiles })
|
|
14794
15553
|
}
|
|
14795
15554
|
);
|
|
15555
|
+
const synced = result.items.find((item) => item.name === data.name) || result.items[0];
|
|
15556
|
+
if (!synced) {
|
|
15557
|
+
throw new Error(
|
|
15558
|
+
`Permission profile source sync did not return ${data.name}`
|
|
15559
|
+
);
|
|
15560
|
+
}
|
|
15561
|
+
return synced;
|
|
14796
15562
|
},
|
|
14797
|
-
delete: async (
|
|
14798
|
-
|
|
14799
|
-
|
|
14800
|
-
{
|
|
14801
|
-
method: "DELETE"
|
|
14802
|
-
}
|
|
15563
|
+
delete: async (_sandboxId, _profileId) => {
|
|
15564
|
+
throw new Error(
|
|
15565
|
+
"Permission profile sources are updated by syncing the desired source set."
|
|
14803
15566
|
);
|
|
14804
15567
|
}
|
|
14805
15568
|
};
|
|
@@ -15055,6 +15818,85 @@ var Granular = class _Granular {
|
|
|
15055
15818
|
};
|
|
15056
15819
|
|
|
15057
15820
|
// src/agent-harness.ts
|
|
15821
|
+
var DEFAULT_IGNORED_REASONING_COMMENT_DIRECTIVES = [
|
|
15822
|
+
/^@ts-ignore\b/i,
|
|
15823
|
+
/^@ts-expect-error\b/i,
|
|
15824
|
+
/^eslint-[\w-]+\b/i,
|
|
15825
|
+
/^biome-ignore\b/i,
|
|
15826
|
+
/^prettier-ignore\b/i,
|
|
15827
|
+
/^istanbul ignore\b/i
|
|
15828
|
+
];
|
|
15829
|
+
var DEFAULT_LOW_SIGNAL_REASONING_LINES = [
|
|
15830
|
+
/^running\.?$/i,
|
|
15831
|
+
/^working\.?$/i,
|
|
15832
|
+
/^thinking\.?$/i,
|
|
15833
|
+
/^generating(?: code)?\.?$/i,
|
|
15834
|
+
/^starting(?: execution)?\.?$/i
|
|
15835
|
+
];
|
|
15836
|
+
function parseReasoningCommentLine(line, options = {}) {
|
|
15837
|
+
const trimmed = line.trimStart();
|
|
15838
|
+
if (!trimmed.startsWith("//")) return null;
|
|
15839
|
+
const text = trimmed.replace(/^\/\/\s?/, "").trim();
|
|
15840
|
+
if (!text) return { kind: "ignored" };
|
|
15841
|
+
const ignoredDirectives = options.ignoredCommentDirectives || DEFAULT_IGNORED_REASONING_COMMENT_DIRECTIVES;
|
|
15842
|
+
if (ignoredDirectives.some((pattern) => pattern.test(text))) {
|
|
15843
|
+
return { kind: "ignored" };
|
|
15844
|
+
}
|
|
15845
|
+
const lowSignalLines = options.lowSignalReasoningLines || DEFAULT_LOW_SIGNAL_REASONING_LINES;
|
|
15846
|
+
if (lowSignalLines.some((pattern) => pattern.test(text))) {
|
|
15847
|
+
return { kind: "ignored" };
|
|
15848
|
+
}
|
|
15849
|
+
return { kind: "reasoning", text };
|
|
15850
|
+
}
|
|
15851
|
+
function consumeGranularReasoningTraceChunk(buffer, chunk, options = {}) {
|
|
15852
|
+
let text = buffer + chunk;
|
|
15853
|
+
let visibleText = "";
|
|
15854
|
+
const reasoningLines = [];
|
|
15855
|
+
while (true) {
|
|
15856
|
+
const newlineIndex = text.indexOf("\n");
|
|
15857
|
+
if (newlineIndex === -1) break;
|
|
15858
|
+
const rawLine = text.slice(0, newlineIndex);
|
|
15859
|
+
text = text.slice(newlineIndex + 1);
|
|
15860
|
+
const comment = parseReasoningCommentLine(
|
|
15861
|
+
rawLine.replace(/\r$/, ""),
|
|
15862
|
+
options
|
|
15863
|
+
);
|
|
15864
|
+
if (comment?.kind === "reasoning") {
|
|
15865
|
+
reasoningLines.push(comment.text);
|
|
15866
|
+
} else if (comment?.kind === "ignored") {
|
|
15867
|
+
continue;
|
|
15868
|
+
} else {
|
|
15869
|
+
visibleText += `${rawLine}
|
|
15870
|
+
`;
|
|
15871
|
+
}
|
|
15872
|
+
}
|
|
15873
|
+
if (options.final && text.length > 0) {
|
|
15874
|
+
const comment = parseReasoningCommentLine(text.replace(/\r$/, ""), options);
|
|
15875
|
+
if (comment?.kind === "reasoning") {
|
|
15876
|
+
reasoningLines.push(comment.text);
|
|
15877
|
+
text = "";
|
|
15878
|
+
} else if (comment?.kind === "ignored") {
|
|
15879
|
+
text = "";
|
|
15880
|
+
} else {
|
|
15881
|
+
visibleText += text;
|
|
15882
|
+
text = "";
|
|
15883
|
+
}
|
|
15884
|
+
}
|
|
15885
|
+
return { buffer: text, visibleText, reasoningLines };
|
|
15886
|
+
}
|
|
15887
|
+
function consumeGranularReasoningOnlyChunk(buffer, chunk, options = {}) {
|
|
15888
|
+
const result = consumeGranularReasoningTraceChunk(buffer, chunk, options);
|
|
15889
|
+
return {
|
|
15890
|
+
buffer: result.buffer,
|
|
15891
|
+
reasoningLines: result.reasoningLines
|
|
15892
|
+
};
|
|
15893
|
+
}
|
|
15894
|
+
function stripGranularReasoningTrace(text, options = {}) {
|
|
15895
|
+
return consumeGranularReasoningTraceChunk("", text, {
|
|
15896
|
+
...options,
|
|
15897
|
+
final: true
|
|
15898
|
+
}).visibleText.trim();
|
|
15899
|
+
}
|
|
15058
15900
|
function asRecord4(value) {
|
|
15059
15901
|
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
15060
15902
|
return value;
|
|
@@ -15078,21 +15920,8 @@ function uniqueStrings(values, maxCount) {
|
|
|
15078
15920
|
}
|
|
15079
15921
|
return output;
|
|
15080
15922
|
}
|
|
15081
|
-
function
|
|
15082
|
-
|
|
15083
|
-
if (typeof value === "number" || typeof value === "boolean")
|
|
15084
|
-
return String(value);
|
|
15085
|
-
if (value === null) return "null";
|
|
15086
|
-
return "unknown";
|
|
15087
|
-
}
|
|
15088
|
-
function describeHeapEntry(entry, previewFieldLimit = 3) {
|
|
15089
|
-
const headline = entry.label || entry.id || entry.path || "Unknown";
|
|
15090
|
-
const pathLabel = entry.path && entry.path !== headline ? ` <${entry.path}>` : "";
|
|
15091
|
-
const classLabel = entry.className || "unknown";
|
|
15092
|
-
const preview = asArray2(entry.fields).filter(
|
|
15093
|
-
(field) => field?.name && field.name !== "_realId" && field.name !== "real_id"
|
|
15094
|
-
).slice(0, previewFieldLimit).map((field) => `${field.name}=${formatScalar(field.value)}`).join(", ");
|
|
15095
|
-
return preview ? `${headline}${pathLabel} [${classLabel}] ${preview}` : `${headline}${pathLabel} [${classLabel}]`;
|
|
15923
|
+
function renderConstBlock(name, value) {
|
|
15924
|
+
return `const ${name} = ${JSON.stringify(value, null, 2)} as const;`;
|
|
15096
15925
|
}
|
|
15097
15926
|
function hashString(value) {
|
|
15098
15927
|
if (!value) return null;
|
|
@@ -15103,97 +15932,248 @@ function hashString(value) {
|
|
|
15103
15932
|
}
|
|
15104
15933
|
return (hash >>> 0).toString(16).padStart(8, "0");
|
|
15105
15934
|
}
|
|
15106
|
-
function
|
|
15107
|
-
const
|
|
15108
|
-
|
|
15109
|
-
|
|
15110
|
-
|
|
15111
|
-
|
|
15935
|
+
function findUndefinedSimpleTemplateIdentifier(source) {
|
|
15936
|
+
const declared = /* @__PURE__ */ new Set();
|
|
15937
|
+
const globals = /* @__PURE__ */ new Set([
|
|
15938
|
+
"Array",
|
|
15939
|
+
"Boolean",
|
|
15940
|
+
"Date",
|
|
15941
|
+
"JSON",
|
|
15942
|
+
"Math",
|
|
15943
|
+
"Number",
|
|
15944
|
+
"Object",
|
|
15945
|
+
"Promise",
|
|
15946
|
+
"String",
|
|
15947
|
+
"undefined",
|
|
15948
|
+
"null",
|
|
15949
|
+
"true",
|
|
15950
|
+
"false"
|
|
15951
|
+
]);
|
|
15952
|
+
for (const match of source.matchAll(/import\s*\{([^}]+)\}\s*from/g)) {
|
|
15953
|
+
for (const part of match[1].split(",")) {
|
|
15954
|
+
const aliasMatch = part.trim().match(/\bas\s+([A-Za-z_$][\w$]*)$/);
|
|
15955
|
+
const nameMatch = part.trim().match(/^([A-Za-z_$][\w$]*)/);
|
|
15956
|
+
const name = aliasMatch?.[1] || nameMatch?.[1];
|
|
15957
|
+
if (name) declared.add(name);
|
|
15958
|
+
}
|
|
15959
|
+
}
|
|
15960
|
+
for (const match of source.matchAll(
|
|
15961
|
+
/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b/g
|
|
15962
|
+
)) {
|
|
15963
|
+
declared.add(match[1]);
|
|
15964
|
+
}
|
|
15965
|
+
for (const match of source.matchAll(
|
|
15966
|
+
/\bfor\s*(?:await\s*)?\(\s*(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s+of\b/g
|
|
15967
|
+
)) {
|
|
15968
|
+
declared.add(match[1]);
|
|
15969
|
+
}
|
|
15970
|
+
for (const match of source.matchAll(
|
|
15971
|
+
/\bcatch\s*\(\s*([A-Za-z_$][\w$]*)\s*\)/g
|
|
15972
|
+
)) {
|
|
15973
|
+
declared.add(match[1]);
|
|
15974
|
+
}
|
|
15975
|
+
for (const match of source.matchAll(
|
|
15976
|
+
/\(\s*([A-Za-z_$][\w$]*)\s*(?:,\s*[A-Za-z_$][\w$]*)*\s*\)\s*=>/g
|
|
15977
|
+
)) {
|
|
15978
|
+
declared.add(match[1]);
|
|
15979
|
+
}
|
|
15980
|
+
for (const match of source.matchAll(/\b([A-Za-z_$][\w$]*)\s*=>/g)) {
|
|
15981
|
+
declared.add(match[1]);
|
|
15982
|
+
}
|
|
15983
|
+
for (const match of source.matchAll(/\$\{\s*([A-Za-z_$][\w$]*)\s*\}/g)) {
|
|
15984
|
+
const identifier = match[1];
|
|
15985
|
+
if (!declared.has(identifier) && !globals.has(identifier)) {
|
|
15986
|
+
return identifier;
|
|
15987
|
+
}
|
|
15988
|
+
}
|
|
15989
|
+
return null;
|
|
15990
|
+
}
|
|
15991
|
+
function getGeneratedJobSyntaxError(source) {
|
|
15992
|
+
const withoutImports = source.replace(
|
|
15993
|
+
/^\s*import\s+[\s\S]*?\s+from\s+["'][^"']+["']\s*;?\s*$/gm,
|
|
15994
|
+
""
|
|
15112
15995
|
);
|
|
15113
|
-
|
|
15114
|
-
|
|
15115
|
-
|
|
15116
|
-
|
|
15117
|
-
|
|
15118
|
-
|
|
15996
|
+
try {
|
|
15997
|
+
new Function(`return (async () => {
|
|
15998
|
+
${withoutImports}
|
|
15999
|
+
});`);
|
|
16000
|
+
return null;
|
|
16001
|
+
} catch (error) {
|
|
16002
|
+
return error instanceof Error ? error.message : String(error);
|
|
16003
|
+
}
|
|
16004
|
+
}
|
|
16005
|
+
function hasNestedTemplateLiteralExpression(source) {
|
|
16006
|
+
let inString = null;
|
|
16007
|
+
let escaped = false;
|
|
16008
|
+
const templateStack = [];
|
|
16009
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
16010
|
+
const char = source[index];
|
|
16011
|
+
const next = source[index + 1] || "";
|
|
16012
|
+
if (escaped) {
|
|
16013
|
+
escaped = false;
|
|
16014
|
+
continue;
|
|
16015
|
+
}
|
|
16016
|
+
if (char === "\\") {
|
|
16017
|
+
escaped = true;
|
|
16018
|
+
continue;
|
|
16019
|
+
}
|
|
16020
|
+
if (inString === "'" || inString === '"') {
|
|
16021
|
+
if (char === inString) inString = null;
|
|
16022
|
+
continue;
|
|
16023
|
+
}
|
|
16024
|
+
if (inString === "`") {
|
|
16025
|
+
const current = templateStack[templateStack.length - 1];
|
|
16026
|
+
if (char === "`") {
|
|
16027
|
+
if (current?.expressionDepth && current.expressionDepth > 0) {
|
|
16028
|
+
return true;
|
|
16029
|
+
}
|
|
16030
|
+
templateStack.pop();
|
|
16031
|
+
if (templateStack.length === 0) inString = null;
|
|
16032
|
+
continue;
|
|
16033
|
+
}
|
|
16034
|
+
if (char === "$" && next === "{") {
|
|
16035
|
+
if (current) current.expressionDepth += 1;
|
|
16036
|
+
index += 1;
|
|
16037
|
+
continue;
|
|
16038
|
+
}
|
|
16039
|
+
if (char === "}" && current?.expressionDepth) {
|
|
16040
|
+
current.expressionDepth -= 1;
|
|
16041
|
+
}
|
|
16042
|
+
continue;
|
|
16043
|
+
}
|
|
16044
|
+
if (char === "'" || char === '"') {
|
|
16045
|
+
inString = char;
|
|
16046
|
+
continue;
|
|
16047
|
+
}
|
|
16048
|
+
if (char === "`") {
|
|
16049
|
+
inString = "`";
|
|
16050
|
+
templateStack.push({ expressionDepth: 0 });
|
|
16051
|
+
}
|
|
15119
16052
|
}
|
|
15120
16053
|
return false;
|
|
15121
16054
|
}
|
|
15122
|
-
function reviewGeneratedJobCode(code) {
|
|
16055
|
+
function reviewGeneratedJobCode(code, _options = {}) {
|
|
15123
16056
|
const normalized = typeof code === "string" ? code : "";
|
|
15124
|
-
if (!normalized.trim()) return [];
|
|
15125
16057
|
const issues = [];
|
|
16058
|
+
if (!normalized.trim()) {
|
|
16059
|
+
return issues;
|
|
16060
|
+
}
|
|
15126
16061
|
if (/require\s*\(\s*['"]\.\/sandbox-tools['"]\s*\)/.test(normalized)) {
|
|
15127
16062
|
issues.push({
|
|
15128
16063
|
code: "commonjs_require",
|
|
15129
16064
|
severity: "error",
|
|
15130
|
-
message: "Use ESM imports
|
|
15131
|
-
});
|
|
15132
|
-
}
|
|
15133
|
-
const placeholderPatterns = [
|
|
15134
|
-
/ready to make the change next/i,
|
|
15135
|
-
/ready to .* next/i,
|
|
15136
|
-
/ready to .* now/i,
|
|
15137
|
-
/i can make the change now/i,
|
|
15138
|
-
/i can do that next/i,
|
|
15139
|
-
/i'?m ready to continue/i,
|
|
15140
|
-
/have your approval .* ready to make/i,
|
|
15141
|
-
/approved\./i
|
|
15142
|
-
];
|
|
15143
|
-
if (normalized.includes("await loop.confirm(")) {
|
|
15144
|
-
const postConfirm = normalized.slice(
|
|
15145
|
-
normalized.indexOf("await loop.confirm(")
|
|
15146
|
-
);
|
|
15147
|
-
const hasPlaceholder = placeholderPatterns.some(
|
|
15148
|
-
(pattern) => pattern.test(postConfirm)
|
|
15149
|
-
);
|
|
15150
|
-
const hasSubstantiveAwait = hasSubstantiveAwaitAfterPrompt(
|
|
15151
|
-
normalized,
|
|
15152
|
-
"await loop.confirm("
|
|
15153
|
-
);
|
|
15154
|
-
if (!hasSubstantiveAwait || hasPlaceholder) {
|
|
15155
|
-
issues.push({
|
|
15156
|
-
code: "placeholder_after_confirm",
|
|
15157
|
-
severity: "error",
|
|
15158
|
-
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.'"
|
|
15159
|
-
});
|
|
15160
|
-
}
|
|
16065
|
+
message: "Use ESM imports from './sandbox-tools' instead of require('./sandbox-tools')."
|
|
16066
|
+
});
|
|
15161
16067
|
}
|
|
15162
|
-
if (
|
|
15163
|
-
|
|
15164
|
-
|
|
15165
|
-
|
|
15166
|
-
|
|
15167
|
-
|
|
15168
|
-
|
|
15169
|
-
|
|
15170
|
-
|
|
15171
|
-
|
|
15172
|
-
|
|
15173
|
-
|
|
15174
|
-
|
|
15175
|
-
|
|
15176
|
-
|
|
15177
|
-
|
|
15178
|
-
|
|
15179
|
-
|
|
16068
|
+
if (/\bprocess\.exit\s*\(/.test(normalized)) {
|
|
16069
|
+
issues.push({
|
|
16070
|
+
code: "process_exit",
|
|
16071
|
+
severity: "error",
|
|
16072
|
+
message: "Generated jobs must not call process.exit(...). Return from the job or emit a runtime message instead."
|
|
16073
|
+
});
|
|
16074
|
+
}
|
|
16075
|
+
if (/\bawait\s+import\s*\(\s*['"]\.\/sandbox-tools['"]\s*\)/.test(normalized)) {
|
|
16076
|
+
issues.push({
|
|
16077
|
+
code: "dynamic_import_in_job",
|
|
16078
|
+
severity: "error",
|
|
16079
|
+
message: "Import sandbox tools with a static top-level import from './sandbox-tools'; do not use dynamic import for runtime tools."
|
|
16080
|
+
});
|
|
16081
|
+
}
|
|
16082
|
+
if (hasNestedTemplateLiteralExpression(normalized)) {
|
|
16083
|
+
issues.push({
|
|
16084
|
+
code: "nested_template_literal_in_job",
|
|
16085
|
+
severity: "error",
|
|
16086
|
+
message: "Avoid nested template literals inside template expressions. Precompute conditional text in variables or use simpler string construction."
|
|
16087
|
+
});
|
|
16088
|
+
}
|
|
16089
|
+
const syntaxError = getGeneratedJobSyntaxError(normalized);
|
|
16090
|
+
if (syntaxError) {
|
|
16091
|
+
issues.push({
|
|
16092
|
+
code: "syntax_error_in_job",
|
|
16093
|
+
severity: "error",
|
|
16094
|
+
message: `The generated job has a JavaScript syntax error before runtime execution: ${syntaxError}.`
|
|
16095
|
+
});
|
|
16096
|
+
}
|
|
16097
|
+
if (/[\u2018-\u201F]/.test(normalized)) {
|
|
16098
|
+
issues.push({
|
|
16099
|
+
code: "syntax_error_in_job",
|
|
16100
|
+
severity: "error",
|
|
16101
|
+
message: "Use plain ASCII quotes and apostrophes in generated job strings."
|
|
16102
|
+
});
|
|
16103
|
+
}
|
|
16104
|
+
const undefinedTemplateIdentifier = findUndefinedSimpleTemplateIdentifier(normalized);
|
|
16105
|
+
if (undefinedTemplateIdentifier) {
|
|
16106
|
+
issues.push({
|
|
16107
|
+
code: "undefined_template_identifier",
|
|
16108
|
+
severity: "error",
|
|
16109
|
+
message: `The template literal references \`${undefinedTemplateIdentifier}\`, but that identifier is not declared in the generated job.`
|
|
16110
|
+
});
|
|
16111
|
+
}
|
|
16112
|
+
if (/\{\s*\.\.\.[A-Za-z_$][\w$]*/.test(normalized)) {
|
|
16113
|
+
issues.push({
|
|
16114
|
+
code: "object_spread_in_job",
|
|
16115
|
+
severity: "error",
|
|
16116
|
+
message: "Avoid object spread in generated jobs until the backend runtime transform can validate it structurally."
|
|
16117
|
+
});
|
|
16118
|
+
}
|
|
16119
|
+
if (/\bloop\./.test(normalized) && !/import\s*\{[^}]*\bloop\b[^}]*\}\s*from\s*['"]\.\/sandbox-tools['"]/.test(
|
|
16120
|
+
normalized
|
|
16121
|
+
)) {
|
|
16122
|
+
issues.push({
|
|
16123
|
+
code: "missing_loop_import",
|
|
16124
|
+
severity: "error",
|
|
16125
|
+
message: "The job calls loop.* but does not import loop from './sandbox-tools'."
|
|
16126
|
+
});
|
|
16127
|
+
}
|
|
16128
|
+
const bareLoopHelperImport = normalized.match(
|
|
16129
|
+
/import\s*\{[^}]*\b(ask_user|confirm|open_decision|close_decision|create_task|update_task|complete_task|close_loop)\b[^}]*\}\s*from\s*['"]\.\/sandbox-tools['"]/
|
|
16130
|
+
);
|
|
16131
|
+
if (bareLoopHelperImport) {
|
|
16132
|
+
issues.push({
|
|
16133
|
+
code: "bare_loop_helper_import",
|
|
16134
|
+
severity: "error",
|
|
16135
|
+
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."
|
|
16136
|
+
});
|
|
16137
|
+
}
|
|
16138
|
+
if (/\bloop\.open_decision\s*\(\s*\{[\s\S]*?\boptions\s*:/.test(normalized)) {
|
|
16139
|
+
issues.push({
|
|
16140
|
+
code: "loop_helper_contract",
|
|
16141
|
+
severity: "error",
|
|
16142
|
+
message: "loop.open_decision(...) must use `candidates: [...]`, not `options: [...]`. Every candidate must include a string `id`."
|
|
16143
|
+
});
|
|
15180
16144
|
}
|
|
15181
|
-
|
|
15182
|
-
const returnsObjectLiteral = /return\s+\{[\s\S]*?\}/.test(normalized);
|
|
15183
|
-
const returnsShowPayload = /return\s+\{[\s\S]*?\bshow\s*:/.test(normalized);
|
|
15184
|
-
const closesLoop = /loop\.close_loop\s*\(/.test(normalized);
|
|
15185
|
-
if (!hasConversationalReturn && returnsObjectLiteral && !closesLoop) {
|
|
16145
|
+
if (/\bloop\.close_decision\s*\(\s*\{[\s\S]*?\bselected\s*:/.test(normalized)) {
|
|
15186
16146
|
issues.push({
|
|
15187
|
-
code: "
|
|
16147
|
+
code: "loop_helper_contract",
|
|
15188
16148
|
severity: "error",
|
|
15189
|
-
message: "
|
|
16149
|
+
message: "loop.close_decision(...) must use `selectedId`, not `selected`."
|
|
15190
16150
|
});
|
|
15191
16151
|
}
|
|
15192
|
-
if (
|
|
16152
|
+
if (/\bloop\.(?:create_task|update_task|complete_task)\s*\(\s*\{[\s\S]*?\bid\s*:/.test(
|
|
16153
|
+
normalized
|
|
16154
|
+
)) {
|
|
15193
16155
|
issues.push({
|
|
15194
|
-
code: "
|
|
16156
|
+
code: "loop_helper_contract",
|
|
15195
16157
|
severity: "error",
|
|
15196
|
-
message: "
|
|
16158
|
+
message: "Loop task helpers must use `taskId`, not `id`, for explicit task identifiers."
|
|
16159
|
+
});
|
|
16160
|
+
}
|
|
16161
|
+
if (/\bconsole\.log\s*\(\s*JSON\.stringify\s*\(\s*\{[\s\S]*?\b(?:action|reply|code)\s*:/.test(
|
|
16162
|
+
normalized
|
|
16163
|
+
)) {
|
|
16164
|
+
issues.push({
|
|
16165
|
+
code: "stdout_json_reply",
|
|
16166
|
+
severity: "error",
|
|
16167
|
+
message: "Do not print JSON chat envelopes from generated jobs; use runtime messaging or return a plain result."
|
|
16168
|
+
});
|
|
16169
|
+
}
|
|
16170
|
+
if (/\breturn\s+\{[\s\S]*?\baction\s*:\s*['"]reply['"][\s\S]*?\breply\s*:/.test(
|
|
16171
|
+
normalized
|
|
16172
|
+
)) {
|
|
16173
|
+
issues.push({
|
|
16174
|
+
code: "return_chat_payload",
|
|
16175
|
+
severity: "error",
|
|
16176
|
+
message: "Do not return chat envelopes like { action, reply, code } from generated jobs; return a plain value or use runtime messaging."
|
|
15197
16177
|
});
|
|
15198
16178
|
}
|
|
15199
16179
|
return issues;
|
|
@@ -15252,15 +16232,40 @@ function collectConversationReferents(liveDoc) {
|
|
|
15252
16232
|
const ts = Number(message.ts) || 0;
|
|
15253
16233
|
const messageId = typeof message.id === "string" ? message.id : void 0;
|
|
15254
16234
|
const jobId = typeof message.jobId === "string" ? message.jobId : void 0;
|
|
15255
|
-
|
|
16235
|
+
const entryPaths = uniqueStrings(asArray2(show.entryPaths));
|
|
16236
|
+
const entryClassCounts = /* @__PURE__ */ new Map();
|
|
16237
|
+
const entryMetadata = entryPaths.map((entryPath) => {
|
|
15256
16238
|
const entry = asRecord4(entriesByPath[entryPath]);
|
|
16239
|
+
const className = typeof entry?.className === "string" ? entry.className : void 0;
|
|
16240
|
+
if (className) {
|
|
16241
|
+
entryClassCounts.set(
|
|
16242
|
+
className,
|
|
16243
|
+
(entryClassCounts.get(className) || 0) + 1
|
|
16244
|
+
);
|
|
16245
|
+
}
|
|
16246
|
+
return { entryPath, entry, className };
|
|
16247
|
+
});
|
|
16248
|
+
const displayGroupId = entryMetadata.length > 1 ? `message:${messageId || jobId || ts}:entries` : void 0;
|
|
16249
|
+
for (const [
|
|
16250
|
+
index,
|
|
16251
|
+
{ entryPath, entry, className }
|
|
16252
|
+
] of entryMetadata.entries()) {
|
|
15257
16253
|
pushReferent({
|
|
15258
16254
|
id: `entry:${entryPath}`,
|
|
15259
16255
|
kind: "entry",
|
|
15260
16256
|
ref: entryPath,
|
|
16257
|
+
role: "assistant",
|
|
16258
|
+
source: "heap_objects",
|
|
15261
16259
|
entryPath,
|
|
15262
|
-
|
|
16260
|
+
recordId: typeof entry?.id === "string" ? entry.id : void 0,
|
|
16261
|
+
className,
|
|
15263
16262
|
label: typeof entry?.label === "string" && entry.label.trim() ? entry.label.trim() : typeof entry?.id === "string" && entry.id.trim() ? entry.id.trim() : entryPath,
|
|
16263
|
+
...displayGroupId ? {
|
|
16264
|
+
displayGroupId,
|
|
16265
|
+
displayGroupIndex: index,
|
|
16266
|
+
displayGroupSize: entryMetadata.length,
|
|
16267
|
+
...className && (entryClassCounts.get(className) || 0) > 1 ? { displayGroupSameTypeSize: entryClassCounts.get(className) } : {}
|
|
16268
|
+
} : {},
|
|
15264
16269
|
messageId,
|
|
15265
16270
|
jobId,
|
|
15266
16271
|
ts
|
|
@@ -15272,6 +16277,8 @@ function collectConversationReferents(liveDoc) {
|
|
|
15272
16277
|
id: `list:${listName}`,
|
|
15273
16278
|
kind: "list",
|
|
15274
16279
|
ref: listName,
|
|
16280
|
+
role: "assistant",
|
|
16281
|
+
source: "heap_objects",
|
|
15275
16282
|
listName,
|
|
15276
16283
|
className: typeof list?.className === "string" ? list.className : void 0,
|
|
15277
16284
|
count: Array.isArray(list?.paths) ? list.paths.length : null,
|
|
@@ -15292,9 +16299,12 @@ function collectConversationReferents(liveDoc) {
|
|
|
15292
16299
|
id: `variable:${variableName}`,
|
|
15293
16300
|
kind: "variable",
|
|
15294
16301
|
ref: variableName,
|
|
16302
|
+
role: "assistant",
|
|
16303
|
+
source: "heap_objects",
|
|
15295
16304
|
variableName,
|
|
15296
16305
|
variableKind: typeof variable?.kind === "string" ? variable.kind : void 0,
|
|
15297
16306
|
entryPath,
|
|
16307
|
+
recordId: typeof entry?.id === "string" ? entry.id : void 0,
|
|
15298
16308
|
listName,
|
|
15299
16309
|
className: typeof variable?.className === "string" ? variable.className : typeof entry?.className === "string" ? entry.className : typeof list?.className === "string" ? list.className : void 0,
|
|
15300
16310
|
label: typeof entry?.label === "string" && entry.label.trim() ? entry.label.trim() : typeof entry?.id === "string" && entry.id.trim() ? entry.id.trim() : null,
|
|
@@ -15315,18 +16325,24 @@ function projectConversationReferentFocus(liveDoc) {
|
|
|
15315
16325
|
const entryPaths = [];
|
|
15316
16326
|
const listNames = [];
|
|
15317
16327
|
const variableNames = [];
|
|
15318
|
-
|
|
15319
|
-
|
|
16328
|
+
let entryCount = 0;
|
|
16329
|
+
let listCount = 0;
|
|
16330
|
+
let variableCount = 0;
|
|
16331
|
+
for (const referent of referents) {
|
|
16332
|
+
if (referent.kind === "entry" && typeof referent.entryPath === "string" && entryCount < 8) {
|
|
16333
|
+
entryCount += 1;
|
|
15320
16334
|
entryPaths.push(referent.entryPath);
|
|
15321
16335
|
continue;
|
|
15322
16336
|
}
|
|
15323
|
-
if (referent.kind === "list" && typeof referent.listName === "string") {
|
|
16337
|
+
if (referent.kind === "list" && typeof referent.listName === "string" && listCount < 4) {
|
|
16338
|
+
listCount += 1;
|
|
15324
16339
|
listNames.push(referent.listName);
|
|
15325
16340
|
const list = asRecord4(listsByName[referent.listName]);
|
|
15326
16341
|
entryPaths.push(...asArray2(list?.paths).slice(0, 4));
|
|
15327
16342
|
continue;
|
|
15328
16343
|
}
|
|
15329
|
-
if (referent.kind === "variable" && typeof referent.variableName === "string") {
|
|
16344
|
+
if (referent.kind === "variable" && typeof referent.variableName === "string" && variableCount < 4) {
|
|
16345
|
+
variableCount += 1;
|
|
15330
16346
|
variableNames.push(referent.variableName);
|
|
15331
16347
|
if (typeof referent.entryPath === "string") {
|
|
15332
16348
|
entryPaths.push(referent.entryPath);
|
|
@@ -15344,61 +16360,91 @@ function projectConversationReferentFocus(liveDoc) {
|
|
|
15344
16360
|
variableNames: uniqueStrings(variableNames, 4)
|
|
15345
16361
|
};
|
|
15346
16362
|
}
|
|
15347
|
-
function
|
|
15348
|
-
const
|
|
15349
|
-
|
|
15350
|
-
|
|
15351
|
-
|
|
15352
|
-
|
|
15353
|
-
const listLines = [];
|
|
15354
|
-
const variableLines = [];
|
|
16363
|
+
function selectConversationReferentsForPrompt(referents) {
|
|
16364
|
+
const selected = [];
|
|
16365
|
+
const seen = /* @__PURE__ */ new Set();
|
|
16366
|
+
let entryCount = 0;
|
|
16367
|
+
let listCount = 0;
|
|
16368
|
+
let variableCount = 0;
|
|
15355
16369
|
for (const referent of referents) {
|
|
16370
|
+
if (!referent.kind || !referent.ref) continue;
|
|
16371
|
+
const key = `${referent.kind}:${referent.ref}`;
|
|
16372
|
+
if (seen.has(key)) continue;
|
|
16373
|
+
if (referent.kind === "entry") {
|
|
16374
|
+
if (entryCount >= 8) continue;
|
|
16375
|
+
entryCount += 1;
|
|
16376
|
+
} else if (referent.kind === "list") {
|
|
16377
|
+
if (listCount >= 4) continue;
|
|
16378
|
+
listCount += 1;
|
|
16379
|
+
} else if (referent.kind === "variable") {
|
|
16380
|
+
if (variableCount >= 4) continue;
|
|
16381
|
+
variableCount += 1;
|
|
16382
|
+
}
|
|
16383
|
+
seen.add(key);
|
|
16384
|
+
selected.push(referent);
|
|
16385
|
+
}
|
|
16386
|
+
return selected;
|
|
16387
|
+
}
|
|
16388
|
+
function projectConversationReferentSummary(liveDoc) {
|
|
16389
|
+
const referents = selectConversationReferentsForPrompt(
|
|
16390
|
+
collectConversationReferents(liveDoc)
|
|
16391
|
+
);
|
|
16392
|
+
const compact = referents.map((referent) => {
|
|
15356
16393
|
if (referent.kind === "entry" && referent.entryPath) {
|
|
15357
|
-
|
|
15358
|
-
|
|
15359
|
-
|
|
15360
|
-
|
|
16394
|
+
return {
|
|
16395
|
+
kind: "entry",
|
|
16396
|
+
role: referent.role || null,
|
|
16397
|
+
source: referent.source || null,
|
|
16398
|
+
path: referent.entryPath,
|
|
16399
|
+
id: referent.recordId || null,
|
|
16400
|
+
type: referent.className || "unknown",
|
|
16401
|
+
label: referent.label || referent.entryPath,
|
|
16402
|
+
group: referent.displayGroupId ? {
|
|
16403
|
+
id: referent.displayGroupId,
|
|
16404
|
+
index: typeof referent.displayGroupIndex === "number" ? referent.displayGroupIndex : null,
|
|
16405
|
+
size: typeof referent.displayGroupSize === "number" ? referent.displayGroupSize : null,
|
|
16406
|
+
sameTypeSize: typeof referent.displayGroupSameTypeSize === "number" ? referent.displayGroupSameTypeSize : null
|
|
16407
|
+
} : void 0
|
|
16408
|
+
};
|
|
16409
|
+
}
|
|
16410
|
+
if (referent.kind === "entry" && referent.recordId) {
|
|
16411
|
+
return {
|
|
16412
|
+
kind: "entry",
|
|
16413
|
+
role: referent.role || null,
|
|
16414
|
+
source: referent.source || null,
|
|
16415
|
+
id: referent.recordId,
|
|
16416
|
+
type: referent.className || "unknown",
|
|
16417
|
+
label: referent.label || referent.recordId
|
|
16418
|
+
};
|
|
15361
16419
|
}
|
|
15362
16420
|
if (referent.kind === "list" && referent.listName) {
|
|
15363
|
-
|
|
15364
|
-
|
|
15365
|
-
|
|
15366
|
-
|
|
15367
|
-
|
|
15368
|
-
|
|
16421
|
+
return {
|
|
16422
|
+
kind: "list",
|
|
16423
|
+
role: referent.role || null,
|
|
16424
|
+
source: referent.source || null,
|
|
16425
|
+
name: referent.listName,
|
|
16426
|
+
type: referent.className || "unknown",
|
|
16427
|
+
count: typeof referent.count === "number" ? referent.count : null
|
|
16428
|
+
};
|
|
15369
16429
|
}
|
|
15370
16430
|
if (referent.kind === "variable" && referent.variableName) {
|
|
15371
|
-
|
|
15372
|
-
|
|
15373
|
-
|
|
15374
|
-
|
|
15375
|
-
|
|
15376
|
-
|
|
15377
|
-
|
|
15378
|
-
|
|
15379
|
-
|
|
15380
|
-
|
|
15381
|
-
|
|
15382
|
-
|
|
15383
|
-
|
|
15384
|
-
}
|
|
15385
|
-
if (referent.variableKind === "scalar") {
|
|
15386
|
-
variableLines.push(
|
|
15387
|
-
`- ${referent.variableName}: scalar = ${formatScalar(referent.scalarValue)}`
|
|
15388
|
-
);
|
|
15389
|
-
continue;
|
|
15390
|
-
}
|
|
15391
|
-
variableLines.push(`- ${referent.variableName}`);
|
|
16431
|
+
return {
|
|
16432
|
+
kind: "variable",
|
|
16433
|
+
role: referent.role || null,
|
|
16434
|
+
source: referent.source || null,
|
|
16435
|
+
name: referent.variableName,
|
|
16436
|
+
valueKind: referent.variableKind || null,
|
|
16437
|
+
type: referent.className || null,
|
|
16438
|
+
path: referent.entryPath || null,
|
|
16439
|
+
list: referent.listName || null,
|
|
16440
|
+
label: referent.label || null,
|
|
16441
|
+
count: typeof referent.count === "number" ? referent.count : null,
|
|
16442
|
+
value: referent.variableKind === "scalar" ? referent.scalarValue ?? null : void 0
|
|
16443
|
+
};
|
|
15392
16444
|
}
|
|
15393
|
-
|
|
15394
|
-
|
|
15395
|
-
|
|
15396
|
-
lines.push(...entryLines.length > 0 ? entryLines : ["- none"]);
|
|
15397
|
-
lines.push("", "Lists:");
|
|
15398
|
-
lines.push(...listLines.length > 0 ? listLines : ["- none"]);
|
|
15399
|
-
lines.push("", "Variables:");
|
|
15400
|
-
lines.push(...variableLines.length > 0 ? variableLines : ["- none"]);
|
|
15401
|
-
return lines.join("\n");
|
|
16445
|
+
return null;
|
|
16446
|
+
}).filter(Boolean);
|
|
16447
|
+
return renderConstBlock("recentReferences", compact);
|
|
15402
16448
|
}
|
|
15403
16449
|
function getCurrentClosureId(liveDoc) {
|
|
15404
16450
|
const loop = asRecord4(liveDoc?.loop);
|
|
@@ -15619,56 +16665,24 @@ function projectWorkflowFocus(liveDoc, pendingPrompts = [], options) {
|
|
|
15619
16665
|
}
|
|
15620
16666
|
function projectWorkflowSummary(liveDoc, pendingPrompts = [], options) {
|
|
15621
16667
|
const focus = projectWorkflowFocus(liveDoc, pendingPrompts, options);
|
|
15622
|
-
|
|
15623
|
-
|
|
15624
|
-
|
|
15625
|
-
|
|
15626
|
-
|
|
15627
|
-
|
|
15628
|
-
|
|
15629
|
-
|
|
15630
|
-
|
|
15631
|
-
|
|
15632
|
-
|
|
15633
|
-
|
|
15634
|
-
|
|
15635
|
-
|
|
15636
|
-
|
|
15637
|
-
|
|
15638
|
-
} else {
|
|
15639
|
-
for (const line of focus.recentActionSummary) {
|
|
15640
|
-
lines.push(line.startsWith("- ") ? line : `- ${line}`);
|
|
15641
|
-
}
|
|
15642
|
-
}
|
|
15643
|
-
lines.push("", "Working Set Hints:");
|
|
15644
|
-
if (focus.variableNames.length === 0 && focus.listNames.length === 0 && focus.entryPaths.length === 0) {
|
|
15645
|
-
lines.push("- none");
|
|
15646
|
-
} else {
|
|
15647
|
-
if (focus.variableNames.length > 0) {
|
|
15648
|
-
lines.push(`- variables: ${focus.variableNames.join(", ")}`);
|
|
15649
|
-
}
|
|
15650
|
-
if (focus.listNames.length > 0) {
|
|
15651
|
-
lines.push(`- lists: ${focus.listNames.join(", ")}`);
|
|
15652
|
-
}
|
|
15653
|
-
if (focus.entryPaths.length > 0) {
|
|
15654
|
-
lines.push(`- entries: ${focus.entryPaths.join(", ")}`);
|
|
15655
|
-
}
|
|
15656
|
-
}
|
|
15657
|
-
lines.push("", "Open Workflow Handles:");
|
|
15658
|
-
if (focus.activeTaskIds.length === 0 && focus.openDecisionIds.length === 0 && focus.openPromptIds.length === 0) {
|
|
15659
|
-
lines.push("- none");
|
|
15660
|
-
} else {
|
|
15661
|
-
if (focus.activeTaskIds.length > 0) {
|
|
15662
|
-
lines.push(`- tasks: ${focus.activeTaskIds.join(", ")}`);
|
|
15663
|
-
}
|
|
15664
|
-
if (focus.openDecisionIds.length > 0) {
|
|
15665
|
-
lines.push(`- decisions: ${focus.openDecisionIds.join(", ")}`);
|
|
15666
|
-
}
|
|
15667
|
-
if (focus.openPromptIds.length > 0) {
|
|
15668
|
-
lines.push(`- prompts: ${focus.openPromptIds.join(", ")}`);
|
|
16668
|
+
return renderConstBlock("workflowContext", {
|
|
16669
|
+
boundary: {
|
|
16670
|
+
timestamp: focus.boundaryTimestamp,
|
|
16671
|
+
reason: focus.boundaryReason,
|
|
16672
|
+
latestClosureId: focus.latestClosureId || null
|
|
16673
|
+
},
|
|
16674
|
+
recentActions: focus.recentActionSummary,
|
|
16675
|
+
workingSet: {
|
|
16676
|
+
variables: focus.variableNames,
|
|
16677
|
+
lists: focus.listNames,
|
|
16678
|
+
entries: focus.entryPaths
|
|
16679
|
+
},
|
|
16680
|
+
openHandles: {
|
|
16681
|
+
tasks: focus.activeTaskIds,
|
|
16682
|
+
decisions: focus.openDecisionIds,
|
|
16683
|
+
prompts: focus.openPromptIds
|
|
15669
16684
|
}
|
|
15670
|
-
}
|
|
15671
|
-
return lines.join("\n");
|
|
16685
|
+
});
|
|
15672
16686
|
}
|
|
15673
16687
|
function hasOpenPrompt(liveDoc, pendingPrompts) {
|
|
15674
16688
|
if (pendingPrompts.length > 0) return true;
|
|
@@ -15689,7 +16703,6 @@ function getExclusivePromptTarget(pendingPrompts) {
|
|
|
15689
16703
|
return prompt?.type === "input" ? prompt : null;
|
|
15690
16704
|
}
|
|
15691
16705
|
function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
|
|
15692
|
-
const lines = [];
|
|
15693
16706
|
const loop = asRecord4(liveDoc?.loop);
|
|
15694
16707
|
const boundary = getWorkflowBoundary(liveDoc, options);
|
|
15695
16708
|
const tasks = toSortedRecords(loop?.tasksById).filter((task) => {
|
|
@@ -15711,22 +16724,12 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
|
|
|
15711
16724
|
5
|
|
15712
16725
|
);
|
|
15713
16726
|
const hiddenTaskCount = Math.max(0, activeTasks.length - visibleTasks.length);
|
|
15714
|
-
|
|
15715
|
-
|
|
15716
|
-
|
|
15717
|
-
|
|
15718
|
-
|
|
15719
|
-
|
|
15720
|
-
const title = typeof task.title === "string" ? task.title : "Untitled task";
|
|
15721
|
-
const taskId = typeof task.taskId === "string" ? task.taskId : "unknown";
|
|
15722
|
-
const status = typeof task.status === "string" ? task.status : "pending";
|
|
15723
|
-
const summary = typeof task.summary === "string" && task.summary.trim() ? ` \u2014 ${task.summary.trim()}` : "";
|
|
15724
|
-
lines.push(`- [${status}] ${title} (${taskId})${summary}`);
|
|
15725
|
-
}
|
|
15726
|
-
if (hiddenTaskCount > 0) {
|
|
15727
|
-
lines.push(`- ${hiddenTaskCount} more active task(s) omitted`);
|
|
15728
|
-
}
|
|
15729
|
-
}
|
|
16727
|
+
const compactTasks = visibleTasks.map((task) => ({
|
|
16728
|
+
id: typeof task.taskId === "string" ? task.taskId : "unknown",
|
|
16729
|
+
title: typeof task.title === "string" ? task.title : "Untitled task",
|
|
16730
|
+
status: typeof task.status === "string" ? task.status : "pending",
|
|
16731
|
+
summary: typeof task.summary === "string" && task.summary.trim() ? task.summary.trim() : null
|
|
16732
|
+
}));
|
|
15730
16733
|
const decisions = toSortedRecords(loop?.decisionsById).filter((decision) => {
|
|
15731
16734
|
const updatedAt = Number(decision.updatedAt) || Number(decision.createdAt) || 0;
|
|
15732
16735
|
if (boundary.reason === "request_start") {
|
|
@@ -15740,33 +16743,29 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
|
|
|
15740
16743
|
(decision) => decision.status === "open"
|
|
15741
16744
|
);
|
|
15742
16745
|
const visibleDecisions = (openDecisions.length > 0 ? openDecisions : decisions.slice(0, 1)).slice(0, 3);
|
|
15743
|
-
|
|
15744
|
-
|
|
15745
|
-
|
|
15746
|
-
|
|
15747
|
-
|
|
15748
|
-
|
|
15749
|
-
|
|
15750
|
-
|
|
15751
|
-
|
|
15752
|
-
|
|
15753
|
-
|
|
15754
|
-
|
|
15755
|
-
|
|
15756
|
-
|
|
15757
|
-
|
|
15758
|
-
|
|
15759
|
-
|
|
15760
|
-
|
|
15761
|
-
|
|
15762
|
-
|
|
15763
|
-
} else {
|
|
15764
|
-
const selected = asRecord4(decision.selected);
|
|
15765
|
-
const label = typeof selected?.label === "string" ? selected.label : typeof selected?.id === "string" ? selected.id : "unknown";
|
|
15766
|
-
lines.push(`- [resolved] ${title} (${decisionId}) -> ${label}`);
|
|
16746
|
+
const compactDecisions = visibleDecisions.map((decision) => {
|
|
16747
|
+
const status = typeof decision.status === "string" ? decision.status : "resolved";
|
|
16748
|
+
const selected = asRecord4(decision.selected);
|
|
16749
|
+
return {
|
|
16750
|
+
id: typeof decision.decisionId === "string" ? decision.decisionId : "unknown",
|
|
16751
|
+
title: typeof decision.title === "string" && decision.title.trim() ? decision.title.trim() : "Decision",
|
|
16752
|
+
status,
|
|
16753
|
+
candidates: status === "open" ? asArray2(decision.candidates).slice(0, 5).map((candidate) => {
|
|
16754
|
+
const record = asRecord4(candidate);
|
|
16755
|
+
if (!record) return null;
|
|
16756
|
+
return {
|
|
16757
|
+
id: typeof record.id === "string" ? record.id : "unknown",
|
|
16758
|
+
label: typeof record.label === "string" && record.label.trim() ? record.label.trim() : null,
|
|
16759
|
+
description: typeof record.description === "string" && record.description.trim() ? record.description.trim() : null,
|
|
16760
|
+
metadata: asRecord4(record.metadata)
|
|
16761
|
+
};
|
|
16762
|
+
}).filter(Boolean) : [],
|
|
16763
|
+
selected: status === "open" ? null : {
|
|
16764
|
+
id: typeof selected?.id === "string" ? selected.id : null,
|
|
16765
|
+
label: typeof selected?.label === "string" ? selected.label : null
|
|
15767
16766
|
}
|
|
15768
|
-
}
|
|
15769
|
-
}
|
|
16767
|
+
};
|
|
16768
|
+
});
|
|
15770
16769
|
const openPrompts = [
|
|
15771
16770
|
...pendingPrompts.map((prompt) => ({
|
|
15772
16771
|
id: prompt.id,
|
|
@@ -15786,29 +16785,29 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
|
|
|
15786
16785
|
(pendingPrompt) => pendingPrompt.id === promptId
|
|
15787
16786
|
) : false);
|
|
15788
16787
|
}) : openPrompts;
|
|
15789
|
-
|
|
15790
|
-
|
|
15791
|
-
|
|
15792
|
-
|
|
15793
|
-
|
|
15794
|
-
|
|
15795
|
-
|
|
15796
|
-
|
|
15797
|
-
|
|
15798
|
-
}
|
|
15799
|
-
}
|
|
16788
|
+
const compactPrompts = visiblePrompts.slice(0, 3).map((prompt) => {
|
|
16789
|
+
const promptRecord = asRecord4(prompt) || {};
|
|
16790
|
+
return {
|
|
16791
|
+
id: typeof promptRecord.id === "string" ? promptRecord.id : typeof promptRecord.promptId === "string" ? promptRecord.promptId : null,
|
|
16792
|
+
type: typeof promptRecord.type === "string" ? promptRecord.type : "input",
|
|
16793
|
+
title: typeof promptRecord.title === "string" && promptRecord.title.trim() ? promptRecord.title.trim() : "Input required",
|
|
16794
|
+
message: typeof promptRecord.message === "string" && promptRecord.message.trim() ? promptRecord.message.trim() : null
|
|
16795
|
+
};
|
|
16796
|
+
});
|
|
15800
16797
|
const currentClosureId = getCurrentClosureId(liveDoc);
|
|
15801
16798
|
const closureRecord = currentClosureId ? asRecord4(asRecord4(loop?.closuresById)?.[currentClosureId]) : null;
|
|
15802
16799
|
const visibleClosure = closureRecord && (boundary.reason !== "request_start" || (Number(closureRecord.createdAt) || 0) >= boundary.timestamp) ? closureRecord : null;
|
|
15803
|
-
|
|
15804
|
-
|
|
15805
|
-
|
|
15806
|
-
|
|
15807
|
-
|
|
15808
|
-
|
|
15809
|
-
|
|
15810
|
-
|
|
15811
|
-
|
|
16800
|
+
return renderConstBlock("workflowState", {
|
|
16801
|
+
tasks: compactTasks,
|
|
16802
|
+
hiddenActiveTaskCount: hiddenTaskCount,
|
|
16803
|
+
decisions: compactDecisions,
|
|
16804
|
+
openPrompts: compactPrompts,
|
|
16805
|
+
closure: visibleClosure ? {
|
|
16806
|
+
id: currentClosureId,
|
|
16807
|
+
status: typeof visibleClosure.status === "string" ? visibleClosure.status : "completed",
|
|
16808
|
+
summary: typeof visibleClosure.summary === "string" ? visibleClosure.summary : null
|
|
16809
|
+
} : null
|
|
16810
|
+
});
|
|
15812
16811
|
}
|
|
15813
16812
|
function projectHeapSummary(heap, options) {
|
|
15814
16813
|
const heapRecord = asRecord4(heap) || {};
|
|
@@ -15853,55 +16852,72 @@ function projectHeapSummary(heap, options) {
|
|
|
15853
16852
|
referencedPaths.add(path);
|
|
15854
16853
|
}
|
|
15855
16854
|
const visibleLists = Object.values(listsByName).map((value) => asRecord4(value)).filter((value) => Boolean(value)).filter(
|
|
15856
|
-
(list) => variables.some(
|
|
16855
|
+
(list) => variables.some(
|
|
16856
|
+
(variable) => Boolean(variable?.listName === list.name)
|
|
16857
|
+
) || Boolean(list.name && focusedListNames.has(list.name))
|
|
15857
16858
|
).sort((left, right) => (right.updatedAt || 0) - (left.updatedAt || 0)).slice(0, maxLists);
|
|
15858
16859
|
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);
|
|
15859
|
-
|
|
15860
|
-
|
|
15861
|
-
|
|
15862
|
-
|
|
15863
|
-
|
|
15864
|
-
|
|
15865
|
-
|
|
15866
|
-
|
|
15867
|
-
|
|
15868
|
-
)
|
|
15869
|
-
|
|
15870
|
-
|
|
15871
|
-
|
|
15872
|
-
|
|
15873
|
-
|
|
15874
|
-
|
|
15875
|
-
|
|
15876
|
-
|
|
15877
|
-
|
|
15878
|
-
|
|
15879
|
-
|
|
15880
|
-
|
|
15881
|
-
|
|
15882
|
-
|
|
15883
|
-
|
|
15884
|
-
|
|
15885
|
-
|
|
15886
|
-
|
|
15887
|
-
|
|
15888
|
-
|
|
15889
|
-
|
|
15890
|
-
|
|
15891
|
-
|
|
15892
|
-
|
|
15893
|
-
|
|
15894
|
-
|
|
15895
|
-
|
|
15896
|
-
|
|
15897
|
-
|
|
15898
|
-
|
|
15899
|
-
|
|
15900
|
-
|
|
15901
|
-
|
|
15902
|
-
|
|
15903
|
-
|
|
15904
|
-
|
|
16860
|
+
return renderConstBlock("savedData", {
|
|
16861
|
+
variables: Object.fromEntries(
|
|
16862
|
+
variables.filter((variable) => typeof variable.name === "string").map((variable) => {
|
|
16863
|
+
if (variable.kind === "scalar") {
|
|
16864
|
+
return [
|
|
16865
|
+
variable.name,
|
|
16866
|
+
{ kind: "scalar", value: variable.value ?? null }
|
|
16867
|
+
];
|
|
16868
|
+
}
|
|
16869
|
+
if (variable.kind === "entry") {
|
|
16870
|
+
const entry = variable.entryPath ? asRecord4(
|
|
16871
|
+
entriesByPath[variable.entryPath]
|
|
16872
|
+
) : null;
|
|
16873
|
+
return [
|
|
16874
|
+
variable.name,
|
|
16875
|
+
{
|
|
16876
|
+
kind: "entry",
|
|
16877
|
+
type: variable.className || entry?.className || "unknown",
|
|
16878
|
+
path: variable.entryPath || null,
|
|
16879
|
+
label: entry?.label || entry?.id || null
|
|
16880
|
+
}
|
|
16881
|
+
];
|
|
16882
|
+
}
|
|
16883
|
+
const list = variable.listName ? asRecord4(listsByName[variable.listName]) : null;
|
|
16884
|
+
return [
|
|
16885
|
+
variable.name,
|
|
16886
|
+
{
|
|
16887
|
+
kind: "list",
|
|
16888
|
+
type: variable.className || list?.className || "unknown",
|
|
16889
|
+
list: variable.listName || null,
|
|
16890
|
+
count: (list?.paths || []).length
|
|
16891
|
+
}
|
|
16892
|
+
];
|
|
16893
|
+
})
|
|
16894
|
+
),
|
|
16895
|
+
lists: Object.fromEntries(
|
|
16896
|
+
visibleLists.filter((list) => typeof list.name === "string").map((list) => [
|
|
16897
|
+
list.name,
|
|
16898
|
+
{
|
|
16899
|
+
type: list.className || "unknown",
|
|
16900
|
+
count: (list.paths || []).length
|
|
16901
|
+
}
|
|
16902
|
+
])
|
|
16903
|
+
),
|
|
16904
|
+
entries: Object.fromEntries(
|
|
16905
|
+
visibleEntries.filter((entry) => typeof entry.path === "string").map((entry) => [
|
|
16906
|
+
entry.path,
|
|
16907
|
+
{
|
|
16908
|
+
type: entry.className || "unknown",
|
|
16909
|
+
id: entry.id || null,
|
|
16910
|
+
label: entry.label || entry.id || null,
|
|
16911
|
+
fields: asArray2(entry.fields).filter(
|
|
16912
|
+
(field) => field?.name && field.name !== "_realId" && field.name !== "real_id"
|
|
16913
|
+
).slice(0, 3).map((field) => ({
|
|
16914
|
+
name: field.name,
|
|
16915
|
+
value: field.value ?? null
|
|
16916
|
+
}))
|
|
16917
|
+
}
|
|
16918
|
+
])
|
|
16919
|
+
)
|
|
16920
|
+
});
|
|
15905
16921
|
}
|
|
15906
16922
|
function createHarnessVerifierSnapshot(input) {
|
|
15907
16923
|
const workflowFocus = projectWorkflowFocus(
|
|
@@ -15998,8 +17014,8 @@ function buildContinuationInstruction(resultPreview) {
|
|
|
15998
17014
|
"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.",
|
|
15999
17015
|
"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.",
|
|
16000
17016
|
"If this request clearly spans multiple steps and there are no active tasks yet, create 2-4 short user-visible tasks now.",
|
|
16001
|
-
"Reuse any existing taskId and decisionId values exactly as they appear in
|
|
16002
|
-
"When progress depends on the user's choice, missing detail, or
|
|
17017
|
+
"Reuse any existing taskId and decisionId values exactly as they appear in [State].",
|
|
17018
|
+
"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.",
|
|
16003
17019
|
"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.'",
|
|
16004
17020
|
"If you ask the user a new question in this job, do not also close the loop in the same job.",
|
|
16005
17021
|
"Write the smallest straightforward code for the current step. Avoid defensive fallback branches for hypothetical states that are not currently true.",
|
|
@@ -16010,39 +17026,101 @@ ${resultPreview}` : null
|
|
|
16010
17026
|
].filter(Boolean).join("\n\n");
|
|
16011
17027
|
}
|
|
16012
17028
|
function buildGranularAgentDomainBlock(domainDocumentation) {
|
|
16013
|
-
return domainDocumentation?.trim() || "No domain
|
|
17029
|
+
return domainDocumentation?.trim() || "No domain contract available. The graph may not be ready yet.";
|
|
16014
17030
|
}
|
|
16015
17031
|
function buildGranularAgentSessionBlock(sessionContext) {
|
|
16016
|
-
|
|
16017
|
-
|
|
16018
|
-
|
|
16019
|
-
|
|
16020
|
-
|
|
16021
|
-
|
|
16022
|
-
const activeRows = rows.filter(([, value]) => Boolean(value));
|
|
16023
|
-
if (activeRows.length === 0) return "No session metadata available.";
|
|
16024
|
-
return activeRows.map(([key, value]) => `${key}: ${value}`).join("\n");
|
|
17032
|
+
return renderConstBlock("session", {
|
|
17033
|
+
runtimeId: sessionContext?.sandboxId || null,
|
|
17034
|
+
environmentId: sessionContext?.environmentId || null,
|
|
17035
|
+
userName: sessionContext?.userName || null,
|
|
17036
|
+
domainRevision: sessionContext?.domainRevision || null
|
|
17037
|
+
});
|
|
16025
17038
|
}
|
|
16026
17039
|
function buildGranularAgentHeapBlock(heapSummary) {
|
|
16027
|
-
return heapSummary?.trim() || "
|
|
17040
|
+
return heapSummary?.trim() || renderConstBlock("savedData", {
|
|
17041
|
+
variables: {},
|
|
17042
|
+
lists: {},
|
|
17043
|
+
entries: {}
|
|
17044
|
+
});
|
|
16028
17045
|
}
|
|
16029
17046
|
function buildGranularAgentReferentBlock(referentSummary) {
|
|
16030
|
-
return referentSummary?.trim() || "
|
|
17047
|
+
return referentSummary?.trim() || renderConstBlock("recentReferences", []);
|
|
16031
17048
|
}
|
|
16032
17049
|
function buildGranularAgentLoopBlock(loopSummary) {
|
|
16033
|
-
return loopSummary?.trim() || "
|
|
17050
|
+
return loopSummary?.trim() || renderConstBlock("workflowState", {
|
|
17051
|
+
tasks: [],
|
|
17052
|
+
decisions: [],
|
|
17053
|
+
openPrompts: [],
|
|
17054
|
+
closure: null
|
|
17055
|
+
});
|
|
16034
17056
|
}
|
|
16035
17057
|
function buildGranularAgentWorkflowBlock(workflowSummary) {
|
|
16036
|
-
return workflowSummary?.trim() || "
|
|
17058
|
+
return workflowSummary?.trim() || renderConstBlock("workflowContext", {
|
|
17059
|
+
boundary: null,
|
|
17060
|
+
recentActions: [],
|
|
17061
|
+
workingSet: {
|
|
17062
|
+
variables: [],
|
|
17063
|
+
lists: [],
|
|
17064
|
+
entries: []
|
|
17065
|
+
},
|
|
17066
|
+
openHandles: {
|
|
17067
|
+
tasks: [],
|
|
17068
|
+
decisions: [],
|
|
17069
|
+
prompts: []
|
|
17070
|
+
}
|
|
17071
|
+
});
|
|
16037
17072
|
}
|
|
16038
|
-
function
|
|
17073
|
+
function resolvePromptCapabilities(capabilities) {
|
|
17074
|
+
return {
|
|
17075
|
+
executeCode: capabilities?.executeCode !== false,
|
|
17076
|
+
readEntities: capabilities?.readEntities !== false,
|
|
17077
|
+
workflowHelpers: Array.isArray(capabilities?.workflowHelpers) ? capabilities.workflowHelpers : [
|
|
17078
|
+
"ask_user",
|
|
17079
|
+
"confirm",
|
|
17080
|
+
"open_decision",
|
|
17081
|
+
"close_decision",
|
|
17082
|
+
"create_task",
|
|
17083
|
+
"update_task",
|
|
17084
|
+
"complete_task",
|
|
17085
|
+
"close_loop"
|
|
17086
|
+
],
|
|
17087
|
+
savedData: capabilities?.savedData !== false,
|
|
17088
|
+
showRecords: capabilities?.showRecords !== false
|
|
17089
|
+
};
|
|
17090
|
+
}
|
|
17091
|
+
function buildGranularAgentToolBlock(tools, capabilityOverrides) {
|
|
17092
|
+
const resolvedCapabilities = resolvePromptCapabilities(capabilityOverrides);
|
|
17093
|
+
const normalizedTools = (tools || []).filter((tool) => tool?.name).slice().sort((left, right) => {
|
|
17094
|
+
const leftScope = `${left.className || "global"}:${left.static ? "static" : "instance"}`;
|
|
17095
|
+
const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
|
|
17096
|
+
return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
|
|
17097
|
+
});
|
|
17098
|
+
const writeActions = normalizedTools.filter((tool) => tool.ready !== false).map((tool) => {
|
|
17099
|
+
const scope = tool.className ? `${tool.static ? "class" : "record"}:${tool.className}` : "global";
|
|
17100
|
+
return {
|
|
17101
|
+
name: tool.name,
|
|
17102
|
+
scope,
|
|
17103
|
+
description: tool.description?.trim() || null
|
|
17104
|
+
};
|
|
17105
|
+
});
|
|
17106
|
+
const capabilities = {
|
|
17107
|
+
executeCode: resolvedCapabilities.executeCode,
|
|
17108
|
+
readEntities: resolvedCapabilities.readEntities,
|
|
17109
|
+
writeActions,
|
|
17110
|
+
workflowHelpers: resolvedCapabilities.workflowHelpers,
|
|
17111
|
+
savedData: resolvedCapabilities.savedData,
|
|
17112
|
+
showRecords: resolvedCapabilities.showRecords
|
|
17113
|
+
};
|
|
17114
|
+
return renderConstBlock("capabilities", capabilities);
|
|
17115
|
+
}
|
|
17116
|
+
function buildGranularAgentActionIndex(tools) {
|
|
16039
17117
|
const normalizedTools = (tools || []).filter((tool) => tool?.name).slice().sort((left, right) => {
|
|
16040
17118
|
const leftScope = `${left.className || "global"}:${left.static ? "static" : "instance"}`;
|
|
16041
17119
|
const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
|
|
16042
17120
|
return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
|
|
16043
17121
|
});
|
|
16044
17122
|
if (normalizedTools.length === 0) {
|
|
16045
|
-
return "No
|
|
17123
|
+
return "No domain write actions are available.";
|
|
16046
17124
|
}
|
|
16047
17125
|
const globalTools = normalizedTools.filter((tool) => !tool.className);
|
|
16048
17126
|
const staticTools = normalizedTools.filter(
|
|
@@ -16051,9 +17129,7 @@ function buildGranularAgentToolBlock(tools) {
|
|
|
16051
17129
|
const instanceTools = normalizedTools.filter(
|
|
16052
17130
|
(tool) => Boolean(tool.className && !tool.static)
|
|
16053
17131
|
);
|
|
16054
|
-
const lines = [
|
|
16055
|
-
"Treat this block as the planning map. Use DOMAIN REFERENCE below for exact signatures and query examples."
|
|
16056
|
-
];
|
|
17132
|
+
const lines = ["Available actions by scope:"];
|
|
16057
17133
|
const appendGroup = (title, group) => {
|
|
16058
17134
|
lines.push(`- ${title}:`);
|
|
16059
17135
|
if (group.length === 0) {
|
|
@@ -16062,187 +17138,466 @@ function buildGranularAgentToolBlock(tools) {
|
|
|
16062
17138
|
}
|
|
16063
17139
|
for (const tool of group.slice(0, 10)) {
|
|
16064
17140
|
const availability = tool.ready === false ? " [not ready]" : "";
|
|
17141
|
+
const schema = formatActionSchemaSummary(tool);
|
|
16065
17142
|
const description = tool.description?.trim() ? ` - ${tool.description.trim()}` : "";
|
|
16066
|
-
lines.push(` ${tool.name}${availability}${description}`);
|
|
17143
|
+
lines.push(` ${tool.name}${availability}${schema}${description}`);
|
|
16067
17144
|
}
|
|
16068
17145
|
if (group.length > 10) {
|
|
16069
17146
|
lines.push(` +${group.length - 10} more`);
|
|
16070
17147
|
}
|
|
16071
17148
|
};
|
|
16072
|
-
appendGroup("Global
|
|
16073
|
-
appendGroup("Class-level
|
|
16074
|
-
appendGroup("Record-level
|
|
17149
|
+
appendGroup("Global", globalTools);
|
|
17150
|
+
appendGroup("Class-level", staticTools);
|
|
17151
|
+
appendGroup("Record-level", instanceTools);
|
|
16075
17152
|
return lines.join("\n");
|
|
16076
17153
|
}
|
|
16077
|
-
function
|
|
16078
|
-
if (
|
|
16079
|
-
|
|
16080
|
-
|
|
16081
|
-
|
|
16082
|
-
|
|
16083
|
-
|
|
16084
|
-
}
|
|
16085
|
-
if (checkpoint.latestJobStatus) {
|
|
16086
|
-
lines.push(`latestJobStatus: ${checkpoint.latestJobStatus}`);
|
|
16087
|
-
}
|
|
16088
|
-
if (checkpoint.controllerOutcome) {
|
|
16089
|
-
lines.push(`controllerOutcome: ${checkpoint.controllerOutcome}`);
|
|
17154
|
+
function normalizeJsonSchema(value) {
|
|
17155
|
+
if (typeof value === "string") {
|
|
17156
|
+
try {
|
|
17157
|
+
return asRecord4(JSON.parse(value));
|
|
17158
|
+
} catch {
|
|
17159
|
+
return null;
|
|
17160
|
+
}
|
|
16090
17161
|
}
|
|
16091
|
-
|
|
16092
|
-
|
|
17162
|
+
return asRecord4(value);
|
|
17163
|
+
}
|
|
17164
|
+
function jsonSchemaTypeName(schema) {
|
|
17165
|
+
const record = normalizeJsonSchema(schema);
|
|
17166
|
+
if (!record) return "unknown";
|
|
17167
|
+
const type = record.type;
|
|
17168
|
+
if (typeof type === "string") {
|
|
17169
|
+
if (type === "array") return "array";
|
|
17170
|
+
if (type === "object") return "object";
|
|
17171
|
+
return type;
|
|
16093
17172
|
}
|
|
16094
|
-
|
|
16095
|
-
|
|
17173
|
+
return "unknown";
|
|
17174
|
+
}
|
|
17175
|
+
function summarizeObjectSchema(schema) {
|
|
17176
|
+
const record = normalizeJsonSchema(schema);
|
|
17177
|
+
const properties = asRecord4(record?.properties);
|
|
17178
|
+
if (!properties || Object.keys(properties).length === 0) {
|
|
17179
|
+
return record ? "{}" : null;
|
|
17180
|
+
}
|
|
17181
|
+
const required = new Set(asArray2(record?.required));
|
|
17182
|
+
const fields = Object.entries(properties).slice(0, 8).map(([name, property]) => {
|
|
17183
|
+
const marker = required.has(name) ? "*" : "?";
|
|
17184
|
+
return `${name}${marker}: ${jsonSchemaTypeName(property)}`;
|
|
17185
|
+
});
|
|
17186
|
+
const remaining = Object.keys(properties).length - fields.length;
|
|
17187
|
+
return remaining > 0 ? `${fields.join(", ")}, +${remaining}` : fields.join(", ");
|
|
17188
|
+
}
|
|
17189
|
+
function formatActionSchemaSummary(tool) {
|
|
17190
|
+
const input = summarizeObjectSchema(tool.inputSchema);
|
|
17191
|
+
const output = summarizeObjectSchema(tool.outputSchema);
|
|
17192
|
+
const parts = [];
|
|
17193
|
+
if (input) parts.push(`input { ${input} }`);
|
|
17194
|
+
if (output) parts.push(`output { ${output} }`);
|
|
17195
|
+
return parts.length ? ` (${parts.join("; ")})` : "";
|
|
17196
|
+
}
|
|
17197
|
+
function splitDomainDocumentation(domainDocumentation) {
|
|
17198
|
+
const normalized = domainDocumentation?.trim() || "";
|
|
17199
|
+
if (!normalized) return { types: "", docs: "" };
|
|
17200
|
+
const docsSectionMatch = normalized.match(/\n\s*\[Docs\]\s*\n/i);
|
|
17201
|
+
if (docsSectionMatch?.index !== void 0) {
|
|
17202
|
+
return {
|
|
17203
|
+
types: normalized.slice(0, docsSectionMatch.index).trim(),
|
|
17204
|
+
docs: normalized.slice(docsSectionMatch.index + docsSectionMatch[0].length).trim()
|
|
17205
|
+
};
|
|
16096
17206
|
}
|
|
16097
|
-
|
|
16098
|
-
|
|
17207
|
+
const legacyMarker = "Generated usage notes from ./sandbox-tools docs:";
|
|
17208
|
+
const legacyIndex = normalized.indexOf(legacyMarker);
|
|
17209
|
+
if (legacyIndex !== -1) {
|
|
17210
|
+
return {
|
|
17211
|
+
types: normalized.slice(0, legacyIndex).trim(),
|
|
17212
|
+
docs: normalized.slice(legacyIndex + legacyMarker.length).trim()
|
|
17213
|
+
};
|
|
16099
17214
|
}
|
|
16100
|
-
|
|
16101
|
-
|
|
16102
|
-
|
|
16103
|
-
|
|
16104
|
-
|
|
16105
|
-
|
|
16106
|
-
|
|
17215
|
+
return { types: normalized, docs: "" };
|
|
17216
|
+
}
|
|
17217
|
+
function buildGranularAgentCheckpointBlock(checkpoint) {
|
|
17218
|
+
if (!checkpoint) {
|
|
17219
|
+
return renderConstBlock("previousCodeResult", null);
|
|
17220
|
+
}
|
|
17221
|
+
return renderConstBlock("previousCodeResult", {
|
|
17222
|
+
iteration: typeof checkpoint.iteration === "number" ? checkpoint.iteration : null,
|
|
17223
|
+
latestJobStatus: checkpoint.latestJobStatus || null,
|
|
17224
|
+
controllerOutcome: checkpoint.controllerOutcome || null,
|
|
17225
|
+
controllerReason: checkpoint.controllerReason || null,
|
|
17226
|
+
noProgressCount: typeof checkpoint.noProgressCount === "number" ? checkpoint.noProgressCount : null,
|
|
17227
|
+
latestJobError: checkpoint.latestJobError?.trim() || null,
|
|
17228
|
+
latestActionSummary: Array.isArray(checkpoint.latestActionSummary) ? checkpoint.latestActionSummary.slice(0, 8).map(normalizeActionSummaryForPrompt) : [],
|
|
17229
|
+
latestJobResult: checkpoint.latestJobResult?.trim() || null
|
|
17230
|
+
});
|
|
17231
|
+
}
|
|
17232
|
+
function parseSummaryOutcome(summary) {
|
|
17233
|
+
const outcome = {};
|
|
17234
|
+
for (const part of summary.split(",")) {
|
|
17235
|
+
const trimmed = part.trim();
|
|
17236
|
+
const match = /^([A-Za-z0-9_]+)=(.+)$/.exec(trimmed);
|
|
17237
|
+
if (!match) continue;
|
|
17238
|
+
const [, key, rawValue] = match;
|
|
17239
|
+
const unquoted = rawValue.replace(/^"|"$/g, "");
|
|
17240
|
+
if (/^-?\d+(?:\.\d+)?$/.test(unquoted)) {
|
|
17241
|
+
outcome[key] = Number(unquoted);
|
|
17242
|
+
} else if (unquoted === "true" || unquoted === "false") {
|
|
17243
|
+
outcome[key] = unquoted === "true";
|
|
17244
|
+
} else {
|
|
17245
|
+
outcome[key] = unquoted;
|
|
16107
17246
|
}
|
|
16108
17247
|
}
|
|
16109
|
-
|
|
16110
|
-
|
|
16111
|
-
|
|
17248
|
+
return outcome;
|
|
17249
|
+
}
|
|
17250
|
+
function buildKnownFactsFromCheckpoint(checkpoint) {
|
|
17251
|
+
const summaries = Array.isArray(checkpoint?.latestActionSummary) ? checkpoint.latestActionSummary.map(normalizeActionSummaryForPrompt) : [];
|
|
17252
|
+
const facts = [];
|
|
17253
|
+
for (const summary of summaries) {
|
|
17254
|
+
const countedMatch = /^-\s*Counted\s+([A-Za-z0-9_]+).*?->\s*value=(\d+)/.exec(summary);
|
|
17255
|
+
if (countedMatch) {
|
|
17256
|
+
facts.push({
|
|
17257
|
+
entity: countedMatch[1],
|
|
17258
|
+
query: {},
|
|
17259
|
+
totalCount: Number(countedMatch[2])
|
|
17260
|
+
});
|
|
17261
|
+
continue;
|
|
17262
|
+
}
|
|
17263
|
+
const listedMatch = /^-\s*Listed\s+([A-Za-z0-9_]+).*?->\s*(.+)$/.exec(
|
|
17264
|
+
summary
|
|
17265
|
+
);
|
|
17266
|
+
if (!listedMatch) continue;
|
|
17267
|
+
const outcome = parseSummaryOutcome(listedMatch[2]);
|
|
17268
|
+
const count = typeof outcome.totalCount === "number" ? outcome.totalCount : typeof outcome.count === "number" ? outcome.count : void 0;
|
|
17269
|
+
if (typeof count !== "number") continue;
|
|
17270
|
+
const fact = {
|
|
17271
|
+
entity: listedMatch[1],
|
|
17272
|
+
query: {},
|
|
17273
|
+
totalCount: count
|
|
17274
|
+
};
|
|
17275
|
+
if (typeof outcome.hasMore === "boolean") {
|
|
17276
|
+
fact.lastPageHasMore = outcome.hasMore;
|
|
17277
|
+
fact.loadedAllItems = !outcome.hasMore;
|
|
17278
|
+
} else if (typeof outcome.count === "number" && outcome.count === count) {
|
|
17279
|
+
fact.loadedAllItems = true;
|
|
17280
|
+
}
|
|
17281
|
+
facts.push(fact);
|
|
16112
17282
|
}
|
|
16113
|
-
return
|
|
17283
|
+
return facts.slice(0, 8);
|
|
16114
17284
|
}
|
|
16115
17285
|
function buildGranularAgentSystemPrompt(input) {
|
|
17286
|
+
const outputMode = input.outputMode || "agentMessages";
|
|
17287
|
+
const promptCapabilities = resolvePromptCapabilities(input.capabilities);
|
|
17288
|
+
const domainSections = splitDomainDocumentation(input.domainDocumentation);
|
|
16116
17289
|
const sessionBlock = buildGranularAgentSessionBlock(input.sessionContext);
|
|
16117
|
-
const toolBlock = buildGranularAgentToolBlock(
|
|
16118
|
-
|
|
17290
|
+
const toolBlock = buildGranularAgentToolBlock(
|
|
17291
|
+
input.tools,
|
|
17292
|
+
input.capabilities
|
|
17293
|
+
);
|
|
17294
|
+
const actionIndex = buildGranularAgentActionIndex(input.tools);
|
|
17295
|
+
const domainBlock = buildGranularAgentDomainBlock(domainSections.types);
|
|
16119
17296
|
const workflowBlock = buildGranularAgentWorkflowBlock(input.workflowSummary);
|
|
16120
17297
|
const checkpointBlock = buildGranularAgentCheckpointBlock(input.checkpoint);
|
|
16121
17298
|
const heapBlock = buildGranularAgentHeapBlock(input.heapSummary);
|
|
16122
17299
|
const referentBlock = buildGranularAgentReferentBlock(input.referentSummary);
|
|
16123
17300
|
const loopBlock = buildGranularAgentLoopBlock(input.loopSummary);
|
|
16124
|
-
|
|
16125
|
-
|
|
16126
|
-
|
|
17301
|
+
const knownFactsBlock = renderConstBlock(
|
|
17302
|
+
"knownFacts",
|
|
17303
|
+
buildKnownFactsFromCheckpoint(input.checkpoint)
|
|
17304
|
+
);
|
|
17305
|
+
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 }\`.
|
|
17306
|
+
- Use \`{ reply, show }\` when the host UI should render records, heap variables, or lists from session state.
|
|
17307
|
+
- For multi-record display, prefer a saved list/listName so the UI can render a table; use entryPaths for a few individual records.
|
|
17308
|
+
- 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.
|
|
17309
|
+
- 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.
|
|
17310
|
+
- 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(...)\`.
|
|
17311
|
+
- \`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.
|
|
17312
|
+
- 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.
|
|
17313
|
+
- 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.
|
|
17314
|
+
- 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.
|
|
17315
|
+
- 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.
|
|
17316
|
+
- 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"] })\`.
|
|
17317
|
+
- \`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.
|
|
17318
|
+
- 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.
|
|
17319
|
+
- 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.
|
|
17320
|
+
- 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.
|
|
17321
|
+
- 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.
|
|
17322
|
+
- 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.
|
|
17323
|
+
- 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.
|
|
17324
|
+
- 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(...)\`.
|
|
17325
|
+
- \`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.
|
|
17326
|
+
- 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.
|
|
17327
|
+
- 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.
|
|
17328
|
+
- 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.`;
|
|
17329
|
+
const codeRules = promptCapabilities.executeCode ? `Code:
|
|
17330
|
+
- Use when the request needs session data, saved data, workflow state, record display, or available actions.
|
|
17331
|
+
- When using code, assistant text must be empty or one brief summary.
|
|
17332
|
+
- Code must be plain runnable JavaScript with top-level await.
|
|
17333
|
+
- Import needed classes and helpers from "./sandbox-tools".
|
|
17334
|
+
- Use static top-level imports such as \`import { Foo, agent_text_message } from "./sandbox-tools";\`. Do not use dynamic \`await import("./sandbox-tools")\`.
|
|
17335
|
+
- 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.
|
|
17336
|
+
- 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")\`.
|
|
17337
|
+
- 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.
|
|
17338
|
+
- User-visible output must use the provided message or record-display helpers.
|
|
17339
|
+
- After calling an action or effect, inspect the returned object and base the user-facing answer on its actual fields.
|
|
17340
|
+
- When calling an action, use the exact input property names from the action schema. Do not invent synonym keys for required inputs.
|
|
17341
|
+
- 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".
|
|
17342
|
+
- Never call \`process.exit(...)\`; emit a message and use \`return;\` to stop early.
|
|
17343
|
+
- 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.
|
|
17344
|
+
- 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.
|
|
17345
|
+
- Write \`//\` planning comments for the user, not for engineers: make them friendly, plain-language, and easy to understand.
|
|
17346
|
+
- 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.
|
|
17347
|
+
- 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.
|
|
17348
|
+
- Avoid technical terms, implementation names, code concepts, hidden helper names, and complex domain jargon in \`//\` planning comments unless the user already used that wording.
|
|
17349
|
+
- Each \`//\` planning comment should provide valuable feedback about the plan or next visible step. Do not add filler such as "Starting", "Running", or "Processing".
|
|
17350
|
+
${outputRules}` : `Code:
|
|
17351
|
+
- Code execution is unavailable. Use text only, or ask the user for missing information.`;
|
|
17352
|
+
const workflowRules = promptCapabilities.workflowHelpers.length > 0 ? `Workflow:
|
|
17353
|
+
- Use workflow helpers when missing input should pause and resume the workflow.
|
|
17354
|
+
- If code discovers missing required input after a read, use \`await loop.ask_user(...)\`; do not just tell the user to provide it.
|
|
17355
|
+
- 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.
|
|
17356
|
+
- 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.
|
|
17357
|
+
- 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.
|
|
17358
|
+
- 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.
|
|
17359
|
+
- Use choice only for 2 to 5 short grounded options.
|
|
17360
|
+
- For record choices, set each option value to a stable scalar such as the record \`_graphPath\` or \`id\`, not a label-only value.
|
|
17361
|
+
- 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.
|
|
17362
|
+
- 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.
|
|
17363
|
+
- 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.
|
|
17364
|
+
- 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.
|
|
17365
|
+
- 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.
|
|
17366
|
+
- 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.
|
|
17367
|
+
- Reuse existing task, decision, and closure ids from [State].
|
|
17368
|
+
- If a user request matches both a domain record/action and a workflow helper, prefer the domain capability.` : "";
|
|
17369
|
+
return `[Harness]
|
|
17370
|
+
You are an assistant for a live user session. Use plain, natural language.
|
|
16127
17371
|
|
|
16128
|
-
|
|
16129
|
-
|
|
16130
|
-
-
|
|
16131
|
-
-
|
|
16132
|
-
Do not
|
|
16133
|
-
-
|
|
16134
|
-
-
|
|
16135
|
-
- 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.
|
|
16136
|
-
- 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.
|
|
17372
|
+
Mode selection:
|
|
17373
|
+
Text only:
|
|
17374
|
+
- Use for general explanations, unsupported requests, or requests that do not need session data.
|
|
17375
|
+
- 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.
|
|
17376
|
+
- 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.
|
|
17377
|
+
- Do not expose internal names, helper names, file paths, parameter names, or code.
|
|
17378
|
+
- 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.
|
|
16137
17379
|
|
|
16138
|
-
|
|
16139
|
-
- While you are writing code, add short single-line comments with the prefix \`// \` before meaningful blocks.
|
|
16140
|
-
- These comments should explain the intent in friendly product language, not in implementation jargon.
|
|
16141
|
-
- Comments are shown live as a reasoning trace, so keep them brief, concrete, and useful.
|
|
16142
|
-
- Do not mention method names, file paths, or internal identifiers in those comments.
|
|
16143
|
-
- Use only single-line \`//\` comments for this purpose. Do not use block comments.
|
|
16144
|
-
- If you are replying with text only, you may also include a few leading \`// \` comment lines before the final answer.
|
|
16145
|
-
- End text-only replies with the plain user-facing answer on normal lines, without a comment prefix.
|
|
17380
|
+
${codeRules}
|
|
16146
17381
|
|
|
16147
|
-
|
|
16148
|
-
- Use plain, friendly product language.
|
|
16149
|
-
- Never mention internal implementation details in user-facing text:
|
|
16150
|
-
class names, effect names, method names, function names, file paths, parameter names, or code snippets.
|
|
16151
|
-
- Never expose dotted identifiers such as \`Class.method\` in user-facing text.
|
|
16152
|
-
- Do not say "sandbox" in user-facing text unless the user is explicitly asking about the runtime environment itself.
|
|
16153
|
-
- If you need clarification, ask in everyday language.
|
|
16154
|
-
- 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.
|
|
16155
|
-
- 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.
|
|
16156
|
-
- Keep replies concise and clear.
|
|
16157
|
-
- This is a conversation UI, not an API console. Favor human answers over machine-shaped payloads.
|
|
17382
|
+
${workflowRules}
|
|
16158
17383
|
|
|
16159
|
-
|
|
16160
|
-
|
|
17384
|
+
High-priority execution rules:
|
|
17385
|
+
- 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.
|
|
17386
|
+
- 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.
|
|
17387
|
+
- 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.
|
|
17388
|
+
- 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.
|
|
17389
|
+
- 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.
|
|
17390
|
+
- 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.
|
|
17391
|
+
- 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.
|
|
17392
|
+
- 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.
|
|
17393
|
+
- 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.
|
|
17394
|
+
- 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.
|
|
17395
|
+
- 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.
|
|
17396
|
+
- 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.
|
|
17397
|
+
- 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.
|
|
17398
|
+
- 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.
|
|
17399
|
+
- 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.
|
|
17400
|
+
- 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.
|
|
17401
|
+
- 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.
|
|
17402
|
+
- 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.
|
|
17403
|
+
- 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.
|
|
17404
|
+
- 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.
|
|
17405
|
+
- 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.
|
|
16161
17406
|
|
|
16162
|
-
|
|
16163
|
-
|
|
17407
|
+
Intent resolution:
|
|
17408
|
+
- If intent is explicit, act directly.
|
|
17409
|
+
- 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.
|
|
17410
|
+
- 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.
|
|
17411
|
+
- 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.
|
|
17412
|
+
- 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.
|
|
17413
|
+
- 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.
|
|
17414
|
+
- 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.
|
|
17415
|
+
- 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.
|
|
17416
|
+
- 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.
|
|
17417
|
+
- 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.
|
|
17418
|
+
- 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.
|
|
17419
|
+
- 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.
|
|
17420
|
+
- 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.
|
|
17421
|
+
- 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.
|
|
17422
|
+
- 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.
|
|
17423
|
+
- 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.
|
|
17424
|
+
- 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.
|
|
17425
|
+
- Never call \`.get({ path: "" })\`; an empty path is not a saved reference.
|
|
17426
|
+
- 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.
|
|
17427
|
+
- \`.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.
|
|
17428
|
+
- 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.
|
|
17429
|
+
- If the entity, field, target, scope, ranking, or action is ambiguous, create 2 to 5 plausible interpretations.
|
|
17430
|
+
- Probe plausible interpretations with cheap read-only queries before deciding.
|
|
17431
|
+
- 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.
|
|
17432
|
+
- 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.
|
|
17433
|
+
- One strong match means proceed.
|
|
17434
|
+
- Several plausible matches means call \`loop.ask_user({ type: "choice", ... })\` with grounded choices.
|
|
17435
|
+
- No grounded match means ask for missing information.
|
|
17436
|
+
- For consequential changes, resolve first, confirm when needed, then act.
|
|
17437
|
+
- 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.
|
|
17438
|
+
- 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\`.
|
|
17439
|
+
- 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.
|
|
17440
|
+
- 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.
|
|
17441
|
+
|
|
17442
|
+
Use exploratory probing when:
|
|
17443
|
+
- the user gives a human reference instead of an exact id or path
|
|
17444
|
+
- a noun could refer to multiple entity types
|
|
17445
|
+
- a name, number, label, date, or amount is given without a clear field
|
|
17446
|
+
- ranking words are used without a clear metric
|
|
17447
|
+
- a requested change has an unclear target
|
|
17448
|
+
- the first reasonable lookup returns zero results
|
|
17449
|
+
- the first reasonable lookup returns several plausible results
|
|
17450
|
+
|
|
17451
|
+
Do not explore when:
|
|
17452
|
+
- the entity, field, filter, and action are explicit
|
|
17453
|
+
- the request is a general explanation
|
|
17454
|
+
- the request is unsupported by available capabilities
|
|
17455
|
+
- the next step is already a required workflow answer or confirmation
|
|
16164
17456
|
|
|
16165
|
-
|
|
16166
|
-
Import classes and
|
|
16167
|
-
Use the
|
|
17457
|
+
[Types]
|
|
17458
|
+
Import classes, helpers, and available actions from "./sandbox-tools".
|
|
17459
|
+
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.
|
|
16168
17460
|
|
|
16169
17461
|
${domainBlock}
|
|
16170
17462
|
|
|
16171
|
-
|
|
17463
|
+
[Docs]
|
|
17464
|
+
Query policy:
|
|
17465
|
+
- Use filter, search, sort, count, page, list, and iterate on entity classes.
|
|
17466
|
+
- Push filtering and sorting into entity queries. Do not fetch a page only to filter or sort locally.
|
|
17467
|
+
- Valid filter fields are defined by each entity filter type.
|
|
17468
|
+
- Valid sort fields are defined by each entity sort field type.
|
|
17469
|
+
- Search is class-wide text retrieval, not a field-scoped operator.
|
|
17470
|
+
- Entity classes do not have a \`.search(...)\` method. Use \`.find({ search })\`, \`.page({ search, ... })\`, or \`.list({ search, ... })\`.
|
|
17471
|
+
- 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\`.
|
|
17472
|
+
- 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.
|
|
17473
|
+
- 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.
|
|
17474
|
+
- Combine search and filter when both free-text matching and exact constraints are needed.
|
|
17475
|
+
- 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.
|
|
17476
|
+
- 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.
|
|
17477
|
+
- Boolean filters use \`equal_to: true\` or \`equal_to: false\`.
|
|
17478
|
+
- 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.
|
|
17479
|
+
- 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.
|
|
17480
|
+
- 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.
|
|
17481
|
+
- 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.
|
|
17482
|
+
- 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.
|
|
17483
|
+
- 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.
|
|
17484
|
+
- 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.
|
|
17485
|
+
- 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.
|
|
17486
|
+
- 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.
|
|
17487
|
+
- Prefer generated instance relationship getters from a grounded record over hand-written deep nested relationship filters.
|
|
17488
|
+
- 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.
|
|
17489
|
+
- 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.
|
|
17490
|
+
- 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.
|
|
17491
|
+
- 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.
|
|
17492
|
+
- 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.
|
|
17493
|
+
- 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.
|
|
17494
|
+
- 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.
|
|
17495
|
+
- 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.
|
|
17496
|
+
- 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.
|
|
17497
|
+
- 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.
|
|
17498
|
+
- 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.
|
|
17499
|
+
- 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 }\`.
|
|
17500
|
+
- 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.
|
|
17501
|
+
- 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.
|
|
17502
|
+
- 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.
|
|
17503
|
+
- 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.
|
|
17504
|
+
- 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.
|
|
17505
|
+
- 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.
|
|
17506
|
+
- 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.
|
|
17507
|
+
- 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.
|
|
17508
|
+
- 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.
|
|
17509
|
+
- For scheduling actions, convert relative wording into concrete ISO timestamps before mutating records.
|
|
17510
|
+
- 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.
|
|
17511
|
+
- 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.
|
|
17512
|
+
- 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.
|
|
17513
|
+
- 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.
|
|
17514
|
+
- For exploratory work, use count for totals and page with small perPage for samples; use iteration only after the interpretation is chosen.
|
|
17515
|
+
|
|
17516
|
+
Lookup ladder:
|
|
17517
|
+
1. Check recent references and saved session data.
|
|
17518
|
+
2. Try exact id or path when the user gave an id-like value.
|
|
17519
|
+
3. If the request names a parent/container plus a target, ground the parent/container and traverse declared relationships to target candidates.
|
|
17520
|
+
4. Try exact filters on fields whose names or aliases match the user words.
|
|
17521
|
+
5. Try class-wide search with short target-local terms, not the whole user phrase.
|
|
17522
|
+
6. Try relationship filters when the user mentions connected concepts and the filter shape is documented.
|
|
17523
|
+
7. If the user names a parent/container and says the label may be approximate, inspect related target records before reporting no match.
|
|
17524
|
+
8. If still empty, try one small set of normalized, prefix, or fuzzy variants when search supports it.
|
|
17525
|
+
9. If still empty or ambiguous, ask the user for steering.
|
|
17526
|
+
|
|
17527
|
+
Exploration budget:
|
|
17528
|
+
- For a simple ambiguous reference, try up to 3 strategies.
|
|
17529
|
+
- For a broad ambiguous task, try up to 5 strategies.
|
|
17530
|
+
- Probe with small pages.
|
|
17531
|
+
- Do not run exhaustive scans during probing unless the user explicitly asks for all records or the selected task requires aggregation.
|
|
17532
|
+
- Stop early when a strong unique match is found.
|
|
17533
|
+
|
|
17534
|
+
Strong unique match:
|
|
17535
|
+
- exactly one record matches an exact id or path
|
|
17536
|
+
- exactly one record matches an exact filter on a likely identifier field
|
|
17537
|
+
- exactly one recent reference or saved value fits the request
|
|
17538
|
+
- one interpretation has results and all other reasonable interpretations have none
|
|
17539
|
+
|
|
17540
|
+
Ask the user when:
|
|
17541
|
+
- multiple exact matches exist
|
|
17542
|
+
- several entity types match the same phrase
|
|
17543
|
+
- the best match comes only from broad search and other plausible matches exist
|
|
17544
|
+
- the ranking or metric is unclear
|
|
17545
|
+
- the target is unique but the requested action is unclear
|
|
17546
|
+
|
|
17547
|
+
Relationship filters:
|
|
17548
|
+
- One-record relationships use \`is\`.
|
|
17549
|
+
- Multi-record relationships use \`some\`.
|
|
17550
|
+
- 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.
|
|
17551
|
+
- 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.
|
|
17552
|
+
- 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.
|
|
17553
|
+
- 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.
|
|
17554
|
+
- Use \`some\` only when the generated TypeScript type says \`ManyRelationFilter\`.
|
|
17555
|
+
- 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.
|
|
17556
|
+
- Use \`{ relationship: { id: "record_id" } }\` or \`{ relationship: { path: "class_record_id" } }\` when matching a known related record.
|
|
17557
|
+
- 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\`.
|
|
17558
|
+
- 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.
|
|
17559
|
+
- Use \`{ relationship: { is: { field: { equal_to: value } } } }\` only for nested field filters. Never put \`id\` or \`path\` inside \`is\`.
|
|
17560
|
+
- 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.
|
|
17561
|
+
- Do not pass a full record instance into a filter; if you already fetched a record, filter by its id or path instead.
|
|
17562
|
+
${domainSections.docs ? `
|
|
17563
|
+
Domain notes:
|
|
17564
|
+
${domainSections.docs}
|
|
17565
|
+
` : ""}
|
|
17566
|
+
|
|
17567
|
+
Actions:
|
|
17568
|
+
${actionIndex}
|
|
17569
|
+
- 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(...)\`.
|
|
17570
|
+
- Actions listed under "Class-level" are class/static methods. Call them on the imported class, e.g. \`await Item.action_name(...)\`.
|
|
17571
|
+
- 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.
|
|
17572
|
+
- Never call a record-level action as \`Class.action_name(...)\`; that method will not exist.
|
|
17573
|
+
- 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.
|
|
17574
|
+
- 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.
|
|
17575
|
+
- 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.
|
|
17576
|
+
- 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.
|
|
17577
|
+
- 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.
|
|
17578
|
+
- 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.
|
|
17579
|
+
- 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.
|
|
17580
|
+
- 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.
|
|
17581
|
+
|
|
17582
|
+
[State]
|
|
17583
|
+
${toolBlock}
|
|
17584
|
+
|
|
17585
|
+
${sessionBlock}
|
|
17586
|
+
|
|
16172
17587
|
${checkpointBlock}
|
|
16173
17588
|
|
|
16174
|
-
\u2500\u2500\u2500 WORKFLOW SNAPSHOT \u2500\u2500\u2500
|
|
16175
17589
|
${workflowBlock}
|
|
16176
17590
|
|
|
16177
|
-
\u2500\u2500\u2500 RECENT REFERENTS \u2500\u2500\u2500
|
|
16178
17591
|
${referentBlock}
|
|
16179
17592
|
|
|
16180
|
-
\u2500\u2500\u2500 SESSION HEAP \u2500\u2500\u2500
|
|
16181
17593
|
${heapBlock}
|
|
16182
17594
|
|
|
16183
|
-
\u2500\u2500\u2500 AGENT LOOP STATE \u2500\u2500\u2500
|
|
16184
17595
|
${loopBlock}
|
|
16185
17596
|
|
|
16186
|
-
|
|
16187
|
-
- 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.
|
|
16188
|
-
- Use CAPABILITY SNAPSHOT to choose the next step, then use DOMAIN REFERENCE for exact signatures and query shapes.
|
|
16189
|
-
- Take the minimum next step that directly helps the user. Avoid duplicate work, speculative cleanup, or extra fetching that is not needed yet.
|
|
16190
|
-
- Use RECENT REFERENTS to resolve follow-up references across turns, such as "that invoice", "that customer", "those products", or "the other one".
|
|
16191
|
-
- 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.
|
|
16192
|
-
- 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.
|
|
16193
|
-
- If the request has more than one reasonable interpretation, ask the user to clarify instead of guessing.
|
|
16194
|
-
- 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.
|
|
16195
|
-
- 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.
|
|
16196
|
-
- 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.
|
|
16197
|
-
- Reuse exact \`taskId\`, \`decisionId\`, and \`closureId\` values from AGENT LOOP STATE. Never invent or rewrite them.
|
|
16198
|
-
- If the request is ambiguous or clearly multi-step, create 2-4 short user-visible tasks and keep them updated as the workflow advances.
|
|
16199
|
-
- Use \`loop.ask_user({ type: 'choice', options: [...] })\` when you have a short, grounded shortlist the user can choose from. Otherwise use \`type: 'input'\`.
|
|
16200
|
-
- 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.
|
|
16201
|
-
- When \`type: 'choice'\` fits, do not ask the same question as plain text with bullets such as "Common options:" or "Choose one of these:".
|
|
16202
|
-
- Use \`loop.confirm(...)\` for consequential approval unless the user already clearly instructed you to perform that exact action now.
|
|
16203
|
-
- Await \`loop.ask_user(...)\` and \`loop.confirm(...)\`. After the job resumes, continue in the same job whenever the answer is enough to act.
|
|
16204
|
-
- 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.
|
|
16205
|
-
- If you ask a new question in the current job, do not also close the loop in that same job.
|
|
16206
|
-
|
|
16207
|
-
\u2500\u2500\u2500 LOOP HELPER REFERENCE \u2500\u2500\u2500
|
|
16208
|
-
- \`loop.ask_user(...)\`: pause the current job for missing input; use \`type: 'choice'\` only for a short grounded shortlist.
|
|
16209
|
-
- \`loop.confirm(...)\`: pause for yes/no approval before a consequential action, then branch on the returned boolean.
|
|
16210
|
-
- \`loop.open_decision(...)\`: save explicit candidates that later jobs can revisit; each candidate needs an \`id\`.
|
|
16211
|
-
- \`loop.close_decision(...)\`: resolve an open decision with a stored \`selectedId\` and optional rationale.
|
|
16212
|
-
- \`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.
|
|
16213
|
-
- \`loop.close_loop(...)\`: record the workflow outcome when it is completed, canceled, or blocked.
|
|
17597
|
+
${knownFactsBlock}
|
|
16214
17598
|
|
|
16215
|
-
|
|
16216
|
-
|
|
16217
|
-
- If you use \`heap\`, \`loop\`, \`agent_text_message\`, or \`agent_heap_objects\`, import them explicitly from \`./sandbox-tools\`.
|
|
16218
|
-
- Write top-level executable code with \`await\` at top level.
|
|
16219
|
-
- The generated job body must be plain runnable JavaScript. Do not use TypeScript-only syntax.
|
|
16220
|
-
- Follow the exact classes, methods, and parameter shapes in DOMAIN REFERENCE. Do not invent helpers or unsupported arguments.
|
|
16221
|
-
- Use \`ClassName.get({ path })\` only for known graph paths when you want a direct graph fetch.
|
|
16222
|
-
- 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.
|
|
16223
|
-
- \`perPage\` defaults to \`100\` and is capped at \`100\`.
|
|
16224
|
-
- 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.
|
|
16225
|
-
- Push \`filter\`, \`search\`, and \`sort\` into graph queries instead of fetching a page and processing it locally.
|
|
16226
|
-
- 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.
|
|
16227
|
-
- 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.
|
|
16228
|
-
- If ordering alone answers the request, use \`sort\` without inventing a \`filter\`.
|
|
16229
|
-
- 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(...)\`.
|
|
16230
|
-
- 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.
|
|
16231
|
-
- Call instance methods on instances, static methods on classes, and global effects by name.
|
|
16232
|
-
- Use \`heap.getEntry(path)\` for remembered heap entries, \`heap.getList(name)\` for remembered lists, and \`heap.getVar(name)\` only for named variables.
|
|
16233
|
-
- Use \`heap.setVar(...)\` and \`heap.deleteVar(...)\` only when they help the next step.
|
|
16234
|
-
- Prefer \`heap.setVar(...)\` for scalars or one selected instance. Prefer \`ClassName.list({ saveAs })\` for reusable typed lists. Empty arrays are allowed.
|
|
16235
|
-
- 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.
|
|
16236
|
-
- Use the \`loop\` helpers to manage workflow state: \`ask_user\`, \`confirm\`, \`open_decision\`, \`close_decision\`, \`create_task\`, \`update_task\`, \`complete_task\`, and \`close_loop\`.
|
|
16237
|
-
- Use \`type: 'choice'\` only for short grounded options. Use \`type: 'input'\` when the answer should stay open-ended.
|
|
16238
|
-
- \`loop.confirm(...)\` is for consequential approval. Do not ask for approval in plain text.
|
|
16239
|
-
- After \`await loop.ask_user(...)\` or \`await loop.confirm(...)\`, continue in the same resumed job when the answer is enough to act.
|
|
16240
|
-
- Every job that answers the user must emit \`agent_text_message(...)\` and/or \`agent_heap_objects(...)\`.
|
|
16241
|
-
- Use \`agent_text_message(...)\` for user-visible text.
|
|
16242
|
-
- 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.
|
|
16243
|
-
- 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.
|
|
16244
|
-
- Keep the code small and direct. Avoid speculative branches, broad casts, and raw JSON dumps unless the user asked for them.
|
|
16245
|
-
- Use \`console.log()\` only for intermediate diagnostics, not for the final user-facing answer.`;
|
|
17599
|
+
[Request]
|
|
17600
|
+
${input.request?.trim() || "Use the latest user message in the conversation."}`;
|
|
16246
17601
|
}
|
|
16247
17602
|
|
|
16248
17603
|
exports.Environment = Environment;
|
|
@@ -16262,6 +17617,8 @@ exports.buildGranularAgentSystemPrompt = buildGranularAgentSystemPrompt;
|
|
|
16262
17617
|
exports.buildGranularAgentToolBlock = buildGranularAgentToolBlock;
|
|
16263
17618
|
exports.buildGranularAgentWorkflowBlock = buildGranularAgentWorkflowBlock;
|
|
16264
17619
|
exports.buildSessionTranscript = buildSessionTranscript;
|
|
17620
|
+
exports.consumeGranularReasoningOnlyChunk = consumeGranularReasoningOnlyChunk;
|
|
17621
|
+
exports.consumeGranularReasoningTraceChunk = consumeGranularReasoningTraceChunk;
|
|
16265
17622
|
exports.createHarnessVerifierSnapshot = createHarnessVerifierSnapshot;
|
|
16266
17623
|
exports.evaluateContinuation = evaluateContinuation;
|
|
16267
17624
|
exports.extractPromptTokens = extractPromptTokens;
|
|
@@ -16272,6 +17629,7 @@ exports.invokeRegisteredEffect = invokeRegisteredEffect;
|
|
|
16272
17629
|
exports.isLocalApiUrl = isLocalApiUrl;
|
|
16273
17630
|
exports.normalizeEffectBehaviors = normalizeEffectBehaviors;
|
|
16274
17631
|
exports.normalizePrompt = normalizePrompt;
|
|
17632
|
+
exports.normalizePromptChoiceOption = normalizePromptChoiceOption;
|
|
16275
17633
|
exports.normalizePromptText = normalizePromptText;
|
|
16276
17634
|
exports.normalizePromptType = normalizePromptType;
|
|
16277
17635
|
exports.projectConversationReferentFocus = projectConversationReferentFocus;
|
|
@@ -16286,5 +17644,6 @@ exports.resolveJobPresentation = resolveJobPresentation;
|
|
|
16286
17644
|
exports.resolvePromptAnswer = resolvePromptAnswer;
|
|
16287
17645
|
exports.reviewGeneratedJobCode = reviewGeneratedJobCode;
|
|
16288
17646
|
exports.scorePromptChoiceMatch = scorePromptChoiceMatch;
|
|
17647
|
+
exports.stripGranularReasoningTrace = stripGranularReasoningTrace;
|
|
16289
17648
|
//# sourceMappingURL=index.js.map
|
|
16290
17649
|
//# sourceMappingURL=index.js.map
|