@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.
package/dist/cli/index.js CHANGED
@@ -18160,6 +18160,7 @@ var Session = class {
18160
18160
  client;
18161
18161
  clientId;
18162
18162
  jobsMap = /* @__PURE__ */ new Map();
18163
+ pendingAgentMessagesByJobId = /* @__PURE__ */ new Map();
18163
18164
  eventListeners = /* @__PURE__ */ new Map();
18164
18165
  toolHandlers = /* @__PURE__ */ new Map();
18165
18166
  /** Tracks which tools are instance methods (className set, not static) */
@@ -18317,6 +18318,15 @@ var Session = class {
18317
18318
  createdAt: Date.now()
18318
18319
  });
18319
18320
  this.jobsMap.set(result.jobId, job2);
18321
+ const pendingAgentMessages = this.pendingAgentMessagesByJobId.get(
18322
+ result.jobId
18323
+ );
18324
+ if (pendingAgentMessages && pendingAgentMessages.length > 0) {
18325
+ this.pendingAgentMessagesByJobId.delete(result.jobId);
18326
+ for (const message of pendingAgentMessages) {
18327
+ job2.replayAgentMessage(message);
18328
+ }
18329
+ }
18320
18330
  return job2;
18321
18331
  }
18322
18332
  /**
@@ -18718,6 +18728,22 @@ import { ${allImports} } from "./sandbox-tools";
18718
18728
  this.client.on("job.status", (data) => {
18719
18729
  this.emit("job:status", data);
18720
18730
  });
18731
+ this.client.on("job.agent_message", (data) => {
18732
+ const normalized = normalizeJobAgentMessageEnvelope(data);
18733
+ if (!normalized) return;
18734
+ if (this.jobsMap.has(normalized.jobId)) return;
18735
+ const pending = this.pendingAgentMessagesByJobId.get(normalized.jobId) || [];
18736
+ if (normalized.message.messageId && pending.some(
18737
+ (message) => message.messageId === normalized.message.messageId
18738
+ )) {
18739
+ return;
18740
+ }
18741
+ pending.push(normalized.message);
18742
+ this.pendingAgentMessagesByJobId.set(
18743
+ normalized.jobId,
18744
+ pending.slice(-25)
18745
+ );
18746
+ });
18721
18747
  this.client.on("exec.completed", (data) => {
18722
18748
  this.emit("exec:completed", data);
18723
18749
  });
@@ -18842,6 +18868,22 @@ function sanitizeFeedbackValue(value, depth = 0, seen = /* @__PURE__ */ new Weak
18842
18868
  }
18843
18869
  return truncateFeedbackString(String(value));
18844
18870
  }
18871
+ function normalizeJobAgentMessageEnvelope(data) {
18872
+ const d = data;
18873
+ if (typeof d?.jobId !== "string" || !d.jobId) {
18874
+ return null;
18875
+ }
18876
+ return {
18877
+ jobId: d.jobId,
18878
+ message: {
18879
+ messageId: d.messageId,
18880
+ kind: d.kind === "artifacts" ? "artifacts" : "text",
18881
+ reply: typeof d.reply === "string" ? d.reply : "",
18882
+ show: d.show,
18883
+ timestamp: d.timestamp || Date.now()
18884
+ }
18885
+ };
18886
+ }
18845
18887
  var JobImplementation = class {
18846
18888
  id;
18847
18889
  client;
@@ -18850,6 +18892,8 @@ var JobImplementation = class {
18850
18892
  _resolveResult;
18851
18893
  _rejectResult;
18852
18894
  eventListeners = /* @__PURE__ */ new Map();
18895
+ bufferedAgentMessages = [];
18896
+ bufferedAgentMessageIds = /* @__PURE__ */ new Set();
18853
18897
  metadata;
18854
18898
  constructor(id, client, initialState) {
18855
18899
  this.id = id;
@@ -19008,14 +19052,9 @@ var JobImplementation = class {
19008
19052
  }
19009
19053
  });
19010
19054
  this.client.on("job.agent_message", (data) => {
19011
- const d = data;
19012
- if (d.jobId === id) {
19013
- this.emit("agentMessage", {
19014
- messageId: d.messageId,
19015
- reply: typeof d.reply === "string" ? d.reply : "",
19016
- show: d.show,
19017
- timestamp: d.timestamp || Date.now()
19018
- });
19055
+ const normalized = normalizeJobAgentMessageEnvelope(data);
19056
+ if (normalized?.jobId === id) {
19057
+ this.captureAgentMessage(normalized.message);
19019
19058
  }
19020
19059
  });
19021
19060
  }
@@ -19042,6 +19081,14 @@ var JobImplementation = class {
19042
19081
  this.eventListeners.set(event, []);
19043
19082
  }
19044
19083
  this.eventListeners.get(event).push(handler);
19084
+ if (event === "agentMessage" && this.bufferedAgentMessages.length > 0) {
19085
+ for (const message of this.bufferedAgentMessages) {
19086
+ handler(message);
19087
+ }
19088
+ }
19089
+ }
19090
+ replayAgentMessage(message) {
19091
+ this.captureAgentMessage(message);
19045
19092
  }
