@granular-software/sdk 0.4.35 → 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.
@@ -1,4 +1,83 @@
1
1
  // src/agent-harness.ts
2
+ var DEFAULT_IGNORED_REASONING_COMMENT_DIRECTIVES = [
3
+ /^@ts-ignore\b/i,
4
+ /^@ts-expect-error\b/i,
5
+ /^eslint-[\w-]+\b/i,
6
+ /^biome-ignore\b/i,
7
+ /^prettier-ignore\b/i,
8
+ /^istanbul ignore\b/i
9
+ ];
10
+ var DEFAULT_LOW_SIGNAL_REASONING_LINES = [
11
+ /^running\.?$/i,
12
+ /^working\.?$/i,
13
+ /^thinking\.?$/i,
14
+ /^generating(?: code)?\.?$/i,
15
+ /^starting(?: execution)?\.?$/i
16
+ ];
17
+ function parseReasoningCommentLine(line, options = {}) {
18
+ const trimmed = line.trimStart();
19
+ if (!trimmed.startsWith("//")) return null;
20
+ const text = trimmed.replace(/^\/\/\s?/, "").trim();
21
+ if (!text) return { kind: "ignored" };
22
+ const ignoredDirectives = options.ignoredCommentDirectives || DEFAULT_IGNORED_REASONING_COMMENT_DIRECTIVES;
23
+ if (ignoredDirectives.some((pattern) => pattern.test(text))) {
24
+ return { kind: "ignored" };
25
+ }
26
+ const lowSignalLines = options.lowSignalReasoningLines || DEFAULT_LOW_SIGNAL_REASONING_LINES;
27
+ if (lowSignalLines.some((pattern) => pattern.test(text))) {
28
+ return { kind: "ignored" };
29
+ }
30
+ return { kind: "reasoning", text };
31
+ }
32
+ function consumeGranularReasoningTraceChunk(buffer, chunk, options = {}) {
33
+ let text = buffer + chunk;
34
+ let visibleText = "";
35
+ const reasoningLines = [];
36
+ while (true) {
37
+ const newlineIndex = text.indexOf("\n");
38
+ if (newlineIndex === -1) break;
39
+ const rawLine = text.slice(0, newlineIndex);
40
+ text = text.slice(newlineIndex + 1);
41
+ const comment = parseReasoningCommentLine(
42
+ rawLine.replace(/\r$/, ""),
43
+ options
44
+ );
45
+ if (comment?.kind === "reasoning") {
46
+ reasoningLines.push(comment.text);
47
+ } else if (comment?.kind === "ignored") {
48
+ continue;
49
+ } else {
50
+ visibleText += `${rawLine}
51
+ `;
52
+ }
53
+ }
54
+ if (options.final && text.length > 0) {
55
+ const comment = parseReasoningCommentLine(text.replace(/\r$/, ""), options);
56
+ if (comment?.kind === "reasoning") {
57
+ reasoningLines.push(comment.text);
58
+ text = "";
59
+ } else if (comment?.kind === "ignored") {
60
+ text = "";
61
+ } else {
62
+ visibleText += text;
63
+ text = "";
64
+ }
65
+ }
66
+ return { buffer: text, visibleText, reasoningLines };
67
+ }
68
+ function consumeGranularReasoningOnlyChunk(buffer, chunk, options = {}) {
69
+ const result = consumeGranularReasoningTraceChunk(buffer, chunk, options);
70
+ return {
71
+ buffer: result.buffer,
72
+ reasoningLines: result.reasoningLines
73
+ };
74
+ }
75
+ function stripGranularReasoningTrace(text, options = {}) {
76
+ return consumeGranularReasoningTraceChunk("", text, {
77
+ ...options,
78
+ final: true
79
+ }).visibleText.trim();
80
+ }
2
81
  function asRecord(value) {
3
82
  if (!value || typeof value !== "object" || Array.isArray(value)) return null;
4
83
  return value;
@@ -22,21 +101,8 @@ function uniqueStrings(values, maxCount) {
22
101
  }
23
102
  return output;
24
103
  }
