@granular-software/sdk 0.4.25 → 0.4.26

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/index.mjs CHANGED
@@ -4588,6 +4588,22 @@ var Session = class {
4588
4588
  }
4589
4589
  };
4590
4590
  }
4591
+ stringifyConversationValue(value) {
4592
+ if (typeof value === "string") {
4593
+ return value;
4594
+ }
4595
+ if (typeof value === "boolean") {
4596
+ return value ? "Confirmed" : "Canceled";
4597
+ }
4598
+ if (value === void 0) {
4599
+ return "";
4600
+ }
4601
+ try {
4602
+ return JSON.stringify(value, null, 2);
4603
+ } catch {
4604
+ return String(value);
4605
+ }
4606
+ }
4591
4607
  // --- Public API ---
4592
4608
  get document() {
4593
4609
  return this.client.doc;
@@ -4738,6 +4754,20 @@ var Session = class {
4738
4754
  answer: resolvedAnswer,
4739
4755
  value: resolvedAnswer
4740
4756
  });
4757
+ try {
4758
+ const content = this.stringifyConversationValue(resolvedAnswer);
4759
+ if (content.trim()) {
4760
+ await this.appendConversationMessage({
4761
+ role: "user",
4762
+ content,
4763
+ promptId
4764
+ });
4765
+ }
4766
+ } catch {
4767
+ }
4768
+ }
4769
+ async appendConversationMessage(input) {
4770
+ return this.client.call("conversation.append", input);
4741
4771
  }
