@granular-software/sdk 0.4.36 → 0.4.37

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