19046
19093
  buildFeedbackMetadata() {
19047
19094
  const startedAt = this.metadata.startedAt;
@@ -19111,6 +19158,18 @@ var JobImplementation = class {
19111
19158
  handlers.forEach((h) => h(data));
19112
19159
  }
19113
19160
  }
19161
+ captureAgentMessage(message) {
19162
+ if (message.messageId && this.bufferedAgentMessageIds.has(message.messageId)) {
19163
+ return;
19164
+ }
19165
+ if (message.messageId) {
19166
+ this.bufferedAgentMessageIds.add(message.messageId);
19167
+ }
19168
+ this.bufferedAgentMessages = [...this.bufferedAgentMessages, message].slice(
19169
+ -25
19170
+ );
19171
+ this.emit("agentMessage", message);
19172
+ }
19114
19173
  };
19115
19174
 
19116
19175
  // src/effect-runtime.ts
@@ -1254,6 +1254,7 @@ declare class Session {
1254
1254
  protected client: WSClient;
1255
1255
  private clientId;
1256
1256
  private jobsMap;
1257
+ private pendingAgentMessagesByJobId;
1257
1258
  private eventListeners;
1258
1259
  private toolHandlers;
1259
1260
  /** Tracks which tools are instance methods (className set, not static) */
@@ -1254,6 +1254,7 @@ declare class Session {
1254
1254
  protected client: WSClient;
1255
1255
  private clientId;
1256
1256
  private jobsMap;
1257
+ private pendingAgentMessagesByJobId;
1257
1258
  private eventListeners;
1258
1259
  private toolHandlers;
1259
1260
  /** Tracks which tools are instance methods (className set, not static) */
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EndpointMode, T as ToolWithHandler, a as EffectHandlerContext, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, S as SessionHeapEntry, b as SessionHeapList, c as SessionHeapSnapshot, P as Prompt } from './client-CQFKsCTd.mjs';
2
- export { b1 as APIError, A as AccessTokenProvider, u as Assignment, v as AssignmentListResponse, K as Build, N as BuildListResponse, B as BuildPolicy, J as BuildStatus, C as ConnectOptions, m as ConversationSessionInfo, y as CreateEnvironmentData, s as CreatePermissionProfileData, o as CreateSandboxData, aw as DefineRelationshipOptions, b2 as DeleteResponse, D as DomainState, a8 as EffectHandler, a5 as EffectInfo, a0 as EffectInvocationMetadata, $ as EffectInvocationMode, a1 as EffectSchema, a2 as EffectWithHandler, a7 as EffectsChangedEvent, d as Environment, x as EnvironmentData, z as EnvironmentListResponse, aG as EnvironmentRecordImportSummary, G as Granular, j as GranularAuth, i as GranularOptions, b0 as GraphQLResult, a9 as InstanceEffectHandler, I as InstanceToolHandler, ah as Job, ae as JobFeedbackInput, ad as JobFeedbackMetadata, af as JobFeedbackRecord, ab as JobFeedbackSentiment, ac as JobFeedbackToolCall, aa as JobStatus, ag as JobSubmitResult, F as Manifest, aS as ManifestApprovalRequiredSpec, a$ as ManifestContent, aQ as ManifestDryRunSpec, aV as ManifestEffectDeclaration, aU as ManifestEffectSchema, aJ as ManifestEnumRuleSpec, aX as ManifestEventStreamDef, aW as ManifestEventTypeDef, aK as ManifestFilterBySpec, aZ as ManifestImport, H as ManifestListResponse, aY as ManifestOperation, aP as ManifestPostConditionSpec, aH as ManifestPropertySpec, aT as ManifestRelationshipDef, aR as ManifestReverseSpec, aO as ManifestStateMachineSpec, aM as ManifestStateMachineStateSpec, aN as ManifestStateMachineTransitionSpec, aI as ManifestValidationOperator, aL as ManifestValidationRuleSpec, a_ as ManifestVolume, au as ModelRef, r as PermissionProfile, t as PermissionProfileListResponse, q as PermissionRules, a3 as PublishEffectsResult, g as PublishToolsResult, ao as RPCRequest, ar as RPCRequestFromServer, ap as RPCResponse, aF as RecordImport, aE as RecordImportItem, aC as RecordImportItemStatus, aD as RecordImportStats, aB as RecordImportStatus, ax as RecordObjectOptions, ay as RecordObjectResult, az as RecordObjectsChunkInfo, aA as RecordObjectsOptions, k as RecordUserOptions, av as RelationshipInfo, _ as ResolvedEffectApprovalRequired, Y as ResolvedEffectDryRun, X as ResolvedEffectPostCondition, Z as ResolvedEffectReverse, n as Sandbox, p as SandboxListResponse, Q as SemanticVersionDiff, O as SemanticVersionDiffEntry, e as Session, ai as SessionHeapFieldType, aj as SessionHeapFieldValue, ak as SessionHeapVariable, b3 as StreamEvent, b5 as StreamStats, b4 as StreamSubscription, l as Subject, aq as SyncMessage, h as ToolHandler, a4 as ToolInfo, as as ToolInvokeParams, at as ToolResultParams, f as ToolSchema, a6 as ToolsChangedEvent, U as User, L as Version, w as VersionTag, V as VersionTracking, W as WSClient, an as WSClientOptions, al as WSDisconnectInfo, am as WSReconnectErrorInfo } from './client-CQFKsCTd.mjs';
1
+ import { E as EndpointMode, T as ToolWithHandler, a as EffectHandlerContext, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, S as SessionHeapEntry, b as SessionHeapList, c as SessionHeapSnapshot, P as Prompt } from './client-BeKRGMoT.mjs';
2
+ export { b1 as APIError, A as AccessTokenProvider, u as Assignment, v as AssignmentListResponse, K as Build, N as BuildListResponse, B as BuildPolicy, J as BuildStatus, C as ConnectOptions, m as ConversationSessionInfo, y as CreateEnvironmentData, s as CreatePermissionProfileData, o as CreateSandboxData, aw as DefineRelationshipOptions, b2 as DeleteResponse, D as DomainState, a8 as EffectHandler, a5 as EffectInfo, a0 as EffectInvocationMetadata, $ as EffectInvocationMode, a1 as EffectSchema, a2 as EffectWithHandler, a7 as EffectsChangedEvent, d as Environment, x as EnvironmentData, z as EnvironmentListResponse, aG as EnvironmentRecordImportSummary, G as Granular, j as GranularAuth, i as GranularOptions, b0 as GraphQLResult, a9 as InstanceEffectHandler, I as InstanceToolHandler, ah as Job, ae as JobFeedbackInput, ad as JobFeedbackMetadata, af as JobFeedbackRecord, ab as JobFeedbackSentiment, ac as JobFeedbackToolCall, aa as JobStatus, ag as JobSubmitResult, F as Manifest, aS as ManifestApprovalRequiredSpec, a$ as ManifestContent, aQ as ManifestDryRunSpec, aV as ManifestEffectDeclaration, aU as ManifestEffectSchema, aJ as ManifestEnumRuleSpec, aX as ManifestEventStreamDef, aW as ManifestEventTypeDef, aK as ManifestFilterBySpec, aZ as ManifestImport, H as ManifestListResponse, aY as ManifestOperation, aP as ManifestPostConditionSpec, aH as ManifestPropertySpec, aT as ManifestRelationshipDef, aR as ManifestReverseSpec, aO as ManifestStateMachineSpec, aM as ManifestStateMachineStateSpec, aN as ManifestStateMachineTransitionSpec, aI as ManifestValidationOperator, aL as ManifestValidationRuleSpec, a_ as ManifestVolume, au as ModelRef, r as PermissionProfile, t as PermissionProfileListResponse, q as PermissionRules, a3 as PublishEffectsResult, g as PublishToolsResult, ao as RPCRequest, ar as RPCRequestFromServer, ap as RPCResponse, aF as RecordImport, aE as RecordImportItem, aC as RecordImportItemStatus, aD as RecordImportStats, aB as RecordImportStatus, ax as RecordObjectOptions, ay as RecordObjectResult, az as RecordObjectsChunkInfo, aA as RecordObjectsOptions, k as RecordUserOptions, av as RelationshipInfo, _ as ResolvedEffectApprovalRequired, Y as ResolvedEffectDryRun, X as ResolvedEffectPostCondition, Z as ResolvedEffectReverse, n as Sandbox, p as SandboxListResponse, Q as SemanticVersionDiff, O as SemanticVersionDiffEntry, e as Session, ai as SessionHeapFieldType, aj as SessionHeapFieldValue, ak as SessionHeapVariable, b3 as StreamEvent, b5 as StreamStats, b4 as StreamSubscription, l as Subject, aq as SyncMessage, h as ToolHandler, a4 as ToolInfo, as as ToolInvokeParams, at as ToolResultParams, f as ToolSchema, a6 as ToolsChangedEvent, U as User, L as Version, w as VersionTag, V as VersionTracking, W as WSClient, an as WSClientOptions, al as WSDisconnectInfo, am as WSReconnectErrorInfo } from './client-BeKRGMoT.mjs';
3
3
  export { BuildGranularAgentSystemPromptInput, GeneratedJobCodeIssue, GranularAgentExecutionCheckpoint, GranularAgentHeapSummaryOptions, GranularAgentSessionContext, GranularAgentToolInfo, GranularAgentWorkflowFocus, HarnessContinuationDecision, HarnessControllerBudgets, HarnessProjectionOptions, HarnessPromptLike, HarnessVerifierSnapshot, HarnessVerifierSnapshotInput, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, createHarnessVerifierSnapshot, evaluateContinuation, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, reviewGeneratedJobCode } from './agent-harness.mjs';
4
4
  import '@automerge/automerge';
5
5
  import '@automerge/automerge/slim';
@@ -34,12 +34,14 @@ interface JobPresentation {
34
34
  lists: SessionHeapList[];
35
35
  changedEntries: SessionHeapEntry[];
36
36
  changedLists: SessionHeapList[];
37
+ hasExplicitArtifacts: boolean;
37
38
  }
38
- declare function resolveJobPresentation({ jobId, result, stdout, sessionHeap, }: {
39
+ declare function resolveJobPresentation({ jobId, result, stdout, sessionHeap, allowExplicitArtifacts, }: {
39
40
  jobId: string;
40
41
  result: unknown;
41
42
  stdout?: string[];
42
43
  sessionHeap: SessionHeapSnapshot;
44
+ allowExplicitArtifacts?: boolean;
43
45
  }): JobPresentation;
44
46
 
45
47
  declare function normalizePromptText(value: string): string;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as EndpointMode, T as ToolWithHandler, a as EffectHandlerContext, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, S as SessionHeapEntry, b as SessionHeapList, c as SessionHeapSnapshot, P as Prompt } from './client-CQFKsCTd.js';
2
- export { b1 as APIError, A as AccessTokenProvider, u as Assignment, v as AssignmentListResponse, K as Build, N as BuildListResponse, B as BuildPolicy, J as BuildStatus, C as ConnectOptions, m as ConversationSessionInfo, y as CreateEnvironmentData, s as CreatePermissionProfileData, o as CreateSandboxData, aw as DefineRelationshipOptions, b2 as DeleteResponse, D as DomainState, a8 as EffectHandler, a5 as EffectInfo, a0 as EffectInvocationMetadata, $ as EffectInvocationMode, a1 as EffectSchema, a2 as EffectWithHandler, a7 as EffectsChangedEvent, d as Environment, x as EnvironmentData, z as EnvironmentListResponse, aG as EnvironmentRecordImportSummary, G as Granular, j as GranularAuth, i as GranularOptions, b0 as GraphQLResult, a9 as InstanceEffectHandler, I as InstanceToolHandler, ah as Job, ae as JobFeedbackInput, ad as JobFeedbackMetadata, af as JobFeedbackRecord, ab as JobFeedbackSentiment, ac as JobFeedbackToolCall, aa as JobStatus, ag as JobSubmitResult, F as Manifest, aS as ManifestApprovalRequiredSpec, a$ as ManifestContent, aQ as ManifestDryRunSpec, aV as ManifestEffectDeclaration, aU as ManifestEffectSchema, aJ as ManifestEnumRuleSpec, aX as ManifestEventStreamDef, aW as ManifestEventTypeDef, aK as ManifestFilterBySpec, aZ as ManifestImport, H as ManifestListResponse, aY as ManifestOperation, aP as ManifestPostConditionSpec, aH as ManifestPropertySpec, aT as ManifestRelationshipDef, aR as ManifestReverseSpec, aO as ManifestStateMachineSpec, aM as ManifestStateMachineStateSpec, aN as ManifestStateMachineTransitionSpec, aI as ManifestValidationOperator, aL as ManifestValidationRuleSpec, a_ as ManifestVolume, au as ModelRef, r as PermissionProfile, t as PermissionProfileListResponse, q as PermissionRules, a3 as PublishEffectsResult, g as PublishToolsResult, ao as RPCRequest, ar as RPCRequestFromServer, ap as RPCResponse, aF as RecordImport, aE as RecordImportItem, aC as RecordImportItemStatus, aD as RecordImportStats, aB as RecordImportStatus, ax as RecordObjectOptions, ay as RecordObjectResult, az as RecordObjectsChunkInfo, aA as RecordObjectsOptions, k as RecordUserOptions, av as RelationshipInfo, _ as ResolvedEffectApprovalRequired, Y as ResolvedEffectDryRun, X as ResolvedEffectPostCondition, Z as ResolvedEffectReverse, n as Sandbox, p as SandboxListResponse, Q as SemanticVersionDiff, O as SemanticVersionDiffEntry, e as Session, ai as SessionHeapFieldType, aj as SessionHeapFieldValue, ak as SessionHeapVariable, b3 as StreamEvent, b5 as StreamStats, b4 as StreamSubscription, l as Subject, aq as SyncMessage, h as ToolHandler, a4 as ToolInfo, as as ToolInvokeParams, at as ToolResultParams, f as ToolSchema, a6 as ToolsChangedEvent, U as User, L as Version, w as VersionTag, V as VersionTracking, W as WSClient, an as WSClientOptions, al as WSDisconnectInfo, am as WSReconnectErrorInfo } from './client-CQFKsCTd.js';
1
+ import { E as EndpointMode, T as ToolWithHandler, a as EffectHandlerContext, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, S as SessionHeapEntry, b as SessionHeapList, c as SessionHeapSnapshot, P as Prompt } from './client-BeKRGMoT.js';
2
+ export { b1 as APIError, A as AccessTokenProvider, u as Assignment, v as AssignmentListResponse, K as Build, N as BuildListResponse, B as BuildPolicy, J as BuildStatus, C as ConnectOptions, m as ConversationSessionInfo, y as CreateEnvironmentData, s as CreatePermissionProfileData, o as CreateSandboxData, aw as DefineRelationshipOptions, b2 as DeleteResponse, D as DomainState, a8 as EffectHandler, a5 as EffectInfo, a0 as EffectInvocationMetadata, $ as EffectInvocationMode, a1 as EffectSchema, a2 as EffectWithHandler, a7 as EffectsChangedEvent, d as Environment, x as EnvironmentData, z as EnvironmentListResponse, aG as EnvironmentRecordImportSummary, G as Granular, j as GranularAuth, i as GranularOptions, b0 as GraphQLResult, a9 as InstanceEffectHandler, I as InstanceToolHandler, ah as Job, ae as JobFeedbackInput, ad as JobFeedbackMetadata, af as JobFeedbackRecord, ab as JobFeedbackSentiment, ac as JobFeedbackToolCall, aa as JobStatus, ag as JobSubmitResult, F as Manifest, aS as ManifestApprovalRequiredSpec, a$ as ManifestContent, aQ as ManifestDryRunSpec, aV as ManifestEffectDeclaration, aU as ManifestEffectSchema, aJ as ManifestEnumRuleSpec, aX as ManifestEventStreamDef, aW as ManifestEventTypeDef, aK as ManifestFilterBySpec, aZ as ManifestImport, H as ManifestListResponse, aY as ManifestOperation, aP as ManifestPostConditionSpec, aH as ManifestPropertySpec, aT as ManifestRelationshipDef, aR as ManifestReverseSpec, aO as ManifestStateMachineSpec, aM as ManifestStateMachineStateSpec, aN as ManifestStateMachineTransitionSpec, aI as ManifestValidationOperator, aL as ManifestValidationRuleSpec, a_ as ManifestVolume, au as ModelRef, r as PermissionProfile, t as PermissionProfileListResponse, q as PermissionRules, a3 as PublishEffectsResult, g as PublishToolsResult, ao as RPCRequest, ar as RPCRequestFromServer, ap as RPCResponse, aF as RecordImport, aE as RecordImportItem, aC as RecordImportItemStatus, aD as RecordImportStats, aB as RecordImportStatus, ax as RecordObjectOptions, ay as RecordObjectResult, az as RecordObjectsChunkInfo, aA as RecordObjectsOptions, k as RecordUserOptions, av as RelationshipInfo, _ as ResolvedEffectApprovalRequired, Y as ResolvedEffectDryRun, X as ResolvedEffectPostCondition, Z as ResolvedEffectReverse, n as Sandbox, p as SandboxListResponse, Q as SemanticVersionDiff, O as SemanticVersionDiffEntry, e as Session, ai as SessionHeapFieldType, aj as SessionHeapFieldValue, ak as SessionHeapVariable, b3 as StreamEvent, b5 as StreamStats, b4 as StreamSubscription, l as Subject, aq as SyncMessage, h as ToolHandler, a4 as ToolInfo, as as ToolInvokeParams, at as ToolResultParams, f as ToolSchema, a6 as ToolsChangedEvent, U as User, L as Version, w as VersionTag, V as VersionTracking, W as WSClient, an as WSClientOptions, al as WSDisconnectInfo, am as WSReconnectErrorInfo } from './client-BeKRGMoT.js';
3
3
  export { BuildGranularAgentSystemPromptInput, GeneratedJobCodeIssue, GranularAgentExecutionCheckpoint, GranularAgentHeapSummaryOptions, GranularAgentSessionContext, GranularAgentToolInfo, GranularAgentWorkflowFocus, HarnessContinuationDecision, HarnessControllerBudgets, HarnessProjectionOptions, HarnessPromptLike, HarnessVerifierSnapshot, HarnessVerifierSnapshotInput, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, createHarnessVerifierSnapshot, evaluateContinuation, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, reviewGeneratedJobCode } from './agent-harness.js';
4
4
  import '@automerge/automerge';
5
5
  import '@automerge/automerge/slim';
@@ -34,12 +34,14 @@ interface JobPresentation {
34
34
  lists: SessionHeapList[];
35
35
  changedEntries: SessionHeapEntry[];
36
36
  changedLists: SessionHeapList[];
37
+ hasExplicitArtifacts: boolean;
37
38
  }
38
- declare function resolveJobPresentation({ jobId, result, stdout, sessionHeap, }: {
39
+ declare function resolveJobPresentation({ jobId, result, stdout, sessionHeap, allowExplicitArtifacts, }: {
39
40
  jobId: string;
40
41
  result: unknown;
41
42
  stdout?: string[];
42
43
  sessionHeap: SessionHeapSnapshot;
44
+ allowExplicitArtifacts?: boolean;
43
45
  }): JobPresentation;
44
46
 
45
47
  declare function normalizePromptText(value: string): string;
package/dist/index.js CHANGED
@@ -4567,6 +4567,7 @@ var Session = class {
4567
4567
  client;
4568
4568
  clientId;
4569
4569
  jobsMap = /* @__PURE__ */ new Map();
4570
+ pendingAgentMessagesByJobId = /* @__PURE__ */ new Map();
4570
4571
  eventListeners = /* @__PURE__ */ new Map();
4571
4572
  toolHandlers = /* @__PURE__ */ new Map();
4572
4573
  /** Tracks which tools are instance methods (className set, not static) */
@@ -4724,6 +4725,15 @@ var Session = class {
4724
4725
  createdAt: Date.now()
4725
4726
  });
4726
4727
  this.jobsMap.set(result.jobId, job);
4728
+ const pendingAgentMessages = this.pendingAgentMessagesByJobId.get(
4729
+ result.jobId
4730
+ );
4731
+ if (pendingAgentMessages && pendingAgentMessages.length > 0) {
4732
+ this.pendingAgentMessagesByJobId.delete(result.jobId);
4733
+ for (const message of pendingAgentMessages) {
4734
+ job.replayAgentMessage(message);
4735
+ }
4736
+ }
4727
4737
  return job;
4728
4738
  }
4729
4739
  /**
@@ -5125,6 +5135,22 @@ import { ${allImports} } from "./sandbox-tools";
5125
5135
  this.client.on("job.status", (data) => {
5126
5136
  this.emit("job:status", data);
5127
5137
  });
5138
+ this.client.on("job.agent_message", (data) => {
5139
+ const normalized = normalizeJobAgentMessageEnvelope(data);
5140
+ if (!normalized) return;
5141
+ if (this.jobsMap.has(normalized.jobId)) return;
5142
+ const pending = this.pendingAgentMessagesByJobId.get(normalized.jobId) || [];
5143
+ if (normalized.message.messageId && pending.some(
5144
+ (message) => message.messageId === normalized.message.messageId
5145
+ )) {
5146
+ return;
5147
+ }
5148
+ pending.push(normalized.message);
5149
+ this.pendingAgentMessagesByJobId.set(
5150
+ normalized.jobId,
5151
+ pending.slice(-25)
5152
+ );
5153
+ });
5128
5154
  this.client.on("exec.completed", (data) => {
5129
5155
  this.emit("exec:completed", data);
5130
5156
  });
@@ -5249,6 +5275,22 @@ function sanitizeFeedbackValue(value, depth = 0, seen = /* @__PURE__ */ new Weak
5249
5275
  }
5250
5276
  return truncateFeedbackString(String(value));
5251
5277
  }
5278
+ function normalizeJobAgentMessageEnvelope(data) {
5279
+ const d = data;
5280
+ if (typeof d?.jobId !== "string" || !d.jobId) {
5281
+ return null;
5282
+ }
5283
+ return {
5284
+ jobId: d.jobId,
5285
+ message: {
5286
+ messageId: d.messageId,
5287
+ kind: d.kind === "artifacts" ? "artifacts" : "text",
5288
+ reply: typeof d.reply === "string" ? d.reply : "",
5289
+ show: d.show,
5290
+ timestamp: d.timestamp || Date.now()
5291
+ }
5292
+ };
5293
+ }
5252
5294
  var JobImplementation = class {
5253
5295
  id;
5254
5296
  client;
@@ -5257,6 +5299,8 @@ var JobImplementation = class {
5257
5299
  _resolveResult;
5258
5300
  _rejectResult;
5259
5301
  eventListeners = /* @__PURE__ */ new Map();
5302
+ bufferedAgentMessages = [];
5303
+ bufferedAgentMessageIds = /* @__PURE__ */ new Set();
5260
5304
  metadata;
5261
5305
  constructor(id, client, initialState) {
5262
5306
  this.id = id;
@@ -5415,14 +5459,9 @@ var JobImplementation = class {
5415
5459
  }
5416
5460
  });
5417
5461
  this.client.on("job.agent_message", (data) => {
5418
- const d = data;
5419
- if (d.jobId === id) {
5420
- this.emit("agentMessage", {
5421
- messageId: d.messageId,
5422
- reply: typeof d.reply === "string" ? d.reply : "",
5423
- show: d.show,
5424
- timestamp: d.timestamp || Date.now()
5425
- });
5462
+ const normalized = normalizeJobAgentMessageEnvelope(data);
5463
+ if (normalized?.jobId === id) {
5464
+ this.captureAgentMessage(normalized.message);
5426
5465
  }
5427
5466
  });
5428
5467
  }
@@ -5449,6 +5488,14 @@ var JobImplementation = class {
5449
5488
  this.eventListeners.set(event, []);
5450
5489
  }
5451
5490
  this.eventListeners.get(event).push(handler);
5491
+ if (event === "agentMessage" && this.bufferedAgentMessages.length > 0) {
5492
+ for (const message of this.bufferedAgentMessages) {
5493
+ handler(message);
5494
+ }
5495
+ }
5496
+ }
5497
+ replayAgentMessage(message) {
5498
+ this.captureAgentMessage(message);
5452
5499
  }
5453
5500
  buildFeedbackMetadata() {
5454
5501
  const startedAt = this.metadata.startedAt;
@@ -5518,6 +5565,18 @@ var JobImplementation = class {
5518
5565
  handlers.forEach((h) => h(data));
5519
5566
  }
5520
5567
  }
5568
+ captureAgentMessage(message) {
5569
+ if (message.messageId && this.bufferedAgentMessageIds.has(message.messageId)) {
5570
+ return;
5571
+ }
5572
+ if (message.messageId) {
5573
+ this.bufferedAgentMessageIds.add(message.messageId);
5574
+ }
5575
+ this.bufferedAgentMessages = [...this.bufferedAgentMessages, message].slice(
5576
+ -25
5577
+ );
5578
+ this.emit("agentMessage", message);
5579
+ }
5521
5580
  };