4742
4772
  /**
4743
4773
  * Get the current list of available effects.
@@ -14762,6 +14792,306 @@ function resolveJobPresentation({
14762
14792
  };
14763
14793
  }
14764
14794
 
14765
- export { Environment, Granular, Session, WSClient, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, createHarnessVerifierSnapshot, evaluateContinuation, extractPromptTokens, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, invokeRegisteredEffect, isLocalApiUrl, normalizeEffectBehaviors, normalizePrompt, normalizePromptText, normalizePromptType, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, resolveApiUrl, resolveAuthTokenForApiUrl, resolveJobPresentation, resolvePromptAnswer, reviewGeneratedJobCode, scorePromptChoiceMatch };
14795
+ // src/session-transcript.ts
14796
+ var EMPTY_HEAP = {
14797
+ entriesByPath: {},
14798
+ listsByName: {},
14799
+ variablesByName: {}};
14800
+ function asRecord4(value) {
14801
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
14802
+ return value;
14803
+ }
14804
+ function asArray2(value) {
14805
+ return Array.isArray(value) ? value : [];
14806
+ }
14807
+ function asNumber(value) {
14808
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
14809
+ }
14810
+ function asString(value) {
14811
+ return typeof value === "string" ? value : void 0;
14812
+ }
14813
+ function trimString(value) {
14814
+ return typeof value === "string" ? value.trim() : "";
14815
+ }
14816
+ function normalizeShowRefs(value) {
14817
+ const record = asRecord4(value);
14818
+ if (!record) return void 0;
14819
+ const normalizeRefs = (input) => {
14820
+ if (!Array.isArray(input)) return void 0;
14821
+ const refs = Array.from(
14822
+ new Set(
14823
+ input.filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean)
14824
+ )
14825
+ );
14826
+ return refs.length > 0 ? refs : void 0;
14827
+ };
14828
+ const show = {
14829
+ entryPaths: normalizeRefs(record.entryPaths),
14830
+ listNames: normalizeRefs(record.listNames),
14831
+ variableNames: normalizeRefs(record.variableNames)
14832
+ };
14833
+ return show.entryPaths || show.listNames || show.variableNames ? show : void 0;
14834
+ }
14835
+ function stringifyTranscriptValue(value, fallback = "") {
14836
+ if (typeof value === "string") {
14837
+ return value.trim() || fallback;
14838
+ }
14839
+ if (typeof value === "boolean") {
14840
+ return value ? "Confirmed" : "Canceled";
14841
+ }
14842
+ if (value === void 0) {
14843
+ return fallback;
14844
+ }
14845
+ try {
14846
+ const json = JSON.stringify(value, null, 2);
14847
+ if (!json || json === "undefined") return fallback;
14848
+ return json.length > 2e3 ? `${json.slice(0, 2e3)}...` : json;
14849
+ } catch {
14850
+ return String(value);
14851
+ }
14852
+ }
14853
+ function buildArtifactHistory(show) {
14854
+ if (!show) return void 0;
14855
+ return `[Agent message]
14856
+ ${stringifyTranscriptValue({ show }, "")}`;
14857
+ }
14858
+ function normalizeConversationMessage(raw) {
14859
+ const record = asRecord4(raw);
14860
+ if (!record) return null;
14861
+ const role = record.role === "user" ? "user" : record.role === "assistant" ? "assistant" : null;
14862
+ if (!role) return null;
14863
+ const content = trimString(
14864
+ record.content ?? record.reply ?? record.message ?? record.text
14865
+ );
14866
+ const show = normalizeShowRefs(record.show);
14867
+ const id = asString(record.id) || crypto.randomUUID();
14868
+ const timestamp = asNumber(record.timestamp) || asNumber(record.ts) || 0;
14869
+ if (!content && !show) return null;
14870
+ return {
14871
+ id,
14872
+ role,
14873
+ content,
14874
+ timestamp,
14875
+ jobId: asString(record.jobId),
14876
+ promptId: asString(record.promptId),
14877
+ show,
14878
+ historyContent: role === "assistant" ? content ? `[Assistant reply]
14879
+ ${content}` : buildArtifactHistory(show) : void 0,
14880
+ source: "conversation"
14881
+ };
14882
+ }
14883
+ function normalizePromptEntries(jobId, rawPrompts, conversationPromptIds) {
14884
+ const promptsById = asRecord4(rawPrompts) || {};
14885
+ return Object.values(promptsById).map((value) => asRecord4(value)).filter((value) => Boolean(value)).sort(
14886
+ (left, right) => (asNumber(left.openedAt) || asNumber(left.answeredAt) || 0) - (asNumber(right.openedAt) || asNumber(right.answeredAt) || 0)
14887
+ ).flatMap((prompt) => {
14888
+ const promptId = asString(prompt.promptId);
14889
+ if (!promptId || conversationPromptIds.has(promptId)) return [];
14890
+ const title = trimString(prompt.title);
14891
+ const message = trimString(prompt.message);
14892
+ const assistantContent = message || title || "Input required";
14893
+ const openedAt = asNumber(prompt.openedAt) || 0;
14894
+ const answeredAt = asNumber(prompt.answeredAt) || openedAt;
14895
+ const entries = [
14896
+ {
14897
+ id: `prompt:${promptId}:assistant`,
14898
+ role: "assistant",
14899
+ content: assistantContent,
14900
+ timestamp: openedAt,
14901
+ jobId,
14902
+ promptId,
14903
+ historyContent: `[Assistant reply]
14904
+ ${assistantContent}`,
14905
+ source: "job_prompt"
14906
+ }
14907
+ ];
14908
+ if (Object.prototype.hasOwnProperty.call(prompt, "answer")) {
14909
+ entries.push({
14910
+ id: `prompt:${promptId}:user`,
14911
+ role: "user",
14912
+ content: stringifyTranscriptValue(prompt.answer, ""),
14913
+ timestamp: answeredAt,
14914
+ jobId,
14915
+ promptId,
14916
+ source: "job_prompt"
14917
+ });
14918
+ }
14919
+ return entries;
14920
+ });
14921
+ }
14922
+ function normalizeAgentMessageEntries(jobId, rawMessages) {
14923
+ return asArray2(rawMessages).map((value) => asRecord4(value)).filter((value) => Boolean(value)).sort(
14924
+ (left, right) => (asNumber(left.timestamp) || asNumber(left.ts) || 0) - (asNumber(right.timestamp) || asNumber(right.ts) || 0)
14925
+ ).flatMap((message) => {
14926
+ const messageId = asString(message.messageId) || asString(message.id) || crypto.randomUUID();
14927
+ const timestamp = asNumber(message.timestamp) || asNumber(message.ts) || 0;
14928
+ const reply = trimString(
14929
+ message.reply ?? message.message ?? message.text ?? message.content
14930
+ );
14931
+ const show = normalizeShowRefs(message.show);
14932
+ const entries = [];
14933
+ if (reply) {
14934
+ entries.push({
14935
+ id: `agent:${messageId}:text`,
14936
+ role: "assistant",
14937
+ content: reply,
14938
+ timestamp,
14939
+ jobId,
14940
+ historyContent: `[Assistant reply]
14941
+ ${reply}`,
14942
+ source: "job_agent_message"
14943
+ });
14944
+ }
14945
+ if (show) {
14946
+ entries.push({
14947
+ id: `agent:${messageId}:artifacts`,
14948
+ role: "assistant",
14949
+ content: "",
14950
+ timestamp,
14951
+ jobId,
14952
+ show,
14953
+ historyContent: buildArtifactHistory(show),
14954
+ source: "job_agent_message"
14955
+ });
14956
+ }
14957
+ return entries;
14958
+ });
14959
+ }
14960
+ function buildJobFallbackEntries(jobId, job, sessionHeap) {
14961
+ const timestamp = asNumber(job.finishedAt) || asNumber(job.startedAt) || asNumber(job.submittedAt) || 0;
14962
+ const resultPreview = stringifyTranscriptValue(
14963
+ job.result,
14964
+ "No job result recorded."
14965
+ );
14966
+ const presentation = resolveJobPresentation({
14967
+ jobId,
14968
+ result: job.result,
14969
+ stdout: [],
14970
+ sessionHeap
14971
+ });
14972
+ const entries = [];
14973
+ const responseText = presentation.responseText || "";
14974
+ if (responseText) {
14975
+ entries.push({
14976
+ id: `job:${jobId}:result-text`,
14977
+ role: "assistant",
14978
+ content: responseText,
14979
+ timestamp,
14980
+ jobId,
14981
+ historyContent: `[Assistant reply]
14982
+ ${responseText}`,
14983
+ source: "job_result"
14984
+ });
14985
+ }
14986
+ const show = {
14987
+ entryPaths: presentation.entries.map((entry) => entry.path),
14988
+ listNames: presentation.lists.map((list) => list.name)
14989
+ };
14990
+ if (show.entryPaths && show.entryPaths.length > 0 || show.listNames && show.listNames.length > 0) {
14991
+ entries.push({
14992
+ id: `job:${jobId}:result-artifacts`,
14993
+ role: "assistant",
14994
+ content: "",
14995
+ timestamp,
14996
+ jobId,
14997
+ show,
14998
+ historyContent: buildArtifactHistory(show),
14999
+ source: "job_result"
15000
+ });
15001
+ }
15002
+ if (entries.length === 0 && trimString(job.error)) {
15003
+ entries.push({
15004
+ id: `job:${jobId}:result-error`,
15005
+ role: "assistant",
15006
+ content: trimString(job.error),
15007
+ timestamp,
15008
+ jobId,
15009
+ historyContent: `[Assistant reply]
15010
+ ${trimString(job.error)}`,
15011
+ source: "job_result"
15012
+ });
15013
+ }
15014
+ if (entries.length === 0 && resultPreview && resultPreview !== "No job result recorded.") {
15015
+ entries.push({
15016
+ id: `job:${jobId}:result-preview`,
15017
+ role: "assistant",
15018
+ content: resultPreview,
15019
+ timestamp,
15020
+ jobId,
15021
+ historyContent: `[Assistant reply]
15022
+ ${resultPreview}`,
15023
+ source: "job_result"
15024
+ });
15025
+ }
15026
+ return entries;
15027
+ }
15028
+ function buildJobCodeEntry(jobId, job) {
15029
+ const code = trimString(job.source);
15030
+ if (!code) return null;
15031
+ const jobStatus = asString(job.status);
15032
+ const error = jobStatus === "failed" || jobStatus === "canceled" || jobStatus === "timeout" ? trimString(job.error) || `Job ${jobStatus}` : void 0;
15033
+ return {
15034
+ id: `job:${jobId}:code`,
15035
+ role: "assistant",
15036
+ content: "",
15037
+ timestamp: asNumber(job.submittedAt) || asNumber(job.startedAt) || asNumber(job.finishedAt) || 0,
15038
+ jobId,
15039
+ code,
15040
+ jobStatus,
15041
+ jobResultPreview: stringifyTranscriptValue(job.result, "No job result recorded."),
15042
+ error,
15043
+ source: "job_code"
15044
+ };
15045
+ }
15046
+ function buildSessionTranscript(input) {
15047
+ const liveDoc = input.liveDoc || null;
15048
+ const sessionHeap = input.sessionHeap || EMPTY_HEAP;
15049
+ const transcript = [];
15050
+ const conversationMessages = asArray2(asRecord4(liveDoc?.conversation)?.messages).map((message) => normalizeConversationMessage(message)).filter((message) => Boolean(message));
15051
+ const conversationPromptIds = new Set(
15052
+ conversationMessages.map((message) => message.promptId).filter((promptId) => Boolean(promptId))
15053
+ );
15054
+ const assistantConversationJobIds = new Set(
15055
+ conversationMessages.filter((message) => message.role === "assistant" && Boolean(message.jobId)).map((message) => message.jobId)
15056
+ );
15057
+ transcript.push(...conversationMessages);
15058
+ const jobsById = asRecord4(asRecord4(liveDoc?.jobs)?.byId) || {};
15059
+ const jobs = Object.values(jobsById).map((value) => asRecord4(value)).filter((value) => Boolean(value)).sort(
15060
+ (left, right) => (asNumber(left.submittedAt) || asNumber(left.startedAt) || asNumber(left.finishedAt) || 0) - (asNumber(right.submittedAt) || asNumber(right.startedAt) || asNumber(right.finishedAt) || 0)
15061
+ );
15062
+ for (const job of jobs) {
15063
+ const jobId = asString(job.jobId);
15064
+ if (!jobId) continue;
15065
+ const codeEntry = buildJobCodeEntry(jobId, job);
15066
+ if (codeEntry) {
15067
+ transcript.push(codeEntry);
15068
+ }
15069
+ transcript.push(
15070
+ ...normalizePromptEntries(jobId, job.prompts, conversationPromptIds)
15071
+ );
15072
+ if (!assistantConversationJobIds.has(jobId)) {
15073
+ const agentEntries = normalizeAgentMessageEntries(jobId, job.agentMessages);
15074
+ if (agentEntries.length > 0) {
15075
+ transcript.push(...agentEntries);
15076
+ } else {
15077
+ transcript.push(
15078
+ ...buildJobFallbackEntries(
15079
+ jobId,
15080
+ job,
15081
+ sessionHeap
15082
+ )
15083
+ );
15084
+ }
15085
+ }
15086
+ }
15087
+ return transcript.sort((left, right) => {
15088
+ if (left.timestamp !== right.timestamp) {
15089
+ return left.timestamp - right.timestamp;
15090
+ }
15091
+ return left.id.localeCompare(right.id);
15092
+ });
15093
+ }
15094
+
15095
+ export { Environment, Granular, Session, WSClient, buildContinuationInstruction, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, buildSessionTranscript, createHarnessVerifierSnapshot, evaluateContinuation, extractPromptTokens, getCurrentClosureId, getExclusivePromptTarget, hasOpenPrompt, invokeRegisteredEffect, isLocalApiUrl, normalizeEffectBehaviors, normalizePrompt, normalizePromptText, normalizePromptType, projectHeapSummary, projectLoopSummary, projectWorkflowFocus, projectWorkflowSummary, resolveApiUrl, resolveAuthTokenForApiUrl, resolveJobPresentation, resolvePromptAnswer, reviewGeneratedJobCode, scorePromptChoiceMatch };
14766
15096
  //# sourceMappingURL=index.mjs.map
14767
15097
  //# sourceMappingURL=index.mjs.map