@granular-software/sdk 0.4.24 → 0.4.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { P as Prompt, d as Environment, c as SessionHeapSnapshot, a$ as ManifestContent, ax as RecordObjectOptions, T as ToolWithHandler, G as Granular, C as ConnectOptions, y as CreateEnvironmentData, i as GranularOptions } from './client-CQFKsCTd.mjs';
1
+ import { P as Prompt, d as Environment, c as SessionHeapSnapshot, a$ as ManifestContent, ax as RecordObjectOptions, T as ToolWithHandler, G as Granular, C as ConnectOptions, y as CreateEnvironmentData, i as GranularOptions } from './client-BeKRGMoT.mjs';
2
2
  import { GeneratedJobCodeIssue, HarnessControllerBudgets } from './agent-harness.mjs';
3
3
  import '@automerge/automerge';
4
4
  import '@automerge/automerge/slim';
@@ -1,4 +1,4 @@
1
- import { P as Prompt, d as Environment, c as SessionHeapSnapshot, a$ as ManifestContent, ax as RecordObjectOptions, T as ToolWithHandler, G as Granular, C as ConnectOptions, y as CreateEnvironmentData, i as GranularOptions } from './client-CQFKsCTd.js';
1
+ import { P as Prompt, d as Environment, c as SessionHeapSnapshot, a$ as ManifestContent, ax as RecordObjectOptions, T as ToolWithHandler, G as Granular, C as ConnectOptions, y as CreateEnvironmentData, i as GranularOptions } from './client-BeKRGMoT.js';
2
2
  import { GeneratedJobCodeIssue, HarnessControllerBudgets } from './agent-harness.js';
3
3
  import '@automerge/automerge';
4
4
  import '@automerge/automerge/slim';
@@ -4572,6 +4572,7 @@ var Session = class {
4572
4572
  client;
4573
4573
  clientId;
4574
4574
  jobsMap = /* @__PURE__ */ new Map();
4575
+ pendingAgentMessagesByJobId = /* @__PURE__ */ new Map();
4575
4576
  eventListeners = /* @__PURE__ */ new Map();
4576
4577
  toolHandlers = /* @__PURE__ */ new Map();
4577
4578
  /** Tracks which tools are instance methods (className set, not static) */
@@ -4729,6 +4730,15 @@ var Session = class {
4729
4730
  createdAt: Date.now()
4730
4731
  });
4731
4732
  this.jobsMap.set(result.jobId, job);
4733
+ const pendingAgentMessages = this.pendingAgentMessagesByJobId.get(
4734
+ result.jobId
4735
+ );
4736
+ if (pendingAgentMessages && pendingAgentMessages.length > 0) {
4737
+ this.pendingAgentMessagesByJobId.delete(result.jobId);
4738
+ for (const message of pendingAgentMessages) {
4739
+ job.replayAgentMessage(message);
4740
+ }
4741
+ }
4732
4742
  return job;
4733
4743
  }
4734
4744
  /**
@@ -5130,6 +5140,22 @@ import { ${allImports} } from "./sandbox-tools";
5130
5140
  this.client.on("job.status", (data) => {
5131
5141
  this.emit("job:status", data);
5132
5142
  });
5143
+ this.client.on("job.agent_message", (data) => {
5144
+ const normalized = normalizeJobAgentMessageEnvelope(data);
5145
+ if (!normalized) return;
5146
+ if (this.jobsMap.has(normalized.jobId)) return;
5147
+ const pending = this.pendingAgentMessagesByJobId.get(normalized.jobId) || [];
5148
+ if (normalized.message.messageId && pending.some(
5149
+ (message) => message.messageId === normalized.message.messageId
5150
+ )) {
5151
+ return;
5152
+ }
5153
+ pending.push(normalized.message);
5154
+ this.pendingAgentMessagesByJobId.set(
5155
+ normalized.jobId,
5156
+ pending.slice(-25)
5157
+ );
5158
+ });
5133
5159
  this.client.on("exec.completed", (data) => {
5134
5160
  this.emit("exec:completed", data);
5135
5161
  });
@@ -5254,6 +5280,22 @@ function sanitizeFeedbackValue(value, depth = 0, seen = /* @__PURE__ */ new Weak
5254
5280
  }