5522
5581
 
5523
5582
  // src/endpoints.ts
@@ -13572,14 +13631,22 @@ function reviewGeneratedJobCode(code) {
13572
13631
  }
13573
13632
  }
13574
13633
  }
13575
- const hasConversationalReturn = /return\s+[`'"]/.test(normalized) || /\breply\s*:/.test(normalized) || /\bagent_message\s*\(/.test(normalized);
13634
+ const hasConversationalReturn = /return\s+[`'"]/.test(normalized) || /\breply\s*:/.test(normalized) || /\bagent_message\s*\(/.test(normalized) || /\bagent_text_message\s*\(/.test(normalized);
13576
13635
  const returnsObjectLiteral = /return\s+\{[\s\S]*?\}/.test(normalized);
13636
+ const returnsShowPayload = /return\s+\{[\s\S]*?\bshow\s*:/.test(normalized);
13577
13637
  const closesLoop = /loop\.close_loop\s*\(/.test(normalized);
13578
13638
  if (!hasConversationalReturn && returnsObjectLiteral && !closesLoop) {
13579
13639
  issues.push({
13580
13640
  code: "missing_user_reply",
13581
13641
  severity: "error",
13582
- 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."
13642
+ 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."
13643
+ });
13644
+ }
13645
+ if (returnsShowPayload) {
13646
+ issues.push({
13647
+ code: "return_show_not_for_ui",
13648
+ severity: "error",
13649
+ 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."
13583
13650
  });
13584
13651
  }
13585
13652
  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