@mgamadeus/ddd-agents 0.16.1 → 0.17.1
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/README.md +113 -10
- package/boundary.json +15 -1
- package/dist/admin-chat-widgets.js +158 -0
- package/dist/admin-chat-widgets.js.map +1 -0
- package/dist/admin.js +92 -65
- package/dist/admin.js.map +1 -1
- package/dist/chat.js +19 -19
- package/dist/chat.js.map +1 -1
- package/dist/chunks/AgentScheduleOrderDraftPanel-DM6pz_hc.js +304 -0
- package/dist/chunks/AgentScheduleOrderDraftPanel-DM6pz_hc.js.map +1 -0
- package/dist/chunks/{ConversationMarkdown-DNQcVuz-.js → ConversationMarkdown-dj0EF6bu.js} +5 -5
- package/dist/chunks/{ConversationMarkdown-DNQcVuz-.js.map → ConversationMarkdown-dj0EF6bu.js.map} +1 -1
- package/dist/chunks/{ConversationMessageInputComposerWidgets-BlpIule7.js → ConversationMessageInputComposerWidgets-ClgCwnVW.js} +6 -6
- package/dist/chunks/{ConversationMessageInputComposerWidgets-BlpIule7.js.map → ConversationMessageInputComposerWidgets-ClgCwnVW.js.map} +1 -1
- package/dist/chunks/{VoiceBarsIcon-eODB_UTI.js → VoiceBarsIcon-B6VTVtdB.js} +4 -4
- package/dist/chunks/{VoiceBarsIcon-eODB_UTI.js.map → VoiceBarsIcon-B6VTVtdB.js.map} +1 -1
- package/dist/chunks/{WebSearchResultsConversationWidget-l9Aek_lG.js → WebSearchResultsConversationWidget-BVMwJfhL.js} +73 -64
- package/dist/chunks/WebSearchResultsConversationWidget-BVMwJfhL.js.map +1 -0
- package/dist/chunks/{agents-http-trace-mappers-rsbGAf2_.js → agents-http-trace-mappers-CuGZOFu-.js} +53 -14
- package/dist/chunks/agents-http-trace-mappers-CuGZOFu-.js.map +1 -0
- package/dist/chunks/{browser-request-interception-D678IemW.js → browser-request-interception-BnOQWLaJ.js} +2 -2
- package/dist/chunks/{browser-request-interception-D678IemW.js.map → browser-request-interception-BnOQWLaJ.js.map} +1 -1
- package/dist/chunks/{canvas-label-context-C1Pc_Ldo.js → canvas-label-context-5yvbmK-V.js} +3 -3
- package/dist/chunks/{canvas-label-context-C1Pc_Ldo.js.map → canvas-label-context-5yvbmK-V.js.map} +1 -1
- package/dist/chunks/{canvas-reducers-BYArW_Ji.js → canvas-reducers-133Kl1QH.js} +2 -2
- package/dist/chunks/{canvas-reducers-BYArW_Ji.js.map → canvas-reducers-133Kl1QH.js.map} +1 -1
- package/dist/chunks/{canvasBodies-BpLPp-S8.js → canvasBodies-B2M6aWao.js} +4 -4
- package/dist/chunks/{canvasBodies-BpLPp-S8.js.map → canvasBodies-B2M6aWao.js.map} +1 -1
- package/dist/chunks/{canvasStorage-DSspwRMg.js → canvasStorage-B69JHOLd.js} +2 -2
- package/dist/chunks/{canvasStorage-DSspwRMg.js.map → canvasStorage-B69JHOLd.js.map} +1 -1
- package/dist/chunks/{content-from-unified-diff-DWyBHRSy.js → content-from-unified-diff-BKdgop63.js} +39 -5
- package/dist/chunks/content-from-unified-diff-BKdgop63.js.map +1 -0
- package/dist/chunks/{contract-DtFmOk91.js → contract-CQ6PO_e8.js} +2 -2
- package/dist/chunks/{contract-DtFmOk91.js.map → contract-CQ6PO_e8.js.map} +1 -1
- package/dist/chunks/{conversation-Cbrqtx-_.js → conversation-VosmRbsr.js} +4 -2
- package/dist/chunks/{conversation-Cbrqtx-_.js.map → conversation-VosmRbsr.js.map} +1 -1
- package/dist/chunks/conversation-trace-fVeh6Lg6.js.map +1 -1
- package/dist/chunks/{widget-name-resolver-DXIE9JUr.js → conversationWidgetRegistry-webrYtkI.js} +810 -530
- package/dist/chunks/conversationWidgetRegistry-webrYtkI.js.map +1 -0
- package/dist/chunks/{index-DZovGMpG.js → index-DAEGct6X.js} +61 -61
- package/dist/chunks/index-DAEGct6X.js.map +1 -0
- package/dist/chunks/{link-navigation-a_sRfmsj.js → link-navigation-DQWyeNkx.js} +2 -2
- package/dist/chunks/{link-navigation-a_sRfmsj.js.map → link-navigation-DQWyeNkx.js.map} +1 -1
- package/dist/chunks/{withPollingChangeSubscription-Cz3Diolr.js → withPollingChangeSubscription-Ct8kjmlL.js} +19 -2
- package/dist/chunks/withPollingChangeSubscription-Ct8kjmlL.js.map +1 -0
- package/dist/client-testing.js +39 -5
- package/dist/client-testing.js.map +1 -1
- package/dist/client.js +43 -14
- package/dist/client.js.map +1 -1
- package/dist/contract.js +4 -3
- package/dist/files/i18n-keys.json +619 -15
- package/dist/files/widgets/DriveFilesConversationWidget/DriveFilesConversationWidget.md +4 -2
- package/dist/files/widgets/OwnerStepConfirmationConversationWidget/OwnerStepConfirmationConversationWidget.md +54 -0
- package/dist/files/widgets/OwnerStepConfirmationConversationWidget/owner-step-confirmation.preview-fixtures.json +16 -0
- package/dist/image-render.js +8 -8
- package/dist/index.js +16 -16
- package/dist/kit.js +2 -2
- package/dist/preview.js +124 -117
- package/dist/preview.js.map +1 -1
- package/dist/provider.js +2 -2
- package/dist/renderer.js +53 -52
- package/dist/styles.css +46 -0
- package/dist/types/admin/connections/connection-parts.d.ts +2 -1
- package/dist/types/admin/schedules/AgentScheduleOrderDraftPanel.d.ts +45 -0
- package/dist/types/admin/schedules/AgentSchedulesPanel.d.ts +11 -3
- package/dist/types/admin/schedules/agent-schedules-api.d.ts +38 -2
- package/dist/types/admin/schedules/agent-schedules-format.d.ts +22 -1
- package/dist/types/admin/schedules/agent-schedules-types.d.ts +91 -1
- package/dist/types/admin-chat-widgets/ScheduleOrderApprovalConversationWidget.d.ts +37 -0
- package/dist/types/admin-chat-widgets/registerScheduleOrderApprovalWidget.d.ts +11 -0
- package/dist/types/chat/trace/TurnMetaLine.d.ts +5 -3
- package/dist/types/chat/trace/trace-counts.d.ts +2 -0
- package/dist/types/chat/trace/trace-types.d.ts +4 -0
- package/dist/types/client/AgentsConversationClient.d.ts +17 -1
- package/dist/types/client/http/agents-http-mappers.d.ts +4 -2
- package/dist/types/client/http/agents-http-trace-wire.d.ts +2 -0
- package/dist/types/client/http/agents-http-wire.d.ts +24 -0
- package/dist/types/client/testing/createInMemoryAgentsConversationClient.d.ts +13 -1
- package/dist/types/contract/conversation-trace.d.ts +4 -0
- package/dist/types/contract/conversation.d.ts +43 -0
- package/dist/types/entries/admin-chat-widgets.d.ts +2 -0
- package/dist/types/entries/admin.d.ts +4 -2
- package/dist/types/entries/renderer.d.ts +1 -1
- package/dist/types/renderer/widget-tree/composed-node-schema.d.ts +20 -3
- package/dist/types/widgets/DriveFilesConversationWidget/shared/drive-files.d.ts +3 -1
- package/dist/voice.js +2 -2
- package/dist/widgets.js +4 -4
- package/package.json +7 -1
- package/public-api.json +39 -0
- package/dist/chunks/WebSearchResultsConversationWidget-l9Aek_lG.js.map +0 -1
- package/dist/chunks/agents-http-trace-mappers-rsbGAf2_.js.map +0 -1
- package/dist/chunks/content-from-unified-diff-DWyBHRSy.js.map +0 -1
- package/dist/chunks/index-DZovGMpG.js.map +0 -1
- package/dist/chunks/widget-name-resolver-DXIE9JUr.js.map +0 -1
- package/dist/chunks/withPollingChangeSubscription-Cz3Diolr.js.map +0 -1
package/dist/chunks/{agents-http-trace-mappers-rsbGAf2_.js → agents-http-trace-mappers-CuGZOFu-.js}
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { C as CONVERSATION_TRACE_LEVELS } from "./conversation-trace-fVeh6Lg6.js";
|
|
3
|
-
import { b as AGENTS_CLIENT_CONTEXT_LIMITS, A as AgentsClientError, C as CONVERSATION_BACKGROUND_JOB_LIVE_STATUSES, c as CONVERSATION_BACKGROUND_JOB_STATES } from "./conversation-
|
|
3
|
+
import { b as AGENTS_CLIENT_CONTEXT_LIMITS, A as AgentsClientError, C as CONVERSATION_BACKGROUND_JOB_LIVE_STATUSES, c as CONVERSATION_BACKGROUND_JOB_STATES, d as CONVERSATION_STEP_CONFIRMATION_STATUSES } from "./conversation-VosmRbsr.js";
|
|
4
4
|
const RUN_STATES = [
|
|
5
5
|
"IDLE",
|
|
6
6
|
"QUEUED",
|
|
@@ -174,6 +174,35 @@ const mapWireBackgroundJobStop = (response) => {
|
|
|
174
174
|
state: readVocabularyValue$1(CONVERSATION_BACKGROUND_JOB_STATES, wireStop.state)
|
|
175
175
|
};
|
|
176
176
|
};
|
|
177
|
+
const mapWireOwnerConsentLine = (wireLine) => {
|
|
178
|
+
if (wireLine === null || typeof wireLine !== "object" || typeof wireLine.template !== "string" || wireLine.template === "") return null;
|
|
179
|
+
const replacements = {};
|
|
180
|
+
const wireReplacements = wireLine.replacements;
|
|
181
|
+
if (wireReplacements !== null && typeof wireReplacements === "object" && !Array.isArray(wireReplacements)) {
|
|
182
|
+
for (const [name, value] of Object.entries(wireReplacements)) {
|
|
183
|
+
if (typeof value === "string" || typeof value === "number") replacements[name] = String(value);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
return { template: wireLine.template, replacements };
|
|
187
|
+
};
|
|
188
|
+
const mapWireStepConfirmation = (response) => {
|
|
189
|
+
const wireStep = response !== null && typeof response === "object" ? response.agentStepConfirmation : null;
|
|
190
|
+
const id = wireStep ? readNumberOrNull$1(wireStep.id) : null;
|
|
191
|
+
if (!wireStep || id === null) return null;
|
|
192
|
+
return {
|
|
193
|
+
id,
|
|
194
|
+
toolName: readStringOrNull$1(wireStep.toolName),
|
|
195
|
+
contentHash: readStringOrNull$1(wireStep.contentHash),
|
|
196
|
+
targetLine: readStringOrNull$1(wireStep.targetLine) ?? "",
|
|
197
|
+
consequenceLine: readStringOrNull$1(wireStep.consequenceLine) ?? "",
|
|
198
|
+
targetText: mapWireOwnerConsentLine(wireStep.targetText),
|
|
199
|
+
consequenceText: mapWireOwnerConsentLine(wireStep.consequenceText),
|
|
200
|
+
status: readVocabularyValue$1(CONVERSATION_STEP_CONFIRMATION_STATUSES, wireStep.status),
|
|
201
|
+
expiresAt: readStringOrNull$1(wireStep.expiresAt),
|
|
202
|
+
answeredAt: readStringOrNull$1(wireStep.answeredAt),
|
|
203
|
+
resultExcerpt: readStringOrNull$1(wireStep.resultExcerpt)
|
|
204
|
+
};
|
|
205
|
+
};
|
|
177
206
|
const mapWireSearchHit = (wireHit) => ({
|
|
178
207
|
messageId: readNumberOrNull$1(wireHit.messageId),
|
|
179
208
|
conversationId: readNumberOrNull$1(wireHit.conversationId),
|
|
@@ -705,6 +734,13 @@ const readCachePercent = (wireTotals) => {
|
|
|
705
734
|
if (inputTokens === null || cachedInputTokens === null || inputTokens <= 0) return null;
|
|
706
735
|
return Math.round(cachedInputTokens / inputTokens * 100);
|
|
707
736
|
};
|
|
737
|
+
const readNewestModelCallInputTokens = (steps) => {
|
|
738
|
+
for (let position = steps.length - 1; position >= 0; position -= 1) {
|
|
739
|
+
const step = steps[position];
|
|
740
|
+
if (step.kind === "MODEL_CALL" && step.modelCall !== null) return step.modelCall.inputTokens;
|
|
741
|
+
}
|
|
742
|
+
return null;
|
|
743
|
+
};
|
|
708
744
|
const mapWireTurnTraceTotals = (wireTurn, steps) => {
|
|
709
745
|
const wireTotals = isPlainObject(wireTurn.totals) ? { ...wireTurn, ...wireTurn.totals } : wireTurn;
|
|
710
746
|
return {
|
|
@@ -714,6 +750,8 @@ const mapWireTurnTraceTotals = (wireTurn, steps) => {
|
|
|
714
750
|
cachedInputTokens: readNumberOrNull(wireTotals.cachedInputTokens),
|
|
715
751
|
cachePercent: readCachePercent(wireTotals),
|
|
716
752
|
costInUsd: readNumberOrNull(wireTotals.costInUSD ?? wireTotals.costInUsd),
|
|
753
|
+
modelCallCount: readNumberOrNull(wireTotals.modelCallCount),
|
|
754
|
+
newestModelCallInputTokens: readNewestModelCallInputTokens(steps),
|
|
717
755
|
stepCount: readNumberOrNull(wireTotals.stepCount) ?? steps.length,
|
|
718
756
|
commandCount: readNumberOrNull(wireTotals.commandCount) ?? steps.filter((step) => step.terminal !== null).length,
|
|
719
757
|
fileCount: readNumberOrNull(wireTotals.fileCount) ?? steps.reduce((count, step) => count + step.fileChanges.length, 0),
|
|
@@ -822,6 +860,7 @@ const mapWireTurnStop = (response) => {
|
|
|
822
860
|
return { isStopped: wireStop.isStopped === true, runState: readStringOrNull(wireStop.runState) };
|
|
823
861
|
};
|
|
824
862
|
export {
|
|
863
|
+
mapWireTurnTrace as A,
|
|
825
864
|
mapWireTraceViewPolicy as a,
|
|
826
865
|
mapWireConversationRunState as b,
|
|
827
866
|
mapWireBoundConversationSubject as c,
|
|
@@ -836,17 +875,17 @@ export {
|
|
|
836
875
|
mapWireTurnStop as l,
|
|
837
876
|
mapWireConversation as m,
|
|
838
877
|
mapWireSelectableModel as n,
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
878
|
+
mapWireStepConfirmation as o,
|
|
879
|
+
mapClientContextToWire as p,
|
|
880
|
+
mapHttpFailureToAgentsClientError as q,
|
|
842
881
|
readWireSetElements as r,
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
};
|
|
852
|
-
//# sourceMappingURL=agents-http-trace-mappers-
|
|
882
|
+
mapWireBackgroundJob as s,
|
|
883
|
+
mapWireRunningBackgroundJobs as t,
|
|
884
|
+
mapWireTraceBackgroundJob as u,
|
|
885
|
+
mapWireTraceFileChange as v,
|
|
886
|
+
mapWireTraceMessage as w,
|
|
887
|
+
mapWireTraceStep as x,
|
|
888
|
+
mapWireTraceTaskPlanItems as y,
|
|
889
|
+
mapWireTraceTaskPlanRejections as z
|
|
890
|
+
};
|
|
891
|
+
//# sourceMappingURL=agents-http-trace-mappers-CuGZOFu-.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agents-http-trace-mappers-CuGZOFu-.js","sources":["../../src/client/http/agents-http-mappers.ts","../../src/client/http/agents-http-trace-mappers.ts"],"sourcesContent":["import {\n AGENTS_CLIENT_CONTEXT_LIMITS,\n AgentsClientError,\n CONVERSATION_BACKGROUND_JOB_LIVE_STATUSES,\n CONVERSATION_BACKGROUND_JOB_STATES,\n type AgentsClientContext,\n type AgentsClientErrorKind,\n type AgentsConversation,\n type AgentsConversationMessage,\n type BoundConversationSubject,\n type ConversationActivity,\n type ConversationActivityElement,\n type ConversationBackgroundJob,\n type ConversationBackgroundJobStop,\n CONVERSATION_STEP_CONFIRMATION_STATUSES,\n type ConversationStepConfirmation,\n type ConversationStepConfirmationLine,\n type ConversationMessageAuthorType,\n type ConversationMessageRole,\n type ConversationMessageSearchHit,\n type ConversationMessageStatus,\n type ConversationMessageType,\n type ConversationProgressStep,\n type ConversationRunState,\n type ConversationRunStateRead,\n type ConversationSearchGroup,\n type ConversationSubAgent,\n type SelectableModel,\n} from \"../../contract/conversation\";\nimport type {\n WireActivityLine,\n WireBackgroundJob,\n WireBackgroundJobStopResponse,\n WireOwnerConsentLine,\n WireStepConfirmation,\n WireStepConfirmationResponse,\n WireBoundConversationSubject,\n WireClientContext,\n WireClientContextRouteParameter,\n WireConversation,\n WireConversationActivityResponse,\n WireConversationMessage,\n WireConversationRunStateResponse,\n WireConversationSearchGroup,\n WireCustomerProgressStep,\n WireDelegationSubAgentRecord,\n WireErrorBody,\n WireSelectableModel,\n WireSemanticSearchHit,\n WireSet,\n} from \"./agents-http-wire\";\n\n// The vocabularies of the contract: a wire value outside one maps to null.\nconst RUN_STATES: readonly ConversationRunState[] = [\n \"IDLE\",\n \"QUEUED\",\n \"RUNNING\",\n \"AWAITING_DELEGATES\",\n \"FAILED\",\n \"COMPLETED\",\n \"CANCELLED\",\n];\nconst MESSAGE_ROLES: readonly ConversationMessageRole[] = [\"SYSTEM\", \"USER\", \"ASSISTANT\"];\nconst MESSAGE_TYPES: readonly ConversationMessageType[] = [\n \"TEXT\",\n \"TOOL_CALL\",\n \"CHECKPOINT\",\n \"ERROR\",\n \"SIGNAL\",\n \"TOOL_MESSAGE\",\n];\nconst MESSAGE_STATUSES: readonly ConversationMessageStatus[] = [\n \"PENDING\",\n \"RUNNING\",\n \"CANCEL_REQUESTED\",\n \"CANCELLED\",\n \"COMPLETED\",\n \"FAILED\",\n];\nconst AUTHOR_TYPES: readonly ConversationMessageAuthorType[] = [\"USER\", \"ASSISTANT\", \"AGENT\", \"TOOL\"];\nconst PROGRESS_STEP_STATUSES: readonly ConversationProgressStep[\"status\"][] = [\"done\", \"active\", \"upcoming\"];\nconst ACTIVITY_STATES: readonly NonNullable<ConversationActivityElement[\"state\"]>[] = [\n \"queued\",\n \"running\",\n \"finished\",\n \"failed\",\n \"skipped\",\n];\nconst ACTIVITY_KINDS: readonly NonNullable<ConversationActivityElement[\"kind\"]>[] = [\n \"tool\",\n \"delegation\",\n \"background\",\n \"long\",\n \"turnStart\",\n];\n\nconst readVocabularyValue = <Value extends string>(vocabulary: readonly Value[], value: unknown): Value | null =>\n typeof value === \"string\" && (vocabulary as readonly string[]).includes(value) ? (value as Value) : null;\n\nconst readNumberOrNull = (value: unknown): number | null =>\n typeof value === \"number\" && Number.isFinite(value) ? value : null;\n\nconst readStringOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\n\n/** The elements of a serialized set (`{ elements: [...] }`), a plain array, or the values of a keyed object. */\nexport const readWireSetElements = <Element>(\n wireSet: WireSet<Element> | Record<string, Element> | null | undefined,\n): Element[] => {\n if (!wireSet) return [];\n if (Array.isArray(wireSet)) return wireSet;\n if (typeof wireSet === \"object\" && \"elements\" in wireSet) {\n const elements = (wireSet as { elements?: Element[] | null }).elements;\n return Array.isArray(elements) ? elements : [];\n }\n return Object.values(wireSet as Record<string, Element>);\n};\n\nconst mapWireProgressStep = (wireStep: WireCustomerProgressStep): ConversationProgressStep => ({\n key: wireStep.key ?? \"\",\n label: wireStep.customerLabel ?? \"\",\n status: readVocabularyValue(PROGRESS_STEP_STATUSES, wireStep.status) ?? \"upcoming\",\n});\n\n/** An `AIConversation` as the contract's conversation. */\nexport const mapWireConversation = (wireConversation: WireConversation): AgentsConversation => {\n const conversation: AgentsConversation = {\n id: wireConversation.id ?? 0,\n agentSpaceKey: readNumberOrNull(wireConversation.agentSpaceId),\n runState: readVocabularyValue(RUN_STATES, wireConversation.runState),\n agentTurnOwedAt: readStringOrNull(wireConversation.agentTurnOwedAt),\n title: readStringOrNull(wireConversation.summary?.title),\n titleManuallyEdited: wireConversation.summary?.manuallyEdited === true,\n summary: readStringOrNull(wireConversation.summary?.text),\n created: readStringOrNull(wireConversation.created ?? wireConversation.changeHistory?.createdTime),\n updated: readStringOrNull(wireConversation.updated ?? wireConversation.changeHistory?.modifiedTime),\n purposeName: readStringOrNull(wireConversation.purposeName),\n initiatorType: readStringOrNull(wireConversation.initiatorType),\n scheduleId: readNumberOrNull(wireConversation.scheduleId),\n entryPointKey: readStringOrNull(wireConversation.entryPointKey),\n progressSteps: readWireSetElements(wireConversation.customerProgressSteps).map(mapWireProgressStep),\n };\n if (wireConversation.lastMessageId !== undefined) conversation.lastMessageId = readNumberOrNull(wireConversation.lastMessageId);\n if (wireConversation.aiPromptExtensionId !== undefined) {\n conversation.promptExtensionId = readNumberOrNull(wireConversation.aiPromptExtensionId);\n }\n return conversation;\n};\n\nconst mapWireSubAgent = (wireSubAgent: WireDelegationSubAgentRecord | null | undefined): ConversationSubAgent | null =>\n wireSubAgent\n ? {\n currentRunNumber: readNumberOrNull(wireSubAgent.currentRunNumber),\n runs: readWireSetElements(wireSubAgent.runs).map((wireRun) => ({\n runNumber: readNumberOrNull(wireRun.runNumber),\n status: readStringOrNull(wireRun.status),\n })),\n }\n : null;\n\n/** An `AIConversationMessage` as the contract's message. */\nexport const mapWireConversationMessage = (wireMessage: WireConversationMessage): AgentsConversationMessage => {\n const message: AgentsConversationMessage = {\n id: wireMessage.id ?? 0,\n conversationId: readNumberOrNull(wireMessage.aiConversationId),\n indexInConversation: readNumberOrNull(wireMessage.indexInConversation),\n role: readVocabularyValue(MESSAGE_ROLES, wireMessage.role),\n messageType: readVocabularyValue(MESSAGE_TYPES, wireMessage.messageType),\n status: readVocabularyValue(MESSAGE_STATUSES, wireMessage.status),\n authorType: readVocabularyValue(AUTHOR_TYPES, wireMessage.authorType),\n signalSource: readStringOrNull(wireMessage.signalSource),\n message: wireMessage.message ?? \"\",\n createdDate: readStringOrNull(wireMessage.createdDate),\n createdAt: readStringOrNull(wireMessage.changeHistory?.createdTime),\n toolCall: wireMessage.toolCall\n ? {\n toolCallId: readStringOrNull(wireMessage.toolCall.toolCallId),\n name: readStringOrNull(wireMessage.toolCall.name),\n arguments: wireMessage.toolCall.arguments ?? null,\n status: readStringOrNull(wireMessage.toolCall.status),\n }\n : null,\n delegatedConversations: readWireSetElements(wireMessage.delegatedConversations).map((delegated) => ({\n id: delegated.id ?? 0,\n runState: readVocabularyValue(RUN_STATES, delegated.runState),\n })),\n subAgent: mapWireSubAgent(wireMessage.delegationResults?.subAgent),\n };\n const hasForensics =\n wireMessage.inputTokens != null || wireMessage.outputTokens != null || wireMessage.requestSnapshot != null;\n if (hasForensics) {\n message.forensics = {\n inputTokens: readNumberOrNull(wireMessage.inputTokens),\n outputTokens: readNumberOrNull(wireMessage.outputTokens),\n costInUSD: readNumberOrNull(wireMessage.costInUSD),\n requestSnapshot: wireMessage.requestSnapshot ?? null,\n };\n }\n return message;\n};\n\n/** The run-state read (`AIConversationRunStateGetResponseDto`). */\nexport const mapWireConversationRunState = (wireRunState: WireConversationRunStateResponse): ConversationRunStateRead => ({\n id: wireRunState.id ?? 0,\n runState: readVocabularyValue(RUN_STATES, wireRunState.runState),\n agentTurnOwedAt: readStringOrNull(wireRunState.agentTurnOwedAt),\n lastMessageId: readNumberOrNull(wireRunState.lastMessageId),\n title: readStringOrNull(wireRunState.title),\n titleManuallyEdited: wireRunState.titleManuallyEdited === true,\n summary: readStringOrNull(wireRunState.summary),\n updated: readStringOrNull(wireRunState.updated),\n});\n\nconst mapWireActivityLine = (wireLine: WireActivityLine): ConversationActivityElement => ({\n toolCallMessageId: wireLine.toolCallMessageId ?? 0,\n batchId: readStringOrNull(wireLine.batchId),\n state: readVocabularyValue(ACTIVITY_STATES, wireLine.state),\n kind: readVocabularyValue(ACTIVITY_KINDS, wireLine.kind),\n childCount: readNumberOrNull(wireLine.childCount),\n helperIndex: readNumberOrNull(wireLine.helperIndex),\n line: readStringOrNull(wireLine.line),\n});\n\n/** A background job of the activity answer (`AgentBackgroundJob`); a job without an id is no job. */\nexport const mapWireBackgroundJob = (wireJob: WireBackgroundJob): ConversationBackgroundJob | null => {\n const id = readNumberOrNull(wireJob.id);\n if (id === null) return null;\n return {\n id,\n kind: readStringOrNull(wireJob.kind),\n label: readStringOrNull(wireJob.label) ?? \"\",\n state: readVocabularyValue(CONVERSATION_BACKGROUND_JOB_STATES, wireJob.state),\n liveStatus: readVocabularyValue(CONVERSATION_BACKGROUND_JOB_LIVE_STATUSES, wireJob.liveStatus),\n liveNote: readStringOrNull(wireJob.liveNote),\n startedAt: readStringOrNull(wireJob.startedAt),\n deadlineAt: readStringOrNull(wireJob.deadlineAt),\n dueAt: readStringOrNull(wireJob.dueAt),\n };\n};\n\n/** The background jobs of an activity answer (`runningBackgroundJobs`); an answer without the field has none. */\nexport const mapWireRunningBackgroundJobs = (wireJobs: WireSet<WireBackgroundJob> | null | undefined): ConversationBackgroundJob[] =>\n readWireSetElements(wireJobs)\n .map(mapWireBackgroundJob)\n .filter((backgroundJob): backgroundJob is ConversationBackgroundJob => backgroundJob !== null);\n\n/** The activity of a turn (`AIConversationActivityGetResponseDto`). */\nexport const mapWireConversationActivity = (wireActivity: WireConversationActivityResponse): ConversationActivity => ({\n turnMessageId: readNumberOrNull(wireActivity.turnMessageId),\n turnRunning: wireActivity.turnRunning === true,\n elements: readWireSetElements(wireActivity.elements).map(mapWireActivityLine),\n runningBackgroundJobs: mapWireRunningBackgroundJobs(wireActivity.runningBackgroundJobs),\n});\n\n/** The answer of the owner's stop of one background job (`AIConversationBackgroundJobStopPostResponseDto`). */\nexport const mapWireBackgroundJobStop = (response: WireBackgroundJobStopResponse | null | undefined): ConversationBackgroundJobStop => {\n const wireStop: WireBackgroundJobStopResponse = response !== null && typeof response === \"object\" ? response : {};\n return {\n isStopped: wireStop.isStopped === true,\n state: readVocabularyValue(CONVERSATION_BACKGROUND_JOB_STATES, wireStop.state),\n };\n};\n\n/** A line of a step as a text key; null without a template (a free line). Values other than text and numbers are dropped. */\nconst mapWireOwnerConsentLine = (wireLine: WireOwnerConsentLine | null | undefined): ConversationStepConfirmationLine | null => {\n if (wireLine === null || typeof wireLine !== \"object\" || typeof wireLine.template !== \"string\" || wireLine.template === \"\") return null;\n const replacements: Record<string, string> = {};\n const wireReplacements = wireLine.replacements;\n if (wireReplacements !== null && typeof wireReplacements === \"object\" && !Array.isArray(wireReplacements)) {\n for (const [name, value] of Object.entries(wireReplacements)) {\n if (typeof value === \"string\" || typeof value === \"number\") replacements[name] = String(value);\n }\n }\n return { template: wireLine.template, replacements };\n};\n\n/** A stored step that waits for the owner's click (`AIConversationStepConfirmationGetResponseDto`); null without a step id. */\nexport const mapWireStepConfirmation = (response: WireStepConfirmationResponse | null | undefined): ConversationStepConfirmation | null => {\n const wireStep: WireStepConfirmation | null | undefined = response !== null && typeof response === \"object\" ? response.agentStepConfirmation : null;\n const id = wireStep ? readNumberOrNull(wireStep.id) : null;\n if (!wireStep || id === null) return null;\n return {\n id,\n toolName: readStringOrNull(wireStep.toolName),\n contentHash: readStringOrNull(wireStep.contentHash),\n targetLine: readStringOrNull(wireStep.targetLine) ?? \"\",\n consequenceLine: readStringOrNull(wireStep.consequenceLine) ?? \"\",\n targetText: mapWireOwnerConsentLine(wireStep.targetText),\n consequenceText: mapWireOwnerConsentLine(wireStep.consequenceText),\n status: readVocabularyValue(CONVERSATION_STEP_CONFIRMATION_STATUSES, wireStep.status),\n expiresAt: readStringOrNull(wireStep.expiresAt),\n answeredAt: readStringOrNull(wireStep.answeredAt),\n resultExcerpt: readStringOrNull(wireStep.resultExcerpt),\n };\n};\n\n/** A `SemanticSearchHit`. */\nexport const mapWireSearchHit = (wireHit: WireSemanticSearchHit): ConversationMessageSearchHit => ({\n messageId: readNumberOrNull(wireHit.messageId),\n conversationId: readNumberOrNull(wireHit.conversationId),\n indexInConversation: readNumberOrNull(wireHit.indexInConversation),\n role: readStringOrNull(wireHit.role),\n excerpt: wireHit.excerpt ?? \"\",\n relevance: readNumberOrNull(wireHit.relevance) ?? 0,\n created: readStringOrNull(wireHit.created),\n updated: readStringOrNull(wireHit.updated),\n title: readStringOrNull(wireHit.title),\n});\n\n/** An `AIConversationSearchGroup`. */\nexport const mapWireSearchGroup = (wireGroup: WireConversationSearchGroup): ConversationSearchGroup => ({\n conversationId: readNumberOrNull(wireGroup.conversationId),\n title: readStringOrNull(wireGroup.title),\n summary: readStringOrNull(wireGroup.summary),\n created: readStringOrNull(wireGroup.created),\n updated: readStringOrNull(wireGroup.updated),\n relevance: readNumberOrNull(wireGroup.relevance) ?? 0,\n hits: readWireSetElements(wireGroup.hits).map(mapWireSearchHit),\n});\n\n/** An `AgentCustomerSelectableModel`. */\nexport const mapWireSelectableModel = (wireModel: WireSelectableModel): SelectableModel => ({\n name: wireModel.name ?? \"\",\n displayName: wireModel.displayName ?? wireModel.name ?? \"\",\n description: wireModel.description ?? \"\",\n strengthLevel: readNumberOrNull(wireModel.strengthLevel),\n speedLevel: readNumberOrNull(wireModel.speedLevel),\n creditsMultiplier: readNumberOrNull(wireModel.creditsMultiplier),\n});\n\n/** The stable codes of the server's refusals the chat tells apart. */\nconst ERROR_KIND_BY_CODE: Readonly<Record<string, AgentsClientErrorKind>> = {\n AI_BUDGET_REACHED: \"budget\",\n RATE_LIMIT_EXCEEDED: \"rateLimit\",\n CONVERSATION_CLOSED: \"closed\",\n};\n\n/**\n * A refused request as the port's error: the stable code first (`errorCode` of the JSON body), then the status — 429\n * `rateLimit` (with `Retry-After`), 404 `notFound`, 403 and 401 `forbidden`, 5xx `network`, everything else `other`.\n */\nexport const mapHttpFailureToAgentsClientError = (\n httpStatus: number,\n wireErrorBody: WireErrorBody | null,\n retryAfterHeader: string | null,\n): AgentsClientError => {\n const code = wireErrorBody?.errorCode ?? wireErrorBody?.code ?? null;\n const message = wireErrorBody?.error ?? wireErrorBody?.message ?? undefined;\n const retryAfterOfHeader = retryAfterHeader !== null && /^\\d+$/.test(retryAfterHeader.trim()) ? Number(retryAfterHeader) : null;\n const retryAfterSeconds = readNumberOrNull(wireErrorBody?.retryAfterSeconds) ?? retryAfterOfHeader;\n const kindOfCode = code !== null ? ERROR_KIND_BY_CODE[code] : undefined;\n const kind: AgentsClientErrorKind =\n kindOfCode ??\n (httpStatus === 429\n ? \"rateLimit\"\n : httpStatus === 404\n ? \"notFound\"\n : httpStatus === 403 || httpStatus === 401\n ? \"forbidden\"\n : httpStatus >= 500\n ? \"network\"\n : \"other\");\n return new AgentsClientError(kind, { message: message ?? undefined, code, retryAfterSeconds, httpStatus });\n};\n\n// eslint-disable-next-line no-control-regex\nconst CONTROL_CHARACTERS = /[\\u0000-\\u001f\\u007f]/;\n\n/** A text field of the client context as it goes out: trimmed, or left out when empty, over its cap or not one line. */\nconst readClientContextText = (value: string | number | null | undefined, maxChars: number): string | undefined => {\n if (value === null || value === undefined) return undefined;\n const text = String(value).trim();\n if (text === \"\" || text.length > maxChars || CONTROL_CHARACTERS.test(text)) return undefined;\n return text;\n};\n\n/**\n * The client context as the body field `clientContext` carries it (`AgentClientContext`): the route parameters as a\n * list of `{name, value}`. A field over its cap ({@link AGENTS_CLIENT_CONTEXT_LIMITS}) or with a control character is\n * left out — never cut — so a send never fails on the context; the route parameters go together or not at all.\n * Undefined when nothing is left.\n */\nexport const mapClientContextToWire = (clientContext: AgentsClientContext | null | undefined): WireClientContext | undefined => {\n if (!clientContext) return undefined;\n const wireClientContext: WireClientContext = {};\n const routePath = readClientContextText(clientContext.routePath, AGENTS_CLIENT_CONTEXT_LIMITS.routePathChars);\n if (routePath !== undefined) wireClientContext.routePath = routePath;\n const routeParameters: WireClientContextRouteParameter[] = Object.entries(clientContext.routeParameters ?? {})\n .filter(([name, value]) => name.trim() !== \"\" && value !== null && value !== undefined)\n .map(([name, value]) => ({ name, value: String(value) }));\n const routeParametersText = routeParameters.map((routeParameter) => `${routeParameter.name}=${routeParameter.value}`).join(\"&\");\n if (\n routeParameters.length > 0 &&\n routeParameters.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParameterCount &&\n routeParametersText.length <= AGENTS_CLIENT_CONTEXT_LIMITS.routeParametersChars &&\n !CONTROL_CHARACTERS.test(routeParametersText)\n ) {\n wireClientContext.routeParameters = routeParameters;\n }\n const recordKind = readClientContextText(clientContext.recordKind, AGENTS_CLIENT_CONTEXT_LIMITS.recordKindChars);\n if (recordKind !== undefined) wireClientContext.recordKind = recordKind;\n const recordId = readClientContextText(clientContext.recordId, AGENTS_CLIENT_CONTEXT_LIMITS.recordIdChars);\n if (recordId !== undefined) wireClientContext.recordId = recordId;\n const tab = readClientContextText(clientContext.tab, AGENTS_CLIENT_CONTEXT_LIMITS.tabChars);\n if (tab !== undefined) wireClientContext.tab = tab;\n return Object.keys(wireClientContext).length > 0 ? wireClientContext : undefined;\n};\n\n/** The record of an answer (`AIConversationBoundSubject`), or null when it names none. */\nexport const mapWireBoundConversationSubject = (wireSubject: WireBoundConversationSubject | null | undefined): BoundConversationSubject | null => {\n const entityId = Number(wireSubject?.subjectEntityId ?? 0);\n if (!wireSubject || !wireSubject.subjectEntityClass || !Number.isInteger(entityId) || entityId < 1) return null;\n return {\n conversationId: wireSubject.aiConversationId ?? null,\n entityClass: wireSubject.subjectEntityClass,\n entityId,\n name: wireSubject.name ?? null,\n link: wireSubject.link ?? null,\n purposeId: wireSubject.purposeName ?? null,\n };\n};\n","import type {\n ConversationTraceBackgroundJob,\n ConversationContextComposition,\n ConversationContextSegment,\n ConversationFileChange,\n ConversationFileChangeDiff,\n ConversationFileChangeDiffState,\n ConversationFileChangeType,\n ConversationTraceCompaction,\n ConversationTraceDecision,\n ConversationTraceDecisionProbability,\n ConversationTraceEntityReference,\n ConversationTraceFieldChange,\n ConversationTraceLevel,\n ConversationTraceViewPolicy,\n ConversationTraceLoadedSkill,\n ConversationTraceLoadedSkillTool,\n ConversationTraceMessage,\n ConversationTraceModelCall,\n ConversationTraceRecordChange,\n ConversationTraceRecordChangeOperation,\n ConversationTraceRefusalReason,\n ConversationTraceSignal,\n ConversationTraceSkillLoad,\n ConversationTraceSkillLoadEntry,\n ConversationTraceStep,\n ConversationTraceStepKind,\n ConversationTraceStepStatus,\n ConversationTraceSubAgent,\n ConversationTraceSubAgentRun,\n ConversationTraceSubAgentTaskKind,\n ConversationTraceTaskPlanItem,\n ConversationTraceTaskPlanRejection,\n ConversationTraceTerminal,\n ConversationTraceToolEffect,\n ConversationTraceWidget,\n ConversationTraceWindowMode,\n ConversationTurnStop,\n ConversationTurnTrace,\n ConversationTurnTraces,\n ConversationTurnTraceTotals,\n} from \"../../contract/conversation-trace\";\nimport { CONVERSATION_TRACE_LEVELS } from \"../../contract/conversation-trace\";\nimport { readWireSetElements } from \"./agents-http-mappers\";\nimport type {\n WireContextComposition,\n WireContextCompositionResponse,\n WireContextSegment,\n WireFileChangeDiffResponse,\n WireTurnStopResponse,\n WireTraceCompaction,\n WireTraceDecision,\n WireTraceFieldChange,\n WireTraceFileChange,\n WireTraceLoadedSkill,\n WireTraceMessage,\n WireTraceModelCall,\n WireTraceRecordChange,\n WireTraceRecordChanges,\n WireTraceSkillLoad,\n WireTraceSkillLoadEntry,\n WireTraceBackgroundJob,\n WireTraceStep,\n WireTraceSubAgent,\n WireTraceSubAgentRun,\n WireTraceTaskPlanItem,\n WireTraceTaskPlanItemDeclaration,\n WireTraceTaskPlanRejection,\n WireTraceTerminal,\n WireTraceWidget,\n WireTurnTrace,\n WireTurnTraces,\n WireTurnTracesResponse,\n WireTurnTraceTotals,\n} from \"./agents-http-trace-wire\";\n\n// The mappers of the trace routes. They are tolerant on purpose: a field the server does not send reads as null (or\n// false, or an empty list), a value outside a vocabulary reads as null, a field the binding does not know is ignored.\n\nconst TRACE_LEVELS: readonly ConversationTraceLevel[] = CONVERSATION_TRACE_LEVELS;\n\n/**\n * The server's `AgentTraceViewPolicy` (`traceViewPolicy` of a conversation or trace read) as the contract's policy;\n * null when absent or without a known maximum. The default never exceeds the maximum; a policy that allows one level\n * shows no switch, whatever the wire says.\n */\nexport const mapWireTraceViewPolicy = (wirePolicy: unknown): ConversationTraceViewPolicy | null => {\n if (wirePolicy === null || typeof wirePolicy !== \"object\") return null;\n const fields = wirePolicy as { maxDetailLevel?: unknown; defaultDetailLevel?: unknown; isSwitchShown?: unknown };\n const maxDetailLevel = readVocabularyValue(TRACE_LEVELS, typeof fields.maxDetailLevel === \"string\" ? fields.maxDetailLevel : null);\n if (maxDetailLevel === null) return null;\n const requestedDefault = readVocabularyValue(TRACE_LEVELS, typeof fields.defaultDetailLevel === \"string\" ? fields.defaultDetailLevel : null);\n const defaultDetailLevel =\n requestedDefault !== null && TRACE_LEVELS.indexOf(requestedDefault) <= TRACE_LEVELS.indexOf(maxDetailLevel) ? requestedDefault : maxDetailLevel;\n const isSwitchShown = maxDetailLevel !== \"RESULT\" && fields.isSwitchShown !== false;\n return { maxDetailLevel, defaultDetailLevel, isSwitchShown };\n};\nconst TRACE_WINDOW_MODES: readonly ConversationTraceWindowMode[] = [\"NEWEST\", \"FROM_TURN\", \"FOLLOW_UP\"];\nconst STEP_KINDS: readonly ConversationTraceStepKind[] = [\n \"THINKING\",\n \"MODEL_CALL\",\n \"TOOL_CALL\",\n \"SKILL_LOAD\",\n \"SUB_AGENT\",\n \"WIDGET\",\n \"COMPACTION\",\n \"SIGNAL\",\n \"DECISION\",\n \"TASK_PLAN\",\n \"ERROR\",\n];\nconst TOOL_EFFECTS: readonly ConversationTraceToolEffect[] = [\"READ\", \"WORKSPACE\", \"WRITE\", \"DELETE\"];\nconst STEP_STATUSES: readonly ConversationTraceStepStatus[] = [\n \"PENDING\",\n \"RUNNING\",\n \"COMPLETED\",\n \"FAILED\",\n \"CANCEL_REQUESTED\",\n \"CANCELLED\",\n \"ERROR\",\n \"REFUSED\",\n];\nconst REFUSAL_REASONS: readonly ConversationTraceRefusalReason[] = [\"turnAnswersOwner\", \"ownerWroteDuringTurn\", \"noSubAgentRunning\", \"other\"];\nconst SUB_AGENT_TASK_KINDS: readonly ConversationTraceSubAgentTaskKind[] = [\"agent\", \"toolRun\", \"awaitedRun\"];\nconst FILE_CHANGE_TYPES: readonly ConversationFileChangeType[] = [\"ADDED\", \"MODIFIED\", \"DELETED\", \"RENAMED\", \"DIRECTORY_CREATED\"];\nconst DIFF_STATES: readonly ConversationFileChangeDiffState[] = [\"NONE\", \"INLINE\", \"STORED\", \"BINARY\", \"TOO_LARGE\", \"UNAVAILABLE\"];\n\nconst readVocabularyValue = <Value extends string>(vocabulary: readonly Value[], value: unknown): Value | null =>\n typeof value === \"string\" && (vocabulary as readonly string[]).includes(value) ? (value as Value) : null;\n\nconst readNumberOrNull = (value: unknown): number | null =>\n typeof value === \"number\" && Number.isFinite(value) ? value : null;\n\nconst readStringOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** The same check for a value whose wire shape is known: the shape stays, null and a non-object are ruled out. */\nconst isWireObject = <Wire extends object>(value: Wire | null | undefined): value is Wire => isPlainObject(value);\n\n/** A list of strings from a set, an array or a comma-separated text. */\nconst readStringList = (value: unknown): string[] => {\n if (typeof value === \"string\") return value.split(\",\").map((part) => part.trim()).filter((part) => part !== \"\");\n if (!isPlainObject(value) && !Array.isArray(value)) return [];\n return readWireSetElements(value as string[]).filter((element): element is string => typeof element === \"string\");\n};\n\nconst mapWireTraceModelCall = (wireModelCall: WireTraceModelCall | null | undefined): ConversationTraceModelCall | null =>\n isPlainObject(wireModelCall)\n ? {\n modelName: readStringOrNull(wireModelCall.modelName),\n effort: readStringOrNull(wireModelCall.reasoningEffort),\n inputTokens: readNumberOrNull(wireModelCall.inputTokens),\n outputTokens: readNumberOrNull(wireModelCall.outputTokens),\n cachedInputTokens: readNumberOrNull(wireModelCall.cachedInputTokens),\n cachePercent: readNumberOrNull(wireModelCall.cachePercent),\n costInUsd: readNumberOrNull(wireModelCall.costInUSD ?? wireModelCall.costInUsd),\n reasoningTokens: readNumberOrNull(wireModelCall.reasoningTokens),\n cacheWriteTokens: readNumberOrNull(wireModelCall.cacheWriteTokens),\n wireApi: readStringOrNull(wireModelCall.wireApi),\n forcedToolChoice: readStringOrNull(wireModelCall.forcedToolChoice ?? wireModelCall.forceToolChoice),\n providerCallMs: readNumberOrNull(wireModelCall.providerCallMs),\n loopOverheadMs: readNumberOrNull(wireModelCall.loopOverheadMs),\n hasStoredPayload: wireModelCall.hasStoredPayload === true,\n contextMessageId: readNumberOrNull(wireModelCall.contextMessageId),\n callNumberInTurn: readNumberOrNull(wireModelCall.callNumberInTurn),\n toolNames: readStringList(wireModelCall.toolNames),\n stopReason: readStringOrNull(wireModelCall.stopReason),\n toolDelivery: readStringOrNull(wireModelCall.toolDelivery),\n retryCount: readNumberOrNull(wireModelCall.retryCount),\n }\n : null;\n\n/** A JSON text from a field that carries text, or an object the server did not encode. */\nconst readJsonTextOrNull = (value: unknown): string | null => {\n if (typeof value === \"string\") return value === \"\" ? null : value;\n if (isPlainObject(value) || Array.isArray(value)) return JSON.stringify(value);\n return null;\n};\n\n/** The probabilities of a decision (name → probability), highest first. */\nconst readDecisionProbabilities = (value: unknown): ConversationTraceDecisionProbability[] =>\n isPlainObject(value)\n ? Object.entries(value)\n .filter((entry): entry is [string, number] => typeof entry[1] === \"number\" && Number.isFinite(entry[1]))\n .map(([name, probability]) => ({ name, probability }))\n .sort((left, right) => right.probability - left.probability)\n : [];\n\n/**\n * The decision of a `DECISION` step. The server's `decision` object is read as it is. A server that sends only the\n * stored event (`eventSite`, `eventPayloadExcerpt`) still names the decision: its site, and from the payload's start\n * who decided and whether the loop acted on it; the payload is what the loop resolved (`outcomeJson`).\n */\nconst mapWireTraceDecision = (wireStep: WireTraceStep): ConversationTraceDecision | null => {\n const wireDecision: WireTraceDecision | null = isWireObject(wireStep.decision) ? wireStep.decision : null;\n const eventSite = readStringOrNull(wireStep.eventSite);\n const eventPayload = readStringOrNull(wireStep.eventPayloadExcerpt);\n if (wireDecision === null && eventSite === null && eventPayload === null) return null;\n // The excerpt may be cut in the middle of its JSON: the two facts are read by their names, not by parsing it.\n const decidedBy = readStringOrNull(wireDecision?.decidedBy) ?? (eventPayload === null ? null : (/\"decidedBy\"\\s*:\\s*\"([^\"]*)\"/.exec(eventPayload)?.[1] ?? null));\n const appliedFlag = eventPayload === null ? null : (/\"applied\"\\s*:\\s*(true|false)/.exec(eventPayload)?.[1] ?? null);\n const isApplied = wireDecision?.isApplied === true || (wireDecision?.isApplied == null && appliedFlag === \"true\");\n const isFallback = decidedBy !== null && decidedBy.startsWith(\"fallback\");\n const derivedStatus = isFallback ? \"FALLBACK\" : decidedBy === \"shadow\" ? \"SHADOW\" : isApplied ? \"APPLIED\" : decidedBy !== null || appliedFlag !== null ? \"DECIDED\" : null;\n const derivedFallbackReason = isFallback ? (decidedBy ?? \"\").replace(/^fallback:?\\s*/, \"\") || null : null;\n return {\n site: readStringOrNull(wireDecision?.site) ?? eventSite,\n siteLabel: readStringOrNull(wireDecision?.siteLabel),\n subject: readStringOrNull(wireDecision?.subject) ?? readStringOrNull(wireStep.eventSubject),\n engine: readStringOrNull(wireDecision?.engine),\n engineLabel: readStringOrNull(wireDecision?.engineLabel) ?? (isFallback ? null : decidedBy),\n mode: readStringOrNull(wireDecision?.mode),\n status: readStringOrNull(wireDecision?.status) ?? derivedStatus,\n resultSummary: readStringOrNull(wireDecision?.resultSummary),\n modelName: readStringOrNull(wireDecision?.modelName),\n modelVersion: readStringOrNull(wireDecision?.modelVersion),\n durationMs: readNumberOrNull(wireDecision?.durationMs) ?? readNumberOrNull(wireStep.durationMs),\n sharedRequestDecisionCount: readNumberOrNull(wireDecision?.sharedRequestDecisionCount),\n confidence: readNumberOrNull(wireDecision?.confidence),\n probabilities: readDecisionProbabilities(wireDecision?.probabilities),\n fallbackReason: readStringOrNull(wireDecision?.fallbackReason) ?? derivedFallbackReason,\n skipReason: readStringOrNull(wireDecision?.skipReason),\n inputJson: readJsonTextOrNull(wireDecision?.inputJson),\n isInputCut: wireDecision?.isInputCut === true,\n questionsJson: readJsonTextOrNull(wireDecision?.questionsJson),\n isQuestionsCut: wireDecision?.isQuestionsCut === true,\n outputJson: readJsonTextOrNull(wireDecision?.outputJson),\n isOutputCut: wireDecision?.isOutputCut === true,\n outcomeJson: readJsonTextOrNull(wireDecision?.outcomeJson) ?? eventPayload,\n isOutcomeCut: wireDecision?.isOutcomeCut === true,\n };\n};\n\nconst mapWireTraceCompaction = (wireCompaction: WireTraceCompaction | null | undefined): ConversationTraceCompaction | null => {\n if (!isWireObject(wireCompaction)) return null;\n const tokensBefore = readNumberOrNull(wireCompaction.coveredTokens);\n const tokensAfter = readNumberOrNull(wireCompaction.summaryTokens);\n const compressionPercentOfTokens =\n tokensBefore !== null && tokensAfter !== null && tokensBefore > 0 ? Math.round(((tokensBefore - tokensAfter) / tokensBefore) * 100) : null;\n return {\n level: readNumberOrNull(wireCompaction.level),\n foldedMessageCount: readNumberOrNull(wireCompaction.coveredMessageCount),\n foldedFromMessageIndex: readNumberOrNull(wireCompaction.coveredFromMessageIndex),\n foldedToMessageIndex: readNumberOrNull(wireCompaction.coveredToMessageIndex),\n tokensBefore,\n tokensAfter,\n compressionPercent: readNumberOrNull(wireCompaction.compressionPercent) ?? compressionPercentOfTokens,\n modelName: readStringOrNull(wireCompaction.modelName),\n summaryText: readStringOrNull(wireCompaction.summaryText),\n isSummaryCut: wireCompaction.isSummaryCut === true,\n preservedFactsJson: readJsonTextOrNull(wireCompaction.preservedFactsJson),\n };\n};\n\n/** The signal of a `SIGNAL` step (the server writes its fields on the step itself). */\nconst mapWireTraceSignal = (wireStep: WireTraceStep): ConversationTraceSignal | null => {\n const source = readStringOrNull(wireStep.signalSource);\n const text = readStringOrNull(wireStep.signalText);\n const kind = readStringOrNull(wireStep.signalKind) ?? (text === null ? null : (/^\\[SIGNAL:([^\\]]+)\\]/.exec(text)?.[1] ?? null));\n const tag = readStringOrNull(wireStep.signalTag) ?? (text === null ? null : (/^\\s*\\[SIGNAL:([^\\]\\s]+)\\]/.exec(text)?.[1] ?? null));\n return source === null && text === null && kind === null ? null : { source, kind, tag, text, isTextCut: wireStep.isSignalTextCut === true };\n};\n\nconst mapWireTraceWidget = (wireWidget: WireTraceWidget | null | undefined): ConversationTraceWidget | null =>\n isWireObject(wireWidget)\n ? {\n type: readStringOrNull(wireWidget.type),\n emittedBy: readStringOrNull(wireWidget.emittedBy),\n isValid: wireWidget.isValid !== false,\n title: readStringOrNull(wireWidget.title),\n summary: readStringOrNull(wireWidget.summary),\n payloadJson: readJsonTextOrNull(wireWidget.payloadJson),\n isPayloadCut: wireWidget.isPayloadCut === true,\n messageId: readNumberOrNull(wireWidget.messageId),\n stepId: readStringOrNull(wireWidget.stepId),\n }\n : null;\n\nconst mapWireTraceLoadedSkillTools = (wireTools: WireTraceSkillLoadEntry[\"tools\"]): ConversationTraceLoadedSkillTool[] =>\n readWireSetElements(wireTools)\n .filter(isPlainObject)\n .map((wireTool) => ({\n name: readStringOrNull(wireTool.name) ?? \"\",\n residentTokens: readNumberOrNull(wireTool.residentTokens),\n usageCount: readNumberOrNull(wireTool.usageCount),\n }));\n\nconst mapWireTraceSkillLoad = (wireSkillLoad: WireTraceSkillLoad | null | undefined): ConversationTraceSkillLoad | null =>\n isWireObject(wireSkillLoad)\n ? {\n cause: readStringOrNull(wireSkillLoad.cause),\n loadedCount: readNumberOrNull(wireSkillLoad.loadedCount),\n notLoadedCount: readNumberOrNull(wireSkillLoad.notLoadedCount),\n requestedNames: readStringList(wireSkillLoad.requestedNames),\n skills: readWireSetElements(wireSkillLoad.skills)\n .filter(isPlainObject)\n .map(\n (wireEntry: WireTraceSkillLoadEntry): ConversationTraceSkillLoadEntry => ({\n name: readStringOrNull(wireEntry.name) ?? \"\",\n type: readStringOrNull(wireEntry.type),\n outcome: readStringOrNull(wireEntry.outcome),\n cause: readStringOrNull(wireEntry.cause),\n residentTokens: readNumberOrNull(wireEntry.residentTokens),\n residentTokensWithTools: readNumberOrNull(wireEntry.residentTokensWithTools),\n tools: mapWireTraceLoadedSkillTools(wireEntry.tools),\n }),\n ),\n notLoadedText: readStringOrNull(wireSkillLoad.notLoadedText),\n }\n : null;\n\nexport const mapWireTraceTaskPlanItems = (wireItems: WireTraceStep[\"taskPlanItems\"]): ConversationTraceTaskPlanItem[] =>\n readWireSetElements(wireItems)\n .filter(isPlainObject)\n .map((wireItem: WireTraceTaskPlanItem, position) => ({\n key: readStringOrNull(wireItem.key) ?? readStringOrNull(wireItem.numberPath) ?? String(position),\n numberPath: readStringOrNull(wireItem.numberPath),\n depth: readNumberOrNull(wireItem.depth) ?? 0,\n title: readStringOrNull(wireItem.title) ?? \"\",\n status: readStringOrNull(wireItem.status),\n shownStatus: readStringOrNull(wireItem.shownStatus),\n statusNote: readStringOrNull(wireItem.statusNote),\n requiresUserAction: wireItem.requiresUserAction === true,\n retryable: wireItem.retryable === true,\n isSeeded: wireItem.isSeeded === true,\n isPreResolvedAtSeed: wireItem.isPreResolvedAtSeed === true,\n closesItself: wireItem.closesItself === true,\n wasClosedByPlatform: wireItem.wasClosedByPlatform === true,\n doneCriterion: readStringOrNull(wireItem.doneCriterion),\n customerProgressStepKey: readStringOrNull(wireItem.customerProgressStepKey),\n instruction: readStringOrNull(wireItem.instruction),\n skillNames: readWireSetElements(wireItem.skillNames).filter((name): name is string => typeof name === \"string\" && name !== \"\"),\n declarations: readWireSetElements(wireItem.declarations)\n .filter(isPlainObject)\n .map((wireDeclaration: WireTraceTaskPlanItemDeclaration) => ({\n name: readStringOrNull(wireDeclaration.name) ?? \"\",\n kind: readStringOrNull(wireDeclaration.kind) ?? \"\",\n value: readStringOrNull(wireDeclaration.value) ?? \"\",\n }))\n .filter((declaration) => declaration.name !== \"\"),\n evidenceMessageIndex: readNumberOrNull(wireItem.evidenceMessageIndex),\n platformResolvedAtMessageIndex: readNumberOrNull(wireItem.platformResolvedAtMessageIndex),\n }));\n\nexport const mapWireTraceTaskPlanRejections = (wireRejections: WireTraceStep[\"taskPlanRejections\"]): ConversationTraceTaskPlanRejection[] =>\n readWireSetElements(wireRejections)\n .filter(isPlainObject)\n .map((wireRejection: WireTraceTaskPlanRejection) => ({\n line: readStringOrNull(wireRejection.line) ?? \"\",\n itemKey: readStringOrNull(wireRejection.itemKey),\n }))\n .filter((rejection) => rejection.line !== \"\");\n\nconst mapWireTraceLoadedSkill = (wireSkill: WireTraceLoadedSkill): ConversationTraceLoadedSkill => ({\n name: readStringOrNull(wireSkill.name) ?? \"\",\n residentTokens: readNumberOrNull(wireSkill.residentTokens),\n isNew: wireSkill.isNew === true,\n isAlwaysLoaded: wireSkill.isAlwaysLoaded === true,\n cause: readStringOrNull(wireSkill.cause ?? wireSkill.source),\n tools: mapWireTraceLoadedSkillTools(wireSkill.tools),\n});\n\nconst mapWireTraceTerminal = (wireTerminal: WireTraceTerminal | null | undefined): ConversationTraceTerminal | null =>\n isPlainObject(wireTerminal)\n ? {\n command: readStringOrNull(wireTerminal.command),\n cwd: readStringOrNull(wireTerminal.cwd),\n exitCode: readNumberOrNull(wireTerminal.exitCode),\n durationMs: readNumberOrNull(wireTerminal.durationMs),\n output: readStringOrNull(wireTerminal.output),\n errorOutput: readStringOrNull(wireTerminal.errorOutput),\n isTruncated: wireTerminal.isTruncated === true,\n isBackground: wireTerminal.isBackground === true,\n timedOut: wireTerminal.timedOut === true,\n }\n : null;\n\n/** An `AgentTraceFileChange` as the contract's file change. */\nexport const mapWireTraceFileChange = (wireFileChange: WireTraceFileChange): ConversationFileChange => ({\n id: readNumberOrNull(wireFileChange.fileChangeId ?? wireFileChange.id),\n source: readStringOrNull(wireFileChange.source),\n mountKind: readStringOrNull(wireFileChange.mountKind),\n mountName: readStringOrNull(wireFileChange.mountName),\n driveSpaceId: readNumberOrNull(wireFileChange.driveSpaceId),\n path: readStringOrNull(wireFileChange.path) ?? \"\",\n previousPath: readStringOrNull(wireFileChange.previousPath),\n changeType: readVocabularyValue(FILE_CHANGE_TYPES, wireFileChange.changeType),\n sizeBefore: readNumberOrNull(wireFileChange.sizeBefore),\n sizeAfter: readNumberOrNull(wireFileChange.sizeAfter),\n sha256Before: readStringOrNull(wireFileChange.sha256Before),\n sha256After: readStringOrNull(wireFileChange.sha256After),\n contentType: readStringOrNull(wireFileChange.contentType),\n isBinary: wireFileChange.isBinary === true,\n linesAdded: readNumberOrNull(wireFileChange.linesAdded),\n linesRemoved: readNumberOrNull(wireFileChange.linesRemoved),\n diffState: readVocabularyValue(DIFF_STATES, wireFileChange.diffState),\n diffPreview: readStringOrNull(wireFileChange.diffPreview),\n driveNodeId: readNumberOrNull(wireFileChange.driveNodeId),\n driveFileVersionId: readNumberOrNull(wireFileChange.driveFileVersionId),\n externalRevisionId: readStringOrNull(wireFileChange.externalRevisionId),\n});\n\nconst mapWireTraceSubAgentRun = (wireRun: WireTraceSubAgentRun): ConversationTraceSubAgentRun => ({\n runNumber: readNumberOrNull(wireRun.runNumber),\n status: readStringOrNull(wireRun.status),\n startedAt: readStringOrNull(wireRun.startedAt),\n finishedAt: readStringOrNull(wireRun.finishedAt),\n verdict: readStringOrNull(wireRun.verdict),\n failureReason: readStringOrNull(wireRun.failureReason),\n costInUsd: readNumberOrNull(wireRun.costInUsd ?? wireRun.costInUSD),\n inputTokens: readNumberOrNull(wireRun.inputTokens),\n outputTokens: readNumberOrNull(wireRun.outputTokens),\n resultText: readStringOrNull(wireRun.resultText),\n isResultTextCut: wireRun.isResultTextCut === true,\n isToolResponse: wireRun.isToolResponse === true,\n isError: typeof wireRun.isError === \"boolean\" ? wireRun.isError : null,\n});\n\nconst mapWireTraceSubAgent = (wireSubAgent: WireTraceSubAgent | null | undefined): ConversationTraceSubAgent | null => {\n if (!isWireObject(wireSubAgent)) return null;\n const runs = readWireSetElements(wireSubAgent.runs).filter(isPlainObject).map(mapWireTraceSubAgentRun);\n return {\n number: readNumberOrNull(wireSubAgent.number),\n label: readStringOrNull(wireSubAgent.label) ?? \"\",\n taskText: readStringOrNull(wireSubAgent.taskText),\n skillNames: readStringList(wireSubAgent.skillNames),\n childConversationId: readNumberOrNull(wireSubAgent.childConversationId),\n status: readStringOrNull(wireSubAgent.status) ?? runs[runs.length - 1]?.status ?? null,\n runs,\n modelName: readStringOrNull(wireSubAgent.modelName ?? wireSubAgent.childModelNames),\n modelLabel: readStringOrNull(wireSubAgent.childModelLabels),\n costInUsd: readNumberOrNull(wireSubAgent.childCostInUSD ?? wireSubAgent.childCostInUsd),\n inputTokens: readNumberOrNull(wireSubAgent.childInputTokens),\n outputTokens: readNumberOrNull(wireSubAgent.childOutputTokens),\n cachedInputTokens: readNumberOrNull(wireSubAgent.childCachedInputTokens),\n messageCount: readNumberOrNull(wireSubAgent.childMessageCount),\n taskKind: readVocabularyValue(SUB_AGENT_TASK_KINDS, wireSubAgent.taskKind),\n toolName: readStringOrNull(wireSubAgent.toolName),\n operationName: readStringOrNull(wireSubAgent.operationName),\n backgroundJobKey: readStringOrNull(wireSubAgent.backgroundJobKey),\n verdictText: readStringOrNull(wireSubAgent.verdictText),\n resultText: readStringOrNull(wireSubAgent.resultText),\n isResultTextCut: wireSubAgent.isResultTextCut === true,\n };\n};\n\nconst mapWireTraceEntityReference = (wireReference: unknown): ConversationTraceEntityReference | null => {\n if (!isPlainObject(wireReference)) return null;\n const argumentName = readStringOrNull(wireReference.argumentName);\n const id = readNumberOrNull(wireReference.id);\n return argumentName !== null && argumentName !== \"\" && id !== null ? { argumentName, id } : null;\n};\n\nconst RECORD_CHANGE_OPERATIONS: readonly ConversationTraceRecordChangeOperation[] = [\"CREATED\", \"CHANGED\", \"DELETED\"];\n\nconst mapWireTraceFieldChange = (wireFieldChange: WireTraceFieldChange | null | undefined): ConversationTraceFieldChange | null => {\n if (!isWireObject(wireFieldChange)) return null;\n const fieldName = readStringOrNull(wireFieldChange.fieldName);\n if (fieldName === null || fieldName === \"\") return null;\n return {\n fieldName,\n before: readStringOrNull(wireFieldChange.before),\n after: readStringOrNull(wireFieldChange.after),\n isCut: wireFieldChange.isCut === true,\n };\n};\n\nconst mapWireTraceRecordChange = (wireRecordChange: WireTraceRecordChange | null | undefined): ConversationTraceRecordChange | null => {\n if (!isWireObject(wireRecordChange)) return null;\n const operation = readVocabularyValue(RECORD_CHANGE_OPERATIONS, wireRecordChange.operation);\n const tableName = readStringOrNull(wireRecordChange.tableName);\n if (operation === null || tableName === null || tableName === \"\") return null;\n return {\n operation,\n tableName,\n recordId: readNumberOrNull(wireRecordChange.recordId),\n fieldChanges: readWireSetElements(wireRecordChange.fieldChanges)\n .map(mapWireTraceFieldChange)\n .filter((fieldChange): fieldChange is ConversationTraceFieldChange => fieldChange !== null),\n omittedFieldCount: readNumberOrNull(wireRecordChange.omittedFieldCount) ?? 0,\n };\n};\n\n/** The readable thinking of a model call, with an ellipsis when the server cut it; null without one. */\nconst readThinkingSummary = (wireStep: WireTraceStep): string | null => {\n const thinkingSummary = readStringOrNull(wireStep.thinkingSummary);\n if (thinkingSummary === null || thinkingSummary.trim() === \"\") return null;\n return wireStep.isThinkingSummaryCut === true ? `${thinkingSummary}…` : thinkingSummary;\n};\n\n/** The record changes of a writing call (`ToolCallRecordChanges`); empty without them. */\nconst mapWireTraceRecordChanges = (\n wireRecordChanges: WireTraceRecordChanges | null | undefined,\n): { recordChanges: ConversationTraceRecordChange[]; omittedRecordChangeCount: number } => {\n if (!isWireObject(wireRecordChanges)) return { recordChanges: [], omittedRecordChangeCount: 0 };\n return {\n recordChanges: readWireSetElements(wireRecordChanges.elements)\n .map(mapWireTraceRecordChange)\n .filter((recordChange): recordChange is ConversationTraceRecordChange => recordChange !== null),\n omittedRecordChangeCount: readNumberOrNull(wireRecordChanges.omittedRecordCount) ?? 0,\n };\n};\n\n/** The background job a tool call started (`AgentTraceBackgroundJob`); null without one or without an id. */\nexport const mapWireTraceBackgroundJob = (wireJob: WireTraceBackgroundJob | null | undefined): ConversationTraceBackgroundJob | null => {\n if (!isWireObject(wireJob)) return null;\n const id = readNumberOrNull(wireJob.id);\n if (id === null) return null;\n return {\n id,\n kind: readStringOrNull(wireJob.kind),\n label: readStringOrNull(wireJob.label) ?? \"\",\n state: readStringOrNull(wireJob.state),\n liveStatus: readStringOrNull(wireJob.liveStatus),\n startedAt: readStringOrNull(wireJob.startedAt),\n endedAt: readStringOrNull(wireJob.endedAt),\n deadlineAt: readStringOrNull(wireJob.deadlineAt),\n dueAt: readStringOrNull(wireJob.dueAt),\n checkCount: readNumberOrNull(wireJob.checkCount) ?? 0,\n lastCheckedAt: readStringOrNull(wireJob.lastCheckedAt),\n reportKind: readStringOrNull(wireJob.reportKind),\n reportedAt: readStringOrNull(wireJob.reportedAt),\n };\n};\n\n/**\n * An `AgentTraceStep` as the contract's step. A step of a kind the binding does not know is mapped to null and left\n * out of its turn. `position` is the step's place in its turn (part of its key when the server sends no step id).\n */\nexport const mapWireTraceStep = (wireStep: WireTraceStep, position: number): ConversationTraceStep | null => {\n if (!isWireObject(wireStep)) return null;\n const kind = readVocabularyValue(STEP_KINDS, wireStep.kind);\n if (kind === null) return null;\n const messageId = readNumberOrNull(wireStep.messageId);\n const loadedSkills =\n wireStep.loadedSkills == null ? null : readWireSetElements(wireStep.loadedSkills).filter(isPlainObject).map(mapWireTraceLoadedSkill);\n const stepId = typeof wireStep.stepId === \"number\" ? String(wireStep.stepId) : readStringOrNull(wireStep.stepId) || null;\n const widget = mapWireTraceWidget(wireStep.widget);\n return {\n key: stepId ?? `${messageId ?? \"event\"}:${kind}:${readStringOrNull(wireStep.toolCallId) ?? position}`,\n stepId,\n turnNumber: readNumberOrNull(wireStep.turnNumber),\n kind,\n messageId,\n toolName: readStringOrNull(wireStep.toolName),\n deliveredThroughCallTool: wireStep.deliveredThroughCallTool === true,\n effect: readVocabularyValue(TOOL_EFFECTS, wireStep.effect),\n status: readVocabularyValue(STEP_STATUSES, wireStep.status),\n storedStatus: readStringOrNull(wireStep.storedStatus),\n refusalReason:\n wireStep.refusalReason == null ? null : (readVocabularyValue(REFUSAL_REASONS, wireStep.refusalReason) ?? \"other\"),\n backgroundOperationName: readStringOrNull(wireStep.backgroundOperationName),\n backgroundJobKey: readStringOrNull(wireStep.backgroundJobKey),\n backgroundJob: mapWireTraceBackgroundJob(wireStep.backgroundJob),\n resultOfBackgroundJobId: readNumberOrNull(wireStep.resultOfBackgroundJobId),\n startedAt: readStringOrNull(wireStep.startedAt),\n durationMs: readNumberOrNull(wireStep.durationMs),\n line: readStringOrNull(wireStep.line),\n toolNameInWords: readStringOrNull(wireStep.toolNameInWords),\n toolSkillNames: readStringList(wireStep.toolSkillNames),\n modelLabel: readStringOrNull(wireStep.modelLabel),\n thinkingSummary: readThinkingSummary(wireStep),\n entityReferences: readWireSetElements(wireStep.entityReferences)\n .map(mapWireTraceEntityReference)\n .filter((reference): reference is ConversationTraceEntityReference => reference !== null),\n ...mapWireTraceRecordChanges(wireStep.recordChanges),\n isHeldForConsent: wireStep.wasHeldForOwnerConsent === true || wireStep.isHeldForConsent === true,\n isAwaitingOwnerClick: wireStep.isAwaitingOwnerClick === true,\n isRefused:\n wireStep.wasRefusedByGate === true || wireStep.wasRefusedAsDuplicate === true || wireStep.wasRefusedAsFinal === true,\n errorText: readStringOrNull(wireStep.errorText),\n errorCode: readStringOrNull(wireStep.errorCode),\n wasRetried: wireStep.wasRetried === true,\n widgetType: widget?.type ?? null,\n widget,\n decision: kind === \"DECISION\" ? mapWireTraceDecision(wireStep) : null,\n compaction: mapWireTraceCompaction(wireStep.compaction),\n signal: kind === \"SIGNAL\" ? mapWireTraceSignal(wireStep) : null,\n skillLoad: mapWireTraceSkillLoad(wireStep.skillLoad),\n taskPlanItems: mapWireTraceTaskPlanItems(wireStep.taskPlanItems),\n taskPlanRejections: mapWireTraceTaskPlanRejections(wireStep.taskPlanRejections),\n taskPlanTitle: readStringOrNull(wireStep.taskPlanTitle),\n taskPlanItemCount: readNumberOrNull(wireStep.taskPlanItemCount),\n taskPlanOpenItemCount: readNumberOrNull(wireStep.taskPlanOpenItemCount),\n taskPlanDoneItemCount: readNumberOrNull(wireStep.taskPlanDoneItemCount),\n taskPlanBlockedItemCount: readNumberOrNull(wireStep.taskPlanBlockedItemCount),\n terminal: mapWireTraceTerminal(wireStep.terminal),\n fileChanges: readWireSetElements(wireStep.fileChanges).filter(isPlainObject).map(mapWireTraceFileChange),\n subAgent: mapWireTraceSubAgent(wireStep.subAgent),\n argumentsJson: readStringOrNull(wireStep.argumentsJson),\n isArgumentsCut: wireStep.isArgumentsCut === true,\n result: readStringOrNull(wireStep.result),\n resultChars: readNumberOrNull(wireStep.resultChars),\n isResultCut: wireStep.isResultCut === true,\n modelCall: mapWireTraceModelCall(wireStep.modelCall),\n loadedSkills,\n loadedSkillNames: readStringList(wireStep.loadedSkillNames),\n assistantText: readStringOrNull(wireStep.assistantText) || null,\n assistantTextChars: readNumberOrNull(wireStep.assistantTextChars),\n isAssistantTextCut: wireStep.isAssistantTextCut === true,\n };\n};\n\n/** An `AgentTraceMessage`: a message of a turn with its text; null for anything that is no object. */\nexport const mapWireTraceMessage = (wireMessage: WireTraceMessage | null | undefined): ConversationTraceMessage | null => {\n if (!isWireObject(wireMessage)) return null;\n const text = readStringOrNull(wireMessage.text) ?? \"\";\n return {\n messageId: readNumberOrNull(wireMessage.messageId),\n messageIndex: readNumberOrNull(wireMessage.messageIndex),\n authorKind: readStringOrNull(wireMessage.authorKind),\n text,\n textChars: readNumberOrNull(wireMessage.textChars) ?? text.length,\n isTextCut: wireMessage.isTextCut === true,\n createdAt: readStringOrNull(wireMessage.createdAt),\n signalSource: readStringOrNull(wireMessage.signalSource),\n isInterim: wireMessage.isInterim === true,\n modelLabel: readStringOrNull(wireMessage.modelLabel),\n modelName: readStringOrNull(wireMessage.modelName),\n widgetTypes: readStringList(wireMessage.widgetTypes),\n widgets: readWireSetElements(wireMessage.widgets)\n .map((wireWidget) => mapWireTraceWidget(wireWidget))\n .filter((widget): widget is ConversationTraceWidget => widget !== null),\n isQueuedDuringRun: wireMessage.isQueuedDuringRun === true,\n arrivedDuringTurnNumber: readNumberOrNull(wireMessage.arrivedDuringTurnNumber),\n handledInTurnNumber: readNumberOrNull(wireMessage.handledInTurnNumber),\n foldSignalMessageId: readNumberOrNull(wireMessage.foldSignalMessageId),\n };\n};\n\n/** The share of the input tokens read from the cache, when the server sends the two counts but not the share. */\nconst readCachePercent = (wireTotals: WireTurnTraceTotals): number | null => {\n const cachePercent = readNumberOrNull(wireTotals.cachePercent);\n if (cachePercent !== null) return cachePercent;\n const inputTokens = readNumberOrNull(wireTotals.inputTokens);\n const cachedInputTokens = readNumberOrNull(wireTotals.cachedInputTokens);\n if (inputTokens === null || cachedInputTokens === null || inputTokens <= 0) return null;\n return Math.round((cachedInputTokens / inputTokens) * 100);\n};\n\n/** The input tokens of the turn's last model call step (what the model read on it); null without such a step. */\nconst readNewestModelCallInputTokens = (steps: ConversationTraceStep[]): number | null => {\n for (let position = steps.length - 1; position >= 0; position -= 1) {\n const step = steps[position];\n if (step.kind === \"MODEL_CALL\" && step.modelCall !== null) return step.modelCall.inputTokens;\n }\n return null;\n};\n\nconst mapWireTurnTraceTotals = (wireTurn: WireTurnTrace, steps: ConversationTraceStep[]): ConversationTurnTraceTotals => {\n // The server writes the totals on the turn itself; an object of their own wins when one arrives.\n const wireTotals: WireTurnTraceTotals = isPlainObject(wireTurn.totals) ? { ...wireTurn, ...wireTurn.totals } : wireTurn;\n return {\n durationMs: readNumberOrNull(wireTotals.durationMs),\n inputTokens: readNumberOrNull(wireTotals.inputTokens),\n outputTokens: readNumberOrNull(wireTotals.outputTokens),\n cachedInputTokens: readNumberOrNull(wireTotals.cachedInputTokens),\n cachePercent: readCachePercent(wireTotals),\n costInUsd: readNumberOrNull(wireTotals.costInUSD ?? wireTotals.costInUsd),\n modelCallCount: readNumberOrNull(wireTotals.modelCallCount),\n newestModelCallInputTokens: readNewestModelCallInputTokens(steps),\n stepCount: readNumberOrNull(wireTotals.stepCount) ?? steps.length,\n commandCount: readNumberOrNull(wireTotals.commandCount) ?? steps.filter((step) => step.terminal !== null).length,\n fileCount: readNumberOrNull(wireTotals.fileCount) ?? steps.reduce((count, step) => count + step.fileChanges.length, 0),\n linesAdded: readNumberOrNull(wireTotals.linesAdded) ?? 0,\n linesRemoved: readNumberOrNull(wireTotals.linesRemoved) ?? 0,\n modelName: readStringOrNull(wireTotals.modelName),\n effort: readStringOrNull(wireTotals.reasoningEffort ?? wireTotals.effort),\n outcome: readStringOrNull(wireTotals.outcome),\n };\n};\n\n/** An `AgentTurnTrace` as the contract's turn trace. */\nexport const mapWireTurnTrace = (wireTurn: WireTurnTrace): ConversationTurnTrace => {\n const steps = readWireSetElements(wireTurn.steps)\n .map((wireStep, position) => mapWireTraceStep(wireStep, position))\n .filter((step): step is ConversationTraceStep => step !== null);\n return {\n turnNumber: readNumberOrNull(wireTurn.turnNumber) ?? 0,\n turnMessageId: readNumberOrNull(wireTurn.initiatorMessageId ?? wireTurn.turnMessageId),\n turnMessageIndex: readNumberOrNull(wireTurn.initiatorMessageIndex),\n startedAt: readStringOrNull(wireTurn.startedAt),\n isRunning: wireTurn.isRunning === true,\n isStoppedByOwner: wireTurn.isStoppedByOwner === true,\n initiatorMessage: mapWireTraceMessage(wireTurn.initiatorMessage),\n answerMessages: readWireSetElements(wireTurn.answerMessages)\n .map(mapWireTraceMessage)\n .filter((message): message is ConversationTraceMessage => message !== null),\n queuedMessages: readWireSetElements(wireTurn.queuedMessages)\n .map(mapWireTraceMessage)\n .filter((message): message is ConversationTraceMessage => message !== null),\n isStartedForQueuedOwnerMessage: wireTurn.isStartedForQueuedOwnerMessage === true,\n startedBySignalMessageId: readNumberOrNull(wireTurn.startedBySignalMessageId),\n steps,\n totals: mapWireTurnTraceTotals(wireTurn, steps),\n };\n};\n\n/** The object of an answer that carries `fieldName`: the answer itself, or the first of its fields that does. */\nconst findObjectWithField = <Found>(response: unknown, fieldName: string): Found | null => {\n if (!isPlainObject(response)) return null;\n if (fieldName in response) return response as Found;\n for (const value of Object.values(response)) {\n if (isPlainObject(value) && fieldName in value) return value as Found;\n }\n return null;\n};\n\n/** The traces of an answer: the object that carries the turns (`elements` of the set, or `turns`) or its paging facts. */\nconst findWireTurnTraces = (response: unknown): WireTurnTraces =>\n findObjectWithField<WireTurnTraces>(response, \"totalTurnCount\") ?? findObjectWithField<WireTurnTraces>(response, \"turns\") ?? {};\n\n/**\n * The trace read (`AgentTurnTraces`) as the contract's turn traces: the traces may be the answer itself or sit in one\n * of its fields (a response DTO). The turns are the elements of the set. An answer without turns reads as an empty\n * trace.\n */\nexport const mapWireTurnTraces = (response: WireTurnTracesResponse | null | undefined): ConversationTurnTraces => {\n const wireTraces = findWireTurnTraces(response);\n const turns = readWireSetElements(Array.isArray(wireTraces.elements) ? wireTraces.elements : wireTraces.turns).filter(isPlainObject).map(mapWireTurnTrace);\n return {\n conversationId: readNumberOrNull(wireTraces.aiConversationId),\n level: readVocabularyValue(TRACE_LEVELS, wireTraces.detailLevel) ?? \"STEPS\",\n turns,\n windowMode: readVocabularyValue(TRACE_WINDOW_MODES, wireTraces.windowMode),\n totalTurnCount: readNumberOrNull(wireTraces.totalTurnCount),\n firstTurnNumber: readNumberOrNull(wireTraces.firstTurnNumber) ?? turns[0]?.turnNumber ?? null,\n lastTurnNumber: readNumberOrNull(wireTraces.lastTurnNumber) ?? turns[turns.length - 1]?.turnNumber ?? null,\n hasOlderTurns: wireTraces.hasOlderTurns === true,\n hasNewerTurns: wireTraces.hasNewerTurns === true,\n newestMessageIndex: readNumberOrNull(wireTraces.newestMessageIndex),\n isRunLive: wireTraces.isRunLive === true,\n // the policy sits beside the traces in the response DTO (or on the traces themselves)\n traceViewPolicy: mapWireTraceViewPolicy(\n (response as Record<string, unknown> | null | undefined)?.traceViewPolicy ?? (wireTraces as Record<string, unknown>).traceViewPolicy,\n ),\n };\n};\n\nconst mapWireContextSegment = (wireSegment: WireContextSegment, position: number): ConversationContextSegment => {\n const key = readStringOrNull(wireSegment.key) ?? readStringOrNull(wireSegment.name) ?? readStringOrNull(wireSegment.type) ?? \"segment\";\n return {\n // The segments of a kind repeat (one per wire message): the position makes the key unique.\n key: `${key}:${position}`,\n label: readStringOrNull(wireSegment.label) ?? key,\n tokens: readNumberOrNull(wireSegment.tokenCount ?? wireSegment.tokens) ?? 0,\n percent: readNumberOrNull(wireSegment.percent),\n };\n};\n\n/**\n * The context composition of one model call. The server's answer carries the composition in `composition` (the\n * segments of the system message, of the tool schemas and of the wire messages, in the order the model read them) and\n * the compaction threshold beside it: the context's size is the provider's count of the newest call, the size it may\n * reach is the threshold in effect. A flat answer (`segments`, `totalTokens`, `contextWindowTokens`) is read as well.\n */\nexport const mapWireContextComposition = (\n response: WireContextCompositionResponse | null | undefined,\n): ConversationContextComposition => {\n const wireResponse: WireContextComposition = isPlainObject(response) ? response : {};\n const wireComposition = isWireObject(wireResponse.composition)\n ? wireResponse.composition\n : isWireObject(wireResponse.contextComposition)\n ? wireResponse.contextComposition\n : null;\n const wireSegments =\n wireComposition !== null\n ? [\n ...readWireSetElements(wireComposition.systemSegments),\n ...readWireSetElements(wireComposition.toolSchemaSegments),\n ...readWireSetElements(wireComposition.messageSegments),\n ]\n : readWireSetElements((findObjectWithField<WireContextComposition>(response, \"segments\") ?? {}).segments);\n const mappedSegments = wireSegments.filter(isPlainObject).map(mapWireContextSegment);\n const segmentTokens = mappedSegments.length > 0 ? mappedSegments.reduce((sum, segment) => sum + segment.tokens, 0) : null;\n const wireThreshold = isWireObject(wireResponse.compactionThreshold) ? wireResponse.compactionThreshold : null;\n const totalTokens = readNumberOrNull(wireResponse.totalTokens) ?? readNumberOrNull(wireThreshold?.latestContextInputTokens) ?? segmentTokens;\n const thresholdTokens = readNumberOrNull(wireThreshold?.thresholdTokens);\n const contextWindowTokens = readNumberOrNull(wireResponse.contextWindowTokens) ?? (thresholdTokens !== null && thresholdTokens > 0 ? thresholdTokens : null);\n const fillPercentOfTokens =\n totalTokens !== null && contextWindowTokens !== null && contextWindowTokens > 0\n ? Math.round((totalTokens / contextWindowTokens) * 100)\n : null;\n // The share of each segment in the composition, when the server sends none.\n const segments = mappedSegments.map((segment) =>\n segment.percent === null && segmentTokens !== null && segmentTokens > 0\n ? { ...segment, percent: Math.round((segment.tokens / segmentTokens) * 1000) / 10 }\n : segment,\n );\n return {\n messageId: readNumberOrNull(wireResponse.messageId ?? wireResponse.aiConversationMessageId),\n totalTokens,\n contextWindowTokens,\n fillPercent: readNumberOrNull(wireResponse.fillPercent) ?? fillPercentOfTokens,\n segments,\n };\n};\n\n/** The whole diff of a file change. */\nexport const mapWireFileChangeDiff = (\n response: WireFileChangeDiffResponse | null | undefined,\n fileChangeId: number,\n): ConversationFileChangeDiff => {\n const wireDiff = findObjectWithField<WireFileChangeDiffResponse>(response, \"diff\") ??\n findObjectWithField<WireFileChangeDiffResponse>(response, \"diffText\") ?? {};\n const wireFileChange = isWireObject(wireDiff.fileChange) ? wireDiff.fileChange : null;\n return {\n fileChangeId: readNumberOrNull(wireDiff.fileChangeId) ?? readNumberOrNull(wireFileChange?.fileChangeId ?? wireFileChange?.id) ?? fileChangeId,\n diff: readStringOrNull(wireDiff.diff) ?? readStringOrNull(wireDiff.diffText) ?? \"\",\n isCut: wireDiff.isCut === true || wireDiff.isDiffCut === true,\n };\n};\n\n/** The answer of the stop route: whether a running turn was stopped, and the run state after it. */\nexport const mapWireTurnStop = (response: WireTurnStopResponse | null | undefined): ConversationTurnStop => {\n const wireStop: WireTurnStopResponse = isPlainObject(response) ? response : {};\n return { isStopped: wireStop.isStopped === true, runState: readStringOrNull(wireStop.runState) };\n};\n"],"names":["readVocabularyValue","readNumberOrNull","readStringOrNull"],"mappings":";;;AAqDA,MAAM,aAA8C;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AACA,MAAM,gBAAoD,CAAC,UAAU,QAAQ,WAAW;AACxF,MAAM,gBAAoD;A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W,CAAA;AAC5E,SAAO,EAAE,WAAW,SAAS,cAAc,MAAM,UAAU,iBAAiB,SAAS,QAAQ,EAAA;AAC/F;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { U as getSandboxLegacyAliases } from "./index-
|
|
2
|
+
import { U as getSandboxLegacyAliases } from "./index-DAEGct6X.js";
|
|
3
3
|
const WIDGET_IMAGE_READINESS_GLOBAL_NAME = "__AGENTS_WIDGET_IMAGE_V1__";
|
|
4
4
|
const readWidgetImageReadinessGlobalNames = () => [
|
|
5
5
|
WIDGET_IMAGE_READINESS_GLOBAL_NAME,
|
|
@@ -332,4 +332,4 @@ export {
|
|
|
332
332
|
readWidgetImageReadiness as r,
|
|
333
333
|
toSameRealmFetchInput as t
|
|
334
334
|
};
|
|
335
|
-
//# sourceMappingURL=browser-request-interception-
|
|
335
|
+
//# sourceMappingURL=browser-request-interception-BnOQWLaJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser-request-interception-D678IemW.js","sources":["../../src/image-render/widget-image-readiness-signal.ts","../../src/request-interception/intercepted-xml-http-request-upload.ts","../../src/request-interception/browser-request-interception.ts"],"sourcesContent":["import { getSandboxLegacyAliases } from \"../provider/environment\";\nimport type { WidgetImageReadiness } from \"./widget-image-render.types\";\n\n/** The `window` property the image capture waits on. */\nexport const WIDGET_IMAGE_READINESS_GLOBAL_NAME = \"__AGENTS_WIDGET_IMAGE_V1__\";\n\ntype WindowSignals = Record<string, WidgetImageReadiness | undefined>;\n\n/**\n * Every name the image readiness signal is published under: the package's own, then each name the app declares\n * (`AgentsEnvironment.sandboxLegacyAliases.imageReadinessGlobalNames`) — read at each publish, so an app may declare\n * them after a readiness was created.\n */\nexport const readWidgetImageReadinessGlobalNames = (): string[] => [\n WIDGET_IMAGE_READINESS_GLOBAL_NAME,\n ...(getSandboxLegacyAliases().imageReadinessGlobalNames ?? []).filter(\n (aliasName) => aliasName !== WIDGET_IMAGE_READINESS_GLOBAL_NAME,\n ),\n];\n\n/** Publishes (or with `undefined` clears) the image readiness signal under every name. */\nexport const publishWidgetImageReadiness = (readiness: WidgetImageReadiness | undefined): void => {\n const windowSignals = window as unknown as WindowSignals;\n for (const globalName of readWidgetImageReadinessGlobalNames()) windowSignals[globalName] = readiness;\n};\n\n/**\n * The published image readiness signal. A `failed` value under ANY name wins — the app's own capture code may have\n * written it under a name it declared — otherwise the value under the package's name, otherwise the first value found.\n */\nexport const readWidgetImageReadiness = (): WidgetImageReadiness | undefined => {\n const windowSignals = window as unknown as WindowSignals;\n const publishedSignals = readWidgetImageReadinessGlobalNames()\n .map((globalName) => windowSignals[globalName])\n .filter((signal): signal is WidgetImageReadiness => signal !== undefined && signal !== null);\n return publishedSignals.find((signal) => signal.state === \"failed\") ?? publishedSignals[0];\n};\n","/** The upload side of the `XMLHttpRequest` stand-in (`xhr.upload`) and the events both sides dispatch. */\n\nexport type XhrEventName = \"loadstart\" | \"progress\" | \"load\" | \"error\" | \"abort\" | \"timeout\" | \"loadend\" | \"readystatechange\";\nexport type XhrEventHandler = ((this: unknown, event: Event) => unknown) | null;\n\nexport const createProgressEvent = (type: string, loaded: number, total: number): Event =>\n typeof ProgressEvent === \"function\"\n ? new ProgressEvent(type, { lengthComputable: total > 0, loaded, total })\n : new Event(type);\n\n/** The event target of `xhr.upload`: listeners and `on…` handlers for the upload's progress. */\nexport class InterceptedXMLHttpRequestUpload extends EventTarget {\n onloadstart: XhrEventHandler = null;\n onprogress: XhrEventHandler = null;\n onload: XhrEventHandler = null;\n onerror: XhrEventHandler = null;\n onabort: XhrEventHandler = null;\n ontimeout: XhrEventHandler = null;\n onloadend: XhrEventHandler = null;\n\n emit(type: XhrEventName, loaded = 0, total = 0) {\n const event = createProgressEvent(type, loaded, total);\n this.dispatchEvent(event);\n (this[`on${type}` as keyof this] as XhrEventHandler)?.call(this, event);\n }\n}\n","import {\n createProgressEvent,\n InterceptedXMLHttpRequestUpload,\n type XhrEventHandler,\n type XhrEventName,\n} from \"./intercepted-xml-http-request-upload\";\n\n/**\n * The browser-level request stand-in of the capture and preview pages: `XMLHttpRequest` (the transport of axios's\n * browser adapter and of uploads with progress) and, where an install asks for it, `window.fetch` are replaced for the\n * duration of an install and send every request into one handler, whatever HTTP client the application uses.\n *\n * The handler answers with a `Response` or throws: `fetch` then rejects with the thrown error, an `XMLHttpRequest`\n * fails like a network error (status 0, `error` and `loadend`, no body, no header). A handler that never settles\n * leaves the request pending. Nothing of the request reaches the network unless the handler sends it itself\n * (`forward()`, or its own copy of the original `fetch`).\n */\n\n/** A request as the handler sees it, the same for `fetch` and `XMLHttpRequest`. */\nexport interface InterceptedRequest {\n /** Upper case (`GET`, `POST`, …). */\n method: string;\n /** Absolute, resolved against the page's origin. A fresh object per request; the handler may change it. */\n url: URL;\n headers: Headers;\n /** The body the client passed (`fetch`'s, or the argument of `XMLHttpRequest.send`, also for a GET), or null. */\n body: BodyInit | null;\n signal: AbortSignal | undefined;\n transport: \"fetch\" | \"xhr\";\n /** Sends the request unchanged through the original `fetch` (an `XMLHttpRequest` with its own credentials mode). */\n forward: () => Promise<Response>;\n}\n\nexport type InterceptedRequestHandler = (request: InterceptedRequest) => Promise<Response>;\n\ntype FetchInput = RequestInfo | URL;\n\n/**\n * An answer without any header, as the former axios adapters answered (`headers: {}`): a string body would add a\n * `Content-Type`, the bytes of it do not.\n */\nexport const createHeaderlessResponse = (body: string | null, status: number, statusText = \"\"): Response =>\n new Response(body === null ? null : new TextEncoder().encode(body), { status, statusText });\n\n/** A `Request` of any realm (an iframe's, jsdom's, Node's) — never `instanceof`, which holds only for this realm. */\nexport const isFetchRequest = (input: unknown): input is Request =>\n Object.prototype.toString.call(input) === \"[object Request]\";\n\nconst pageOrigin = (): string =>\n typeof window !== \"undefined\" && window.location ? window.location.origin : \"http://localhost\";\n\nconst copyHeaders = (target: Headers, source: HeadersInit | undefined) => {\n if (source === undefined) return;\n new Headers(source).forEach((value, name) => target.set(name, value));\n};\n\n/** The `fetch` arguments as one request: a `Request` of any realm, a `URL` or a string, with `init` taking precedence. */\nexport const readFetchRequest = async (\n input: FetchInput,\n init: RequestInit | undefined,\n originalFetch: typeof fetch,\n): Promise<InterceptedRequest> => {\n const fromRequest = isFetchRequest(input) ? input : undefined;\n const headers = new Headers();\n if (fromRequest) fromRequest.headers.forEach((value, name) => headers.set(name, value));\n copyHeaders(headers, init?.headers);\n const initBody = init?.body ?? null;\n const body =\n initBody !== null\n ? initBody\n : fromRequest && fromRequest.body !== null\n ? await fromRequest.clone().arrayBuffer()\n : null;\n return {\n method: (init?.method ?? fromRequest?.method ?? \"GET\").toUpperCase(),\n url: new URL(fromRequest ? fromRequest.url : String(input), pageOrigin()),\n headers,\n body,\n signal: init?.signal ?? fromRequest?.signal ?? undefined,\n transport: \"fetch\",\n forward: () => originalFetch(input, init),\n };\n};\n\nconst bodySize = (body: BodyInit | null): number => {\n if (body === null) return 0;\n if (typeof body === \"string\") return new TextEncoder().encode(body).byteLength;\n if (typeof Blob !== \"undefined\" && body instanceof Blob) return body.size;\n if (body instanceof ArrayBuffer) return body.byteLength;\n if (ArrayBuffer.isView(body)) return body.byteLength;\n return 0;\n};\n\nconst invalidState = (message: string) => new DOMException(message, \"InvalidStateError\");\n\n/** Builds the `XMLHttpRequest` class an install puts on the page: every request goes to `handle`. */\nconst createInterceptedXMLHttpRequest = (handle: InterceptedRequestHandler, originalFetch: typeof fetch) =>\n class InterceptedXMLHttpRequest extends EventTarget {\n static readonly UNSENT = 0;\n static readonly OPENED = 1;\n static readonly HEADERS_RECEIVED = 2;\n static readonly LOADING = 3;\n static readonly DONE = 4;\n readonly UNSENT = 0;\n readonly OPENED = 1;\n readonly HEADERS_RECEIVED = 2;\n readonly LOADING = 3;\n readonly DONE = 4;\n\n readyState = 0;\n status = 0;\n statusText = \"\";\n responseURL = \"\";\n responseType: XMLHttpRequestResponseType = \"\";\n timeout = 0;\n withCredentials = false;\n readonly upload = new InterceptedXMLHttpRequestUpload();\n readonly responseXML = null;\n\n onreadystatechange: XhrEventHandler = null;\n onloadstart: XhrEventHandler = null;\n onprogress: XhrEventHandler = null;\n onload: XhrEventHandler = null;\n onerror: XhrEventHandler = null;\n onabort: XhrEventHandler = null;\n ontimeout: XhrEventHandler = null;\n onloadend: XhrEventHandler = null;\n\n protected method = \"GET\";\n protected requestUrl = \"\";\n protected requestHeaders = new Headers();\n protected responseHeaders = new Headers();\n protected responseValue: unknown = \"\";\n protected responseTextValue = \"\";\n protected sent = false;\n protected settled = false;\n protected controller: AbortController | undefined;\n protected timer: ReturnType<typeof setTimeout> | undefined;\n\n get response(): unknown {\n if (this.responseType === \"\" || this.responseType === \"text\") return this.responseText;\n return this.readyState === 4 ? this.responseValue : null;\n }\n\n get responseText(): string {\n if (this.responseType !== \"\" && this.responseType !== \"text\") {\n throw invalidState(`responseText is not available for responseType \"${this.responseType}\"`);\n }\n return this.readyState >= 3 ? this.responseTextValue : \"\";\n }\n\n open(method: string, url: string | URL) {\n // A running request is dropped without events, as a browser does.\n if (this.sent && !this.settled) this.settle();\n this.controller?.abort();\n this.controller = undefined;\n this.method = method.toUpperCase();\n this.requestUrl = String(url);\n this.requestHeaders = new Headers();\n this.responseHeaders = new Headers();\n this.responseValue = \"\";\n this.responseTextValue = \"\";\n this.status = 0;\n this.statusText = \"\";\n this.responseURL = \"\";\n this.sent = false;\n this.settled = false;\n this.setReadyState(1);\n }\n\n setRequestHeader(name: string, value: string) {\n if (this.readyState !== 1 || this.sent) throw invalidState(\"setRequestHeader needs an opened, unsent request\");\n this.requestHeaders.append(name, value);\n }\n\n overrideMimeType() {}\n\n getAllResponseHeaders(): string {\n if (this.readyState < 2) return \"\";\n let lines = \"\";\n this.responseHeaders.forEach((value, name) => {\n lines += `${name}: ${value}\\r\\n`;\n });\n return lines;\n }\n\n getResponseHeader(name: string): string | null {\n return this.readyState < 2 ? null : this.responseHeaders.get(name);\n }\n\n send(body?: Document | XMLHttpRequestBodyInit | null) {\n if (this.readyState !== 1 || this.sent) throw invalidState(\"send needs an opened, unsent request\");\n this.sent = true;\n const controller = new AbortController();\n this.controller = controller;\n const passedBody = body === undefined || body === null ? null : (body as BodyInit);\n // A browser sends no body with a GET or HEAD; the handler still sees what the client passed.\n const requestBody = this.method === \"GET\" || this.method === \"HEAD\" ? null : passedBody;\n const headers = new Headers(this.requestHeaders);\n const url = new URL(this.requestUrl, pageOrigin());\n const credentials: RequestCredentials = this.withCredentials ? \"include\" : \"same-origin\";\n const method = this.method;\n const request: InterceptedRequest = {\n method,\n url,\n headers,\n body: passedBody,\n signal: controller.signal,\n transport: \"xhr\",\n forward: () =>\n originalFetch(url.href, {\n method,\n headers: new Headers(headers),\n body: requestBody,\n credentials,\n signal: controller.signal,\n }),\n };\n const responseUrl = url.href;\n if (this.timeout > 0) this.timer = setTimeout(() => this.finishWithoutResponse(\"timeout\"), this.timeout);\n this.emit(\"loadstart\");\n const size = bodySize(requestBody);\n if (requestBody !== null) {\n this.upload.emit(\"loadstart\", 0, size);\n this.upload.emit(\"progress\", size, size);\n this.upload.emit(\"load\", size, size);\n this.upload.emit(\"loadend\", size, size);\n }\n Promise.resolve()\n .then(() => handle(request))\n .then(\n (response) => this.receive(controller, response, responseUrl),\n () => {\n if (this.controller === controller) this.finishWithoutResponse(\"error\");\n },\n );\n }\n\n abort() {\n if (!this.sent || this.settled) return;\n this.finishWithoutResponse(\"abort\");\n this.readyState = 0;\n }\n\n protected async receive(controller: AbortController, response: Response, responseUrl: string) {\n if (this.controller !== controller || this.settled) return;\n try {\n this.status = response.status;\n this.statusText = response.statusText;\n this.responseURL = responseUrl;\n this.responseHeaders = new Headers(response.headers);\n this.setReadyState(2);\n const value = await this.readBody(response);\n if (this.controller !== controller || this.settled) return;\n this.responseValue = value;\n this.setReadyState(3);\n const size = typeof this.responseTextValue === \"string\" ? this.responseTextValue.length : 0;\n this.emit(\"progress\", size, size);\n this.settle();\n this.setReadyState(4);\n this.emit(\"load\", size, size);\n this.emit(\"loadend\", size, size);\n } catch {\n if (this.controller === controller && !this.settled) this.finishWithoutResponse(\"error\");\n }\n }\n\n protected async readBody(response: Response): Promise<unknown> {\n switch (this.responseType) {\n case \"json\": {\n const text = await response.text();\n this.responseTextValue = text;\n try {\n return text === \"\" ? null : JSON.parse(text);\n } catch {\n return null;\n }\n }\n case \"blob\":\n return response.blob();\n case \"arraybuffer\":\n return response.arrayBuffer();\n case \"document\":\n return null;\n default: {\n const text = await response.text();\n this.responseTextValue = text;\n return text;\n }\n }\n }\n\n /** A request that ends without a response — an error, an abort or a timeout: status 0, nothing of a body. */\n protected finishWithoutResponse(type: \"error\" | \"abort\" | \"timeout\") {\n if (this.settled) return;\n this.settle();\n this.controller?.abort();\n this.status = 0;\n this.statusText = \"\";\n this.responseHeaders = new Headers();\n this.responseValue = null;\n this.responseTextValue = \"\";\n this.setReadyState(4);\n this.emit(type);\n this.emit(\"loadend\");\n }\n\n protected settle() {\n this.settled = true;\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n protected setReadyState(state: number) {\n this.readyState = state;\n this.emit(\"readystatechange\");\n }\n\n protected emit(type: XhrEventName, loaded = 0, total = 0) {\n const event = type === \"readystatechange\" ? new Event(type) : createProgressEvent(type, loaded, total);\n this.dispatchEvent(event);\n (this[`on${type}` as keyof this] as XhrEventHandler)?.call(this, event);\n }\n };\n\ntype GlobalScope = { fetch?: typeof fetch; XMLHttpRequest?: typeof XMLHttpRequest };\n\n/** The scopes that carry the page's `fetch` and `XMLHttpRequest` (the window and the global object, once each). */\nconst globalScopes = (): GlobalScope[] => {\n const scopes: GlobalScope[] = [globalThis as GlobalScope];\n if (typeof window !== \"undefined\" && (window as unknown) !== globalThis) scopes.push(window as GlobalScope);\n return scopes;\n};\n\n/** The page's `fetch` as it is now (the window's), callable after an install replaced it. */\nconst capturePageFetch = (): typeof fetch => {\n const pageFetch = (typeof window !== \"undefined\" ? window.fetch : globalThis.fetch) as typeof fetch;\n return (input, init) => pageFetch.call(globalThis, input, init);\n};\n\n/** Puts `value` on every global scope under `name` until the returned function restores what was there. */\nconst replaceGlobal = <Name extends keyof GlobalScope>(name: Name, value: GlobalScope[Name]): (() => void) => {\n const saved = globalScopes().map((scope) => ({ scope, value: scope[name] }));\n for (const { scope } of saved) scope[name] = value;\n return () => {\n for (const entry of saved) entry.scope[name] = entry.value;\n };\n};\n\n/**\n * Replaces `XMLHttpRequest` on the page until the returned function is called; `fetch` stays as it is. A handler's\n * `forward()` goes through the page's `fetch` as it was at the install.\n */\nexport const interceptXMLHttpRequests = (handle: InterceptedRequestHandler): (() => void) =>\n replaceGlobal(\n \"XMLHttpRequest\",\n createInterceptedXMLHttpRequest(handle, capturePageFetch()) as unknown as typeof XMLHttpRequest,\n );\n\n/** Replaces `fetch` on the page until the returned function is called; `XMLHttpRequest` stays as it is. */\nexport const interceptFetchRequests = (handle: InterceptedRequestHandler): (() => void) => {\n const originalFetch = capturePageFetch();\n const interceptedFetch = async (input: FetchInput, init?: RequestInit): Promise<Response> =>\n handle(await readFetchRequest(input, init, originalFetch));\n return replaceGlobal(\"fetch\", interceptedFetch as typeof fetch);\n};\n\n/**\n * A `fetch` input this realm's `Request` constructor reads correctly: a `Request` of another realm becomes one of this\n * realm with the same URL, method, headers, body and signal; anything else is returned as it is.\n */\nexport const toSameRealmFetchInput = async (input: FetchInput): Promise<FetchInput> => {\n if (!isFetchRequest(input) || (input as unknown) instanceof Request) return input;\n const foreign: Request = input;\n const body = foreign.body !== null ? await foreign.clone().arrayBuffer() : null;\n return new Request(foreign.url, {\n method: foreign.method,\n headers: new Headers(foreign.headers),\n body,\n // A signal of another realm is not accepted by this realm's constructor.\n signal: foreign.signal instanceof AbortSignal ? foreign.signal : undefined,\n });\n};\n"],"names":[],"mappings":";;AAIO,MAAM,qCAAqC;AAS3C,MAAM,sCAAsC,MAAgB;AAAA,EACjE;AAAA,EACA,IAAI,wBAAA,EAA0B,6BAA6B,CAAA,GAAI;AAAA,IAC7D,CAAC,cAAc,cAAc;AAAA,E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BAAgB,iBAAA;AACtB,QAAM,mBAAmB,OAAO,OAAmB,SACjD,OAAO,MAAM,iBAAiB,OAAO,MAAM,aAAa,CAAC;AAC3D,SAAO,cAAc,SAAS,gBAAgC;AAChE;AAMO,MAAM,wBAAwB,OAAO,UAA2C;AACrF,MAAI,CAAC,eAAe,KAAK,KAAM,iBAA6B,QAAS,QAAO;AAC5E,QAAM,UAAmB;AACzB,QAAM,OAAO,QAAQ,SAAS,OAAO,MAAM,QAAQ,MAAA,EAAQ,YAAA,IAAgB;AAC3E,SAAO,IAAI,QAAQ,QAAQ,KAAK;AAAA,IAC9B,QAAQ,QAAQ;AAAA,IAChB,SAAS,IAAI,QAAQ,QAAQ,OAAO;AAAA,IACpC;AAAA;AAAA,IAEA,QAAQ,QAAQ,kBAAkB,cAAc,QAAQ,SAAS;AAAA,EAAA,CAClE;AACH;"}
|
|
1
|
+
{"version":3,"file":"browser-request-interception-BnOQWLaJ.js","sources":["../../src/image-render/widget-image-readiness-signal.ts","../../src/request-interception/intercepted-xml-http-request-upload.ts","../../src/request-interception/browser-request-interception.ts"],"sourcesContent":["import { getSandboxLegacyAliases } from \"../provider/environment\";\nimport type { WidgetImageReadiness } from \"./widget-image-render.types\";\n\n/** The `window` property the image capture waits on. */\nexport const WIDGET_IMAGE_READINESS_GLOBAL_NAME = \"__AGENTS_WIDGET_IMAGE_V1__\";\n\ntype WindowSignals = Record<string, WidgetImageReadiness | undefined>;\n\n/**\n * Every name the image readiness signal is published under: the package's own, then each name the app declares\n * (`AgentsEnvironment.sandboxLegacyAliases.imageReadinessGlobalNames`) — read at each publish, so an app may declare\n * them after a readiness was created.\n */\nexport const readWidgetImageReadinessGlobalNames = (): string[] => [\n WIDGET_IMAGE_READINESS_GLOBAL_NAME,\n ...(getSandboxLegacyAliases().imageReadinessGlobalNames ?? []).filter(\n (aliasName) => aliasName !== WIDGET_IMAGE_READINESS_GLOBAL_NAME,\n ),\n];\n\n/** Publishes (or with `undefined` clears) the image readiness signal under every name. */\nexport const publishWidgetImageReadiness = (readiness: WidgetImageReadiness | undefined): void => {\n const windowSignals = window as unknown as WindowSignals;\n for (const globalName of readWidgetImageReadinessGlobalNames()) windowSignals[globalName] = readiness;\n};\n\n/**\n * The published image readiness signal. A `failed` value under ANY name wins — the app's own capture code may have\n * written it under a name it declared — otherwise the value under the package's name, otherwise the first value found.\n */\nexport const readWidgetImageReadiness = (): WidgetImageReadiness | undefined => {\n const windowSignals = window as unknown as WindowSignals;\n const publishedSignals = readWidgetImageReadinessGlobalNames()\n .map((globalName) => windowSignals[globalName])\n .filter((signal): signal is WidgetImageReadiness => signal !== undefined && signal !== null);\n return publishedSignals.find((signal) => signal.state === \"failed\") ?? publishedSignals[0];\n};\n","/** The upload side of the `XMLHttpRequest` stand-in (`xhr.upload`) and the events both sides dispatch. */\n\nexport type XhrEventName = \"loadstart\" | \"progress\" | \"load\" | \"error\" | \"abort\" | \"timeout\" | \"loadend\" | \"readystatechange\";\nexport type XhrEventHandler = ((this: unknown, event: Event) => unknown) | null;\n\nexport const createProgressEvent = (type: string, loaded: number, total: number): Event =>\n typeof ProgressEvent === \"function\"\n ? new ProgressEvent(type, { lengthComputable: total > 0, loaded, total })\n : new Event(type);\n\n/** The event target of `xhr.upload`: listeners and `on…` handlers for the upload's progress. */\nexport class InterceptedXMLHttpRequestUpload extends EventTarget {\n onloadstart: XhrEventHandler = null;\n onprogress: XhrEventHandler = null;\n onload: XhrEventHandler = null;\n onerror: XhrEventHandler = null;\n onabort: XhrEventHandler = null;\n ontimeout: XhrEventHandler = null;\n onloadend: XhrEventHandler = null;\n\n emit(type: XhrEventName, loaded = 0, total = 0) {\n const event = createProgressEvent(type, loaded, total);\n this.dispatchEvent(event);\n (this[`on${type}` as keyof this] as XhrEventHandler)?.call(this, event);\n }\n}\n","import {\n createProgressEvent,\n InterceptedXMLHttpRequestUpload,\n type XhrEventHandler,\n type XhrEventName,\n} from \"./intercepted-xml-http-request-upload\";\n\n/**\n * The browser-level request stand-in of the capture and preview pages: `XMLHttpRequest` (the transport of axios's\n * browser adapter and of uploads with progress) and, where an install asks for it, `window.fetch` are replaced for the\n * duration of an install and send every request into one handler, whatever HTTP client the application uses.\n *\n * The handler answers with a `Response` or throws: `fetch` then rejects with the thrown error, an `XMLHttpRequest`\n * fails like a network error (status 0, `error` and `loadend`, no body, no header). A handler that never settles\n * leaves the request pending. Nothing of the request reaches the network unless the handler sends it itself\n * (`forward()`, or its own copy of the original `fetch`).\n */\n\n/** A request as the handler sees it, the same for `fetch` and `XMLHttpRequest`. */\nexport interface InterceptedRequest {\n /** Upper case (`GET`, `POST`, …). */\n method: string;\n /** Absolute, resolved against the page's origin. A fresh object per request; the handler may change it. */\n url: URL;\n headers: Headers;\n /** The body the client passed (`fetch`'s, or the argument of `XMLHttpRequest.send`, also for a GET), or null. */\n body: BodyInit | null;\n signal: AbortSignal | undefined;\n transport: \"fetch\" | \"xhr\";\n /** Sends the request unchanged through the original `fetch` (an `XMLHttpRequest` with its own credentials mode). */\n forward: () => Promise<Response>;\n}\n\nexport type InterceptedRequestHandler = (request: InterceptedRequest) => Promise<Response>;\n\ntype FetchInput = RequestInfo | URL;\n\n/**\n * An answer without any header, as the former axios adapters answered (`headers: {}`): a string body would add a\n * `Content-Type`, the bytes of it do not.\n */\nexport const createHeaderlessResponse = (body: string | null, status: number, statusText = \"\"): Response =>\n new Response(body === null ? null : new TextEncoder().encode(body), { status, statusText });\n\n/** A `Request` of any realm (an iframe's, jsdom's, Node's) — never `instanceof`, which holds only for this realm. */\nexport const isFetchRequest = (input: unknown): input is Request =>\n Object.prototype.toString.call(input) === \"[object Request]\";\n\nconst pageOrigin = (): string =>\n typeof window !== \"undefined\" && window.location ? window.location.origin : \"http://localhost\";\n\nconst copyHeaders = (target: Headers, source: HeadersInit | undefined) => {\n if (source === undefined) return;\n new Headers(source).forEach((value, name) => target.set(name, value));\n};\n\n/** The `fetch` arguments as one request: a `Request` of any realm, a `URL` or a string, with `init` taking precedence. */\nexport const readFetchRequest = async (\n input: FetchInput,\n init: RequestInit | undefined,\n originalFetch: typeof fetch,\n): Promise<InterceptedRequest> => {\n const fromRequest = isFetchRequest(input) ? input : undefined;\n const headers = new Headers();\n if (fromRequest) fromRequest.headers.forEach((value, name) => headers.set(name, value));\n copyHeaders(headers, init?.headers);\n const initBody = init?.body ?? null;\n const body =\n initBody !== null\n ? initBody\n : fromRequest && fromRequest.body !== null\n ? await fromRequest.clone().arrayBuffer()\n : null;\n return {\n method: (init?.method ?? fromRequest?.method ?? \"GET\").toUpperCase(),\n url: new URL(fromRequest ? fromRequest.url : String(input), pageOrigin()),\n headers,\n body,\n signal: init?.signal ?? fromRequest?.signal ?? undefined,\n transport: \"fetch\",\n forward: () => originalFetch(input, init),\n };\n};\n\nconst bodySize = (body: BodyInit | null): number => {\n if (body === null) return 0;\n if (typeof body === \"string\") return new TextEncoder().encode(body).byteLength;\n if (typeof Blob !== \"undefined\" && body instanceof Blob) return body.size;\n if (body instanceof ArrayBuffer) return body.byteLength;\n if (ArrayBuffer.isView(body)) return body.byteLength;\n return 0;\n};\n\nconst invalidState = (message: string) => new DOMException(message, \"InvalidStateError\");\n\n/** Builds the `XMLHttpRequest` class an install puts on the page: every request goes to `handle`. */\nconst createInterceptedXMLHttpRequest = (handle: InterceptedRequestHandler, originalFetch: typeof fetch) =>\n class InterceptedXMLHttpRequest extends EventTarget {\n static readonly UNSENT = 0;\n static readonly OPENED = 1;\n static readonly HEADERS_RECEIVED = 2;\n static readonly LOADING = 3;\n static readonly DONE = 4;\n readonly UNSENT = 0;\n readonly OPENED = 1;\n readonly HEADERS_RECEIVED = 2;\n readonly LOADING = 3;\n readonly DONE = 4;\n\n readyState = 0;\n status = 0;\n statusText = \"\";\n responseURL = \"\";\n responseType: XMLHttpRequestResponseType = \"\";\n timeout = 0;\n withCredentials = false;\n readonly upload = new InterceptedXMLHttpRequestUpload();\n readonly responseXML = null;\n\n onreadystatechange: XhrEventHandler = null;\n onloadstart: XhrEventHandler = null;\n onprogress: XhrEventHandler = null;\n onload: XhrEventHandler = null;\n onerror: XhrEventHandler = null;\n onabort: XhrEventHandler = null;\n ontimeout: XhrEventHandler = null;\n onloadend: XhrEventHandler = null;\n\n protected method = \"GET\";\n protected requestUrl = \"\";\n protected requestHeaders = new Headers();\n protected responseHeaders = new Headers();\n protected responseValue: unknown = \"\";\n protected responseTextValue = \"\";\n protected sent = false;\n protected settled = false;\n protected controller: AbortController | undefined;\n protected timer: ReturnType<typeof setTimeout> | undefined;\n\n get response(): unknown {\n if (this.responseType === \"\" || this.responseType === \"text\") return this.responseText;\n return this.readyState === 4 ? this.responseValue : null;\n }\n\n get responseText(): string {\n if (this.responseType !== \"\" && this.responseType !== \"text\") {\n throw invalidState(`responseText is not available for responseType \"${this.responseType}\"`);\n }\n return this.readyState >= 3 ? this.responseTextValue : \"\";\n }\n\n open(method: string, url: string | URL) {\n // A running request is dropped without events, as a browser does.\n if (this.sent && !this.settled) this.settle();\n this.controller?.abort();\n this.controller = undefined;\n this.method = method.toUpperCase();\n this.requestUrl = String(url);\n this.requestHeaders = new Headers();\n this.responseHeaders = new Headers();\n this.responseValue = \"\";\n this.responseTextValue = \"\";\n this.status = 0;\n this.statusText = \"\";\n this.responseURL = \"\";\n this.sent = false;\n this.settled = false;\n this.setReadyState(1);\n }\n\n setRequestHeader(name: string, value: string) {\n if (this.readyState !== 1 || this.sent) throw invalidState(\"setRequestHeader needs an opened, unsent request\");\n this.requestHeaders.append(name, value);\n }\n\n overrideMimeType() {}\n\n getAllResponseHeaders(): string {\n if (this.readyState < 2) return \"\";\n let lines = \"\";\n this.responseHeaders.forEach((value, name) => {\n lines += `${name}: ${value}\\r\\n`;\n });\n return lines;\n }\n\n getResponseHeader(name: string): string | null {\n return this.readyState < 2 ? null : this.responseHeaders.get(name);\n }\n\n send(body?: Document | XMLHttpRequestBodyInit | null) {\n if (this.readyState !== 1 || this.sent) throw invalidState(\"send needs an opened, unsent request\");\n this.sent = true;\n const controller = new AbortController();\n this.controller = controller;\n const passedBody = body === undefined || body === null ? null : (body as BodyInit);\n // A browser sends no body with a GET or HEAD; the handler still sees what the client passed.\n const requestBody = this.method === \"GET\" || this.method === \"HEAD\" ? null : passedBody;\n const headers = new Headers(this.requestHeaders);\n const url = new URL(this.requestUrl, pageOrigin());\n const credentials: RequestCredentials = this.withCredentials ? \"include\" : \"same-origin\";\n const method = this.method;\n const request: InterceptedRequest = {\n method,\n url,\n headers,\n body: passedBody,\n signal: controller.signal,\n transport: \"xhr\",\n forward: () =>\n originalFetch(url.href, {\n method,\n headers: new Headers(headers),\n body: requestBody,\n credentials,\n signal: controller.signal,\n }),\n };\n const responseUrl = url.href;\n if (this.timeout > 0) this.timer = setTimeout(() => this.finishWithoutResponse(\"timeout\"), this.timeout);\n this.emit(\"loadstart\");\n const size = bodySize(requestBody);\n if (requestBody !== null) {\n this.upload.emit(\"loadstart\", 0, size);\n this.upload.emit(\"progress\", size, size);\n this.upload.emit(\"load\", size, size);\n this.upload.emit(\"loadend\", size, size);\n }\n Promise.resolve()\n .then(() => handle(request))\n .then(\n (response) => this.receive(controller, response, responseUrl),\n () => {\n if (this.controller === controller) this.finishWithoutResponse(\"error\");\n },\n );\n }\n\n abort() {\n if (!this.sent || this.settled) return;\n this.finishWithoutResponse(\"abort\");\n this.readyState = 0;\n }\n\n protected async receive(controller: AbortController, response: Response, responseUrl: string) {\n if (this.controller !== controller || this.settled) return;\n try {\n this.status = response.status;\n this.statusText = response.statusText;\n this.responseURL = responseUrl;\n this.responseHeaders = new Headers(response.headers);\n this.setReadyState(2);\n const value = await this.readBody(response);\n if (this.controller !== controller || this.settled) return;\n this.responseValue = value;\n this.setReadyState(3);\n const size = typeof this.responseTextValue === \"string\" ? this.responseTextValue.length : 0;\n this.emit(\"progress\", size, size);\n this.settle();\n this.setReadyState(4);\n this.emit(\"load\", size, size);\n this.emit(\"loadend\", size, size);\n } catch {\n if (this.controller === controller && !this.settled) this.finishWithoutResponse(\"error\");\n }\n }\n\n protected async readBody(response: Response): Promise<unknown> {\n switch (this.responseType) {\n case \"json\": {\n const text = await response.text();\n this.responseTextValue = text;\n try {\n return text === \"\" ? null : JSON.parse(text);\n } catch {\n return null;\n }\n }\n case \"blob\":\n return response.blob();\n case \"arraybuffer\":\n return response.arrayBuffer();\n case \"document\":\n return null;\n default: {\n const text = await response.text();\n this.responseTextValue = text;\n return text;\n }\n }\n }\n\n /** A request that ends without a response — an error, an abort or a timeout: status 0, nothing of a body. */\n protected finishWithoutResponse(type: \"error\" | \"abort\" | \"timeout\") {\n if (this.settled) return;\n this.settle();\n this.controller?.abort();\n this.status = 0;\n this.statusText = \"\";\n this.responseHeaders = new Headers();\n this.responseValue = null;\n this.responseTextValue = \"\";\n this.setReadyState(4);\n this.emit(type);\n this.emit(\"loadend\");\n }\n\n protected settle() {\n this.settled = true;\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n protected setReadyState(state: number) {\n this.readyState = state;\n this.emit(\"readystatechange\");\n }\n\n protected emit(type: XhrEventName, loaded = 0, total = 0) {\n const event = type === \"readystatechange\" ? new Event(type) : createProgressEvent(type, loaded, total);\n this.dispatchEvent(event);\n (this[`on${type}` as keyof this] as XhrEventHandler)?.call(this, event);\n }\n };\n\ntype GlobalScope = { fetch?: typeof fetch; XMLHttpRequest?: typeof XMLHttpRequest };\n\n/** The scopes that carry the page's `fetch` and `XMLHttpRequest` (the window and the global object, once each). */\nconst globalScopes = (): GlobalScope[] => {\n const scopes: GlobalScope[] = [globalThis as GlobalScope];\n if (typeof window !== \"undefined\" && (window as unknown) !== globalThis) scopes.push(window as GlobalScope);\n return scopes;\n};\n\n/** The page's `fetch` as it is now (the window's), callable after an install replaced it. */\nconst capturePageFetch = (): typeof fetch => {\n const pageFetch = (typeof window !== \"undefined\" ? window.fetch : globalThis.fetch) as typeof fetch;\n return (input, init) => pageFetch.call(globalThis, input, init);\n};\n\n/** Puts `value` on every global scope under `name` until the returned function restores what was there. */\nconst replaceGlobal = <Name extends keyof GlobalScope>(name: Name, value: GlobalScope[Name]): (() => void) => {\n const saved = globalScopes().map((scope) => ({ scope, value: scope[name] }));\n for (const { scope } of saved) scope[name] = value;\n return () => {\n for (const entry of saved) entry.scope[name] = entry.value;\n };\n};\n\n/**\n * Replaces `XMLHttpRequest` on the page until the returned function is called; `fetch` stays as it is. A handler's\n * `forward()` goes through the page's `fetch` as it was at the install.\n */\nexport const interceptXMLHttpRequests = (handle: InterceptedRequestHandler): (() => void) =>\n replaceGlobal(\n \"XMLHttpRequest\",\n createInterceptedXMLHttpRequest(handle, capturePageFetch()) as unknown as typeof XMLHttpRequest,\n );\n\n/** Replaces `fetch` on the page until the returned function is called; `XMLHttpRequest` stays as it is. */\nexport const interceptFetchRequests = (handle: InterceptedRequestHandler): (() => void) => {\n const originalFetch = capturePageFetch();\n const interceptedFetch = async (input: FetchInput, init?: RequestInit): Promise<Response> =>\n handle(await readFetchRequest(input, init, originalFetch));\n return replaceGlobal(\"fetch\", interceptedFetch as typeof fetch);\n};\n\n/**\n * A `fetch` input this realm's `Request` constructor reads correctly: a `Request` of another realm becomes one of this\n * realm with the same URL, method, headers, body and signal; anything else is returned as it is.\n */\nexport const toSameRealmFetchInput = async (input: FetchInput): Promise<FetchInput> => {\n if (!isFetchRequest(input) || (input as unknown) instanceof Request) return input;\n const foreign: Request = input;\n const body = foreign.body !== null ? await foreign.clone().arrayBuffer() : null;\n return new Request(foreign.url, {\n method: foreign.method,\n headers: new Headers(foreign.headers),\n body,\n // A signal of another realm is not accepted by this realm's constructor.\n signal: foreign.signal instanceof AbortSignal ? foreign.signal : undefined,\n });\n};\n"],"names":[],"mappings":";;AAIO,MAAM,qCAAqC;AAS3C,MAAM,sCAAsC,MAAgB;AAAA,EACjE;AAAA,EACA,IAAI,wBAAA,EAA0B,6BAA6B,CAAA,GAAI;AAAA,IAC7D,CAAC,cAAc,cAAc;AAAA,EAAA;AAEjC;AAGO,MAAM,8BAA8B,CAAC,cAAsD;AAChG,QAAM,gBAAgB;A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BAAiB,OAAO,MAAM,aAAa,CAAC;AAC3D,SAAO,cAAc,SAAS,gBAAgC;AAChE;AAMO,MAAM,wBAAwB,OAAO,UAA2C;AACrF,MAAI,CAAC,eAAe,KAAK,KAAM,iBAA6B,QAAS,QAAO;AAC5E,QAAM,UAAmB;AACzB,QAAM,OAAO,QAAQ,SAAS,OAAO,MAAM,QAAQ,MAAA,EAAQ,YAAA,IAAgB;AAC3E,SAAO,IAAI,QAAQ,QAAQ,KAAK;AAAA,IAC9B,QAAQ,QAAQ;AAAA,IAChB,SAAS,IAAI,QAAQ,QAAQ,OAAO;AAAA,IACpC;AAAA;AAAA,IAEA,QAAQ,QAAQ,kBAAkB,cAAc,QAAQ,SAAS;AAAA,EAAA,CAClE;AACH;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { j as conversationWidgetRegistry } from "./
|
|
3
|
-
import { O as getFurtherWidgetClickSignalSources } from "./index-
|
|
2
|
+
import { j as conversationWidgetRegistry } from "./conversationWidgetRegistry-webrYtkI.js";
|
|
3
|
+
import { O as getFurtherWidgetClickSignalSources } from "./index-DAEGct6X.js";
|
|
4
4
|
import { createContext, useContext, useEffect } from "react";
|
|
5
5
|
const resolveDeepLinkableWidget = (widgetName) => {
|
|
6
6
|
if (!widgetName) return null;
|
|
@@ -45,4 +45,4 @@ export {
|
|
|
45
45
|
resolveDeepLinkableWidget as r,
|
|
46
46
|
useCanvasLabel as u
|
|
47
47
|
};
|
|
48
|
-
//# sourceMappingURL=canvas-label-context-
|
|
48
|
+
//# sourceMappingURL=canvas-label-context-5yvbmK-V.js.map
|
package/dist/chunks/{canvas-label-context-C1Pc_Ldo.js.map → canvas-label-context-5yvbmK-V.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"canvas-label-context-
|
|
1
|
+
{"version":3,"file":"canvas-label-context-5yvbmK-V.js","sources":["../../src/renderer/resolve-deep-linkable-widget.ts","../../src/renderer/widget-click-signal-sources.ts","../../src/renderer/canvas/canvas-title-slot-context.ts","../../src/renderer/canvas/canvas-label-context.ts"],"sourcesContent":["import type { CanvasId } from \"./canvas/canvas-behaviours\";\nimport { ConversationWidgetEntry, conversationWidgetRegistry } from \"./conversationWidgetRegistry\";\n\n/**\n * Resolves the widget a `?agentWidget=<name>` deep-link (or a restored pinned canvas) may mount, by its CANONICAL\n * registry wire name.\n *\n * A URL is untrusted input, so this is an allow-list rather than a registry lookup: only an entry that declares\n * `deepLinkable: true` can be opened this way. Every other widget is emitted by the agent inside a message, where the\n * conversation itself is the authorisation — a link must not be able to mount an arbitrary widget (some carry\n * mount-time side effects) just because its name was typed into the address bar.\n *\n * Returns the entry (the caller renders its `component`, applying the feature gate the entry declares) or null when the\n * name is empty, unknown, or not deep-linkable.\n */\nexport const resolveDeepLinkableWidget = (widgetName?: string | null): ConversationWidgetEntry | null => {\n if (!widgetName) return null;\n return (\n conversationWidgetRegistry.widgets.find((entry) => entry.name === widgetName && entry.deepLinkable === true) ?? null\n );\n};\n\n/**\n * The reverse direction: which deep-linkable widget re-opens THIS canvas. The open canvas of the agent chat is\n * mirrored into `?agentWidget=` (AgentTrigger) so a reload brings the customer back to the surface they were working\n * on — an editor a cold chat opened has no conversation id yet, so the canvas model's own pointer storage\n * has nothing to restore from.\n *\n * Null for every canvas no deep-linkable widget declares: it is the agent's to open inside a message, and a URL must\n * not be able to mount it (the allow-list above).\n */\nexport const deepLinkableWidgetNameForCanvas = (canvasId: CanvasId | null | undefined): string | null => {\n if (!canvasId) return null;\n return (\n conversationWidgetRegistry.widgets.find(\n (entry) => entry.deepLinkable === true && entry.opensCanvases?.includes(canvasId),\n )?.name ?? null\n );\n};\n","import { getFurtherWidgetClickSignalSources } from \"../provider/environment\";\n\n/**\n * The `signalSource`s a widget CLICK posts into the conversation (`injectSignal`): the generic widget click and the\n * dedicated source the former owner-action consent widget sent (no component posts it any more; stored rows keep it),\n * plus the further sources an app's own widgets post (`AgentsEnvironment.furtherWidgetClickSignalSources`, e.g. a form\n * submit that starts its own owner turn). The message list reads them to tell an answered widget from an open one after\n * a reload — a widget the owner already clicked must never come back interactive (a consent widget re-armed is a second\n * confirmation for a destructive tool). Add a source here when a widget of the package starts posting a new one.\n */\nexport const FRONTEND_WIDGET_CLICK_SIGNAL_SOURCE = \"FRONTEND_WIDGET_CLICK\";\nexport const OWNER_ACTION_CONFIRM_SIGNAL_SOURCE = \"OWNER_ACTION_CONFIRM\";\n\n/** The package's own widget click sources (the backend's sources of the package that carry an owner statement). */\nexport const PACKAGE_WIDGET_CLICK_SIGNAL_SOURCES: readonly string[] = [\n FRONTEND_WIDGET_CLICK_SIGNAL_SOURCE,\n OWNER_ACTION_CONFIRM_SIGNAL_SOURCE,\n];\n\n/** Every widget click source: the package's own and the app's further ones. */\nexport const getWidgetClickSignalSources = (): readonly string[] => [\n ...PACKAGE_WIDGET_CLICK_SIGNAL_SOURCES,\n ...getFurtherWidgetClickSignalSources(),\n];\n\nexport const isWidgetClickSignalSource = (signalSource: string | undefined | null): boolean =>\n signalSource != null && getWidgetClickSignalSources().includes(signalSource);\n","import { createContext, useContext } from \"react\";\n\n/**\n * The place beside the canvas pane's close button, for a canvas whose behaviour declares `titleBesideCloseButton`:\n * its body portals its title there. Null outside a canvas pane and for every other canvas.\n */\nexport const CanvasTitleSlotContext = createContext<HTMLElement | null>(null);\n\nexport const useCanvasTitleSlot = (): HTMLElement | null => useContext(CanvasTitleSlotContext);\n","import { createContext, useContext, useEffect } from \"react\";\n\n/**\n * Where a canvas body reports its short name (a file's name, a list's title): the chat hands it to the `SplitView`\n * as `sideLabel`, so a host that frames the canvas (a tab, a card head) can name it. Null outside a canvas pane.\n */\nexport const CanvasLabelContext = createContext<((label: string | null) => void) | null>(null);\n\n/**\n * Reports the open canvas's short name while the body is mounted; `null` or `undefined` (still loading) reports none.\n * The name is taken back when the body unmounts. Outside a canvas pane it does nothing.\n */\nexport const useCanvasLabel = (label: string | null | undefined): void => {\n const reportLabel = useContext(CanvasLabelContext);\n const shownLabel = label ?? null;\n useEffect(() => {\n if (reportLabel === null) return undefined;\n reportLabel(shownLabel);\n return () => reportLabel(null);\n }, [reportLabel, shownLabel]);\n};\n"],"names":[],"mappings":";;;;AAeO,MAAM,4BAA4B,CAAC,eAA+D;AACvG,MAAI,CAAC,WAAY,QAAO;AACxB,SACE,2BAA2B,QAAQ,KAAK,CAAC,UAAU,MAAM,SAAS,cAAc,MAAM,iBAAiB,IAAI,KAAK;AAEpH;AAWO,MAAM,kCAAkC,CAAC,aAAyD;AACvG,MAAI,CAAC,SAAU,QAAO;AACtB,SACE,2BAA2B,QAAQ;AAAA,IACjC,CAAC,UAAU,MAAM,iBAAiB,QAAQ,MAAM,eAAe,SAAS,QAAQ;AAAA,EAAA,GAC/E,QAAQ;AAEf;AC5BO,MAAM,sCAAsC;AAC5C,MAAM,qCAAqC;AAG3C,MAAM,sCAAyD;AAAA,EACpE;AAAA,EACA;AACF;AAGO,MAAM,8BAA8B,MAAyB;AAAA,EAClE,GAAG;AAAA,EACH,GAAG,mCAAA;AACL;AAEO,MAAM,4BAA4B,CAAC,iBACxC,gBAAgB,QAAQ,4BAAA,EAA8B,SAAS,YAAY;ACpBtE,MAAM,yBAAyB,cAAkC,IAAI;AAErE,MAAM,qBAAqB,MAA0B,WAAW,sBAAsB;ACFtF,MAAM,qBAAqB,cAAuD,IAAI;AAMtF,MAAM,iBAAiB,CAAC,UAA2C;AACxE,QAAM,cAAc,WAAW,kBAAkB;AACjD,QAAM,aAAa,SAAS;AAC5B,YAAU,MAAM;AACd,QAAI,gBAAgB,KAAM,QAAO;AACjC,gBAAY,UAAU;AACtB,WAAO,MAAM,YAAY,IAAI;AAAA,EAC/B,GAAG,CAAC,aAAa,UAAU,CAAC;AAC9B;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { s as sameCanvasIdentity,
|
|
2
|
+
import { s as sameCanvasIdentity, k as canvasBehaviourOf } from "./WebSearchResultsConversationWidget-BVMwJfhL.js";
|
|
3
3
|
const ACCEPT = { kind: "accept" };
|
|
4
4
|
const ignore = (reason) => ({ kind: "ignore", reason });
|
|
5
5
|
const decideCanvasOpen = (behaviour, openCanvas, lastClosedCanvas, request) => {
|
|
@@ -84,4 +84,4 @@ export {
|
|
|
84
84
|
applySetCanvasCreatedEntityId as e,
|
|
85
85
|
decideCanvasOpen as f
|
|
86
86
|
};
|
|
87
|
-
//# sourceMappingURL=canvas-reducers-
|
|
87
|
+
//# sourceMappingURL=canvas-reducers-133Kl1QH.js.map
|