5255
5281
  return truncateFeedbackString(String(value));
5256
5282
  }
5283
+ function normalizeJobAgentMessageEnvelope(data) {
5284
+ const d = data;
5285
+ if (typeof d?.jobId !== "string" || !d.jobId) {
5286
+ return null;
5287
+ }
5288
+ return {
5289
+ jobId: d.jobId,
5290
+ message: {
5291
+ messageId: d.messageId,
5292
+ kind: d.kind === "artifacts" ? "artifacts" : "text",
5293
+ reply: typeof d.reply === "string" ? d.reply : "",
5294
+ show: d.show,
5295
+ timestamp: d.timestamp || Date.now()
5296
+ }
5297
+ };
5298
+ }
5257
5299
  var JobImplementation = class {
5258
5300
  id;
5259
5301
  client;
@@ -5262,6 +5304,8 @@ var JobImplementation = class {
5262
5304
  _resolveResult;
5263
5305
  _rejectResult;
5264
5306
  eventListeners = /* @__PURE__ */ new Map();
5307
+ bufferedAgentMessages = [];
5308
+ bufferedAgentMessageIds = /* @__PURE__ */ new Set();
5265
5309
  metadata;
5266
5310
  constructor(id, client, initialState) {
5267
5311
  this.id = id;
@@ -5420,14 +5464,9 @@ var JobImplementation = class {
5420
5464
  }
5421
5465
  });
5422
5466
  this.client.on("job.agent_message", (data) => {
5423
- const d = data;
5424
- if (d.jobId === id) {
5425
- this.emit("agentMessage", {
5426
- messageId: d.messageId,
5427
- reply: typeof d.reply === "string" ? d.reply : "",
5428
- show: d.show,
5429
- timestamp: d.timestamp || Date.now()
5430
- });
5467
+ const normalized = normalizeJobAgentMessageEnvelope(data);
5468
+ if (normalized?.jobId === id) {
5469
+ this.captureAgentMessage(normalized.message);
5431
5470
  }
5432
5471
  });
5433
5472
  }
@@ -5454,6 +5493,14 @@ var JobImplementation = class {
5454
5493
  this.eventListeners.set(event, []);
5455
5494
  }
5456
5495
  this.eventListeners.get(event).push(handler);
5496
+ if (event === "agentMessage" && this.bufferedAgentMessages.length > 0) {
5497
+ for (const message of this.bufferedAgentMessages) {
5498
+ handler(message);
5499
+ }
5500
+ }
5501
+ }
5502
+ replayAgentMessage(message) {
5503
+ this.captureAgentMessage(message);
5457
5504
  }
5458
5505
  buildFeedbackMetadata() {
5459
5506
  const startedAt = this.metadata.startedAt;
@@ -5523,6 +5570,18 @@ var JobImplementation = class {
5523
5570
  handlers.forEach((h) => h(data));
5524
5571
  }
5525
5572
  }
5573
+ captureAgentMessage(message) {
5574
+ if (message.messageId && this.bufferedAgentMessageIds.has(message.messageId)) {
5575
+ return;
5576
+ }
5577
+ if (message.messageId) {
5578
+ this.bufferedAgentMessageIds.add(message.messageId);
5579
+ }
5580
+ this.bufferedAgentMessages = [...this.bufferedAgentMessages, message].slice(
5581
+ -25
5582
+ );
5583
+ this.emit("agentMessage", message);
5584
+ }
5526
5585
  };
5527
5586
 
5528
5587
  // src/endpoints.ts
@@ -13577,14 +13636,22 @@ function reviewGeneratedJobCode(code) {
13577
13636
  }
13578
13637
  }
13579
13638
  }