25
- function formatScalar(value) {
26
- if (typeof value === "string") return JSON.stringify(value);
27
- if (typeof value === "number" || typeof value === "boolean")
28
- return String(value);
29
- if (value === null) return "null";
30
- return "unknown";
31
- }
32
- function describeHeapEntry(entry, previewFieldLimit = 3) {
33
- const headline = entry.label || entry.id || entry.path || "Unknown";
34
- const pathLabel = entry.path && entry.path !== headline ? ` <${entry.path}>` : "";
35
- const classLabel = entry.className || "unknown";
36
- const preview = asArray(entry.fields).filter(
37
- (field) => field?.name && field.name !== "_realId" && field.name !== "real_id"
38
- ).slice(0, previewFieldLimit).map((field) => `${field.name}=${formatScalar(field.value)}`).join(", ");
39
- return preview ? `${headline}${pathLabel} [${classLabel}] ${preview}` : `${headline}${pathLabel} [${classLabel}]`;
104
+ function renderConstBlock(name, value) {
105
+ return `const ${name} = ${JSON.stringify(value, null, 2)} as const;`;
40
106
  }
41
107
  function hashString(value) {
42
108
  if (!value) return null;
@@ -47,97 +113,248 @@ function hashString(value) {
47
113
  }
48
114
  return (hash >>> 0).toString(16).padStart(8, "0");
49
115
  }
50
- function hasSubstantiveAwaitAfterPrompt(code, marker) {
51
- const startIndex = code.indexOf(marker);
52
- if (startIndex === -1) return true;
53
- const segment = code.slice(startIndex + marker.length);
54
- const callMatches = segment.matchAll(
55
- /await\s+([A-Za-z0-9_$.]+)\.([A-Za-z0-9_]+)\s*\(/g
116
+ function findUndefinedSimpleTemplateIdentifier(source) {
117
+ const declared = /* @__PURE__ */ new Set();
118
+ const globals = /* @__PURE__ */ new Set([
119
+ "Array",
120
+ "Boolean",
121
+ "Date",
122
+ "JSON",
123
+ "Math",
124
+ "Number",
125
+ "Object",
126
+ "Promise",
127
+ "String",
128
+ "undefined",
129
+ "null",
130
+ "true",
131
+ "false"
132
+ ]);
133
+ for (const match of source.matchAll(/import\s*\{([^}]+)\}\s*from/g)) {
134
+ for (const part of match[1].split(",")) {
135
+ const aliasMatch = part.trim().match(/\bas\s+([A-Za-z_$][\w$]*)$/);
136
+ const nameMatch = part.trim().match(/^([A-Za-z_$][\w$]*)/);
137
+ const name = aliasMatch?.[1] || nameMatch?.[1];
138
+ if (name) declared.add(name);
139
+ }
140
+ }
141
+ for (const match of source.matchAll(
142
+ /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\b/g
143
+ )) {
144
+ declared.add(match[1]);
145
+ }
146
+ for (const match of source.matchAll(
147
+ /\bfor\s*(?:await\s*)?\(\s*(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s+of\b/g
148
+ )) {
149
+ declared.add(match[1]);
150
+ }
151
+ for (const match of source.matchAll(
152
+ /\bcatch\s*\(\s*([A-Za-z_$][\w$]*)\s*\)/g
153
+ )) {
154
+ declared.add(match[1]);
155
+ }
156
+ for (const match of source.matchAll(
157
+ /\(\s*([A-Za-z_$][\w$]*)\s*(?:,\s*[A-Za-z_$][\w$]*)*\s*\)\s*=>/g
158
+ )) {
159
+ declared.add(match[1]);
160
+ }
161
+ for (const match of source.matchAll(/\b([A-Za-z_$][\w$]*)\s*=>/g)) {
162
+ declared.add(match[1]);
163
+ }
164
+ for (const match of source.matchAll(/\$\{\s*([A-Za-z_$][\w$]*)\s*\}/g)) {
165
+ const identifier = match[1];
166
+ if (!declared.has(identifier) && !globals.has(identifier)) {
167
+ return identifier;
168
+ }
169
+ }
170
+ return null;
171
+ }
172
+ function getGeneratedJobSyntaxError(source) {
173
+ const withoutImports = source.replace(
174
+ /^\s*import\s+[\s\S]*?\s+from\s+["'][^"']+["']\s*;?\s*$/gm,
175
+ ""
56
176
  );
57
- for (const match of callMatches) {
58
- const receiver = match[1] || "";
59
- const method = match[2] || "";
60
- if (receiver === "loop" || receiver === "heap") continue;
61
- if (method.startsWith("get_") || method.startsWith("get")) continue;
62
- return true;
177
+ try {
178
+ new Function(`return (async () => {
179
+ ${withoutImports}
180
+ });`);
181
+ return null;
182
+ } catch (error) {
183
+ return error instanceof Error ? error.message : String(error);
184
+ }
185
+ }
186
+ function hasNestedTemplateLiteralExpression(source) {
187
+ let inString = null;
188
+ let escaped = false;
189
+ const templateStack = [];
190
+ for (let index = 0; index < source.length; index += 1) {
191
+ const char = source[index];
192
+ const next = source[index + 1] || "";
193
+ if (escaped) {
194
+ escaped = false;
195
+ continue;
196
+ }
197
+ if (char === "\\") {
198
+ escaped = true;
199
+ continue;
200
+ }
201
+ if (inString === "'" || inString === '"') {
202
+ if (char === inString) inString = null;
203
+ continue;
204
+ }
205
+ if (inString === "`") {
206
+ const current = templateStack[templateStack.length - 1];
207
+ if (char === "`") {
208
+ if (current?.expressionDepth && current.expressionDepth > 0) {
209
+ return true;
210
+ }
211
+ templateStack.pop();
212
+ if (templateStack.length === 0) inString = null;
213
+ continue;
214
+ }
215
+ if (char === "$" && next === "{") {
216
+ if (current) current.expressionDepth += 1;
217
+ index += 1;
218
+ continue;
219
+ }
220
+ if (char === "}" && current?.expressionDepth) {
221
+ current.expressionDepth -= 1;
222
+ }
223
+ continue;
224
+ }
225
+ if (char === "'" || char === '"') {
226
+ inString = char;
227
+ continue;
228
+ }
229
+ if (char === "`") {
230
+ inString = "`";
231
+ templateStack.push({ expressionDepth: 0 });
232
+ }
63
233
  }
64
234
  return false;
65
235
  }
66
- function reviewGeneratedJobCode(code) {
236
+ function reviewGeneratedJobCode(code, _options = {}) {
67
237
  const normalized = typeof code === "string" ? code : "";
68
- if (!normalized.trim()) return [];
69
238
  const issues = [];
239
+ if (!normalized.trim()) {
240
+ return issues;
241
+ }
70
242
  if (/require\s*\(\s*['"]\.\/sandbox-tools['"]\s*\)/.test(normalized)) {
71
243
  issues.push({
72
244
  code: "commonjs_require",
73
245
  severity: "error",
74
- message: "Use ESM imports like `import { Customer, loop } from './sandbox-tools';` instead of require('./sandbox-tools'). Generated jobs must be plain runnable JavaScript for the sandbox runtime."
246
+ message: "Use ESM imports from './sandbox-tools' instead of require('./sandbox-tools')."
75
247
  });
76
248
  }
77
- const placeholderPatterns = [
78
- /ready to make the change next/i,
79
- /ready to .* next/i,
80
- /ready to .* now/i,
81
- /i can make the change now/i,
82
- /i can do that next/i,
83
- /i'?m ready to continue/i,
84
- /have your approval .* ready to make/i,
85
- /approved\./i
86
- ];
87
- if (normalized.includes("await loop.confirm(")) {
88
- const postConfirm = normalized.slice(
89
- normalized.indexOf("await loop.confirm(")
90
- );
91
- const hasPlaceholder = placeholderPatterns.some(
92
- (pattern) => pattern.test(postConfirm)
93
- );
94
- const hasSubstantiveAwait = hasSubstantiveAwaitAfterPrompt(
95
- normalized,
96
- "await loop.confirm("
97
- );
98
- if (!hasSubstantiveAwait || hasPlaceholder) {
99
- issues.push({
100
- code: "placeholder_after_confirm",
101
- severity: "error",
102
- 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.'"
103
- });
104
- }
249
+ if (/\bprocess\.exit\s*\(/.test(normalized)) {
250
+ issues.push({
251
+ code: "process_exit",
252
+ severity: "error",
253
+ message: "Generated jobs must not call process.exit(...). Return from the job or emit a runtime message instead."
254
+ });
105
255
  }
106
- if (normalized.includes("await loop.ask_user(")) {
107
- const postPrompt = normalized.slice(
108
- normalized.indexOf("await loop.ask_user(")
109
- );
110
- const hasPlaceholder = placeholderPatterns.some(
111
- (pattern) => pattern.test(postPrompt)
112
- );
113
- const hasSubstantiveAwait = hasSubstantiveAwaitAfterPrompt(
114
- normalized,
115
- "await loop.ask_user("
116
- );
117
- if (hasPlaceholder && !hasSubstantiveAwait) {
118
- issues.push({
119
- code: "placeholder_after_ask_user",
120
- severity: "error",
121
- message: "After await loop.ask_user(...) returns a usable answer, continue the workflow in the same resumed run instead of stopping with placeholder text about doing the work later."
122
- });
123
- }
256
+ if (/\bawait\s+import\s*\(\s*['"]\.\/sandbox-tools['"]\s*\)/.test(normalized)) {
257
+ issues.push({
258
+ code: "dynamic_import_in_job",
259
+ severity: "error",
260
+ message: "Import sandbox tools with a static top-level import from './sandbox-tools'; do not use dynamic import for runtime tools."
261
+ });
124
262
  }
125
- const hasConversationalReturn = /return\s+[`'"]/.test(normalized) || /\breply\s*:/.test(normalized) || /\bagent_message\s*\(/.test(normalized) || /\bagent_text_message\s*\(/.test(normalized);
126
- const returnsObjectLiteral = /return\s+\{[\s\S]*?\}/.test(normalized);
127
- const returnsShowPayload = /return\s+\{[\s\S]*?\bshow\s*:/.test(normalized);
128
- const closesLoop = /loop\.close_loop\s*\(/.test(normalized);
129
- if (!hasConversationalReturn && returnsObjectLiteral && !closesLoop) {
263
+ if (hasNestedTemplateLiteralExpression(normalized)) {
130
264
  issues.push({
131
- code: "missing_user_reply",
265
+ code: "nested_template_literal_in_job",
132
266
  severity: "error",
133
- message: "User-facing jobs must end with a natural-language answer. Return a short string, an object with a top-level `reply` string, or post text with agent_text_message(...). Do not end with bare structured JSON."
267
+ message: "Avoid nested template literals inside template expressions. Precompute conditional text in variables or use simpler string construction."
134
268
  });
135
269
  }
136
- if (returnsShowPayload) {
270
+ const syntaxError = getGeneratedJobSyntaxError(normalized);
271
+ if (syntaxError) {
137
272
  issues.push({
138
- code: "return_show_not_for_ui",
273
+ code: "syntax_error_in_job",
139
274
  severity: "error",
140
- message: "Do not use the final return value to send UI record refs through `show`. Use agent_heap_objects(...) for heap-backed UI, then return plain text if you still want a final textual answer."
275
+ message: `The generated job has a JavaScript syntax error before runtime execution: ${syntaxError}.`
276
+ });
277
+ }
278
+ if (/[\u2018-\u201F]/.test(normalized)) {
279
+ issues.push({
280
+ code: "syntax_error_in_job",
281
+ severity: "error",
282
+ message: "Use plain ASCII quotes and apostrophes in generated job strings."
283
+ });
284
+ }
285
+ const undefinedTemplateIdentifier = findUndefinedSimpleTemplateIdentifier(normalized);
286
+ if (undefinedTemplateIdentifier) {
287
+ issues.push({
288
+ code: "undefined_template_identifier",
289
+ severity: "error",
290
+ message: `The template literal references \`${undefinedTemplateIdentifier}\`, but that identifier is not declared in the generated job.`
291
+ });
292
+ }
293
+ if (/\{\s*\.\.\.[A-Za-z_$][\w$]*/.test(normalized)) {
294
+ issues.push({
295
+ code: "object_spread_in_job",
296
+ severity: "error",
297
+ message: "Avoid object spread in generated jobs until the backend runtime transform can validate it structurally."
298
+ });
299
+ }
300
+ if (/\bloop\./.test(normalized) && !/import\s*\{[^}]*\bloop\b[^}]*\}\s*from\s*['"]\.\/sandbox-tools['"]/.test(
301
+ normalized
302
+ )) {
303
+ issues.push({
304
+ code: "missing_loop_import",
305
+ severity: "error",
306
+ message: "The job calls loop.* but does not import loop from './sandbox-tools'."
307
+ });
308
+ }
309
+ const bareLoopHelperImport = normalized.match(
310
+ /import\s*\{[^}]*\b(ask_user|confirm|open_decision|close_decision|create_task|update_task|complete_task|close_loop)\b[^}]*\}\s*from\s*['"]\.\/sandbox-tools['"]/
311
+ );
312
+ if (bareLoopHelperImport) {
313
+ issues.push({
314
+ code: "bare_loop_helper_import",
315
+ severity: "error",
316
+ 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."
317
+ });
318
+ }
319
+ if (/\bloop\.open_decision\s*\(\s*\{[\s\S]*?\boptions\s*:/.test(normalized)) {
320
+ issues.push({
321
+ code: "loop_helper_contract",
322
+ severity: "error",
323
+ message: "loop.open_decision(...) must use `candidates: [...]`, not `options: [...]`. Every candidate must include a string `id`."
324
+ });
325
+ }
326
+ if (/\bloop\.close_decision\s*\(\s*\{[\s\S]*?\bselected\s*:/.test(normalized)) {
327
+ issues.push({
328
+ code: "loop_helper_contract",
329
+ severity: "error",
330
+ message: "loop.close_decision(...) must use `selectedId`, not `selected`."
331
+ });
332
+ }
333
+ if (/\bloop\.(?:create_task|update_task|complete_task)\s*\(\s*\{[\s\S]*?\bid\s*:/.test(
334
+ normalized
335
+ )) {
336
+ issues.push({
337
+ code: "loop_helper_contract",
338
+ severity: "error",
339
+ message: "Loop task helpers must use `taskId`, not `id`, for explicit task identifiers."
340
+ });
341
+ }
342
+ if (/\bconsole\.log\s*\(\s*JSON\.stringify\s*\(\s*\{[\s\S]*?\b(?:action|reply|code)\s*:/.test(
343
+ normalized
344
+ )) {
345
+ issues.push({
346
+ code: "stdout_json_reply",
347
+ severity: "error",
348
+ message: "Do not print JSON chat envelopes from generated jobs; use runtime messaging or return a plain result."
349
+ });
350
+ }
351
+ if (/\breturn\s+\{[\s\S]*?\baction\s*:\s*['"]reply['"][\s\S]*?\breply\s*:/.test(
352
+ normalized
353
+ )) {
354
+ issues.push({
355
+ code: "return_chat_payload",
356
+ severity: "error",
357
+ message: "Do not return chat envelopes like { action, reply, code } from generated jobs; return a plain value or use runtime messaging."
141
358
  });
142
359
  }
143
360
  return issues;
@@ -196,15 +413,40 @@ function collectConversationReferents(liveDoc) {
196
413
  const ts = Number(message.ts) || 0;
197
414
  const messageId = typeof message.id === "string" ? message.id : void 0;
198
415
  const jobId = typeof message.jobId === "string" ? message.jobId : void 0;
199
- for (const entryPath of uniqueStrings(asArray(show.entryPaths))) {
416
+ const entryPaths = uniqueStrings(asArray(show.entryPaths));
417
+ const entryClassCounts = /* @__PURE__ */ new Map();
418
+ const entryMetadata = entryPaths.map((entryPath) => {
200
419
  const entry = asRecord(entriesByPath[entryPath]);
420
+ const className = typeof entry?.className === "string" ? entry.className : void 0;
421
+ if (className) {
422
+ entryClassCounts.set(
423
+ className,
424
+ (entryClassCounts.get(className) || 0) + 1
425
+ );
426
+ }
427
+ return { entryPath, entry, className };
428
+ });
429
+ const displayGroupId = entryMetadata.length > 1 ? `message:${messageId || jobId || ts}:entries` : void 0;
430
+ for (const [
431
+ index,
432
+ { entryPath, entry, className }
433
+ ] of entryMetadata.entries()) {
201
434
  pushReferent({
202
435
  id: `entry:${entryPath}`,
203
436
  kind: "entry",
204
437
  ref: entryPath,
438
+ role: "assistant",
439
+ source: "heap_objects",
205
440
  entryPath,
206
- className: typeof entry?.className === "string" ? entry.className : void 0,
441
+ recordId: typeof entry?.id === "string" ? entry.id : void 0,
442
+ className,
207
443
  label: typeof entry?.label === "string" && entry.label.trim() ? entry.label.trim() : typeof entry?.id === "string" && entry.id.trim() ? entry.id.trim() : entryPath,
444
+ ...displayGroupId ? {
445
+ displayGroupId,
446
+ displayGroupIndex: index,
447
+ displayGroupSize: entryMetadata.length,
448
+ ...className && (entryClassCounts.get(className) || 0) > 1 ? { displayGroupSameTypeSize: entryClassCounts.get(className) } : {}
449
+ } : {},
208
450
  messageId,
209
451
  jobId,
210
452
  ts
@@ -216,6 +458,8 @@ function collectConversationReferents(liveDoc) {
216
458
  id: `list:${listName}`,
217
459
  kind: "list",
218
460
  ref: listName,
461
+ role: "assistant",
462
+ source: "heap_objects",
219
463
  listName,
220
464
  className: typeof list?.className === "string" ? list.className : void 0,
221
465
  count: Array.isArray(list?.paths) ? list.paths.length : null,
@@ -236,9 +480,12 @@ function collectConversationReferents(liveDoc) {
236
480
  id: `variable:${variableName}`,
237
481
  kind: "variable",
238
482
  ref: variableName,
483
+ role: "assistant",
484
+ source: "heap_objects",
239
485
  variableName,
240
486
  variableKind: typeof variable?.kind === "string" ? variable.kind : void 0,
241
487
  entryPath,
488
+ recordId: typeof entry?.id === "string" ? entry.id : void 0,
242
489
  listName,
243
490
  className: typeof variable?.className === "string" ? variable.className : typeof entry?.className === "string" ? entry.className : typeof list?.className === "string" ? list.className : void 0,
244
491
  label: typeof entry?.label === "string" && entry.label.trim() ? entry.label.trim() : typeof entry?.id === "string" && entry.id.trim() ? entry.id.trim() : null,
@@ -259,18 +506,24 @@ function projectConversationReferentFocus(liveDoc) {
259
506
  const entryPaths = [];
260
507
  const listNames = [];
261
508
  const variableNames = [];
262
- for (const referent of referents.slice(0, 8)) {
263
- if (referent.kind === "entry" && typeof referent.entryPath === "string") {
509
+ let entryCount = 0;
510
+ let listCount = 0;
511
+ let variableCount = 0;
512
+ for (const referent of referents) {
513
+ if (referent.kind === "entry" && typeof referent.entryPath === "string" && entryCount < 8) {
514
+ entryCount += 1;
264
515
  entryPaths.push(referent.entryPath);
265
516
  continue;
266
517
  }
267
- if (referent.kind === "list" && typeof referent.listName === "string") {
518
+ if (referent.kind === "list" && typeof referent.listName === "string" && listCount < 4) {
519
+ listCount += 1;
268
520
  listNames.push(referent.listName);
269
521
  const list = asRecord(listsByName[referent.listName]);
270
522
  entryPaths.push(...asArray(list?.paths).slice(0, 4));
271
523
  continue;
272
524
  }
273
- if (referent.kind === "variable" && typeof referent.variableName === "string") {
525
+ if (referent.kind === "variable" && typeof referent.variableName === "string" && variableCount < 4) {
526
+ variableCount += 1;
274
527
  variableNames.push(referent.variableName);
275
528
  if (typeof referent.entryPath === "string") {
276
529
  entryPaths.push(referent.entryPath);
@@ -288,61 +541,91 @@ function projectConversationReferentFocus(liveDoc) {
288
541
  variableNames: uniqueStrings(variableNames, 4)
289
542
  };
290
543
  }
291
- function projectConversationReferentSummary(liveDoc) {
292
- const referents = collectConversationReferents(liveDoc).slice(0, 8);
293
- if (referents.length === 0) {
294
- return "No recent referents recorded from prior assistant replies.";
295
- }
296
- const entryLines = [];
297
- const listLines = [];
298
- const variableLines = [];
544
+ function selectConversationReferentsForPrompt(referents) {
545
+ const selected = [];
546
+ const seen = /* @__PURE__ */ new Set();
547
+ let entryCount = 0;
548
+ let listCount = 0;
549
+ let variableCount = 0;
299
550
  for (const referent of referents) {
551
+ if (!referent.kind || !referent.ref) continue;
552
+ const key = `${referent.kind}:${referent.ref}`;
553
+ if (seen.has(key)) continue;
554
+ if (referent.kind === "entry") {
555
+ if (entryCount >= 8) continue;
556
+ entryCount += 1;
557
+ } else if (referent.kind === "list") {
558
+ if (listCount >= 4) continue;
559
+ listCount += 1;
560
+ } else if (referent.kind === "variable") {
561
+ if (variableCount >= 4) continue;
562
+ variableCount += 1;
563
+ }
564
+ seen.add(key);
565
+ selected.push(referent);
566
+ }
567
+ return selected;
568
+ }
569
+ function projectConversationReferentSummary(liveDoc) {
570
+ const referents = selectConversationReferentsForPrompt(
571
+ collectConversationReferents(liveDoc)
572
+ );
573
+ const compact = referents.map((referent) => {
300
574
  if (referent.kind === "entry" && referent.entryPath) {
301
- const label = referent.label || referent.entryPath;
302
- const classLabel = referent.className || "unknown";
303
- entryLines.push(`- ${label} <${referent.entryPath}> [${classLabel}]`);
304
- continue;
575
+ return {
576
+ kind: "entry",
577
+ role: referent.role || null,
578
+ source: referent.source || null,
579
+ path: referent.entryPath,
580
+ id: referent.recordId || null,
581
+ type: referent.className || "unknown",
582
+ label: referent.label || referent.entryPath,
583
+ group: referent.displayGroupId ? {
584
+ id: referent.displayGroupId,
585
+ index: typeof referent.displayGroupIndex === "number" ? referent.displayGroupIndex : null,
586
+ size: typeof referent.displayGroupSize === "number" ? referent.displayGroupSize : null,
587
+ sameTypeSize: typeof referent.displayGroupSameTypeSize === "number" ? referent.displayGroupSameTypeSize : null
588
+ } : void 0
589
+ };
590
+ }
591
+ if (referent.kind === "entry" && referent.recordId) {
592
+ return {
593
+ kind: "entry",
594
+ role: referent.role || null,
595
+ source: referent.source || null,
596
+ id: referent.recordId,
597
+ type: referent.className || "unknown",
598
+ label: referent.label || referent.recordId
599
+ };
305
600
  }
306
601
  if (referent.kind === "list" && referent.listName) {
307
- const classLabel = referent.className || "unknown";
308
- const countLabel = typeof referent.count === "number" ? referent.count : "?";
309
- listLines.push(
310
- `- ${referent.listName}: list<${classLabel}> -> ${countLabel} item(s)`
311
- );
312
- continue;
602
+ return {
603
+ kind: "list",
604
+ role: referent.role || null,
605
+ source: referent.source || null,
606
+ name: referent.listName,
607
+ type: referent.className || "unknown",
608
+ count: typeof referent.count === "number" ? referent.count : null
609
+ };
313
610
  }
314
611
  if (referent.kind === "variable" && referent.variableName) {
315
- if (referent.variableKind === "entry" && referent.entryPath && referent.className) {
316
- const label = referent.label || referent.entryPath;
317
- variableLines.push(
318
- `- ${referent.variableName}: entry<${referent.className}> -> ${label} <${referent.entryPath}>`
319
- );
320
- continue;
321
- }
322
- if (referent.variableKind === "list" && referent.listName && referent.className) {
323
- const countLabel = typeof referent.count === "number" ? referent.count : "?";
324
- variableLines.push(
325
- `- ${referent.variableName}: list<${referent.className}> -> ${countLabel} item(s) via ${referent.listName}`
326
- );
327
- continue;
328
- }
329
- if (referent.variableKind === "scalar") {
330
- variableLines.push(
331
- `- ${referent.variableName}: scalar = ${formatScalar(referent.scalarValue)}`
332
- );
333
- continue;
334
- }
335
- variableLines.push(`- ${referent.variableName}`);
612
+ return {
613
+ kind: "variable",
614
+ role: referent.role || null,
615
+ source: referent.source || null,
616
+ name: referent.variableName,
617
+ valueKind: referent.variableKind || null,
618
+ type: referent.className || null,
619
+ path: referent.entryPath || null,
620
+ list: referent.listName || null,
621
+ label: referent.label || null,
622
+ count: typeof referent.count === "number" ? referent.count : null,
623
+ value: referent.variableKind === "scalar" ? referent.scalarValue ?? null : void 0
624
+ };
336
625
  }
337
- }
338
- const lines = [];
339
- lines.push("Entries:");
340
- lines.push(...entryLines.length > 0 ? entryLines : ["- none"]);
341
- lines.push("", "Lists:");
342
- lines.push(...listLines.length > 0 ? listLines : ["- none"]);
343
- lines.push("", "Variables:");
344
- lines.push(...variableLines.length > 0 ? variableLines : ["- none"]);
345
- return lines.join("\n");
626
+ return null;
627
+ }).filter(Boolean);
628
+ return renderConstBlock("recentReferences", compact);
346
629
  }
347
630
  function getCurrentClosureId(liveDoc) {
348
631
  const loop = asRecord(liveDoc?.loop);
@@ -563,56 +846,24 @@ function projectWorkflowFocus(liveDoc, pendingPrompts = [], options) {
563
846
  }
564
847
  function projectWorkflowSummary(liveDoc, pendingPrompts = [], options) {
565
848
  const focus = projectWorkflowFocus(liveDoc, pendingPrompts, options);
566
- const lines = [];
567
- lines.push("Workflow Boundary:");
568
- if (focus.boundaryReason === "request_start") {
569
- lines.push(
570
- "- Start from work recorded after the current user request began."
571
- );
572
- } else if (focus.boundaryReason === "last_closed_loop" && focus.latestClosureId) {
573
- lines.push(`- Start from work recorded after ${focus.latestClosureId}.`);
574
- } else {
575
- lines.push(
576
- "- No prior closed loop recorded; use the latest user request as the boundary."
577
- );
578
- }
579
- lines.push("", "Recent Actions:");
580
- if (focus.recentActionSummary.length === 0) {
581
- lines.push("- none");
582
- } else {
583
- for (const line of focus.recentActionSummary) {
584
- lines.push(line.startsWith("- ") ? line : `- ${line}`);
585
- }
586
- }
587
- lines.push("", "Working Set Hints:");
588
- if (focus.variableNames.length === 0 && focus.listNames.length === 0 && focus.entryPaths.length === 0) {
589
- lines.push("- none");
590
- } else {
591
- if (focus.variableNames.length > 0) {
592
- lines.push(`- variables: ${focus.variableNames.join(", ")}`);
849
+ return renderConstBlock("workflowContext", {
850
+ boundary: {
851
+ timestamp: focus.boundaryTimestamp,
852
+ reason: focus.boundaryReason,
853
+ latestClosureId: focus.latestClosureId || null
854
+ },
855
+ recentActions: focus.recentActionSummary,
856
+ workingSet: {
857
+ variables: focus.variableNames,
858
+ lists: focus.listNames,
859
+ entries: focus.entryPaths
860
+ },
861
+ openHandles: {
862
+ tasks: focus.activeTaskIds,
863
+ decisions: focus.openDecisionIds,
864
+ prompts: focus.openPromptIds
593
865
  }
594
- if (focus.listNames.length > 0) {
595
- lines.push(`- lists: ${focus.listNames.join(", ")}`);
596
- }
597
- if (focus.entryPaths.length > 0) {
598
- lines.push(`- entries: ${focus.entryPaths.join(", ")}`);
599
- }
600
- }
601
- lines.push("", "Open Workflow Handles:");
602
- if (focus.activeTaskIds.length === 0 && focus.openDecisionIds.length === 0 && focus.openPromptIds.length === 0) {
603
- lines.push("- none");
604
- } else {
605
- if (focus.activeTaskIds.length > 0) {
606
- lines.push(`- tasks: ${focus.activeTaskIds.join(", ")}`);
607
- }
608
- if (focus.openDecisionIds.length > 0) {
609
- lines.push(`- decisions: ${focus.openDecisionIds.join(", ")}`);
610
- }
611
- if (focus.openPromptIds.length > 0) {
612
- lines.push(`- prompts: ${focus.openPromptIds.join(", ")}`);
613
- }
614
- }
615
- return lines.join("\n");
866
+ });
616
867
  }
617
868
  function hasOpenPrompt(liveDoc, pendingPrompts) {
618
869
  if (pendingPrompts.length > 0) return true;
@@ -633,7 +884,6 @@ function getExclusivePromptTarget(pendingPrompts) {
633
884
  return prompt?.type === "input" ? prompt : null;
634
885
  }
635
886
  function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
636
- const lines = [];
637
887
  const loop = asRecord(liveDoc?.loop);
638
888
  const boundary = getWorkflowBoundary(liveDoc, options);
639
889
  const tasks = toSortedRecords(loop?.tasksById).filter((task) => {
@@ -655,22 +905,12 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
655
905
  5
656
906
  );
657
907
  const hiddenTaskCount = Math.max(0, activeTasks.length - visibleTasks.length);
658
- lines.push("Tasks:");
659
- if (visibleTasks.length === 0) {
660
- lines.push("- none");
661
- } else {
662
- lines.push("- Reuse existing taskId values exactly as written below.");
663
- for (const task of visibleTasks) {
664
- const title = typeof task.title === "string" ? task.title : "Untitled task";
665
- const taskId = typeof task.taskId === "string" ? task.taskId : "unknown";
666
- const status = typeof task.status === "string" ? task.status : "pending";
667
- const summary = typeof task.summary === "string" && task.summary.trim() ? ` \u2014 ${task.summary.trim()}` : "";
668
- lines.push(`- [${status}] ${title} (${taskId})${summary}`);
669
- }
670
- if (hiddenTaskCount > 0) {
671
- lines.push(`- ${hiddenTaskCount} more active task(s) omitted`);
672
- }
673
- }
908
+ const compactTasks = visibleTasks.map((task) => ({
909
+ id: typeof task.taskId === "string" ? task.taskId : "unknown",
910
+ title: typeof task.title === "string" ? task.title : "Untitled task",
911
+ status: typeof task.status === "string" ? task.status : "pending",
912
+ summary: typeof task.summary === "string" && task.summary.trim() ? task.summary.trim() : null
913
+ }));
674
914
  const decisions = toSortedRecords(loop?.decisionsById).filter((decision) => {
675
915
  const updatedAt = Number(decision.updatedAt) || Number(decision.createdAt) || 0;
676
916
  if (boundary.reason === "request_start") {
@@ -684,33 +924,29 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
684
924
  (decision) => decision.status === "open"
685
925
  );
686
926
  const visibleDecisions = (openDecisions.length > 0 ? openDecisions : decisions.slice(0, 1)).slice(0, 3);
687
- lines.push("", "Recent Decisions:");
688
- if (visibleDecisions.length === 0) {
689
- lines.push("- none");
690
- } else {
691
- lines.push("- Reuse existing decisionId values exactly as written below.");
692
- for (const decision of visibleDecisions) {
693
- const status = typeof decision.status === "string" ? decision.status : "resolved";
694
- const title = typeof decision.title === "string" && decision.title.trim() ? decision.title.trim() : "Decision";
695
- const decisionId = typeof decision.decisionId === "string" ? decision.decisionId : "unknown";
696
- if (status === "open") {
697
- const candidatePreview = asArray(decision.candidates).slice(0, 3).map((candidate) => {
698
- const record = asRecord(candidate);
699
- if (!record) return null;
700
- const candidateId = typeof record.id === "string" ? record.id : "unknown";
701
- const candidateLabel = typeof record.label === "string" && record.label.trim() ? record.label.trim() : candidateId;
702
- return candidateLabel === candidateId ? candidateId : `${candidateLabel} (${candidateId})`;
703
- }).filter((value) => Boolean(value)).join(", ");
704
- lines.push(
705
- `- [open] ${title} (${decisionId})${candidatePreview ? ` \u2014 candidates: ${candidatePreview}` : ""}`
706
- );
707
- } else {
708
- const selected = asRecord(decision.selected);
709
- const label = typeof selected?.label === "string" ? selected.label : typeof selected?.id === "string" ? selected.id : "unknown";
710
- lines.push(`- [resolved] ${title} (${decisionId}) -> ${label}`);
927
+ const compactDecisions = visibleDecisions.map((decision) => {
928
+ const status = typeof decision.status === "string" ? decision.status : "resolved";
929
+ const selected = asRecord(decision.selected);
930
+ return {
931
+ id: typeof decision.decisionId === "string" ? decision.decisionId : "unknown",
932
+ title: typeof decision.title === "string" && decision.title.trim() ? decision.title.trim() : "Decision",
933
+ status,
934
+ candidates: status === "open" ? asArray(decision.candidates).slice(0, 5).map((candidate) => {
935
+ const record = asRecord(candidate);
936
+ if (!record) return null;
937
+ return {
938
+ id: typeof record.id === "string" ? record.id : "unknown",
939
+ label: typeof record.label === "string" && record.label.trim() ? record.label.trim() : null,
940
+ description: typeof record.description === "string" && record.description.trim() ? record.description.trim() : null,
941
+ metadata: asRecord(record.metadata)
942
+ };
943
+ }).filter(Boolean) : [],
944
+ selected: status === "open" ? null : {
945
+ id: typeof selected?.id === "string" ? selected.id : null,
946
+ label: typeof selected?.label === "string" ? selected.label : null
711
947
  }
712
- }
713
- }
948
+ };
949
+ });
714
950
  const openPrompts = [
715
951
  ...pendingPrompts.map((prompt) => ({
716
952
  id: prompt.id,
@@ -730,29 +966,29 @@ function projectLoopSummary(liveDoc, pendingPrompts = [], options) {
730
966
  (pendingPrompt) => pendingPrompt.id === promptId
731
967
  ) : false);
732
968
  }) : openPrompts;
733
- lines.push("", "Open Prompts:");
734
- if (visiblePrompts.length === 0) {
735
- lines.push("- none");
736
- } else {
737
- for (const prompt of visiblePrompts.slice(0, 3)) {
738
- const title = typeof prompt.title === "string" && prompt.title.trim() ? prompt.title.trim() : "Input required";
739
- const type = typeof prompt.type === "string" ? prompt.type : "input";
740
- const message = typeof prompt.message === "string" && prompt.message.trim() ? ` \u2014 ${prompt.message.trim()}` : "";
741
- lines.push(`- [${type}] ${title}${message}`);
742
- }
743
- }
969
+ const compactPrompts = visiblePrompts.slice(0, 3).map((prompt) => {
970
+ const promptRecord = asRecord(prompt) || {};
971
+ return {
972
+ id: typeof promptRecord.id === "string" ? promptRecord.id : typeof promptRecord.promptId === "string" ? promptRecord.promptId : null,
973
+ type: typeof promptRecord.type === "string" ? promptRecord.type : "input",
974
+ title: typeof promptRecord.title === "string" && promptRecord.title.trim() ? promptRecord.title.trim() : "Input required",
975
+ message: typeof promptRecord.message === "string" && promptRecord.message.trim() ? promptRecord.message.trim() : null
976
+ };
977
+ });
744
978
  const currentClosureId = getCurrentClosureId(liveDoc);
745
979
  const closureRecord = currentClosureId ? asRecord(asRecord(loop?.closuresById)?.[currentClosureId]) : null;
746
980
  const visibleClosure = closureRecord && (boundary.reason !== "request_start" || (Number(closureRecord.createdAt) || 0) >= boundary.timestamp) ? closureRecord : null;
747
- lines.push("", "Loop Closure:");
748
- if (visibleClosure) {
749
- const status = typeof visibleClosure.status === "string" ? visibleClosure.status : "completed";
750
- const summary = typeof visibleClosure.summary === "string" ? visibleClosure.summary : "No summary";
751
- lines.push(`- current: [${status}] ${summary} (${currentClosureId})`);
752
- } else {
753
- lines.push("- none");
754
- }
755
- return lines.join("\n");
981
+ return renderConstBlock("workflowState", {
982
+ tasks: compactTasks,
983
+ hiddenActiveTaskCount: hiddenTaskCount,
984
+ decisions: compactDecisions,
985
+ openPrompts: compactPrompts,
986
+ closure: visibleClosure ? {
987
+ id: currentClosureId,
988
+ status: typeof visibleClosure.status === "string" ? visibleClosure.status : "completed",
989
+ summary: typeof visibleClosure.summary === "string" ? visibleClosure.summary : null
990
+ } : null
991
+ });
756
992
  }
757
993
  function projectHeapSummary(heap, options) {
758
994
  const heapRecord = asRecord(heap) || {};
@@ -797,55 +1033,72 @@ function projectHeapSummary(heap, options) {
797
1033
  referencedPaths.add(path);
798
1034
  }
799
1035
  const visibleLists = Object.values(listsByName).map((value) => asRecord(value)).filter((value) => Boolean(value)).filter(
800
- (list) => variables.some((variable) => variable.listName === list.name) || Boolean(list.name && focusedListNames.has(list.name))
1036
+ (list) => variables.some(
1037
+ (variable) => Boolean(variable?.listName === list.name)
1038
+ ) || Boolean(list.name && focusedListNames.has(list.name))
801
1039
  ).sort((left, right) => (right.updatedAt || 0) - (left.updatedAt || 0)).slice(0, maxLists);
802
1040
  const visibleEntries = Object.values(entriesByPath).map((value) => asRecord(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);
803
- const lines = [];
804
- lines.push("Variables:");
805
- if (variables.length === 0) {
806
- lines.push("- none");
807
- } else {
808
- for (const variable of variables) {
809
- if (variable.kind === "scalar") {
810
- lines.push(
811
- `- ${variable.name}: scalar = ${formatScalar(variable.value)}`
812
- );
813
- continue;
814
- }
815
- if (variable.kind === "entry") {
816
- const entry = variable.entryPath ? asRecord(
817
- entriesByPath[variable.entryPath]
818
- ) : null;
819
- lines.push(
820
- `- ${variable.name}: entry<${variable.className || entry?.className || "unknown"}> -> ${entry ? describeHeapEntry(entry) : variable.entryPath || "missing"}`
821
- );
822
- continue;
823
- }
824
- const list = variable.listName ? asRecord(listsByName[variable.listName]) : null;
825
- lines.push(
826
- `- ${variable.name}: list<${variable.className || list?.className || "unknown"}> -> ${(list?.paths || []).length} item(s)`
827
- );
828
- }
829
- }
830
- lines.push("", "Named Lists:");
831
- if (visibleLists.length === 0) {
832
- lines.push("- none");
833
- } else {
834
- for (const list of visibleLists) {
835
- lines.push(
836
- `- ${list.name}: ${list.className || "unknown"}[${(list.paths || []).length}]`
837
- );
838
- }
839
- }
840
- lines.push("", "Active Entries:");
841
- if (visibleEntries.length === 0) {
842
- lines.push("- none");
843
- } else {
844
- for (const entry of visibleEntries) {
845
- lines.push(`- ${describeHeapEntry(entry)}`);
846
- }
847
- }
848
- return lines.join("\n");
1041
+ return renderConstBlock("savedData", {
1042
+ variables: Object.fromEntries(
1043
+ variables.filter((variable) => typeof variable.name === "string").map((variable) => {
1044
+ if (variable.kind === "scalar") {
1045
+ return [
1046
+ variable.name,
1047
+ { kind: "scalar", value: variable.value ?? null }
1048
+ ];
1049
+ }
1050
+ if (variable.kind === "entry") {
1051
+ const entry = variable.entryPath ? asRecord(
1052
+ entriesByPath[variable.entryPath]
1053
+ ) : null;
1054
+ return [
1055
+ variable.name,
1056
+ {
1057
+ kind: "entry",
1058
+ type: variable.className || entry?.className || "unknown",
1059
+ path: variable.entryPath || null,
1060
+ label: entry?.label || entry?.id || null
1061
+ }
1062
+ ];
1063
+ }
1064
+ const list = variable.listName ? asRecord(listsByName[variable.listName]) : null;
1065
+ return [
1066
+ variable.name,
1067
+ {
1068
+ kind: "list",
1069
+ type: variable.className || list?.className || "unknown",
1070
+ list: variable.listName || null,
1071
+ count: (list?.paths || []).length
1072
+ }
1073
+ ];
1074
+ })
1075
+ ),
1076
+ lists: Object.fromEntries(
1077
+ visibleLists.filter((list) => typeof list.name === "string").map((list) => [
1078
+ list.name,
1079
+ {
1080
+ type: list.className || "unknown",
1081
+ count: (list.paths || []).length
1082
+ }
1083
+ ])
1084
+ ),
1085
+ entries: Object.fromEntries(
1086
+ visibleEntries.filter((entry) => typeof entry.path === "string").map((entry) => [
1087
+ entry.path,
1088
+ {
1089
+ type: entry.className || "unknown",
1090
+ id: entry.id || null,
1091
+ label: entry.label || entry.id || null,
1092
+ fields: asArray(entry.fields).filter(
1093
+ (field) => field?.name && field.name !== "_realId" && field.name !== "real_id"
1094
+ ).slice(0, 3).map((field) => ({
1095
+ name: field.name,
1096
+ value: field.value ?? null
1097
+ }))
1098
+ }
1099
+ ])
1100
+ )
1101
+ });
849
1102
  }
850
1103
  function createHarnessVerifierSnapshot(input) {
851
1104
  const workflowFocus = projectWorkflowFocus(
@@ -942,8 +1195,8 @@ function buildContinuationInstruction(resultPreview) {
942
1195
  "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.",
943
1196
  "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.",
944
1197
  "If this request clearly spans multiple steps and there are no active tasks yet, create 2-4 short user-visible tasks now.",
945
- "Reuse any existing taskId and decisionId values exactly as they appear in AGENT LOOP STATE.",
946
- "When progress depends on the user's choice, missing detail, or approval, use loop.ask_user(...) or loop.confirm(...) so the job pauses and resumes through the live workflow.",
1198
+ "Reuse any existing taskId and decisionId values exactly as they appear in [State].",
1199
+ "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.",
947
1200
  "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.'",
948
1201
  "If you ask the user a new question in this job, do not also close the loop in the same job.",
949
1202
  "Write the smallest straightforward code for the current step. Avoid defensive fallback branches for hypothetical states that are not currently true.",
@@ -954,39 +1207,101 @@ ${resultPreview}` : null
954
1207
  ].filter(Boolean).join("\n\n");
955
1208
  }
956
1209
  function buildGranularAgentDomainBlock(domainDocumentation) {
957
- return domainDocumentation?.trim() || "No domain reference available. The graph may not be ready yet.";
1210
+ return domainDocumentation?.trim() || "No domain contract available. The graph may not be ready yet.";
958
1211
  }
959
1212
  function buildGranularAgentSessionBlock(sessionContext) {
960
- if (!sessionContext) return "No session metadata available.";
961
- const rows = [
962
- ["sandboxId", sessionContext.sandboxId],
963
- ["environmentId", sessionContext.environmentId],
964
- ["userName", sessionContext.userName]
965
- ];
966
- const activeRows = rows.filter(([, value]) => Boolean(value));
967
- if (activeRows.length === 0) return "No session metadata available.";
968
- return activeRows.map(([key, value]) => `${key}: ${value}`).join("\n");
1213
+ return renderConstBlock("session", {
1214
+ runtimeId: sessionContext?.sandboxId || null,
1215
+ environmentId: sessionContext?.environmentId || null,
1216
+ userName: sessionContext?.userName || null,
1217
+ domainRevision: sessionContext?.domainRevision || null
1218
+ });
969
1219
  }
970
1220
  function buildGranularAgentHeapBlock(heapSummary) {
971
- return heapSummary?.trim() || "Heap is empty for this session.";
1221
+ return heapSummary?.trim() || renderConstBlock("savedData", {
1222
+ variables: {},
1223
+ lists: {},
1224
+ entries: {}
1225
+ });
972
1226
  }
973
1227
  function buildGranularAgentReferentBlock(referentSummary) {
974
- return referentSummary?.trim() || "No recent referents recorded from prior assistant replies.";
1228
+ return referentSummary?.trim() || renderConstBlock("recentReferences", []);
975
1229
  }
976
1230
  function buildGranularAgentLoopBlock(loopSummary) {
977
- return loopSummary?.trim() || "No active loop state recorded for this session.";
1231
+ return loopSummary?.trim() || renderConstBlock("workflowState", {
1232
+ tasks: [],
1233
+ decisions: [],
1234
+ openPrompts: [],
1235
+ closure: null
1236
+ });
978
1237
  }
979
1238
  function buildGranularAgentWorkflowBlock(workflowSummary) {
980
- return workflowSummary?.trim() || "No current workflow snapshot recorded for this request yet.";
1239
+ return workflowSummary?.trim() || renderConstBlock("workflowContext", {
1240
+ boundary: null,
1241
+ recentActions: [],
1242
+ workingSet: {
1243
+ variables: [],
1244
+ lists: [],
1245
+ entries: []
1246
+ },
1247
+ openHandles: {
1248
+ tasks: [],
1249
+ decisions: [],
1250
+ prompts: []
1251
+ }
1252
+ });
1253
+ }
1254
+ function resolvePromptCapabilities(capabilities) {
1255
+ return {
1256
+ executeCode: capabilities?.executeCode !== false,
1257
+ readEntities: capabilities?.readEntities !== false,
1258
+ workflowHelpers: Array.isArray(capabilities?.workflowHelpers) ? capabilities.workflowHelpers : [
1259
+ "ask_user",
1260
+ "confirm",
1261
+ "open_decision",
1262
+ "close_decision",
1263
+ "create_task",
1264
+ "update_task",
1265
+ "complete_task",
1266
+ "close_loop"
1267
+ ],
1268
+ savedData: capabilities?.savedData !== false,
1269
+ showRecords: capabilities?.showRecords !== false
1270
+ };
1271
+ }
1272
+ function buildGranularAgentToolBlock(tools, capabilityOverrides) {
1273
+ const resolvedCapabilities = resolvePromptCapabilities(capabilityOverrides);
1274
+ const normalizedTools = (tools || []).filter((tool) => tool?.name).slice().sort((left, right) => {
1275
+ const leftScope = `${left.className || "global"}:${left.static ? "static" : "instance"}`;
1276
+ const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
1277
+ return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
1278
+ });
1279
+ const writeActions = normalizedTools.filter((tool) => tool.ready !== false).map((tool) => {
1280
+ const scope = tool.className ? `${tool.static ? "class" : "record"}:${tool.className}` : "global";
1281
+ return {
1282
+ name: tool.name,
1283
+ scope,
1284
+ description: tool.description?.trim() || null
1285
+ };
1286
+ });
1287
+ const capabilities = {
1288
+ executeCode: resolvedCapabilities.executeCode,
1289
+ readEntities: resolvedCapabilities.readEntities,
1290
+ writeActions,
1291
+ workflowHelpers: resolvedCapabilities.workflowHelpers,
1292
+ savedData: resolvedCapabilities.savedData,
1293
+ showRecords: resolvedCapabilities.showRecords
1294
+ };
1295
+ return renderConstBlock("capabilities", capabilities);
981
1296
  }
982
- function buildGranularAgentToolBlock(tools) {
1297
+ function buildGranularAgentActionIndex(tools) {
983
1298
  const normalizedTools = (tools || []).filter((tool) => tool?.name).slice().sort((left, right) => {
984
1299
  const leftScope = `${left.className || "global"}:${left.static ? "static" : "instance"}`;
985
1300
  const rightScope = `${right.className || "global"}:${right.static ? "static" : "instance"}`;
986
1301
  return leftScope.localeCompare(rightScope) || left.name.localeCompare(right.name);
987
1302
  });
988
1303
  if (normalizedTools.length === 0) {
989
- return "No live effects are available in this session yet.";
1304
+ return "No domain write actions are available.";
990
1305
  }
991
1306
  const globalTools = normalizedTools.filter((tool) => !tool.className);
992
1307
  const staticTools = normalizedTools.filter(
@@ -995,9 +1310,7 @@ function buildGranularAgentToolBlock(tools) {
995
1310
  const instanceTools = normalizedTools.filter(
996
1311
  (tool) => Boolean(tool.className && !tool.static)
997
1312
  );
998
- const lines = [
999
- "Treat this block as the planning map. Use DOMAIN REFERENCE below for exact signatures and query examples."
1000
- ];
1313
+ const lines = ["Available actions by scope:"];
1001
1314
  const appendGroup = (title, group) => {
1002
1315
  lines.push(`- ${title}:`);
1003
1316
  if (group.length === 0) {
@@ -1006,189 +1319,468 @@ function buildGranularAgentToolBlock(tools) {
1006
1319
  }
1007
1320
  for (const tool of group.slice(0, 10)) {
1008
1321
  const availability = tool.ready === false ? " [not ready]" : "";
1322
+ const schema = formatActionSchemaSummary(tool);
1009
1323
  const description = tool.description?.trim() ? ` - ${tool.description.trim()}` : "";
1010
- lines.push(` ${tool.name}${availability}${description}`);
1324
+ lines.push(` ${tool.name}${availability}${schema}${description}`);
1011
1325
  }
1012
1326
  if (group.length > 10) {
1013
1327
  lines.push(` +${group.length - 10} more`);
1014
1328
  }
1015
1329
  };
1016
- appendGroup("Global effects", globalTools);
1017
- appendGroup("Class-level effects", staticTools);
1018
- appendGroup("Record-level effects", instanceTools);
1330
+ appendGroup("Global", globalTools);
1331
+ appendGroup("Class-level", staticTools);
1332
+ appendGroup("Record-level", instanceTools);
1019
1333
  return lines.join("\n");
1020
1334
  }
1021
- function buildGranularAgentCheckpointBlock(checkpoint) {
1022
- if (!checkpoint) {
1023
- return "No previous execution checkpoint recorded for this request yet.";
1024
- }
1025
- const lines = [];
1026
- if (typeof checkpoint.iteration === "number") {
1027
- lines.push(`iteration: ${checkpoint.iteration}`);
1335
+ function normalizeJsonSchema(value) {
1336
+ if (typeof value === "string") {
1337
+ try {
1338
+ return asRecord(JSON.parse(value));
1339
+ } catch {
1340
+ return null;
1341
+ }
1028
1342
  }
1029
- if (checkpoint.latestJobStatus) {
1030
- lines.push(`latestJobStatus: ${checkpoint.latestJobStatus}`);
1343
+ return asRecord(value);
1344
+ }
1345
+ function jsonSchemaTypeName(schema) {
1346
+ const record = normalizeJsonSchema(schema);
1347
+ if (!record) return "unknown";
1348
+ const type = record.type;
1349
+ if (typeof type === "string") {
1350
+ if (type === "array") return "array";
1351
+ if (type === "object") return "object";
1352
+ return type;
1031
1353
  }
1032
- if (checkpoint.controllerOutcome) {
1033
- lines.push(`controllerOutcome: ${checkpoint.controllerOutcome}`);
1354
+ return "unknown";
1355
+ }
1356
+ function summarizeObjectSchema(schema) {
1357
+ const record = normalizeJsonSchema(schema);
1358
+ const properties = asRecord(record?.properties);
1359
+ if (!properties || Object.keys(properties).length === 0) {
1360
+ return record ? "{}" : null;
1034
1361
  }
1035
- if (checkpoint.controllerReason) {
1036
- lines.push(`controllerReason: ${checkpoint.controllerReason}`);
1362
+ const required = new Set(asArray(record?.required));
1363
+ const fields = Object.entries(properties).slice(0, 8).map(([name, property]) => {
1364
+ const marker = required.has(name) ? "*" : "?";
1365
+ return `${name}${marker}: ${jsonSchemaTypeName(property)}`;
1366
+ });
1367
+ const remaining = Object.keys(properties).length - fields.length;
1368
+ return remaining > 0 ? `${fields.join(", ")}, +${remaining}` : fields.join(", ");
1369
+ }
1370
+ function formatActionSchemaSummary(tool) {
1371
+ const input = summarizeObjectSchema(tool.inputSchema);
1372
+ const output = summarizeObjectSchema(tool.outputSchema);
1373
+ const parts = [];
1374
+ if (input) parts.push(`input { ${input} }`);
1375
+ if (output) parts.push(`output { ${output} }`);
1376
+ return parts.length ? ` (${parts.join("; ")})` : "";
1377
+ }
1378
+ function splitDomainDocumentation(domainDocumentation) {
1379
+ const normalized = domainDocumentation?.trim() || "";
1380
+ if (!normalized) return { types: "", docs: "" };
1381
+ const docsSectionMatch = normalized.match(/\n\s*\[Docs\]\s*\n/i);
1382
+ if (docsSectionMatch?.index !== void 0) {
1383
+ return {
1384
+ types: normalized.slice(0, docsSectionMatch.index).trim(),
1385
+ docs: normalized.slice(docsSectionMatch.index + docsSectionMatch[0].length).trim()
1386
+ };
1037
1387
  }
1038
- if (typeof checkpoint.noProgressCount === "number") {
1039
- lines.push(`noProgressCount: ${checkpoint.noProgressCount}`);
1388
+ const legacyMarker = "Generated usage notes from ./sandbox-tools docs:";
1389
+ const legacyIndex = normalized.indexOf(legacyMarker);
1390
+ if (legacyIndex !== -1) {
1391
+ return {
1392
+ types: normalized.slice(0, legacyIndex).trim(),
1393
+ docs: normalized.slice(legacyIndex + legacyMarker.length).trim()
1394
+ };
1040
1395
  }
1041
- if (checkpoint.latestJobError?.trim()) {
1042
- lines.push(`latestJobError: ${checkpoint.latestJobError.trim()}`);
1396
+ return { types: normalized, docs: "" };
1397
+ }
1398
+ function buildGranularAgentCheckpointBlock(checkpoint) {
1399
+ if (!checkpoint) {
1400
+ return renderConstBlock("previousCodeResult", null);
1043
1401
  }
1044
- if (Array.isArray(checkpoint.latestActionSummary) && checkpoint.latestActionSummary.length > 0) {
1045
- lines.push("latestActionSummary:");
1046
- for (const line of checkpoint.latestActionSummary.slice(0, 8)) {
1047
- const normalizedLine = normalizeActionSummaryForPrompt(line);
1048
- lines.push(
1049
- normalizedLine.startsWith("- ") ? normalizedLine : `- ${normalizedLine}`
1050
- );
1402
+ return renderConstBlock("previousCodeResult", {
1403
+ iteration: typeof checkpoint.iteration === "number" ? checkpoint.iteration : null,
1404
+ latestJobStatus: checkpoint.latestJobStatus || null,
1405
+ controllerOutcome: checkpoint.controllerOutcome || null,
1406
+ controllerReason: checkpoint.controllerReason || null,
1407
+ noProgressCount: typeof checkpoint.noProgressCount === "number" ? checkpoint.noProgressCount : null,
1408
+ latestJobError: checkpoint.latestJobError?.trim() || null,
1409
+ latestActionSummary: Array.isArray(checkpoint.latestActionSummary) ? checkpoint.latestActionSummary.slice(0, 8).map(normalizeActionSummaryForPrompt) : [],
1410
+ latestJobResult: checkpoint.latestJobResult?.trim() || null
1411
+ });
1412
+ }
1413
+ function parseSummaryOutcome(summary) {
1414
+ const outcome = {};
1415
+ for (const part of summary.split(",")) {
1416
+ const trimmed = part.trim();
1417
+ const match = /^([A-Za-z0-9_]+)=(.+)$/.exec(trimmed);
1418
+ if (!match) continue;
1419
+ const [, key, rawValue] = match;
1420
+ const unquoted = rawValue.replace(/^"|"$/g, "");
1421
+ if (/^-?\d+(?:\.\d+)?$/.test(unquoted)) {
1422
+ outcome[key] = Number(unquoted);
1423
+ } else if (unquoted === "true" || unquoted === "false") {
1424
+ outcome[key] = unquoted === "true";
1425
+ } else {
1426
+ outcome[key] = unquoted;
1051
1427
  }
1052
1428
  }
1053
- if (checkpoint.latestJobResult?.trim()) {
1054
- lines.push(`latestJobResult:
1055
- ${checkpoint.latestJobResult.trim()}`);
1429
+ return outcome;
1430
+ }
1431
+ function buildKnownFactsFromCheckpoint(checkpoint) {
1432
+ const summaries = Array.isArray(checkpoint?.latestActionSummary) ? checkpoint.latestActionSummary.map(normalizeActionSummaryForPrompt) : [];
1433
+ const facts = [];
1434
+ for (const summary of summaries) {
1435
+ const countedMatch = /^-\s*Counted\s+([A-Za-z0-9_]+).*?->\s*value=(\d+)/.exec(summary);
1436
+ if (countedMatch) {
1437
+ facts.push({
1438
+ entity: countedMatch[1],
1439
+ query: {},
1440
+ totalCount: Number(countedMatch[2])
1441
+ });
1442
+ continue;
1443
+ }
1444
+ const listedMatch = /^-\s*Listed\s+([A-Za-z0-9_]+).*?->\s*(.+)$/.exec(
1445
+ summary
1446
+ );
1447
+ if (!listedMatch) continue;
1448
+ const outcome = parseSummaryOutcome(listedMatch[2]);
1449
+ const count = typeof outcome.totalCount === "number" ? outcome.totalCount : typeof outcome.count === "number" ? outcome.count : void 0;
1450
+ if (typeof count !== "number") continue;
1451
+ const fact = {
1452
+ entity: listedMatch[1],
1453
+ query: {},
1454
+ totalCount: count
1455
+ };
1456
+ if (typeof outcome.hasMore === "boolean") {
1457
+ fact.lastPageHasMore = outcome.hasMore;
1458
+ fact.loadedAllItems = !outcome.hasMore;
1459
+ } else if (typeof outcome.count === "number" && outcome.count === count) {
1460
+ fact.loadedAllItems = true;
1461
+ }
1462
+ facts.push(fact);
1056
1463
  }
1057
- return lines.length > 0 ? lines.join("\n") : "No previous execution checkpoint recorded for this request yet.";
1464
+ return facts.slice(0, 8);
1058
1465
  }
1059
1466
  function buildGranularAgentSystemPrompt(input) {
1467
+ const outputMode = input.outputMode || "agentMessages";
1468
+ const promptCapabilities = resolvePromptCapabilities(input.capabilities);
1469
+ const domainSections = splitDomainDocumentation(input.domainDocumentation);
1060
1470
  const sessionBlock = buildGranularAgentSessionBlock(input.sessionContext);
1061
- const toolBlock = buildGranularAgentToolBlock(input.tools);
1062
- const domainBlock = buildGranularAgentDomainBlock(input.domainDocumentation);
1471
+ const toolBlock = buildGranularAgentToolBlock(
1472
+ input.tools,
1473
+ input.capabilities
1474
+ );
1475
+ const actionIndex = buildGranularAgentActionIndex(input.tools);
1476
+ const domainBlock = buildGranularAgentDomainBlock(domainSections.types);
1063
1477
  const workflowBlock = buildGranularAgentWorkflowBlock(input.workflowSummary);
1064
1478
  const checkpointBlock = buildGranularAgentCheckpointBlock(input.checkpoint);
1065
1479
  const heapBlock = buildGranularAgentHeapBlock(input.heapSummary);
1066
1480
  const referentBlock = buildGranularAgentReferentBlock(input.referentSummary);
1067
1481
  const loopBlock = buildGranularAgentLoopBlock(input.loopSummary);
1068
- return `You are an AI assistant for a live Granular session.
1069
- You can help the user understand the domain, answer questions, or generate and execute code against the live session.
1070
- Your tone must be natural and human-like.
1482
+ const knownFactsBlock = renderConstBlock(
1483
+ "knownFacts",
1484
+ buildKnownFactsFromCheckpoint(input.checkpoint)
1485
+ );
1486
+ 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 }\`.
1487
+ - Use \`{ reply, show }\` when the host UI should render records, heap variables, or lists from session state.
1488
+ - For multi-record display, prefer a saved list/listName so the UI can render a table; use entryPaths for a few individual records.
1489
+ - 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.
1490
+ - 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.
1491
+ - 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(...)\`.
1492
+ - \`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.
1493
+ - 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.
1494
+ - 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.
1495
+ - 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.
1496
+ - 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.
1497
+ - 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"] })\`.
1498
+ - \`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.
1499
+ - 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.
1500
+ - 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.
1501
+ - 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.
1502
+ - 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.
1503
+ - 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.
1504
+ - 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.
1505
+ - 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(...)\`.
1506
+ - \`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.
1507
+ - 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.
1508
+ - 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.
1509
+ - 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.`;
1510
+ const codeRules = promptCapabilities.executeCode ? `Code:
1511
+ - Use when the request needs session data, saved data, workflow state, record display, or available actions.
1512
+ - When using code, assistant text must be empty or one brief summary.
1513
+ - Code must be plain runnable JavaScript with top-level await.
1514
+ - Import needed classes and helpers from "./sandbox-tools".
1515
+ - Use static top-level imports such as \`import { Foo, agent_text_message } from "./sandbox-tools";\`. Do not use dynamic \`await import("./sandbox-tools")\`.
1516
+ - 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.
1517
+ - 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")\`.
1518
+ - 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.
1519
+ - User-visible output must use the provided message or record-display helpers.
1520
+ - After calling an action or effect, inspect the returned object and base the user-facing answer on its actual fields.
1521
+ - When calling an action, use the exact input property names from the action schema. Do not invent synonym keys for required inputs.
1522
+ - 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".
1523
+ - Never call \`process.exit(...)\`; emit a message and use \`return;\` to stop early.
1524
+ - 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.
1525
+ - 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.
1526
+ - Write \`//\` planning comments for the user, not for engineers: make them friendly, plain-language, and easy to understand.
1527
+ - 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.
1528
+ - 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.
1529
+ - Avoid technical terms, implementation names, code concepts, hidden helper names, and complex domain jargon in \`//\` planning comments unless the user already used that wording.
1530
+ - Each \`//\` planning comment should provide valuable feedback about the plan or next visible step. Do not add filler such as "Starting", "Running", or "Processing".
1531
+ ${outputRules}` : `Code:
1532
+ - Code execution is unavailable. Use text only, or ask the user for missing information.`;
1533
+ const workflowRules = promptCapabilities.workflowHelpers.length > 0 ? `Workflow:
1534
+ - Use workflow helpers when missing input should pause and resume the workflow.
1535
+ - If code discovers missing required input after a read, use \`await loop.ask_user(...)\`; do not just tell the user to provide it.
1536
+ - 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.
1537
+ - 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.
1538
+ - 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.
1539
+ - 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.
1540
+ - Use choice only for 2 to 5 short grounded options.
1541
+ - For record choices, set each option value to a stable scalar such as the record \`_graphPath\` or \`id\`, not a label-only value.
1542
+ - 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.
1543
+ - 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.
1544
+ - 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.
1545
+ - 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.
1546
+ - 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.
1547
+ - 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.
1548
+ - Reuse existing task, decision, and closure ids from [State].
1549
+ - If a user request matches both a domain record/action and a workflow helper, prefer the domain capability.` : "";
1550
+ return `[Harness]
1551
+ You are an assistant for a live user session. Use plain, natural language.
1071
1552
 
1072
- Call the \`execute_code\` effect ONLY when the user's intent matches the domain's capabilities and requires executing code against the live session. If the user is just asking a general question or if their request doesn't match the available effects or domain types, respond with text to explain.
1073
- When you call \`execute_code\`, additional assistant text must be either:
1074
- - empty, or
1075
- - a brief summary of the actions the generated code will perform.
1076
- Do not include any other kind of commentary when calling \`execute_code\`.
1077
- - If the next step needs to create or update workflow state in the live session, you must call \`execute_code\`. This includes \`loop.ask_user(...)\`, \`loop.confirm(...)\`, \`loop.open_decision(...)\`, \`loop.close_decision(...)\`, \`loop.create_task(...)\`, \`loop.update_task(...)\`, \`loop.complete_task(...)\`, and \`loop.close_loop(...)\`.
1078
- - If the next step is an interactive clarification that should be resumable in the live workflow, you must call \`execute_code\`. A missing preference, rule, metric, target, or option selection is not a plain-text reply when the answer should drive the next live step.
1079
- - 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.
1080
- - 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.
1553
+ Mode selection:
1554
+ Text only:
1555
+ - Use for general explanations, unsupported requests, or requests that do not need session data.
1556
+ - 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.
1557
+ - 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.
1558
+ - Do not expose internal names, helper names, file paths, parameter names, or code.
1559
+ - 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.
1081
1560
 
1082
- \u2500\u2500\u2500 STREAMING COMMENT RULES \u2500\u2500\u2500
1083
- - While you are writing code, add short single-line comments with the prefix \`// \` before meaningful blocks.
1084
- - These comments should explain the intent in friendly product language, not in implementation jargon.
1085
- - Comments are shown live as a reasoning trace, so keep them brief, concrete, and useful.
1086
- - Do not mention method names, file paths, or internal identifiers in those comments.
1087
- - Use only single-line \`//\` comments for this purpose. Do not use block comments.
1088
- - If you are replying with text only, you may also include a few leading \`// \` comment lines before the final answer.
1089
- - End text-only replies with the plain user-facing answer on normal lines, without a comment prefix.
1561
+ ${codeRules}
1090
1562
 
1091
- \u2500\u2500\u2500 RESPONSE STYLE RULES \u2500\u2500\u2500
1092
- - Use plain, friendly product language.
1093
- - Never mention internal implementation details in user-facing text:
1094
- class names, effect names, method names, function names, file paths, parameter names, or code snippets.
1095
- - Never expose dotted identifiers such as \`Class.method\` in user-facing text.
1096
- - Do not say "sandbox" in user-facing text unless the user is explicitly asking about the runtime environment itself.
1097
- - If you need clarification, ask in everyday language.
1098
- - 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.
1099
- - 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.
1100
- - Keep replies concise and clear.
1101
- - This is a conversation UI, not an API console. Favor human answers over machine-shaped payloads.
1563
+ ${workflowRules}
1102
1564
 
1103
- \u2500\u2500\u2500 SESSION CONTEXT \u2500\u2500\u2500
1104
- ${sessionBlock}
1565
+ High-priority execution rules:
1566
+ - 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.
1567
+ - 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.
1568
+ - 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.
1569
+ - 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.
1570
+ - 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.
1571
+ - 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.
1572
+ - 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.
1573
+ - 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.
1574
+ - 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.
1575
+ - 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.
1576
+ - 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.
1577
+ - 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.
1578
+ - 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.
1579
+ - 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.
1580
+ - 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.
1581
+ - 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.
1582
+ - 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.
1583
+ - 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.
1584
+ - 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.
1585
+ - 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.
1586
+ - 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.
1105
1587
 
1106
- \u2500\u2500\u2500 CAPABILITY SNAPSHOT \u2500\u2500\u2500
1107
- ${toolBlock}
1588
+ Intent resolution:
1589
+ - If intent is explicit, act directly.
1590
+ - 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.
1591
+ - 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.
1592
+ - 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.
1593
+ - 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.
1594
+ - 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.
1595
+ - 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.
1596
+ - 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.
1597
+ - 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.
1598
+ - 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.
1599
+ - 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.
1600
+ - 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.
1601
+ - 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.
1602
+ - 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.
1603
+ - 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.
1604
+ - 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.
1605
+ - 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.
1606
+ - Never call \`.get({ path: "" })\`; an empty path is not a saved reference.
1607
+ - 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.
1608
+ - \`.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.
1609
+ - 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.
1610
+ - If the entity, field, target, scope, ranking, or action is ambiguous, create 2 to 5 plausible interpretations.
1611
+ - Probe plausible interpretations with cheap read-only queries before deciding.
1612
+ - 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.
1613
+ - 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.
1614
+ - One strong match means proceed.
1615
+ - Several plausible matches means call \`loop.ask_user({ type: "choice", ... })\` with grounded choices.
1616
+ - No grounded match means ask for missing information.
1617
+ - For consequential changes, resolve first, confirm when needed, then act.
1618
+ - 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.
1619
+ - 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\`.
1620
+ - 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.
1621
+ - 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.
1622
+
1623
+ Use exploratory probing when:
1624
+ - the user gives a human reference instead of an exact id or path
1625
+ - a noun could refer to multiple entity types
1626
+ - a name, number, label, date, or amount is given without a clear field
1627
+ - ranking words are used without a clear metric
1628
+ - a requested change has an unclear target
1629
+ - the first reasonable lookup returns zero results
1630
+ - the first reasonable lookup returns several plausible results
1108
1631
 
1109
- \u2500\u2500\u2500 DOMAIN REFERENCE (from ./sandbox-tools) \u2500\u2500\u2500
1110
- Import classes and effect functions from \`./sandbox-tools\` in generated code.
1111
- Use the TypeScript declarations for exact signatures. When present, the generated usage notes below them show query patterns and examples.
1632
+ Do not explore when:
1633
+ - the entity, field, filter, and action are explicit
1634
+ - the request is a general explanation
1635
+ - the request is unsupported by available capabilities
1636
+ - the next step is already a required workflow answer or confirmation
1637
+
1638
+ [Types]
1639
+ Import classes, helpers, and available actions from "./sandbox-tools".
1640
+ 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.
1112
1641
 
1113
1642
  ${domainBlock}
1114
1643
 
1115
- \u2500\u2500\u2500 EXECUTION CHECKPOINT \u2500\u2500\u2500
1644
+ [Docs]
1645
+ Query policy:
1646
+ - Use filter, search, sort, count, page, list, and iterate on entity classes.
1647
+ - Push filtering and sorting into entity queries. Do not fetch a page only to filter or sort locally.
1648
+ - Valid filter fields are defined by each entity filter type.
1649
+ - Valid sort fields are defined by each entity sort field type.
1650
+ - Search is class-wide text retrieval, not a field-scoped operator.
1651
+ - Entity classes do not have a \`.search(...)\` method. Use \`.find({ search })\`, \`.page({ search, ... })\`, or \`.list({ search, ... })\`.
1652
+ - 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\`.
1653
+ - 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.
1654
+ - 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.
1655
+ - Combine search and filter when both free-text matching and exact constraints are needed.
1656
+ - 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.
1657
+ - 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.
1658
+ - Boolean filters use \`equal_to: true\` or \`equal_to: false\`.
1659
+ - 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.
1660
+ - 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.
1661
+ - 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.
1662
+ - 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.
1663
+ - 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.
1664
+ - 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.
1665
+ - 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.
1666
+ - 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.
1667
+ - 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.
1668
+ - Prefer generated instance relationship getters from a grounded record over hand-written deep nested relationship filters.
1669
+ - 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.
1670
+ - 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.
1671
+ - 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.
1672
+ - 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.
1673
+ - 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.
1674
+ - 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.
1675
+ - 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.
1676
+ - 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.
1677
+ - 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.
1678
+ - 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.
1679
+ - 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.
1680
+ - 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 }\`.
1681
+ - 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.
1682
+ - 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.
1683
+ - 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.
1684
+ - 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.
1685
+ - 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.
1686
+ - 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.
1687
+ - 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.
1688
+ - 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.
1689
+ - 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.
1690
+ - For scheduling actions, convert relative wording into concrete ISO timestamps before mutating records.
1691
+ - 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.
1692
+ - 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.
1693
+ - 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.
1694
+ - 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.
1695
+ - For exploratory work, use count for totals and page with small perPage for samples; use iteration only after the interpretation is chosen.
1696
+
1697
+ Lookup ladder:
1698
+ 1. Check recent references and saved session data.
1699
+ 2. Try exact id or path when the user gave an id-like value.
1700
+ 3. If the request names a parent/container plus a target, ground the parent/container and traverse declared relationships to target candidates.
1701
+ 4. Try exact filters on fields whose names or aliases match the user words.
1702
+ 5. Try class-wide search with short target-local terms, not the whole user phrase.
1703
+ 6. Try relationship filters when the user mentions connected concepts and the filter shape is documented.
1704
+ 7. If the user names a parent/container and says the label may be approximate, inspect related target records before reporting no match.
1705
+ 8. If still empty, try one small set of normalized, prefix, or fuzzy variants when search supports it.
1706
+ 9. If still empty or ambiguous, ask the user for steering.
1707
+
1708
+ Exploration budget:
1709
+ - For a simple ambiguous reference, try up to 3 strategies.
1710
+ - For a broad ambiguous task, try up to 5 strategies.
1711
+ - Probe with small pages.
1712
+ - Do not run exhaustive scans during probing unless the user explicitly asks for all records or the selected task requires aggregation.
1713
+ - Stop early when a strong unique match is found.
1714
+
1715
+ Strong unique match:
1716
+ - exactly one record matches an exact id or path
1717
+ - exactly one record matches an exact filter on a likely identifier field
1718
+ - exactly one recent reference or saved value fits the request
1719
+ - one interpretation has results and all other reasonable interpretations have none
1720
+
1721
+ Ask the user when:
1722
+ - multiple exact matches exist
1723
+ - several entity types match the same phrase
1724
+ - the best match comes only from broad search and other plausible matches exist
1725
+ - the ranking or metric is unclear
1726
+ - the target is unique but the requested action is unclear
1727
+
1728
+ Relationship filters:
1729
+ - One-record relationships use \`is\`.
1730
+ - Multi-record relationships use \`some\`.
1731
+ - 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.
1732
+ - 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.
1733
+ - 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.
1734
+ - 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.
1735
+ - Use \`some\` only when the generated TypeScript type says \`ManyRelationFilter\`.
1736
+ - 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.
1737
+ - Use \`{ relationship: { id: "record_id" } }\` or \`{ relationship: { path: "class_record_id" } }\` when matching a known related record.
1738
+ - 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\`.
1739
+ - 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.
1740
+ - Use \`{ relationship: { is: { field: { equal_to: value } } } }\` only for nested field filters. Never put \`id\` or \`path\` inside \`is\`.
1741
+ - 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.
1742
+ - Do not pass a full record instance into a filter; if you already fetched a record, filter by its id or path instead.
1743
+ ${domainSections.docs ? `
1744
+ Domain notes:
1745
+ ${domainSections.docs}
1746
+ ` : ""}
1747
+
1748
+ Actions:
1749
+ ${actionIndex}
1750
+ - 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(...)\`.
1751
+ - Actions listed under "Class-level" are class/static methods. Call them on the imported class, e.g. \`await Item.action_name(...)\`.
1752
+ - 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.
1753
+ - Never call a record-level action as \`Class.action_name(...)\`; that method will not exist.
1754
+ - 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.
1755
+ - 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.
1756
+ - 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.
1757
+ - 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.
1758
+ - 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.
1759
+ - 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.
1760
+ - 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.
1761
+ - 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.
1762
+
1763
+ [State]
1764
+ ${toolBlock}
1765
+
1766
+ ${sessionBlock}
1767
+
1116
1768
  ${checkpointBlock}
1117
1769
 
1118
- \u2500\u2500\u2500 WORKFLOW SNAPSHOT \u2500\u2500\u2500
1119
1770
  ${workflowBlock}
1120
1771
 
1121
- \u2500\u2500\u2500 RECENT REFERENTS \u2500\u2500\u2500
1122
1772
  ${referentBlock}
1123
1773
 
1124
- \u2500\u2500\u2500 SESSION HEAP \u2500\u2500\u2500
1125
1774
  ${heapBlock}
1126
1775
 
1127
- \u2500\u2500\u2500 AGENT LOOP STATE \u2500\u2500\u2500
1128
1776
  ${loopBlock}
1129
1777
 
1130
- \u2500\u2500\u2500 LOOP PLAYBOOK \u2500\u2500\u2500
1131
- - 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.
1132
- - Use CAPABILITY SNAPSHOT to choose the next step, then use DOMAIN REFERENCE for exact signatures and query shapes.
1133
- - Take the minimum next step that directly helps the user. Avoid duplicate work, speculative cleanup, or extra fetching that is not needed yet.
1134
- - Use RECENT REFERENTS to resolve follow-up references across turns, such as "that invoice", "that customer", "those products", or "the other one".
1135
- - 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.
1136
- - 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.
1137
- - If the request has more than one reasonable interpretation, ask the user to clarify instead of guessing.
1138
- - 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.
1139
- - 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.
1140
- - 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.
1141
- - Reuse exact \`taskId\`, \`decisionId\`, and \`closureId\` values from AGENT LOOP STATE. Never invent or rewrite them.
1142
- - If the request is ambiguous or clearly multi-step, create 2-4 short user-visible tasks and keep them updated as the workflow advances.
1143
- - Use \`loop.ask_user({ type: 'choice', options: [...] })\` when you have a short, grounded shortlist the user can choose from. Otherwise use \`type: 'input'\`.
1144
- - 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.
1145
- - When \`type: 'choice'\` fits, do not ask the same question as plain text with bullets such as "Common options:" or "Choose one of these:".
1146
- - Use \`loop.confirm(...)\` for consequential approval unless the user already clearly instructed you to perform that exact action now.
1147
- - Await \`loop.ask_user(...)\` and \`loop.confirm(...)\`. After the job resumes, continue in the same job whenever the answer is enough to act.
1148
- - 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.
1149
- - If you ask a new question in the current job, do not also close the loop in that same job.
1150
-
1151
- \u2500\u2500\u2500 LOOP HELPER REFERENCE \u2500\u2500\u2500
1152
- - \`loop.ask_user(...)\`: pause the current job for missing input; use \`type: 'choice'\` only for a short grounded shortlist.
1153
- - \`loop.confirm(...)\`: pause for yes/no approval before a consequential action, then branch on the returned boolean.
1154
- - \`loop.open_decision(...)\`: save explicit candidates that later jobs can revisit; each candidate needs an \`id\`.
1155
- - \`loop.close_decision(...)\`: resolve an open decision with a stored \`selectedId\` and optional rationale.
1156
- - \`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.
1157
- - \`loop.close_loop(...)\`: record the workflow outcome when it is completed, canceled, or blocked.
1778
+ ${knownFactsBlock}
1158
1779
 
1159
- \u2500\u2500\u2500 CODE RULES \u2500\u2500\u2500
1160
- - Import from \`./sandbox-tools\`.
1161
- - If you use \`heap\`, \`loop\`, \`agent_text_message\`, or \`agent_heap_objects\`, import them explicitly from \`./sandbox-tools\`.
1162
- - Write top-level executable code with \`await\` at top level.
1163
- - The generated job body must be plain runnable JavaScript. Do not use TypeScript-only syntax.
1164
- - Follow the exact classes, methods, and parameter shapes in DOMAIN REFERENCE. Do not invent helpers or unsupported arguments.
1165
- - Use \`ClassName.get({ path })\` only for known graph paths when you want a direct graph fetch.
1166
- - 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.
1167
- - \`perPage\` defaults to \`100\` and is capped at \`100\`.
1168
- - 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.
1169
- - Push \`filter\`, \`search\`, and \`sort\` into graph queries instead of fetching a page and processing it locally.
1170
- - 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.
1171
- - 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.
1172
- - If ordering alone answers the request, use \`sort\` without inventing a \`filter\`.
1173
- - 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(...)\`.
1174
- - 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.
1175
- - Call instance methods on instances, static methods on classes, and global effects by name.
1176
- - Use \`heap.getEntry(path)\` for remembered heap entries, \`heap.getList(name)\` for remembered lists, and \`heap.getVar(name)\` only for named variables.
1177
- - Use \`heap.setVar(...)\` and \`heap.deleteVar(...)\` only when they help the next step.
1178
- - Prefer \`heap.setVar(...)\` for scalars or one selected instance. Prefer \`ClassName.list({ saveAs })\` for reusable typed lists. Empty arrays are allowed.
1179
- - 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.
1180
- - Use the \`loop\` helpers to manage workflow state: \`ask_user\`, \`confirm\`, \`open_decision\`, \`close_decision\`, \`create_task\`, \`update_task\`, \`complete_task\`, and \`close_loop\`.
1181
- - Use \`type: 'choice'\` only for short grounded options. Use \`type: 'input'\` when the answer should stay open-ended.
1182
- - \`loop.confirm(...)\` is for consequential approval. Do not ask for approval in plain text.
1183
- - After \`await loop.ask_user(...)\` or \`await loop.confirm(...)\`, continue in the same resumed job when the answer is enough to act.
1184
- - Every job that answers the user must emit \`agent_text_message(...)\` and/or \`agent_heap_objects(...)\`.
1185
- - Use \`agent_text_message(...)\` for user-visible text.
1186
- - 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.
1187
- - 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.
1188
- - Keep the code small and direct. Avoid speculative branches, broad casts, and raw JSON dumps unless the user asked for them.
1189
- - Use \`console.log()\` only for intermediate diagnostics, not for the final user-facing answer.`;
1780
+ [Request]
1781
+ ${input.request?.trim() || "Use the latest user message in the conversation."}`;
1190
1782
  }
1191
1783
 
1192
- export { buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentReferentBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, createHarnessVerifierSnapshot, evaluateContinuation, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, reviewGeneratedJobCode };
1784
+ export { buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentReferentBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, consumeGranularReasoningOnlyChunk, consumeGranularReasoningTraceChunk, createHarnessVerifierSnapshot, evaluateContinuation, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, reviewGeneratedJobCode, stripGranularReasoningTrace };
1193
1785
  //# sourceMappingURL=agent-harness.mjs.map
1194
1786
  //# sourceMappingURL=agent-harness.mjs.map