13580
- const hasConversationalReturn = /return\s+[`'"]/.test(normalized) || /\breply\s*:/.test(normalized) || /\bagent_message\s*\(/.test(normalized);
13639
+ const hasConversationalReturn = /return\s+[`'"]/.test(normalized) || /\breply\s*:/.test(normalized) || /\bagent_message\s*\(/.test(normalized) || /\bagent_text_message\s*\(/.test(normalized);
13581
13640
  const returnsObjectLiteral = /return\s+\{[\s\S]*?\}/.test(normalized);
13641
+ const returnsShowPayload = /return\s+\{[\s\S]*?\bshow\s*:/.test(normalized);
13582
13642
  const closesLoop = /loop\.close_loop\s*\(/.test(normalized);
13583
13643
  if (!hasConversationalReturn && returnsObjectLiteral && !closesLoop) {
13584
13644
  issues.push({
13585
13645
  code: "missing_user_reply",
13586
13646
  severity: "error",
13587
- message: "User-facing jobs must end with a natural-language answer. Return a short string, an object with a top-level `reply` string, or use agent_message({ reply, show }). Do not end with bare structured JSON."
13647
+ 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."
13648
+ });
13649
+ }
13650
+ if (returnsShowPayload) {
13651
+ issues.push({
13652
+ code: "return_show_not_for_ui",
13653
+ severity: "error",
13654
+ 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."
13588
13655
  });
13589
13656
  }
13590
13657
  return issues;
@@ -14429,7 +14496,7 @@ ${loopBlock}
14429
14496
 
14430
14497
  \u2500\u2500\u2500 CODE RULES \u2500\u2500\u2500
14431
14498
  - Import from \`./sandbox-tools\`.
14432
- - If you use \`heap\`, \`loop\`, or \`agent_message\`, import them explicitly from \`./sandbox-tools\`.
14499
+ - If you use \`heap\`, \`loop\`, \`agent_text_message\`, \`agent_heap_objects\`, or legacy \`agent_message\`, import them explicitly from \`./sandbox-tools\`.
14433
14500
  - Write top-level executable code with \`await\` at top level.
14434
14501
  - The generated job body must be plain runnable JavaScript. The DOMAIN TYPES block is only a reference for shapes and available methods.
14435
14502
  - Do not write TypeScript-only syntax in executable code: no type annotations, no interfaces, no enums, no \`as Type\` casts, no \`satisfies\`, and no generic type parameters in code.
@@ -14471,21 +14538,31 @@ ${loopBlock}
14471
14538
  - \`loop.close_loop(...)\`: record the current workflow outcome with a short summary before stopping. Do not call it in the same job that opens a new user prompt unless the workflow is explicitly blocked. This does not end the session forever.
14472
14539
  - Avoid \`as any\` and other broad casts when the DOMAIN TYPES block already tells you the correct class or list type.
14473
14540
  - Prefer manipulating heap-backed instances and typed lists instead of returning raw JSON blobs or object IDs unless the user explicitly asks for them.
14474
- - If the user expects an answer after the job runs, the final \`return\` value must be either a short natural-language string or an object with a top-level \`reply\` string.
14475
- - You may call \`agent_message(...)\` multiple times in one job to post several assistant messages while the job is still running.
14476
- - Prefer \`agent_message({ reply, show })\` when you want to leave a user-facing answer and optionally show heap-backed records in the UI.
14477
- - \`agent_message(...)\` also accepts \`content\`, \`message\`, or \`text\` instead of \`reply\`.
14478
- - \`agent_message({ show })\` may receive explicit refs or sandbox instances and arrays of sandbox instances. The runtime will convert those into UI references.
14479
- - When it helps the UI show specific heap-backed results, you may instead return:
14480
- \`{ reply: string, show: { entryPaths?: string[], listNames?: string[], variableNames?: string[] } }\`
14481
- - If you create or load objects the user should see, save them in the heap and return references to them through \`show\` instead of serializing full objects.
14541
+ - Every job that intends to answer the user must emit at least one explicit UI message with \`agent_text_message(...)\` and/or \`agent_heap_objects(...)\`.
14542
+ - Use \`agent_text_message("...")\` for all user-visible text shown in the UI.
14543
+ - Use \`agent_heap_objects(...)\` only when you want the UI to render heap-backed records or lists.
14544
+ - If you want to show both text and records, call \`agent_text_message(...)\` and \`agent_heap_objects(...)\` separately in whatever order fits the interaction.
14545
+ - \`agent_text_message(...)\` should be used with a plain text string in normal generated code.
14546
+ - \`agent_heap_objects(...)\` should point at heap-backed values: explicit \`entryPaths\` / \`listNames\` / \`variableNames\`, a named list saved with \`saveAs\`, or values read back from \`heap.getVar(...)\`.
14547
+ - If you just fetched records and want to show them in the UI, save or reference them through the heap first, then call \`agent_heap_objects(...)\`. Do not try to hand-build UI payloads in job code.
14548
+ - Do not assume heap changes will be displayed automatically. If records should appear in the UI, you must call \`agent_heap_objects(...)\`.
14549
+ - Never write \`return { reply, show }\` or \`return { show: ... }\` for UI. If you want the UI to render records or lists, call \`agent_heap_objects(...)\` instead.
14550
+ - Do not rely on the final return value for user-visible output. A plain return value is not considered a displayed UI answer.
14551
+ - \`agent_message(...)\` remains available as a legacy compatibility alias, but prefer \`agent_text_message(...)\` and \`agent_heap_objects(...)\` in new code.
14482
14552
  - Do not return bare structured JSON, low-level diagnostics, or database-shaped payloads as the final answer unless the user explicitly asks for them.
14483
14553
  - Prefer simple executable JavaScript over clever interpolation. Avoid nested template literals or unusually dense inline expressions when a small temporary variable or string concatenation would be clearer and safer.
14484
14554
  - Use \`console.log()\` only for intermediate diagnostics, not for the final user-facing answer.`;
14485
14555
  }
14486
14556
 
14487
14557
  // src/job-presentation.ts
14488
- var RESPONSE_KEYS = ["reply", "response", "text", "message", "summary", "answer"];
14558
+ var RESPONSE_KEYS = [
14559
+ "reply",
14560
+ "response",
14561
+ "text",
14562
+ "message",
14563
+ "summary",
14564
+ "answer"
14565
+ ];
14489
14566
  var ENTRY_KEY_CANDIDATES = ["entryPath", "path"];
14490
14567
  var ENTRY_ARRAY_KEY_CANDIDATES = ["entryPaths", "paths"];
14491
14568
  var LIST_KEY_CANDIDATES = ["listName"];
@@ -14527,15 +14604,22 @@ function pushStringArray(target, value) {
14527
14604
  }
14528
14605
  }
14529
14606
  function collectReferencesFromRecord(record, refs) {
14530
- for (const key of ENTRY_KEY_CANDIDATES) pushString(refs.entryPaths, record[key]);
14531
- for (const key of ENTRY_ARRAY_KEY_CANDIDATES) pushStringArray(refs.entryPaths, record[key]);
14532
- for (const key of LIST_KEY_CANDIDATES) pushString(refs.listNames, record[key]);
14533
- for (const key of LIST_ARRAY_KEY_CANDIDATES) pushStringArray(refs.listNames, record[key]);
14534
- for (const key of VARIABLE_KEY_CANDIDATES) pushString(refs.variableNames, record[key]);
14535
- for (const key of VARIABLE_ARRAY_KEY_CANDIDATES) pushStringArray(refs.variableNames, record[key]);
14607
+ for (const key of ENTRY_KEY_CANDIDATES)
14608
+ pushString(refs.entryPaths, record[key]);
14609
+ for (const key of ENTRY_ARRAY_KEY_CANDIDATES)
14610
+ pushStringArray(refs.entryPaths, record[key]);
14611
+ for (const key of LIST_KEY_CANDIDATES)
14612
+ pushString(refs.listNames, record[key]);
14613
+ for (const key of LIST_ARRAY_KEY_CANDIDATES)
14614
+ pushStringArray(refs.listNames, record[key]);
14615
+ for (const key of VARIABLE_KEY_CANDIDATES)
14616
+ pushString(refs.variableNames, record[key]);
14617
+ for (const key of VARIABLE_ARRAY_KEY_CANDIDATES)
14618
+ pushStringArray(refs.variableNames, record[key]);
14536
14619
  }
14537
14620
  function scanForHeapReferences(value, heap, refs, depth = 0, seen = /* @__PURE__ */ new Set()) {
14538
- if (value === null || value === void 0 || depth > 4 || seen.has(value)) return;
14621
+ if (value === null || value === void 0 || depth > 4 || seen.has(value))
14622
+ return;
14539
14623
  if (typeof value === "string") {
14540
14624
  const trimmed = value.trim();
14541
14625
  if (heap.entriesByPath?.[trimmed]) refs.entryPaths.add(trimmed);
@@ -14631,12 +14715,16 @@ function fallbackResponseText(entries, lists) {
14631
14715
  }
14632
14716
  function getJobRelatedEntries(heap, jobId) {
14633
14717
  return sortEntries(
14634
- Object.values(heap.entriesByPath || {}).filter((entry) => entry.relatedJobIds?.includes(jobId))
14718
+ Object.values(heap.entriesByPath || {}).filter(
14719
+ (entry) => entry.relatedJobIds?.includes(jobId)
14720
+ )
14635
14721
  );
14636
14722
  }
14637
14723
  function getJobRelatedLists(heap, jobId) {
14638
14724
  return sortLists(
14639
- Object.values(heap.listsByName || {}).filter((list) => list.relatedJobIds?.includes(jobId))
14725
+ Object.values(heap.listsByName || {}).filter(
14726
+ (list) => list.relatedJobIds?.includes(jobId)
14727
+ )
14640
14728
  );
14641
14729
  }
14642
14730
  function entriesFromLists(lists, heap) {
@@ -14653,15 +14741,18 @@ function resolveJobPresentation({
14653
14741
  jobId,
14654
14742
  result,
14655
14743
  stdout = [],
14656
- sessionHeap
14744
+ sessionHeap,
14745
+ allowExplicitArtifacts = true
14657
14746
  }) {
14658
14747
  const refs = {
14659
14748
  entryPaths: /* @__PURE__ */ new Set(),
14660
14749
  listNames: /* @__PURE__ */ new Set(),
14661
14750
  variableNames: /* @__PURE__ */ new Set()
14662
14751
  };
14663
- scanForHeapReferences(result, sessionHeap, refs);
14664
- resolveVariablesToReferences(refs.variableNames, sessionHeap, refs);
14752
+ if (allowExplicitArtifacts) {
14753
+ scanForHeapReferences(result, sessionHeap, refs);
14754
+ resolveVariablesToReferences(refs.variableNames, sessionHeap, refs);
14755
+ }
14665
14756
  const referencedLists = sortLists(
14666
14757
  [...refs.listNames].map((name) => sessionHeap.listsByName?.[name]).filter((list) => Boolean(list))
14667
14758
  );
@@ -14674,20 +14765,22 @@ function resolveJobPresentation({
14674
14765
  ...jobEntries,
14675
14766
  ...entriesFromLists(jobLists, sessionHeap)
14676
14767
  ]);
14677
- const lists = dedupeLists([...referencedLists, ...jobLists]);
14678
- const entries = dedupeEntries([
14768
+ const explicitLists = dedupeLists(referencedLists);
14769
+ const explicitEntries = dedupeEntries([
14679
14770
  ...referencedEntries,
14680
- ...entriesFromLists(referencedLists, sessionHeap),
14681
- ...jobEntries,
14682
- ...entriesFromLists(jobLists, sessionHeap)
14771
+ ...entriesFromLists(referencedLists, sessionHeap)
14683
14772
  ]);
14773
+ const hasExplicitArtifacts = allowExplicitArtifacts && (explicitEntries.length > 0 || explicitLists.length > 0);
14774
+ const lists = hasExplicitArtifacts ? explicitLists : jobLists;
14775
+ const entries = hasExplicitArtifacts ? explicitEntries : changedEntries;
14684
14776
  const responseText = extractResponseText(result, stdout) || fallbackResponseText(entries, lists);
14685
14777
  return {
14686
14778
  responseText,
14687
14779
  entries,
14688
14780
  lists,
14689
14781
  changedEntries,
14690
- changedLists: jobLists
14782
+ changedLists: jobLists,
14783
+ hasExplicitArtifacts
14691
14784
  };
14692
14785
  }
14693
14786